scorm.class.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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.scorm
  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('lp',$dbname);
  361. $new_lp_item = Database::get_course_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 = mb_convert_encoding($myname,$charset,$this->manifest_encoding);
  381. //error_log('New LP - Converting name from '.$this->manifest_encoding.' to ISO-8859-1',0);
  382. }
  383. $sql = "INSERT INTO $new_lp (lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order)" .
  384. "VALUES (2,'".$myname."', '".$oOrganization->get_ref()."','','".$this->subdir."', 0, 'embedded', '".$this->manifest_encoding."','scorm_api.php',$dsp)";
  385. if($this->debug>1){error_log('New LP - In import_manifest(), inserting path: '. $sql,0);}
  386. $res = api_sql_query($sql,__FILE__,__LINE__);
  387. $lp_id = Database::get_last_insert_id();
  388. $this->lp_id = $lp_id;
  389. //insert into item_property
  390. api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'LearnpathAdded',api_get_user_id());
  391. api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'visible',api_get_user_id());
  392. //now insert all elements from inside that learning path
  393. //make sure we also get the href and sco/asset from the resources
  394. $list = $oOrganization->get_flat_items_list();
  395. $parents_stack = array(0);
  396. $parent = 0;
  397. $previous = 0;
  398. $level = 0;
  399. foreach($list as $item){
  400. if($item['level'] > $level){
  401. //push something into the parents array
  402. array_push($parents_stack,$previous);
  403. $parent = $previous;
  404. }elseif($item['level'] < $level){
  405. $diff = $level - $item['level'];
  406. //pop something out of the parents array
  407. for($j=1;$j<=$diff;$j++){
  408. $outdated_parent = array_pop($parents_stack);
  409. }
  410. $parent = array_pop($parents_stack); //just save that value, then add it back
  411. array_push($parents_stack,$parent);
  412. }
  413. $path = '';
  414. $type = 'dir';
  415. if(isset($this->resources[$item['identifierref']])){
  416. $oRes =& $this->resources[$item['identifierref']];
  417. $path = @$oRes->get_path();
  418. if(!empty($path)){
  419. $temptype = $oRes->get_scorm_type();
  420. if(!empty($temptype)){
  421. $type = $temptype;
  422. }
  423. }
  424. }
  425. $level = $item['level'];
  426. $field_add = '';
  427. $value_add = '';
  428. if(!empty($item['masteryscore'])){
  429. $field_add .= 'mastery_score, ';
  430. $value_add .= $item['masteryscore'].',';
  431. }
  432. if(!empty($item['maxtimeallowed']))
  433. {
  434. $field_add .= 'max_time_allowed, ';
  435. $value_add .= "'".$item['maxtimeallowed']."',";
  436. }
  437. $title = mysql_real_escape_string($item['title']);
  438. //DOM in PHP5 is always recovering data as UTF-8, somehow, no matter what
  439. //the XML document encoding is. This means that we have to convert
  440. //the data to the declared encoding when it is not UTF-8
  441. if($this->manifest_encoding != 'UTF-8'){
  442. $title = mb_convert_encoding($title,$this->manifest_encoding,'UTF-8');
  443. }
  444. //if($this->manifest_encoding != $charset){
  445. // $title = mb_convert_encoding($title,$charset,$this->manifest_encoding);
  446. //}
  447. $identifier = mysql_real_escape_string($item['identifier']);
  448. $prereq = mysql_real_escape_string($item['prerequisites']);
  449. $sql_item = "INSERT INTO $new_lp_item " .
  450. "(lp_id,item_type,ref,title," .
  451. "path,min_score,max_score, $field_add" .
  452. "parent_item_id,previous_item_id,next_item_id," .
  453. "prerequisite,display_order,launch_data," .
  454. "parameters) " .
  455. "VALUES " .
  456. "($lp_id, '$type','".$identifier."','".$title."'," .
  457. "'$path',0,100, $value_add" .
  458. "$parent, $previous, 0, " .
  459. "'$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."'," .
  460. "'".$item['parameters']."'" .
  461. ")";
  462. $res_item = api_sql_query($sql_item);
  463. if($this->debug>1){error_log('New LP - In import_manifest(), inserting item : '.$sql_item.' : '.mysql_error(),0);}
  464. $item_id = Database::get_last_insert_id();
  465. //now update previous item to change next_item_id
  466. $upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE id = $previous";
  467. $upd_res = api_sql_query($upd);
  468. //update previous item id
  469. $previous = $item_id;
  470. }
  471. }
  472. }
  473. /**
  474. * Intermediate to import_package only to allow import from local zip files
  475. * @param string Path to the zip file, from the dokeos sys root
  476. * @param string Current path (optional)
  477. * @return string Absolute path to the imsmanifest.xml file or empty string on error
  478. */
  479. function import_local_package($file_path,$current_dir='')
  480. {
  481. //todo prepare info as given by the $_FILES[''] vector
  482. $file_info = array();
  483. $file_info['tmp_name'] = $file_path;
  484. $file_info['name'] = basename($file_path);
  485. //call the normal import_package function
  486. return $this->import_package($file_info,$current_dir);
  487. }
  488. /**
  489. * Imports a zip file into the Dokeos structure
  490. * @param string Zip file info as given by $_FILES['userFile']
  491. * @return string Absolute path to the imsmanifest.xml file or empty string on error
  492. */
  493. function import_package($zip_file_info,$current_dir = '')
  494. {
  495. if($this->debug>0){error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method',0);}
  496. $maxFilledSpace = 1000000000;
  497. $zip_file_path = $zip_file_info['tmp_name'];
  498. $zip_file_name = $zip_file_info['name'];
  499. if($this->debug>1){error_log('New LP - import_package() - zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name,0);}
  500. $course_rel_dir = api_get_course_path().'/scorm'; //scorm dir web path starting from /courses
  501. $course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; //absolute system path for this course
  502. $current_dir = replace_dangerous_char(trim($current_dir),'strict'); //current dir we are in, inside scorm/
  503. if($this->debug>1){error_log('New LP - import_package() - current_dir = '.$current_dir,0);}
  504. //$uploaded_filename = $_FILES['userFile']['name'];
  505. //get name of the zip file without the extension
  506. if($this->debug>1){error_log('New LP - Received zip file name: '.$zip_file_path,0);}
  507. $file_info = pathinfo($zip_file_name);
  508. $filename = $file_info['basename'];
  509. $extension = $file_info['extension'];
  510. $file_base_name = str_replace('.'.$extension,'',$filename); //filename without its extension
  511. $this->zipname = $file_base_name; //save for later in case we don't have a title
  512. if($this->debug>1){error_log("New LP - base file name is : ".$file_base_name,0);}
  513. $new_dir = replace_dangerous_char(trim($file_base_name),'strict');
  514. $this->subdir = $new_dir;
  515. if($this->debug>1){error_log("New LP - subdir is first set to : ".$this->subdir,0);}
  516. $zipFile = new pclZip($zip_file_path);
  517. // Check the zip content (real size and file extension)
  518. $zipContentArray = $zipFile->listContent();
  519. $package_type='';
  520. $at_root = false;
  521. $manifest = '';
  522. $manifest_list = array();
  523. //the following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?)
  524. foreach($zipContentArray as $thisContent)
  525. {
  526. //error_log('Looking at '.$thisContent['filename'],0);
  527. if ( preg_match('~.(php.*|phtml)$~i', $thisContent['filename']) )
  528. {
  529. $this->set_error_msg("File $file contains a PHP script");
  530. //return api_failure::set_failure('php_file_in_zip_file');
  531. }
  532. elseif(stristr($thisContent['filename'],'imsmanifest.xml'))
  533. {
  534. //error_log('Found imsmanifest at '.$thisContent['filename'],0);
  535. if($thisContent['filename'] == basename($thisContent['filename'])){
  536. $at_root = true;
  537. }else{
  538. //$this->subdir .= '/'.dirname($thisContent['filename']);
  539. if($this->debug>2){error_log("New LP - subdir is now ".$this->subdir,0);}
  540. }
  541. $package_type = 'scorm';
  542. $manifest_list[] = $thisContent['filename'];
  543. $manifest = $thisContent['filename']; //just the relative directory inside scorm/
  544. }
  545. else
  546. {
  547. //do nothing, if it has not been set as scorm somewhere else, it stays as '' default
  548. }
  549. $realFileSize += $thisContent['size'];
  550. }
  551. //now get the shortest path (basically, the imsmanifest that is the closest to the root)
  552. $shortest_path = $manifest_list[0];
  553. $slash_count = substr_count($shortest_path,'/');
  554. foreach($manifest_list as $manifest_path){
  555. $tmp_slash_count = substr_count($manifest_path,'/');
  556. if($tmp_slash_count<$slash_count){
  557. $shortest_path = $manifest_path;
  558. $slash_count = $tmp_slash_count;
  559. }
  560. }
  561. $this->subdir .= '/'.dirname($shortest_path); //do not concatenate because already done above
  562. $manifest = $shortest_path;
  563. if($this->debug>1){error_log('New LP - Package type is now '.$package_type,0);}
  564. if($package_type== '')
  565. // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
  566. {
  567. return api_failure::set_failure('not_scorm_content');
  568. }
  569. if (! enough_size($realFileSize, $course_sys_dir, $maxFilledSpace) )
  570. {
  571. return api_failure::set_failure('not_enough_space');
  572. }
  573. // it happens on Linux that $new_dir sometimes doesn't start with '/'
  574. if($new_dir[0] != '/')
  575. {
  576. $new_dir='/'.$new_dir;
  577. }
  578. if($new_dir[strlen($new_dir)-1] == '/')
  579. {
  580. $new_dir=substr($new_dir,0,-1);
  581. }
  582. /*
  583. --------------------------------------
  584. Uncompressing phase
  585. --------------------------------------
  586. */
  587. /*
  588. We need to process each individual file in the zip archive to
  589. - add it to the database
  590. - parse & change relative html links
  591. - make sure the filenames are secure (filter funny characters or php extensions)
  592. */
  593. if(is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir))
  594. {
  595. // PHP method - slower...
  596. if($this->debug>=1){error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir,0);}
  597. $saved_dir = getcwd();
  598. chdir($course_sys_dir.$new_dir);
  599. $unzippingState = $zipFile->extract();
  600. for($j=0;$j<count($unzippingState);$j++)
  601. {
  602. $state=$unzippingState[$j];
  603. //TODO fix relative links in html files (?)
  604. $extension = strrchr($state["stored_filename"], ".");
  605. if($this->debug>=1){error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'],0);}
  606. }
  607. if(!empty($new_dir))
  608. {
  609. $new_dir = $new_dir.'/';
  610. }
  611. //rename files, for example with \\ in it
  612. if($dir=@opendir($course_sys_dir.$new_dir))
  613. {
  614. if($this->debug==1){error_log('New LP - Opened dir '.$course_sys_dir.$new_dir,0);}
  615. while($file=readdir($dir))
  616. {
  617. if($file != '.' && $file != '..')
  618. {
  619. $filetype="file";
  620. if(is_dir($course_sys_dir.$new_dir.$file)) $filetype="folder";
  621. //TODO RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
  622. //$safe_file=replace_dangerous_char($file,'strict');
  623. $find_str = array('\\','.php','.phtml');
  624. $repl_str = array('/', '.txt','.txt');
  625. $safe_file = str_replace($find_str,$repl_str,$file);
  626. if($safe_file != $file){
  627. //@rename($course_sys_dir.$new_dir,$course_sys_dir.'/'.$safe_file);
  628. $mydir = dirname($course_sys_dir.$new_dir.$safe_file);
  629. if(!is_dir($mydir)){
  630. $mysubdirs = split('/',$mydir);
  631. $mybasedir = '/';
  632. foreach($mysubdirs as $mysubdir){
  633. if(!empty($mysubdir)){
  634. $mybasedir = $mybasedir.$mysubdir.'/';
  635. if(!is_dir($mybasedir)){
  636. @mkdir($mybasedir);
  637. if($this->debug==1){error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.',0);}
  638. }
  639. }
  640. }
  641. }
  642. @rename($course_sys_dir.$new_dir.$file,$course_sys_dir.$new_dir.$safe_file);
  643. if($this->debug==1){error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file,0);}
  644. }
  645. //set_default_settings($course_sys_dir,$safe_file,$filetype);
  646. }
  647. }
  648. closedir($dir);
  649. chdir($saved_dir);
  650. $perm = api_get_setting('permissions_for_new_directories');
  651. $perm = octdec(!empty($perm)?$perm:'0770');
  652. api_chmod_R($course_sys_dir.$new_dir , $perm);
  653. }
  654. }else{
  655. return '';
  656. }
  657. return $course_sys_dir.$new_dir.$manifest;
  658. }
  659. /**
  660. * Sets the proximity setting in the database
  661. * @param string Proximity setting
  662. */
  663. function set_proximity($proxy=''){
  664. if($this->debug>0){error_log('In scorm::set_proximity('.$proxy.') method',0);}
  665. $lp = $this->get_id();
  666. if($lp!=0){
  667. $tbl_lp = Database::get_course_table('lp');
  668. $sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE id = ".$lp;
  669. $res = api_sql_query($sql);
  670. return $res;
  671. }else{
  672. return false;
  673. }
  674. }
  675. /**
  676. * Sets the theme setting in the database
  677. * @param string theme setting
  678. */
  679. function set_theme($theme=''){
  680. if($this->debug>0){error_log('In scorm::set_theme('.$theme.') method',0);}
  681. $lp = $this->get_id();
  682. if($lp!=0){
  683. $tbl_lp = Database::get_course_table('lp');
  684. $sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE id = ".$lp;
  685. $res = api_sql_query($sql);
  686. return $res;
  687. }else{
  688. return false;
  689. }
  690. }
  691. /**
  692. * Sets the content maker setting in the database
  693. * @param string Proximity setting
  694. */
  695. function set_maker($maker=''){
  696. if($this->debug>0){error_log('In scorm::set_maker method('.$maker.')',0);}
  697. $lp = $this->get_id();
  698. if($lp!=0){
  699. $tbl_lp = Database::get_course_table('lp');
  700. $sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE id = ".$lp;
  701. $res = api_sql_query($sql);
  702. return $res;
  703. }else{
  704. return false;
  705. }
  706. }
  707. /**
  708. * Exports the current SCORM object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
  709. * @param integer Learnpath ID (optional, taken from object context if not defined)
  710. */
  711. function export_zip($lp_id=null){
  712. if($this->debug>0){error_log('In scorm::export_zip method('.$lp_id.')',0);}
  713. if(empty($lp_id)){
  714. if(!is_object($this))
  715. {
  716. return false;
  717. }
  718. else{
  719. $id = $this->get_id();
  720. if(empty($id)){
  721. return false;
  722. }
  723. else{
  724. $lp_id = $this->get_id();
  725. }
  726. }
  727. }
  728. //error_log('New LP - in export_zip()',0);
  729. //zip everything that is in the corresponding scorm dir
  730. //write the zip file somewhere (might be too big to return)
  731. require_once (api_get_path(LIBRARY_PATH)."fileUpload.lib.php");
  732. require_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
  733. require_once (api_get_path(LIBRARY_PATH)."document.lib.php");
  734. require_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
  735. require_once ("learnpath_functions.inc.php");
  736. $tbl_lp = Database::get_course_table('lp');
  737. $_course = Database::get_course_info(api_get_course_id());
  738. $sql = "SELECT * FROM $tbl_lp WHERE id=".$lp_id;
  739. $result = api_sql_query($sql, __FILE__, __LINE__);
  740. $row = mysql_fetch_array($result);
  741. $LPname = $row['path'];
  742. $list = split('/',$LPname);
  743. $LPnamesafe = $list[0];
  744. //$zipfoldername = '/tmp';
  745. //$zipfoldername = '../../courses/'.$_course['directory']."/temp/".$LPnamesafe;
  746. $zipfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/temp/".$LPnamesafe;
  747. $scormfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/scorm/".$LPnamesafe;
  748. $zipfilename = $zipfoldername."/".$LPnamesafe.".zip";
  749. //Get a temporary dir for creating the zip file
  750. //error_log('New LP - cleaning dir '.$zipfoldername,0);
  751. deldir($zipfoldername); //make sure the temp dir is cleared
  752. $res = mkdir($zipfoldername);
  753. //error_log('New LP - made dir '.$zipfoldername,0);
  754. //create zipfile of given directory
  755. $zip_folder = new PclZip($zipfilename);
  756. $zip_folder->create($scormfoldername.'/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername.'/');
  757. //$zipfilename = '/var/www/dokeos-comp/courses/TEST2/scorm/example_document.html';
  758. //this file sending implies removing the default mime-type from php.ini
  759. //DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.".zip");
  760. DocumentManager :: file_send_for_download($zipfilename, true);
  761. // Delete the temporary zip file and directory in fileManage.lib.php
  762. my_delete($zipfilename);
  763. my_delete($zipfoldername);
  764. return true;
  765. }
  766. /**
  767. * Gets a resource's path if available, otherwise return empty string
  768. * @param string Resource ID as used in resource array
  769. * @return string The resource's path as declared in imsmanifest.xml
  770. */
  771. function get_res_path($id){
  772. if($this->debug>0){error_log('In scorm::get_res_path('.$id.') method',0);}
  773. $path = '';
  774. if(isset($this->resources[$id])){
  775. $oRes =& $this->resources[$id];
  776. $path = @$oRes->get_path();
  777. }
  778. return $path;
  779. }
  780. /**
  781. * Gets a resource's type if available, otherwise return empty string
  782. * @param string Resource ID as used in resource array
  783. * @return string The resource's type as declared in imsmanifest.xml
  784. */
  785. function get_res_type($id){
  786. if($this->debug>0){error_log('In scorm::get_res_type('.$id.') method',0);}
  787. $type = '';
  788. if(isset($this->resources[$id])){
  789. $oRes =& $this->resources[$id];
  790. $temptype = $oRes->get_scorm_type();
  791. if(!empty($temptype)){
  792. $type = $temptype;
  793. }
  794. }
  795. return $type;
  796. }
  797. /**
  798. * Gets the default organisation's title
  799. * @return string The organization's title
  800. */
  801. function get_title(){
  802. if($this->debug>0){error_log('In scorm::get_title() method',0);}
  803. $title = '';
  804. if(isset($this->manifest['organizations']['default'])){
  805. $title = $this->organizations[$this->manifest['organizations']['default']]->get_name();
  806. }elseif(count($this->organizations)==1){
  807. //this will only get one title but so we don't need to know the index
  808. foreach($this->organizations as $id => $value){
  809. $title = $this->organizations[$id]->get_name();
  810. break;
  811. }
  812. }
  813. return $title;
  814. }
  815. /**
  816. * //TODO @TODO implement this function to restore items data from an imsmanifest,
  817. * updating the existing table... This will prove very useful in case initial data
  818. * from imsmanifest were not imported well enough
  819. * @param string course Code
  820. * @param string LP ID (in database)
  821. * @param string Manifest file path (optional if lp_id defined)
  822. * @return integer New LP ID or false on failure
  823. * TODO @TODO Implement imsmanifest_path parameter
  824. */
  825. function reimport_manifest($course,$lp_id=null,$imsmanifest_path=''){
  826. if($this->debug>0){error_log('In scorm::reimport_manifest() method',0);}
  827. global $_course;
  828. //RECOVERING PATH FROM DB
  829. $main_table = Database::get_main_table(TABLE_MAIN_COURSE);
  830. //$course = Database::escape_string($course);
  831. $course = $this->escape_string($course);
  832. $sql = "SELECT * FROM $main_table WHERE code = '$course'";
  833. if($this->debug>2){error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying course: '.$sql,0);}
  834. //$res = Database::query($sql);
  835. $res = api_sql_query($sql);
  836. if(Database::num_rows($res)>0)
  837. {
  838. $this->cc = $course;
  839. }
  840. else
  841. {
  842. $this->error = 'Course code does not exist in database ('.$sql.')';
  843. return false;
  844. }
  845. //TODO make it flexible to use any course_code (still using env course code here)
  846. //$lp_table = Database::get_course_table(LEARNPATH_TABLE);
  847. $lp_table = Database::get_course_table('lp');
  848. //$id = Database::escape_integer($id);
  849. $lp_id = $this->escape_string($lp_id);
  850. $sql = "SELECT * FROM $lp_table WHERE id = '$lp_id'";
  851. if($this->debug>2){error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying lp: '.$sql,0);}
  852. //$res = Database::query($sql);
  853. $res = api_sql_query($sql);
  854. if(Database::num_rows($res)>0)
  855. {
  856. $this->lp_id = $lp_id;
  857. $row = Database::fetch_array($res);
  858. $this->type = $row['lp_type'];
  859. $this->name = stripslashes($row['name']);
  860. $this->encoding = $row['default_encoding'];
  861. $this->proximity = $row['content_local'];
  862. $this->maker = $row['content_maker'];
  863. $this->prevent_reinit = $row['prevent_reinit'];
  864. $this->license = $row['content_license'];
  865. $this->scorm_debug = $row['debug'];
  866. $this->js_lib = $row['js_lib'];
  867. $this->path = $row['path'];
  868. if($this->type == 2){
  869. if($row['force_commit'] == 1){
  870. $this->force_commit = true;
  871. }
  872. }
  873. $this->mode = $row['default_view_mod'];
  874. $this->subdir = $row['path'];
  875. }
  876. //parse the manifest (it is already in this lp's details)
  877. $manifest_file = api_get_path('SYS_COURSE_PATH').$_course['directory'].'/scorm/'.$this->subdir.'/imsmanifest.xml';
  878. if($this->subdir == ''){
  879. $manifest_file = api_get_path('SYS_COURSE_PATH').$_course['directory'].'/scorm/imsmanifest.xml';
  880. }
  881. echo $manifest_file;
  882. if(is_file($manifest_file) && is_readable($manifest_file)){
  883. //re-parse the manifest file
  884. if($this->debug>1){error_log('New LP - In scorm::reimport_manifest() - Parsing manifest '.$manifest_file,0);}
  885. $manifest = $this->parse_manifest($manifest_file);
  886. //import new LP in DB (ignore the current one)
  887. if($this->debug>1){error_log('New LP - In scorm::reimport_manifest() - Importing manifest '.$manifest_file,0);}
  888. $this->import_manifest(api_get_course_id());
  889. }else{
  890. if($this->debug>0){error_log('New LP - In scorm::reimport_manifest() - Could not find manifest file at '.$manifest_file,0);}
  891. }
  892. return false;
  893. }
  894. }
  895. ?>