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