scorm.class.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Symfony\Component\DomCrawler\Crawler;
  4. /**
  5. * Defines the scorm class, which is meant to contain the scorm items (nuclear elements).
  6. *
  7. * @package chamilo.learnpath
  8. *
  9. * @author Yannick Warnier <ywarnier@beeznest.org>
  10. */
  11. class scorm extends learnpath
  12. {
  13. public $manifest = [];
  14. public $resources = [];
  15. public $resources_att = [];
  16. public $organizations = [];
  17. public $organizations_att = [];
  18. public $metadata = [];
  19. // Will hold the references to resources for each item ID found.
  20. public $idrefs = [];
  21. // For each resource found, stores the file url/uri.
  22. public $refurls = [];
  23. /* Path between the scorm/ directory and the imsmanifest.xml e.g.
  24. maritime_nav/maritime_nav. This is the path that will be used in the
  25. lp_path when importing a package. */
  26. public $subdir = '';
  27. public $items = [];
  28. // Keeps the zipfile safe for the object's life so that we can use it if no title avail.
  29. public $zipname = '';
  30. // Keeps an index of the number of uses of the zipname so far.
  31. public $lastzipnameindex = 0;
  32. public $manifest_encoding = 'UTF-8';
  33. public $debug = false;
  34. /**
  35. * Class constructor. Based on the parent constructor.
  36. *
  37. * @param string Course code
  38. * @param int Learnpath ID in DB
  39. * @param int User ID
  40. */
  41. public function __construct($course_code = null, $resource_id = null, $user_id = null)
  42. {
  43. if ($this->debug > 0) {
  44. error_log('New LP - scorm::scorm('.$course_code.','.$resource_id.','.$user_id.') - In scorm constructor');
  45. }
  46. parent::__construct($course_code, $resource_id, $user_id);
  47. }
  48. /**
  49. * Opens a resource.
  50. *
  51. * @param int $id Database ID of the resource
  52. */
  53. public function open($id)
  54. {
  55. if ($this->debug > 0) {
  56. error_log('New LP - scorm::open() - In scorm::open method', 0);
  57. }
  58. // redefine parent method
  59. }
  60. /**
  61. * Possible SCO status: see CAM doc 2.3.2.5.1: passed, completed, browsed, failed, not attempted, incomplete.
  62. * Prerequisites: see CAM doc 2.3.2.5.1 for pseudo-code.
  63. *
  64. * Parses an imsmanifest.xml file and puts everything into the $manifest array.
  65. *
  66. * @param string Path to the imsmanifest.xml file on the system.
  67. * If not defined, uses the base path of the course's scorm dir
  68. *
  69. * @return array Structured array representing the imsmanifest's contents
  70. */
  71. public function parse_manifest($file = '')
  72. {
  73. if ($this->debug > 0) {
  74. error_log('In scorm::parse_manifest('.$file.')', 0);
  75. }
  76. if (empty($file)) {
  77. // Get the path of the imsmanifest file.
  78. }
  79. if (is_file($file) && is_readable($file) && ($xml = @file_get_contents($file))) {
  80. // Parsing using PHP5 DOMXML methods.
  81. if ($this->debug > 0) {
  82. error_log('In scorm::parse_manifest() - Parsing using PHP5 method');
  83. }
  84. // $this->manifest_encoding = api_detect_encoding_xml($xml);
  85. // This is the usual way for reading the encoding.
  86. // This method reads the encoding, it tries to be correct even in cases
  87. // of wrong or missing encoding declarations.
  88. $this->manifest_encoding = self::detect_manifest_encoding($xml);
  89. // UTF-8 is supported by DOMDocument class, this is for sure.
  90. $xml = api_utf8_encode_xml($xml, $this->manifest_encoding);
  91. $crawler = new Crawler();
  92. $crawler->addXmlContent($xml);
  93. $xmlErrors = libxml_get_errors();
  94. if (!empty($xmlErrors)) {
  95. if ($this->debug > 0) {
  96. error_log('New LP - In scorm::parse_manifest() - Exception thrown when loading '.$file.' in DOMDocument');
  97. }
  98. // Throw exception?
  99. return null;
  100. }
  101. if ($this->debug > 1) {
  102. error_log('New LP - Called (encoding:'.$this->manifest_encoding.' - saved: '.$this->manifest_encoding.')', 0);
  103. }
  104. $root = $crawler->getNode(0);
  105. if ($root->hasAttributes()) {
  106. $attributes = $root->attributes;
  107. if ($attributes->length !== 0) {
  108. foreach ($attributes as $attrib) {
  109. // <manifest> element attributes
  110. $this->manifest[$attrib->name] = $attrib->value;
  111. }
  112. }
  113. }
  114. $this->manifest['name'] = $root->tagName;
  115. if ($root->hasChildNodes()) {
  116. $children = $root->childNodes;
  117. if ($children->length !== 0) {
  118. foreach ($children as $child) {
  119. // <manifest> element children (can be <metadata>, <organizations> or <resources> )
  120. if ($child->nodeType == XML_ELEMENT_NODE) {
  121. switch ($child->tagName) {
  122. case 'metadata':
  123. // Parse items from inside the <metadata> element.
  124. $this->metadata = new scormMetadata('manifest', $child);
  125. break;
  126. case 'organizations':
  127. // Contains the course structure - this element appears 1 and only 1 time in a package imsmanifest.
  128. // It contains at least one 'organization' sub-element.
  129. $orgs_attribs = $child->attributes;
  130. foreach ($orgs_attribs as $orgs_attrib) {
  131. // Attributes of the <organizations> element.
  132. if ($orgs_attrib->nodeType == XML_ATTRIBUTE_NODE) {
  133. $this->manifest['organizations'][$orgs_attrib->name] = $orgs_attrib->value;
  134. }
  135. }
  136. $orgs_nodes = $child->childNodes;
  137. $i = 0;
  138. $found_an_org = false;
  139. foreach ($orgs_nodes as $orgnode) {
  140. // <organization> elements - can contain <item>, <metadata> and <title>
  141. // Here we are at the 'organization' level. There might be several organization tags but
  142. // there is generally only one.
  143. // There are generally three children nodes we are looking for inside and organization:
  144. // -title
  145. // -item (may contain other item tags or may appear several times inside organization)
  146. // -metadata (relative to the organization)
  147. $found_an_org = false;
  148. switch ($orgnode->nodeType) {
  149. case XML_TEXT_NODE:
  150. // Ignore here.
  151. break;
  152. case XML_ATTRIBUTE_NODE:
  153. // Just in case there would be interesting attributes inside the organization tag.
  154. // There shouldn't as this is a node-level, not a data level.
  155. //$manifest['organizations'][$i][$orgnode->name] = $orgnode->value;
  156. //$found_an_org = true;
  157. break;
  158. case XML_ELEMENT_NODE:
  159. // <item>, <metadata> or <title> (or attributes)
  160. $organizations_attributes = $orgnode->attributes;
  161. foreach ($organizations_attributes as $orgs_attr) {
  162. $this->organizations_att[$orgs_attr->name] = $orgs_attr->value;
  163. }
  164. $oOrganization = new scormOrganization(
  165. 'manifest',
  166. $orgnode,
  167. $this->manifest_encoding
  168. );
  169. if ($oOrganization->identifier != '') {
  170. $name = $oOrganization->get_name();
  171. if (empty($name)) {
  172. // If the org title is empty, use zip file name.
  173. $myname = $this->zipname;
  174. if ($this->lastzipnameindex != 0) {
  175. $myname = $myname + $this->lastzipnameindex;
  176. $this->lastzipnameindex++;
  177. }
  178. $oOrganization->set_name($this->zipname);
  179. }
  180. $this->organizations[$oOrganization->identifier] = $oOrganization;
  181. }
  182. break;
  183. }
  184. }
  185. break;
  186. case 'resources':
  187. if ($child->hasAttributes()) {
  188. $resources_attribs = $child->attributes;
  189. foreach ($resources_attribs as $res_attr) {
  190. if ($res_attr->type == XML_ATTRIBUTE_NODE) {
  191. $this->manifest['resources'][$res_attr->name] = $res_attr->value;
  192. }
  193. }
  194. }
  195. if ($child->hasChildNodes()) {
  196. $resources_nodes = $child->childNodes;
  197. $i = 0;
  198. foreach ($resources_nodes as $res_node) {
  199. $oResource = new scormResource('manifest', $res_node);
  200. if ($oResource->identifier != '') {
  201. $this->resources[$oResource->identifier] = $oResource;
  202. $i++;
  203. }
  204. }
  205. }
  206. // Contains links to physical resources.
  207. break;
  208. case 'manifest':
  209. // Only for sub-manifests.
  210. break;
  211. }
  212. }
  213. }
  214. }
  215. }
  216. // End parsing using PHP5 DOMXML methods.
  217. } else {
  218. if ($this->debug > 1) {
  219. error_log('New LP - Could not open/read file '.$file);
  220. }
  221. $this->set_error_msg("File $file could not be read");
  222. return null;
  223. }
  224. $fixTemplate = api_get_configuration_value('learnpath_fix_xerte_template');
  225. $proxyPath = api_get_configuration_value('learnpath_proxy_url');
  226. if ($fixTemplate && !empty($proxyPath)) {
  227. // Check organisations:
  228. if (isset($this->manifest['organizations'])) {
  229. foreach ($this->manifest['organizations'] as $data) {
  230. if (strpos(strtolower($data), 'xerte') !== false) {
  231. // Check if template.xml exists:
  232. $templatePath = str_replace('imsmanifest.xml', 'template.xml', $file);
  233. if (file_exists($templatePath) && is_file($templatePath)) {
  234. $templateContent = file_get_contents($templatePath);
  235. $find = [
  236. 'href="www.',
  237. 'href="https://',
  238. 'href="http://',
  239. 'url="www.',
  240. 'pdfs/download.php?',
  241. ];
  242. $replace = [
  243. 'href="http://www.',
  244. 'target = "_blank" href="'.$proxyPath.'?type=link&src=https://',
  245. 'target = "_blank" href="'.$proxyPath.'?type=link&src=http://',
  246. 'url="http://www.',
  247. 'pdfs/download.php&',
  248. ];
  249. $templateContent = str_replace($find, $replace, $templateContent);
  250. file_put_contents($templatePath, $templateContent);
  251. }
  252. // Fix link generation:
  253. $linkPath = str_replace('imsmanifest.xml', 'models_html5/links.html', $file);
  254. if (file_exists($linkPath) && is_file($linkPath)) {
  255. $linkContent = file_get_contents($linkPath);
  256. $find = [
  257. ':this.getAttribute("url")',
  258. ];
  259. $replace = [
  260. ':"'.$proxyPath.'?type=link&src=" + this.getAttribute("url")',
  261. ];
  262. $linkContent = str_replace($find, $replace, $linkContent);
  263. file_put_contents($linkPath, $linkContent);
  264. }
  265. // Fix iframe generation
  266. $framePath = str_replace('imsmanifest.xml', 'models_html5/embedDiv.html', $file);
  267. if (file_exists($framePath) && is_file($framePath)) {
  268. $content = file_get_contents($framePath);
  269. $find = [
  270. '$iFrameHolder.html(iFrameTag);',
  271. ];
  272. $replace = [
  273. 'iFrameTag = \'<a target ="_blank" href="'.$proxyPath.'?type=link&src=\'+ pageSrc + \'">Open website. <img width="16px" src="'.Display::returnIconPath('link-external.png').'"></a>\'; $iFrameHolder.html(iFrameTag); ',
  274. ];
  275. $content = str_replace($find, $replace, $content);
  276. file_put_contents($framePath, $content);
  277. }
  278. // Fix new window generation
  279. $newWindowPath = str_replace('imsmanifest.xml', 'models_html5/newWindow.html', $file);
  280. if (file_exists($newWindowPath) && is_file($newWindowPath)) {
  281. $content = file_get_contents($newWindowPath);
  282. $find = [
  283. 'var src = x_currentPageXML',
  284. ];
  285. $replace = [
  286. 'var src = "'.$proxyPath.'?type=link&src=" + x_currentPageXML',
  287. ];
  288. $content = str_replace($find, $replace, $content);
  289. file_put_contents($newWindowPath, $content);
  290. }
  291. }
  292. }
  293. }
  294. }
  295. // TODO: Close the DOM handler.
  296. return $this->manifest;
  297. }
  298. /**
  299. * Import the scorm object (as a result from the parse_manifest function) into the database structure.
  300. *
  301. * @param string $courseCode
  302. * @param int $userMaxScore
  303. * @param int $sessionId
  304. * @param int $userId
  305. *
  306. * @return bool Returns -1 on error
  307. */
  308. public function import_manifest(
  309. $courseCode,
  310. $userMaxScore = 1,
  311. $sessionId = 0,
  312. $userId = 0
  313. ) {
  314. if ($this->debug > 0) {
  315. error_log('New LP - Entered import_manifest('.$courseCode.')', 0);
  316. }
  317. $courseInfo = api_get_course_info($courseCode);
  318. $courseId = $courseInfo['real_id'];
  319. $userId = (int) $userId;
  320. if (empty($userId)) {
  321. $userId = api_get_user_id();
  322. }
  323. // Get table names.
  324. $new_lp = Database::get_course_table(TABLE_LP_MAIN);
  325. $new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  326. $userMaxScore = (int) $userMaxScore;
  327. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  328. foreach ($this->organizations as $id => $dummy) {
  329. $oOrganization = &$this->organizations[$id];
  330. // Prepare and execute insert queries:
  331. // -for learnpath
  332. // -for items
  333. // -for views?
  334. $get_max = "SELECT MAX(display_order) FROM $new_lp WHERE c_id = $courseId ";
  335. $res_max = Database::query($get_max);
  336. $dsp = 1;
  337. if (Database::num_rows($res_max) > 0) {
  338. $row = Database::fetch_array($res_max);
  339. $dsp = $row[0] + 1;
  340. }
  341. $myname = api_utf8_decode($oOrganization->get_name());
  342. $now = api_get_utc_datetime();
  343. $params = [
  344. 'c_id' => $courseId,
  345. 'lp_type' => 2,
  346. 'name' => $myname,
  347. 'ref' => $oOrganization->get_ref(),
  348. 'description' => '',
  349. 'path' => $this->subdir,
  350. 'force_commit' => 0,
  351. 'default_view_mod' => 'embedded',
  352. 'default_encoding' => $this->manifest_encoding,
  353. 'js_lib' => 'scorm_api.php',
  354. 'display_order' => $dsp,
  355. 'session_id' => $sessionId,
  356. 'use_max_score' => $userMaxScore,
  357. 'content_maker' => '',
  358. 'content_license' => '',
  359. 'debug' => 0,
  360. 'theme' => '',
  361. 'preview_image' => '',
  362. 'author' => '',
  363. 'prerequisite' => 0,
  364. 'hide_toc_frame' => 0,
  365. 'seriousgame_mode' => 0,
  366. 'autolaunch' => 0,
  367. 'category_id' => 0,
  368. 'max_attempts' => 0,
  369. 'subscribe_users' => 0,
  370. 'created_on' => $now,
  371. 'modified_on' => $now,
  372. 'publicated_on' => $now,
  373. ];
  374. $lp_id = Database::insert($new_lp, $params);
  375. if ($lp_id) {
  376. $sql = "UPDATE $new_lp SET id = iid WHERE iid = $lp_id";
  377. Database::query($sql);
  378. $this->lp_id = $lp_id;
  379. // Insert into item_property.
  380. api_item_property_update(
  381. $courseInfo,
  382. TOOL_LEARNPATH,
  383. $this->lp_id,
  384. 'LearnpathAdded',
  385. $userId
  386. );
  387. api_item_property_update(
  388. $courseInfo,
  389. TOOL_LEARNPATH,
  390. $this->lp_id,
  391. 'visible',
  392. $userId
  393. );
  394. }
  395. // Now insert all elements from inside that learning path.
  396. // Make sure we also get the href and sco/asset from the resources.
  397. $list = $oOrganization->get_flat_items_list();
  398. $parents_stack = [0];
  399. $parent = 0;
  400. $previous = 0;
  401. $level = 0;
  402. foreach ($list as $item) {
  403. if ($item['level'] > $level) {
  404. // Push something into the parents array.
  405. array_push($parents_stack, $previous);
  406. $parent = $previous;
  407. } elseif ($item['level'] < $level) {
  408. $diff = $level - $item['level'];
  409. // Pop something out of the parents array.
  410. for ($j = 1; $j <= $diff; $j++) {
  411. $outdated_parent = array_pop($parents_stack);
  412. }
  413. $parent = array_pop($parents_stack); // Just save that value, then add it back.
  414. array_push($parents_stack, $parent);
  415. }
  416. $path = '';
  417. $type = 'dir';
  418. if (isset($this->resources[$item['identifierref']])) {
  419. $oRes = &$this->resources[$item['identifierref']];
  420. $path = @$oRes->get_path();
  421. if (!empty($path)) {
  422. $temptype = $oRes->get_scorm_type();
  423. if (!empty($temptype)) {
  424. $type = $temptype;
  425. }
  426. }
  427. }
  428. $level = $item['level'];
  429. $field_add = '';
  430. $value_add = '';
  431. if (!empty($item['masteryscore'])) {
  432. $field_add .= 'mastery_score, ';
  433. $value_add .= $item['masteryscore'].',';
  434. }
  435. if (!empty($item['maxtimeallowed'])) {
  436. $field_add .= 'max_time_allowed, ';
  437. $value_add .= "'".$item['maxtimeallowed']."',";
  438. }
  439. $title = Database::escape_string($item['title']);
  440. $title = api_utf8_decode($title);
  441. $max_score = (int) $item['max_score'];
  442. if ($max_score === 0) {
  443. // If max score is not set The use_max_score parameter
  444. // is check in order to use 100 (chamilo style) or '' (strict scorm)
  445. $max_score = 'NULL';
  446. if ($userMaxScore) {
  447. $max_score = 100;
  448. }
  449. } else {
  450. // Otherwise save the max score.
  451. $max_score = "'$max_score'";
  452. }
  453. $identifier = Database::escape_string($item['identifier']);
  454. if (empty($title)) {
  455. $title = get_lang('Untitled');
  456. }
  457. $prereq = Database::escape_string($item['prerequisites']);
  458. $item['datafromlms'] = Database::escape_string($item['datafromlms']);
  459. $item['parameters'] = Database::escape_string($item['parameters']);
  460. $sql = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters)
  461. VALUES ($courseId, $lp_id, '$type', '$identifier', '$title', '$path' , 0, $max_score, $value_add $parent, $previous, 0, '$prereq', ".$item['rel_order'].", '".$item['datafromlms']."', '".$item['parameters']."' )";
  462. Database::query($sql);
  463. if ($this->debug > 1) {
  464. error_log('New LP - In import_manifest(), inserting item : '.$sql);
  465. }
  466. $item_id = Database::insert_id();
  467. if ($item_id) {
  468. $sql = "UPDATE $new_lp_item SET id = iid WHERE iid = $item_id";
  469. Database::query($sql);
  470. // Now update previous item to change next_item_id.
  471. $upd = "UPDATE $new_lp_item SET next_item_id = $item_id
  472. WHERE iid = $previous";
  473. Database::query($upd);
  474. // Update previous item id.
  475. $previous = $item_id;
  476. }
  477. // Code for indexing, now only index specific fields like terms and the title.
  478. if (!empty($_POST['index_document'])) {
  479. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  480. $di = new ChamiloIndexer();
  481. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  482. $di->connectDb(null, null, $lang);
  483. $ic_slide = new IndexableChunk();
  484. $ic_slide->addValue('title', $title);
  485. $specific_fields = get_specific_field_list();
  486. $all_specific_terms = '';
  487. foreach ($specific_fields as $specific_field) {
  488. if (isset($_REQUEST[$specific_field['code']])) {
  489. $sterms = trim($_REQUEST[$specific_field['code']]);
  490. $all_specific_terms .= ' '.$sterms;
  491. if (!empty($sterms)) {
  492. $sterms = explode(',', $sterms);
  493. foreach ($sterms as $sterm) {
  494. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  495. }
  496. }
  497. }
  498. }
  499. $body_to_index = $all_specific_terms.' '.$title;
  500. $ic_slide->addValue("content", $body_to_index);
  501. // TODO: Add a comment to say terms separated by commas.
  502. $courseid = api_get_course_id();
  503. $ic_slide->addCourseId($courseid);
  504. $ic_slide->addToolId(TOOL_LEARNPATH);
  505. // TODO: Unify with other lp types.
  506. $xapian_data = [
  507. SE_COURSE_ID => $courseid,
  508. SE_TOOL_ID => TOOL_LEARNPATH,
  509. SE_DATA => ['lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => ''],
  510. SE_USER => api_get_user_id(),
  511. ];
  512. $ic_slide->xapian_data = serialize($xapian_data);
  513. $di->addChunk($ic_slide);
  514. // Index and return search engine document id.
  515. $did = $di->index();
  516. if ($did) {
  517. // Save it to db.
  518. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  519. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  520. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  521. $sql = sprintf($sql, $tbl_se_ref, $courseCode, TOOL_LEARNPATH, $lp_id, $previous, $did);
  522. Database::query($sql);
  523. }
  524. }
  525. }
  526. }
  527. }
  528. /**
  529. * Intermediate to import_package only to allow import from local zip files.
  530. *
  531. * @param string Path to the zip file, from the sys root
  532. * @param string Current path (optional)
  533. *
  534. * @return string Absolute path to the imsmanifest.xml file or empty string on error
  535. */
  536. public function import_local_package($file_path, $currentDir = '')
  537. {
  538. // TODO: Prepare info as given by the $_FILES[''] vector.
  539. $fileInfo = [];
  540. $fileInfo['tmp_name'] = $file_path;
  541. $fileInfo['name'] = basename($file_path);
  542. // Call the normal import_package function.
  543. return $this->import_package($fileInfo, $currentDir);
  544. }
  545. /**
  546. * Imports a zip file into the Chamilo structure.
  547. *
  548. * @param string $zipFileInfo Zip file info as given by $_FILES['userFile']
  549. * @param string $currentDir
  550. * @param array $courseInfo
  551. * @param bool $updateDirContents
  552. * @param learnpath $lpToCheck
  553. * @param bool $allowHtaccess
  554. *
  555. * @return string $current_dir Absolute path to the imsmanifest.xml file or empty string on error
  556. */
  557. public function import_package(
  558. $zipFileInfo,
  559. $currentDir = '',
  560. $courseInfo = [],
  561. $updateDirContents = false,
  562. $lpToCheck = null,
  563. $allowHtaccess = false
  564. ) {
  565. if ($this->debug > 0) {
  566. error_log(
  567. 'In scorm::import_package('.print_r($zipFileInfo, true).',"'.$currentDir.'") method'
  568. );
  569. }
  570. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  571. $maxFilledSpace = DocumentManager::get_course_quota($courseInfo['code']);
  572. $zipFilePath = $zipFileInfo['tmp_name'];
  573. $zipFileName = $zipFileInfo['name'];
  574. if ($this->debug > 1) {
  575. error_log(
  576. 'New LP - import_package() - zip file path = '.$zipFilePath.', zip file name = '.$zipFileName,
  577. 0
  578. );
  579. }
  580. $courseRelDir = api_get_course_path($courseInfo['code']).'/scorm'; // scorm dir web path starting from /courses
  581. $courseSysDir = api_get_path(SYS_COURSE_PATH).$courseRelDir; // Absolute system path for this course.
  582. $currentDir = api_replace_dangerous_char(trim($currentDir)); // Current dir we are in, inside scorm/
  583. if ($this->debug > 1) {
  584. error_log('New LP - import_package() - current_dir = '.$currentDir, 0);
  585. }
  586. // Get name of the zip file without the extension.
  587. $fileInfo = pathinfo($zipFileName);
  588. $filename = $fileInfo['basename'];
  589. $extension = $fileInfo['extension'];
  590. $fileBaseName = str_replace('.'.$extension, '', $filename); // Filename without its extension.
  591. $this->zipname = $fileBaseName; // Save for later in case we don't have a title.
  592. $newDir = api_replace_dangerous_char(trim($fileBaseName));
  593. $this->subdir = $newDir;
  594. if ($this->debug > 1) {
  595. error_log('New LP - Received zip file name: '.$zipFilePath);
  596. error_log("New LP - subdir is first set to : ".$this->subdir);
  597. error_log("New LP - base file name is : ".$fileBaseName);
  598. }
  599. $zipFile = new PclZip($zipFilePath);
  600. // Check the zip content (real size and file extension).
  601. $zipContentArray = $zipFile->listContent();
  602. $packageType = '';
  603. $manifestList = [];
  604. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  605. $realFileSize = 0;
  606. foreach ($zipContentArray as $thisContent) {
  607. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  608. $file = $thisContent['filename'];
  609. $this->set_error_msg("File $file contains a PHP script");
  610. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml')) {
  611. if ($thisContent['filename'] == basename($thisContent['filename'])) {
  612. } else {
  613. if ($this->debug > 2) {
  614. error_log("New LP - subdir is now ".$this->subdir);
  615. }
  616. }
  617. $packageType = 'scorm';
  618. $manifestList[] = $thisContent['filename'];
  619. }
  620. $realFileSize += $thisContent['size'];
  621. }
  622. // Now get the shortest path (basically, the imsmanifest that is the closest to the root).
  623. $shortestPath = $manifestList[0];
  624. $slashCount = substr_count($shortestPath, '/');
  625. foreach ($manifestList as $manifestPath) {
  626. $tmpSlashCount = substr_count($manifestPath, '/');
  627. if ($tmpSlashCount < $slashCount) {
  628. $shortestPath = $manifestPath;
  629. $slashCount = $tmpSlashCount;
  630. }
  631. }
  632. $this->subdir .= '/'.dirname($shortestPath); // Do not concatenate because already done above.
  633. $manifest = $shortestPath;
  634. if ($this->debug) {
  635. error_log("New LP - Package type is now: '$packageType'");
  636. }
  637. if ($packageType == '') {
  638. Display::addFlash(
  639. Display::return_message(get_lang('NotScormContent'))
  640. );
  641. return false;
  642. }
  643. if (!enough_size($realFileSize, $courseSysDir, $maxFilledSpace)) {
  644. if ($this->debug > 1) {
  645. error_log('New LP - Not enough space to store package');
  646. }
  647. Display::addFlash(
  648. Display::return_message(get_lang('NoSpace'))
  649. );
  650. return false;
  651. }
  652. if ($updateDirContents && $lpToCheck) {
  653. $originalPath = str_replace('/.', '', $lpToCheck->path);
  654. if ($originalPath != $newDir) {
  655. Display::addFlash(Display::return_message(get_lang('FileError')));
  656. return false;
  657. }
  658. }
  659. // It happens on Linux that $newDir sometimes doesn't start with '/'
  660. if ($newDir[0] != '/') {
  661. $newDir = '/'.$newDir;
  662. }
  663. if ($newDir[strlen($newDir) - 1] == '/') {
  664. $newDir = substr($newDir, 0, -1);
  665. }
  666. /* Uncompressing phase */
  667. /*
  668. We need to process each individual file in the zip archive to
  669. - add it to the database
  670. - parse & change relative html links
  671. - make sure the filenames are secure (filter funny characters or php extensions)
  672. */
  673. if (is_dir($courseSysDir.$newDir) ||
  674. @mkdir(
  675. $courseSysDir.$newDir,
  676. api_get_permissions_for_new_directories()
  677. )
  678. ) {
  679. // PHP method - slower...
  680. if ($this->debug >= 1) {
  681. error_log('New LP - Changing dir to '.$courseSysDir.$newDir);
  682. }
  683. chdir($courseSysDir.$newDir);
  684. $callBack = 'clean_up_files_in_zip';
  685. if ($allowHtaccess) {
  686. $callBack = 'cleanZipFilesAllowHtaccess';
  687. }
  688. $zipFile->extract(
  689. PCLZIP_CB_PRE_EXTRACT,
  690. $callBack
  691. );
  692. if (!empty($newDir)) {
  693. $newDir = $newDir.'/';
  694. }
  695. api_chmod_R($courseSysDir.$newDir, api_get_permissions_for_new_directories());
  696. } else {
  697. return false;
  698. }
  699. return $courseSysDir.$newDir.$manifest;
  700. }
  701. /**
  702. * Sets the proximity setting in the database.
  703. *
  704. * @param string Proximity setting
  705. * @param int $courseId
  706. *
  707. * @return bool
  708. */
  709. public function set_proximity($proxy = '', $courseId = null)
  710. {
  711. if ($this->debug > 0) {
  712. error_log('In scorm::set_proximity('.$proxy.') method');
  713. }
  714. $lp = $this->get_id();
  715. if ($lp != 0) {
  716. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  717. $sql = "UPDATE $tbl_lp SET content_local = '$proxy'
  718. WHERE iid = $lp";
  719. $res = Database::query($sql);
  720. return $res;
  721. } else {
  722. return false;
  723. }
  724. }
  725. /**
  726. * Sets the theme setting in the database.
  727. *
  728. * @param string theme setting
  729. *
  730. * @return bool
  731. */
  732. public function set_theme($theme = '')
  733. {
  734. if ($this->debug > 0) {
  735. error_log('In scorm::set_theme('.$theme.') method');
  736. }
  737. $lp = $this->get_id();
  738. if ($lp != 0) {
  739. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  740. $sql = "UPDATE $tbl_lp SET theme = '$theme'
  741. WHERE iid = $lp";
  742. $res = Database::query($sql);
  743. return $res;
  744. } else {
  745. return false;
  746. }
  747. }
  748. /**
  749. * Sets the image setting in the database.
  750. *
  751. * @param string preview_image setting
  752. *
  753. * @return bool
  754. */
  755. public function set_preview_image($preview_image = '')
  756. {
  757. if ($this->debug > 0) {
  758. error_log('In scorm::set_theme('.$preview_image.') method', 0);
  759. }
  760. $lp = $this->get_id();
  761. if ($lp != 0) {
  762. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  763. $sql = "UPDATE $tbl_lp SET preview_image = '$preview_image'
  764. WHERE iid = $lp";
  765. $res = Database::query($sql);
  766. return $res;
  767. } else {
  768. return false;
  769. }
  770. }
  771. /**
  772. * Sets the author setting in the database.
  773. *
  774. * @param string $author
  775. *
  776. * @return bool
  777. */
  778. public function set_author($author = '')
  779. {
  780. if ($this->debug > 0) {
  781. error_log('In scorm::set_author('.$author.') method', 0);
  782. }
  783. $lp = $this->get_id();
  784. if ($lp != 0) {
  785. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  786. $sql = "UPDATE $tbl_lp SET author = '$author'
  787. WHERE iid = ".$lp;
  788. $res = Database::query($sql);
  789. return $res;
  790. } else {
  791. return false;
  792. }
  793. }
  794. /**
  795. * Sets the content maker setting in the database.
  796. *
  797. * @param string Proximity setting
  798. *
  799. * @return bool
  800. */
  801. public function set_maker($maker = '', $courseId = null)
  802. {
  803. if ($this->debug > 0) {
  804. error_log('In scorm::set_maker method('.$maker.')', 0);
  805. }
  806. $lp = $this->get_id();
  807. if ($lp != 0) {
  808. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  809. $sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE iid = $lp";
  810. $res = Database::query($sql);
  811. return $res;
  812. } else {
  813. return false;
  814. }
  815. }
  816. /**
  817. * Exports the current SCORM object's files as a zip.
  818. * Excerpts taken from learnpath_functions.inc.php::exportpath().
  819. *
  820. * @param int Learnpath ID (optional, taken from object context if not defined)
  821. *
  822. * @return bool
  823. */
  824. public function export_zip($lp_id = null)
  825. {
  826. if ($this->debug > 0) {
  827. error_log('In scorm::export_zip method('.$lp_id.')');
  828. }
  829. if (empty($lp_id)) {
  830. if (!is_object($this)) {
  831. return false;
  832. } else {
  833. $id = $this->get_id();
  834. if (empty($id)) {
  835. return false;
  836. } else {
  837. $lp_id = $this->get_id();
  838. }
  839. }
  840. }
  841. //zip everything that is in the corresponding scorm dir
  842. //write the zip file somewhere (might be too big to return)
  843. $_course = api_get_course_info();
  844. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  845. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id";
  846. $result = Database::query($sql);
  847. $row = Database::fetch_array($result);
  848. $LPname = $row['path'];
  849. $list = explode('/', $LPname);
  850. $LPnamesafe = $list[0];
  851. $zipfoldername = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/temp/'.$LPnamesafe;
  852. $scormfoldername = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/scorm/'.$LPnamesafe;
  853. $zipfilename = $zipfoldername.'/'.$LPnamesafe.'.zip';
  854. // Get a temporary dir for creating the zip file.
  855. //error_log('New LP - cleaning dir '.$zipfoldername, 0);
  856. my_delete($zipfoldername); // Make sure the temp dir is cleared.
  857. mkdir($zipfoldername, api_get_permissions_for_new_directories());
  858. // Create zipfile of given directory.
  859. $zip_folder = new PclZip($zipfilename);
  860. $zip_folder->create($scormfoldername.'/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername.'/');
  861. //This file sending implies removing the default mime-type from php.ini
  862. //DocumentManager::file_send_for_download($zipfilename, true, $LPnamesafe.'.zip');
  863. DocumentManager::file_send_for_download($zipfilename, true);
  864. // Delete the temporary zip file and directory in fileManage.lib.php
  865. my_delete($zipfilename);
  866. my_delete($zipfoldername);
  867. return true;
  868. }
  869. /**
  870. * Gets a resource's path if available, otherwise return empty string.
  871. *
  872. * @param string Resource ID as used in resource array
  873. *
  874. * @return string The resource's path as declared in imsmanifest.xml
  875. */
  876. public function get_res_path($id)
  877. {
  878. if ($this->debug > 0) {
  879. error_log('In scorm::get_res_path('.$id.') method');
  880. }
  881. $path = '';
  882. if (isset($this->resources[$id])) {
  883. $oRes = &$this->resources[$id];
  884. $path = @$oRes->get_path();
  885. }
  886. return $path;
  887. }
  888. /**
  889. * Gets a resource's type if available, otherwise return empty string.
  890. *
  891. * @param string Resource ID as used in resource array
  892. *
  893. * @return string The resource's type as declared in imsmanifest.xml
  894. */
  895. public function get_res_type($id)
  896. {
  897. if ($this->debug > 0) {
  898. error_log('In scorm::get_res_type('.$id.') method');
  899. }
  900. $type = '';
  901. if (isset($this->resources[$id])) {
  902. $oRes = &$this->resources[$id];
  903. $temptype = $oRes->get_scorm_type();
  904. if (!empty($temptype)) {
  905. $type = $temptype;
  906. }
  907. }
  908. return $type;
  909. }
  910. /**
  911. * Gets the default organisation's title.
  912. *
  913. * @return string The organization's title
  914. */
  915. public function get_title()
  916. {
  917. if ($this->debug > 0) {
  918. error_log('In scorm::get_title() method');
  919. }
  920. $title = '';
  921. if (isset($this->manifest['organizations']['default'])) {
  922. $title = $this->organizations[$this->manifest['organizations']['default']]->get_name();
  923. } elseif (count($this->organizations) == 1) {
  924. // This will only get one title but so we don't need to know the index.
  925. foreach ($this->organizations as $id => $value) {
  926. $title = $this->organizations[$id]->get_name();
  927. break;
  928. }
  929. }
  930. return $title;
  931. }
  932. /**
  933. * // TODO @TODO Implement this function to restore items data from an imsmanifest,
  934. * updating the existing table... This will prove very useful in case initial data
  935. * from imsmanifest were not imported well enough.
  936. *
  937. * @param string $courseCode
  938. * @param int LP ID (in database)
  939. * @param string Manifest file path (optional if lp_id defined)
  940. *
  941. * @return int New LP ID or false on failure
  942. * TODO @TODO Implement imsmanifest_path parameter
  943. */
  944. public function reimport_manifest($courseCode, $lp_id = null, $imsmanifest_path = '')
  945. {
  946. if ($this->debug > 0) {
  947. error_log('In scorm::reimport_manifest() method', 0);
  948. }
  949. $courseInfo = api_get_course_info($courseCode);
  950. if (empty($courseInfo)) {
  951. $this->error = 'Course code does not exist in database';
  952. return false;
  953. }
  954. $this->cc = $courseInfo['code'];
  955. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  956. $lp_id = intval($lp_id);
  957. $sql = "SELECT * FROM $lp_table WHERE iid = $lp_id";
  958. if ($this->debug > 2) {
  959. error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying lp: '.$sql);
  960. }
  961. $res = Database::query($sql);
  962. if (Database::num_rows($res) > 0) {
  963. $this->lp_id = $lp_id;
  964. $row = Database::fetch_array($res);
  965. $this->type = $row['lp_type'];
  966. $this->name = stripslashes($row['name']);
  967. $this->encoding = $row['default_encoding'];
  968. $this->proximity = $row['content_local'];
  969. $this->maker = $row['content_maker'];
  970. $this->prevent_reinit = $row['prevent_reinit'];
  971. $this->license = $row['content_license'];
  972. $this->scorm_debug = $row['debug'];
  973. $this->js_lib = $row['js_lib'];
  974. $this->path = $row['path'];
  975. if ($this->type == 2) {
  976. if ($row['force_commit'] == 1) {
  977. $this->force_commit = true;
  978. }
  979. }
  980. $this->mode = $row['default_view_mod'];
  981. $this->subdir = $row['path'];
  982. }
  983. // Parse the manifest (it is already in this lp's details).
  984. $manifest_file = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/scorm/'.$this->subdir.'/imsmanifest.xml';
  985. if ($this->subdir == '') {
  986. $manifest_file = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/scorm/imsmanifest.xml';
  987. }
  988. echo $manifest_file;
  989. if (is_file($manifest_file) && is_readable($manifest_file)) {
  990. // Re-parse the manifest file.
  991. if ($this->debug > 1) {
  992. error_log('New LP - In scorm::reimport_manifest() - Parsing manifest '.$manifest_file);
  993. }
  994. $manifest = $this->parse_manifest($manifest_file);
  995. // Import new LP in DB (ignore the current one).
  996. if ($this->debug > 1) {
  997. error_log('New LP - In scorm::reimport_manifest() - Importing manifest '.$manifest_file);
  998. }
  999. $this->import_manifest($this->cc);
  1000. } else {
  1001. if ($this->debug > 0) {
  1002. error_log('New LP - In scorm::reimport_manifest() - Could not find manifest file at '.$manifest_file);
  1003. }
  1004. }
  1005. return false;
  1006. }
  1007. /**
  1008. * Detects the encoding of a given manifest (a xml-text).
  1009. * It is possible the encoding of the manifest to be wrongly declared or
  1010. * not to be declared at all. The proposed method tries to resolve these problems.
  1011. *
  1012. * @param string $xml the input xml-text
  1013. *
  1014. * @return string the detected value of the input xml
  1015. */
  1016. private function detect_manifest_encoding(&$xml)
  1017. {
  1018. if (api_is_valid_utf8($xml)) {
  1019. return 'UTF-8';
  1020. }
  1021. if (preg_match(_PCRE_XML_ENCODING, $xml, $matches)) {
  1022. $declared_encoding = api_refine_encoding_id($matches[1]);
  1023. } else {
  1024. $declared_encoding = '';
  1025. }
  1026. if (!empty($declared_encoding) && !api_is_utf8($declared_encoding)) {
  1027. return $declared_encoding;
  1028. }
  1029. $test_string = '';
  1030. if (preg_match_all('/<langstring[^>]*>(.*)<\/langstring>/m', $xml, $matches)) {
  1031. $test_string = implode("\n", $matches[1]);
  1032. unset($matches);
  1033. }
  1034. if (preg_match_all('/<title[^>]*>(.*)<\/title>/m', $xml, $matches)) {
  1035. $test_string .= "\n".implode("\n", $matches[1]);
  1036. unset($matches);
  1037. }
  1038. if (empty($test_string)) {
  1039. $test_string = $xml;
  1040. }
  1041. return api_detect_encoding($test_string);
  1042. }
  1043. }