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