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 /************************************************************************/
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'].
274 * This allows import/export repeatedly without duplicating its path
275 * @param array contains the breakdown of all resources in the XML
277 function removeCommonPath($items){
279 $quit = false; //a flag that is set if it's not the first time being run.
281 $filearray = array();
282 //get all files listed in the manifest
283 foreach($items as $name=>$fileinfo){
284 if(isset($fileinfo['file']) && is_array($fileinfo['file']) && !empty($fileinfo['file'])){
285 foreach($fileinfo['file'] as $fn){
286 if (!in_array($fn, $filearray)){
287 if (preg_match('/^http[s]?\:/', $fn) == 0){
295 foreach($filearray as $index=>$path){
297 //check if this is a XML file; if so, skip through,
298 //cause XML most likely isn't a content resource.
299 $ext = substr($path, (strrpos($path, '.')+1));
304 //if common path is empty, assign the first path to it.
305 if ($common_path=='' && $quit==false){
306 $common_path = $path;
307 $quit = true; //the next time common_path is empty, quit;
310 //we use '/' here instead of DIRECTORY_SEPARATOR because php would
311 //actually use '\' and return the whole string.
312 $common_array = explode('/', $common_path);
313 $path_array = explode('/', $path);
314 $intersect_array = array_intersect($common_array, $path_array);
315 $common_path = implode('/', $intersect_array);
322 * This function will take the test accessment XML and add these to the database.
323 * @param string The path of the XML, without the import_path.
324 * @param mixed An item singleton. Contains the info of this item, namely, the accessment details.
325 * The item must be an object created by the ims class.
326 * @param string the import path
327 * @return mixed An Array that contains all the question IDs that have been imported.
329 function addQuestions($xml, $item, $import_path){
331 $qti_import = new QTIImport($import_path);
332 $tests_xml = $import_path.$xml;
334 //Mimic the array for now.
335 $test_attributes['resource']['href'] = $item['href'];
336 $test_attributes['resource']['type'] = preg_match('/imsqti_xmlv1p2/', $item['type'])==1?'imsqti_xmlv1p2':'imsqti_xmlv1p1';
337 $test_attributes['resource']['file'] = $item['file'];
339 //Get the XML file out and start importing them into our database.
340 //TODO: See question_import.php 287-289.
341 $qids = $qti_import->importQuestions($test_attributes);
342 $test_title = $qti_import->title;
348 /* called at the start of en element */
349 /* builds the $path array which is the path from the root to the current element */
350 function startElement($parser, $name, $attrs) {
351 global $items, $path, $package_base_path, $all_package_base_path, $package_real_base_path;
352 global $element_path, $import_path, $skip_ims_validation;
353 global $xml_base_path, $test_message, $content_type;
354 global $current_identifier, $msg, $ns, $ns_cp;
356 //check if the xml is valid
358 if(isset($attrs['xsi:schemaLocation']) && $name == 'manifest'){
359 //run the loop and check it thru the ns.inc.php
360 } elseif ($name == 'manifest' && !isset($attrs['xsi:schemaLocation'])) {
361 //$msg->addError('MANIFEST_NOT_WELLFORM: NO NAMESPACE');
362 $msg->addError('IMPORT_CARTRIDGE_FAILED');
366 //error if the tag names are wrong
367 if (preg_match('/^xsi\:/', $name) >= 1){
368 //$msg->addError('MANIFEST_NOT_WELLFORM');
369 $msg->addError('IMPORT_CARTRIDGE_FAILED');
373 //validate namespaces
374 if(!$skip_ims_validation && isset($attrs['xsi:schemaLocation']) && $name=='manifest'){
375 $schema_location = array();
376 $split_location = preg_split('/[\r\n\s]+/', trim($attrs['xsi:schemaLocation']));
378 //check if the namespace is actually right, have an array or some sort in IMS class
379 if(sizeof($split_location)%2==1){
380 //schema is not in the form of "The first URI reference in each pair is a namespace name,
381 //and the second is the location of a schema that describes that namespace."
382 //$msg->addError('MANIFEST_NOT_WELLFORM');
383 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('schema_error')));
386 //turn the xsi:schemaLocation URI into a schema that describe namespace.
388 //http://msdn.microsoft.com/en-us/library/ms256100(VS.85).aspx
389 //http://www.w3.org/TR/xmlschema-1/
390 for($i=0; $i < sizeof($split_location);$i=$i+2){
392 if (isset($ns[$split_location[$i]]) && $ns[$split_location[$i]] != $split_location[$i+1]){
393 //$msg->addError('MANIFEST_NOT_WELLFORM: SCHEMA');
394 $msg->addError('IMPORT_CARTRIDGE_FAILED');
397 //if the key of the namespace is not defined. Throw error.
398 if(!isset($ns[$split_location[$i]]) && !isset($ns_cp[$split_location[$i]])){
399 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('schema_error')));
406 if ($name == 'manifest' && isset($attrs['xml:base']) && $attrs['xml:base']) {
407 $xml_base_path = $attrs['xml:base'];
408 } else if ($name == 'file') {
409 // check if it misses file references
410 if(!$skip_ims_validation && (!isset($attrs['href']) || $attrs['href']=='')){
411 //$msg->addError('MANIFEST_NOT_WELLFORM');
412 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT('ims_missing_references')));
415 // special case for webCT content packages that don't specify the `href` attribute
416 // with the `<resource>` element.
417 // we take the `href` from the first `<file>` element.
418 if (isset($items[$current_identifier]) && ($items[$current_identifier]['href'] == '')) {
419 $attrs['href'] = urldecode($attrs['href']);
420 $items[$current_identifier]['href'] = $attrs['href'];
423 $temp_path = pathinfo($attrs['href']);
424 $temp_path = explode('/', $temp_path['dirname']);
425 if (empty($package_base_path)){
426 $package_base_path = $temp_path;
428 if ($all_package_base_path!='' && empty($all_package_base_path)){
429 $all_package_base_path = $temp_path;
431 $package_base_path = array_intersect_assoc($package_base_path, $temp_path);
433 //calculate the depths of relative paths
434 if ($all_package_base_path!=''){
435 $no_relative_temp_path = $temp_path;
436 foreach($no_relative_temp_path as $path_node){
437 if ($path_node=='..'){
438 array_pop($no_relative_temp_path);
439 array_pop($no_relative_temp_path); //not a typo, have to pop twice, both itself('..'), and the one before.
442 $all_package_base_path = array_intersect_assoc($all_package_base_path, $no_relative_temp_path);
443 if (empty($all_package_base_path)){
444 $all_package_base_path = ''; //unset it, there is no intersection.
448 //save the actual content base path
449 if (in_array('..', $temp_path)){
450 $sizeofrp = array_count_values($temp_path);
453 //for IMSCC, assume that all resources lies in the same folder, except styles.css
454 if ($items[$current_identifier]['type']=='webcontent' || $items[$current_identifier]['type']=='imsdt_xmlv1p0'){
455 //find the intersection of each item's related files, then that intersection is the content_path
456 if (isset($items[$current_identifier]['file'])){
457 foreach ($items[$current_identifier]['file'] as $resource_path){
458 $temp_path = pathinfo($resource_path);
459 $temp_path = explode('/', $temp_path['dirname']);
460 $package_base_path = array_intersect_assoc($package_base_path, $temp_path);
466 if($sizeofrp['..'] > 0 && !empty($all_package_base_path)){
467 for ($i=0; $i<$sizeofrp['..']; $i++){
468 array_pop($all_package_base_path);
472 if (count($package_base_path) > 0) {
473 $items[$current_identifier]['new_path'] = implode('/', $package_base_path);
477 * @harris, reworked the package_base_path
478 if ($package_base_path=="") {
479 $package_base_path = $temp_path;
481 elseif (is_array($package_base_path) && $content_type != 'IMS Common Cartridge') {
482 //if this is a content package, we want only intersection
483 $package_base_path = array_intersect($package_base_path, $temp_path);
484 $temp_path = $package_base_path;
486 //added these 2 lines in so that pictures would load. making the elseif above redundant.
487 //if there is a bug for pictures not load, then it's the next 2 lines.
488 $package_base_path = array_intersect($package_base_path, $temp_path);
489 $temp_path = $package_base_path;
491 $items[$current_identifier]['new_path'] = implode('/', $temp_path);
493 if ( isset($_POST['allow_test_import']) && isset($items[$current_identifier])
494 && preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $attrs['href'])) {
495 $items[$current_identifier]['tests'][] = $attrs['href'];
497 if ( isset($_POST['allow_a4a_import']) && isset($items[$current_identifier])) {
498 $items[$current_identifier]['a4a_import_enabled'] = true;
500 } else if (($name == 'item') && ($attrs['identifierref'] != '')) {
501 $path[] = $attrs['identifierref'];
502 } else if (($name == 'item') && ($attrs['identifier'])) {
503 $path[] = $attrs['identifier'];
504 // } else if (($name == 'resource') && is_array($items[$attrs['identifier']])) {
505 } else if (($name == 'resource')) {
506 $current_identifier = $attrs['identifier'];
507 $items[$current_identifier]['type'] = $attrs['type'];
508 if ($attrs['href']) {
509 $attrs['href'] = urldecode($attrs['href']);
511 $items[$attrs['identifier']]['href'] = $attrs['href'];
513 // href points to a remote url
514 if (preg_match('/^http.*:\/\//', trim($attrs['href']))) {
515 $items[$attrs['identifier']]['new_path'] = '';
516 } else // href points to local file
518 $temp_path = pathinfo($attrs['href']);
519 $temp_path = explode('/', $temp_path['dirname']);
520 // if (empty($package_base_path)) {
521 $package_base_path = $temp_path;
524 // $package_base_path = array_intersect($package_base_path, $temp_path);
526 $items[$attrs['identifier']]['new_path'] = implode('/', $temp_path);
530 //if test custom message has not been saved
531 // if (!isset($items[$current_identifier]['test_message'])){
532 // $items[$current_identifier]['test_message'] = $test_message;
534 } else if ($name=='dependency' && $attrs['identifierref']!='') {
535 //if there is a dependency, attach it to the item array['file']
536 $items[$current_identifier]['dependency'][] = $attrs['identifierref'];
538 if (($name == 'item') && ($attrs['parameters'] != '')) {
539 $items[$attrs['identifierref']]['test_message'] = $attrs['parameters'];
542 if(!isset($items[$current_identifier]) && $attrs['href']!=''){
543 $items[$current_identifier]['href'] = $attrs['href'];
545 if (substr($attrs['href'], 0, 7) == 'http://' || substr($attrs['href'], 0, 8) == 'https://' || file_exists($import_path.$attrs['href']) || $skip_ims_validation){
546 $items[$current_identifier]['file'][] = $attrs['href'];
548 $msg->addError(array('IMPORT_CARTRIDGE_FAILED', _AT(array('ims_files_missing', $attrs['href']))));
551 if ($name=='cc:authorizations'){
552 //don't have authorization setup.
553 //$msg->addError('');
554 $msg->addError('IMS_AUTHORIZATION_NOT_SUPPORT');
556 array_push($element_path, $name);
559 /* called when an element ends */
560 /* removed the current element from the $path */
561 function endElement($parser, $name) {
562 global $path, $element_path, $my_data, $items;
563 global $current_identifier, $skip_ims_validation;
564 global $msg, $content_type;
565 static $resource_num = 0;
567 if ($name == 'item') {
571 //check if this is a test import
572 if ($name == 'schema'){
573 if (trim($my_data)=='IMS Question and Test Interoperability'){
574 $msg->addError('IMPORT_FAILED');
576 $content_type = trim($my_data);
580 if ($current_identifier != ''){
581 $my_data = trim($my_data);
582 $last_file_name = $items[$current_identifier]['file'][(sizeof($items[$current_identifier]['file']))-1];
584 if ($name=='originalAccessMode'){
585 if (in_array('accessModeStatement', $element_path)){
586 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['access_stmt_originalAccessMode'] = $my_data;
587 } elseif (in_array('adaptationStatement', $element_path)){
588 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['adapt_stmt_originalAccessMode'] = $my_data;
590 } elseif (($name=='language') && in_array('accessModeStatement', $element_path)){
591 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['language'][] = $my_data;
592 } elseif ($name=='hasAdaptation') {
593 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['hasAdaptation'][] = $my_data;
594 } elseif ($name=='isAdaptationOf'){
595 $items[$current_identifier]['a4a'][$last_file_name][$resource_num]['isAdaptationOf'][] = $my_data;
596 } elseif ($name=='accessForAllResource'){
597 /* the head node of accessForAll Metadata, if this exists in the manifest. Skip XSD validation,
598 * because A4a doesn't have a xsd yet. Our access for all is based on ISO which will not pass
599 * the current IMS validation.
600 * Also, since ATutor is the only one (as of Oct 21, 2009) that exports IMS with access for all
601 * content, we can almost assume that any ims access for all content is by us, and is valid.
603 $skip_ims_validation = true;
605 } elseif($name=='file'){
606 $resource_num = 0; //reset resournce number to 0 when the file tags ends
610 if ($element_path === array('manifest', 'metadata', 'imsmd:lom', 'imsmd:general', 'imsmd:title', 'imsmd:langstring')) {
611 global $package_base_name;
612 $package_base_name = trim($my_data);
615 array_pop($element_path);
619 /* called when there is character data within elements */
620 /* constructs the $items array using the last entry in $path as the parent element */
621 function characterData($parser, $data){
622 global $path, $items, $order, $my_data, $element_path;
623 global $current_identifier;
625 $str_trimmed_data = trim($data);
627 if (!empty($str_trimmed_data)) {
628 $size = count($path);
630 $current_item_id = $path[$size-1];
632 $parent_item_id = $path[$size-2];
637 if (isset($items[$current_item_id]['parent_content_id']) && is_array($items[$current_item_id])) {
639 /* this item already exists, append the title */
640 /* this fixes {\n, \t, `, &} characters in elements */
642 /* horible kludge to fix the <ns2:objectiveDesc xmlns:ns2="http://www.utoronto.ca/atrc/tile/xsd/tile_objective"> */
644 if (in_array('accessForAllResource', $element_path)){
646 } elseif ($element_path[count($element_path)-1] != 'ns1:objectiveDesc') {
647 $items[$current_item_id]['title'] .= $data;
651 $order[$parent_item_id] ++;
652 $item_tmpl = array( 'title' => $data,
653 'parent_content_id' => $parent_item_id,
654 'ordering' => $order[$parent_item_id]-1);
655 //append other array values if it exists
656 if (is_array($items[$current_item_id])){
657 $items[$current_item_id] = array_merge($items[$current_item_id], $item_tmpl);
659 $items[$current_item_id] = $item_tmpl;
668 /* glossary parser: */
669 function glossaryStartElement($parser, $name, $attrs) {
670 global $element_path;
672 array_push($element_path, $name);
675 /* called when an element ends */
676 /* removed the current element from the $path */
677 function glossaryEndElement($parser, $name) {
678 global $element_path, $my_data, $imported_glossary;
679 static $current_term;
681 if ($element_path === array('glossary', 'item', 'term') ||
682 $element_path === array('glossary:glossary', 'item', 'term')) {
683 $current_term = $my_data;
685 } else if ($element_path === array('glossary', 'item', 'definition') ||
686 $element_path === array('glossary:glossary', 'item', 'definition')) {
687 $imported_glossary[trim($current_term)] = trim($my_data);
690 array_pop($element_path);
694 function glossaryCharacterData($parser, $data){
700 if (!isset($_POST['submit']) && !isset($_POST['cancel'])) {
701 /* just a catch all */
703 $errors = array('FILE_MAX_SIZE', ini_get('post_max_size'));
704 $msg->addError($errors);
706 header('Location: ./index.php');
708 } else if (isset($_POST['cancel'])) {
709 $msg->addFeedback('IMPORT_CANCELLED');
711 header('Location: ../content/index.php');
715 $cid = intval($_POST['cid']);
717 //If user chooses to ignore validation.
718 if(isset($_POST['ignore_validation']) && $_POST['ignore_validation']==1) {
719 $skip_ims_validation = true;
722 if (isset($_POST['url']) && ($_POST['url'] != 'http://') ) {
723 if ($content = @file_get_contents($_POST['url'])) {
724 // save file to /content/
725 $filename = substr(time(), -6). '.zip';
726 $full_filename = AT_CONTENT_DIR . $filename;
728 if (!$fp = fopen($full_filename, 'w+b')) {
729 echo "Cannot open file ($filename)";
733 if (fwrite($fp, $content, strlen($content) ) === FALSE) {
734 echo "Cannot write to file ($filename)";
739 $_FILES['file']['name'] = $filename;
740 $_FILES['file']['tmp_name'] = $full_filename;
741 $_FILES['file']['size'] = strlen($content);
743 $url_parts = pathinfo($_POST['url']);
744 $package_base_name_url = $url_parts['basename'];
746 $ext = pathinfo($_FILES['file']['name']);
747 $ext = $ext['extension'];
750 $msg->addError('IMPORTDIR_IMS_NOTVALID');
751 } else if ($_FILES['file']['error'] == 1) {
752 $errors = array('FILE_MAX_SIZE', ini_get('upload_max_filesize'));
753 $msg->addError($errors);
754 } else if ( !$_FILES['file']['name'] || (!is_uploaded_file($_FILES['file']['tmp_name']) && !$_POST['url'])) {
755 $msg->addError('FILE_NOT_SELECTED');
756 } else if ($_FILES['file']['size'] == 0) {
757 $msg->addError('IMPORTFILE_EMPTY');
760 if ($msg->containsErrors()) {
761 if (isset($_GET['tile'])) {
762 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
764 header('Location: index.php');
769 /* check if ../content/import/ exists */
770 $import_path = AT_CONTENT_DIR . 'import/';
771 $content_path = AT_CONTENT_DIR;
773 if (!is_dir($import_path)) {
774 if (!@mkdir($import_path, 0700)) {
775 $msg->addError('IMPORTDIR_FAILED');
779 $import_path .= $_SESSION['course_id'].'/';
780 if (is_dir($import_path)) {
781 clr_dir($import_path);
784 if (!@mkdir($import_path, 0700)) {
785 $msg->addError('IMPORTDIR_FAILED');
788 if ($msg->containsErrors()) {
789 if (isset($_GET['tile'])) {
790 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
792 header('Location: index.php');
797 /* extract the entire archive into AT_COURSE_CONTENT . import/$course using the call back function to filter out php files */
799 $archive = new PclZip($_FILES['file']['tmp_name']);
800 if ($archive->extract( PCLZIP_OPT_PATH, $import_path,
801 PCLZIP_CB_PRE_EXTRACT, 'preImportCallBack') == 0) {
802 $msg->addError('IMPORT_FAILED');
803 echo 'Error : '.$archive->errorInfo(true);
804 clr_dir($import_path);
805 header('Location: index.php');
808 error_reporting(AT_ERROR_REPORTING);
810 /* get the course's max_quota */
811 $sql = "SELECT max_quota FROM ".TABLE_PREFIX."courses WHERE course_id=$_SESSION[course_id]";
812 $result = mysql_query($sql, $db);
813 $q_row = mysql_fetch_assoc($result);
815 if ($q_row['max_quota'] != AT_COURSESIZE_UNLIMITED) {
817 if ($q_row['max_quota'] == AT_COURSESIZE_DEFAULT) {
818 $q_row['max_quota'] = $MaxCourseSize;
820 $totalBytes = dirsize($import_path);
821 $course_total = dirsize(AT_CONTENT_DIR . $_SESSION['course_id'].'/');
822 $total_after = $q_row['max_quota'] - $course_total - $totalBytes + $MaxCourseFloat;
824 if ($total_after < 0) {
825 /* remove the content dir, since there's no space for it */
826 $errors = array('NO_CONTENT_SPACE', number_format(-1*($total_after/AT_KBYTE_SIZE), 2 ) );
827 $msg->addError($errors);
829 clr_dir($import_path);
831 if (isset($_GET['tile'])) {
832 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
834 header('Location: index.php');
841 $items = array(); /* all the content pages */
842 $order = array(); /* keeps track of the ordering for each content page */
843 $path = array(); /* the hierarchy path taken in the menu to get to the current item in the manifest */
844 $dependency_files = array(); /* the file path for the dependency files */
847 $items[content_id/resource_id] = array(
849 'real_content_id' // calculated after being inserted
855 $ims_manifest_xml = @file_get_contents($import_path.'imsmanifest.xml');
856 //scan for manifest xml if it's not on the top level.
857 if ($ims_manifest_xml === false){
858 $data = rscandir($import_path);
859 $manifest_array = array();
860 foreach($data as $scanned_file){
861 $scanned_file = realpath($scanned_file);
862 //change the file string to an array
863 $this_file_array = explode(DIRECTORY_SEPARATOR, $scanned_file);
864 if(empty($manifest_array)){
865 $manifest_array = $this_file_array;
867 $manifest_array = array_intersect_assoc($this_file_array, $manifest_array);
869 if (strpos($scanned_file, 'imsmanifest')!==false){
870 $ims_manifest_xml = @file_get_contents($scanned_file);
873 if ($ims_manifest_xml !== false){
874 $import_path = implode(DIRECTORY_SEPARATOR, $manifest_array) . DIRECTORY_SEPARATOR;
878 //if no imsmanifest.xml found in the entire package, throw error.
879 if ($ims_manifest_xml === false) {
880 $msg->addError('NO_IMSMANIFEST');
882 if (file_exists($import_path . 'atutor_backup_version')) {
883 $msg->addError('NO_IMS_BACKUP');
885 clr_dir($import_path);
887 if (isset($_GET['tile'])) {
888 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
890 header('Location: index.php');
895 $xml_parser = xml_parser_create();
897 xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); /* conform to W3C specs */
898 xml_set_element_handler($xml_parser, 'startElement', 'endElement');
899 xml_set_character_data_handler($xml_parser, 'characterData');
901 if (!xml_parse($xml_parser, $ims_manifest_xml, true)) {
902 die(sprintf("XML error: %s at line %d",
903 xml_error_string(xml_get_error_code($xml_parser)),
904 xml_get_current_line_number($xml_parser)));
906 xml_parser_free($xml_parser);
907 /* check if the glossary terms exist */
909 if ($content_type == 'IMS Common Cartridge'){
910 $glossary_path = 'resources/GlossaryItem/';
911 // $package_base_path = '';
913 if (file_exists($import_path . $glossary_path . 'glossary.xml')){
914 $glossary_xml = @file_get_contents($import_path.$glossary_path.'glossary.xml');
915 $element_path = array();
916 $xml_parser = xml_parser_create();
918 /* insert the glossary terms into the database (if they're not in there already) */
919 /* parse the glossary.xml file and insert the terms */
920 xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); /* conform to W3C specs */
921 xml_set_element_handler($xml_parser, 'glossaryStartElement', 'glossaryEndElement');
922 xml_set_character_data_handler($xml_parser, 'glossaryCharacterData');
924 if (!xml_parse($xml_parser, $glossary_xml, true)) {
925 die(sprintf("XML error: %s at line %d",
926 xml_error_string(xml_get_error_code($xml_parser)),
927 xml_get_current_line_number($xml_parser)));
929 xml_parser_free($xml_parser);
930 $contains_glossary_terms = true;
931 foreach ($imported_glossary as $term => $defn) {
932 if (!$glossary[$term]) {
933 $sql = "INSERT INTO ".TABLE_PREFIX."glossary VALUES (NULL, $_SESSION[course_id], '$term', '$defn', 0)";
934 mysql_query($sql, $db);
939 // Check if all the files exists in the manifest, iff it's a IMS CC package.
940 if ($content_type == 'IMS Common Cartridge') {
941 checkResources($import_path);
944 // Check if there are any errors during parsing.
945 if ($msg->containsErrors()) {
946 if (isset($_GET['tile'])) {
947 header('Location: '.$_base_path.'mods/_standard/tile_search/index.php');
949 header('Location: index.php');
954 /* generate a unique new package base path based on the package file name and date as needed. */
955 /* the package name will be the dir where the content for this package will be put, as a result */
956 /* the 'content_path' field in the content table will be set to this path. */
957 /* $package_base_name_url comes from the URL file name (NOT the file name of the actual file we open)*/
958 if (!$package_base_name && $package_base_name_url) {
959 $package_base_name = substr($package_base_name_url, 0, -4);
960 } else if (!$package_base_name) {
961 $package_base_name = substr($_FILES['file']['name'], 0, -4);
964 $package_base_name = strtolower($package_base_name);
965 $package_base_name = str_replace(array('\'', '"', ' ', '|', '\\', '/', '<', '>', ':'), '_' , $package_base_name);
966 $package_base_name = preg_replace("/[^A-Za-z0-9._\-]/", '', $package_base_name);
968 if (is_dir(AT_CONTENT_DIR . $_SESSION['course_id'].'/'.$package_base_name)) {
969 $package_base_name .= '_'.date('ymdHis');
972 if ($package_base_path) {
973 $package_base_path = implode('/', $package_base_path);
974 } elseif (empty($package_base_path)){
975 $package_base_path = '';
978 if ($xml_base_path) {
979 $package_base_path = $xml_base_path . $package_base_path;
981 mkdir(AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$xml_base_path);
982 $package_base_name = $xml_base_path . $package_base_name;
985 /* get the top level content ordering offset */
986 $sql = "SELECT MAX(ordering) AS ordering FROM ".TABLE_PREFIX."content WHERE course_id=$_SESSION[course_id] AND content_parent_id=$cid";
987 $result = mysql_query($sql, $db);
988 $row = mysql_fetch_assoc($result);
989 $order_offset = intval($row['ordering']); /* it's nice to have a real number to deal with */
990 $lti_offset = array(); //since we don't need lti tools, the ordering needs to be subtracted
991 //reorder the items stack
992 $common_path = removeCommonPath($items);
993 $items = rehash($items);
994 //debug($items);exit;
995 foreach ($items as $item_id => $content_info)
997 //formatting field, default 1
998 $content_formatting = 1; //CONTENT_TYPE_CONTENT
1000 //don't want to display glossary as a page
1001 if ($content_info['href']== $glossary_path . 'glossary.xml'){
1005 //if discussion tools, add it to the list of unhandled dts
1006 if ($content_info['type']=='imsdt_xmlv1p0'){
1007 //if it will be taken care after (has dependency), then move along.
1008 if (in_array($item_id, $avail_dt)){
1009 $lti_offset[$content_info['parent_content_id']]++;
1014 //handle the special case of cc import, where there is no content association. The resource should
1015 //still be imported.
1016 if(!isset($content_info['parent_content_id'])){
1017 //if this is a question bank
1018 if ($content_info['type']=="imsqti_xmlv1p2/imscc_xmlv1p0/question-bank"){
1019 addQuestions($content_info['href'], $content_info, $import_path);
1023 //if it has no title, most likely it is not a page but just a normal item, skip it
1024 if (!isset($content_info['title'])){
1028 //check dependency immediately, then handles it
1030 if (is_array($content_info['dependency']) && !empty($content_info['dependency'])){
1031 foreach($content_info['dependency'] as $dependency_ref){
1033 /** handled by get_html_head in vitals.inc.php
1034 if (preg_match('/(.*)\.css$/', $items[$dependency_ref]['href'])){
1035 //calculate where this is based on our current base_href.
1036 //assuming the dependency folders are siblings of the item
1037 $head = '<link rel="stylesheet" type="text/css" href="../'.$items[$dependency_ref]['href'].'" />';
1040 //check if this is a discussion tool dependency
1041 if ($items[$dependency_ref]['type']=='imsdt_xmlv1p0'){
1042 $items[$item_id]['forum'][$dependency_ref] = $items[$dependency_ref]['href'];
1044 //check if this is a QTI dependency
1045 if (strpos($items[$dependency_ref]['type'], 'imsqti_xmlv1p2/imscc_xmlv1p0') !== false){
1046 $items[$item_id]['tests'][$dependency_ref] = $items[$dependency_ref]['href'];
1051 //check file array, see if there are css.
1052 //edited nov 26, harris
1053 //removed cuz i added link to the html_tags
1055 if (is_array($content_info['file']) && !empty($content_info['file'])){
1056 foreach($content_info['file'] as $dependency_ref){
1058 if (preg_match('/(.*)\.css$/', $dependency_ref)){
1059 //calculate where this is based on our current base_href.
1060 //assuming the dependency folders are siblings of the item
1061 $head = '<link rel="stylesheet" type="text/css" href="'.$dependency_ref.'" />';
1068 if (preg_match('/^http.*:\/\//', trim($content_info['href'])) )
1070 $content = '<a href="'.$content_info['href'].'" target="_blank">'.$content_info['title'].'</a>';
1074 if ($content_type == 'IMS Common Cartridge'){
1075 //to handle import with purely images but nothing else
1076 //don't need a content base path for it.
1077 $content_new_path = $content_info['new_path'];
1078 $content_info['new_path'] = '';
1080 if (isset($content_info['href'], $xml_base_path)) {
1081 $content_info['href'] = $xml_base_path . $content_info['href'];
1083 if (!isset($content_info['href'])) {
1084 // this item doesn't have an identifierref. so create an empty page.
1085 // what we called a folder according to v1.2 Content Packaging spec
1089 $last_modified = date('Y-m-d H:i:s');
1091 //$file_info = @stat(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1092 $file_info = @stat($import_path.$content_info['href']);
1093 if ($file_info === false) {
1097 //$path_parts = pathinfo(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1098 $path_parts = pathinfo($import_path.$content_info['href']);
1099 $ext = strtolower($path_parts['extension']);
1101 $last_modified = date('Y-m-d H:i:s', $file_info['mtime']);
1103 if (in_array($ext, array('gif', 'jpg', 'bmp', 'png', 'jpeg'))) {
1104 /* this is an image */
1105 $content = '<img src="'.$content_info['href'].'" alt="'.$content_info['title'].'" />';
1106 } else if ($ext == 'swf') {
1108 /* Using default size of 550 x 400 */
1110 $content = '<object type="application/x-shockwave-flash" data="' . $content_info['href'] . '" width="550" height="400"><param name="movie" value="'. $content_info['href'] .'" /></object>';
1112 } else if ($ext == 'mov') {
1113 /* this is a quicktime movie */
1114 /* Using default size of 550 x 400 */
1116 $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>';
1119 * commenting this whole chunk out. It's part of my test import codes, not sure why it's here,
1120 * and I don't think it should be here. Remove this whole comment after further testing and confirmation.
1123 //Mimic the array for now.
1124 $test_attributes['resource']['href'] = $test_xml_file;
1125 $test_attributes['resource']['type'] = isset($items[$item_id]['type'])?'imsqti_xmlv1p2':'imsqti_xmlv1p1';
1126 $test_attributes['resource']['file'] = $items[$item_id]['file'];
1127 // $test_attributes['resource']['file'] = array($test_xml_file);
1129 //Get the XML file out and start importing them into our database.
1130 //TODO: See question_import.php 287-289.
1131 $qids = $qti_import->importQuestions($test_attributes);
1134 } else if ($ext == 'mp3') {
1135 $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>';
1136 } else if (in_array($ext, array('wav', 'au'))) {
1137 $content = '<embed SRC="'.$content_info['href'].'" autostart="false" width="145" height="60"><noembed><bgsound src="'.$content_info['href'].'"></noembed></embed>';
1139 } else if (in_array($ext, array('txt', 'css', 'html', 'htm', 'csv', 'asc', 'tsv', 'xml', 'xsl'))) {
1140 if ($content_type == 'IMS Common Cartridge'){
1141 $content_info['new_path'] = $content_new_path;
1144 /* this is a plain text file */
1145 //$content = file_get_contents(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1146 $content = file_get_contents($import_path.$content_info['href']);
1147 if ($content === false) {
1148 /* if we can't stat() it then we're unlikely to be able to read it */
1149 /* so we'll never get here. */
1153 // get the contents of the 'head' element
1154 $head .= get_html_head_by_tag($content, $html_head_tags);
1156 // Specifically handle eXe package
1157 // NOTE: THIS NEEDS WORK! TO FIND A WAY APPLY EXE .CSS FILES ONLY ON COURSE CONTENT PART.
1158 // NOW USE OUR OWN .CSS CREATED SOLELY FOR EXE
1159 $isExeContent = false;
1161 // check xml file in eXe package
1162 if (preg_match("/<organization[ ]*identifier=\"eXe*>*/", $ims_manifest_xml))
1164 $isExeContent = true;
1167 // use ATutor's eXe style sheet as the ones from eXe conflicts with ATutor's style sheets
1170 $head = preg_replace ('/(<style.*>)(.*)(<\/style>)/ms', '\\1@import url(/docs/exestyles.css);\\3', $head);
1173 // end of specifically handle eXe package
1175 $content = get_html_body($content);
1176 if ($contains_glossary_terms)
1178 // replace glossary content package links to real glossary mark-up using [?] [/?]
1179 // refer to bug 3641, edited by Harris
1180 $content = preg_replace('/<a href="([.\w\d\s]+[^"]+)" target="body" class="at-term">([.\w\d\s&;"]+|.*)<\/a>/i', '[?]\\2[/?]', $content);
1183 /* potential security risk? */
1184 if ( strpos($content_info['href'], '..') === false && !preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $content_info['href'])) {
1185 // @unlink(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$content_info['href']);
1188 /* overwrite content if this is discussion tool. */
1189 if ($content_info['type']=='imsdt_xmlv1p0'){
1190 $dt_parser = new DiscussionToolsParser();
1191 $xml_content = @file_get_contents($import_path . $content_info['href']);
1192 $dt_parser->parse($xml_content);
1193 $forum_obj = $dt_parser->getDt();
1194 $content = $forum_obj->getText();
1196 $dt_parser->close();
1199 /* non text file, and can't embed (example: PDF files) */
1200 $content = '<a href="'.$content_info['href'].'">'.$content_info['title'].'</a>';
1203 $content_parent_id = $cid;
1204 if ($content_info['parent_content_id'] !== 0) {
1205 $content_parent_id = $items[$content_info['parent_content_id']]['real_content_id'];
1206 //if it's not there, use $cid
1207 if (!$content_parent_id){
1208 $content_parent_id = $cid;
1213 if ($content_parent_id == $cid) {
1214 $my_offset = $order_offset;
1217 /* replace the old path greatest common denomiator with the new package path. */
1218 /* we don't use str_replace, b/c there's no knowing what the paths may be */
1219 /* we only want to replace the first part of the path.
1221 if(is_array($all_package_base_path)){
1222 $all_package_base_path = implode('/', $all_package_base_path);
1224 if ($common_path != '') {
1225 $content_info['new_path'] = $package_base_name . substr($content_info['new_path'], strlen($common_path));
1227 $content_info['new_path'] = $package_base_name . '/' . $content_info['new_path'];
1231 if ($content_info['type']=='imswl_xmlv1p0'){
1232 $weblinks_parser = new WeblinksParser();
1233 $xml_content = @file_get_contents($import_path . $content_info['href']);
1234 $weblinks_parser->parse($xml_content);
1235 $content_info['title'] = $weblinks_parser->getTitle();
1236 $content = $weblinks_parser->getUrl();
1237 $content_folder_type = CONTENT_TYPE_WEBLINK;
1238 $content_formatting = 2;
1240 $head = addslashes($head);
1241 $content_info['title'] = addslashes($content_info['title']);
1242 $content_info['test_message'] = addslashes($content_info['test_message']);
1244 //if this file is a test_xml, create a blank page instead, for imscc.
1245 if (preg_match('/((.*)\/)*tests\_[0-9]+\.xml$/', $content_info['href'])
1246 || preg_match('/imsqti\_(.*)/', $content_info['type'])) {
1249 $content = addslashes($content);
1252 //check for content_type
1253 if ($content_formatting!=CONTENT_TYPE_WEBLINK){
1254 $content_folder_type = (!isset($content_info['type'])?CONTENT_TYPE_FOLDER:CONTENT_TYPE_CONTENT);
1257 $sql= 'INSERT INTO '.TABLE_PREFIX.'content'
1266 use_customized_head,
1274 ('.$_SESSION['course_id'].','
1275 .intval($content_parent_id).','
1276 .($content_info['ordering'] + $my_offset - $lti_offset[$content_info['parent_content_id']] + 1).','
1277 .'"'.$last_modified.'",
1279 .$content_formatting.' ,
1284 .'"'.$content_info['new_path'].'",'
1285 .'"'.$content_info['title'].'",'
1287 .'"'.$content_info['test_message'].'",'
1288 .$content_folder_type.')';
1290 $result = mysql_query($sql, $db) or die(mysql_error());
1292 /* get the content id and update $items */
1293 $items[$item_id]['real_content_id'] = mysql_insert_id($db);
1295 /* get the tests associated with this content */
1296 if (!empty($items[$item_id]['tests']) || strpos($items[$item_id]['type'], 'imsqti_xmlv1p2/imscc_xmlv1p0') !== false){
1297 $qti_import = new QTIImport($import_path);
1298 if (isset($items[$item_id]['tests'])){
1299 $loop_var = $items[$item_id]['tests'];
1301 $loop_var = $items[$item_id]['file'];
1304 foreach ($loop_var as $array_id => $test_xml_file){
1305 //check if this item is the qti item object, or it is the content item obj
1306 //switch it to qti obj if it's content item obj
1307 if ($items[$item_id]['type'] == 'webcontent'){
1308 $item_qti = $items[$array_id];
1310 $item_qti = $items[$item_id];
1312 //call subrountine to add the questions.
1313 $qids = addQuestions($test_xml_file, $item_qti, $import_path);
1316 if ($test_title==''){
1317 $test_title = $content_info['title'];
1320 $tid = $qti_import->importTest($test_title);
1322 //associate question and tests
1323 foreach ($qids as $order=>$qid){
1324 if (isset($qti_import->weights[$order])){
1325 $weight = round($qti_import->weights[$order]);
1329 $new_order = $order + 1;
1330 $sql = "INSERT INTO " . TABLE_PREFIX . "tests_questions_assoc" .
1331 "(test_id, question_id, weight, ordering, required) " .
1332 "VALUES ($tid, $qid, $weight, $new_order, 0)";
1333 $result = mysql_query($sql, $db);
1336 //associate content and test
1337 $sql = 'INSERT INTO ' . TABLE_PREFIX . 'content_tests_assoc' .
1338 '(content_id, test_id) ' .
1339 'VALUES (' . $items[$item_id]['real_content_id'] . ", $tid)";
1340 $result = mysql_query($sql, $db);
1342 // if (!$msg->containsErrors()) {
1343 // $msg->addFeedback('IMPORT_SUCCEEDED');
1348 /* get the a4a related xml */
1349 if (isset($items[$item_id]['a4a_import_enabled']) && isset($items[$item_id]['a4a']) && !empty($items[$item_id]['a4a'])) {
1350 $a4a_import = new A4aImport($items[$item_id]['real_content_id']);
1351 $a4a_import->setRelativePath($items[$item_id]['new_path']);
1352 $a4a_import->importA4a($items[$item_id]['a4a']);
1355 /* get the discussion tools (dependent to content)*/
1356 if (isset($items[$item_id]['forum']) && !empty($items[$item_id]['forum'])){
1357 foreach($items[$item_id]['forum'] as $forum_ref => $forum_link){
1358 $dt_parser = new DiscussionToolsParser();
1359 $dt_import = new DiscussionToolsImport();
1361 //if this forum has not been added, parse it and add it.
1362 if (!isset($added_dt[$forum_ref])){
1363 $xml_content = @file_get_contents($import_path . $forum_link);
1364 $dt_parser->parse($xml_content);
1365 $forum_obj = $dt_parser->getDt();
1366 $dt_import->import($forum_obj, $items[$item_id]['real_content_id']);
1367 $added_dt[$forum_ref] = $dt_import->getFid();
1369 //associate the fid and content id
1370 $dt_import->associateForum($items[$item_id]['real_content_id'], $added_dt[$forum_ref]);
1372 } elseif ($items[$item_id]['type']=='imsdt_xmlv1p0'){
1373 //optimize this, repeated codes as above
1374 $dt_parser = new DiscussionToolsParser();
1375 $dt_import = new DiscussionToolsImport();
1376 $xml_content = @file_get_contents($import_path . $content_info['href']);
1377 $dt_parser->parse($xml_content);
1378 $forum_obj = $dt_parser->getDt();
1379 $dt_import->import($forum_obj, $items[$item_id]['real_content_id']);
1380 $added_dt[$item_id] = $dt_import->getFid();
1382 //associate the fid and content id
1383 $dt_import->associateForum($items[$item_id]['real_content_id'], $added_dt[$item_id]);
1387 if ($package_base_path == '.') {
1388 $package_base_path = '';
1391 // loop through the files outside the package folder, and copy them to its relative path
1393 if (is_dir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources')) {
1394 $handler = opendir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources');
1395 while ($file = readdir($handler)){
1396 $filename = AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/resources/'.$file;
1398 if(is_file($filename)){
1399 @rename($filename, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name.'/'.$file);
1405 //--- harris edit for path thing
1406 $file = AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].DIRECTORY_SEPARATOR.$common_path;
1407 if (is_dir($file)) {
1408 rename($file, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name);
1411 //takes care of the condition where the whole package doesn't have any contents but question banks
1412 //also is the case of urls
1413 if(is_array($all_package_base_path)){
1414 $all_package_base_path = implode('/', $all_package_base_path);
1415 if(strpos($all_package_base_path, 'http:/')===false){
1416 if (@rename($import_path.$all_package_base_path, AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name) === false) {
1417 if (!$msg->containsErrors()) {
1418 $msg->addError('IMPORT_FAILED');
1424 //check if there are still resources missing
1426 foreach($items as $idetails){
1427 $temp_path = pathinfo($idetails['href']);
1428 @rename(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id'].'/'.$temp_path['dirname'], AT_CONTENT_DIR .$_SESSION['course_id'].'/'.$package_base_name . '/' . $temp_path['dirname']);
1431 clr_dir(AT_CONTENT_DIR . 'import/'.$_SESSION['course_id']);
1433 if (file_exists($full_filename)) {
1434 @unlink($full_filename);
1438 if ($_POST['s_cid']){
1439 if (!$msg->containsErrors()) {
1440 $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
1442 header('Location: ../editor/edit_content.php?cid='.intval($_POST['cid']));
1445 if (!$msg->containsErrors()) {
1446 $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
1448 if ($_GET['tile']) {
1449 header('Location: '.AT_BASE_HREF.'mods/_standard/tile_search/index.php');
1451 header('Location: ./index.php?cid='.intval($_POST['cid']));