scorm.class.php 41 KB

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