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