scorm.class.php 41 KB

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