scorm.class.php 45 KB

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