scorm.class.php 44 KB

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