scorm.class.php 44 KB

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