scorm.class.php 49 KB

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