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