scorm.class.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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. // Get table names.
  249. $new_lp = Database::get_course_table(TABLE_LP_MAIN, $dbname);
  250. $new_lp_item = Database::get_course_table(TABLE_LP_ITEM, $dbname);
  251. $use_max_score = intval($use_max_score);
  252. foreach ($this->organizations as $id => $dummy) {
  253. $is_session = api_get_session_id();
  254. $is_session != 0 ? $session_id = $is_session : $session_id = 0;
  255. $oOrganization =& $this->organizations[$id];
  256. // Prepare and execute insert queries:
  257. // -for learnpath
  258. // -for items
  259. // -for views?
  260. $get_max = "SELECT MAX(display_order) FROM $new_lp";
  261. $res_max = Database::query($get_max);
  262. $dsp = 1;
  263. if (Database::num_rows($res_max) > 0) {
  264. $row = Database::fetch_array($res_max);
  265. $dsp = $row[0] + 1;
  266. }
  267. $myname = $oOrganization->get_name();
  268. $myname = api_utf8_decode($myname);
  269. $sql = "INSERT INTO $new_lp (lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order, session_id, use_max_score)" .
  270. "VALUES (2,'".$myname."', '".$oOrganization->get_ref()."','','".$this->subdir."', 0, 'embedded', '".$this->manifest_encoding."', 'scorm_api.php', $dsp, $session_id, $use_max_score)";
  271. if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting path: '. $sql, 0); }
  272. $res = Database::query($sql);
  273. $lp_id = Database::insert_id();
  274. $this->lp_id = $lp_id;
  275. // Insert into item_property.
  276. api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'LearnpathAdded', api_get_user_id());
  277. api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'visible', api_get_user_id());
  278. // Now insert all elements from inside that learning path.
  279. // Make sure we also get the href and sco/asset from the resources.
  280. $list = $oOrganization->get_flat_items_list();
  281. $parents_stack = array(0);
  282. $parent = 0;
  283. $previous = 0;
  284. $level = 0;
  285. foreach ($list as $item) {
  286. if ($item['level'] > $level) {
  287. // Push something into the parents array.
  288. array_push($parents_stack, $previous);
  289. $parent = $previous;
  290. } elseif ($item['level'] < $level) {
  291. $diff = $level - $item['level'];
  292. // Pop something out of the parents array.
  293. for ($j = 1; $j <= $diff; $j++) {
  294. $outdated_parent = array_pop($parents_stack);
  295. }
  296. $parent = array_pop($parents_stack); // Just save that value, then add it back.
  297. array_push($parents_stack,$parent);
  298. }
  299. $path = '';
  300. $type = 'dir';
  301. if (isset($this->resources[$item['identifierref']])) {
  302. $oRes =& $this->resources[$item['identifierref']];
  303. $path = @$oRes->get_path();
  304. if (!empty($path)) {
  305. $temptype = $oRes->get_scorm_type();
  306. if (!empty($temptype)) {
  307. $type = $temptype;
  308. }
  309. }
  310. }
  311. $level = $item['level'];
  312. $field_add = '';
  313. $value_add = '';
  314. if (!empty($item['masteryscore'])) {
  315. $field_add .= 'mastery_score, ';
  316. $value_add .= $item['masteryscore'].',';
  317. }
  318. if (!empty($item['maxtimeallowed'])) {
  319. $field_add .= 'max_time_allowed, ';
  320. $value_add .= "'".$item['maxtimeallowed']."',";
  321. }
  322. $title = Database::escape_string($item['title']);
  323. $title = api_utf8_decode($title);
  324. $max_score = Database::escape_string($item['max_score']);
  325. if ($max_score == 0 || is_null($max_score) || $max_score == '') {
  326. //If max score is not set The use_max_score parameter is check in order to use 100 (chamilo style) or '' (strict scorm)
  327. if ($use_max_score) {
  328. $max_score = "'100'";
  329. } else {
  330. $max_score = "NULL";
  331. }
  332. } else {
  333. //Otherwise save the max score
  334. $max_score = "'$max_score'";
  335. }
  336. $identifier = Database::escape_string($item['identifier']);
  337. $prereq = Database::escape_string($item['prerequisites']);
  338. $sql_item = "INSERT INTO $new_lp_item " .
  339. "(lp_id,item_type,ref,title," .
  340. "path,min_score,max_score, $field_add" .
  341. "parent_item_id,previous_item_id,next_item_id," .
  342. "prerequisite,display_order,launch_data," .
  343. "parameters) " .
  344. "VALUES " .
  345. "($lp_id, '$type','".$identifier."','".$title."'," .
  346. "'$path',0,$max_score, $value_add" .
  347. "$parent, $previous, 0, " .
  348. "'$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."'," .
  349. "'".$item['parameters']."'" .
  350. ")";
  351. $res_item = Database::query($sql_item);
  352. if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting item : '.$sql_item.' : '.mysql_error(), 0); }
  353. $item_id = Database::insert_id();
  354. // Now update previous item to change next_item_id.
  355. $upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE id = $previous";
  356. $upd_res = Database::query($upd);
  357. // Update previous item id.
  358. $previous = $item_id;
  359. // Code for indexing, now only index specific fields like terms and the title.
  360. if (!empty($_POST['index_document'])) {
  361. require_once api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php';
  362. require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
  363. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  364. $di = new DokeosIndexer();
  365. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  366. $di->connectDb(NULL, NULL, $lang);
  367. $ic_slide = new IndexableChunk();
  368. $ic_slide->addValue('title', $title);
  369. $specific_fields = get_specific_field_list();
  370. $all_specific_terms = '';
  371. foreach ($specific_fields as $specific_field) {
  372. if (isset($_REQUEST[$specific_field['code']])) {
  373. $sterms = trim($_REQUEST[$specific_field['code']]);
  374. $all_specific_terms .= ' '. $sterms;
  375. if (!empty($sterms)) {
  376. $sterms = explode(',', $sterms);
  377. foreach ($sterms as $sterm) {
  378. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  379. }
  380. }
  381. }
  382. }
  383. $body_to_index = $all_specific_terms .' '. $title;
  384. $ic_slide->addValue("content", $body_to_index);
  385. // TODO: Add a comment to say terms separated by commas.
  386. $courseid = api_get_course_id();
  387. $ic_slide->addCourseId($courseid);
  388. $ic_slide->addToolId(TOOL_LEARNPATH);
  389. $xapian_data = array(
  390. SE_COURSE_ID => $courseid,
  391. SE_TOOL_ID => TOOL_LEARNPATH,
  392. SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => ''), // TODO: Unify with other lp types.
  393. SE_USER => (int)api_get_user_id(),
  394. );
  395. $ic_slide->xapian_data = serialize($xapian_data);
  396. $di->addChunk($ic_slide);
  397. // Index and return search engine document id.
  398. $did = $di->index();
  399. if ($did) {
  400. // Save it to db.
  401. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  402. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  403. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  404. $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
  405. Database::query($sql);
  406. }
  407. }
  408. }
  409. }
  410. }
  411. /**
  412. * Intermediate to import_package only to allow import from local zip files
  413. * @param string Path to the zip file, from the dokeos sys root
  414. * @param string Current path (optional)
  415. * @return string Absolute path to the imsmanifest.xml file or empty string on error
  416. */
  417. function import_local_package($file_path, $current_dir = '') {
  418. // TODO: Prepare info as given by the $_FILES[''] vector.
  419. $file_info = array();
  420. $file_info['tmp_name'] = $file_path;
  421. $file_info['name'] = basename($file_path);
  422. // Call the normal import_package function.
  423. return $this->import_package($file_info, $current_dir);
  424. }
  425. /**
  426. * Imports a zip file into the Chamilo structure
  427. * @param string Zip file info as given by $_FILES['userFile']
  428. * @return string Absolute path to the imsmanifest.xml file or empty string on error
  429. */
  430. function import_package($zip_file_info, $current_dir = '') {
  431. if ($this->debug > 0) { error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method', 0); }
  432. require_once api_get_path(LIBRARY_PATH).'document.lib.php';
  433. $maxFilledSpace = DocumentManager :: get_course_quota();
  434. $zip_file_path = $zip_file_info['tmp_name'];
  435. $zip_file_name = $zip_file_info['name'];
  436. if ($this->debug > 1) { error_log('New LP - import_package() - zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name, 0); }
  437. $course_rel_dir = api_get_course_path().'/scorm'; // scorm dir web path starting from /courses
  438. $course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // Sbsolute system path for this course.
  439. $current_dir = replace_dangerous_char(trim($current_dir),'strict'); // Current dir we are in, inside scorm/
  440. if ($this->debug > 1) { error_log('New LP - import_package() - current_dir = '.$current_dir, 0); }
  441. //$uploaded_filename = $_FILES['userFile']['name'];
  442. // Get name of the zip file without the extension.
  443. if ($this->debug > 1) { error_log('New LP - Received zip file name: '.$zip_file_path, 0); }
  444. $file_info = pathinfo($zip_file_name);
  445. $filename = $file_info['basename'];
  446. $extension = $file_info['extension'];
  447. $file_base_name = str_replace('.'.$extension,'',$filename); // Filename without its extension.
  448. $this->zipname = $file_base_name; // Save for later in case we don't have a title.
  449. if ($this->debug > 1) { error_log("New LP - base file name is : ".$file_base_name, 0); }
  450. $new_dir = replace_dangerous_char(trim($file_base_name),'strict');
  451. $this->subdir = $new_dir;
  452. if ($this->debug > 1) { error_log("New LP - subdir is first set to : ".$this->subdir, 0); }
  453. $zipFile = new pclZip($zip_file_path);
  454. // Check the zip content (real size and file extension).
  455. $zipContentArray = $zipFile->listContent();
  456. $package_type = '';
  457. $at_root = false;
  458. $manifest = '';
  459. $manifest_list = array();
  460. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  461. foreach($zipContentArray as $thisContent) {
  462. //error_log('Looking at '.$thisContent['filename'], 0);
  463. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  464. $this->set_error_msg("File $file contains a PHP script");
  465. //return api_failure::set_failure('php_file_in_zip_file');
  466. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml')) {
  467. //error_log('Found imsmanifest at '.$thisContent['filename'], 0);
  468. if ($thisContent['filename'] == basename($thisContent['filename'])) {
  469. $at_root = true;
  470. } else {
  471. //$this->subdir .= '/'.dirname($thisContent['filename']);
  472. if ($this->debug > 2) { error_log("New LP - subdir is now ".$this->subdir, 0); }
  473. }
  474. $package_type = 'scorm';
  475. $manifest_list[] = $thisContent['filename'];
  476. $manifest = $thisContent['filename']; //just the relative directory inside scorm/
  477. } else {
  478. // Do nothing, if it has not been set as scorm somewhere else, it stays as '' default.
  479. }
  480. $realFileSize += $thisContent['size'];
  481. }
  482. // Now get the shortest path (basically, the imsmanifest that is the closest to the root).
  483. $shortest_path = $manifest_list[0];
  484. $slash_count = substr_count($shortest_path, '/');
  485. foreach ($manifest_list as $manifest_path) {
  486. $tmp_slash_count = substr_count($manifest_path, '/');
  487. if ($tmp_slash_count<$slash_count) {
  488. $shortest_path = $manifest_path;
  489. $slash_count = $tmp_slash_count;
  490. }
  491. }
  492. $this->subdir .= '/'.dirname($shortest_path); // Do not concatenate because already done above.
  493. $manifest = $shortest_path;
  494. if ($this->debug > 1) { error_log('New LP - Package type is now '.$package_type, 0); }
  495. if ($package_type== '')
  496. // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
  497. {
  498. if ($this->debug > 1) { error_log('New LP - Package type is empty', 0); }
  499. return api_failure::set_failure('not_scorm_content');
  500. }
  501. if (!enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
  502. if ($this->debug > 1) { error_log('New LP - Not enough space to store package', 0); }
  503. return api_failure::set_failure('not_enough_space');
  504. }
  505. // It happens on Linux that $new_dir sometimes doesn't start with '/'
  506. if ($new_dir[0] != '/') {
  507. $new_dir = '/'.$new_dir;
  508. }
  509. if ($new_dir[strlen($new_dir)-1] == '/') {
  510. $new_dir = substr($new_dir,0,-1);
  511. }
  512. /* Uncompressing phase */
  513. /*
  514. We need to process each individual file in the zip archive to
  515. - add it to the database
  516. - parse & change relative html links
  517. - make sure the filenames are secure (filter funny characters or php extensions)
  518. */
  519. if (is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir, api_get_permissions_for_new_directories())) {
  520. // PHP method - slower...
  521. if ($this->debug >= 1) { error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir, 0); }
  522. $saved_dir = getcwd();
  523. chdir($course_sys_dir.$new_dir);
  524. $unzippingState = $zipFile->extract();
  525. for($j = 0; $j < count($unzippingState); $j++) {
  526. $state = $unzippingState[$j];
  527. // TODO: Fix relative links in html files (?)
  528. $extension = strrchr($state['stored_filename'], '.');
  529. if ($this->debug >= 1) { error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'], 0); }
  530. }
  531. if (!empty($new_dir)) {
  532. $new_dir = $new_dir.'/';
  533. }
  534. // Rename files, for example with \\ in it.
  535. if ($dir = @opendir($course_sys_dir.$new_dir)) {
  536. if ($this->debug == 1) { error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0); }
  537. while ($file=readdir($dir)) {
  538. if ($file != '.' && $file != '..') {
  539. $filetype = 'file';
  540. if (is_dir($course_sys_dir.$new_dir.$file)) $filetype = 'folder';
  541. // TODO: RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
  542. //$safe_file = replace_dangerous_char($file, 'strict');
  543. $find_str = array('\\', '.php', '.phtml');
  544. $repl_str = array('/', '.txt', '.txt');
  545. $safe_file = str_replace($find_str, $repl_str,$file);
  546. if ($safe_file != $file) {
  547. //@rename($course_sys_dir.$new_dir, $course_sys_dir.'/'.$safe_file);
  548. $mydir = dirname($course_sys_dir.$new_dir.$safe_file);
  549. if (!is_dir($mydir)) {
  550. $mysubdirs = split('/', $mydir);
  551. $mybasedir = '/';
  552. foreach ($mysubdirs as $mysubdir) {
  553. if (!empty($mysubdir)) {
  554. $mybasedir = $mybasedir.$mysubdir.'/';
  555. if (!is_dir($mybasedir)) {
  556. @mkdir($mybasedir, api_get_permissions_for_new_directories());
  557. if ($this->debug == 1) { error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.', 0); }
  558. }
  559. }
  560. }
  561. }
  562. @rename($course_sys_dir.$new_dir.$file,$course_sys_dir.$new_dir.$safe_file);
  563. if ($this->debug == 1) { error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file, 0); }
  564. }
  565. //set_default_settings($course_sys_dir, $safe_file, $filetype);
  566. }
  567. }
  568. closedir($dir);
  569. chdir($saved_dir);
  570. api_chmod_R($course_sys_dir.$new_dir, api_get_permissions_for_new_directories());
  571. if ($this->debug > 1) { error_log('New LP - changed back to init dir', 0); }
  572. }
  573. } else {
  574. return '';
  575. }
  576. return $course_sys_dir.$new_dir.$manifest;
  577. }
  578. /**
  579. * Sets the proximity setting in the database
  580. * @param string Proximity setting
  581. */
  582. function set_proximity($proxy = '') {
  583. if ($this->debug > 0) { error_log('In scorm::set_proximity('.$proxy.') method', 0); }
  584. $lp = $this->get_id();
  585. if ($lp != 0) {
  586. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  587. $sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE id = ".$lp;
  588. $res = Database::query($sql);
  589. return $res;
  590. } else {
  591. return false;
  592. }
  593. }
  594. /**
  595. * Sets the theme setting in the database
  596. * @param string theme setting
  597. */
  598. function set_theme($theme = '') {
  599. if ($this->debug > 0) { error_log('In scorm::set_theme('.$theme.') method', 0); }
  600. $lp = $this->get_id();
  601. if ($lp != 0) {
  602. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  603. $sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE id = ".$lp;
  604. $res = Database::query($sql);
  605. return $res;
  606. } else {
  607. return false;
  608. }
  609. }
  610. /**
  611. * Sets the image setting in the database
  612. * @param string preview_image setting
  613. */
  614. function set_preview_image($preview_image = '') {
  615. if ($this->debug > 0) { error_log('In scorm::set_theme('.$preview_image.') method', 0); }
  616. $lp = $this->get_id();
  617. if ($lp != 0) {
  618. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  619. $sql = "UPDATE $tbl_lp SET preview_image = '$preview_image' WHERE id = ".$lp;
  620. $res = Database::query($sql);
  621. return $res;
  622. } else {
  623. return false;
  624. }
  625. }
  626. /**
  627. * Sets the author setting in the database
  628. * @param string preview_image setting
  629. */
  630. function set_author($author = '') {
  631. if ($this->debug > 0) { error_log('In scorm::set_author('.$author.') method', 0); }
  632. $lp = $this->get_id();
  633. if ($lp != 0) {
  634. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  635. $sql = "UPDATE $tbl_lp SET author = '$author' WHERE id = ".$lp;
  636. $res = Database::query($sql);
  637. return $res;
  638. } else {
  639. return false;
  640. }
  641. }
  642. /**
  643. * Sets the content maker setting in the database
  644. * @param string Proximity setting
  645. */
  646. function set_maker($maker = '') {
  647. if ($this->debug > 0) { error_log('In scorm::set_maker method('.$maker.')', 0); }
  648. $lp = $this->get_id();
  649. if ($lp != 0) {
  650. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  651. $sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE id = ".$lp;
  652. $res = Database::query($sql);
  653. return $res;
  654. } else {
  655. return false;
  656. }
  657. }
  658. /**
  659. * Exports the current SCORM object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
  660. * @param integer Learnpath ID (optional, taken from object context if not defined)
  661. */
  662. function export_zip($lp_id = null) {
  663. if ($this->debug > 0) { error_log('In scorm::export_zip method('.$lp_id.')', 0); }
  664. if (empty($lp_id)) {
  665. if (!is_object($this)) {
  666. return false;
  667. } else {
  668. $id = $this->get_id();
  669. if (empty($id)) {
  670. return false;
  671. } else {
  672. $lp_id = $this->get_id();
  673. }
  674. }
  675. }
  676. //error_log('New LP - in export_zip()',0);
  677. //zip everything that is in the corresponding scorm dir
  678. //write the zip file somewhere (might be too big to return)
  679. require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
  680. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  681. require_once api_get_path(LIBRARY_PATH).'document.lib.php';
  682. require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
  683. require_once 'learnpath_functions.inc.php';
  684. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  685. $_course = Database::get_course_info(api_get_course_id());
  686. $sql = "SELECT * FROM $tbl_lp WHERE id=".$lp_id;
  687. $result = Database::query($sql);
  688. $row = Database::fetch_array($result);
  689. $LPname = $row['path'];
  690. $list = split('/', $LPname);
  691. $LPnamesafe = $list[0];
  692. //$zipfoldername = '/tmp';
  693. //$zipfoldername = '../../courses/'.$_course['directory'].'/temp/'.$LPnamesafe;
  694. $zipfoldername = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/temp/'.$LPnamesafe;
  695. $scormfoldername = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/scorm/'.$LPnamesafe;
  696. $zipfilename = $zipfoldername.'/'.$LPnamesafe.'.zip';
  697. // Get a temporary dir for creating the zip file.
  698. //error_log('New LP - cleaning dir '.$zipfoldername, 0);
  699. deldir($zipfoldername); // Make sure the temp dir is cleared.
  700. $res = mkdir($zipfoldername, api_get_permissions_for_new_directories());
  701. //error_log('New LP - made dir '.$zipfoldername, 0);
  702. // Create zipfile of given directory.
  703. $zip_folder = new PclZip($zipfilename);
  704. $zip_folder->create($scormfoldername.'/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername.'/');
  705. //$zipfilename = '/var/www/dokeos-comp/courses/TEST2/scorm/example_document.html';
  706. //This file sending implies removing the default mime-type from php.ini
  707. //DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.'.zip');
  708. DocumentManager :: file_send_for_download($zipfilename, true);
  709. // Delete the temporary zip file and directory in fileManage.lib.php
  710. my_delete($zipfilename);
  711. my_delete($zipfoldername);
  712. return true;
  713. }
  714. /**
  715. * Gets a resource's path if available, otherwise return empty string
  716. * @param string Resource ID as used in resource array
  717. * @return string The resource's path as declared in imsmanifest.xml
  718. */
  719. function get_res_path($id) {
  720. if ($this->debug > 0) { error_log('In scorm::get_res_path('.$id.') method', 0); }
  721. $path = '';
  722. if (isset($this->resources[$id])) {
  723. $oRes =& $this->resources[$id];
  724. $path = @$oRes->get_path();
  725. }
  726. return $path;
  727. }
  728. /**
  729. * Gets a resource's type if available, otherwise return empty string
  730. * @param string Resource ID as used in resource array
  731. * @return string The resource's type as declared in imsmanifest.xml
  732. */
  733. function get_res_type($id) {
  734. if ($this->debug > 0) { error_log('In scorm::get_res_type('.$id.') method', 0); }
  735. $type = '';
  736. if (isset($this->resources[$id])) {
  737. $oRes =& $this->resources[$id];
  738. $temptype = $oRes->get_scorm_type();
  739. if (!empty($temptype)) {
  740. $type = $temptype;
  741. }
  742. }
  743. return $type;
  744. }
  745. /**
  746. * Gets the default organisation's title
  747. * @return string The organization's title
  748. */
  749. function get_title() {
  750. if ($this->debug > 0) { error_log('In scorm::get_title() method', 0); }
  751. $title = '';
  752. if (isset($this->manifest['organizations']['default'])) {
  753. $title = $this->organizations[$this->manifest['organizations']['default']]->get_name();
  754. } elseif (count($this->organizations)==1) {
  755. // This will only get one title but so we don't need to know the index.
  756. foreach($this->organizations as $id => $value) {
  757. $title = $this->organizations[$id]->get_name();
  758. break;
  759. }
  760. }
  761. return $title;
  762. }
  763. /**
  764. * // TODO @TODO Implement this function to restore items data from an imsmanifest,
  765. * updating the existing table... This will prove very useful in case initial data
  766. * from imsmanifest were not imported well enough
  767. * @param string course Code
  768. * @param string LP ID (in database)
  769. * @param string Manifest file path (optional if lp_id defined)
  770. * @return integer New LP ID or false on failure
  771. * TODO @TODO Implement imsmanifest_path parameter
  772. */
  773. function reimport_manifest($course, $lp_id = null, $imsmanifest_path = '') {
  774. if ($this->debug > 0) { error_log('In scorm::reimport_manifest() method', 0); }
  775. global $_course;
  776. // RECOVERING PATH FROM DB
  777. $main_table = Database::get_main_table(TABLE_MAIN_COURSE);
  778. //$course = Database::escape_string($course);
  779. $course = $this->escape_string($course);
  780. $sql = "SELECT * FROM $main_table WHERE code = '$course'";
  781. if ($this->debug > 2) { error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying course: '.$sql, 0); }
  782. //$res = Database::query($sql);
  783. $res = Database::query($sql);
  784. if (Database::num_rows($res) > 0) {
  785. $this->cc = $course;
  786. } else {
  787. $this->error = 'Course code does not exist in database ('.$sql.')';
  788. return false;
  789. }
  790. // TODO: Make it flexible to use any course_code (still using env course code here)
  791. //$lp_table = Database::get_course_table(LEARNPATH_TABLE);
  792. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  793. //$id = Database::escape_integer($id);
  794. $lp_id = $this->escape_string($lp_id);
  795. $sql = "SELECT * FROM $lp_table WHERE id = '$lp_id'";
  796. if ($this->debug > 2) { error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying lp: '.$sql, 0); }
  797. //$res = Database::query($sql);
  798. $res = Database::query($sql);
  799. if (Database::num_rows($res) > 0) {
  800. $this->lp_id = $lp_id;
  801. $row = Database::fetch_array($res);
  802. $this->type = $row['lp_type'];
  803. $this->name = stripslashes($row['name']);
  804. $this->encoding = $row['default_encoding'];
  805. $this->proximity = $row['content_local'];
  806. $this->maker = $row['content_maker'];
  807. $this->prevent_reinit = $row['prevent_reinit'];
  808. $this->license = $row['content_license'];
  809. $this->scorm_debug = $row['debug'];
  810. $this->js_lib = $row['js_lib'];
  811. $this->path = $row['path'];
  812. if ($this->type == 2) {
  813. if ($row['force_commit'] == 1) {
  814. $this->force_commit = true;
  815. }
  816. }
  817. $this->mode = $row['default_view_mod'];
  818. $this->subdir = $row['path'];
  819. }
  820. // Parse the manifest (it is already in this lp's details).
  821. $manifest_file = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/scorm/'.$this->subdir.'/imsmanifest.xml';
  822. if ($this->subdir == '') {
  823. $manifest_file = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/scorm/imsmanifest.xml';
  824. }
  825. echo $manifest_file;
  826. if (is_file($manifest_file) && is_readable($manifest_file)) {
  827. // Re-parse the manifest file.
  828. if ($this->debug > 1) { error_log('New LP - In scorm::reimport_manifest() - Parsing manifest '.$manifest_file, 0); }
  829. $manifest = $this->parse_manifest($manifest_file);
  830. // Import new LP in DB (ignore the current one).
  831. if ($this->debug > 1) { error_log('New LP - In scorm::reimport_manifest() - Importing manifest '.$manifest_file, 0); }
  832. $this->import_manifest(api_get_course_id());
  833. } else {
  834. if ($this->debug > 0) { error_log('New LP - In scorm::reimport_manifest() - Could not find manifest file at '.$manifest_file, 0); }
  835. }
  836. return false;
  837. }
  838. }