scorm.class.php 45 KB

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