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