scorm.class.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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.
  751. * Excerpts taken from learnpath_functions.inc.php::exportpath()
  752. * @param integer Learnpath ID (optional, taken from object context if not defined)
  753. */
  754. public function export_zip($lp_id = null)
  755. {
  756. if ($this->debug > 0) { error_log('In scorm::export_zip method('.$lp_id.')', 0); }
  757. if (empty($lp_id)) {
  758. if (!is_object($this)) {
  759. return false;
  760. } else {
  761. $id = $this->get_id();
  762. if (empty($id)) {
  763. return false;
  764. } else {
  765. $lp_id = $this->get_id();
  766. }
  767. }
  768. }
  769. //zip everything that is in the corresponding scorm dir
  770. //write the zip file somewhere (might be too big to return)
  771. $courseId = api_get_course_int_id();
  772. $_course = api_get_course_info();
  773. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  774. $sql = "SELECT * FROM $tbl_lp WHERE c_id = ".$courseId." AND id=".$lp_id;
  775. $result = Database::query($sql);
  776. $row = Database::fetch_array($result);
  777. $LPname = $row['path'];
  778. $list = explode('/', $LPname);
  779. $LPnamesafe = $list[0];
  780. $zipfoldername = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/temp/'.$LPnamesafe;
  781. $scormfoldername = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/scorm/'.$LPnamesafe;
  782. $zipfilename = $zipfoldername.'/'.$LPnamesafe.'.zip';
  783. // Get a temporary dir for creating the zip file.
  784. //error_log('New LP - cleaning dir '.$zipfoldername, 0);
  785. my_delete($zipfoldername); // Make sure the temp dir is cleared.
  786. mkdir($zipfoldername, api_get_permissions_for_new_directories());
  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. }