2 /************************************************************************/
4 /************************************************************************/
5 /* Copyright (c) 2002 - 2009 */
6 /* Inclusive Design Institute */
8 /* This program is free software. You can redistribute it and/or */
9 /* modify it under the terms of the GNU General Public License */
10 /* as published by the Free Software Foundation. */
11 /************************************************************************/
12 // $Id: ims_import.php 10319 2010-10-08 20:43:03Z hwong $
13 define('AT_INCLUDE_PATH', '../../../include/');
14 require(AT_INCLUDE_PATH.'vitals.inc.php');
16 require_once(AT_INCLUDE_PATH.'../mods/_core/file_manager/filemanager.inc.php'); /* for clr_dir() and preImportCallBack and dirsize() */
17 require(AT_INCLUDE_PATH.'classes/pclzip.lib.php');
18 require(AT_INCLUDE_PATH.'../mods/_core/imsqti/lib/qti.inc.php');
19 require(AT_INCLUDE_PATH.'../mods/_core/imsqti/classes/QTIImport.class.php');
20 require(AT_INCLUDE_PATH.'../mods/_core/imsafa/classes/A4aImport.class.php');
21 require(AT_INCLUDE_PATH.'../mods/_core/imscp/ns.inc.php'); //namespace, no longer needs, delete it after it's stable.
22 require(AT_INCLUDE_PATH.'../mods/_core/imscc/classes/WeblinksParser.class.php');
23 require(AT_INCLUDE_PATH.'../mods/_core/imscc/classes/DiscussionToolsParser.class.php');
24 require(AT_INCLUDE_PATH.'../mods/_core/imscc/classes/DiscussionToolsImport.class.php');
27 /* make sure we own this course that we're exporting */
28 authenticate(AT_PRIV_CONTENT);
30 /* to avoid timing out on large files */
32 $_SESSION['done'] = 1;
34 $html_head_tags = array("style", "script", "link");
36 $package_base_path = '';
37 $package_real_base_path = ''; //the path to save the contents
38 $all_package_base_path = array();
40 $element_path = array();
41 $imported_glossary = array();
46 $skip_ims_validation = false;
47 $added_dt = array(); //the mapping of discussion tools that are added
48 $avail_dt = array(); //list of discussion tools that have not been handled
51 * return the error messages represented by the given array
53 * @ref http://ca3.php.net/manual/en/domdocument.schemavalidate.php
55 function libxml_display_error($error)
58 switch ($error->level) {
59 case LIBXML_ERR_WARNING:
60 $return .= "<b>Warning $error->code</b>: ";
62 case LIBXML_ERR_ERROR:
63 $return .= "<b>Error $error->code</b>: ";
65 case LIBXML_ERR_FATAL:
66 $return .= "<b>Fatal Error $error->code</b>: ";
69 $return .= trim($error->message);
71 $return .= " in <b>$error->file</b>";
73 $return .= " on line <b>$error->line</b>\n";
79 * Validate all the XML in the package, including checking XSDs, missing data.
80 * @param string the path of the directory that contains all the package files
81 * @return boolean true if every file exists in the manifest, false if any is missing.
83 function checkResources($import_path){
84 global $items, $msg, $skip_ims_validation, $avail_dt;
86 if (!is_dir($import_path)){
90 //if the package has access for all content, skip validation for now.
91 //todo: import the XSD into our validator
92 if ($skip_ims_validation){
96 //generate a file tree
97 $data = rscandir($import_path);
99 //check if every file is presented in the manifest
100 foreach($data as $filepath){
101 $filepath = substr($filepath, strlen($import_path));
103 //validate xml via its xsd/dtds
104 if (preg_match('/(.*)\.xml/', $filepath)){
105 libxml_use_internal_errors(true);
106 $dom = new DOMDocument();
107 $dom->load(realpath($import_path.$filepath));
108 if (!@$dom->schemaValidate('main.xsd')){
109 $errors = libxml_get_errors();
110 foreach ($errors as $error) {
112 if ($error->level==LIBXML_ERR_WARNING){
115 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', libxml_display_error($error)));
117 libxml_clear_errors();
119 //if this is the manifest file, we do not have to check for its existance.
120 // if (preg_match('/(.*)imsmanifest\.xml/', $filepath)){
126 //Create an array that mimics the structure of the data array, based on the xml items
127 $filearray = array();
128 foreach($items as $name=>$fileinfo){
129 if(isset($fileinfo['file']) && is_array($fileinfo['file']) && !empty($fileinfo['file'])){
130 foreach($fileinfo['file'] as $fn){
131 if (!in_array(realpath($import_path.$fn), $filearray)){
133 if (preg_match('/^http[s]?\:/', $fn) == 0){
134 $filearray[] = realpath($import_path. $fn);
140 //validate the xml by its schema
141 if (preg_match('/imsqti\_(.*)/', $fileinfo['type'])){
142 $qti = new QTIParser($fileinfo['type']);
143 $xml_content = @file_get_contents($import_path . $fileinfo['href']);
144 $qti->parse($xml_content); //will add error to $msg if failed
147 //add all dependent discussion tools to a list
148 if(isset($fileinfo['dependency']) && !empty($fileinfo['dependency'])){
149 $avail_dt = array_merge($avail_dt, $fileinfo['dependency']);
153 //check if all files in the xml is presented in the archieve
154 $result = array_diff($filearray, $data);
155 //using sizeof because array_diff only
156 //returns an array containing all the entries from array1 that are not present in any of the
158 //Using sizeof make sure it's not a subset of array2.
159 //-1 on data because it always contain the imsmanifest.xml file
160 if (!$skip_ims_validation){
161 if (!empty($result) || sizeof($data)-1>sizeof($filearray)){
162 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('ims_missing_references')));
169 * @example rscandir(dirname(__FILE__).'/'));
170 * @param string $base
175 function rscandir($base='', &$data=array()) {
176 $array = array_diff(scandir($base), array('.', '..')); # remove ' and .. from the array */
177 foreach($array as $value) : /* loop through the array at the level of the supplied $base */
179 if (is_dir($base.$value)) : /* if this is a directory */
180 // don't save the directory name
181 // $data[] = $base.$value.'/'; /* add it to the $data array */
182 $data = rscandir($base.$value.'/', $data); /* then make a recursive call with the
183 current $value as the $base supplying the $data array to carry into the recursion */
185 elseif (is_file($base.$value)) : /* else if the current $value is a file */
186 $data[] = realpath($base.$value); /* just add the current $value to the $data array */
191 return $data; // return the $data array
196 * Function to restructure the $items. So that old import will merge the top page into its children, and
197 * create a new folder on top of it
199 function rehash($items){
201 $parent_page_maps = array(); //old=>new
202 $temp_popped_items = array();
203 $rehashed_items = array(); //the reconstructed array
204 foreach($items as $id => $content){
205 $parent_obj = $items[$content['parent_content_id']];
206 $rehashed_items[$id] = $content; //copy
207 //first check if this is the top folder of the archieve, we don't want the top folder, remove it.
208 /* if (isset($content['parent_content_id']) && !isset($parent_obj) && !isset($content['type'])){
209 //if we can get into here, it means the parent_content_id of this is empty
210 //implying this is the first folder.
211 //note: it checks content[type] cause it could be a webcontent. In that case,
212 // we do want to keep it.
213 debug($content, 'hit');
214 unset($rehashed_items[$id]);
217 //then check if there exists a mapping for this item, if so, simply replace is and next.
219 */ if (isset($parent_page_maps[$content['parent_content_id']])){
220 $rehashed_items [$id]['parent_content_id'] = $parent_page_maps[$content['parent_content_id']];
221 $rehashed_items [$id]['ordering']++;
223 //If its parent page is a top page and have an identiferref
224 elseif (isset($parent_obj) && isset($parent_obj['href'])){
225 if (!isset($parent_obj['href'])){
226 //check if this top page is already a folder, if so, next.
229 //else, make its parent page to a folder
230 $new_item['title'] = $parent_obj['title'];
231 //check if this parent has been modified, if so, chnage it
232 if (isset($parent_page_maps[$parent_obj['parent_content_id']])){
233 $new_item['parent_content_id'] = $parent_page_maps[$parent_obj['parent_content_id']];
235 $new_item['parent_content_id'] = $parent_obj['parent_content_id'];
237 //all ordering needs to be +1 because we are creating a new folder on top of
238 //everything, except the first page.
239 $new_item['ordering'] = $parent_obj['ordering'];
240 if ($new_item['parent_content_id']!='0'){
241 $new_item['ordering']++;
244 //assign this new parent folder to the pending items array
245 $new_item_name = $content['parent_content_id'].'_FOLDER';
246 //a not so brilliant way to append the folder in its appropriate position
247 $reordered_hashed_items = array(); //use to store the new rehashed item with the correct item order
248 foreach($rehashed_items as $rh_id=>$rh_content){
249 if ($rh_id == $content['parent_content_id']){
250 //add the folder in before the parent subpage.
251 $reordered_hashed_items[$new_item_name] = $new_item;
253 $reordered_hashed_items[$rh_id] = $rh_content; //clone
255 $rehashed_items = $reordered_hashed_items; //replace it back
256 unset($reordered_hashed_items);
257 $parent_page_maps[$content['parent_content_id']] = $new_item_name; //save this page on the hash map
259 //reconstruct the parent
260 $rehashed_items[$content['parent_content_id']]['parent_content_id'] = $parent_page_maps[$content['parent_content_id']];
261 $rehashed_items[$content['parent_content_id']]['ordering'] = 0; //always the first one.
264 $rehashed_items[$id]['parent_content_id'] = $parent_page_maps[$content['parent_content_id']];
265 $rehashed_items[$id]['ordering']++;
269 return $rehashed_items;
273 * Take out the common path within all $items['new_path']. Make sure we include
274 * AccessForAll files in the array.
275 * This allows import/export repeatedly without duplicating its path
276 * @param array contains the breakdown of all resources in the XML
278 function removeCommonPath($items){
280 $quit = false; //a flag that is set if it's not the first time being run.
282 $filearray = array();
283 //get all files listed in the manifest
284 foreach($items as $name=>$fileinfo){
285 if(isset($fileinfo['file']) && is_array($fileinfo['file']) && !empty($fileinfo['file'])){
286 foreach($fileinfo['file'] as $fn){
287 if (!in_array($fn, $filearray)){
288 if (preg_match('/^http[s]?\:/', $fn) == 0){
296 foreach($filearray as $index=>$path){
298 //check if this is a XML file; if so, skip through,
299 //cause XML most likely isn't a content resource.
300 $ext = substr($path, (strrpos($path, '.')+1));
305 //if common path is empty, assign the first path to it.
306 if ($common_path=='' && $quit==false){
307 $common_path = $path;
308 $quit = true; //the next time common_path is empty, quit;
311 //we use '/' here instead of DIRECTORY_SEPARATOR because php would
312 //actually use '\' and return the whole string.
313 $common_array = explode('/', $common_path);
314 $path_array = explode('/', $path);
315 //convert path_array to absolute path
316 //TODO: array_search is slow, build a faster search
317 $pos=array_search('..', $path_array);
318 while($pos=array_search('..', $path_array)){
319 array_splice($path_array, $pos-1, 2);
321 $intersect_array = array_intersect($common_array, $path_array);
322 $common_path = implode('/', $intersect_array);
329 * This function will take the test accessment XML and add these to the database.
330 * @param string The path of the XML, without the import_path.
331 * @param mixed An item singleton. Contains the info of this item, namely, the accessment details.
332 * The item must be an object created by the ims class.
333 * @param string the import path
334 * @return mixed An Array that contains all the question IDs that have been imported.
336 function addQuestions($xml, $item, $import_path){
338 $qti_import = new QTIImport($import_path);
339 $tests_xml = $import_path.$xml;
341 //Mimic the array for now.
342 $test_attributes['resource']['href'] = $item['href'];
343 $test_attributes['resource']['type'] = preg_match('/imsqti_xmlv1p2/', $item['type'])==1?'imsqti_xmlv1p2':'imsqti_xmlv1p1';
344 $test_attributes['resource']['file'] = $item['file'];
346 //Get the XML file out and start importing them into our database.
347 //TODO: See question_import.php 287-289.
348 $qids = $qti_import->importQuestions($test_attributes);
349 $test_title = $qti_import->title;
355 /* called at the start of en element */
356 /* builds the $path array which is the path from the root to the current element */
357 function startElement($parser, $name, $attrs) {
358 global $items, $path, $package_base_path, $all_package_base_path, $package_real_base_path;
359 global $element_path, $import_path, $skip_ims_validation;
360 global $xml_base_path, $test_message, $content_type;
361 global $current_identifier, $msg, $ns, $ns_cp;
363 //check if the xml is valid
365 if(isset($attrs['xsi:schemaLocation']) && $name == 'manifest'){
366 //run the loop and check it thru the ns.inc.php
367 } elseif ($name == 'manifest' && !isset($attrs['xsi:schemaLocation'])) {
368 //$msg->addError('MANIFEST_NOT_WELLFORM: NO NAMESPACE');
369 $msg->addError('IMPORT_CARTRIDGE_FAILED');
373 //error if the tag names are wrong
374 if (preg_match('/^xsi\:/', $name) >= 1){
375 //$msg->addError('MANIFEST_NOT_WELLFORM');
376 $msg->addError('IMPORT_CARTRIDGE_FAILED');
380 //validate namespaces
381 if(!$skip_ims_validation && isset($attrs['xsi:schemaLocation']) && $name=='manifest'){
382 $schema_location = array();
383 $split_location = preg_split('/[\r\n\s]+/', trim($attrs['xsi:schemaLocation']));
385 //check if the namespace is actually right, have an array or some sort in IMS class
386 if(sizeof($split_location)%2==1){
387 //schema is not in the form of "The first URI reference in each pair is a namespace name,
388 //and the second is the location of a schema that describes that namespace."
389 //$msg->addError('MANIFEST_NOT_WELLFORM');
390 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('schema_error')));
393 //turn the xsi:schemaLocation URI into a schema that describe namespace.
395 //http://msdn.microsoft.com/en-us/library/ms256100(VS.85).aspx
396 //http://www.w3.org/TR/xmlschema-1/
397 for($i=0; $i < sizeof($split_location);$i=$i+2){
399 if (isset($ns[$split_location[$i]]) && $ns[$split_location[$i]] != $split_location[$i+1]){
400 //$msg->addError('MANIFEST_NOT_WELLFORM: SCHEMA');
401 $msg->addError('IMPORT_CARTRIDGE_FAILED');
404 //if the key of the namespace is not defined. Throw error.
405 if(!isset($ns[$split_location[$i]]) && !isset($ns_cp[$split_location[$i]])){
406 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('schema_error')));
413 if ($name == 'manifest' && isset($attrs['xml:base']) && $attrs['xml:base']) {
414 $xml_base_path = $attrs['xml:base'];
415 } else if ($name == 'file') {
416 // check if it misses file references
417 if(!$skip_ims_validation && (!isset($attrs['href']) || $attrs['href']=='')){
418 //$msg->addError('MANIFEST_NOT_WELLFORM');
419 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('ims_missing_references')));
422 // special case for webCT content packages that don't specify the `href` attribute
423 // with the `<resource>` element.
424 // we take the `href` from the first `<file>` element.
425 if (isset($items[$current_identifier]) && ($items[$current_identifier]['href'] == '')) {
426 $attrs['href'] = urldecode($attrs['href']);
427 $items[$current_identifier]['href'] = $attrs['href'];
430 $temp_path = pathinfo($attrs['href']);
431 $temp_path = explode('/', $temp_path['dirname']);
432 if (empty($package_base_path)){
433 $package_base_path = $temp_path;
435 if ($all_package_base_path!='' && empty($all_package_base_path)){
436 $all_package_base_path = $temp_path;
438 $package_base_path = array_intersect_assoc($package_base_path, $temp_path);
440 //calculate the depths of relative paths
441 if ($all_package_base_path!=''){
442 $no_relative_temp_path = $temp_path;
443 foreach($no_relative_temp_path as $path_node){
444 if ($path_node=='..'){
445 array_pop($no_relative_temp_path);
446 array_pop($no_relative_temp_path); //not a typo, have to pop twice, both itself('..'), and the one before.
449 $all_package_base_path = array_intersect_assoc($all_package_base_path, $no_relative_temp_path);
450 if (empty($all_package_base_path)){
451 $all_package_base_path = ''; //unset it, there is no intersection.
455 //save the actual content base path
456 if (in_array('..', $temp_path)){
457 $sizeofrp = array_count_values($temp_path);
460 //for IMSCC, assume that all resources lies in the same folder, except styles.css
461 if ($items[$current_identifier]['type']=='webcontent' || $items[$current_identifier]['type']=='imsdt_xmlv1p0'){
462 //find the intersection of each item's related files, then that intersection is the content_path
463 if (isset($items[$current_identifier]['file'])){
464 foreach ($items[$current_identifier]['file'] as $resource_path){
465 $temp_path = pathinfo($resource_path);
466 $temp_path = explode('/', $temp_path['dirname']);
467 $package_base_path = array_intersect_assoc($package_base_path, $temp_path);
473 if($sizeofrp['..'] > 0 && !empty($all_package_base_path)){
474 for ($i=0; $i<$sizeofrp['..']; $i++){
475 array_pop($all_package_base_path);
479 if (count($package_base_path) > 0) {
480 $items[$current_identifier]['new_path'] = implode('/', $package_base_path);
484 * @harris, reworked the package_base_path
485 if ($package_base_path=="") {
486 $package_base_path = $temp_path;
488 elseif (is_array($package_base_path) && $content_type != 'IMS Common Cartridge') {
489 //if this is a content package, we want only intersection
490 $package_base_path = array_intersect($package_base_path, $temp_path);
491 $temp_path = $package_base_path;
493 //added these 2 lines in so that pictures would load. making the elseif above redundant.
494 //if there is a bug for pictures not load, then it's the next 2 lines.
495 $package_base_path = array_intersect($package_base_path, $temp_path);
496 $temp_path = $package_base_path;
498 $items[$current_identifier]['new_path'] = implode('/', $temp_path);
500 if ( isset($_POST['allow_test_import']) && isset($items[$current_identifier])
501 && preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $attrs['href'])) {
502 $items[$current_identifier]['tests'][] = $attrs['href'];
504 if ( isset($_POST['allow_a4a_import']) && isset($items[$current_identifier])) {
505 $items[$current_identifier]['a4a_import_enabled'] = true;
507 } else if (($name == 'item') && ($attrs['identifierref'] != '')) {
508 $path[] = $attrs['identifierref'];
509 } else if (($name == 'item') && ($attrs['identifier'])) {
510 $path[] = $attrs['identifier'];
511 // } else if (($name == 'resource') && is_array($items[$attrs['identifier']])) {
512 } else if (($name == 'resource')) {
513 $current_identifier = $attrs['identifier'];
514 $items[$current_identifier]['type'] = $attrs['type'];
515 if ($attrs['href']) {
516 $attrs['href'] = urldecode($attrs['href']);
518 $items[$attrs['identifier']]['href'] = $attrs['href'];
520 // href points to a remote url
521 if (preg_match('/^http.*:\/\//', trim($attrs['href']))) {
522 $items[$attrs['identifier']]['new_path'] = '';
523 } else // href points to local file
525 $temp_path = pathinfo($attrs['href']);
526 $temp_path = explode('/', $temp_path['dirname']);
527 // if (empty($package_base_path)) {
528 $package_base_path = $temp_path;
531 // $package_base_path = array_intersect($package_base_path, $temp_path);
533 $items[$attrs['identifier']]['new_path'] = implode('/', $temp_path);
537 //if test custom message has not been saved
538 // if (!isset($items[$current_identifier]['test_message'])){
539 // $items[$current_identifier]['test_message'] = $test_message;
541 } else if ($name=='dependency' && $attrs['identifierref']!='') {
542 //if there is a dependency, attach it to the item array['file']
543 $items[$current_identifier]['dependency'][] = $attrs['identifierref'];
545 if (($name == 'item') && ($attrs['parameters'] != '')) {
546 $items[$attrs['identifierref']]['test_message'] = $attrs['parameters'];
549 if(!isset($items[$current_identifier]) && $attrs['href']!=''){
550 $items[$current_identifier]['href'] = $attrs['href'];
552 if (substr($attrs['href'], 0, 7) == 'http://' || substr($attrs['href'], 0, 8) == 'https://' || file_exists($import_path.$attrs['href']) || $skip_ims_validation){
553 $items[$current_identifier]['file'][] = $attrs['href'];
555 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT(array('ims_files_missing', $attrs['href']))));
558 if ($name=='cc:authorizations'){
559 //don't have authorization setup.
560 //$msg->addError('');
561 $msg->addError('IMS_AUTHORIZATION_NOT_SUPPORT');
563 array_push($element_path, $name);
566 /* called when an element ends */
567 /* removed the current element from the $path */
568 function endElement($parser, $name) {
569 global $path, $element_path, $my_data, $items;
570 global $current_identifier, $skip_ims_validation;
571 global $msg, $content_type;
572 static $resource_num = 0;
574 if ($name == 'item') {
578 //check if this is a test import
579 if ($name == 'schema'){
580 if (trim($my_data)=='IMS Question and Test Interoperability'){
581 $msg->addError('IMPORT_FAILED');
583 $content_type = trim($my_data);
587 if ($current_identifier != ''){
588 $my_data = trim($my_data);
589 $last_file_name = $items[$current_identifier]['file'][(sizeof($items[$current_identifier]['file']))-1];
591 if ($name=='originalAccessMode'){
592 if (in_array('accessModeStatement', $element_path)){
593 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['access_stmt_originalAccessMode'] = $my_data;
594 } elseif (in_array('adaptationStatement', $element_path)){
595 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['adapt_stmt_originalAccessMode'] = $my_data;
597 } elseif (($name=='language') && in_array('accessModeStatement', $element_path)){
598 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['language'][] = $my_data;
599 } elseif ($name=='hasAdaptation') {
600 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['hasAdaptation'][] = $my_data;
601 } elseif ($name=='isAdaptationOf'){
602 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['isAdaptationOf'][] = $my_data;
603 } elseif ($name=='accessForAllResource'){
604 /* the head node of accessForAll Metadata, if this exists in the manifest. Skip XSD validation,
605 * because A4a doesn't have a xsd yet. Our access for all is based on ISO which will not pass
606 * the current IMS validation.
607 * Also, since ATutor is the only one (as of Oct 21, 2009) that exports IMS with access for all
608 * content, we can almost assume that any ims access for all content is by us, and is valid.
610 $skip_ims_validation = true;
612 } elseif($name=='file'){
613 $resource_num = 0; //reset resournce number to 0 when the file tags ends
617 if ($element_path === array('manifest', 'metadata', 'imsmd:lom', 'imsmd:general', 'imsmd:title', 'imsmd:langstring')) {
618 global $package_base_name;
619 $package_base_name = trim($my_data);
622 array_pop($element_path);
626 /* called when there is character data within elements */
627 /* constructs the $items array using the last entry in $path as the parent element */
628 function characterData($parser, $data){
629 global $path, $items, $order, $my_data, $element_path;
630 global $current_identifier;
632 $str_trimmed_data = trim($data);
634 if (!empty($str_trimmed_data)) {
635 $size = count($path);
637 $current_item_id = $path[$size-1];
639 $parent_item_id = $path[$size-2];
644 if (isset($items[$current_item_id]['parent_content_id']) && is_array($items[$current_item_id])) {
646 /* this item already exists, append the title */
647 /* this fixes {\n, \t, `, &} characters in elements */
649 /* horible kludge to fix the <ns2:objectiveDesc xmlns:ns2="http://www.utoronto.ca/atrc/tile/xsd/tile_objective"> */
651 if (in_array('accessForAllResource', $element_path)){
653 } elseif ($element_path[count($element_path)-1] != 'ns1:objectiveDesc') {
654 $items[$current_item_id]['title'] .= $data;
658 $order[$parent_item_id] ++;
659 $item_tmpl = array( 'title' => $data,
660 'parent_content_id' => $parent_item_id,
661 'ordering' => $order[$parent_item_id]-1);
662 //append other array values if it exists
663 if (is_array($items[$current_item_id])){
664 $items[$current_item_id] = array_merge($items[$current_item_id], $item_tmpl);
666 $items[$current_item_id] = $item_tmpl;
675 /* glossary parser: */
676 function glossaryStartElement($parser, $name, $attrs) {
677 global $element_path;
679 array_push($element_path, $name);
682 /* called when an element ends */
683 /* removed the current element from the $path */
684 function glossaryEndElement($parser, $name) {
685 global $element_path, $my_data, $imported_glossary;
686 static $current_term;
688 if ($element_path === array('glossary', 'item', 'term') ||
689 $element_path === array('glossary:glossary', 'item', 'term')) {
690 $current_term = $my_data;
692 } else if ($element_path === array('glossary', 'item', 'definition') ||
693 $element_path === array('glossary:glossary', 'item', 'definition')) {
694 $imported_glossary[trim($current_term)] = trim($my_data);
697 array_pop($element_path);
701 function glossaryCharacterData($parser, $data){
707 if (!isset($_POST['submit']) && !isset($_POST['cancel'])) {
708 /* just a catch all */
710 $errors = array('FILE_MAX_SIZE', ini_get('post_max_size'));
711 $msg->addError($errors);
713 header('Location: ./index.php');
715 } else if (isset($_POST['cancel'])) {
716 $msg->addFeedback('IMPORT_CANCELLED');
718 header('Location: ../content/index.php');
722 $cid = intval($_POST['cid']);
724 //If user chooses to ignore validation.
725 if(isset($_POST['ignore_validation']) && $_POST['ignore_validation']==1) {
726 $skip_ims_validation = true;
729 if (isset($_POST['url']) && ($_POST['url'] != 'http://') ) {
730 if ($content = @file_get_contents($_POST['url'])) {
731 // save file to /content/
732 $filename = substr(time(), -6). '.zip';
733 $full_filename = AT_CONTENT_DIR . $filename;
735 if (!$fp = fopen($full_filename, 'w+b')) {
736 echo "Cannot open file ($filename)";
740 if (fwrite($fp, $content, strlen($content) ) === FALSE) {
741 echo "Cannot write to file ($filename)";
746 $_FILES['file']['name'] = $filename;
747 $_FILES['file']['tmp_name'] = $full_filename;
748 $_FILES['file']['size'] = strlen($content);
750 //$url_parts = pathinfo($_POST['url']);
751 //$package_base_name_url = $url_parts['basename'];
752 $package_base_name_url = md5(time());
754 $ext = pathinfo($_FILES['file']['name']);
755 $ext = $ext['extension'];
758 $msg->addError('IMPORTDIR_IMS_NOTVALID');
759 } else if ($_FILES['file']['error'] == 1) {
760 $errors = array('FILE_MAX_SIZE', ini_get('upload_max_filesize'));
761 $msg->addError($errors);
762 } else if ( !$_FILES['file']['name'] || (!is_uploaded_file($_FILES['file']['tmp_name']) && !$_POST['url'])) {
763 $msg->addError('FILE_NOT_SELECTED');
764 } else if ($_FILES['file']['size'] == 0) {
765 $msg->addError('IMPORTFILE_EMPTY');
768 if ($msg->containsErrors()) {
769 if (isset($_GET['tile'])) {
770 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
772 header('Location: index.php');
777 /* check if ../content/import/ exists */
778 $import_path = AT_CONTENT_DIR . 'import/';
779 $content_path = AT_CONTENT_DIR;
781 if (!is_dir($import_path)) {
782 if (!@mkdir($import_path, 0700)) {
783 $msg->addError('IMPORTDIR_FAILED');
787 $import_path .= $_SESSION['course_id'].'/';
788 if (is_dir($import_path)) {
789 clr_dir($import_path);
792 if (!@mkdir($import_path, 0700)) {
793 $msg->addError('IMPORTDIR_FAILED');
796 if ($msg->containsErrors()) {
797 if (isset($_GET['tile'])) {
798 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
800 header('Location: index.php');
805 /* extract the entire archive into AT_COURSE_CONTENT . import/$course using the call back function to filter out php files */
807 $archive = new PclZip($_FILES['file']['tmp_name']);
808 if ($archive->extract( PCLZIP_OPT_PATH, $import_path,
809 PCLZIP_CB_PRE_EXTRACT, 'preImportCallBack') == 0) {
810 $msg->addError('IMPORT_FAILED');
811 echo 'Error : '.$archive->errorInfo(true);
812 clr_dir($import_path);
813 header('Location: index.php');
816 error_reporting(AT_ERROR_REPORTING);
818 /* get the course's max_quota */
819 $sql = "SELECT max_quota FROM ".TABLE_PREFIX."courses WHERE course_id=$_SESSION[course_id]";
820 $result = mysql_query($sql, $db);
821 $q_row = mysql_fetch_assoc($result);
823 if ($q_row['max_quota'] != AT_COURSESIZE_UNLIMITED) {
825 if ($q_row['max_quota'] == AT_COURSESIZE_DEFAULT) {
826 $q_row['max_quota'] = $MaxCourseSize;
828 $totalBytes = dirsize($import_path);
829 $course_total = dirsize(AT_CONTENT_DIR . $_SESSION['course_id'].'/');
830 $total_after = $q_row['max_quota'] - $course_total - $totalBytes + $MaxCourseFloat;
832 if ($total_after < 0) {
833 /* remove the content dir, since there's no space for it */
834 $errors = array('NO_CONTENT_SPACE', number_format(-1*($total_after/AT_KBYTE_SIZE), 2 ) );
835 $msg->addError($errors);
837 clr_dir($import_path);
839 if (isset($_GET['tile'])) {
840 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
842 header('Location: index.php');
849 $items = array(); /* all the content pages */
850 $order = array(); /* keeps track of the ordering for each content page */
851 $path = array(); /* the hierarchy path taken in the menu to get to the current item in the manifest */
852 $dependency_files = array(); /* the file path for the dependency files */
855 $items[content_id/resource_id] = array(
857 'real_content_id' // calculated after being inserted
863 $ims_manifest_xml = @file_get_contents($import_path.'imsmanifest.xml');
864 //scan for manifest xml if it's not on the top level.
865 if ($ims_manifest_xml === false){
866 $data = rscandir($import_path);
867 $manifest_array = array();
868 foreach($data as $scanned_file){
869 $scanned_file = realpath($scanned_file);
870 //change the file string to an array
871 $this_file_array = explode(DIRECTORY_SEPARATOR, $scanned_file);
872 if(empty($manifest_array)){
873 $manifest_array = $this_file_array;
875 $manifest_array = array_intersect_assoc($this_file_array, $manifest_array);
877 if (strpos($scanned_file, 'imsmanifest')!==false){
878 $ims_manifest_xml = @file_get_contents($scanned_file);
881 if ($ims_manifest_xml !== false){
882 $import_path = implode(DIRECTORY_SEPARATOR, $manifest_array) . DIRECTORY_SEPARATOR;
886 //if no imsmanifest.xml found in the entire package, throw error.
887 if ($ims_manifest_xml === false) {
888 $msg->addError('NO_IMSMANIFEST');
890 if (file_exists($import_path . 'atutor_backup_version')) {
891 $msg->addError('NO_IMS_BACKUP');
893 clr_dir($import_path);
895 if (isset($_GET['tile'])) {
896 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
898 header('Location: index.php');
903 $xml_parser = xml_parser_create();
905 xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); /* conform to W3C specs */
906 xml_set_element_handler($xml_parser, 'startElement', 'endElement');
907 xml_set_character_data_handler($xml_parser, 'characterData');
909 if (!xml_parse($xml_parser, $ims_manifest_xml, true)) {
910 die(sprintf("XML error: %s at line %d",
911 xml_error_string(xml_get_error_code($xml_parser)),
912 xml_get_current_line_number($xml_parser)));
914 xml_parser_free($xml_parser);
915 /* check if the glossary terms exist */
917 if ($content_type == 'IMS Common Cartridge'){
918 $glossary_path = 'resources/GlossaryItem/';
919 // $package_base_path = '';
921 if (file_exists($import_path . $glossary_path . 'glossary.xml')){
922 $glossary_xml = @file_get_contents($import_path.$glossary_path.'glossary.xml');
923 $element_path = array();
924 $xml_parser = xml_parser_create();
926 /* insert the glossary terms into the database (if they're not in there already) */
927 /* parse the glossary.xml file and insert the terms */
928 xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); /* conform to W3C specs */
929 xml_set_element_handler($xml_parser, 'glossaryStartElement', 'glossaryEndElement');
930 xml_set_character_data_handler($xml_parser, 'glossaryCharacterData');
932 if (!xml_parse($xml_parser, $glossary_xml, true)) {
933 die(sprintf("XML error: %s at line %d",
934 xml_error_string(xml_get_error_code($xml_parser)),
935 xml_get_current_line_number($xml_parser)));
937 xml_parser_free($xml_parser);
938 $contains_glossary_terms = true;
939 foreach ($imported_glossary as $term => $defn) {
940 if (!$glossary[$term]) {
941 $sql = "INSERT INTO ".TABLE_PREFIX."glossary VALUES (NULL, $_SESSION[course_id], '$term', '$defn', 0)";
942 mysql_query($sql, $db);
947 // Check if all the files exists in the manifest, iff it's a IMS CC package.
948 if ($content_type == 'IMS Common Cartridge') {
949 checkResources($import_path);
952 // Check if there are any errors during parsing.
953 if ($msg->containsErrors()) {
954 if (isset($_GET['tile'])) {
955 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
957 header('Location: index.php');
962 /* generate a unique new package base path based on the package file name and date as needed. */
963 /* the package name will be the dir where the content for this package will be put, as a result */
964 /* the 'content_path' field in the content table will be set to this path. */
965 /* $package_base_name_url comes from the URL file name (NOT the file name of the actual file we open)*/
966 if (!$package_base_name && $package_base_name_url) {
967 $package_base_name = substr($package_base_name_url, -6);
968 } else if (!$package_base_name) {
969 $package_base_name = substr($_FILES['file']['name'], 0, -4);
972 $package_base_name = strtolower($package_base_name);
973 $package_base_name = str_replace(array('\'', '"', ' ', '|', '\\', '/', '<', '>', ':'), '_' , $package_base_name);
974 $package_base_name = preg_replace("/[^A-Za-z0-9._\-]/", '', $package_base_name);
976 if (is_dir(AT_CONTENT_DIR . $_SESSION['course_id'].'/'.$package_base_name)) {
977 $package_base_name .= '_'.date('ymdHis');
980 if ($package_base_path) {
981 $package_base_path = implode('/', $package_base_path);
982 } elseif (empty($package_base_path)){
983 $package_base_path = '';
986 if ($xml_base_path) {
987 $package_base_path = $xml_base_path . $package_base_path;
989 mkdir(AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$xml_base_path);
990 $package_base_name = $xml_base_path . $package_base_name;
993 /* get the top level content ordering offset */
994 $sql = "SELECT MAX(ordering) AS ordering FROM ".TABLE_PREFIX."content WHERE course_id=$_SESSION[course_id] AND content_parent_id=$cid";
995 $result = mysql_query($sql, $db);
996 $row = mysql_fetch_assoc($result);
997 $order_offset = intval($row['ordering']); /* it's nice to have a real number to deal with */
998 $lti_offset = array(); //since we don't need lti tools, the ordering needs to be subtracted
999 //reorder the items stack
1000 $common_path = removeCommonPath($items);
1001 $items = rehash($items);
1002 //debug($items);exit;
1003 foreach ($items as $item_id => $content_info)
1005 //formatting field, default 1
1006 $content_formatting = 1; //CONTENT_TYPE_CONTENT
1008 //don't want to display glossary as a page
1009 if ($content_info['href']== $glossary_path . 'glossary.xml'){
1013 //if discussion tools, add it to the list of unhandled dts
1014 if ($content_info['type']=='imsdt_xmlv1p0'){
1015 //if it will be taken care after (has dependency), then move along.
1016 if (in_array($item_id, $avail_dt)){
1017 $lti_offset[$content_info['parent_content_id']]++;
1022 //handle the special case of cc import, where there is no content association. The resource should
1023 //still be imported.
1024 if(!isset($content_info['parent_content_id'])){
1025 //if this is a question bank
1026 if ($content_info['type']=="imsqti_xmlv1p2/imscc_xmlv1p0/question-bank"){
1027 addQuestions($content_info['href'], $content_info, $import_path);
1031 //if it has no title, most likely it is not a page but just a normal item, skip it
1032 if (!isset($content_info['title'])){
1036 //check dependency immediately, then handles it
1038 if (is_array($content_info['dependency']) && !empty($content_info['dependency'])){
1039 foreach($content_info['dependency'] as $dependency_ref){
1041 /** handled by get_html_head in vitals.inc.php
1042 if (preg_match('/(.*)\.css$/', $items[$dependency_ref]['href'])){
1043 //calculate where this is based on our current base_href.
1044 //assuming the dependency folders are siblings of the item
1045 $head = '<link rel="stylesheet" type="text/css" href="../'.$items[$dependency_ref]['href'].'" />';
1048 //check if this is a discussion tool dependency
1049 if ($items[$dependency_ref]['type']=='imsdt_xmlv1p0'){
1050 $items[$item_id]['forum'][$dependency_ref] = $items[$dependency_ref]['href'];
1052 //check if this is a QTI dependency
1053 if (strpos($items[$dependency_ref]['type'], 'imsqti_xmlv1p2/imscc_xmlv1p0') !== false){
1054 $items[$item_id]['tests'][$dependency_ref] = $items[$dependency_ref]['href'];
1059 //check file array, see if there are css.
1060 //edited nov 26, harris
1061 //removed cuz i added link to the html_tags
1063 if (is_array($content_info['file']) && !empty($content_info['file'])){
1064 foreach($content_info['file'] as $dependency_ref){
1066 if (preg_match('/(.*)\.css$/', $dependency_ref)){
1067 //calculate where this is based on our current base_href.
1068 //assuming the dependency folders are siblings of the item
1069 $head = '<link rel="stylesheet" type="text/css" href="'.$dependency_ref.'" />';
1076 if (preg_match('/^http.*:\/\//', trim($content_info['href'])) )
1078 $content = '<a href="'.$content_info['href'].'" target="_blank">'.$content_info['title'].'</a>';
1082 if ($content_type == 'IMS Common Cartridge'){
1083 //to handle import with purely images but nothing else
1084 //don't need a content base path for it.
1085 $content_new_path = $content_info['new_path'];
1086 $content_info['new_path'] = '';
1088 if (isset($content_info['href'], $xml_base_path)) {
1089 $content_info['href'] = $xml_base_path . $content_info['href'];
1091 if (!isset($content_info['href'])) {
1092 // this item doesn't have an identifierref. so create an empty page.
1093 // what we called a folder according to v1.2 Content Packaging spec
1097 $last_modified = date('Y-m-d H:i:s');
1099 //$file_info = @stat(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1100 $file_info = @stat($import_path.$content_info['href']);
1101 if ($file_info === false) {
1105 //$path_parts = pathinfo(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1106 $path_parts = pathinfo($import_path.$content_info['href']);
1107 $ext = strtolower($path_parts['extension']);
1109 $last_modified = date('Y-m-d H:i:s', $file_info['mtime']);
1111 if (in_array($ext, array('gif', 'jpg', 'bmp', 'png', 'jpeg'))) {
1112 /* this is an image */
1113 $content = '<img src="'.$content_info['href'].'" alt="'.$content_info['title'].'" />';
1114 } else if ($ext == 'swf') {
1116 /* Using default size of 550 x 400 */
1118 $content = '<object type="application/x-shockwave-flash" data="' . $content_info['href'] . '" width="550" height="400"><param name="movie" value="'. $content_info['href'] .'" /></object>';
1120 } else if ($ext == 'mov') {
1121 /* this is a quicktime movie */
1122 /* Using default size of 550 x 400 */
1124 $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>';
1127 * commenting this whole chunk out. It's part of my test import codes, not sure why it's here,
1128 * and I don't think it should be here. Remove this whole comment after further testing and confirmation.
1131 //Mimic the array for now.
1132 $test_attributes['resource']['href'] = $test_xml_file;
1133 $test_attributes['resource']['type'] = isset($items[$item_id]['type'])?'imsqti_xmlv1p2':'imsqti_xmlv1p1';
1134 $test_attributes['resource']['file'] = $items[$item_id]['file'];
1135 // $test_attributes['resource']['file'] = array($test_xml_file);
1137 //Get the XML file out and start importing them into our database.
1138 //TODO: See question_import.php 287-289.
1139 $qids = $qti_import->importQuestions($test_attributes);
1142 } else if ($ext == 'mp3') {
1143 $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>';
1144 } else if (in_array($ext, array('wav', 'au'))) {
1145 $content = '<embed SRC="'.$content_info['href'].'" autostart="false" width="145" height="60"><noembed><bgsound src="'.$content_info['href'].'"></noembed></embed>';
1147 } else if (in_array($ext, array('txt', 'css', 'html', 'htm', 'csv', 'asc', 'tsv', 'xml', 'xsl'))) {
1148 if ($content_type == 'IMS Common Cartridge'){
1149 $content_info['new_path'] = $content_new_path;
1152 /* this is a plain text file */
1153 //$content = file_get_contents(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1154 $content = file_get_contents($import_path.$content_info['href']);
1155 if ($content === false) {
1156 /* if we can't stat() it then we're unlikely to be able to read it */
1157 /* so we'll never get here. */
1161 // get the contents of the 'head' element
1162 $head .= get_html_head_by_tag($content, $html_head_tags);
1164 // Specifically handle eXe package
1165 // NOTE: THIS NEEDS WORK! TO FIND A WAY APPLY EXE .CSS FILES ONLY ON COURSE CONTENT PART.
1166 // NOW USE OUR OWN .CSS CREATED SOLELY FOR EXE
1167 $isExeContent = false;
1169 // check xml file in eXe package
1170 if (preg_match("/<organization[ ]*identifier=\"eXe*>*/", $ims_manifest_xml))
1172 $isExeContent = true;
1175 // use ATutor's eXe style sheet as the ones from eXe conflicts with ATutor's style sheets
1178 $head = preg_replace ('/(<style.*>)(.*)(<\/style>)/ms', '\\1@import url(/docs/exestyles.css);\\3', $head);
1181 // end of specifically handle eXe package
1183 $content = get_html_body($content);
1184 if ($contains_glossary_terms)
1186 // replace glossary content package links to real glossary mark-up using [?] [/?]
1187 // refer to bug 3641, edited by Harris
1188 $content = preg_replace('/<a href="([.\w\d\s]+[^"]+)" target="body" class="at-term">([.\w\d\s&;"]+|.*)<\/a>/i', '[?]\\2[/?]', $content);
1191 /* potential security risk? */
1192 if ( strpos($content_info['href'], '..') === false && !preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $content_info['href'])) {
1193 // @unlink(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1196 /* overwrite content if this is discussion tool. */
1197 if ($content_info['type']=='imsdt_xmlv1p0'){
1198 $dt_parser = new DiscussionToolsParser();
1199 $xml_content = @file_get_contents($import_path . $content_info['href']);
1200 $dt_parser->parse($xml_content);
1201 $forum_obj = $dt_parser->getDt();
1202 $content = $forum_obj->getText();
1204 $dt_parser->close();
1207 /* non text file, and can't embed (example: PDF files) */
1208 $content = '<a href="'.$content_info['href'].'">'.$content_info['title'].'</a>';
1211 $content_parent_id = $cid;
1212 if ($content_info['parent_content_id'] !== 0) {
1213 $content_parent_id = $items[$content_info['parent_content_id']]['real_content_id'];
1214 //if it's not there, use $cid
1215 if (!$content_parent_id){
1216 $content_parent_id = $cid;
1221 if ($content_parent_id == $cid) {
1222 $my_offset = $order_offset;
1225 /* replace the old path greatest common denomiator with the new package path. */
1226 /* we don't use str_replace, b/c there's no knowing what the paths may be */
1227 /* we only want to replace the first part of the path.
1229 if(is_array($all_package_base_path)){
1230 $all_package_base_path = implode('/', $all_package_base_path);
1232 if ($common_path != '') {
1233 $content_info['new_path'] = $package_base_name . substr($content_info['new_path'], strlen($common_path));
1235 $content_info['new_path'] = $package_base_name . '/' . $content_info['new_path'];
1239 if ($content_info['type']=='imswl_xmlv1p0'){
1240 $weblinks_parser = new WeblinksParser();
1241 $xml_content = @file_get_contents($import_path . $content_info['href']);
1242 $weblinks_parser->parse($xml_content);
1243 $content_info['title'] = $weblinks_parser->getTitle();
1244 $content = $weblinks_parser->getUrl();
1245 $content_folder_type = CONTENT_TYPE_WEBLINK;
1246 $content_formatting = 2;
1248 $head = addslashes($head);
1249 $content_info['title'] = addslashes($content_info['title']);
1250 $content_info['test_message'] = addslashes($content_info['test_message']);
1252 //if this file is a test_xml, create a blank page instead, for imscc.
1253 if (preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $content_info['href'])
1254 || preg_match('/imsqti\_(.*)/', $content_info['type'])) {
1257 $content = addslashes($content);
1260 //check for content_type
1261 if ($content_formatting!=CONTENT_TYPE_WEBLINK){
1262 $content_folder_type = (!isset($content_info['type'])?CONTENT_TYPE_FOLDER:CONTENT_TYPE_CONTENT);
1265 $sql= 'INSERT INTO '.TABLE_PREFIX.'content'
1274 use_customized_head,
1282 ('.$_SESSION['course_id'].','
1283 .intval($content_parent_id).','
1284 .($content_info['ordering'] + $my_offset - $lti_offset[$content_info['parent_content_id']] + 1).','
1285 .'"'.$last_modified.'",
1287 .$content_formatting.' ,
1292 .'"'.$content_info['new_path'].'",'
1293 .'"'.$content_info['title'].'",'
1295 .'"'.$content_info['test_message'].'",'
1296 .$content_folder_type.')';
1298 $result = mysql_query($sql, $db) or die(mysql_error());
1300 /* get the content id and update $items */
1301 $items[$item_id]['real_content_id'] = mysql_insert_id($db);
1303 /* get the tests associated with this content */
1304 if (!empty($items[$item_id]['tests']) || strpos($items[$item_id]['type'], 'imsqti_xmlv1p2/imscc_xmlv1p0') !== false){
1305 $qti_import = new QTIImport($import_path);
1306 if (isset($items[$item_id]['tests'])){
1307 $loop_var = $items[$item_id]['tests'];
1309 $loop_var = $items[$item_id]['file'];
1312 foreach ($loop_var as $array_id => $test_xml_file){
1313 //check if this item is the qti item object, or it is the content item obj
1314 //switch it to qti obj if it's content item obj
1315 if ($items[$item_id]['type'] == 'webcontent'){
1316 $item_qti = $items[$array_id];
1318 $item_qti = $items[$item_id];
1320 //call subrountine to add the questions.
1321 $qids = addQuestions($test_xml_file, $item_qti, $import_path);
1324 if ($test_title==''){
1325 $test_title = $content_info['title'];
1328 $tid = $qti_import->importTest($test_title);
1330 //associate question and tests
1331 foreach ($qids as $order=>$qid){
1332 if (isset($qti_import->weights[$order])){
1333 $weight = round($qti_import->weights[$order]);
1337 $new_order = $order + 1;
1338 $sql = "INSERT INTO " . TABLE_PREFIX . "tests_questions_assoc" .
1339 "(test_id, question_id, weight, ordering, required) " .
1340 "VALUES ($tid, $qid, $weight, $new_order, 0)";
1341 $result = mysql_query($sql, $db);
1344 //associate content and test
1345 $sql = 'INSERT INTO ' . TABLE_PREFIX . 'content_tests_assoc' .
1346 '(content_id, test_id) ' .
1347 'VALUES (' . $items[$item_id]['real_content_id'] . ", $tid)";
1348 $result = mysql_query($sql, $db);
1350 // if (!$msg->containsErrors()) {
1351 // $msg->addFeedback('IMPORT_SUCCEEDED');
1356 /* get the a4a related xml */
1357 if (isset($items[$item_id]['a4a_import_enabled']) && isset($items[$item_id]['a4a']) && !empty($items[$item_id]['a4a'])) {
1358 $a4a_import = new A4aImport($items[$item_id]['real_content_id']);
1359 $a4a_import->setRelativePath($items[$item_id]['new_path']);
1360 $a4a_import->importA4a($items[$item_id]['a4a']);
1363 /* get the discussion tools (dependent to content)*/
1364 if (isset($items[$item_id]['forum']) && !empty($items[$item_id]['forum'])){
1365 foreach($items[$item_id]['forum'] as $forum_ref => $forum_link){
1366 $dt_parser = new DiscussionToolsParser();
1367 $dt_import = new DiscussionToolsImport();
1369 //if this forum has not been added, parse it and add it.
1370 if (!isset($added_dt[$forum_ref])){
1371 $xml_content = @file_get_contents($import_path . $forum_link);
1372 $dt_parser->parse($xml_content);
1373 $forum_obj = $dt_parser->getDt();
1374 $dt_import->import($forum_obj, $items[$item_id]['real_content_id']);
1375 $added_dt[$forum_ref] = $dt_import->getFid();
1377 //associate the fid and content id
1378 $dt_import->associateForum($items[$item_id]['real_content_id'], $added_dt[$forum_ref]);
1380 } elseif ($items[$item_id]['type']=='imsdt_xmlv1p0'){
1381 //optimize this, repeated codes as above
1382 $dt_parser = new DiscussionToolsParser();
1383 $dt_import = new DiscussionToolsImport();
1384 $xml_content = @file_get_contents($import_path . $content_info['href']);
1385 $dt_parser->parse($xml_content);
1386 $forum_obj = $dt_parser->getDt();
1387 $dt_import->import($forum_obj, $items[$item_id]['real_content_id']);
1388 $added_dt[$item_id] = $dt_import->getFid();
1390 //associate the fid and content id
1391 $dt_import->associateForum($items[$item_id]['real_content_id'], $added_dt[$item_id]);
1395 if ($package_base_path == '.') {
1396 $package_base_path = '';
1399 // loop through the files outside the package folder, and copy them to its relative path
1401 if (is_dir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources')) {
1402 $handler = opendir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources');
1403 while ($file = readdir($handler)){
1404 $filename = AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources/'.$file;
1406 if(is_file($filename)){
1407 @rename($filename, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name.'/'.$file);
1413 //--- harris edit for path thing
1414 $file = AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].DIRECTORY_SEPARATOR.$common_path;
1415 if (is_dir($file)) {
1416 rename($file, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name);
1419 //takes care of the condition where the whole package doesn't have any contents but question banks
1420 //also is the case of urls
1421 if(is_array($all_package_base_path)){
1422 $all_package_base_path = implode('/', $all_package_base_path);
1423 if(strpos($all_package_base_path, 'http:/')===false){
1424 if (@rename($import_path.$all_package_base_path, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name) === false) {
1425 if (!$msg->containsErrors()) {
1426 $msg->addError('IMPORT_FAILED');
1432 //check if there are still resources missing
1434 foreach($items as $idetails){
1435 $temp_path = pathinfo($idetails['href']);
1436 @rename(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$temp_path['dirname'], AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name . '/' . $temp_path['dirname']);
1439 clr_dir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id']);
1441 if (file_exists($full_filename)) {
1442 @unlink($full_filename);
1446 if ($_POST['s_cid']){
1447 if (!$msg->containsErrors()) {
1448 $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
1450 header('Location: ../editor/edit_content.php?cid='.intval($_POST['cid']));
1453 if (!$msg->containsErrors()) {
1454 $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
1456 if ($_GET['tile']) {
1457 header('Location: '.AT_BASE_HREF.'mods/_standard/tile_search/index.php');
1459 header('Location: ./index.php?cid='.intval($_POST['cid']));