scorm.class.php 44 KB

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