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