Moved scripts in "docs" one level up into root folder. In addition, removed "docs...
[atutor.git] / mods / _core / imscp / ims_import.php
1 <?php
2 /************************************************************************/
3 /* ATutor                                                               */
4 /************************************************************************/
5 /* Copyright (c) 2002 - 2009                                            */
6 /* Inclusive Design Institute                                           */
7 /*                                                                      */
8 /* This program is free software. You can redistribute it and/or        */
9 /* modify it under the terms of the GNU General Public License          */
10 /* as published by the Free Software Foundation.                        */
11 /************************************************************************/
12 // $Id: ims_import.php 10319 2010-10-08 20:43:03Z hwong $
13 define('AT_INCLUDE_PATH', '../../../include/');
14 require(AT_INCLUDE_PATH.'vitals.inc.php');
15
16 require_once(AT_INCLUDE_PATH.'../mods/_core/file_manager/filemanager.inc.php'); /* for clr_dir() and preImportCallBack and dirsize() */
17 require(AT_INCLUDE_PATH.'classes/pclzip.lib.php');
18 require(AT_INCLUDE_PATH.'../mods/_core/imsqti/lib/qti.inc.php'); 
19 require(AT_INCLUDE_PATH.'../mods/_core/imsqti/classes/QTIImport.class.php');
20 require(AT_INCLUDE_PATH.'../mods/_core/imsafa/classes/A4aImport.class.php');
21 require(AT_INCLUDE_PATH.'../mods/_core/imscp/ns.inc.php');      //namespace, no longer needs, delete it after it's stable.
22 require(AT_INCLUDE_PATH.'../mods/_core/imscc/classes/WeblinksParser.class.php');
23 require(AT_INCLUDE_PATH.'../mods/_core/imscc/classes/DiscussionToolsParser.class.php');
24 require(AT_INCLUDE_PATH.'../mods/_core/imscc/classes/DiscussionToolsImport.class.php');
25
26
27 /* make sure we own this course that we're exporting */
28 authenticate(AT_PRIV_CONTENT);
29
30 /* to avoid timing out on large files */
31 @set_time_limit(0);
32 $_SESSION['done'] = 1;
33
34 $html_head_tags = array("style", "script", "link");
35
36 $package_base_path = '';
37 $package_real_base_path = '';   //the path to save the contents
38 $all_package_base_path = array();
39 $xml_base_path = '';
40 $element_path = array();
41 $imported_glossary = array();
42 $character_data = '';
43 $test_message = '';
44 $test_title = '';
45 $content_type = '';
46 $skip_ims_validation = false;
47 $added_dt = array();    //the mapping of discussion tools that are added
48 $avail_dt = array();    //list of discussion tools that have not been handled
49
50 /*
51  * return the error messages represented by the given array 
52  * @author      Mike A.
53  * @ref         http://ca3.php.net/manual/en/domdocument.schemavalidate.php
54  */
55 function libxml_display_error($error)
56 {
57     $return = "<br/>\n";
58     switch ($error->level) {
59         case LIBXML_ERR_WARNING:
60             $return .= "<b>Warning $error->code</b>: ";
61             break;
62         case LIBXML_ERR_ERROR:
63             $return .= "<b>Error $error->code</b>: ";
64             break;
65         case LIBXML_ERR_FATAL:
66             $return .= "<b>Fatal Error $error->code</b>: ";
67             break;
68     }
69     $return .= trim($error->message);
70     if ($error->file) {
71         $return .=    " in <b>$error->file</b>";
72     }
73     $return .= " on line <b>$error->line</b>\n";
74
75     return $return;
76 }
77
78 /**
79  * Validate all the XML in the package, including checking XSDs, missing data.
80  * @param       string          the path of the directory that contains all the package files
81  * @return      boolean         true if every file exists in the manifest, false if any is missing.
82  */
83 function checkResources($import_path){
84         global $items, $msg, $skip_ims_validation, $avail_dt;
85
86         if (!is_dir($import_path)){
87                 return;
88         }
89
90         //if the package has access for all content, skip validation for now. 
91         //todo: import the XSD into our validator
92         if ($skip_ims_validation){
93                 return true;
94         }
95
96         //generate a file tree
97         $data = rscandir($import_path);
98
99         //check if every file is presented in the manifest
100         foreach($data as $filepath){
101                 $filepath = substr($filepath, strlen($import_path));
102
103                 //validate xml via its xsd/dtds
104                 if (preg_match('/(.*)\.xml/', $filepath)){
105                         libxml_use_internal_errors(true);
106                         $dom = new DOMDocument();
107                         $dom->load(realpath($import_path.$filepath));
108                         if (!@$dom->schemaValidate('main.xsd')){
109                                 $errors = libxml_get_errors();
110                                 foreach ($errors as $error) {
111                                         //suppress warnings
112                                         if ($error->level==LIBXML_ERR_WARNING){
113                                                 continue;
114                                         }
115                                         $msg->addError(array('IMPORT_CARTRIDGE_FAILED', libxml_display_error($error)));
116                                 }
117                                 libxml_clear_errors();
118                         }
119                         //if this is the manifest file, we do not have to check for its existance.
120 //                      if (preg_match('/(.*)imsmanifest\.xml/', $filepath)){
121 //                              continue;
122 //                      }
123                 }
124         }
125
126         //Create an array that mimics the structure of the data array, based on the xml items
127         $filearray = array();
128         foreach($items as $name=>$fileinfo){
129                 if(isset($fileinfo['file']) && is_array($fileinfo['file']) && !empty($fileinfo['file'])){
130                         foreach($fileinfo['file'] as $fn){
131                                 if (!in_array(realpath($import_path.$fn), $filearray)){
132                                         //if url, skip
133                                         if (preg_match('/^http[s]?\:/', $fn) == 0){
134                                                 $filearray[] = realpath($import_path. $fn);
135                                         }                                       
136                                 }
137                         }
138                 }
139
140                 //validate the xml by its schema
141                 if (preg_match('/imsqti\_(.*)/', $fileinfo['type'])){
142                         $qti = new QTIParser($fileinfo['type']);
143                         $xml_content = @file_get_contents($import_path . $fileinfo['href']);
144                         $qti->parse($xml_content); //will add error to $msg if failed                   
145                 } 
146
147                 //add all dependent discussion tools to a list
148                 if(isset($fileinfo['dependency']) && !empty($fileinfo['dependency'])){
149                         $avail_dt = array_merge($avail_dt, $fileinfo['dependency']);
150                 }
151         }
152
153         //check if all files in the xml is presented in the archieve
154         $result = array_diff($filearray, $data);
155         //using sizeof because array_diff only 
156         //returns an array containing all the entries from array1  that are not present in any of the 
157         //other arrays. 
158         //Using sizeof make sure it's not a subset of array2.
159         //-1 on data because it always contain the imsmanifest.xml file
160         if (!$skip_ims_validation){
161             if (!empty($result) || sizeof($data)-1>sizeof($filearray)){
162                     $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('ims_missing_references')));
163             }
164         }
165         return true;
166 }
167
168 /*
169  * @example rscandir(dirname(__FILE__).'/'));
170  * @param string $base
171  * @param array $omit
172  * @param array $data
173  * @return array
174  */
175 function rscandir($base='', &$data=array()) {
176   $array = array_diff(scandir($base), array('.', '..')); # remove ' and .. from the array */
177   foreach($array as $value) : /* loop through the array at the level of the supplied $base */
178  
179     if (is_dir($base.$value)) : /* if this is a directory */
180 //        don't save the directory name
181 //        $data[] = $base.$value.'/'; /* add it to the $data array */
182       $data = rscandir($base.$value.'/', $data); /* then make a recursive call with the
183       current $value as the $base supplying the $data array to carry into the recursion */
184      
185     elseif (is_file($base.$value)) : /* else if the current $value is a file */
186       $data[] = realpath($base.$value); /* just add the current $value to the $data array */
187      
188     endif;
189    
190   endforeach;
191   return $data; // return the $data array
192  
193 }
194
195 /**
196  * Function to restructure the $items.  So that old import will merge the top page into its children, and
197  * create a new folder on top of it
198  */
199 function rehash($items){
200         global $order;
201         $parent_page_maps = array();    //old=>new
202         $temp_popped_items = array();
203         $rehashed_items = array();      //the reconstructed array
204         foreach($items as $id => $content){
205                 $parent_obj = $items[$content['parent_content_id']];
206                 $rehashed_items[$id] = $content;        //copy
207         //first check if this is the top folder of the archieve, we don't want the top folder, remove it.
208 /*        if (isset($content['parent_content_id']) && !isset($parent_obj) && !isset($content['type'])){
209             //if we can get into here, it means the parent_content_id of this is empty
210             //implying this is the first folder.
211             //note: it checks content[type] cause it could be a webcontent. In that case, 
212             //      we do want to keep it.  
213                         debug($content, 'hit');
214             unset($rehashed_items[$id]);
215             continue;
216         }               
217                 //then check if there exists a mapping for this item, if so, simply replace is and next.
218                 else
219 */              if (isset($parent_page_maps[$content['parent_content_id']])){
220                         $rehashed_items [$id]['parent_content_id'] = $parent_page_maps[$content['parent_content_id']];
221                         $rehashed_items [$id]['ordering']++;
222                 } 
223                 //If its parent page is a top page and have an identiferref
224                 elseif (isset($parent_obj) && isset($parent_obj['href'])){                      
225                         if (!isset($parent_obj['href'])){
226                                 //check if this top page is already a folder, if so, next.
227                                 continue;
228                         }
229                         //else, make its parent page to a folder
230                         $new_item['title'] = $parent_obj['title'];
231                         //check if this parent has been modified, if so, chnage it
232                         if (isset($parent_page_maps[$parent_obj['parent_content_id']])){
233                             $new_item['parent_content_id'] = $parent_page_maps[$parent_obj['parent_content_id']];
234                         } else {
235                         $new_item['parent_content_id'] = $parent_obj['parent_content_id'];
236             }
237                         //all ordering needs to be +1 because we are creating a new folder on top of
238                         //everything, except the first page.
239                         $new_item['ordering'] = $parent_obj['ordering'];
240                         if ($new_item['parent_content_id']!='0'){
241                                 $new_item['ordering']++;
242                         } 
243
244                 //assign this new parent folder to the pending items array
245                         $new_item_name = $content['parent_content_id'].'_FOLDER';
246                         //a not so brilliant way to append the folder in its appropriate position
247                         $reordered_hashed_items = array();  //use to store the new rehashed item with the correct item order
248                         foreach($rehashed_items as $rh_id=>$rh_content){
249                             if ($rh_id == $content['parent_content_id']){
250                                 //add the folder in before the parent subpage.
251                                 $reordered_hashed_items[$new_item_name] = $new_item;
252                             }
253                             $reordered_hashed_items[$rh_id] = $rh_content;  //clone
254                         }
255                         $rehashed_items = $reordered_hashed_items;  //replace it back
256                         unset($reordered_hashed_items);
257                         $parent_page_maps[$content['parent_content_id']] = $new_item_name;  //save this page on the hash map
258
259                         //reconstruct the parent
260                         $rehashed_items[$content['parent_content_id']]['parent_content_id'] = $parent_page_maps[$content['parent_content_id']];
261                         $rehashed_items[$content['parent_content_id']]['ordering'] = 0; //always the first one.
262
263                         //reconstruct itself
264                         $rehashed_items[$id]['parent_content_id'] = $parent_page_maps[$content['parent_content_id']];
265                         $rehashed_items[$id]['ordering']++;
266
267                 }
268         }
269         return $rehashed_items;
270 }
271
272 /**
273  * Take out the common path within all $items['new_path']. Make sure we include
274  * AccessForAll files in the array.  
275  * This allows import/export repeatedly without duplicating its path
276  * @param   array   contains the breakdown of all resources in the XML
277  */
278 function removeCommonPath($items){
279     $common_path; 
280     $quit = false;  //a flag that is set if it's not the first time being run.
281
282     $filearray = array();
283     //get all files listed in the manifest
284     foreach($items as $name=>$fileinfo){
285                 if(isset($fileinfo['file']) && is_array($fileinfo['file']) && !empty($fileinfo['file'])){
286                         foreach($fileinfo['file'] as $fn){
287                                 if (!in_array($fn, $filearray)){
288                                         if (preg_match('/^http[s]?\:/', $fn) == 0){
289                                                 $filearray[] = $fn;
290                                         }                                       
291                                 }
292                         }
293                 }
294         }
295
296     foreach($filearray as $index=>$path){
297         //hack
298         //check if this is a XML file; if so, skip through, 
299         //cause XML most likely isn't a content resource.
300         $ext = substr($path, (strrpos($path, '.')+1));
301         if($ext=='xml'){
302             continue;
303         }
304         
305         //if common path is empty, assign the first path to it.
306         if ($common_path=='' && $quit==false){
307             $common_path = $path;
308             $quit = true;   //the next time common_path is empty, quit;
309             continue;
310         }
311         //we use '/' here instead of DIRECTORY_SEPARATOR because php would
312         //actually use '\' and return the whole string. 
313         $common_array = explode('/', $common_path);
314         $path_array = explode('/', $path);
315         //convert path_array to absolute path
316         //TODO: array_search is slow, build a faster search
317         $pos=array_search('..', $path_array);
318         while($pos=array_search('..', $path_array)){
319             array_splice($path_array, $pos-1, 2);
320         }
321         $intersect_array = array_intersect($common_array, $path_array);
322         $common_path = implode('/', $intersect_array);       
323     }
324     return $common_path;
325 }
326
327
328 /** 
329  * This function will take the test accessment XML and add these to the database.
330  * @param       string  The path of the XML, without the import_path.
331  * @param       mixed   An item singleton.  Contains the info of this item, namely, the accessment details.
332  *                                      The item must be an object created by the ims class.
333  * @param       string  the import path
334  * @return      mixed   An Array that contains all the question IDs that have been imported.
335  */
336  function addQuestions($xml, $item, $import_path){
337         global $test_title;
338         $qti_import = new QTIImport($import_path);
339         $tests_xml = $import_path.$xml;
340         
341         //Mimic the array for now.
342         $test_attributes['resource']['href'] = $item['href'];
343         $test_attributes['resource']['type'] = preg_match('/imsqti_xmlv1p2/', $item['type'])==1?'imsqti_xmlv1p2':'imsqti_xmlv1p1';
344         $test_attributes['resource']['file'] = $item['file'];
345
346         //Get the XML file out and start importing them into our database.
347         //TODO: See question_import.php 287-289.
348         $qids = $qti_import->importQuestions($test_attributes);
349         $test_title = $qti_import->title;
350
351         return $qids;
352  }
353
354
355         /* called at the start of en element */
356         /* builds the $path array which is the path from the root to the current element */
357         function startElement($parser, $name, $attrs) {
358                 global $items, $path, $package_base_path, $all_package_base_path, $package_real_base_path;
359                 global $element_path, $import_path, $skip_ims_validation;
360                 global $xml_base_path, $test_message, $content_type;
361                 global $current_identifier, $msg, $ns, $ns_cp;
362
363                 //check if the xml is valid
364 /*
365                 if(isset($attrs['xsi:schemaLocation']) && $name == 'manifest'){
366                         //run the loop and check it thru the ns.inc.php
367                 } elseif ($name == 'manifest' && !isset($attrs['xsi:schemaLocation'])) {
368                         //$msg->addError('MANIFEST_NOT_WELLFORM: NO NAMESPACE');
369                         $msg->addError('IMPORT_CARTRIDGE_FAILED');
370                 } else {
371                         //error
372                 }
373                 //error if the tag names are wrong
374                 if (preg_match('/^xsi\:/', $name) >= 1){
375                         //$msg->addError('MANIFEST_NOT_WELLFORM');
376                         $msg->addError('IMPORT_CARTRIDGE_FAILED');
377                 }
378 */
379
380                 //validate namespaces
381                 if(!$skip_ims_validation && isset($attrs['xsi:schemaLocation']) && $name=='manifest'){
382                         $schema_location = array();
383                         $split_location = preg_split('/[\r\n\s]+/', trim($attrs['xsi:schemaLocation']));
384
385                         //check if the namespace is actually right, have an array or some sort in IMS class
386                         if(sizeof($split_location)%2==1){
387                                 //schema is not in the form of "The first URI reference in each pair is a namespace name,
388                                 //and the second is the location of a schema that describes that namespace."
389                                 //$msg->addError('MANIFEST_NOT_WELLFORM');
390                                 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('schema_error')));
391                         }
392
393                         //turn the xsi:schemaLocation URI into a schema that describe namespace.
394                         //name = url
395                         //http://msdn.microsoft.com/en-us/library/ms256100(VS.85).aspx
396                         //http://www.w3.org/TR/xmlschema-1/
397                         for($i=0; $i < sizeof($split_location);$i=$i+2){
398                                 /*
399                                 if (isset($ns[$split_location[$i]]) && $ns[$split_location[$i]] != $split_location[$i+1]){
400                                         //$msg->addError('MANIFEST_NOT_WELLFORM: SCHEMA');
401                                         $msg->addError('IMPORT_CARTRIDGE_FAILED');
402                                 }
403                                 */
404                                 //if the key of the namespace is not defined. Throw error.
405                                 if(!isset($ns[$split_location[$i]]) && !isset($ns_cp[$split_location[$i]])){
406                                         $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('schema_error')));
407                                 }
408                         }
409                 } else {
410                         //throw error           
411                 }
412
413                 if ($name == 'manifest' && isset($attrs['xml:base']) && $attrs['xml:base']) {
414                         $xml_base_path = $attrs['xml:base'];
415                 } else if ($name == 'file') {
416                         // check if it misses file references
417                         if(!$skip_ims_validation && (!isset($attrs['href']) || $attrs['href']=='')){
418                                 //$msg->addError('MANIFEST_NOT_WELLFORM');
419                                 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('ims_missing_references')));
420                         }
421
422                         // special case for webCT content packages that don't specify the `href` attribute 
423                         // with the `<resource>` element.
424                         // we take the `href` from the first `<file>` element.
425                         if (isset($items[$current_identifier]) && ($items[$current_identifier]['href'] == '')) {
426                                 $attrs['href'] = urldecode($attrs['href']);
427                                 $items[$current_identifier]['href'] = $attrs['href'];
428                         }
429
430                         $temp_path = pathinfo($attrs['href']);
431                         $temp_path = explode('/', $temp_path['dirname']);
432                         if (empty($package_base_path)){
433                             $package_base_path = $temp_path;
434             }
435                         if ($all_package_base_path!='' && empty($all_package_base_path)){
436                                 $all_package_base_path = $temp_path;
437                         }
438                         $package_base_path = array_intersect_assoc($package_base_path, $temp_path);
439                         
440                         //calculate the depths of relative paths
441                         if ($all_package_base_path!=''){
442                                 $no_relative_temp_path = $temp_path;
443                                 foreach($no_relative_temp_path as $path_node){
444                                         if ($path_node=='..'){
445                                                 array_pop($no_relative_temp_path);
446                                                 array_pop($no_relative_temp_path); //not a typo, have to pop twice, both itself('..'), and the one before.
447                                         }
448                                 }
449                                 $all_package_base_path = array_intersect_assoc($all_package_base_path, $no_relative_temp_path);
450                                 if (empty($all_package_base_path)){
451                                         $all_package_base_path = '';    //unset it, there is no intersection.
452                                 }
453                         }
454
455                         //save the actual content base path
456                         if (in_array('..', $temp_path)){
457                                 $sizeofrp = array_count_values($temp_path);
458                         }
459
460                         //for IMSCC, assume that all resources lies in the same folder, except styles.css
461                         if ($items[$current_identifier]['type']=='webcontent' || $items[$current_identifier]['type']=='imsdt_xmlv1p0'){
462                                 //find the intersection of each item's related files, then that intersection is the content_path
463                                 if (isset($items[$current_identifier]['file'])){
464                                         foreach ($items[$current_identifier]['file'] as $resource_path){
465                                                 $temp_path = pathinfo($resource_path);
466                                                 $temp_path = explode('/', $temp_path['dirname']);
467                                                 $package_base_path = array_intersect_assoc($package_base_path, $temp_path);                                             
468                                         }
469                                 }
470                         }
471
472                         //real content path
473                         if($sizeofrp['..'] > 0 && !empty($all_package_base_path)){
474                                 for ($i=0; $i<$sizeofrp['..']; $i++){
475                                         array_pop($all_package_base_path);
476                                 }
477                         }
478                         
479                         if (count($package_base_path) > 0) {
480                                 $items[$current_identifier]['new_path'] = implode('/', $package_base_path);
481                         }
482                                 
483 /* 
484  * @harris, reworked the package_base_path 
485                                 if ($package_base_path=="") {
486                                         $package_base_path = $temp_path;
487                                 } 
488                                 elseif (is_array($package_base_path) && $content_type != 'IMS Common Cartridge') {
489                                         //if this is a content package, we want only intersection
490                                         $package_base_path = array_intersect($package_base_path, $temp_path);
491                                         $temp_path = $package_base_path;
492                                 }
493                                 //added these 2 lines in so that pictures would load.  making the elseif above redundant.
494                                 //if there is a bug for pictures not load, then it's the next 2 lines.
495                                 $package_base_path = array_intersect($package_base_path, $temp_path);
496                                 $temp_path = $package_base_path;
497                         }
498                         $items[$current_identifier]['new_path'] = implode('/', $temp_path);     
499 */
500                         if (    isset($_POST['allow_test_import']) && isset($items[$current_identifier]) 
501                                                 && preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $attrs['href'])) {
502                                 $items[$current_identifier]['tests'][] = $attrs['href'];
503                         } 
504                         if (    isset($_POST['allow_a4a_import']) && isset($items[$current_identifier])) {
505                                 $items[$current_identifier]['a4a_import_enabled'] = true;
506                         }
507                 } else if (($name == 'item') && ($attrs['identifierref'] != '')) {
508                         $path[] = $attrs['identifierref'];
509                 } else if (($name == 'item') && ($attrs['identifier'])) {
510                         $path[] = $attrs['identifier'];
511 //              } else if (($name == 'resource') && is_array($items[$attrs['identifier']]))  {
512                 } else if (($name == 'resource')) {
513                         $current_identifier = $attrs['identifier'];
514                         $items[$current_identifier]['type'] = $attrs['type'];
515                         if ($attrs['href']) {
516                                 $attrs['href'] = urldecode($attrs['href']);
517
518                                 $items[$attrs['identifier']]['href'] = $attrs['href'];
519
520                                 // href points to a remote url
521                                 if (preg_match('/^http.*:\/\//', trim($attrs['href']))) {
522                                         $items[$attrs['identifier']]['new_path'] = '';
523                                 } else // href points to local file
524                                 {
525                                         $temp_path = pathinfo($attrs['href']);
526                                         $temp_path = explode('/', $temp_path['dirname']);
527 //                                      if (empty($package_base_path)) {
528                                                 $package_base_path = $temp_path;
529 //                                      } 
530 //                                      else {
531 //                                              $package_base_path = array_intersect($package_base_path, $temp_path);
532 //                                      }
533                                         $items[$attrs['identifier']]['new_path'] = implode('/', $temp_path);
534                                 }
535                         }
536
537                         //if test custom message has not been saved
538 //                      if (!isset($items[$current_identifier]['test_message'])){
539 //                              $items[$current_identifier]['test_message'] = $test_message;
540 //                      }
541                 } else if ($name=='dependency' && $attrs['identifierref']!='') {
542                         //if there is a dependency, attach it to the item array['file']
543                         $items[$current_identifier]['dependency'][] = $attrs['identifierref'];
544                 }
545                 if (($name == 'item') && ($attrs['parameters'] != '')) {
546                         $items[$attrs['identifierref']]['test_message'] = $attrs['parameters'];
547                 }
548                 if ($name=='file'){
549                         if(!isset($items[$current_identifier]) && $attrs['href']!=''){
550                                 $items[$current_identifier]['href']      = $attrs['href'];
551                         }
552                         if (substr($attrs['href'], 0, 7) == 'http://' || substr($attrs['href'], 0, 8) == 'https://' || file_exists($import_path.$attrs['href']) || $skip_ims_validation){
553                                 $items[$current_identifier]['file'][] = $attrs['href'];
554                         } else {
555                                 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT(array('ims_files_missing', $attrs['href']))));
556                         }
557                 }               
558                 if ($name=='cc:authorizations'){
559                         //don't have authorization setup.
560                         //$msg->addError('');
561                         $msg->addError('IMS_AUTHORIZATION_NOT_SUPPORT');
562                 }
563                 array_push($element_path, $name);
564         }
565
566         /* called when an element ends */
567         /* removed the current element from the $path */
568         function endElement($parser, $name) {
569                 global $path, $element_path, $my_data, $items;
570                 global $current_identifier, $skip_ims_validation;
571                 global $msg, $content_type;             
572                 static $resource_num = 0;
573                 
574                 if ($name == 'item') {
575                         array_pop($path);
576                 } 
577
578                 //check if this is a test import
579                 if ($name == 'schema'){
580                         if (trim($my_data)=='IMS Question and Test Interoperability'){
581                                 $msg->addError('IMPORT_FAILED');
582                         } 
583                         $content_type = trim($my_data);
584                 }
585
586                 //Handles A4a
587                 if ($current_identifier != ''){
588                         $my_data = trim($my_data);
589                         $last_file_name = $items[$current_identifier]['file'][(sizeof($items[$current_identifier]['file']))-1];
590
591                         if ($name=='originalAccessMode'){                               
592                                 if (in_array('accessModeStatement', $element_path)){
593                                         $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['access_stmt_originalAccessMode'] = $my_data;
594                                 } elseif (in_array('adaptationStatement', $element_path)){
595                                         $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['adapt_stmt_originalAccessMode'] = $my_data;
596                                 }
597                         } elseif (($name=='language') && in_array('accessModeStatement', $element_path)){
598                                 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['language'][] = $my_data;
599                         } elseif ($name=='hasAdaptation') {
600                                 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['hasAdaptation'][] = $my_data;
601                         } elseif ($name=='isAdaptationOf'){
602                                 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['isAdaptationOf'][] = $my_data;
603                         } elseif ($name=='accessForAllResource'){
604                                 /* the head node of accessForAll Metadata, if this exists in the manifest. Skip XSD validation,
605                                  * because A4a doesn't have a xsd yet.  Our access for all is based on ISO which will not pass 
606                                  * the current IMS validation.  
607                                  * Also, since ATutor is the only one (as of Oct 21, 2009) that exports IMS with access for all
608                                  * content, we can almost assume that any ims access for all content is by us, and is valid. 
609                                  */
610                                 $skip_ims_validation = true;
611                                 $resource_num++;
612                         } elseif($name=='file'){
613                                 $resource_num = 0;      //reset resournce number to 0 when the file tags ends
614                         }
615                 }
616
617                 if ($element_path === array('manifest', 'metadata', 'imsmd:lom', 'imsmd:general', 'imsmd:title', 'imsmd:langstring')) {
618                         global $package_base_name;
619                         $package_base_name = trim($my_data);
620                 }
621
622                 array_pop($element_path);
623                 $my_data = '';
624         }
625
626         /* called when there is character data within elements */
627         /* constructs the $items array using the last entry in $path as the parent element */
628         function characterData($parser, $data){
629                 global $path, $items, $order, $my_data, $element_path;
630                 global $current_identifier;
631
632                 $str_trimmed_data = trim($data);
633                                 
634                 if (!empty($str_trimmed_data)) {
635                         $size = count($path);
636                         if ($size > 0) {
637                                 $current_item_id = $path[$size-1];
638                                 if ($size > 1) {
639                                         $parent_item_id = $path[$size-2];
640                                 } else {
641                                         $parent_item_id = 0;
642                                 }
643
644                                 if (isset($items[$current_item_id]['parent_content_id']) && is_array($items[$current_item_id])) {
645
646                                         /* this item already exists, append the title           */
647                                         /* this fixes {\n, \t, `, &} characters in elements */
648
649                                         /* horible kludge to fix the <ns2:objectiveDesc xmlns:ns2="http://www.utoronto.ca/atrc/tile/xsd/tile_objective"> */
650                                         /* from TILE */
651                                         if (in_array('accessForAllResource', $element_path)){
652                                                 //skip this tag
653                                         } elseif ($element_path[count($element_path)-1] != 'ns1:objectiveDesc') {
654                                                 $items[$current_item_id]['title'] .= $data;
655                                         }
656         
657                                 } else {
658                                         $order[$parent_item_id] ++;
659                                         $item_tmpl = array(     'title'                         => $data,
660                                                                                 'parent_content_id' => $parent_item_id,
661                                                                                 'ordering'                      => $order[$parent_item_id]-1);
662                                         //append other array values if it exists
663                                         if (is_array($items[$current_item_id])){
664                                                 $items[$current_item_id] = array_merge($items[$current_item_id], $item_tmpl);
665                                         } else {
666                                                 $items[$current_item_id] = $item_tmpl;
667                                         }
668                                 }
669                         }
670                 }
671
672                 $my_data .= $data;
673         }
674
675         /* glossary parser: */
676         function glossaryStartElement($parser, $name, $attrs) {
677                 global $element_path;
678
679                 array_push($element_path, $name);
680         }
681
682         /* called when an element ends */
683         /* removed the current element from the $path */
684         function glossaryEndElement($parser, $name) {
685                 global $element_path, $my_data, $imported_glossary;
686                 static $current_term;
687
688                 if ($element_path === array('glossary', 'item', 'term') || 
689                         $element_path === array('glossary:glossary', 'item', 'term')) {
690                         $current_term = $my_data;
691
692                 } else if ($element_path === array('glossary', 'item', 'definition') || 
693                                    $element_path === array('glossary:glossary', 'item', 'definition')) {
694                         $imported_glossary[trim($current_term)] = trim($my_data);
695                 }
696
697                 array_pop($element_path);
698                 $my_data = '';
699         }
700
701         function glossaryCharacterData($parser, $data){
702                 global $my_data;
703
704                 $my_data .= $data;
705         }
706
707 if (!isset($_POST['submit']) && !isset($_POST['cancel'])) {
708         /* just a catch all */
709         
710         $errors = array('FILE_MAX_SIZE', ini_get('post_max_size'));
711         $msg->addError($errors);
712
713         header('Location: ./index.php');
714         exit;
715 } else if (isset($_POST['cancel'])) {
716         $msg->addFeedback('IMPORT_CANCELLED');
717
718         header('Location: ../content/index.php');
719         exit;
720 }
721
722 $cid = intval($_POST['cid']);
723
724 //If user chooses to ignore validation.
725 if(isset($_POST['ignore_validation']) && $_POST['ignore_validation']==1) {
726         $skip_ims_validation = true;
727 }
728
729 if (isset($_POST['url']) && ($_POST['url'] != 'http://') ) {
730         if ($content = @file_get_contents($_POST['url'])) {
731                 // save file to /content/
732                 $filename = substr(time(), -6). '.zip';
733                 $full_filename = AT_CONTENT_DIR . $filename;
734
735                 if (!$fp = fopen($full_filename, 'w+b')) {
736                         echo "Cannot open file ($filename)";
737                         exit;
738                 }
739
740                 if (fwrite($fp, $content, strlen($content) ) === FALSE) {
741                         echo "Cannot write to file ($filename)";
742                         exit;
743                 }
744                 fclose($fp);
745         }       
746         $_FILES['file']['name']     = $filename;
747         $_FILES['file']['tmp_name'] = $full_filename;
748         $_FILES['file']['size']     = strlen($content);
749         unset($content);
750         //$url_parts = pathinfo($_POST['url']);
751         //$package_base_name_url = $url_parts['basename'];
752     $package_base_name_url = md5(time());
753 }
754 $ext = pathinfo($_FILES['file']['name']);
755 $ext = $ext['extension'];
756
757 if ($ext != 'zip') {
758         $msg->addError('IMPORTDIR_IMS_NOTVALID');
759 } else if ($_FILES['file']['error'] == 1) {
760         $errors = array('FILE_MAX_SIZE', ini_get('upload_max_filesize'));
761         $msg->addError($errors);
762 } else if ( !$_FILES['file']['name'] || (!is_uploaded_file($_FILES['file']['tmp_name']) && !$_POST['url'])) {
763         $msg->addError('FILE_NOT_SELECTED');
764 } else if ($_FILES['file']['size'] == 0) {
765         $msg->addError('IMPORTFILE_EMPTY');
766
767
768 if ($msg->containsErrors()) {
769         if (isset($_GET['tile'])) {
770                 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
771         } else {
772                 header('Location: index.php');
773         }
774         exit;
775 }
776
777 /* check if ../content/import/ exists */
778 $import_path = AT_CONTENT_DIR . 'import/';
779 $content_path = AT_CONTENT_DIR;
780
781 if (!is_dir($import_path)) {
782         if (!@mkdir($import_path, 0700)) {
783                 $msg->addError('IMPORTDIR_FAILED');
784         }
785 }
786
787 $import_path .= $_SESSION['course_id'].'/';
788 if (is_dir($import_path)) {
789         clr_dir($import_path);
790 }
791
792 if (!@mkdir($import_path, 0700)) {
793         $msg->addError('IMPORTDIR_FAILED');
794 }
795
796 if ($msg->containsErrors()) {
797         if (isset($_GET['tile'])) {
798                 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
799         } else {
800                 header('Location: index.php');
801         }
802         exit;
803 }
804
805 /* extract the entire archive into AT_COURSE_CONTENT . import/$course using the call back function to filter out php files */
806 error_reporting(0);
807 $archive = new PclZip($_FILES['file']['tmp_name']);
808 if ($archive->extract(  PCLZIP_OPT_PATH,        $import_path,
809                                                 PCLZIP_CB_PRE_EXTRACT,  'preImportCallBack') == 0) {
810         $msg->addError('IMPORT_FAILED');
811         echo 'Error : '.$archive->errorInfo(true);
812         clr_dir($import_path);
813         header('Location: index.php');
814         exit;
815 }
816 error_reporting(AT_ERROR_REPORTING);
817
818 /* get the course's max_quota */
819 $sql    = "SELECT max_quota FROM ".TABLE_PREFIX."courses WHERE course_id=$_SESSION[course_id]";
820 $result = mysql_query($sql, $db);
821 $q_row  = mysql_fetch_assoc($result);
822
823 if ($q_row['max_quota'] != AT_COURSESIZE_UNLIMITED) {
824
825         if ($q_row['max_quota'] == AT_COURSESIZE_DEFAULT) {
826                 $q_row['max_quota'] = $MaxCourseSize;
827         }
828         $totalBytes   = dirsize($import_path);
829         $course_total = dirsize(AT_CONTENT_DIR . $_SESSION['course_id'].'/');
830         $total_after  = $q_row['max_quota'] - $course_total - $totalBytes + $MaxCourseFloat;
831
832         if ($total_after < 0) {
833                 /* remove the content dir, since there's no space for it */
834                 $errors = array('NO_CONTENT_SPACE', number_format(-1*($total_after/AT_KBYTE_SIZE), 2 ) );
835                 $msg->addError($errors);
836                 
837                 clr_dir($import_path);
838
839                 if (isset($_GET['tile'])) {
840                         header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
841                 } else {
842                         header('Location: index.php');
843                 }
844                 exit;
845         }
846 }
847
848
849 $items = array(); /* all the content pages */
850 $order = array(); /* keeps track of the ordering for each content page */
851 $path  = array();  /* the hierarchy path taken in the menu to get to the current item in the manifest */
852 $dependency_files = array(); /* the file path for the dependency files */
853
854 /*
855 $items[content_id/resource_id] = array(
856                                                                         'title'
857                                                                         'real_content_id' // calculated after being inserted
858                                                                         'parent_content_id'
859                                                                         'href'
860                                                                         'ordering'
861                                                                         );
862 */
863 $ims_manifest_xml = @file_get_contents($import_path.'imsmanifest.xml');
864 //scan for manifest xml if it's not on the top level.
865 if ($ims_manifest_xml === false){
866         $data = rscandir($import_path);
867         $manifest_array = array();
868         foreach($data as $scanned_file){
869                 $scanned_file = realpath($scanned_file);
870                 //change the file string to an array
871                 $this_file_array = explode(DIRECTORY_SEPARATOR, $scanned_file);
872                 if(empty($manifest_array)){
873                         $manifest_array = $this_file_array;
874                 }
875                 $manifest_array = array_intersect_assoc($this_file_array, $manifest_array);
876
877                 if (strpos($scanned_file, 'imsmanifest')!==false){
878                         $ims_manifest_xml = @file_get_contents($scanned_file);
879                 }
880         }
881         if ($ims_manifest_xml !== false){
882                 $import_path = implode(DIRECTORY_SEPARATOR, $manifest_array) . DIRECTORY_SEPARATOR;
883         }
884 }
885
886 //if no imsmanifest.xml found in the entire package, throw error.
887 if ($ims_manifest_xml === false) {
888         $msg->addError('NO_IMSMANIFEST');
889
890         if (file_exists($import_path . 'atutor_backup_version')) {
891                 $msg->addError('NO_IMS_BACKUP');
892         }
893         clr_dir($import_path);
894
895         if (isset($_GET['tile'])) {
896                 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
897         } else {
898                 header('Location: index.php');
899         }
900         exit;
901 }
902
903 $xml_parser = xml_parser_create();
904
905 xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); /* conform to W3C specs */
906 xml_set_element_handler($xml_parser, 'startElement', 'endElement');
907 xml_set_character_data_handler($xml_parser, 'characterData');
908
909 if (!xml_parse($xml_parser, $ims_manifest_xml, true)) {
910         die(sprintf("XML error: %s at line %d",
911                                 xml_error_string(xml_get_error_code($xml_parser)),
912                                 xml_get_current_line_number($xml_parser)));
913 }
914 xml_parser_free($xml_parser);
915 /* check if the glossary terms exist */
916 $glossary_path = '';
917 if ($content_type == 'IMS Common Cartridge'){
918         $glossary_path = 'resources/GlossaryItem/';
919 //      $package_base_path = '';
920 }
921 if (file_exists($import_path . $glossary_path . 'glossary.xml')){
922         $glossary_xml = @file_get_contents($import_path.$glossary_path.'glossary.xml');
923         $element_path = array();
924         $xml_parser = xml_parser_create();
925
926         /* insert the glossary terms into the database (if they're not in there already) */
927         /* parse the glossary.xml file and insert the terms */
928         xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); /* conform to W3C specs */
929         xml_set_element_handler($xml_parser, 'glossaryStartElement', 'glossaryEndElement');
930         xml_set_character_data_handler($xml_parser, 'glossaryCharacterData');
931
932         if (!xml_parse($xml_parser, $glossary_xml, true)) {
933                 die(sprintf("XML error: %s at line %d",
934                                         xml_error_string(xml_get_error_code($xml_parser)),
935                                         xml_get_current_line_number($xml_parser)));
936         }
937         xml_parser_free($xml_parser);
938         $contains_glossary_terms = true;
939         foreach ($imported_glossary as $term => $defn) {
940                 if (!$glossary[$term]) {
941                         $sql = "INSERT INTO ".TABLE_PREFIX."glossary VALUES (NULL, $_SESSION[course_id], '$term', '$defn', 0)";
942                         mysql_query($sql, $db); 
943                 }
944         }
945 }
946
947 // Check if all the files exists in the manifest, iff it's a IMS CC package.
948 if ($content_type == 'IMS Common Cartridge') {  
949         checkResources($import_path);
950 }
951
952 // Check if there are any errors during parsing.
953 if ($msg->containsErrors()) {
954         if (isset($_GET['tile'])) {
955                 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
956         } else {
957                 header('Location: index.php');
958         }
959         exit;
960 }
961
962 /* generate a unique new package base path based on the package file name and date as needed. */
963 /* the package name will be the dir where the content for this package will be put, as a result */
964 /* the 'content_path' field in the content table will be set to this path. */
965 /* $package_base_name_url comes from the URL file name (NOT the file name of the actual file we open)*/
966 if (!$package_base_name && $package_base_name_url) {
967         $package_base_name = substr($package_base_name_url, -6);
968 } else if (!$package_base_name) {
969         $package_base_name = substr($_FILES['file']['name'], 0, -4);
970 }
971
972 $package_base_name = strtolower($package_base_name);
973 $package_base_name = str_replace(array('\'', '"', ' ', '|', '\\', '/', '<', '>', ':'), '_' , $package_base_name);
974 $package_base_name = preg_replace("/[^A-Za-z0-9._\-]/", '', $package_base_name);
975
976 if (is_dir(AT_CONTENT_DIR . $_SESSION['course_id'].'/'.$package_base_name)) {
977         $package_base_name .= '_'.date('ymdHis');
978 }
979
980 if ($package_base_path) {
981         $package_base_path = implode('/', $package_base_path);
982 } elseif (empty($package_base_path)){
983         $package_base_path = '';
984 }
985
986 if ($xml_base_path) {
987         $package_base_path = $xml_base_path . $package_base_path;
988
989         mkdir(AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$xml_base_path);
990         $package_base_name = $xml_base_path . $package_base_name;
991 }
992
993 /* get the top level content ordering offset */
994 $sql    = "SELECT MAX(ordering) AS ordering FROM ".TABLE_PREFIX."content WHERE course_id=$_SESSION[course_id] AND content_parent_id=$cid";
995 $result = mysql_query($sql, $db);
996 $row    = mysql_fetch_assoc($result);
997 $order_offset = intval($row['ordering']); /* it's nice to have a real number to deal with */
998 $lti_offset = array();  //since we don't need lti tools, the ordering needs to be subtracted
999 //reorder the items stack
1000 $common_path = removeCommonPath($items);
1001 $items = rehash($items);
1002 //debug($items);exit;
1003 foreach ($items as $item_id => $content_info) 
1004 {       
1005         //formatting field, default 1
1006         $content_formatting = 1;        //CONTENT_TYPE_CONTENT
1007
1008         //don't want to display glossary as a page
1009         if ($content_info['href']== $glossary_path . 'glossary.xml'){
1010                 continue;
1011         }
1012
1013         //if discussion tools, add it to the list of unhandled dts
1014         if ($content_info['type']=='imsdt_xmlv1p0'){
1015                 //if it will be taken care after (has dependency), then move along.
1016                 if (in_array($item_id, $avail_dt)){
1017                         $lti_offset[$content_info['parent_content_id']]++;
1018                         continue;
1019                 }
1020         }
1021
1022         //handle the special case of cc import, where there is no content association. The resource should
1023         //still be imported.
1024         if(!isset($content_info['parent_content_id'])){
1025                 //if this is a question bank 
1026                 if ($content_info['type']=="imsqti_xmlv1p2/imscc_xmlv1p0/question-bank"){
1027                         addQuestions($content_info['href'], $content_info, $import_path);
1028                 }
1029         }
1030
1031         //if it has no title, most likely it is not a page but just a normal item, skip it
1032         if (!isset($content_info['title'])){
1033                 continue;
1034         }
1035         
1036         //check dependency immediately, then handles it
1037         $head = '';
1038         if (is_array($content_info['dependency']) && !empty($content_info['dependency'])){
1039                 foreach($content_info['dependency'] as $dependency_ref){
1040                         //handle styles 
1041                         /** handled by get_html_head in vitals.inc.php
1042                         if (preg_match('/(.*)\.css$/', $items[$dependency_ref]['href'])){
1043                                 //calculate where this is based on our current base_href. 
1044                                 //assuming the dependency folders are siblings of the item
1045                                 $head = '<link rel="stylesheet" type="text/css" href="../'.$items[$dependency_ref]['href'].'" />';
1046                         }
1047                         */
1048                         //check if this is a discussion tool dependency
1049                         if ($items[$dependency_ref]['type']=='imsdt_xmlv1p0'){
1050                                 $items[$item_id]['forum'][$dependency_ref] = $items[$dependency_ref]['href'];
1051                         }
1052                         //check if this is a QTI dependency
1053                         if (strpos($items[$dependency_ref]['type'], 'imsqti_xmlv1p2/imscc_xmlv1p0') !== false){
1054                                 $items[$item_id]['tests'][$dependency_ref] = $items[$dependency_ref]['href'];
1055                         }
1056                 }
1057         }
1058
1059         //check file array, see if there are css. 
1060         //edited nov 26, harris
1061         //removed cuz i added link to the html_tags
1062         /*
1063         if (is_array($content_info['file']) && !empty($content_info['file'])){
1064                 foreach($content_info['file'] as $dependency_ref){
1065                         //handle styles 
1066                         if (preg_match('/(.*)\.css$/', $dependency_ref)){
1067                                 //calculate where this is based on our current base_href. 
1068                                 //assuming the dependency folders are siblings of the item
1069                                 $head = '<link rel="stylesheet" type="text/css" href="'.$dependency_ref.'" />';
1070                         }
1071                 }
1072         }
1073         */
1074
1075         // remote href
1076         if (preg_match('/^http.*:\/\//', trim($content_info['href'])) )
1077         {
1078                 $content = '<a href="'.$content_info['href'].'" target="_blank">'.$content_info['title'].'</a>';
1079         }
1080         else
1081         {
1082                 if ($content_type == 'IMS Common Cartridge'){
1083                         //to handle import with purely images but nothing else
1084                         //don't need a content base path for it.
1085                         $content_new_path = $content_info['new_path'];
1086                         $content_info['new_path'] = '';
1087                 }
1088                 if (isset($content_info['href'], $xml_base_path)) {
1089                         $content_info['href'] = $xml_base_path . $content_info['href'];
1090                 }
1091                 if (!isset($content_info['href'])) {
1092                         // this item doesn't have an identifierref. so create an empty page.
1093                         // what we called a folder according to v1.2 Content Packaging spec
1094                         // Hop over
1095                         $content = '';
1096                         $ext = '';
1097                         $last_modified = date('Y-m-d H:i:s');
1098                 } else {
1099                         //$file_info = @stat(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1100                         $file_info = @stat($import_path.$content_info['href']);
1101                         if ($file_info === false) {
1102                                 continue;
1103                         }
1104                 
1105                         //$path_parts = pathinfo(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1106                         $path_parts = pathinfo($import_path.$content_info['href']);
1107                         $ext = strtolower($path_parts['extension']);
1108
1109                         $last_modified = date('Y-m-d H:i:s', $file_info['mtime']);
1110                 }
1111                 if (in_array($ext, array('gif', 'jpg', 'bmp', 'png', 'jpeg'))) {
1112                         /* this is an image */
1113                         $content = '<img src="'.$content_info['href'].'" alt="'.$content_info['title'].'" />';
1114                 } else if ($ext == 'swf') {
1115                         /* this is flash */
1116             /* Using default size of 550 x 400 */
1117
1118                         $content = '<object type="application/x-shockwave-flash" data="' . $content_info['href'] . '" width="550" height="400"><param name="movie" value="'. $content_info['href'] .'" /></object>';
1119
1120                 } else if ($ext == 'mov') {
1121                         /* this is a quicktime movie  */
1122             /* Using default size of 550 x 400 */
1123
1124                         $content = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="550" height="400" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="src" value="'. $content_info['href'] . '" /><param name="autoplay" value="true" /><param name="controller" value="true" /><embed src="' . $content_info['href'] .'" width="550" height="400" controller="true" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>';
1125
1126                 /* Oct 19, 2009
1127                  * commenting this whole chunk out.  It's part of my test import codes, not sure why it's here, 
1128                  * and I don't think it should be here.  Remove this whole comment after further testing and confirmation.
1129                  * @harris
1130                  *
1131                         //Mimic the array for now.
1132                         $test_attributes['resource']['href'] = $test_xml_file;
1133                         $test_attributes['resource']['type'] = isset($items[$item_id]['type'])?'imsqti_xmlv1p2':'imsqti_xmlv1p1';
1134                         $test_attributes['resource']['file'] = $items[$item_id]['file'];
1135 //                      $test_attributes['resource']['file'] = array($test_xml_file);
1136
1137                         //Get the XML file out and start importing them into our database.
1138                         //TODO: See question_import.php 287-289.
1139                         $qids = $qti_import->importQuestions($test_attributes);
1140                 
1141                  */
1142                 } else if ($ext == 'mp3') {
1143                         $content = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="200" height="15" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="src" value="'. $content_info['href'] . '" /><param name="autoplay" value="false" /><embed src="' . $content_info['href'] .'" width="200" height="15" autoplay="false" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>';
1144                 } else if (in_array($ext, array('wav', 'au'))) {
1145                         $content = '<embed SRC="'.$content_info['href'].'" autostart="false" width="145" height="60"><noembed><bgsound src="'.$content_info['href'].'"></noembed></embed>';
1146
1147                 } else if (in_array($ext, array('txt', 'css', 'html', 'htm', 'csv', 'asc', 'tsv', 'xml', 'xsl'))) {
1148                         if ($content_type == 'IMS Common Cartridge'){
1149                                 $content_info['new_path'] = $content_new_path;
1150                         }
1151
1152                         /* this is a plain text file */
1153                         //$content = file_get_contents(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1154                         $content = file_get_contents($import_path.$content_info['href']);
1155                         if ($content === false) {
1156                                 /* if we can't stat() it then we're unlikely to be able to read it */
1157                                 /* so we'll never get here. */
1158                                 continue;
1159                         }
1160
1161                         // get the contents of the 'head' element
1162                         $head .= get_html_head_by_tag($content, $html_head_tags);
1163                         
1164                         // Specifically handle eXe package
1165                         // NOTE: THIS NEEDS WORK! TO FIND A WAY APPLY EXE .CSS FILES ONLY ON COURSE CONTENT PART.
1166                         // NOW USE OUR OWN .CSS CREATED SOLELY FOR EXE
1167                         $isExeContent = false;
1168
1169                         // check xml file in eXe package
1170                         if (preg_match("/<organization[ ]*identifier=\"eXe*>*/", $ims_manifest_xml))
1171                         {
1172                                 $isExeContent = true;
1173                         }
1174
1175                         // use ATutor's eXe style sheet as the ones from eXe conflicts with ATutor's style sheets
1176                         if ($isExeContent)
1177                         {
1178                                 $head = preg_replace ('/(<style.*>)(.*)(<\/style>)/ms', '\\1@import url(/docs/exestyles.css);\\3', $head);
1179                         }
1180
1181                         // end of specifically handle eXe package
1182
1183                         $content = get_html_body($content);
1184                         if ($contains_glossary_terms) 
1185                         {
1186                                 // replace glossary content package links to real glossary mark-up using [?] [/?]
1187                                 // refer to bug 3641, edited by Harris
1188                                 $content = preg_replace('/<a href="([.\w\d\s]+[^"]+)" target="body" class="at-term">([.\w\d\s&;"]+|.*)<\/a>/i', '[?]\\2[/?]', $content);
1189                         }
1190
1191                         /* potential security risk? */
1192                         if ( strpos($content_info['href'], '..') === false && !preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $content_info['href'])) {
1193 //                              @unlink(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1194                         }
1195
1196                         /* overwrite content if this is discussion tool. */
1197                         if ($content_info['type']=='imsdt_xmlv1p0'){
1198                                 $dt_parser = new DiscussionToolsParser();
1199                                 $xml_content = @file_get_contents($import_path . $content_info['href']);
1200                                 $dt_parser->parse($xml_content);
1201                                 $forum_obj = $dt_parser->getDt();
1202                                 $content = $forum_obj->getText();
1203                                 unset($forum_obj);
1204                                 $dt_parser->close();
1205                         }
1206                 } else if ($ext) {
1207                         /* non text file, and can't embed (example: PDF files) */
1208                         $content = '<a href="'.$content_info['href'].'">'.$content_info['title'].'</a>';
1209                 }       
1210         }
1211         $content_parent_id = $cid;
1212         if ($content_info['parent_content_id'] !== 0) {
1213                 $content_parent_id = $items[$content_info['parent_content_id']]['real_content_id'];
1214                 //if it's not there, use $cid
1215                 if (!$content_parent_id){
1216                         $content_parent_id = $cid;
1217                 }
1218         }
1219
1220         $my_offset = 0;
1221         if ($content_parent_id == $cid) {
1222                 $my_offset = $order_offset;
1223         }
1224
1225         /* replace the old path greatest common denomiator with the new package path. */
1226         /* we don't use str_replace, b/c there's no knowing what the paths may be         */
1227         /* we only want to replace the first part of the path.  
1228         */
1229         if(is_array($all_package_base_path)){
1230                 $all_package_base_path = implode('/', $all_package_base_path);
1231         }
1232         if ($common_path != '') {
1233                 $content_info['new_path'] = $package_base_name . substr($content_info['new_path'], strlen($common_path));
1234         } else {
1235                 $content_info['new_path'] = $package_base_name . '/' . $content_info['new_path'];
1236         }
1237         
1238         //handles weblinks
1239         if ($content_info['type']=='imswl_xmlv1p0'){
1240                 $weblinks_parser = new WeblinksParser();
1241                 $xml_content = @file_get_contents($import_path . $content_info['href']);
1242                 $weblinks_parser->parse($xml_content);
1243                 $content_info['title'] = $weblinks_parser->getTitle();
1244                 $content = $weblinks_parser->getUrl();
1245                 $content_folder_type = CONTENT_TYPE_WEBLINK;
1246                 $content_formatting = 2;
1247         }
1248         $head = addslashes($head);
1249         $content_info['title'] = addslashes($content_info['title']);
1250         $content_info['test_message'] = addslashes($content_info['test_message']);
1251
1252         //if this file is a test_xml, create a blank page instead, for imscc.
1253         if (preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $content_info['href']) 
1254                 || preg_match('/imsqti\_(.*)/', $content_info['type'])) {
1255                 $content = ' ';
1256         } else {
1257                 $content = addslashes($content);
1258         }
1259
1260         //check for content_type
1261         if ($content_formatting!=CONTENT_TYPE_WEBLINK){
1262                 $content_folder_type = (!isset($content_info['type'])?CONTENT_TYPE_FOLDER:CONTENT_TYPE_CONTENT);
1263         }
1264
1265         $sql= 'INSERT INTO '.TABLE_PREFIX.'content'
1266               . '(course_id, 
1267                   content_parent_id, 
1268                   ordering,
1269                   last_modified, 
1270                   revision, 
1271                   formatting, 
1272                   release_date,
1273                   head,
1274                   use_customized_head,
1275                   keywords, 
1276                   content_path, 
1277                   title, 
1278                   text,
1279                           test_message,
1280                           content_type) 
1281                VALUES 
1282                              ('.$_SESSION['course_id'].','                                                                                                                      
1283                              .intval($content_parent_id).','            
1284                              .($content_info['ordering'] + $my_offset - $lti_offset[$content_info['parent_content_id']] + 1).','
1285                              .'"'.$last_modified.'",                                                                                                    
1286                               0,'
1287                              .$content_formatting.' ,
1288                               NOW(),"'
1289                              . $head .'",
1290                              1,
1291                               "",'
1292                              .'"'.$content_info['new_path'].'",'
1293                              .'"'.$content_info['title'].'",'
1294                              .'"'.$content.'",'
1295                                  .'"'.$content_info['test_message'].'",'
1296                                  .$content_folder_type.')';
1297
1298         $result = mysql_query($sql, $db) or die(mysql_error());
1299
1300         /* get the content id and update $items */
1301         $items[$item_id]['real_content_id'] = mysql_insert_id($db);
1302
1303         /* get the tests associated with this content */
1304         if (!empty($items[$item_id]['tests']) || strpos($items[$item_id]['type'], 'imsqti_xmlv1p2/imscc_xmlv1p0') !== false){
1305                 $qti_import = new QTIImport($import_path);
1306                 if (isset($items[$item_id]['tests'])){
1307                         $loop_var = $items[$item_id]['tests'];
1308                 } else {
1309                         $loop_var = $items[$item_id]['file'];
1310                 }
1311
1312                 foreach ($loop_var as $array_id => $test_xml_file){
1313                         //check if this item is the qti item object, or it is the content item obj
1314                         //switch it to qti obj if it's content item obj
1315                         if ($items[$item_id]['type'] == 'webcontent'){
1316                                 $item_qti = $items[$array_id];
1317                         } else {
1318                                 $item_qti = $items[$item_id];
1319                         }
1320                         //call subrountine to add the questions.
1321                         $qids = addQuestions($test_xml_file, $item_qti, $import_path);
1322
1323                         //import test
1324                         if ($test_title==''){
1325                                 $test_title = $content_info['title'];
1326                         }
1327
1328                         $tid = $qti_import->importTest($test_title);
1329
1330                         //associate question and tests
1331                         foreach ($qids as $order=>$qid){
1332                                 if (isset($qti_import->weights[$order])){
1333                                         $weight = round($qti_import->weights[$order]);
1334                                 } else {
1335                                         $weight = 0;
1336                                 }
1337                                 $new_order = $order + 1;
1338                                 $sql = "INSERT INTO " . TABLE_PREFIX . "tests_questions_assoc" . 
1339                                                 "(test_id, question_id, weight, ordering, required) " .
1340                                                 "VALUES ($tid, $qid, $weight, $new_order, 0)";
1341                                 $result = mysql_query($sql, $db);
1342                         }
1343
1344                         //associate content and test
1345                         $sql =  'INSERT INTO ' . TABLE_PREFIX . 'content_tests_assoc' . 
1346                                         '(content_id, test_id) ' .
1347                                         'VALUES (' . $items[$item_id]['real_content_id'] . ", $tid)";
1348                         $result = mysql_query($sql, $db);
1349                 
1350 //                      if (!$msg->containsErrors()) {
1351 //                              $msg->addFeedback('IMPORT_SUCCEEDED');
1352 //                      }
1353                 }
1354         }
1355
1356         /* get the a4a related xml */
1357         if (isset($items[$item_id]['a4a_import_enabled']) && isset($items[$item_id]['a4a']) && !empty($items[$item_id]['a4a'])) {
1358                 $a4a_import = new A4aImport($items[$item_id]['real_content_id']);
1359                 $a4a_import->setRelativePath($items[$item_id]['new_path']);
1360                 $a4a_import->importA4a($items[$item_id]['a4a']);
1361         }
1362
1363         /* get the discussion tools (dependent to content)*/
1364         if (isset($items[$item_id]['forum']) && !empty($items[$item_id]['forum'])){
1365                 foreach($items[$item_id]['forum'] as $forum_ref => $forum_link){
1366                         $dt_parser = new DiscussionToolsParser();
1367                         $dt_import = new DiscussionToolsImport();
1368
1369                         //if this forum has not been added, parse it and add it.
1370                         if (!isset($added_dt[$forum_ref])){
1371                                 $xml_content = @file_get_contents($import_path . $forum_link);
1372                                 $dt_parser->parse($xml_content);
1373                                 $forum_obj = $dt_parser->getDt();
1374                                 $dt_import->import($forum_obj, $items[$item_id]['real_content_id']);
1375                                 $added_dt[$forum_ref] = $dt_import->getFid();                           
1376                         }
1377                         //associate the fid and content id
1378                         $dt_import->associateForum($items[$item_id]['real_content_id'], $added_dt[$forum_ref]);
1379                 }
1380         } elseif ($items[$item_id]['type']=='imsdt_xmlv1p0'){
1381                 //optimize this, repeated codes as above
1382                 $dt_parser = new DiscussionToolsParser();
1383                 $dt_import = new DiscussionToolsImport();
1384                 $xml_content = @file_get_contents($import_path . $content_info['href']);
1385                 $dt_parser->parse($xml_content);
1386                 $forum_obj = $dt_parser->getDt();
1387                 $dt_import->import($forum_obj, $items[$item_id]['real_content_id']);
1388                 $added_dt[$item_id] = $dt_import->getFid();
1389
1390                 //associate the fid and content id
1391                 $dt_import->associateForum($items[$item_id]['real_content_id'], $added_dt[$item_id]);
1392         }
1393 }
1394 //exit;//harris
1395 if ($package_base_path == '.') {
1396         $package_base_path = '';
1397 }
1398
1399 // loop through the files outside the package folder, and copy them to its relative path
1400 /**
1401 if (is_dir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources')) {
1402         $handler = opendir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources');
1403         while ($file = readdir($handler)){
1404                 $filename = AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources/'.$file;
1405 debug($filename);
1406                 if(is_file($filename)){
1407                         @rename($filename, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name.'/'.$file);
1408                 }
1409         }
1410         closedir($handler);
1411 }
1412 **/
1413 //--- harris edit for path thing
1414 $file = AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].DIRECTORY_SEPARATOR.$common_path;
1415 if (is_dir($file)) {
1416     rename($file, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name);
1417 }
1418 //--- end
1419 //takes care of the condition where the whole package doesn't have any contents but question banks
1420 //also is the case of urls
1421 if(is_array($all_package_base_path)){
1422         $all_package_base_path = implode('/', $all_package_base_path);
1423         if(strpos($all_package_base_path, 'http:/')===false){
1424         if (@rename($import_path.$all_package_base_path, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name) === false) {
1425             if (!$msg->containsErrors()) {
1426                 $msg->addError('IMPORT_FAILED');
1427             }
1428         }
1429     }
1430 }
1431
1432 //check if there are still resources missing
1433 /*
1434 foreach($items as $idetails){
1435         $temp_path = pathinfo($idetails['href']);
1436         @rename(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$temp_path['dirname'], AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name . '/' . $temp_path['dirname']);
1437 }
1438 */
1439 clr_dir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id']);
1440
1441 if (file_exists($full_filename)) {
1442         @unlink($full_filename);
1443 }
1444
1445
1446 if ($_POST['s_cid']){
1447         if (!$msg->containsErrors()) {
1448                 $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
1449         }
1450         header('Location: ../editor/edit_content.php?cid='.intval($_POST['cid']));
1451         exit;
1452 } else {
1453         if (!$msg->containsErrors()) {
1454                 $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
1455         }
1456         if ($_GET['tile']) {
1457                 header('Location: '.AT_BASE_HREF.'mods/_standard/tile_search/index.php');
1458         } else {
1459                 header('Location: ./index.php?cid='.intval($_POST['cid']));
1460         }
1461         exit;
1462 }
1463
1464 ?>