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