scorm.class.php 44 KB

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