Пример #1
0
function unpack_zip_inner($zipfile, $clone) {
    global $webDir, $uid;

    require_once 'include/lib/fileUploadLib.inc.php';

    $zip = new pclZip($zipfile);
    if (!$clone) {
        validateUploadedZipFile($zip->listContent(), 3);
    }

    $destdir = $webDir . '/courses/tmpUnzipping/' . $uid;
    if (!is_dir($destdir)) {
        mkdir($destdir, 0755);
    }
    chdir($destdir);
    $zip->extract();

    $retArr = array();
    foreach (find_backup_folders($destdir) as $folder) {
        $retArr[] = array(
            'path' => $folder['path'] . '/' . $folder['dir'],
            'file' => $folder['dir'],
            'course' => preg_replace('|^.*/|', '', $folder['path'])
        );
    }
    
    chdir($webDir);
    return $retArr;
}
Пример #2
0
function get_package_type($file_path, $file_name)
{
    //get name of the zip file without the extension
    $file_info = pathinfo($file_name);
    $filename = $file_info['basename'];
    //name including extension
    $extension = $file_info['extension'];
    //extension only
    if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), array('dll', 'exe'))) {
        return 'oogie';
    }
    if (!empty($_POST['woogie']) && !in_array(strtolower($extension), array('dll', 'exe'))) {
        return 'woogie';
    }
    $file_base_name = str_replace('.' . $extension, '', $filename);
    //filename without its extension
    require_once "lib/pclzip/pclzip.lib.php";
    $zipFile = new pclZip($file_path);
    // Check the zip content (real size and file extension)
    $zipContentArray = $zipFile->listContent();
    $package_type = '';
    $at_root = false;
    $manifest = '';
    //the following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?)
    if (is_array($zipContentArray) && count($zipContentArray) > 0) {
        foreach ($zipContentArray as $thisContent) {
            if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
                //New behaviour: Don't do anything. These files will be removed in scorm::import_package
            } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== FALSE) {
                $manifest = $thisContent['filename'];
                //just the relative directory inside scorm/
                $package_type = 'scorm';
                break;
                //exit the foreach loop
            } elseif (preg_match('/aicc\\//i', $thisContent['filename']) != false || strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)) == 'crs') {
                //if found an aicc directory... (!= false means it cannot be false (error) or 0 (no match))
                //or if a file has the .crs extension
                $package_type = 'aicc';
                //break;//don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC
            }
        }
    }
    return $package_type;
}
Пример #3
0
     $errorFound = true;
     array_push($errorMsgs, $langFileScormError);
 } elseif (!enough_size($_FILES['uploadedPackage']['size'], $baseWorkDir, $maxFilledSpace)) {
     $errorFound = true;
     array_push($errorMsgs, $langNoSpace);
 } elseif (preg_match("/.zip\$/i", $_FILES['uploadedPackage']['name'])) {
     array_push($okMsgs, $langOkFileReceived . basename($_FILES['uploadedPackage']['name']));
     if (!function_exists('gzopen')) {
         $errorFound = true;
         array_push($errorMsgs, $langErrorNoZlibExtension);
     } else {
         $zipFile = new pclZip($_FILES['uploadedPackage']['tmp_name']);
         $is_allowedToUnzip = true;
         // default initialisation
         // Check the zip content (real size and file extension)
         $zipContentArray = $zipFile->listContent();
         if ($zipContentArray == 0) {
             $errorFound = true;
             array_push($errorMsgs, $langErrorReadingZipFile);
         }
         $pathToManifest = "";
         // empty by default because we can expect that the manifest.xml is in the root of zip file
         $pathToManifestFound = false;
         $realFileSize = 0;
         foreach ($zipContentArray as $thisContent) {
             if (preg_match('/.(php[[:digit:]]?|phtml)$/i', $thisContent['filename'])) {
                 $errorFound = true;
                 array_push($errorMsgs, $langZipNoPhp);
                 $is_allowedToUnzip = false;
                 break;
             }
Пример #4
0
 $action_message = $dialogBox = '';
 if (isset($_FILES['userFile']) and is_uploaded_file($_FILES['userFile']['tmp_name'])) {
     validateUploadedFile($_FILES['userFile']['name'], $menuTypeID);
     $extra_path = '';
     $userFile = $_FILES['userFile']['tmp_name'];
     // check for disk quotas
     $diskUsed = dir_total_space($basedir);
     if ($diskUsed + @$_FILES['userFile']['size'] > $diskQuotaDocument) {
         $action_message .= "<div class='alert alert-danger'>{$langNoSpace}</div>";
     } else {
         if (unwanted_file($_FILES['userFile']['name'])) {
             $action_message .= "<div class='alert alert-danger'>{$langUnwantedFiletype}: " . q($_FILES['userFile']['name']) . "</div>";
         } elseif (isset($_POST['uncompress']) and $_POST['uncompress'] == 1 and preg_match('/\\.zip$/i', $_FILES['userFile']['name'])) {
             /* ** Unzipping stage ** */
             $zipFile = new pclZip($userFile);
             validateUploadedZipFile($zipFile->listContent(), $menuTypeID);
             $realFileSize = 0;
             $zipFile->extract(PCLZIP_CB_PRE_EXTRACT, 'process_extracted_file');
             if ($diskUsed + $realFileSize > $diskQuotaDocument) {
                 $action_message .= "<div class='alert alert-danger'>{$langNoSpace}</div>";
             } else {
                 $action_message .= "<div class='alert alert-success'>{$langDownloadAndZipEnd}</div><br />";
             }
         } else {
             $fileName = canonicalize_whitespace($_FILES['userFile']['name']);
             $uploaded = true;
         }
     }
 } elseif (isset($_POST['fileURL']) and $fileURL = trim($_POST['fileURL'])) {
     $extra_path = canonicalize_url($fileURL);
     if (preg_match('/^javascript/', $extra_path)) {
Пример #5
0
 /**
  * Imports a zip file (presumably AICC) into the Dokeos structure
  * @param	string	Zip file info as given by $_FILES['userFile']
  * @return	string	Absolute path to the AICC config files directory or empty string on error
  */
 function import_package($zip_file_info, $current_dir = '')
 {
     if ($this->debug > 0) {
         error_log('In aicc::import_package(' . print_r($zip_file_info, true) . ',"' . $current_dir . '") method', 0);
     }
     //ini_set('error_log','E_ALL');
     $maxFilledSpace = 1000000000;
     $zip_file_path = $zip_file_info['tmp_name'];
     $zip_file_name = $zip_file_info['name'];
     if ($this->debug > 0) {
         error_log('New LP - aicc::import_package() - Zip file path = ' . $zip_file_path . ', zip file name = ' . $zip_file_name, 0);
     }
     $course_rel_dir = api_get_course_path() . '/scorm';
     //scorm dir web path starting from /courses
     $course_sys_dir = api_get_path(SYS_COURSE_PATH) . $course_rel_dir;
     //absolute system path for this course
     $current_dir = replace_dangerous_char(trim($current_dir), 'strict');
     //current dir we are in, inside scorm/
     if ($this->debug > 0) {
         error_log('New LP - aicc::import_package() - Current_dir = ' . $current_dir, 0);
     }
     //$uploaded_filename = $_FILES['userFile']['name'];
     //get name of the zip file without the extension
     if ($this->debug > 0) {
         error_log('New LP - aicc::import_package() - Received zip file name: ' . $zip_file_path, 0);
     }
     $file_info = pathinfo($zip_file_name);
     $filename = $file_info['basename'];
     $extension = $file_info['extension'];
     $file_base_name = str_replace('.' . $extension, '', $filename);
     //filename without its extension
     $this->zipname = $file_base_name;
     //save for later in case we don't have a title
     if ($this->debug > 0) {
         error_log('New LP - aicc::import_package() - Base file name is : ' . $file_base_name, 0);
     }
     $new_dir = replace_dangerous_char(trim($file_base_name), 'strict');
     $this->subdir = $new_dir;
     if ($this->debug > 0) {
         error_log('New LP - aicc::import_package() - Subdir is first set to : ' . $this->subdir, 0);
     }
     /*
     		if( check_name_exist($course_sys_dir.$current_dir."/".$new_dir) )
     		{
     			$dialogBox = get_lang('FileExists');
     			$stopping_error = true;
     		}
     */
     $zipFile = new pclZip($zip_file_path);
     // Check the zip content (real size and file extension)
     $zipContentArray = $zipFile->listContent();
     $package_type = '';
     //the type of the package. Should be 'aicc' after the next few lines
     $package = '';
     //the basename of the config files (if 'courses.crs' => 'courses')
     $at_root = false;
     //check if the config files are at zip root
     $config_dir = '';
     //the directory in which the config files are. May remain empty
     $files_found = array();
     $subdir_isset = false;
     //the following loop should be stopped as soon as we found the right config files (.crs, .au, .des and .cst)
     foreach ($zipContentArray as $thisContent) {
         if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
             //if a php file is found, do not authorize (security risk)
             if ($this->debug > 1) {
                 error_log('New LP - aicc::import_package() - Found unauthorized file: ' . $thisContent['filename'], 0);
             }
             return api_failure::set_failure('php_file_in_zip_file');
         } elseif (preg_match('?.*/aicc/$?', $thisContent['filename'])) {
             //if a directory named 'aicc' is found, package type = aicc, but continue
             //because we need to find the right AICC files
             if ($this->debug > 1) {
                 error_log('New LP - aicc::import_package() - Found aicc directory: ' . $thisContent['filename'], 0);
             }
             $package_type = 'aicc';
         } else {
             //else, look for one of the files we're searching for (something.crs case insensitive)
             $res = array();
             if (preg_match('?^(.*)\\.(crs|au|des|cst|ore|pre|cmp)$?i', $thisContent['filename'], $res)) {
                 if ($this->debug > 1) {
                     error_log('New LP - aicc::import_package() - Found AICC config file: ' . $thisContent['filename'] . '. Now splitting: ' . $res[1] . ' and ' . $res[2], 0);
                 }
                 if ($thisContent['filename'] == basename($thisContent['filename'])) {
                     if ($this->debug > 2) {
                         error_log('New LP - aicc::import_package() - ' . $thisContent['filename'] . ' is at root level', 0);
                     }
                     $at_root = true;
                     if (!is_array($files_found[$res[1]])) {
                         $files_found[$res[1]] = $this->config_exts;
                         //initialise list of expected extensions (defined in class definition)
                     }
                     $files_found[$res[1]][strtolower($res[2])] = $thisContent['filename'];
                     $subdir_isset = true;
                 } else {
                     if (!$subdir_isset) {
                         if (preg_match('?^.*/aicc$?i', dirname($thisContent['filename']))) {
                             //echo "Cutting subdir<br/>";
                             $this->subdir .= '/' . substr(dirname($thisContent['filename']), 0, -5);
                         } else {
                             //echo "Not cutting subdir<br/>";
                             $this->subdir .= '/' . dirname($thisContent['filename']);
                         }
                         $subdir_isset = true;
                     }
                     if ($this->debug > 2) {
                         error_log('New LP - aicc::import_package() - ' . $thisContent['filename'] . ' is not at root level - recording subdir ' . $this->subdir, 0);
                     }
                     $config_dir = dirname($thisContent['filename']);
                     //just the relative directory inside scorm/
                     if (!is_array($files_found[basename($res[1])])) {
                         $files_found[basename($res[1])] = $this->config_exts;
                     }
                     $files_found[basename($res[1])][strtolower($res[2])] = basename($thisContent['filename']);
                 }
                 $package_type = 'aicc';
             } else {
                 if ($this->debug > 3) {
                     error_log('New LP - aicc::import_package() - File ' . $thisContent['filename'] . ' didnt match any check', 0);
                 }
             }
         }
         $realFileSize += $thisContent['size'];
     }
     if ($this->debug > 2) {
         error_log('New LP - aicc::import_package() - $files_found: ' . print_r($files_found, true), 0);
     }
     if ($this->debug > 1) {
         error_log('New LP - aicc::import_package() - Package type is now ' . $package_type, 0);
     }
     $mandatory = false;
     foreach ($files_found as $file_name => $file_exts) {
         $temp = (!empty($files_found[$file_name]['crs']) and !empty($files_found[$file_name]['au']) and !empty($files_found[$file_name]['des']) and !empty($files_found[$file_name]['cst']));
         if ($temp) {
             if ($this->debug > 1) {
                 error_log('New LP - aicc::import_package() - Found all config files for ' . $file_name, 0);
             }
             $mandatory = true;
             $package = $file_name;
             //store base config file name for reuse in parse_config_files()
             $this->config_basename = $file_name;
             //store filenames for reuse in parse_config_files()
             $this->config_files = $files_found[$file_name];
             //get out, we only want one config files set
             break;
         }
     }
     if ($package_type == '' or $mandatory != true) {
         return api_failure::set_failure('not_aicc_content');
     }
     if (!enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
         return api_failure::set_failure('not_enough_space');
     }
     // it happens on Linux that $new_dir sometimes doesn't start with '/'
     if ($new_dir[0] != '/') {
         $new_dir = '/' . $new_dir;
     }
     //cut trailing slash
     if ($new_dir[strlen($new_dir) - 1] == '/') {
         $new_dir = substr($new_dir, 0, -1);
     }
     /*
     --------------------------------------
     	Uncompressing phase
     --------------------------------------
     */
     /*
     	We need to process each individual file in the zip archive to
     	- add it to the database
     	- parse & change relative html links
     	- make sure the filenames are secure (filter funny characters or php extensions)
     */
     if (is_dir($course_sys_dir . $new_dir) or @mkdir($course_sys_dir . $new_dir)) {
         // PHP method - slower...
         if ($this->debug >= 1) {
             error_log('New LP - Changing dir to ' . $course_sys_dir . $new_dir, 0);
         }
         $saved_dir = getcwd();
         chdir($course_sys_dir . $new_dir);
         $unzippingState = $zipFile->extract();
         for ($j = 0; $j < count($unzippingState); $j++) {
             $state = $unzippingState[$j];
             //TODO fix relative links in html files (?)
             $extension = strrchr($state["stored_filename"], ".");
             //if($this->debug>1){error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'],0);}
         }
         if (!empty($new_dir)) {
             $new_dir = $new_dir . '/';
         }
         //rename files, for example with \\ in it
         if ($dir = @opendir($course_sys_dir . $new_dir)) {
             if ($this->debug == 1) {
                 error_log('New LP - Opened dir ' . $course_sys_dir . $new_dir, 0);
             }
             while ($file = readdir($dir)) {
                 if ($file != '.' && $file != '..') {
                     $filetype = "file";
                     if (is_dir($course_sys_dir . $new_dir . $file)) {
                         $filetype = "folder";
                     }
                     //TODO RENAMING FILES CAN BE VERY DANGEROUS AICC-WISE, avoid that as much as possible!
                     //$safe_file=replace_dangerous_char($file,'strict');
                     $find_str = array('\\', '.php', '.phtml');
                     $repl_str = array('/', '.txt', '.txt');
                     $safe_file = str_replace($find_str, $repl_str, $file);
                     if ($safe_file != $file) {
                         //@rename($course_sys_dir.$new_dir,$course_sys_dir.'/'.$safe_file);
                         $mydir = dirname($course_sys_dir . $new_dir . $safe_file);
                         if (!is_dir($mydir)) {
                             $mysubdirs = split('/', $mydir);
                             $mybasedir = '/';
                             foreach ($mysubdirs as $mysubdir) {
                                 if (!empty($mysubdir)) {
                                     $mybasedir = $mybasedir . $mysubdir . '/';
                                     if (!is_dir($mybasedir)) {
                                         @mkdir($mybasedir);
                                         if ($this->debug == 1) {
                                             error_log('New LP - Dir ' . $mybasedir . ' doesnt exist. Creating.', 0);
                                         }
                                     }
                                 }
                             }
                         }
                         @rename($course_sys_dir . $new_dir . $file, $course_sys_dir . $new_dir . $safe_file);
                         if ($this->debug == 1) {
                             error_log('New LP - Renaming ' . $course_sys_dir . $new_dir . $file . ' to ' . $course_sys_dir . $new_dir . $safe_file, 0);
                         }
                     }
                     //set_default_settings($course_sys_dir,$safe_file,$filetype);
                 }
             }
             closedir($dir);
             chdir($saved_dir);
         }
     } else {
         return '';
     }
     return $course_sys_dir . $new_dir . $config_dir;
 }
Пример #6
0
/**
 * unzip safly a zipfile
 *
 * @author Hugues Peeters <*****@*****.**>
 *
 * @param string $fileName file name of zip
 * @param string $filePath file path of zip
 * @param string $extractPath
 * @param integer $maxFilledSpace (byte) count  of byte size aivailable
 * @param boolean $allowPHP whether True the file can't contain php or phtml files
 * @return true
 * @throws claro_failure on error
 */
function treat_secure_file_unzip($fileName, $filePath, $extractPath, $maxFilledSpace, $allowPHP = false)
{
    $zipFile = new pclZip($fileName);
    // Check the zip content (real size and file extension)
    $zipContentArray = $zipFile->listContent();
    if (!is_array($zipContentArray)) {
        return false;
    }
    foreach ($zipContentArray as $thisContent) {
        if (!$allowPHP) {
            if (preg_match('~.(php.?|phtml)$~i', $thisContent['filename'])) {
                return claro_failure::set_failure(get_lang('The zip file can not contain .PHP files'));
            }
        }
        if (!isset($realFileSize)) {
            $realFileSize = 0;
        }
        $realFileSize += $thisContent['size'];
    }
    if (!enough_size($realFileSize, $extractPath, $maxFilledSpace)) {
        return claro_failure::set_failure(get_lang('The upload has failed. There is not enough space in your directory'));
    }
    $extractedFileNameList = $zipFile->extract(PCLZIP_OPT_PATH, $extractPath . $filePath, PCLZIP_OPT_SET_CHMOD, CLARO_FILE_PERMISSIONS);
    if (is_array($extractedFileNameList)) {
        return $extractedFileNameList;
    } else {
        return false;
    }
}
Пример #7
0
 function prepareFTP($filename)
 {
     $this->is_prepared = 0;
     if (!extension_loaded('zlib')) {
         return "Error! zlib library unavailable";
     }
     if (!$filename) {
         return _JLMS_EM_SELECT_FILE;
     }
     if (strcmp(substr($filename, -4, 1), ".")) {
         return _JLMS_EM_BAD_FILEEXT;
     }
     if (strcmp(substr($filename, -4), ".zip")) {
         return _JLMS_EM_BAD_FILEEXT;
     }
     $baseDir = mosPathName(JPATH_SITE . '/media');
     $tmp_name = $baseDir . $filename;
     if (!file_exists($tmp_name)) {
         return _JLMS_EM_UPLOAD_SIZE_ERROR;
     }
     if (preg_match("/.zip\$/", strtolower($filename))) {
         $zipFile = new pclZip($tmp_name);
         $zipContentArray = $zipFile->listContent();
         $exp_xml_file = false;
         foreach ($zipContentArray as $thisContent) {
             if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
                 return _JLMS_EM_READ_PACKAGE_ERROR;
             }
             if ($thisContent['filename'] == 'imsmanifest.xml') {
                 $exp_xml_file = true;
             }
         }
         if ($exp_xml_file == false) {
             return "Could not find a Course XML setup file in the package.";
         }
     } else {
         return _JLMS_EM_BAD_FILEEXT;
     }
     $this->bb_file_media_name = $filename;
     $this->is_prepared = 1;
     return '';
 }
Пример #8
0
if (!$is_editor) {
    redirect_to_home_page();
} else {
    $title = trim(@$_POST['title']);
    if (empty($title)) {
        Session::Messages($langFieldsMissing, 'alert-danger');
        redirect_to_home_page("modules/ebook/index.php?course=$course_code&create=1");
    }
    if (isset($_FILES['file']['name']) and !$_FILES['file']['error']) {
        if (!preg_match('/\.zip$/i', $_FILES['file']['name'])) {
            Session::Messages("$langUnwantedFiletype: " . $_FILES['file']['name'], 'alert-danger');
            redirect_to_home_page("modules/ebook/index.php?course=$course_code&create=1");
        }
        validateUploadedFile($_FILES['file']['name'], 2);
        $zipFile = new pclZip($_FILES['file']['tmp_name']);
        validateUploadedZipFile($zipFile->listContent(), 2);
    }

    $order = Database::get()->querySingle("SELECT COALESCE(MAX(`order`), 1) AS `order` FROM ebook WHERE course_id = ?d", $course_id)->order;
    $ebook_id = Database::get()->query("INSERT INTO ebook SET `order` = ?d, `course_id` = ?d, `title` = ?s, `visible` = 1", $order + 1, $course_id, $title)->lastInsertID;
    Database::get()->query("INSERT INTO ebook_section SET ebook_id = ?d,
                                                    public_id = ?s,
                                                    title = ?s"
            , $ebook_id, '1', $langSection.' 1');
    // Initialize document subsystem global variables
    require_once 'modules/document/doc_init.php';
    require_once 'include/log.php';

    if (!mkdir($basedir, 0775, true)) {
        Database::get()->query("DELETE FROM ebook WHERE course_id = ?d AND id = ?d", $course_id, $ebook_id);
        Session::Messages($langImpossible, 'alert-danger');
Пример #9
0
 /**
  * Imports a zip file into the Dokeos structure
  * @param	string	Zip file info as given by $_FILES['userFile']
  * @return	string	Absolute path to the imsmanifest.xml file or empty string on error
  */
 function import_package($zip_file_info, $current_dir = '')
 {
     if ($this->debug > 0) {
         error_log('In scorm::import_package(' . print_r($zip_file_info, true) . ',"' . $current_dir . '") method', 0);
     }
     //require_once(api_get_path(LIBRARY_PATH).'document.lib.php');
     //$maxFilledSpace = DocumentManager :: get_course_quota();
     $zip_file_path = $zip_file_info['tmp_name'];
     $zip_file_name = $zip_file_info['name'];
     if ($this->debug > 1) {
         error_log('New LP - import_package() - zip file path = ' . $zip_file_path . ', zip file name = ' . $zip_file_name, 0);
     }
     $course_rel_dir = api_get_course_path() . '/scorm';
     //scorm dir web path starting from /courses
     $course_sys_dir = api_get_path(SYS_COURSE_PATH) . $course_rel_dir;
     //absolute system path for this course
     $current_dir = replace_dangerous_char(trim($current_dir), 'strict');
     //current dir we are in, inside scorm/
     if ($this->debug > 1) {
         error_log('New LP - import_package() - current_dir = ' . $current_dir, 0);
     }
     //$uploaded_filename = $_FILES['userFile']['name'];
     //get name of the zip file without the extension
     if ($this->debug > 1) {
         error_log('New LP - Received zip file name: ' . $zip_file_path, 0);
     }
     $file_info = pathinfo($zip_file_name);
     $filename = $file_info['basename'];
     $extension = $file_info['extension'];
     $file_base_name = str_replace('.' . $extension, '', $filename);
     //filename without its extension
     $this->zipname = $file_base_name;
     //save for later in case we don't have a title
     if ($this->debug > 1) {
         error_log("New LP - base file name is : " . $file_base_name, 0);
     }
     $new_dir = replace_dangerous_char(trim($file_base_name), 'strict');
     $this->subdir = $new_dir;
     if ($this->debug > 1) {
         error_log("New LP - subdir is first set to : " . $this->subdir, 0);
     }
     $zipFile = new pclZip($zip_file_path);
     // Check the zip content (real size and file extension)
     $zipContentArray = $zipFile->listContent();
     $package_type = '';
     $at_root = false;
     $manifest = '';
     $manifest_list = array();
     //the following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?)
     foreach ($zipContentArray as $thisContent) {
         //error_log('Looking at  '.$thisContent['filename'],0);
         if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
             $this->set_error_msg("File {$file} contains a PHP script");
             //return api_failure::set_failure('php_file_in_zip_file');
         } elseif (stristr($thisContent['filename'], 'imsmanifest.xml')) {
             //error_log('Found imsmanifest at '.$thisContent['filename'],0);
             if ($thisContent['filename'] == basename($thisContent['filename'])) {
                 $at_root = true;
             } else {
                 //$this->subdir .= '/'.dirname($thisContent['filename']);
                 if ($this->debug > 2) {
                     error_log("New LP - subdir is now " . $this->subdir, 0);
                 }
             }
             $package_type = 'scorm';
             $manifest_list[] = $thisContent['filename'];
             $manifest = $thisContent['filename'];
             //just the relative directory inside scorm/
         } else {
             //do nothing, if it has not been set as scorm somewhere else, it stays as '' default
         }
         $realFileSize += $thisContent['size'];
     }
     //now get the shortest path (basically, the imsmanifest that is the closest to the root)
     $shortest_path = $manifest_list[0];
     $slash_count = substr_count($shortest_path, '/');
     foreach ($manifest_list as $manifest_path) {
         $tmp_slash_count = substr_count($manifest_path, '/');
         if ($tmp_slash_count < $slash_count) {
             $shortest_path = $manifest_path;
             $slash_count = $tmp_slash_count;
         }
     }
     $this->subdir .= '/' . dirname($shortest_path);
     //do not concatenate because already done above
     $manifest = $shortest_path;
     if ($this->debug > 1) {
         error_log('New LP - Package type is now ' . $package_type, 0);
     }
     if ($package_type == '') {
         return api_failure::set_failure('not_scorm_content');
     }
     if (!enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
         return api_failure::set_failure('not_enough_space');
     }
     // it happens on Linux that $new_dir sometimes doesn't start with '/'
     if ($new_dir[0] != '/') {
         $new_dir = '/' . $new_dir;
     }
     if ($new_dir[strlen($new_dir) - 1] == '/') {
         $new_dir = substr($new_dir, 0, -1);
     }
     /*
     --------------------------------------
     	Uncompressing phase
     --------------------------------------
     */
     /*
     	We need to process each individual file in the zip archive to
     	- add it to the database
     	- parse & change relative html links
     	- make sure the filenames are secure (filter funny characters or php extensions)
     */
     if (is_dir($course_sys_dir . $new_dir) or @mkdir($course_sys_dir . $new_dir)) {
         // PHP method - slower...
         if ($this->debug >= 1) {
             error_log('New LP - Changing dir to ' . $course_sys_dir . $new_dir, 0);
         }
         $saved_dir = getcwd();
         chdir($course_sys_dir . $new_dir);
         ini_set('memory_limit', '512M');
         $unzippingState = $zipFile->extract();
         for ($j = 0; $j < count($unzippingState); $j++) {
             $state = $unzippingState[$j];
             //TODO fix relative links in html files (?)
             $extension = strrchr($state["stored_filename"], ".");
             if ($this->debug >= 1) {
                 error_log('New LP - found extension ' . $extension . ' in ' . $state['stored_filename'], 0);
             }
         }
         if (!empty($new_dir)) {
             $new_dir = $new_dir . '/';
         }
         //rename files, for example with \\ in it
         if ($dir = @opendir($course_sys_dir . $new_dir)) {
             if ($this->debug == 1) {
                 error_log('New LP - Opened dir ' . $course_sys_dir . $new_dir, 0);
             }
             while ($file = readdir($dir)) {
                 if ($file != '.' && $file != '..') {
                     $filetype = "file";
                     if (is_dir($course_sys_dir . $new_dir . $file)) {
                         $filetype = "folder";
                     }
                     //TODO RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
                     //$safe_file=replace_dangerous_char($file,'strict');
                     $find_str = array('\\', '.php', '.phtml');
                     $repl_str = array('/', '.txt', '.txt');
                     $safe_file = str_replace($find_str, $repl_str, $file);
                     if ($safe_file != $file) {
                         //@rename($course_sys_dir.$new_dir,$course_sys_dir.'/'.$safe_file);
                         $mydir = dirname($course_sys_dir . $new_dir . $safe_file);
                         if (!is_dir($mydir)) {
                             $mysubdirs = split('/', $mydir);
                             $mybasedir = '/';
                             foreach ($mysubdirs as $mysubdir) {
                                 if (!empty($mysubdir)) {
                                     $mybasedir = $mybasedir . $mysubdir . '/';
                                     if (!is_dir($mybasedir)) {
                                         @mkdir($mybasedir);
                                         if ($this->debug == 1) {
                                             error_log('New LP - Dir ' . $mybasedir . ' doesnt exist. Creating.', 0);
                                         }
                                     }
                                 }
                             }
                         }
                         @rename($course_sys_dir . $new_dir . $file, $course_sys_dir . $new_dir . $safe_file);
                         if ($this->debug == 1) {
                             error_log('New LP - Renaming ' . $course_sys_dir . $new_dir . $file . ' to ' . $course_sys_dir . $new_dir . $safe_file, 0);
                         }
                     }
                     //set_default_settings($course_sys_dir,$safe_file,$filetype);
                 }
             }
             closedir($dir);
             chdir($saved_dir);
             $perm = api_get_setting('permissions_for_new_directories');
             $perm = octdec(!empty($perm) ? $perm : '0770');
             api_chmod_R($course_sys_dir . $new_dir, $perm);
         }
     } else {
         return '';
     }
     return $course_sys_dir . $new_dir . $manifest;
 }
Пример #10
0
function JLMS_courseImport_main($backupfile, $option, $course_id, $imp_tools, $course_zname = '', $is_template = false)
{
    global $JLMS_DB, $JLMS_CONFIG, $my;
    if (!$backupfile) {
        mosErrorAlert(_JLMS_EM_SELECT_FILE);
    }
    $backupfile_name = $backupfile['name'];
    $filename = explode(".", $backupfile_name);
    if (empty($backupfile_name)) {
        mosErrorAlert(_JLMS_EM_SELECT_FILE);
    }
    //commented (12.01.2007 Bjarne request forum post #331)
    #if (eregi("[^0-9a-zA-Z_]", $filename[0])) {
    #	mosErrorAlert("File must only contain alphanumeric characters and no special symbols and spaces please.");
    #}
    if (strcmp(substr($backupfile_name, -4, 1), ".")) {
        mosErrorAlert(_JLMS_EM_BAD_FILEEXT);
    }
    if (strcmp(substr($backupfile_name, -4), ".zip")) {
        mosErrorAlert(_JLMS_EM_BAD_FILEEXT);
    }
    $tmp_name = $backupfile['tmp_name'];
    if (!file_exists($tmp_name)) {
        mosErrorAlert(_JLMS_EM_UPLOAD_SIZE_ERROR);
    }
    if (preg_match("/.zip\$/", strtolower($backupfile_name))) {
        $zipFile = new pclZip($tmp_name);
        $zipContentArray = $zipFile->listContent();
        $exp_xml_file = false;
        if (!empty($zipContentArray)) {
            foreach ($zipContentArray as $thisContent) {
                if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
                    mosErrorAlert(_JLMS_EM_READ_PACKAGE_ERROR);
                }
                if ($thisContent['filename'] == 'export.xml') {
                    $exp_xml_file = true;
                }
            }
        }
        if ($exp_xml_file == false) {
            mosErrorAlert("Could not find a Course XML setup file in the package.");
        }
    } else {
        mosErrorAlert(_JLMS_EM_BAD_FILEEXT);
    }
    $config =& JFactory::getConfig();
    $tmp_dest = $config->getValue('config.tmp_path') . DS . $backupfile['name'];
    $tmp_src = $backupfile['tmp_name'];
    // Move uploaded file
    jimport('joomla.filesystem.file');
    if ($is_template) {
        $uploaded = JFile::copy($tmp_src, $tmp_dest);
    } else {
        $uploaded = JFile::upload($tmp_src, $tmp_dest);
    }
    $extract_dir = $config->getValue('config.tmp_path') . DS . "course_backup_" . uniqid(rand(), true) . DS;
    $archive = $tmp_dest;
    //$JLMS_CONFIG->getCfg('absolute_path')."/media/".$backupfile['name'];
    if (!is_file($archive)) {
        $archive = $backupfile['tmp_name'];
    }
    //exstract archive in uniqfolder media
    JLMS_Zip::extractFile($archive, $extract_dir);
    $xmlFile = $extract_dir . "export.xml";
    $xmlDoc =& JLMSFactory::getXMLParser();
    //$xmlDoc->resolveErrors( true );
    if (!$xmlDoc->loadFile($xmlFile)) {
        echo "<script> alert('Error during reading xml file'); window.history.go(-1); </script>\n";
        exit;
    }
    $root =& $xmlDoc->document;
    if ($root->name() != 'course_backup') {
        echo "<script> alert('Not a Course installation file'); window.history.go(-1); </script>\n";
        exit;
    }
    $course = new stdClass();
    // ****************************************************************************************************
    //get config values
    $query = "SELECT * FROM `#__lms_config`";
    $JLMS_DB->SetQuery($query);
    $lms_cfg = $JLMS_DB->LoadObjectList();
    $lms_cfg_doc_folder = '';
    $lms_cfg_scorm = '';
    $lms_cfg_backup_folder = '';
    $lms_cfg_quiz_enabled = 0;
    foreach ($lms_cfg as $lcf) {
        if ($lcf->lms_config_var == 'plugin_quiz') {
            $lms_cfg_quiz_enabled = $lcf->lms_config_value;
        } elseif ($lcf->lms_config_var == 'jlms_doc_folder') {
            $lms_cfg_doc_folder = $lcf->lms_config_value;
        } elseif ($lcf->lms_config_var == 'scorm_folder') {
            $lms_cfg_scorm = $lcf->lms_config_value;
        } elseif ($lcf->lms_config_var == 'jlms_backup_folder') {
            $lms_cfg_backup_folder = $lcf->lms_config_value;
        }
    }
    // ****************************************************************************************************
    // Get course DATA and insert it into the 'lms_courses' table
    if (!$course_id) {
        $element =& $root->getElementByPath('name');
        if (!$course_zname) {
            $course->course_name = $element ? $element->data() : '';
        } else {
            $course->course_name = $course_zname;
        }
        if ($course->course_name) {
            $element =& $root->getElementByPath('description');
            $course->course_description = $element ? $element->data() : '';
            //	echo $xmlDoc->getErrorString();
            //	var_dump($course->course_description); die;
            $element =& $root->getElementByPath('metadesc');
            $course->metadesc = $element ? $element->data() : '';
            $element =& $root->getElementByPath('metakeys');
            $course->metakeys = $element ? $element->data() : '';
            $element =& $root->getElementByPath('self_registration');
            $course->self_reg = $element ? $element->data() : '';
            $element =& $root->getElementByPath('course_paid');
            $course->paid = $element ? $element->data() : 0;
            $course->add_forum = 0;
            $course->add_chat = 0;
            $course->owner_id = $my->id;
            $course->published = 0;
            $element =& $root->getElementByPath('publish_start');
            $course->publish_start = $element ? $element->data() : 0;
            $element =& $root->getElementByPath('publish_end');
            $course->publish_end = $element ? $element->data() : 0;
            $element =& $root->getElementByPath('publish_start_date');
            $course->start_date = $element ? $element->data() : '0000-00-00';
            $element =& $root->getElementByPath('publish_end_date');
            $course->end_date = $element ? $element->data() : '0000-00-00';
            $element =& $root->getElementByPath('spec_reg');
            $course->spec_reg = $element ? $element->data() : 0;
            $course->cat_id = 0;
            $element =& $root->getElementByPath('course_category');
            $course_category_txt = $element ? $element->data() : '';
            $element =& $root->getElementByPath('course_question');
            $course_question_txt = $element ? $element->data() : '';
            // 02.03.2007 1.0.1 support
            $element =& $root->getElementByPath('course_params');
            $params_txt = $element ? $element->data() : '';
            $course->params = '';
            $params = new JLMSParameters($params_txt);
            $params->def('lpath_redirect', 0);
            $params->def('agenda_view', 0);
            $params->def('dropbox_view', 0);
            $params->def('homework_view', 0);
            $params->def('learn_path', 0);
            $course_redirect_lp = $params->get('learn_path');
            $params->set('learn_path', 0);
            $params_ar = $params->toArray();
            if (is_array($params_ar)) {
                foreach ($params_ar as $k => $v) {
                    $txt[] = "{$k}={$v}";
                }
                $course->params = implode("\n", $txt);
            }
            // to do:
            // check lpath_redirect parameter !!!!!!!!!
            $course->gid = 0;
            if ($course_category_txt) {
                $query = "SELECT id FROM #__lms_course_cats WHERE c_category = '" . $course_category_txt . "'";
                $JLMS_DB->SetQuery($query);
                $course_cat_id = $JLMS_DB->LoadResult();
                if ($course_cat_id) {
                    $course->cat_id = $course_cat_id;
                }
            }
            $course->language = 0;
            $element =& $root->getElementByPath('language_name');
            $course_lang_txt = $element ? $element->data() : '';
            if ($course_lang_txt) {
                $query = "SELECT id FROM #__lms_languages WHERE lang_name = '" . $course_lang_txt . "'";
                $JLMS_DB->SetQuery($query);
                $course_lang_id = $JLMS_DB->LoadResult();
                if ($course_lang_id) {
                    $course->language = $course_lang_id;
                }
            }
            $JLMS_DB->insertObject("#__lms_courses", $course, "id");
            //get new Course_id
            $course_id = $JLMS_DB->insertid();
            $is_new_course = true;
            $default_teacher_role = 0;
            $query = "SELECT id FROM #__lms_usertypes WHERE roletype_id = 2 AND default_role = 1 LIMIT 0,1";
            $JLMS_DB->setQuery($query);
            $default_teacher_role = intval($JLMS_DB->LoadResult());
            if (!$default_teacher_role) {
                $query = "SELECT id FROM #__lms_usertypes WHERE roletype_id = 2 LIMIT 0,1";
                $JLMS_DB->setQuery($query);
                $default_teacher_role = intval($JLMS_DB->LoadResult());
                if (!$default_teacher_role) {
                    $default_teacher_role = 1;
                }
            }
            // create teacher for imported course
            $query = "INSERT INTO `#__lms_user_courses` (user_id, course_id, role_id) VALUES ('" . $my->id . "','" . $course_id . "','" . $default_teacher_role . "')";
            $JLMS_DB->setQuery($query);
            $JLMS_DB->query();
            // commented by DEN - 27.03.2008 - enrollment questions are moved into another section
            /*if ($course->spec_reg && $course_question_txt) {
            			$query = "INSERT INTO #__lms_spec_reg_questions (course_id, course_question) VALUES ($course_id, ".$JLMS_DB->Quote($course_question_txt).")";
            			$JLMS_DB->SetQuery( $query );
            			$JLMS_DB->query();
            		}*/
            // ****************************************************************************************************
            // Get hidden menu items DATA, insert it into 'lms_local_menu' table
            //get hidden menu items array from xml
            $element =& $root->getElementByPath('hidden_menu_items');
            $hidden_menus = JLMS_parse_XML_elements($element->children(), array('menu_id', 'user_access'), array());
            $i = 0;
            while ($i < count($hidden_menus)) {
                $hdmn = new stdClass();
                $hdmn->course_id = $course_id;
                $hdmn->menu_id = $hidden_menus[$i]->menu_id;
                $hdmn->user_access = $hidden_menus[$i]->user_access;
                $query = "INSERT INTO #__lms_local_menu (course_id, menu_id, user_access) " . "\n VALUES (" . $course_id . ", " . intval($hdmn->menu_id) . ", " . intval($hdmn->user_access) . ")";
                $JLMS_DB->SetQuery($query);
                $JLMS_DB->query();
                $i++;
            }
        }
    }
    if ($course_id) {
        //get hidden menu items array from xml
        $element =& $root->getElementByPath('course_questions');
        $course_questions = JLMS_parse_XML_elements($element->children(), array('is_optional', 'ordering'), array('question_text', 'default_answer'));
        if (isset($course_question_txt) && $course_question_txt) {
            $add = new stdClass();
            $add->is_optional = 0;
            $add->ordering = 0;
            $add->question_text = $course_question_txt;
            $add->default_answer = '';
            $course_questions[] = $add;
        }
        $i = 0;
        while ($i < count($course_questions)) {
            $insert = new stdClass();
            $insert->course_id = $course_id;
            $insert->is_optional = $course_questions[$i]->is_optional;
            $insert->ordering = $course_questions[$i]->ordering;
            $insert->question_text = $course_questions[$i]->question_text;
            $insert->default_answer = $course_questions[$i]->default_answer;
            $insert->role_id = 0;
            $JLMS_DB->insertObject("#__lms_spec_reg_questions", $insert, "id");
            $i++;
        }
        /*$element 					= &$root->getElementsByPath('course_price', 1);
        		$course_price				= $element ? $element->data() : 0;
        		$query = "INSERT INTO #__lms_course_price (course_id, price ) VALUES('".$course_id."', '".$course_price."')";
        		$JLMS_DB->SetQuery( $query );
        		$JLMS_DB->query();*/
        // ****************************************************************************************************
        // Get files DATA, insert it into 'lms_files' table and copy files to the 'lms_files' folder
        //get files array from xml
        $element =& $root->getElementByPath('files');
        $files_pre = JLMS_parse_XML_elements($element->children(), array('id'), array('filename', 'servername'));
        // 05 June 2007. Nugno sformirovat' spisok of files - tol'ko tex? kotoryi deistvitel'no budut importirovat'sya
        //					(t.e. s uchetom vybrannyx tools pri 'import').
        $documents = array();
        if (in_array(1, $imp_tools)) {
            $element =& $root->getElementByPath('documents');
            $documents = JLMS_parse_XML_elements($element->children(), array('id', 'file_id', 'folder_flag', 'collapsed_folder', 'parent_id', 'ordering', 'published', 'publish_start', 'start_date', 'publish_start', 'publish_end', 'end_date', 'is_time_related', 'show_period'), array('doc_name', 'doc_description'));
        }
        $element =& $root->getElementByPath('certificates');
        $certificates = JLMS_parse_XML_elements($element->children(), array('id', 'file_id', 'crtf_type', 'text_x', 'text_y', 'text_size'), array('certificate_text', 'certificate_font'));
        $element =& $root->getElementByPath('certificate_texts');
        $certificate_texts = JLMS_parse_XML_elements($element->children(), array('parent_id', 'crtf_type', 'text_x', 'text_y', 'text_size'), array('add_certificate_text', 'certificate_font'));
        $quiz_images2 = array();
        // for fields 'c_image' of the question (e.g. hostspot)
        $quiz_images = array();
        if (in_array(5, $imp_tools)) {
            $element_qimg =& $root->getElementByPath('quizzes_images');
            $quiz_images = JLMS_parse_XML_elements($element_qimg->children(), array('c_id', 'file_id'), array('quiz_image_name'));
        }
        /*if (in_array(5,$cid)) {
        			$query = "SELECT * FROM `#__lms_certificates` WHERE course_id = '$course_id'";
        		} else {
        			$query = "SELECT * FROM `#__lms_certificates` WHERE course_id = '$course_id' AND crtf_type <> 2";
        		}*/
        $files = array();
        foreach ($documents as $doc) {
            foreach ($files_pre as $file_pre) {
                if ($doc->file_id == $file_pre->id) {
                    $is_exists = false;
                    foreach ($files as $file_ex) {
                        if ($file_ex->id == $file_pre->id) {
                            $is_exists = true;
                            break;
                        }
                    }
                    if (!$is_exists) {
                        $files[] = $file_pre;
                    }
                    break;
                }
            }
        }
        foreach ($certificates as $crtf) {
            foreach ($files_pre as $file_pre) {
                if ($crtf->file_id == $file_pre->id) {
                    $do_add = false;
                    if ($crtf->crtf_type == 2) {
                        if (in_array(5, $imp_tools)) {
                            $do_add = true;
                        }
                    } else {
                        $do_add = true;
                    }
                    if ($do_add) {
                        $is_exists = false;
                        foreach ($files as $file_ex) {
                            if ($file_ex->id == $file_pre->id) {
                                $is_exists = true;
                                break;
                            }
                        }
                        if (!$is_exists) {
                            $files[] = $file_pre;
                        }
                        break;
                    }
                }
            }
        }
        foreach ($quiz_images as $qimg) {
            foreach ($files_pre as $file_pre) {
                if ($qimg->file_id == $file_pre->id) {
                    $is_exists = false;
                    foreach ($files as $file_ex) {
                        if ($file_ex->id == $file_pre->id) {
                            $is_exists = true;
                            break;
                        }
                    }
                    if (!$is_exists) {
                        $files[] = $file_pre;
                    }
                    break;
                }
            }
        }
        $i = 0;
        $fromDir = $extract_dir . "files/";
        $toDir = $lms_cfg_doc_folder . "/";
        while ($i < count($files)) {
            $insert_file = new stdClass();
            $insert_file->file_name = $files[$i]->filename;
            $file_unique_name = str_pad($course_id, 4, '0', STR_PAD_LEFT) . '_' . md5(uniqid(rand(), true)) . '.' . substr($files[$i]->servername, -3);
            $insert_file->file_srv_name = $file_unique_name;
            $insert_file->owner_id = $my->id;
            $JLMS_DB->insertObject("#__lms_files", $insert_file, "id");
            $files[$i]->new_file_id = $JLMS_DB->insertid();
            rename($fromDir . $files[$i]->servername, $toDir . $file_unique_name);
            $i++;
        }
        $zip_docs = array();
        if (in_array(1, $imp_tools)) {
            // ****************************************************************************************************
            // Get ZIPPACK's DATA, insert it into 'lms_documents_zip' table and copy zippack files to the 'lms_scorm' folder
            $fromDir = $extract_dir . "zippacks/";
            $toDir = $JLMS_CONFIG->getCfg('absolute_path') . "/" . $lms_cfg_scorm . "/";
            $element =& $root->getElementByPath('zipped_documents');
            $zip_docs = JLMS_parse_XML_elements($element->children(), array('id', 'upload_time', 'count_files', 'zip_size', 'zipfile_size', 'is_time_related', 'show_period'), array('zip_folder', 'zip_srv_name', 'zip_name', 'startup_file'));
            $i = 0;
            while ($i < count($zip_docs)) {
                $insert = new stdClass();
                $insert->owner_id = $my->id;
                $insert->course_id = $course_id;
                $folder_unique_name = str_pad($my->id, 4, '0', STR_PAD_LEFT) . '_zip_' . md5(uniqid(rand(), true));
                $insert->zip_folder = $folder_unique_name;
                $file_unique_name = $folder_unique_name . ".zip";
                $insert->zip_srv_name = $file_unique_name;
                $insert->zip_name = $zip_docs[$i]->zip_name;
                $insert->startup_file = $zip_docs[$i]->startup_file;
                $insert->count_files = $zip_docs[$i]->count_files;
                $insert->zip_size = $zip_docs[$i]->zip_size;
                $insert->zipfile_size = $zip_docs[$i]->zipfile_size;
                $insert->upload_time = date('Y-m-d H:i:s');
                //$scorms[$i]->upload_time;
                //insert into DB
                $JLMS_DB->insertObject("#__lms_documents_zip", $insert, "id");
                $zip_docs[$i]->new_zip_id = $JLMS_DB->insertid();
                //move scrom package
                rename($fromDir . $zip_docs[$i]->zip_srv_name, $toDir . $file_unique_name);
                //extract SCORM package archive
                extractBackupArchive($toDir . $file_unique_name, $toDir . $folder_unique_name);
                $i++;
            }
        }
        if (in_array(1, $imp_tools)) {
            // ****************************************************************************************************
            // Get documents DATA and insert it into the 'lms_documents' table
            //$element = &$root->getElementsByPath('documents', 1);
            //$documents = JLMS_parse_XML_elements($element->children(), array('id', 'file_id', 'folder_flag', 'parent_id', 'ordering', 'published', 'publish_start', 'start_date', 'publish_start', 'publish_end', 'end_date'), array('doc_name', 'doc_description'));
            // 05 June 2007 - this array is generated above (~~ line 270)
            $j = 0;
            $collapsed_folders = array();
            while ($j < count($documents)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->owner_id = $my->id;
                $insert->file_id = 0;
                if ($documents[$j]->file_id) {
                    if ($documents[$j]->folder_flag == 2) {
                        // search $zip_docs for new file_id
                        for ($i = 0; $i < count($zip_docs); $i++) {
                            if ($zip_docs[$i]->id == $documents[$j]->file_id) {
                                $insert->file_id = $zip_docs[$i]->new_zip_id;
                                break;
                            }
                        }
                    } else {
                        // search $files for new file_id
                        for ($i = 0; $i < count($files); $i++) {
                            if ($files[$i]->id == $documents[$j]->file_id) {
                                $insert->file_id = $files[$i]->new_file_id;
                                break;
                            }
                        }
                    }
                }
                $insert->folder_flag = $documents[$j]->folder_flag;
                $insert->doc_name = $documents[$j]->doc_name;
                $insert->doc_description = $documents[$j]->doc_description;
                $insert->ordering = $documents[$j]->ordering;
                $insert->published = $documents[$j]->published;
                $insert->publish_start = $documents[$j]->publish_start;
                $insert->start_date = $documents[$j]->start_date;
                $insert->publish_end = $documents[$j]->publish_end;
                $insert->end_date = $documents[$j]->end_date;
                $insert->is_time_related = $documents[$i]->is_time_related;
                $insert->show_period = $documents[$i]->show_period;
                // search processed $documents for parent_id
                $parent = $documents[$j]->parent_id;
                if ($parent) {
                    $a = 0;
                    while ($a < $j) {
                        if ($documents[$a]->id == $parent) {
                            $parent = $documents[$a]->new_doc_id;
                            break;
                        }
                        $a++;
                    }
                }
                $insert->parent_id = $parent;
                $do_ins_object = true;
                $ins_object_folder_already_exists_id = 0;
                if ($insert->folder_flag == 1 && $course_id) {
                    //if we are merging imported course with already existeten course, then some folders can be already exists
                    $query = "SELECT id FROM #__lms_documents WHERE doc_name = " . $JLMS_DB->quote($insert->doc_name) . " AND parent_id = " . intval($insert->parent_id) . " AND folder_flag = 1 AND file_id = 0 AND course_id = {$course_id}";
                    $JLMS_DB->SetQuery($query);
                    $ins_object_folder_already_exists_id = $JLMS_DB->LoadResult();
                    if ($ins_object_folder_already_exists_id) {
                        $do_ins_object = false;
                    }
                }
                if ($do_ins_object) {
                    $JLMS_DB->insertObject("#__lms_documents", $insert, "id");
                    $documents[$j]->new_doc_id = $JLMS_DB->insertid();
                } else {
                    $documents[$j]->new_doc_id = $ins_object_folder_already_exists_id;
                }
                if ($do_ins_object) {
                    if ($documents[$j]->folder_flag == 1 && !$documents[$j]->file_id && $documents[$j]->collapsed_folder) {
                        $collapsed_folders[] = $documents[$j]->new_doc_id;
                    }
                }
                $j++;
            }
            if (!empty($collapsed_folders)) {
                $query = "INSERT INTO #__lms_documents_view (course_id, doc_id) VALUES";
                $s = '';
                $is_add = false;
                foreach ($collapsed_folders as $cf) {
                    if ($cf) {
                        $is_add = true;
                        $query .= $s . "\n ({$course_id}, {$cf})";
                        $s = ',';
                    }
                }
                if ($is_add) {
                    $JLMS_DB->SetQuery($query);
                    $JLMS_DB->query();
                }
            }
        }
        $scorms = array();
        if (in_array(3, $imp_tools)) {
            // ****************************************************************************************************
            // Get SCORM's DATA, insert it into 'lms_scorm_packages' table and copy scorm files to the 'lms_scorm' folder
            $fromDir = $extract_dir . "scorm/";
            $toDir = $JLMS_CONFIG->getCfg('absolute_path') . "/" . $lms_cfg_scorm . "/";
            $element =& $root->getElementByPath('scorms');
            $scorms = JLMS_parse_XML_elements($element->children(), array('id', 'upload_time'), array('foldersrvname', 'packagesrvname', 'packageusername'));
            $i = 0;
            while ($i < count($scorms)) {
                $insert = new stdClass();
                $insert->owner_id = $my->id;
                $insert->course_id = $course_id;
                $folder_unique_name = str_pad($my->id, 4, '0', STR_PAD_LEFT) . '_' . md5(uniqid(rand(), true));
                $insert->folder_srv_name = $folder_unique_name;
                $file_unique_name = $folder_unique_name . ".zip";
                $insert->package_srv_name = $file_unique_name;
                $insert->package_user_name = $scorms[$i]->packageusername;
                $insert->upload_time = date('Y-m-d H:i:s');
                //$scorms[$i]->upload_time;
                //insert into DB
                $JLMS_DB->insertObject("#__lms_scorm_packages", $insert, "id");
                $scorms[$i]->new_sco_id = $JLMS_DB->insertid();
                //move scrom package
                rename($fromDir . $scorms[$i]->packagesrvname, $toDir . $file_unique_name);
                //extract SCORM package archive
                extractBackupArchive($toDir . $file_unique_name, $toDir . $folder_unique_name);
                $i++;
            }
        }
        $links = array();
        if (in_array(4, $imp_tools)) {
            // ****************************************************************************************************
            // Get links DATA and insert it into the 'lms_links' table
            $element =& $root->getElementByPath('links');
            $links = JLMS_parse_XML_elements($element->children(), array('id', 'link_type', 'ordering', 'published', 'is_time_related', 'show_period'), array('linkname', 'linkhref', 'description', 'link_params'));
            $i = 0;
            while ($i < count($links)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->owner_id = $my->id;
                $insert->link_name = $links[$i]->linkname;
                $insert->link_href = $links[$i]->linkhref;
                $insert->link_description = $links[$i]->description;
                $insert->link_type = $links[$i]->link_type;
                $insert->ordering = $links[$i]->ordering;
                $insert->published = $links[$i]->published;
                $insert->is_time_related = $links[$i]->is_time_related;
                $insert->show_period = $links[$i]->show_period;
                $insert->params = $links[$i]->link_params;
                $JLMS_DB->insertObject("#__lms_links", $insert, "id");
                $links[$i]->new_link_id = $JLMS_DB->insertid();
                $i++;
            }
        }
        $homeworks = array();
        if (in_array(7, $imp_tools)) {
            // ****************************************************************************************************
            // Get homeworks DATA and insert it into the 'lms_homework' table
            $element =& $root->getElementByPath('homework_tool');
            $homeworks = JLMS_parse_XML_elements($element->children(), array('id', 'post_date', 'end_date', 'is_time_related', 'show_period'), array('hw_name', 'description', 'short_description'));
            $i = 0;
            while ($i < count($homeworks)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->hw_name = $homeworks[$i]->hw_name;
                $insert->hw_description = $homeworks[$i]->description;
                $insert->hw_shortdescription = $homeworks[$i]->short_description;
                $insert->post_date = $homeworks[$i]->post_date;
                $insert->end_date = $homeworks[$i]->end_date;
                $insert->is_time_related = $homeworks[$i]->is_time_related;
                $insert->show_period = $homeworks[$i]->show_period;
                $JLMS_DB->insertObject("#__lms_homework", $insert, "id");
                $homeworks[$i]->new_hw_id = $JLMS_DB->insertid();
                $i++;
            }
        }
        $announcements = array();
        if (in_array(6, $imp_tools)) {
            // ****************************************************************************************************
            // Get announcements DATA and insert it into the 'lms_agenda' table
            $element =& $root->getElementByPath('announcement_tool');
            $announcements = JLMS_parse_XML_elements($element->children(), array('id', 'start_date', 'end_date', 'is_time_related', 'show_period'), array('announcement_title', 'announcement_content'));
            $i = 0;
            while ($i < count($announcements)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->owner_id = $my->id;
                $insert->title = $announcements[$i]->announcement_title;
                $insert->content = $announcements[$i]->announcement_content;
                $insert->start_date = $announcements[$i]->start_date;
                $insert->end_date = $announcements[$i]->end_date;
                $insert->is_time_related = $announcements[$i]->is_time_related;
                $insert->show_period = $announcements[$i]->show_period;
                $JLMS_DB->insertObject("#__lms_agenda", $insert, "agenda_id");
                $announcements[$i]->new_ag_id = $JLMS_DB->insertid();
                $i++;
            }
        }
        // ****************************************************************************************************
        // Get certificates DATA and insert it into the 'lms_certificates' table
        //$element = &$root->getElementsByPath('certificates', 1);
        //$certificates = JLMS_parse_XML_elements($element->children(), array('id', 'file_id', 'crtf_type', 'text_x', 'text_y', 'text_size'), array('certificate_text'));
        // 05 June 2007 - this array is generated above (~~ line 270)
        $i = 0;
        $crtf_ids_exp = array();
        while ($i < count($certificates)) {
            $do_add = false;
            if ($certificates[$i]->crtf_type == 2) {
                if (in_array(5, $imp_tools)) {
                    $do_add = true;
                }
            } else {
                $do_add = true;
            }
            if ($do_add) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->file_id = 0;
                $insert->parent_id = 0;
                if ($certificates[$i]->file_id) {
                    for ($k = 0; $k < count($files); $k++) {
                        if ($files[$k]->id == $certificates[$i]->file_id) {
                            $insert->file_id = $files[$k]->new_file_id;
                            break;
                        }
                    }
                }
                $insert->crtf_text = $certificates[$i]->certificate_text;
                $insert->crtf_font = $certificates[$i]->certificate_font;
                $insert->text_x = $certificates[$i]->text_x;
                $insert->text_y = $certificates[$i]->text_y;
                $insert->text_size = $certificates[$i]->text_size;
                $insert->crtf_type = $certificates[$i]->crtf_type;
                if ($insert->crtf_type == 1) {
                    $insert->published = 0;
                }
                $JLMS_DB->insertObject("#__lms_certificates", $insert, "id");
                $certificates[$i]->new_id = $JLMS_DB->insertid();
                $crtf_ids_exp[] = $certificates[$i]->id;
            }
            $i++;
        }
        // 27.03.2008 (DEN) - Additional certificate texts
        $i = 0;
        while ($i < count($certificate_texts)) {
            $do_add = false;
            if ($certificates[$i]->crtf_type == -2 && $certificates[$i]->parent_id) {
                if (in_array($certificates[$i]->parent_id, $crtf_ids_exp)) {
                    $do_add = true;
                }
            }
            if ($do_add) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->file_id = 0;
                $insert->parent_id = 0;
                for ($k = 0; $k < count($certificates); $k++) {
                    if ($certificates[$k]->id == $certificate_texts[$i]->parent_id) {
                        $insert->parent_id = $certificates[$k]->new_id;
                        break;
                    }
                }
                if ($insert->parent_id) {
                    $insert->crtf_text = $certificate_texts[$i]->add_certificate_text;
                    $insert->crtf_font = $certificate_texts[$i]->certificate_font;
                    $insert->text_x = $certificate_texts[$i]->text_x;
                    $insert->text_y = $certificate_texts[$i]->text_y;
                    $insert->text_size = $certificate_texts[$i]->text_size;
                    $insert->crtf_type = $certificate_texts[$i]->crtf_type;
                    $JLMS_DB->insertObject("#__lms_certificates", $insert, "id");
                    $certificate_texts[$i]->new_id = $JLMS_DB->insertid();
                }
            }
            $i++;
        }
        $quizzes = array();
        if (in_array(5, $imp_tools)) {
            // ****************************************************************************************************
            // Get Quizzes DATA and insert it into the DB
            //if ($lms_cfg_quiz_enabled) { // commented 05.03.2007 (to put exported quizzes into LP anywhere) (else we've got errors in LP)
            /* 28 April 2007 (DEN) - Question categories processing
             *
             */
            $element_qcat =& $root->getElementByPath('quizzes_quest_categories');
            $quest_cats = JLMS_parse_XML_elements($element_qcat->children(), array('c_id'), array('quest_category_name', 'quest_category_instr'));
            $i = 0;
            while ($i < count($quest_cats)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->c_category = $quest_cats[$i]->quest_category_name;
                $insert->c_instruction = $quest_cats[$i]->quest_category_instr;
                $insert->is_quiz_cat = 0;
                $JLMS_DB->insertObject("#__lms_quiz_t_category", $insert, "c_id");
                $quest_cats[$i]->new_qcat_id = $JLMS_DB->insertid();
                $i++;
            }
            /* 27 March 2008 (DEN) - Quizzes images processing
             * (variable $quiz_images defined above)
             */
            $i = 0;
            while ($i < count($quiz_images)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->imgs_name = $quiz_images[$i]->quiz_image_name;
                $insert->imgs_id = 0;
                if ($quiz_images[$i]->file_id) {
                    for ($k = 0; $k < count($files); $k++) {
                        if ($files[$k]->id == $quiz_images[$i]->file_id) {
                            $insert->imgs_id = $files[$k]->new_file_id;
                            break;
                        }
                    }
                }
                if ($insert->imgs_id) {
                    $JLMS_DB->insertObject("#__lms_quiz_images", $insert, "c_id");
                    $quiz_images[$i]->new_img_id = $JLMS_DB->insertid();
                    $quiz_images[$i]->imgs_new_id = $insert->imgs_id;
                    // Axtung!: vse tablicy nabora question options (like 't_choice', 't_matching') are stores imgs_id instead of id from #__lms_quiz_images
                }
                $i++;
            }
            /* 28 April 2007 (DEN) - Questions Pool processing
             *
             */
            $element_pool =& $root->getElementByPath('quizzes_question_pool');
            $q_pool = JLMS_parse_XML_elements($element_pool->children(), array(), array(), true, array('pool_questions', 'question_feedbacks', 'choice_data', 'match_data', 'scale_data', 'blank_data', 'hotspot_data'), array(array('c_id', 'c_point', 'c_attempts', 'c_type', 'c_pool', 'c_qcat', 'ordering'), array('quest_id', 'choice_id'), array('c_question_id', 'c_right', 'ordering'), array('c_question_id', 'ordering'), array('c_question_id', 'c_type', 'ordering'), array('c_question_id', 'ordering'), array('c_question_id')), array(array('question_text', 'question_image', 'question_params', 'question_explanation'), array('fb_text'), array('choice_text'), array('match_text_left', 'match_text_right'), array('scale_field'), array('blank_text', 'default_answer'), array('hs_start_x', 'hs_start_y', 'hs_width', 'hs_height')));
            $i = 0;
            while ($i < count($q_pool)) {
                //questions processing
                $j = 0;
                while ($j < count($q_pool[$i]->pool_questions)) {
                    $quest = new stdClass();
                    $quest->course_id = $course_id;
                    $quest->c_quiz_id = 0;
                    //$new_quiz_id;
                    $quest->c_point = $q_pool[$i]->pool_questions[$j]->c_point;
                    $quest->c_attempts = $q_pool[$i]->pool_questions[$j]->c_attempts;
                    $quest->c_question = $q_pool[$i]->pool_questions[$j]->question_text;
                    $quest->c_image = $q_pool[$i]->pool_questions[$j]->question_image;
                    $quest->params = $q_pool[$i]->pool_questions[$j]->question_params;
                    $quest->c_explanation = $q_pool[$i]->pool_questions[$j]->question_explanation;
                    // added 27.03.2008 (DEN)
                    $quest->c_type = $q_pool[$i]->pool_questions[$j]->c_type;
                    $quest->c_pool = 0;
                    //$q_pool[$i]->pool_questions[$j]->c_pool;
                    $quest->c_qcat = 0;
                    if ($q_pool[$i]->pool_questions[$j]->c_qcat) {
                        for ($ij = 0; $ij < count($quest_cats); $ij++) {
                            if ($quest_cats[$ij]->c_id == $q_pool[$i]->pool_questions[$j]->c_qcat) {
                                $quest->c_qcat = $quest_cats[$ij]->new_qcat_id;
                                break;
                            }
                        }
                    }
                    $quest->ordering = $q_pool[$i]->pool_questions[$j]->ordering;
                    if ($q_pool[$i]->pool_questions[$j]->question_image && !in_array($q_pool[$i]->pool_questions[$j]->question_image, $quiz_images2)) {
                        // Changed 20.08.2007 by DEN - from:
                        //if ($q_pool[$i]->pool_questions[$j]->question_image) {
                        $quiz_images2[] = $q_pool[$i]->pool_questions[$j]->question_image;
                    }
                    $JLMS_DB->insertObject("#__lms_quiz_t_question", $quest, "c_id");
                    $q_pool[$i]->pool_questions[$j]->new_id = $JLMS_DB->insertid();
                    $j++;
                }
                //feedbacks processing
                $j = 0;
                while ($j < count($q_pool[$i]->question_feedbacks)) {
                    $q_fb = new stdClass();
                    $q_fb->choice_id = $q_pool[$i]->question_feedbacks[$j]->choice_id;
                    $q_fb->fb_text = $q_pool[$i]->question_feedbacks[$j]->fb_text;
                    $q_fb->quest_id = 0;
                    for ($k = 0; $k < count($q_pool[$i]->pool_questions); $k++) {
                        if ($q_pool[$i]->pool_questions[$k]->c_id == $q_pool[$i]->question_feedbacks[$j]->quest_id) {
                            $q_fb->quest_id = isset($q_pool[$i]->pool_questions[$k]->new_id) ? intval($q_pool[$i]->pool_questions[$k]->new_id) : 0;
                            break;
                        }
                    }
                    if ($q_fb->quest_id && $q_fb->fb_text && ($q_fb->choice_id == -1 || $q_fb->choice_id == 0)) {
                        $query = "INSERT INTO #__lms_quiz_t_question_fb (quest_id, choice_id, fb_text) VALUES ({$q_fb->quest_id}, {$q_fb->choice_id}, " . $JLMS_DB->Quote($q_fb->fb_text) . ")";
                        $JLMS_DB->SetQuery($query);
                        $JLMS_DB->query();
                    }
                    $j++;
                }
                //choices processing
                $j = 0;
                while ($j < count($q_pool[$i]->choice_data)) {
                    $q_choice = new stdClass();
                    $q_choice->c_choice = $q_pool[$i]->choice_data[$j]->choice_text;
                    $q_choice->c_right = $q_pool[$i]->choice_data[$j]->c_right;
                    $q_choice->ordering = $q_pool[$i]->choice_data[$j]->ordering;
                    $q_choice->c_question_id = 0;
                    for ($k = 0; $k < count($q_pool[$i]->pool_questions); $k++) {
                        if ($q_pool[$i]->pool_questions[$k]->c_id == $q_pool[$i]->choice_data[$j]->c_question_id) {
                            $q_choice->c_question_id = isset($q_pool[$i]->pool_questions[$k]->new_id) ? $q_pool[$i]->pool_questions[$k]->new_id : 0;
                            if ($q_pool[$i]->pool_questions[$k]->c_type == 12 || $q_pool[$i]->pool_questions[$k]->c_type == 13) {
                                $q_choice->c_choice = intval($q_choice->c_choice);
                                for ($kk = 0; $kk < count($quiz_images); $kk++) {
                                    if ($q_choice->c_choice == $quiz_images[$kk]->file_id) {
                                        $q_choice->c_choice = isset($quiz_images[$kk]->imgs_new_id) ? intval($quiz_images[$kk]->imgs_new_id) : 0;
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                    if ($q_choice->c_question_id) {
                        $JLMS_DB->insertObject("#__lms_quiz_t_choice", $q_choice, "c_id");
                    }
                    $j++;
                }
                //matching processing
                $j = 0;
                while ($j < count($q_pool[$i]->match_data)) {
                    $q_match = new stdClass();
                    $q_match->c_left_text = $q_pool[$i]->match_data[$j]->match_text_left;
                    $q_match->c_right_text = $q_pool[$i]->match_data[$j]->match_text_right;
                    $q_match->ordering = $q_pool[$i]->match_data[$j]->ordering;
                    $q_match->c_question_id = 0;
                    for ($k = 0; $k < count($q_pool[$i]->pool_questions); $k++) {
                        if ($q_pool[$i]->pool_questions[$k]->c_id == $q_pool[$i]->match_data[$j]->c_question_id) {
                            $q_match->c_question_id = isset($q_pool[$i]->pool_questions[$k]->new_id) ? $q_pool[$i]->pool_questions[$k]->new_id : 0;
                            if ($q_pool[$i]->pool_questions[$k]->c_type == 11) {
                                $q_match->c_left_text = intval($q_match->c_left_text);
                                $q_match->c_right_text = intval($q_match->c_right_text);
                                $is_changed_match_images = 0;
                                for ($kk = 0; $kk < count($quiz_images); $kk++) {
                                    if ($q_match->c_left_text == $quiz_images[$kk]->file_id) {
                                        $q_match->c_left_text = isset($quiz_images[$kk]->imgs_new_id) ? intval($quiz_images[$kk]->imgs_new_id) : 0;
                                        $is_changed_match_images++;
                                        if ($is_changed_match_images == 2) {
                                            break;
                                        }
                                    }
                                    if ($q_match->c_right_text == $quiz_images[$kk]->file_id) {
                                        $q_match->c_right_text = isset($quiz_images[$kk]->imgs_new_id) ? intval($quiz_images[$kk]->imgs_new_id) : 0;
                                        $is_changed_match_images++;
                                        if ($is_changed_match_images == 2) {
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }
                    if ($q_match->c_question_id) {
                        $JLMS_DB->insertObject("#__lms_quiz_t_matching", $q_match, "c_id");
                    }
                    $j++;
                }
                //likert scale processing (27.03.2008 - DEN)
                $j = 0;
                while ($j < count($q_pool[$i]->scale_data)) {
                    $q_scale = new stdClass();
                    $q_scale->c_field = $q_pool[$i]->scale_data[$j]->scale_field;
                    $q_scale->c_type = $q_pool[$i]->scale_data[$j]->c_type;
                    $q_scale->ordering = $q_pool[$i]->scale_data[$j]->ordering;
                    $q_scale->c_question_id = 0;
                    for ($k = 0; $k < count($q_pool[$i]->pool_questions); $k++) {
                        if ($q_pool[$i]->pool_questions[$k]->c_id == $q_pool[$i]->scale_data[$j]->c_question_id) {
                            $q_scale->c_question_id = isset($q_pool[$i]->pool_questions[$k]->new_id) ? $q_pool[$i]->pool_questions[$k]->new_id : 0;
                            break;
                        }
                    }
                    if ($q_scale->c_question_id) {
                        $JLMS_DB->insertObject("#__lms_quiz_t_scale", $q_scale, "c_id");
                    }
                    $j++;
                }
                //hotspot processing
                $j = 0;
                while ($j < count($q_pool[$i]->hotspot_data)) {
                    $q_hotspot = new stdClass();
                    $q_hotspot->c_start_x = $q_pool[$i]->hotspot_data[$j]->hs_start_x;
                    $q_hotspot->c_start_y = $q_pool[$i]->hotspot_data[$j]->hs_start_y;
                    $q_hotspot->c_width = $q_pool[$i]->hotspot_data[$j]->hs_width;
                    $q_hotspot->c_height = $q_pool[$i]->hotspot_data[$j]->hs_height;
                    $q_hotspot->c_question_id = 0;
                    for ($k = 0; $k < count($q_pool[$i]->pool_questions); $k++) {
                        if ($q_pool[$i]->pool_questions[$k]->c_id == $q_pool[$i]->hotspot_data[$j]->c_question_id) {
                            $q_hotspot->c_question_id = isset($q_pool[$i]->pool_questions[$k]->new_id) ? $q_pool[$i]->pool_questions[$k]->new_id : 0;
                            break;
                        }
                    }
                    if ($q_hotspot->c_question_id) {
                        $JLMS_DB->insertObject("#__lms_quiz_t_hotspot", $q_hotspot, "c_id");
                    }
                    $j++;
                }
                //blank quests processing
                $j = 0;
                $blank_inserted = array();
                while ($j < count($q_pool[$i]->blank_data)) {
                    $q_blank = new stdClass();
                    $q_blank->c_question_id = 0;
                    $q_blank->c_default = $q_pool[$i]->blank_data[$j]->default_answer;
                    for ($k = 0; $k < count($q_pool[$i]->pool_questions); $k++) {
                        if ($q_pool[$i]->pool_questions[$k]->c_id == $q_pool[$i]->blank_data[$j]->c_question_id) {
                            $q_blank->c_question_id = isset($q_pool[$i]->pool_questions[$k]->new_id) ? $q_pool[$i]->pool_questions[$k]->new_id : 0;
                            break;
                        }
                    }
                    if ($q_blank->c_question_id) {
                        $proceed_insert = true;
                        foreach ($blank_inserted as $bains) {
                            if ($bains->quest_id == $q_blank->c_question_id) {
                                $proceed_insert = false;
                                $new_blank_id = $bains->blank_id;
                                break;
                            }
                        }
                        if ($proceed_insert) {
                            $JLMS_DB->insertObject("#__lms_quiz_t_blank", $q_blank, "c_id");
                            $new_blank_id = $JLMS_DB->insertid();
                            $blankins = new stdClass();
                            $blankins->quest_id = $q_blank->c_question_id;
                            $blankins->blank_id = $new_blank_id;
                            $blank_inserted[] = $blankins;
                        }
                        $q_blank_text = new stdClass();
                        $q_blank_text->c_blank_id = $new_blank_id;
                        $q_blank_text->c_text = $q_pool[$i]->blank_data[$j]->blank_text;
                        $q_blank_text->ordering = $q_pool[$i]->blank_data[$j]->ordering;
                        if ($q_blank_text->c_blank_id) {
                            $JLMS_DB->insertObject("#__lms_quiz_t_text", $q_blank_text, "c_id");
                        }
                    }
                    $j++;
                }
                $i++;
            }
            $element =& $root->getElementByPath('quizzes');
            $quizzes = JLMS_parse_XML_elements($element->children(), array('c_id', 'published'), array('quiz_title', 'quiz_description', 'quiz_category', 'quiz_full_score', 'quiz_time_limit', 'quiz_min_after', 'quiz_passing_score', 'quiz_right_message', 'quiz_wrong_message', 'quiz_pass_message', 'quiz_unpass_message', 'quiz_review', 'quiz_email', 'quiz_print', 'quiz_certif', 'quiz_skin', 'quiz_random', 'quiz_guest', 'quiz_slide', 'quiz_language', 'quiz_certificate', 'quiz_gradebook', 'quiz_params', 'is_time_related', 'show_period'), true, array('quiz_pool_assoc', 'quiz_questions', 'question_feedbacks', 'choice_data', 'match_data', 'scale_data', 'blank_data', 'hotspot_data'), array(array('qcat_id', 'items_number'), array('c_id', 'c_point', 'c_attempts', 'c_type', 'c_pool', 'c_qcat', 'ordering'), array('quest_id', 'choice_id'), array('c_question_id', 'c_right', 'ordering'), array('c_question_id', 'ordering'), array('c_question_id', 'c_type', 'ordering'), array('c_question_id', 'ordering'), array('c_question_id')), array(array(), array('question_text', 'question_image', 'question_params', 'question_explanation'), array('fb_text'), array('choice_text'), array('match_text_left', 'match_text_right'), array('scale_field'), array('blank_text', 'default_answer'), array('hs_start_x', 'hs_start_y', 'hs_width', 'hs_height')));
            $i = 0;
            while ($i < count($quizzes)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->c_category_id = 0;
                $quiz_cat_name = $quizzes[$i]->quiz_category;
                $query = "SELECT c_id FROM #__lms_quiz_t_category WHERE c_category = '" . $quiz_cat_name . "' AND is_quiz_cat = 1";
                $JLMS_DB->SetQuery($query);
                $quiz_cat_id = $JLMS_DB->LoadResult();
                if ($quiz_cat_id) {
                    $insert->c_category_id = $quiz_cat_id;
                } elseif ($quiz_cat_name) {
                    $query = "INSERT INTO #__lms_quiz_t_category (course_id, c_category, c_instruction, is_quiz_cat) VALUES ({$course_id}, " . $JLMS_DB->Quote($quiz_cat_name) . ", '', 1)";
                    $JLMS_DB->SetQuery($query);
                    $JLMS_DB->query();
                    $insert->c_category_id = $JLMS_DB->insertid();
                }
                $insert->c_user_id = $my->id;
                $insert->c_full_score = $quizzes[$i]->quiz_full_score;
                $insert->c_title = $quizzes[$i]->quiz_title;
                $insert->c_description = $quizzes[$i]->quiz_description;
                $insert->c_time_limit = $quizzes[$i]->quiz_time_limit;
                $insert->c_min_after = $quizzes[$i]->quiz_min_after;
                $insert->c_passing_score = $quizzes[$i]->quiz_passing_score;
                $insert->c_created_time = date('Y-m-d');
                $insert->published = $quizzes[$i]->published;
                //!!!
                $insert->c_right_message = $quizzes[$i]->quiz_right_message;
                $insert->c_wrong_message = $quizzes[$i]->quiz_wrong_message;
                $insert->c_pass_message = $quizzes[$i]->quiz_pass_message;
                $insert->c_unpass_message = $quizzes[$i]->quiz_unpass_message;
                $insert->c_enable_review = $quizzes[$i]->quiz_review;
                $insert->c_email_to = $quizzes[$i]->quiz_email;
                $insert->c_enable_print = $quizzes[$i]->quiz_print;
                $insert->c_enable_sertif = $quizzes[$i]->quiz_certif;
                $insert->c_skin = $quizzes[$i]->quiz_skin;
                $insert->c_random = $quizzes[$i]->quiz_random;
                $insert->c_guest = $quizzes[$i]->quiz_guest;
                $insert->c_skin = $quizzes[$i]->quiz_skin;
                $insert->c_slide = $quizzes[$i]->quiz_slide;
                $insert->c_language = $quizzes[$i]->quiz_language;
                $insert->params = $quizzes[$i]->quiz_params;
                $insert->is_time_related = $quizzes[$i]->is_time_related;
                $insert->show_period = $quizzes[$i]->show_period;
                $insert->c_certificate = 0;
                if ($quizzes[$i]->quiz_certificate) {
                    for ($r = 0; $r < count($certificates); $r++) {
                        if ($certificates[$r]->id == $quizzes[$i]->quiz_certificate) {
                            $insert->c_certificate = $certificates[$r]->new_id;
                            break;
                        }
                    }
                }
                $insert->c_gradebook = $quizzes[$i]->quiz_gradebook;
                $JLMS_DB->insertObject("#__lms_quiz_t_quiz", $insert, "c_id");
                $new_quiz_id = $JLMS_DB->insertid();
                $quizzes[$i]->new_quiz_id = $new_quiz_id;
                if (!empty($quizzes[$i]->quiz_pool_assoc)) {
                    $j = 0;
                    while ($j < count($quizzes[$i]->quiz_pool_assoc)) {
                        $ins_qp = new stdClass();
                        $ins_qp->quiz_id = $new_quiz_id;
                        $ins_qp->qcat_id = 0;
                        //$quizzes[$i]->quiz_pool_assoc[$j]->qcat_id;
                        if ($quizzes[$i]->quiz_pool_assoc[$j]->qcat_id) {
                            for ($ij = 0; $ij < count($quest_cats); $ij++) {
                                if ($quest_cats[$ij]->c_id == $quizzes[$i]->quiz_pool_assoc[$j]->qcat_id) {
                                    $ins_qp->qcat_id = $quest_cats[$ij]->new_qcat_id;
                                    break;
                                }
                            }
                        }
                        $ins_qp->items_number = $quizzes[$i]->quiz_pool_assoc[$j]->items_number;
                        $query = "INSERT INTO #__lms_quiz_t_quiz_pool (quiz_id, qcat_id, items_number) VALUES ({$ins_qp->quiz_id}, {$ins_qp->qcat_id}, {$ins_qp->items_number})";
                        $JLMS_DB->SetQuery($query);
                        $JLMS_DB->query();
                        $j++;
                    }
                }
                //questions processing
                $j = 0;
                while ($j < count($quizzes[$i]->quiz_questions)) {
                    $quest = new stdClass();
                    $quest->course_id = $course_id;
                    $quest->c_quiz_id = $new_quiz_id;
                    $quest->c_point = $quizzes[$i]->quiz_questions[$j]->c_point;
                    $quest->c_attempts = $quizzes[$i]->quiz_questions[$j]->c_attempts;
                    $quest->c_question = $quizzes[$i]->quiz_questions[$j]->question_text;
                    $quest->c_image = $quizzes[$i]->quiz_questions[$j]->question_image;
                    $quest->c_type = $quizzes[$i]->quiz_questions[$j]->c_type;
                    $quest->params = $quizzes[$i]->quiz_questions[$j]->question_params;
                    $quest->c_explanation = $quizzes[$i]->quiz_questions[$j]->question_explanation;
                    // added 27.03.2008 (DEN)
                    $quest->c_pool = 0;
                    //$q_pool[$i]->pool_questions[$j]->c_pool;
                    $quest->c_qcat = 0;
                    if ($quizzes[$i]->quiz_questions[$j]->c_qcat) {
                        for ($ij = 0; $ij < count($quest_cats); $ij++) {
                            if ($quest_cats[$ij]->c_id == $quizzes[$i]->quiz_questions[$j]->c_qcat) {
                                $quest->c_qcat = $quest_cats[$ij]->new_qcat_id;
                                break;
                            }
                        }
                    }
                    if ($quizzes[$i]->quiz_questions[$j]->c_pool && $quest->c_type == 20) {
                        if (!empty($q_pool[0]->pool_questions)) {
                            for ($ij = 0; $ij < count($q_pool[0]->pool_questions); $ij++) {
                                if ($q_pool[0]->pool_questions[$ij]->c_id == $quizzes[$i]->quiz_questions[$j]->c_pool) {
                                    $quest->c_pool = $q_pool[0]->pool_questions[$ij]->new_id;
                                    break;
                                }
                            }
                        }
                    }
                    $quest->ordering = $quizzes[$i]->quiz_questions[$j]->ordering;
                    if ($quizzes[$i]->quiz_questions[$j]->question_image && !in_array($quizzes[$i]->quiz_questions[$j]->question_image, $quiz_images2)) {
                        // Changed 20.08.2007 by DEN - from:
                        //if ($q_pool[$i]->pool_questions[$j]->question_image) {
                        $quiz_images2[] = $quizzes[$i]->quiz_questions[$j]->question_image;
                    }
                    $JLMS_DB->insertObject("#__lms_quiz_t_question", $quest, "c_id");
                    $quizzes[$i]->quiz_questions[$j]->new_id = $JLMS_DB->insertid();
                    $j++;
                }
                //feedbacks processing
                $j = 0;
                while ($j < count($quizzes[$i]->question_feedbacks)) {
                    $q_fb = new stdClass();
                    $q_fb->choice_id = $quizzes[$i]->question_feedbacks[$j]->choice_id;
                    $q_fb->fb_text = $quizzes[$i]->question_feedbacks[$j]->fb_text;
                    $q_fb->quest_id = 0;
                    for ($k = 0; $k < count($quizzes[$i]->quiz_questions); $k++) {
                        if ($quizzes[$i]->quiz_questions[$k]->c_id == $quizzes[$i]->question_feedbacks[$j]->quest_id) {
                            $q_fb->quest_id = isset($quizzes[$i]->quiz_questions[$k]->new_id) ? intval($quizzes[$i]->quiz_questions[$k]->new_id) : 0;
                            break;
                        }
                    }
                    if ($q_fb->quest_id && $q_fb->fb_text && ($q_fb->choice_id == -1 || $q_fb->choice_id == 0)) {
                        $query = "INSERT INTO #__lms_quiz_t_question_fb (quest_id, choice_id, fb_text) VALUES ({$q_fb->quest_id}, {$q_fb->choice_id}, " . $JLMS_DB->Quote($q_fb->fb_text) . ")";
                        $JLMS_DB->SetQuery($query);
                        $JLMS_DB->query();
                    }
                    $j++;
                }
                //choices processing
                $j = 0;
                while ($j < count($quizzes[$i]->choice_data)) {
                    $q_choice = new stdClass();
                    $q_choice->c_choice = $quizzes[$i]->choice_data[$j]->choice_text;
                    $q_choice->c_right = $quizzes[$i]->choice_data[$j]->c_right;
                    $q_choice->ordering = $quizzes[$i]->choice_data[$j]->ordering;
                    $q_choice->c_question_id = 0;
                    for ($k = 0; $k < count($quizzes[$i]->quiz_questions); $k++) {
                        if ($quizzes[$i]->quiz_questions[$k]->c_id == $quizzes[$i]->choice_data[$j]->c_question_id) {
                            $q_choice->c_question_id = isset($quizzes[$i]->quiz_questions[$k]->new_id) ? $quizzes[$i]->quiz_questions[$k]->new_id : 0;
                            if ($quizzes[$i]->quiz_questions[$k]->c_type == 12 || $quizzes[$i]->quiz_questions[$k]->c_type == 13) {
                                $q_choice->c_choice = intval($q_choice->c_choice);
                                for ($kk = 0; $kk < count($quiz_images); $kk++) {
                                    if ($q_choice->c_choice == $quiz_images[$kk]->file_id) {
                                        $q_choice->c_choice = isset($quiz_images[$kk]->imgs_new_id) ? intval($quiz_images[$kk]->imgs_new_id) : 0;
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                    if ($q_choice->c_question_id) {
                        $JLMS_DB->insertObject("#__lms_quiz_t_choice", $q_choice, "c_id");
                    }
                    $j++;
                }
                //matching processing
                $j = 0;
                while ($j < count($quizzes[$i]->match_data)) {
                    $q_match = new stdClass();
                    $q_match->c_left_text = $quizzes[$i]->match_data[$j]->match_text_left;
                    $q_match->c_right_text = $quizzes[$i]->match_data[$j]->match_text_right;
                    $q_match->ordering = $quizzes[$i]->match_data[$j]->ordering;
                    $q_match->c_question_id = 0;
                    for ($k = 0; $k < count($quizzes[$i]->quiz_questions); $k++) {
                        if ($quizzes[$i]->quiz_questions[$k]->c_id == $quizzes[$i]->match_data[$j]->c_question_id) {
                            $q_match->c_question_id = isset($quizzes[$i]->quiz_questions[$k]->new_id) ? $quizzes[$i]->quiz_questions[$k]->new_id : 0;
                            break;
                            if ($quizzes[$i]->quiz_questions[$k]->c_type == 11) {
                                $q_match->c_left_text = intval($q_match->c_left_text);
                                $q_match->c_right_text = intval($q_match->c_right_text);
                                $is_changed_match_images = 0;
                                for ($kk = 0; $kk < count($quiz_images); $kk++) {
                                    if ($q_match->c_left_text == $quiz_images[$kk]->file_id) {
                                        $q_match->c_left_text = isset($quiz_images[$kk]->imgs_new_id) ? intval($quiz_images[$kk]->imgs_new_id) : 0;
                                        $is_changed_match_images++;
                                        if ($is_changed_match_images == 2) {
                                            break;
                                        }
                                    }
                                    if ($q_match->c_right_text == $quiz_images[$kk]->file_id) {
                                        $q_match->c_right_text = isset($quiz_images[$kk]->imgs_new_id) ? intval($quiz_images[$kk]->imgs_new_id) : 0;
                                        $is_changed_match_images++;
                                        if ($is_changed_match_images == 2) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if ($q_match->c_question_id) {
                        $JLMS_DB->insertObject("#__lms_quiz_t_matching", $q_match, "c_id");
                    }
                    $j++;
                }
                //likert scale processing (27.03.2008 - DEN)
                $j = 0;
                while ($j < count($quizzes[$i]->scale_data)) {
                    $q_scale = new stdClass();
                    $q_scale->c_field = $quizzes[$i]->scale_data[$j]->scale_field;
                    $q_scale->c_type = $quizzes[$i]->scale_data[$j]->c_type;
                    $q_scale->ordering = $quizzes[$i]->scale_data[$j]->ordering;
                    $q_scale->c_question_id = 0;
                    for ($k = 0; $k < count($quizzes[$i]->quiz_questions); $k++) {
                        if ($quizzes[$i]->quiz_questions[$k]->c_id == $quizzes[$i]->scale_data[$j]->c_question_id) {
                            $q_scale->c_question_id = isset($quizzes[$i]->quiz_questions[$k]->new_id) ? $quizzes[$i]->quiz_questions[$k]->new_id : 0;
                            break;
                        }
                    }
                    if ($q_scale->c_question_id) {
                        $JLMS_DB->insertObject("#__lms_quiz_t_scale", $q_scale, "c_id");
                    }
                    $j++;
                }
                //hotspot processing
                $j = 0;
                while ($j < count($quizzes[$i]->hotspot_data)) {
                    $q_hotspot = new stdClass();
                    $q_hotspot->c_start_x = $quizzes[$i]->hotspot_data[$j]->hs_start_x;
                    $q_hotspot->c_start_y = $quizzes[$i]->hotspot_data[$j]->hs_start_y;
                    $q_hotspot->c_width = $quizzes[$i]->hotspot_data[$j]->hs_width;
                    $q_hotspot->c_height = $quizzes[$i]->hotspot_data[$j]->hs_height;
                    $q_hotspot->c_question_id = 0;
                    for ($k = 0; $k < count($quizzes[$i]->quiz_questions); $k++) {
                        if ($quizzes[$i]->quiz_questions[$k]->c_id == $quizzes[$i]->hotspot_data[$j]->c_question_id) {
                            $q_hotspot->c_question_id = isset($quizzes[$i]->quiz_questions[$k]->new_id) ? $quizzes[$i]->quiz_questions[$k]->new_id : 0;
                            break;
                        }
                    }
                    if ($q_hotspot->c_question_id) {
                        $JLMS_DB->insertObject("#__lms_quiz_t_hotspot", $q_hotspot, "c_id");
                    }
                    $j++;
                }
                //blank quests processing
                $j = 0;
                $blank_inserted = array();
                while ($j < count($quizzes[$i]->blank_data)) {
                    $q_blank = new stdClass();
                    $q_blank->c_question_id = 0;
                    $q_blank->c_default = $quizzes[$i]->blank_data[$j]->default_answer;
                    for ($k = 0; $k < count($quizzes[$i]->quiz_questions); $k++) {
                        if ($quizzes[$i]->quiz_questions[$k]->c_id == $quizzes[$i]->blank_data[$j]->c_question_id) {
                            $q_blank->c_question_id = isset($quizzes[$i]->quiz_questions[$k]->new_id) ? $quizzes[$i]->quiz_questions[$k]->new_id : 0;
                            break;
                        }
                    }
                    if ($q_blank->c_question_id) {
                        $proceed_insert = true;
                        foreach ($blank_inserted as $bains) {
                            if ($bains->quest_id == $q_blank->c_question_id) {
                                $proceed_insert = false;
                                $new_blank_id = $bains->blank_id;
                                break;
                            }
                        }
                        if ($proceed_insert) {
                            $JLMS_DB->insertObject("#__lms_quiz_t_blank", $q_blank, "c_id");
                            $new_blank_id = $JLMS_DB->insertid();
                            $blankins = new stdClass();
                            $blankins->quest_id = $q_blank->c_question_id;
                            $blankins->blank_id = $new_blank_id;
                            $blank_inserted[] = $blankins;
                        }
                        $q_blank_text = new stdClass();
                        $q_blank_text->c_blank_id = $new_blank_id;
                        $q_blank_text->c_text = $quizzes[$i]->blank_data[$j]->blank_text;
                        $q_blank_text->ordering = $quizzes[$i]->blank_data[$j]->ordering;
                        if ($q_blank_text->c_blank_id) {
                            $JLMS_DB->insertObject("#__lms_quiz_t_text", $q_blank_text, "c_id");
                        }
                    }
                    $j++;
                }
                $i++;
            }
            // ****************************************************************************************************
            // Copy quiz images
            if (count($quiz_images2)) {
                $fromDir = $extract_dir . "quiz_images/";
                $toDir = $JLMS_CONFIG->getCfg('absolute_path') . "/images/joomlaquiz/images/";
                $i = 0;
                while ($i < count($quiz_images2)) {
                    if (file_exists($fromDir . $quiz_images2[$i])) {
                        @rename($fromDir . $quiz_images2[$i], $toDir . $quiz_images2[$i]);
                    }
                    $i++;
                }
            }
            //} // end if ($lms_cfg_quiz_enabled)
        }
        $l_paths = array();
        $lpath_prerequisites = array();
        if (in_array(2, $imp_tools)) {
            // ****************************************************************************************************
            // Get LearningPaths DATA and insert it into the DB
            $element =& $root->getElementByPath('learn_paths');
            $l_paths = JLMS_parse_XML_elements($element->children(), array('id', 'item_id', 'ordering', 'published', 'is_time_related', 'show_period'), array('lp_name', 'lp_shortdescription', 'lp_description', 'lp_params'), true, array('prerequisites', 'steps', 'conds'), array(array('lpath_id', 'req_id', 'time_minutes'), array('id', 'item_id', 'lpath_id', 'step_type', 'parent_id', 'ordering'), array('lpath_id', 'step_id', 'ref_step', 'cond_type', 'cond_value')), array(array(), array('step_name', 'step_shortdescription', 'step_description'), array()));
            $i = 0;
            $process_steps_on_exit = array();
            while ($i < count($l_paths)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->owner_id = $my->id;
                $insert->lpath_name = $l_paths[$i]->lp_name;
                if ($l_paths[$i]->item_id) {
                    $n = 0;
                    $scorm_found = false;
                    while ($n < count($scorms)) {
                        if ($scorms[$n]->id == $l_paths[$i]->item_id) {
                            $insert->item_id = $scorms[$n]->new_sco_id;
                            $scorm_found = true;
                            break;
                        }
                        $n++;
                    }
                    if (!$scorm_found) {
                        $i++;
                        continue;
                    }
                } else {
                    $insert->item_id = 0;
                }
                $insert->lpath_shortdescription = $l_paths[$i]->lp_shortdescription;
                $insert->lp_params = $l_paths[$i]->lp_params;
                $insert->lpath_description = $l_paths[$i]->lp_description;
                $insert->ordering = $l_paths[$i]->ordering;
                $insert->published = $l_paths[$i]->published;
                $insert->lp_type = 0;
                // for compatibility with SCORM import/export (if lp_type == 0, then new instance in 'lms_n_scorm' will be added automatically)
                $insert->is_time_related = $l_paths[$i]->is_time_related;
                $insert->show_period = $l_paths[$i]->show_period;
                $JLMS_DB->insertObject("#__lms_learn_paths", $insert, "id");
                $l_paths[$i]->new_step_id = $JLMS_DB->insertid();
                // 18 August 2007 - DEN - prerequisites import
                $j = 0;
                while ($j < count($l_paths[$i]->prerequisites)) {
                    $new_prereq = new stdClass();
                    $new_prereq->old_lpath_id = $l_paths[$i]->prerequisites[$j]->lpath_id;
                    $new_prereq->old_req_id = $l_paths[$i]->prerequisites[$j]->req_id;
                    $new_prereq->lpath_id = 0;
                    $new_prereq->req_id = 0;
                    $new_prereq->time_minutes = 0;
                    $lpath_prerequisites[] = $new_prereq;
                    $j++;
                }
                if ($l_paths[$i]->item_id) {
                } else {
                    $j = 0;
                    while ($j < count($l_paths[$i]->steps)) {
                        $step = new stdClass();
                        $step->course_id = $course_id;
                        $step->lpath_id = $l_paths[$i]->new_step_id;
                        $step->step_type = $l_paths[$i]->steps[$j]->step_type;
                        $do_process_on_exit = false;
                        $proc_exit_item = 0;
                        if ($step->step_type == 2) {
                            //document
                            $is_doc_found = false;
                            for ($k = 0; $k < count($documents); $k++) {
                                if ($documents[$k]->id == $l_paths[$i]->steps[$j]->item_id) {
                                    $step->item_id = $documents[$k]->new_doc_id;
                                    $is_doc_found = true;
                                    break;
                                }
                            }
                            if (!$is_doc_found) {
                                $step->step_type = 4;
                            }
                        } elseif ($step->step_type == 3) {
                            //link
                            $is_link_found = false;
                            for ($k = 0; $k < count($links); $k++) {
                                if ($links[$k]->id == $l_paths[$i]->steps[$j]->item_id) {
                                    $step->item_id = $links[$k]->new_link_id;
                                    $is_link_found = true;
                                    break;
                                }
                            }
                            if (!$is_link_found) {
                                $step->step_type = 4;
                            }
                        } elseif ($step->step_type == 5) {
                            //quiz
                            $is_quiz_found = false;
                            for ($k = 0; $k < count($quizzes); $k++) {
                                if ($quizzes[$k]->c_id == $l_paths[$i]->steps[$j]->item_id) {
                                    $step->item_id = $quizzes[$k]->new_quiz_id;
                                    $is_quiz_found = true;
                                    break;
                                }
                            }
                            if (!$is_quiz_found) {
                                $step->step_type = 4;
                            }
                        } elseif ($step->step_type == 6) {
                            //scorm
                            // Axtung - we should make all scorm steps - as 4 (content) and after processing all LPaths -> upgrade them to type 6 (scorm) and link to scorm LPath
                            // (because) at this step not all Lpaths are processed !!!
                            $step->step_type = 4;
                            $do_process_on_exit = true;
                            $proc_exit_item = $l_paths[$i]->steps[$j]->item_id;
                        } else {
                            //other
                            $step->item_id = $l_paths[$i]->steps[$j]->item_id;
                        }
                        $parent = $l_paths[$i]->steps[$j]->parent_id;
                        // search processed steps for parent_id
                        if ($parent) {
                            $a = 0;
                            while ($a < $j) {
                                if ($l_paths[$i]->steps[$a]->id == $parent) {
                                    $parent = $l_paths[$i]->steps[$a]->new_id;
                                    break;
                                }
                                $a++;
                            }
                        }
                        $step->parent_id = $parent;
                        $step->step_name = $l_paths[$i]->steps[$j]->step_name;
                        $step->step_shortdescription = $l_paths[$i]->steps[$j]->step_shortdescription;
                        $step->step_description = $l_paths[$i]->steps[$j]->step_description;
                        $step->ordering = $l_paths[$i]->steps[$j]->ordering;
                        $JLMS_DB->insertObject("#__lms_learn_path_steps", $step, "id");
                        $l_paths[$i]->steps[$j]->new_id = $JLMS_DB->insertid();
                        if ($do_process_on_exit) {
                            $pr_step = new stdClass();
                            $pr_step->step_id = $l_paths[$i]->steps[$j]->new_id;
                            $pr_step->item_id = $proc_exit_item;
                            $pr_step->new_item_id = 0;
                            $process_steps_on_exit[] = $pr_step;
                        }
                        $j++;
                    }
                    $j = 0;
                    while ($j < count($l_paths[$i]->conds)) {
                        $cond = new stdClass();
                        $cond->course_id = $course_id;
                        $cond->lpath_id = $l_paths[$i]->new_step_id;
                        $cond->cond_type = $l_paths[$i]->conds[$j]->cond_type;
                        $cond->cond_value = $l_paths[$i]->conds[$j]->cond_value;
                        $st1 = $l_paths[$i]->conds[$j]->step_id;
                        if ($st1) {
                            $a = 0;
                            while ($a < count($l_paths[$i]->steps)) {
                                if ($l_paths[$i]->steps[$a]->id == $st1) {
                                    $st1 = $l_paths[$i]->steps[$a]->new_id;
                                    break;
                                }
                                $a++;
                            }
                        }
                        $cond->step_id = $st1;
                        $st2 = $l_paths[$i]->conds[$j]->ref_step;
                        if ($st2) {
                            $a = 0;
                            while ($a < count($l_paths[$i]->steps)) {
                                if ($l_paths[$i]->steps[$a]->id == $st2) {
                                    $st2 = $l_paths[$i]->steps[$a]->new_id;
                                    break;
                                }
                                $a++;
                            }
                        }
                        $cond->ref_step = $st2;
                        $JLMS_DB->insertObject("#__lms_learn_path_conds", $cond, "id");
                        $j++;
                    }
                }
                $i++;
            }
            // 18 August 2007 - DEN - import scorm steps
            if (!empty($process_steps_on_exit)) {
                $a = 0;
                while ($a < count($process_steps_on_exit)) {
                    foreach ($l_paths as $lp) {
                        if ($lp->id == $process_steps_on_exit[$a]->item_id) {
                            $process_steps_on_exit[$a]->new_item_id = $lp->new_step_id;
                            // xm.. why 'step' ?? (bad name)
                        }
                    }
                    $a++;
                }
                foreach ($process_steps_on_exit as $lp_pse) {
                    if ($lp_pse->new_item_id && $lp_pse->step_id) {
                        $query = "UPDATE #__lms_learn_path_steps SET step_type = 6, item_id = " . intval($lp_pse->new_item_id) . " WHERE id = " . intval($lp_pse->step_id);
                        $JLMS_DB->SetQuery($query);
                        $JLMS_DB->query();
                    }
                }
            }
            // 18 August 2007 - DEN - prerequisites import
            if (!empty($lpath_prerequisites)) {
                $a = 0;
                while ($a < count($lpath_prerequisites)) {
                    foreach ($l_paths as $lp) {
                        if ($lp->id == $lpath_prerequisites[$a]->old_lpath_id) {
                            $lpath_prerequisites[$a]->lpath_id = $lp->new_step_id;
                            // xm.. why 'step' ?? (bad name)
                        }
                        if ($lp->id == $lpath_prerequisites[$a]->old_req_id) {
                            $lpath_prerequisites[$a]->req_id = $lp->new_step_id;
                            // xm.. why 'step' ?? (bad name)
                        }
                    }
                    $a++;
                }
                foreach ($lpath_prerequisites as $lp_pre) {
                    if ($lp_pre->lpath_id && $lp_pre->req_id && $lp_pre->lpath_id != $lp_pre->req_id) {
                        $query = "INSERT INTO #__lms_learn_path_prerequisites (lpath_id, req_id, time_minutes) VALUES (" . intval($lp_pre->lpath_id) . ", " . intval($lp_pre->req_id) . ", " . intval($lp_pre->time_minutes) . ")";
                        $JLMS_DB->SetQuery($query);
                        $JLMS_DB->query();
                    }
                }
            }
            if ($course_redirect_lp) {
                $lp_id = 0;
                foreach ($l_paths as $lp) {
                    if ($lp->id == $course_redirect_lp) {
                        $lp_id = $lp->new_step_id;
                        // xm.. why 'step' ?? (bad name)
                        break;
                    }
                }
                if ($lp_id) {
                    $params->set('learn_path', $lp_id);
                    $params_ar = $params->toArray();
                    if (is_array($params_ar)) {
                        foreach ($params_ar as $k => $v) {
                            $txt[] = "{$k}={$v}";
                        }
                        $new_params = implode("\n", $txt);
                        if ($new_params) {
                            $query = "UPDATE #__lms_courses SET " . $JLMS_DB->NameQuote('params') . " = " . $JLMS_DB->Quote($new_params) . " WHERE id = {$course_id}";
                            $JLMS_DB->SetQuery($query);
                            $JLMS_DB->query();
                        }
                    }
                }
            }
        }
        $course_topics = array();
        // ****************************************************************************************************
        // Get TOPICS Items DATA and insert it into the 'lms_topics', 'lms_topic_items' tables - 27.03.2008 (DEN)
        $element =& $root->getElementByPath('course_topics');
        $course_topics = JLMS_parse_XML_elements($element->children(), array('topic_id', 'ordering', 'published', 'publish_start', 'start_date', 'publish_end', 'end_date', 'is_time_related', 'show_period'), array('topic_name', 'topic_description'));
        $i = 0;
        while ($i < count($course_topics)) {
            $insert = new stdClass();
            $insert->course_id = $course_id;
            $insert->ordering = $course_topics[$i]->ordering;
            $insert->name = $course_topics[$i]->topic_name;
            $insert->description = $course_topics[$i]->topic_description;
            $insert->published = $course_topics[$i]->published;
            $insert->start_date = $course_topics[$i]->start_date;
            $insert->publish_start = $course_topics[$i]->publish_start;
            $insert->end_date = $course_topics[$i]->end_date;
            $insert->publish_end = $course_topics[$i]->publish_end;
            $insert->is_time_related = $course_topics[$i]->is_time_related;
            $insert->show_period = $course_topics[$i]->show_period;
            $JLMS_DB->insertObject("#__lms_topics", $insert, "id");
            $course_topics[$i]->new_topic_id = $JLMS_DB->insertid();
            $i++;
        }
        $element =& $root->getElementByPath('course_topic_items');
        $course_topic_items = JLMS_parse_XML_elements($element->children(), array('topic_id', 'item_id', 'item_type', 'ordering', 'is_shown'), array());
        $i = 0;
        while ($i < count($course_topic_items)) {
            $insert = new stdClass();
            $insert->course_id = $course_id;
            $insert->topic_id = 0;
            foreach ($course_topics as $ct) {
                if ($course_topic_items[$i]->topic_id == $ct->topic_id) {
                    $insert->topic_id = $ct->new_topic_id;
                }
            }
            if ($insert->topic_id) {
                $insert->ordering = $course_topic_items[$i]->ordering;
                $insert->item_type = $course_topic_items[$i]->item_type;
                $insert->show = $course_topic_items[$i]->is_shown ? 1 : 0;
                $insert->item_id = 0;
                $do_add_topic_item = false;
                if ($insert->item_type == 2) {
                    // documents
                    if (in_array(1, $imp_tools)) {
                        for ($k = 0; $k < count($documents); $k++) {
                            if ($documents[$k]->id == $course_topic_items[$i]->item_id) {
                                $insert->item_id = $documents[$k]->new_doc_id;
                                $do_add_topic_item = true;
                                break;
                            }
                        }
                    }
                } elseif ($insert->item_type == 3) {
                    // links
                    if (in_array(4, $imp_tools)) {
                        for ($k = 0; $k < count($links); $k++) {
                            if ($links[$k]->id == $course_topic_items[$i]->item_id) {
                                $insert->item_id = $links[$k]->new_link_id;
                                $do_add_topic_item = true;
                                break;
                            }
                        }
                    }
                } elseif ($insert->item_type == 5) {
                    // quizzes
                    if (in_array(5, $imp_tools)) {
                        for ($k = 0; $k < count($quizzes); $k++) {
                            if ($quizzes[$k]->c_id == $course_topic_items[$i]->item_id) {
                                $insert->item_id = $quizzes[$k]->new_quiz_id;
                                $do_add_topic_item = true;
                                break;
                            }
                        }
                    }
                } elseif ($insert->item_type == 7) {
                    // learning paths
                    if (in_array(2, $imp_tools)) {
                        for ($k = 0; $k < count($l_paths); $k++) {
                            if ($l_paths[$k]->id == $course_topic_items[$i]->item_id) {
                                $insert->item_id = $l_paths[$k]->new_step_id;
                                $do_add_topic_item = true;
                                break;
                            }
                        }
                    }
                }
                if ($do_add_topic_item && $insert->item_id) {
                    $JLMS_DB->insertObject("#__lms_topic_items", $insert, "id");
                    $course_topic_items[$i]->new_topic_item_id = $JLMS_DB->insertid();
                }
            }
            $i++;
        }
        if (in_array(8, $imp_tools)) {
            // ****************************************************************************************************
            // Get GradeBook Items DATA and insert it into the 'lms_gradebook_items' table
            $element =& $root->getElementByPath('gradebook_items');
            $gb_items = JLMS_parse_XML_elements($element->children(), array('gbi_option', 'ordering'), array('gbi_name', 'gbi_description', 'gb_category'));
            $i = 0;
            while ($i < count($gb_items)) {
                $insert = new stdClass();
                $query = "SELECT id FROM #__lms_gradebook_cats WHERE gb_category = '" . $gb_items[$i]->gb_category . "'";
                $JLMS_DB->SetQuery($query);
                $cat_id = $JLMS_DB->LoadResult();
                if (!$cat_id) {
                    $cat_id = 0;
                }
                $insert->course_id = $course_id;
                $insert->gbc_id = $cat_id;
                $insert->gbi_name = $gb_items[$i]->gbi_name;
                $insert->gbi_description = $gb_items[$i]->gbi_description;
                $insert->gbi_points = 0;
                $insert->gbi_option = $gb_items[$i]->gbi_option;
                $insert->ordering = $gb_items[$i]->ordering;
                $JLMS_DB->insertObject("#__lms_gradebook_items", $insert, "id");
                $gb_items[$i]->new_gbi_id = $JLMS_DB->insertid();
                $i++;
            }
            // ****************************************************************************************************
            // Get GradeBook Scale DATA and insert it into the 'lms_gradebook_scale' table
            $element =& $root->getElementByPath('gradebook_scale');
            $gb_scale = JLMS_parse_XML_elements($element->children(), array('min_val', 'max_val', 'ordering'), array('scale_name'));
            $i = 0;
            while ($i < count($gb_scale)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->scale_name = $gb_scale[$i]->scale_name;
                $insert->min_val = $gb_scale[$i]->min_val;
                $insert->max_val = $gb_scale[$i]->max_val;
                $insert->ordering = $gb_scale[$i]->ordering;
                $JLMS_DB->insertObject("#__lms_gradebook_scale", $insert, "id");
                $gb_scale[$i]->new_gbs_id = $JLMS_DB->insertid();
                $i++;
            }
            // ****************************************************************************************************
            // Get GradeBook Scale DATA and insert it into the 'lms_gradebook_scale' table
            $element =& $root->getElementByPath('gradebook_lpaths');
            $gb_lpaths = JLMS_parse_XML_elements($element->children(), array('learn_path_id'), array());
            $i = 0;
            while ($i < count($gb_lpaths)) {
                $insert = new stdClass();
                $insert->course_id = $course_id;
                $insert->learn_path_id = 0;
                foreach ($l_paths as $lp) {
                    if ($gb_lpaths[$i]->learn_path_id == $lp->id) {
                        $insert->learn_path_id = $lp->new_step_id;
                    }
                }
                if ($insert->learn_path_id) {
                    $JLMS_DB->insertObject("#__lms_gradebook_lpaths", $insert, "id");
                }
                $i++;
            }
        }
    }
    // delete temporary files
    deldir($extract_dir);
    return $archive;
}
Пример #11
0
function doImport($course_code, $webDir, $scoFileSize, $scoFileName, $displayExtraMessages = false) {
    global $langUnamedPath;
    global $langFileScormError;
    global $langNotice;
    global $langMaxFileSize;
    global $langNoSpace;
    global $langOkFileReceived;
    global $langErrorNoZlibExtension;
    global $langErrorReadingZipFile;
    global $langZipNoPhp;
    global $langErrortExtractingManifest;
    global $langErrorFileMustBeZip;
    global $langErrorOpeningManifest;
    global $langOkManifestFound;
    global $langErrorReadingManifest;
    global $langOkManifestRead;
    global $langErrorAssetNotFound;
    global $langErrorNoModuleInPackage;
    global $langErrorSql;
    global $langOkChapterHeadAdded;
    global $langUnamedModule;
    global $langDefaultModuleComment;
    global $langDefaultModuleAddedComment;
    global $langOkModuleAdded;
    global $langOkDefaultTitleUsed;
    global $langDefaultLearningPathComment;
    global $langOkDefaultCommentUsed;
    global $langSuccessOk;
    global $langError;
    global $langInstalled;
    global $langNotInstalled;
    global $langBack;
    global $errorFound;
    global $elementsPile;
    global $itemsPile;
    global $manifestData;
    global $iterator;
    global $course_code;
    global $course_id;
    global $langErrorValidatingManifest;
    global $urlServer;

    $pwd = getcwd();

    // init msg arays
    $okMsgs = array();
    $errorMsgs = array();

    $maxFilledSpace = 100000000;

    $courseDir = "/courses/" . $course_code . "/scormPackages/";
    $tempDir = "/courses/" . $course_code . "/temp/";
    $baseWorkDir = $webDir . $courseDir; // path_id
    $tempWorkDir = $webDir . $tempDir;

    if (!is_dir($baseWorkDir)) {
        claro_mkdir($baseWorkDir, CLARO_FILE_PERMISSIONS);
    }

    // arrays used to store inserted ids
    $insertedModule_id = array();
    $insertedAsset_id = array();

    $lpName = $langUnamedPath;

    // we need a new path_id for this learning path so we prepare a line in DB
    // this line will be removed if an error occurs
    $rankMax = 1 + intval(Database::get()->querySingle("SELECT MAX(`rank`) AS max
            FROM `lp_learnPath` WHERE `course_id` = ?d", $course_id)->max);

    $tempPathId = Database::get()->query("INSERT INTO `lp_learnPath`
            (`course_id`, `name`,`visible`,`rank`,`comment`)
            VALUES (?d, ?s, 0, ?d,'')", $course_id, $lpName, $rankMax)->lastInsertID;
    $baseWorkDir .= "path_" . $tempPathId;

    if (!is_dir($baseWorkDir)) {
        claro_mkdir($baseWorkDir, CLARO_FILE_PERMISSIONS);
    }

    // unzip package
    require_once("include/pclzip/pclzip.lib.php");

    /*
     * Check the file size doesn't exceed
     * the maximum file size authorized in the directory
     */

    if (!enough_size($scoFileSize, $baseWorkDir, $maxFilledSpace)) {
        $errorFound = true;
        array_push($errorMsgs, $langNoSpace);
    }

    /*
     * Unzipping stage
     */ elseif (preg_match("/.zip$/i", $scoFileName)) {
        array_push($okMsgs, $langOkFileReceived . basename($scoFileName));

        if (!function_exists('gzopen')) {
            $errorFound = true;
            array_push($errorMsgs, $langErrorNoZlibExtension);
        } else {
            $zipFile = new pclZip($tempWorkDir . $scoFileName);
            $is_allowedToUnzip = true; // default initialisation
            // Check the zip content (real size and file extension)

            $zipContentArray = $zipFile->listContent();

            if ($zipContentArray == 0) {
                $errorFound = true;
                array_push($errorMsgs, $langErrorReadingZipFile);
            }

            $pathToManifest = ""; // empty by default because we can expect that the manifest.xml is in the root of zip file
            $pathToManifestFound = false;
            $realFileSize = 0;

            foreach ($zipContentArray as $thisContent) {
                if (preg_match('/.(php[[:digit:]]?|phtml)$/i', $thisContent['filename'])) {
                    $errorFound = true;
                    array_push($errorMsgs, $langZipNoPhp);
                    $is_allowedToUnzip = false;
                    break;
                }

                if (strtolower(substr($thisContent['filename'], -15)) == "imsmanifest.xml") {
                    // this check exists to find the less deep imsmanifest.xml in the zip if there are several imsmanifest.xml
                    // if this is the first imsmanifest.xml we found OR path to the new manifest found is shorter (less deep)
                    if (!$pathToManifestFound || ( count(explode('/', $thisContent['filename'])) < count(explode('/', $pathToManifest . "imsmanifest.xml")) )
                    ) {
                        $pathToManifest = substr($thisContent['filename'], 0, -15);
                        $pathToManifestFound = true;
                    }
                }
                $realFileSize += $thisContent['size'];
            }

            if (!isset($alreadyFilledSpace)) {
                $alreadyFilledSpace = 0;
            }

            if (($realFileSize + $alreadyFilledSpace) > $maxFilledSpace) { // check the real size.
                $errorFound = true;
                array_push($errorMsgs, $langNoSpace);
                $is_allowedToUnzip = false;
            }

            if ($is_allowedToUnzip && !$errorFound) {
                // PHP extraction of zip file using zlib

                chdir($baseWorkDir);
                $unzippingState = $zipFile->extract(PCLZIP_OPT_BY_NAME, $pathToManifest . "imsmanifest.xml", PCLZIP_OPT_PATH, '', PCLZIP_OPT_REMOVE_PATH, $pathToManifest);
                if ($unzippingState == 0) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrortExtractingManifest);
                }
            } //end of if ($is_allowedToUnzip)
        } // end of if (!function_exists...
    } else {
        $errorFound = true;
        array_push($errorMsgs, $langErrorFileMustBeZip . ": " . basename($scoFileName));
    }
    // find xmlmanifest (must be in root else ==> cancel operation, delete files)
    // parse xml manifest to find :
    // package name - learning path name
    // SCO list
    // start asset path

    if (!$errorFound) {
        $elementsPile = array(); // array used to remember where we are in the arborescence of the XML file
        $itemsPile = array(); // array used to remember parents items
        // declaration of global arrays used for extracting needed info from manifest for the new modules/SCO
        $manifestData = array();   // for global data  of the learning path
        $manifestData['items'] = array(); // item tags content (attributes + some child elements data (title for an example)
        $manifestData['scos'] = array();  // for path of start asset id of each new module to create

        $iterator = 0; // will be used to increment position of paths in manifestData['scosPaths"]
        // and to have the names at the same pos if found
        //$xml_parser = xml_parser_create();
        $xml_parser = xml_parser_create('utf-8');
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_set_character_data_handler($xml_parser, "elementData");

        // this file has to exist in a SCORM conformant package
        // this file must be in the root the sent zip
        $file = "imsmanifest.xml";

        if (!($fp = @fopen($file, "r"))) {
            $errorFound = true;
            array_push($errorMsgs, $langErrorOpeningManifest);
        } else {
            if (!isset($manifestPath)) {
                $manifestPath = "";
            }

            array_push($okMsgs, $langOkManifestFound . $manifestPath . "imsmanifest.xml");

            while ($data = str_replace("\n", "", fread($fp, 4096))) {
                // fix for fread breaking thing
                // msg from "ml at csite dot com" 02-Jul-2003 02:29 on http://www.php.net/xml
                // preg expression has been modified to match tag with inner attributes

                if (!isset($cache)) {
                    $cache = "";
                }

                $data = $cache . $data;
                if (!feof($fp)) {
                    // search fo opening, closing, empty tags (with or without attributes)
                    if (preg_match_all("/<[^\>]*.>/", $data, $regs)) {
                        $lastTagname = $regs[0][count($regs[0]) - 1];
                        $split = false;
                        for ($i = strlen($data) - strlen($lastTagname); $i >= strlen($lastTagname); $i--) {
                            if ($lastTagname == substr($data, $i, strlen($lastTagname))) {
                                $cache = substr($data, $i, strlen($data));
                                $data = substr($data, 0, $i);
                                $split = true;
                                break;
                            }
                        }
                    }

                    if (!$split) {
                        $cache = $data;
                    }
                }
                // end of fix

                if (!xml_parse($xml_parser, $data, feof($fp))) {
                    // if reading of the xml file in not successfull :
                    // set errorFound, set error msg, break while statement

                    $errorFound = true;
                    array_push($errorMsgs, $langErrorReadingManifest);
                    // Since manifest.xml cannot be parsed, test versus IMS CP 1.4.4 XSD (compatible with all SCORM packages as well)
                    require_once 'include/validateXML.php';
                    libxml_use_internal_errors(true);
                    
                    $xml = new DOMDocument();
                    $xml->load($manifestPath."imsmanifest.xml");
                    
                    if (!$xml->schemaValidate($urlServer . 'modules/learnPath/export/imscp_v1p2.xsd')) {
                        $messages = libxml_display_errors();
                        
                        array_push($errorMsgs, $langErrorValidatingManifest . $messages);
                    }
                    break;
                }
            }
            // close file
            fclose($fp);
        }

        // liberate parser ressources
        xml_parser_free($xml_parser);
    } //if (!$errorFound)
    // check if all starts assets files exist in the zip file
    if (!$errorFound) {
        array_push($okMsgs, $langOkManifestRead);
        if (sizeof($manifestData['items']) > 0) {
            // if there is items in manifest we look for sco type resources referenced in idientifierref
            foreach ($manifestData['items'] as $item) {
                if (!isset($item['identifierref']) || $item['identifierref'] == '') {
                    break; // skip if no ressource reference in item (item is probably a chapter head)
                }

                    
// find the file in the zip file
                $scoPathFound = false;

                for ($i = 0; $i < sizeof($zipContentArray); $i++) {
                    if (isset($manifestData['scos'][$item['identifierref']]['xml:base'])) {
                        $extraPath = $manifestData['scos'][$item['identifierref']]['xml:base'];
                    } else if (isset($manifestData['assets'][$item['identifierref']]['xml:base'])) {
                        $extraPath = $manifestData['assets'][$item['identifierref']]['xml:base'];
                    } else {
                        $extraPath = "";
                    }

                    if (isset($zipContentArray[$i]["filename"]) &&
                            ( ( isset($manifestData['scos'][$item['identifierref']]['href']) && $zipContentArray[$i]["filename"] == $pathToManifest . $extraPath . $manifestData['scos'][$item['identifierref']]['href']) || (isset($manifestData['assets'][$item['identifierref']]['href']) && $zipContentArray[$i]["filename"] == $pathToManifest . $extraPath . $manifestData['assets'][$item['identifierref']]['href'])
                            )
                    ) {
                        $scoPathFound = true;
                        break;
                    }
                }

                if (!$scoPathFound) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorAssetNotFound . $manifestData['scos'][$item['identifierref']]['href']);
                    break;
                }
            }
        } //if (sizeof ...)
        elseif (sizeof($manifestData['scos']) > 0) {
            // if there ie no items in the manifest file
            // check for scos in resources

            foreach ($manifestData['scos'] as $sco) {
                // find the file in the zip file
                // create a fake item so that the rest of the procedure (add infos of in db) can remains the same
                $manifestData['items'][$sco['href']]['identifierref'] = $sco['href'];
                $manifestData['items'][$sco['href']]['parameters'] = '';
                $manifestData['items'][$sco['href']]['isvisible'] = "true";
                $manifestData['items'][$sco['href']]['title'] = $sco['title'];
                $manifestData['items'][$sco['href']]['description'] = $sco['description'];
                $manifestData['items'][$attributes['IDENTIFIER']]['parent'] = 0;

                $scoPathFound = false;

                for ($i = 0; $i < sizeof($zipContentArray); $i++) {
                    if ($zipContentArray[$i]["filename"] == $sco['href']) {
                        $scoPathFound = true;
                        break;
                    }
                }
                if (!$scoPathFound) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorAssetNotFound . $sco['href']);
                    break;
                }
            }
        } // if sizeof (...ΰ
        else {
            $errorFound = true;
            array_push($errorMsgs, $langErrorNoModuleInPackage);
        }
    }// if errorFound
    // unzip all files
    // &&
    // insert corresponding entries in database

    if (!$errorFound) {
        // PHP extraction of zip file using zlib
        chdir($baseWorkDir);

        // PCLZIP_OPT_PATH is the path where files will be extracted ( '' )
        // PLZIP_OPT_REMOVE_PATH suppress a part of the path of the file ( $pathToManifest )
        // the result is that the manifest is in th eroot of the path_# directory and all files will have a path related to the root
        $unzippingState = $zipFile->extract(PCLZIP_OPT_PATH, '', PCLZIP_OPT_REMOVE_PATH, $pathToManifest);

        // insert informations in DB :
        //        - 1 learning path ( already added because we needed its id to create the package directory )
        //        - n modules
        //        - n asset as start asset of modules

        if (sizeof($manifestData['items']) == 0) {
            $errorFound = true;
            array_push($errorMsgs, $langErrorNoModuleInPackage);
        } else {
            $i = 0;
            $insertedLPMid = array(); // array of learnPath_module_id && order of related group
            $inRootRank = 1; // default rank for root module (parent == 0)

            foreach ($manifestData['items'] as $item) {
                if (isset($item['parent']) && isset($insertedLPMid[$item['parent']])) {
                    $parent = $insertedLPMid[$item['parent']]['LPMid'];
                    $rank = $insertedLPMid[$item['parent']]['rank'] ++;
                } else {
                    $parent = 0;
                    $rank = $inRootRank++;
                }

                //-------------------------------------------------------------------------------
                // add chapter head
                //-------------------------------------------------------------------------------

                if ((!isset($item['identifierref']) || $item['identifierref'] == '') && isset($item['title']) && $item['title'] != '') {
                    // add title as a module
                    $chapterTitle = $item['title'];

                    // array of all inserted module ids
                    $insertedModule_id[$i] = Database::get()->query("INSERT INTO `lp_module`
                            (`course_id`, `name`, `comment`, `contentType`, `launch_data`)
                            VALUES (?d, ?s, '', ?s,'')", $course_id, $chapterTitle, CTLABEL_)->lastInsertID;
                    if (!$insertedModule_id[$i]) {
                        $errorFound = true;
                        array_push($errorMsgs, $langErrorSql);
                        break;
                    }
                    // visibility
                    if (isset($item['isvisible']) && $item['isvisible'] != '') {
                        $visibility = ($item['isvisible'] == "true") ? 1 : 0;
                    } else {
                        $visibility = 1; // IMS consider that the default value of 'isvisible' is true
                    }

                    // add title module in the learning path
                    // finally : insert in learning path
                    // get the inserted id of the learnPath_module rel to allow 'parent' link in next inserts
                    $insertedLPMid[$item['itemIdentifier']]['LPMid'] = Database::get()->query("INSERT INTO `lp_rel_learnPath_module`
                            (`learnPath_id`, `module_id`,`rank`, `visible`, `parent`)
                            VALUES (?d, ?d, ?d, ?d, ?d)", $tempPathId, $insertedModule_id[$i], $rank, $visibility, $parent)->lastInsertID;
                    $insertedLPMid[$item['itemIdentifier']]['rank'] = 1;

                    if (!$insertedLPMid[$item['itemIdentifier']]['LPMid']) {
                        $errorFound = true;
                        array_push($errorMsgs, $langErrorSql);
                        break;
                    }
                    if (!$errorFound) {
                        array_push($okMsgs, $langOkChapterHeadAdded . "<i>" . $chapterTitle . "</i>");
                    }
                    $i++;
                    continue;
                }

                // use found title of module or use default title
                if (!isset($item['title']) || $item['title'] == '') {
                    $moduleName = $langUnamedModule;
                } else {
                    $moduleName = $item['title'];
                }

                // set description as comment or default comment
                // look fo description in item description or in sco (resource) description
                // don't remember why I checked for parameters string ... so comment it
                if ((!isset($item['description']) || $item['description'] == '' ) &&
                        (!isset($manifestData['scos'][$item['identifierref']]['description']) /* || $manifestData['scos'][$item['identifierref']]['parameters'] == '' */ )
                ) {
                    $description = $langDefaultModuleComment;
                } else {
                    if (isset($item['description']) && $item['description'] != '') {
                        $description = $item['description'];
                    } else {
                        $description = $manifestData['scos'][$item['identifierref']]['description'];
                    }
                }

                // insert modules and their start asset
                // create new module

                if (!isset($item['datafromlms'])) {
                    $item['datafromlms'] = "";
                }

                // elegxoume an to contentType prepei na einai scorm h asset
                if (isset($manifestData['scos'][$item['identifierref']]['contentTypeFlag']) && $manifestData['scos'][$item['identifierref']]['contentTypeFlag'] == CTSCORMASSET_) {
                    $contentType = CTSCORMASSET_;
                } else {
                    $contentType = CTSCORM_;
                }

                // array of all inserted module ids
                $insertedModule_id[$i] = Database::get()->query("INSERT INTO `lp_module`
                        (`course_id`, `name`, `comment`, `contentType`, `launch_data`)
                        VALUES (?d, ?s, ?s, ?s, ?s)", $course_id, $moduleName, $description, $contentType, $item['datafromlms'])->lastInsertID;
                
                if (!$insertedModule_id[$i]) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorSql);
                    break;
                }
                // build asset path
                // a $manifestData['scos'][$item['identifierref']] __SHOULD__ not exist if a $manifestData['assets'][$item['identifierref']] exists
                // so according to IMS we can say that one is empty if the other is filled, so we concat them without more verification than if the var exists.

                // suppress notices
                if (!isset($manifestData['xml:base']['manifest'])) {
                    $manifestData['xml:base']['manifest'] = "";
                }
                if (!isset($manifestData['xml:base']['ressources'])) {
                    $manifestData['xml:base']['ressources'] = "";
                }
                if (!isset($manifestData['scos'][$item['identifierref']]['href'])) {
                    $manifestData['scos'][$item['identifierref']]['href'] = "";
                }
                if (!isset($manifestData['assets'][$item['identifierref']]['href'])) {
                    $manifestData['assets'][$item['identifierref']]['href'] = "";
                }
                if (!isset($manifestData['scos'][$item['identifierref']]['parameters'])) {
                    $manifestData['scos'][$item['identifierref']]['parameters'] = "";
                }
                if (!isset($manifestData['assets'][$item['identifierref']]['parameters'])) {
                    $manifestData['assets'][$item['identifierref']]['parameters'] = "";
                }
                if (!isset($manifestData['items'][$item['itemIdentifier']]['parameters'])) {
                    $manifestData['items'][$item['itemIdentifier']]['parameters'] = "";
                }

                if (isset($manifestData['scos'][$item['identifierref']]['xml:base'])) {
                    $extraPath = $manifestData['scos'][$item['identifierref']]['xml:base'];
                } else if (isset($manifestData['assets'][$item['identifierref']]['xml:base'])) {
                    $extraPath = $manifestData['assets'][$item['identifierref']]['xml:base'];
                } else {
                    $extraPath = "";
                }

                $assetPath = "/"
                        . $manifestData['xml:base']['manifest']
                        . $manifestData['xml:base']['ressources']
                        . $extraPath
                        . $manifestData['scos'][$item['identifierref']]['href']
                        . $manifestData['assets'][$item['identifierref']]['href']
                        . $manifestData['scos'][$item['identifierref']]['parameters']
                        . $manifestData['assets'][$item['identifierref']]['parameters']
                        . $manifestData['items'][$item['itemIdentifier']]['parameters'];

                // create new asset
                // array of all inserted asset ids
                $insertedAsset_id[$i] = Database::get()->query("INSERT INTO `lp_asset`
                        (`path` , `module_id` , `comment`)
                        VALUES (?s, ?d, '')", $assetPath, $insertedModule_id[$i])->lastInsertID;
                
                if (!$insertedAsset_id[$i]) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorSql);
                    break;
                }
                // update of module with correct start asset id
                Database::get()->query("UPDATE `lp_module`
                        SET `startAsset_id` = ?d
                        WHERE `module_id` = ?d
                        AND `course_id` = ?d", $insertedAsset_id[$i], $insertedModule_id[$i], $course_id);

                // visibility
                if (isset($item['isvisible']) && $item['isvisible'] != '') {
                    ( $item['isvisible'] == "true" ) ? $visibility = 1 : $visibility = 0;
                } else {
                    $visibility = 1; // IMS consider that the default value of 'isvisible' is true
                }

                // finally : insert in learning path
                // get the inserted id of the learnPath_module rel to allow 'parent' link in next inserts
                $insertedLPMid[$item['itemIdentifier']]['LPMid'] = Database::get()->query("INSERT INTO `lp_rel_learnPath_module`
                        (`learnPath_id`, `module_id`, `specificComment`, `rank`, `visible`, `lock`, `parent`)
                        VALUES (?d, ?d, ?s, ?d, ?d, 'OPEN', ?d)", $tempPathId, $insertedModule_id[$i], $langDefaultModuleAddedComment, $rank, $visibility, $parent)->lastInsertID;
                $insertedLPMid[$item['itemIdentifier']]['rank'] = 1;

                if (!$insertedLPMid[$item['itemIdentifier']]['LPMid']) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorSql);
                    break;
                }

                if (!$errorFound) {
                    array_push($okMsgs, $langOkModuleAdded . "<i>" . $moduleName . "</i>");
                }
                $i++;
            }//foreach
        } // if sizeof($manifestData['items'] == 0 )
    } // if errorFound
    // last step
    // - delete all added files/directories/records in db
    // or
    // - update the learning path record

    if ($errorFound) {
        // delete all database entries of this "module"
        // delete modules and assets (build query)
        // delete assets
        $sqlDelAssets = "DELETE FROM `lp_asset` WHERE 1 = 0";
        foreach ($insertedAsset_id as $insertedAsset) {
            $sqlDelAssets .= " OR `asset_id` = " . intval($insertedAsset);
        }
        Database::get()->query($sqlDelAssets);

        // delete modules
        $sqlDelModules = "DELETE FROM `lp_module` WHERE 1 = 0";
        foreach ($insertedModule_id as $insertedModule) {
            $sqlDelModules .= " OR ( `module_id` = " . intval($insertedModule) . " AND `course_id` = " . intval($course_id) . " )";
        }
        Database::get()->query($sqlDelModules);

        // delete learningPath_module
        Database::get()->query("DELETE FROM `lp_rel_learnPath_module` WHERE `learnPath_id` = ?d", $tempPathId);

        // delete learning path
        Database::get()->query("DELETE FROM `lp_learnPath`
                     WHERE `learnPath_id` = ?d
                     AND `course_id` = ?d", $tempPathId, $course_id);

        // delete the directory (and files) of this learning path and all its content
        claro_delete_file($baseWorkDir);
    } else {
        // finalize insertion : update the empty learning path insert that was made to find its id
        $rankMax = 1 + intval(Database::get()->querySingle("SELECT MAX(`rank`) AS max
                FROM `lp_learnPath`
                WHERE `course_id` = ?d", $course_id)->max);

        if (isset($manifestData['packageTitle'])) {
            $lpName = $manifestData['packageTitle'];
        } else {
            array_push($okMsgs, $langOkDefaultTitleUsed);
        }

        if (isset($manifestData['packageDesc'])) {
            $lpComment = $manifestData['packageDesc'];
        } else {
            $lpComment = $langDefaultLearningPathComment;
            array_push($okMsgs, $langOkDefaultCommentUsed);
        }

        Database::get()->query("UPDATE `lp_learnPath`
                SET `rank` = ?d,
                    `name` = ?s,
                    `comment` = ?s,
                    `visible` = 1
                WHERE `learnPath_id` = ?d
                AND `course_id` = ?d", $rankMax, $lpName, $lpComment, $tempPathId, $course_id);
    }

    /* --------------------------------------
      status messages
      -------------------------------------- */
    $importMessages = "\n<p>\n";
    //$importMessages .= "<!-- Messages -->";
    foreach ($okMsgs as $msg) {
        $importMessages .= "\n<b>[</b><span class=\"correct\">$langSuccessOk</span><b>]</b>&nbsp;&nbsp;&nbsp;" . $msg . "<br />";
    }

    foreach ($errorMsgs as $msg) {
        $importMessages .= "\n<b>[</b><span class=\"error\">$langError</span><b>]</b>&nbsp;&nbsp;&nbsp;" . $msg . "<br />";
    }

    $importMessages .= "\n\n";
    //$importMessages .= "<!-- End messages -->";
    // installation completed or not message
    if (!$errorFound) {
        $importMessages .= "\n<br /><center><b>" . $langInstalled . "</b></center>";
        if ($displayExtraMessages == true) {
            $importMessages .= "\n<br /><br ><center><a href=\"learningPathAdmin.php?course=$course_code&amp;path_id=" . $tempPathId . "\">" . $lpName . "</a></center>";
        }        
        $importMessages .= "\n<br /><br >";
    }
    else {
        $importMessages .= "\n<br /><center><b>" . $langNotInstalled . "</b></center>";
    }
    //$importMessages .= "\n<br /><a href=\"index.php?course=$course_code\">$langBack</a></p>";
    $importMessages .= "\n<br /></p>";

    chdir($pwd);

    return array($importMessages, $tempPathId);
}