scorm.class.php 44 KB

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