Exemple #1
0
 public function export()
 {
     $postsList = $this->loadTopic($this->getTopicId());
     $topicInfo = get_topic_settings($this->getTopicId());
     $css = $this->importCss();
     $form = new PhpTemplate(get_module_path('CLFRM') . '/templates/forum_export.tpl.php');
     $form->assign('forum_id', $topicInfo['forum_id']);
     $form->assign('topic_id', $topicInfo['topic_id']);
     $form->assign('notification_bloc', false);
     $form->assign('topic_subject', $topicInfo['topic_title']);
     $form->assign('postList', $postsList);
     $form->assign('claro_notifier', false);
     $form->assign('is_allowedToEdit', false);
     $form->assign('date', null);
     $out = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . "\n" . '<html>' . "\n" . '<head>' . "\n" . '<meta http-equiv="Content-Type" content="text/HTML; charset=' . get_conf('charset') . '"  />' . "\n" . '<style type="text/css">' . $css . '</style>' . "\n" . '<title>' . $topicInfo['topic_title'] . '</title>' . "\n" . '</head>' . "\n" . '<body><div id="forumExport">' . "\n";
     $out .= $form->render();
     $out .= '</div></body>' . "\n" . '</html>';
     $path = get_conf('rootSys') . get_conf('tmpPathSys') . '/forum_export/';
     $filename = $path . replace_dangerous_char(str_replace(' ', '_', $topicInfo['topic_title']) . '_' . $topicInfo['topic_id']) . '.html';
     claro_mkdir($path);
     file_put_contents($filename, $out);
     switch ($this->output) {
         case 'screen':
             header('Content-Description: File Transfer');
             header('Content-Type: application/force-download');
             header('Content-Length: ' . filesize($filename));
             header('Content-Disposition: attachment; filename=' . basename($filename));
             readfile($filename);
             claro_delete_file($filename);
             break;
         case 'file':
             break;
     }
     return true;
 }
Exemple #2
0
/**
 * Handle user's profile picture modification
 * (based on $_REQUEST['delPicture'] and $_FILE['picture'].
 *
 * @return  $feedback array (yes, it is kinda ugly)
 */
function user_handle_profile_picture($userData)
{
    $feedback = array('success' => false, 'messages' => array(), 'pictureName' => '');
    // Handle user picture
    if (!empty($_REQUEST['delPicture'])) {
        $picturePath = user_get_picture_path($userData);
        if ($picturePath) {
            claro_delete_file($picturePath);
            $feedback['success'] = true;
            $feedback['messages'][] = get_lang("User picture deleted");
        } else {
            $feedback['messages'][] = get_lang("Cannot delete user picture");
        }
    }
    if (isset($_FILES['picture']['name']) && $_FILES['picture']['size'] > 0) {
        $fileName = $_FILES['picture']['name'];
        $fileTmpName = $_FILES['picture']['tmp_name'];
        if (is_uploaded_file($fileTmpName)) {
            // Is it an picture ?
            if (is_image($fileName)) {
                // Does it meet the platform's requirements
                list($width, $height, $type, $attr) = getimagesize($fileTmpName);
                if ($width > 0 && $width <= get_conf('maxUserPictureWidth', 150) && $height > 0 && $height <= get_conf('maxUserPictureHeight', 200) && $_FILES['picture']['size'] <= get_conf('maxUserPictureSize', 100 * 1024)) {
                    $uploadDir = user_get_private_folder_path($userData['user_id']);
                    if (!file_exists($uploadDir)) {
                        claro_mkdir($uploadDir, CLARO_FILE_PERMISSIONS, true);
                    }
                    // User's picture successfully treated
                    if (false !== ($pictureName = treat_uploaded_file($_FILES['picture'], $uploadDir, '', 1000000000000.0))) {
                        $feedback['success'] = true;
                        $feedback['messages'][] = get_lang("User picture added");
                        $feedback['pictureName'] = $pictureName;
                    } else {
                        $feedback['messages'][] = get_lang("Cannot upload file");
                    }
                } else {
                    $feedback['messages'][] = get_lang("Image is too big : max size %width%x%height%, %size% bytes", array('%width%' => get_conf('maxUserPictureWidth', 150), '%height%' => get_conf('maxUserPictureHeight', 200), '%size%' => get_conf('maxUserPictureHeight', 100 * 1024)));
                }
            } else {
                $feedback['messages'][] = get_lang("Invalid file format, use gif, jpg or png");
            }
        } else {
            $feedback['messages'][] = get_lang('Upload failed');
        }
    }
    return $feedback;
}
Exemple #3
0
/**
 * Delete a file or a directory (and its whole content)
 *
 * @param  - $filePath (String) - the path of file or directory to delete
 * @return - boolean - true if the delete succeed
 *           boolean - false otherwise.
 */
function claro_delete_file($filePath)
{
    if (is_file($filePath)) {
        return unlink($filePath);
    } elseif (is_dir($filePath)) {
        $dirHandle = @opendir($filePath);
        if (!$dirHandle) {
            function_exists('claro_html_debug_backtrace') && pushClaroMessage(claro_html_debug_backtrace());
            return false;
        }
        $removableFileList = array();
        while (false !== ($file = readdir($dirHandle))) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            $removableFileList[] = $filePath . '/' . $file;
        }
        closedir($dirHandle);
        // impossible to test, closedir return void ...
        if (sizeof($removableFileList) > 0) {
            foreach ($removableFileList as $thisFile) {
                if (!claro_delete_file($thisFile)) {
                    return false;
                }
            }
        }
        clearstatcache();
        if (is_writable($filePath)) {
            return @rmdir($filePath);
        } else {
            function_exists('claro_html_debug_backtrace') && pushClaroMessage(claro_html_debug_backtrace());
            return false;
        }
    }
    // end elseif is_dir()
}
Exemple #4
0
         case 'curl':
             $dialogBox->error('<p>' . "\n" . get_lang('This feature is not ready.') . '</p>' . "\n\n");
             $dialogBox->warning('<p>' . "\n" . get_lang('Imported modules must consist of a zip file and be compatible with your Claroline version.') . '<br />' . "\n" . get_lang('Find more available modules on <a href="http://www.claroline.net/">Claroline.net</a>.') . '</p>' . "\n\n");
             $dialogBox->form('<form action="' . $_SERVER['PHP_SELF'] . '" method="GET">' . "\n" . '<input type="hidden" name="claroFormId" value="' . uniqid('') . '" />' . '<input name="cmd" type="hidden" value="exInstall" />' . "\n" . get_lang('Url of package') . '<br />' . "\n" . '<input name="packageCandidateUrl" size="80" type="text" /><br />' . "\n" . '<input name="activateOnInstall"  id="activateOnInstall" type="checkbox" />' . '<label for="activateOnInstall" >' . get_lang('Activate module on install') . '</label>' . '<br />' . '<input name="visibleOnInstall"  id="visibleOnInstall" type="checkbox" />' . '<label for="visibleOnInstall" >' . get_lang('Visible on  each course on install <small>(tool only)</small>') . '</label>' . '<br />' . "\n" . '<br />' . "\n" . '<input value="' . get_lang('Fetch and install module') . '" type="submit" />&nbsp;' . "\n" . claro_html_button($_SERVER['PHP_SELF'], get_lang('Cancel')) . '</form>' . "\n");
             break;
     }
     break;
     // rqInstall
 // rqInstall
 case 'exLocalRemove':
     if (isset($_REQUEST['moduleDir'])) {
         $moduleDir = str_replace('../', '', $_REQUEST['moduleDir']);
         $moduleRepositorySys = get_path('rootSys') . 'module/';
         $modulePath = $moduleRepositorySys . $moduleDir . '/';
         if (file_exists($modulePath)) {
             if (claro_delete_file($modulePath)) {
                 $dialogBox->success('<p>' . "\n" . get_lang('Module files deleted') . '</p>' . "\n");
             } else {
                 $dialogBox->error('<p>' . "\n" . get_lang('Error while deleting module files') . '</p>' . "\n");
                 $success = false;
             }
         }
     } else {
         $summary = get_lang('Module installation failed');
         $details = get_lang('Missing module directory');
         $dialogBox->error(Backlog_Reporter::report($summary, $details));
     }
     break;
 case 'exLocalInstall':
     if (isset($_REQUEST['moduleDir'])) {
         $moduleDir = str_replace('../', '', $_REQUEST['moduleDir']);
function claro_delete_file($filePath)
{
    if (is_file($filePath)) {
        return unlink($filePath);
    } elseif (is_dir($filePath)) {
        $dirHandle = opendir($filePath);
        if (!$dirHandle) {
            return false;
        }
        $removableFileList = array();
        while ($file = readdir($dirHandle)) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            $removableFileList[] = $filePath . '/' . $file;
        }
        closedir($dirHandle);
        // impossible to test, closedir return void ...
        if (sizeof($removableFileList) > 0) {
            foreach ($removableFileList as $thisFile) {
                if (!claro_delete_file($thisFile)) {
                    return false;
                }
            }
        }
        return rmdir($filePath);
    }
    // end elseif is_dir()
}
Exemple #6
0
 /**
  * delete assignment from DB
  *
  * @author Sebastien Piraux <*****@*****.**>
  * @return boolean
  */
 public function delete()
 {
     $sql = "DELETE FROM `" . $this->tblSubmission . "`\n                WHERE `assignment_id` = '" . $this->id . "'";
     if (claro_sql_query($sql)) {
         $sql = "DELETE FROM `" . $this->tblAssignment . "`\n                    WHERE `id` = '" . $this->id . "'";
         if (claro_sql_query($sql)) {
             claro_delete_file($this->assigDirSys);
         } else {
             return false;
         }
     } else {
         return false;
     }
     $this->id = -1;
     return true;
 }
Exemple #7
0
/**
 * Uninstall a specific module to the platform
 *
 * @param integer $moduleId the id of the module to uninstall
 * @return array( backlog, boolean )
 *      backlog object
 *      boolean true if the uninstall process suceeded, false otherwise
 * @todo remove the need of the Backlog and use Exceptions instead
 */
function uninstall_module($moduleId, $deleteModuleData = true)
{
    $success = true;
    $backlog = new Backlog();
    //first thing to do : deactivate the module
    // deactivate_module($moduleId);
    $moduleInfo = get_module_info($moduleId);
    if ($moduleInfo['type'] == 'tool' && $moduleId) {
        // 2- delete the module in the cours_tool table, used for every course creation
        list($backlog2, $success2) = unregister_module_from_courses($moduleId);
        if ($success2) {
            $backlog->success(get_lang('Module uninstalled in all courses'));
        } else {
            $backlog->append($backlog2);
        }
    }
    //Needed tables and vars
    $tbl = claro_sql_get_main_tbl();
    $backlog = new Backlog();
    // 0- find info about the module to uninstall
    $sql = "SELECT `label`\n              FROM `" . $tbl['module'] . "`\n             WHERE `id` = " . (int) $moduleId;
    $module = claro_sql_query_get_single_row($sql);
    if ($module == false) {
        $backlog->failure(get_lang("No module to uninstall"));
        $success = false;
    } else {
        // 1- Include the local 'uninstall.sql' and 'uninstall.php' file of the module if they exist
        // call uninstall.php first in case it requires module database schema to run
        if (isset($uninstallPhpScript)) {
            unset($uninstallPhpScript);
        }
        $uninstallPhpScript = get_module_path($module['label']) . '/setup/uninstall.php';
        if (file_exists($uninstallPhpScript)) {
            language::load_translation();
            language::load_locale_settings();
            language::load_module_translation($module['label']);
            load_module_config($module['label']);
            require $uninstallPhpScript;
            $backlog->info(get_lang('Module uninstallation script called'));
        }
        if (isset($uninstallSqlScript)) {
            unset($uninstallSqlScript);
        }
        $uninstallSqlScript = get_module_path($module['label']) . '/setup/uninstall.sql';
        if ($deleteModuleData && file_exists($uninstallSqlScript)) {
            $sql = file_get_contents($uninstallSqlScript);
            if (!empty($sql)) {
                $sql = str_replace('__CL_MAIN__', get_conf('mainTblPrefix'), $sql);
                if (false !== claro_sql_multi_query($sql)) {
                    $backlog->success(get_lang('Database uninstallation succeeded'));
                } else {
                    $backlog->failure(get_lang('Database uninstallation failed'));
                    $success = false;
                }
            }
        } elseif (!$deleteModuleData && file_exists($uninstallSqlScript)) {
            $backlog->info(get_lang('Database uninstallation skipped'));
        }
        // 2- delete related files and folders
        $modulePath = get_module_path($module['label']);
        if (file_exists($modulePath)) {
            if (claro_delete_file($modulePath)) {
                $backlog->success(get_lang('Delete scripts of the module'));
            } else {
                $backlog->failure(get_lang('Error while deleting the scripts of the module'));
                $success = false;
            }
        }
        //  delete the module in the cours_tool table, used for every course creation
        //retrieve this module_id first
        $sql = "SELECT id as tool_id FROM `" . $tbl['tool'] . "`\n                WHERE claro_label = '" . $module['label'] . "'";
        $tool_to_delete = claro_sql_query_get_single_row($sql);
        $tool_id = $tool_to_delete['tool_id'];
        $sql = "DELETE FROM `" . $tbl['tool'] . "`\n                WHERE claro_label = '" . $module['label'] . "'\n            ";
        claro_sql_query($sql);
        // 3- delete related entries in main DB
        $sql = "DELETE FROM `" . $tbl['module'] . "`\n                WHERE `id` = " . (int) $moduleId;
        claro_sql_query($sql);
        $sql = "DELETE FROM `" . $tbl['module_info'] . "`\n                WHERE `module_id` = " . (int) $moduleId;
        claro_sql_query($sql);
        $sql = "DELETE FROM `" . $tbl['module_contexts'] . "`\n                WHERE `module_id` = " . (int) $moduleId;
        claro_sql_query($sql);
        // 4-Manage right - Delete read action
        $action = new RightToolAction();
        $action->setName('read');
        $action->setToolId($tool_id);
        $action->delete();
        // Manage right - Delete edit action
        $action = new RightToolAction();
        $action->setName('edit');
        $action->setToolId($tool_id);
        $action->delete();
        // 5- remove all docks entries in which the module displays
        // TODO FIXME handle failure
        remove_module_dock($moduleId, 'ALL');
        // 6- cache file with the module's include must be renewed after uninstallation of the module
        if (!generate_module_cache()) {
            $backlog->failure(get_lang('Module cache update failed'));
            $success = false;
        } else {
            $backlog->success(get_lang('Module cache update succeeded'));
        }
    }
    return array($backlog, $success);
}
Exemple #8
0
                $dialogBox->error(get_lang('Cannot copy the file'));
                $formCorrectlySent = false;
            }
            // remove the previous file if there was one
            if ($assignment->getAutoFeedbackFilename() != '') {
                if (file_exists($assignment->getAssigDirSys() . $assignment->getAutoFeedbackFilename())) {
                    claro_delete_file($assignment->getAssigDirSys() . $assignment->getAutoFeedbackFilename());
                }
            }
            // else : file sending shows no error
            // $formCorrectlySent stay true;
        }
    } elseif (isset($_REQUEST['delFeedbackFile'])) {
        // delete the file was requested
        if (file_exists($assignment->getAssigDirSys() . $assignment->getAutoFeedbackFilename())) {
            claro_delete_file($assignment->getAssigDirSys() . $assignment->getAutoFeedbackFilename());
        }
        $autoFeedbackFilename = '';
    } else {
        $autoFeedbackFilename = $assignment->getAutoFeedbackFilename();
    }
    $autoFeedbackSubmitMethod = $_REQUEST['autoFeedbackSubmitMethod'];
}
if ($is_allowedToEdit) {
    /*--------------------------------------------------------------------
      MODIFY An ASSIGNMENT FEEDBACK
      --------------------------------------------------------------------*/
    /*-----------------------------------
      STEP 2 : check & query
      -------------------------------------*/
    // edit an assignment / form has been sent
        /**
         * Create the final zip file.
         *
         * @return False on error, True otherwise.
         * @author Amand Tihon <*****@*****.**>
         */
        function zip() {
            global $langErrorCreatingScormArchive;

            $list = 1;
            $zipFile = new PclZip($this->destDir . '.zip');
            $list = $zipFile->create($this->destDir, PCLZIP_OPT_REMOVE_PATH, $this->destDir);

            if (!$list) {
                $this->error[] = $langErrorCreatingScormArchive;
                return false;
            }

            // Temporary directory can be deleted, now that the zip is made.
            claro_delete_file($this->destDir);

            return true;
        }
Exemple #10
0
 if (isset($_POST['phone'])) {
     $user_data['phone'] = trim($_POST['phone']);
 }
 if (isset($_POST['language'])) {
     $user_data['language'] = trim($_POST['language']);
 }
 if (isset($_POST['isCourseCreator'])) {
     $user_data['isCourseCreator'] = (int) $_POST['isCourseCreator'];
 }
 if (isset($_POST['is_admin'])) {
     $user_data['is_admin'] = (bool) $_POST['is_admin'];
 }
 if (isset($_POST['delPicture']) && $_POST['delPicture'] == 'true') {
     $picturePath = user_get_picture_path($user_data);
     if ($picturePath) {
         claro_delete_file($picturePath);
         $user_data['picture'] = '';
         $dialogBox->success(get_lang("User picture deleted"));
     } else {
         $dialogBox->error(get_lang("Cannot delete user picture"));
     }
 }
 // Handle user picture
 if (isset($_FILES['picture']['name']) && $_FILES['picture']['size'] > 0) {
     $fileName = $_FILES['picture']['name'];
     $fileTmpName = $_FILES['picture']['tmp_name'];
     if (is_uploaded_file($fileTmpName)) {
         if (is_image($fileName)) {
             list($width, $height, $type, $attr) = getimagesize($fileTmpName);
             if ($width > 0 && $width <= get_conf('maxUserPictureWidth', 150) && $height > 0 && $height <= get_conf('maxUserPictureHeight', 200) && $_FILES['picture']['size'] <= get_conf('maxUserPictureSize', 100 * 1024)) {
                 $uploadDir = user_get_private_folder_path($user_data['user_id']);
Exemple #11
0
     }
     claro_sql_query($delAssetSql);
     // DELETE the SCORM modules
     $delModuleSql = "DELETE\n                                 FROM `" . $TABLEMODULE . "`\n                                 WHERE (`contentType` = '" . CTSCORM_ . "' OR `contentType` = '" . CTLABEL_ . "')\n                                 AND (1=0\n                                 ";
     if (mysql_num_rows($findResult) > 0) {
         mysql_data_seek($findResult, 0);
     }
     while ($delList = mysql_fetch_array($findResult)) {
         $delModuleSql .= " OR `module_id`=" . (int) $delList['module_id'];
     }
     $delModuleSql .= ")";
     claro_sql_query($delModuleSql);
     // DELETE the directory containing the package and all its content
     //TODO use claro_get_course_data_repository()
     $real = realpath(get_path('coursesRepositorySys') . claro_get_course_path() . '/scormPackages/path_' . $_GET['del_path_id']);
     claro_delete_file($real);
 } else {
     $findsql = "SELECT M.`module_id`\n                                 FROM  `" . $TABLELEARNPATHMODULE . "` AS LPM,\n                                      `" . $TABLEMODULE . "` AS M\n                                 WHERE LPM.`learnPath_id` = " . (int) $_GET['del_path_id'] . "\n                                 AND M.`contentType` = '" . CTLABEL_ . "'\n                                 AND LPM.`module_id` = M.`module_id`\n                                 ";
     //echo $findsql;
     $findResult = claro_sql_query($findsql);
     // delete labels of non scorm learning path
     $delLabelModuleSql = "DELETE\n                                     FROM `" . $TABLEMODULE . "`\n                                     WHERE 1=0\n                                  ";
     while ($delList = mysql_fetch_array($findResult)) {
         $delLabelModuleSql .= " OR `module_id`=" . (int) $delList['module_id'];
     }
     //echo $delLabelModuleSql;
     $query = claro_sql_query($delLabelModuleSql);
 }
 // delete everything for this path (common to normal and scorm paths) concerning modules, progression and path
 // delete all user progression
 $sql1 = "DELETE\n                       FROM `" . $TABLEUSERMODULEPROGRESS . "`\n                       WHERE `learnPath_id` = " . (int) $_GET['del_path_id'];
Exemple #12
0
 /**
  * Create the final zip file.
  *
  * @return False on error, True otherwise.
  * @author Amand Tihon <*****@*****.**>
  */
 public function zip()
 {
     $list = 1;
     $zipFile = new PclZip($this->destDir . '.zip');
     if ($this->fromScorm) {
         $exportFrom = $this->destDir . '/OrigScorm';
     } else {
         $exportFrom = $this->destDir;
     }
     $list = $zipFile->create($exportFrom, PCLZIP_OPT_REMOVE_PATH, $exportFrom);
     if (!$list) {
         $this->error[] = get_lang('Unable to create the SCORM archive');
         return false;
     }
     // Temporary directory can be deleted, now that the zip is made.
     claro_delete_file($this->destDir);
     return true;
 }
Exemple #13
0
                foreach ($topicsList as $topic) {
                    $export = new exportHTML($topic['topic_id'], 'file');
                    if (!$export->export()) {
                        $dialogBox->error(get_lang('Unable to export your topic in HTML format.'));
                        break;
                    }
                }
                include_once get_path('incRepositorySys') . "/lib/thirdparty/pclzip/pclzip.lib.php";
                $filename = replace_dangerous_char(str_replace(' ', '_', $forumSettingList['forum_name'])) . '.zip';
                $path = get_conf('rootSys') . get_conf('tmpPathSys') . '/forum_export/';
                $zipFile = new PclZip($filename);
                $list = $zipFile->create($path, PCLZIP_OPT_REMOVE_PATH, $path);
                if (!$list) {
                    $dialogBox->error(get_lang('Unable to create the archive'));
                    break;
                }
                claro_delete_file($path);
                header('Content-Description: File Transfer');
                header('Content-Type: application/force-download');
                header('Content-Length: ' . filesize($filename));
                header('Content-Disposition: attachment; filename=' . basename($filename));
                readfile($filename);
                claro_delete_file($filename);
                exit(0);
            }
            break;
    }
}
$out .= $dialogBox->render();
$claroline->display->body->appendContent($out);
echo $claroline->display->render();
Exemple #14
0
 public function delete($assigDirSys)
 {
     $sql = "DELETE FROM `" . $this->tblSubmission . "`\n                WHERE `id` = '" . $this->id . "'";
     if (claro_sql_query($sql)) {
         if (!empty($this->submittedFilename) && file_exists($assigDirSys . $this->submittedFilename)) {
             claro_delete_file($assigDirSys . $this->submittedFilename);
         }
     } else {
         return false;
     }
 }
Exemple #15
0
     claro_sql_query($sql);
     //delete all user progression concerning this module
     $sql = "DELETE\n                FROM `" . $TABLEUSERMODULEPROGRESS . "`\n                WHERE 1=0 ";
     while ($list = mysql_fetch_array($result)) {
         $sql .= " OR `learnPath_module_id`=" . (int) $list['learnPath_module_id'];
     }
     claro_sql_query($sql);
     // This query does the same as the 3 previous queries but does not work with MySQL versions before 4.0.0
     // delete all asset, all learning path module, and from module table
     /*
     claro_sql_query("DELETE
                    FROM `".$TABLEASSET."`, `".$TABLELEARNPATHMODULE."`, `".$TABLEMODULE."`
                   WHERE `module_id` = ".$_REQUEST['cmdid'] );
     */
     // delete directory and it content
     claro_delete_file($moduleWorkDir . "/module_" . (int) $_REQUEST['cmdid']);
     break;
     // COMMAND RENAME :
     //display the form to enter new name
 // COMMAND RENAME :
 //display the form to enter new name
 case "rqRename":
     //get current name from DB
     $query = "SELECT `name`\n                 FROM `" . $TABLEMODULE . "`\n                 WHERE `module_id` = '" . (int) $_REQUEST['module_id'] . "'";
     $result = claro_sql_query($query);
     $list = mysql_fetch_array($result);
     $out .= "\n" . '<form method="post" name="rename" action="' . $_SERVER['PHP_SELF'] . '">' . "\n" . claro_form_relay_context() . '<label for="newName">' . get_lang('Insert new name') . '</label> :' . "\n" . '<input type="text" name="newName" id="newName" value="' . claro_htmlspecialchars($list['name']) . '" />' . "\n" . '<input type="submit" value="' . get_lang('Ok') . '" name="submit" />' . "\n" . '<input type="hidden" name="cmd" value="exRename" />' . "\n" . '<input type="hidden" name="module_id" value="' . $_REQUEST['module_id'] . '" />' . "\n" . '</form>' . "\n\n";
     break;
     //try to change name for selected module
 //try to change name for selected module
 case "exRename":
Exemple #16
0
/**
 * Main function to import an exercise.
 *
 * @param string $file path of the file
 * @param array $backlog_message
 *
 * @return the id of the created exercise or false if the operation failed
 */
function import_exercise($file, &$backlog)
{
    global $exercise_info;
    global $element_pile;
    global $non_HTML_tag_to_avoid;
    global $record_item_body;
    // used to specify the question directory where files could be found in relation in any question
    global $questionTempDir;
    // get required table names
    $tbl_cdb_names = get_module_course_tbl(array('qwz_exercise', 'qwz_question'), claro_get_current_course_id());
    $tbl_quiz_exercise = $tbl_cdb_names['qwz_exercise'];
    $tbl_quiz_question = $tbl_cdb_names['qwz_question'];
    // paths
    $baseWorkDir = get_path('rootSys') . get_conf('tmpPathSys') . 'upload/';
    // create temp dir for upload
    if (!file_exists($baseWorkDir)) {
        claro_mkdir($baseWorkDir, CLARO_FILE_PERMISSIONS);
    }
    $uploadDir = claro_mkdir_tmp($baseWorkDir);
    // this function should return the dir name and not the full path ...
    $uploadPath = str_replace($baseWorkDir, '', $uploadDir);
    // set some default values for the new exercise
    $exercise_info = array();
    $exercise_info['name'] = preg_replace('/.zip$/i', '', $file);
    $exercise_info['description'] = '';
    $exercise_info['question'] = array();
    // create parser and array to retrieve info from manifest
    $element_pile = array();
    //pile to known the depth in which we are
    $module_info = array();
    //array to store the info we need
    // if file is not a .zip, then we cancel all
    if (!preg_match('/.zip$/i', $_FILES['uploadedExercise']['name'])) {
        $backlog->failure(get_lang('You must upload a zip file'));
        return false;
    }
    //unzip the uploaded file in a tmp directory
    if (!get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)) {
        $backlog->failure(get_lang('Upload failed'));
        return false;
    }
    // find the different manifests for each question and parse them.
    $exerciseHandle = opendir($uploadDir);
    $question_number = 0;
    $file_found = false;
    // parse every subdirectory to search xml question files
    while (false !== ($file = readdir($exerciseHandle))) {
        if (is_dir($uploadDir . '/' . $file) && $file != "." && $file != "..") {
            //find each manifest for each question repository found
            $questionHandle = opendir($uploadDir . '/' . $file);
            while (false !== ($questionFile = readdir($questionHandle))) {
                if (preg_match('/.xml$/i', $questionFile)) {
                    list($parsingBacklog, $success) = parse_file($uploadDir, $file, $questionFile);
                    $backlog->append($parsingBacklog);
                    $file_found = true;
                }
            }
        } elseif (preg_match('/.xml$/i', $file)) {
            list($parsingBacklog, $success) = parse_file($uploadDir, '', $file);
            $backlog->append($parsingBacklog);
            $file_found = true;
        }
        // else ignore file
    }
    if (!$file_found) {
        $backlog->failure(get_lang('No XML file found in the zip'));
        return false;
    }
    //---------------------
    //add exercise in tool
    //---------------------
    //1.create exercise
    $exercise = new Exercise();
    $exercise->setTitle($exercise_info['name']);
    $exercise->setDescription($exercise_info['description']);
    if ($exercise->validate()) {
        $exercise_id = $exercise->save();
    } else {
        $backlog->failure(get_lang('There is an error in exercise data of imported file.'));
        return false;
    }
    ksort($exercise_info['question'], SORT_NUMERIC);
    //For each question found...
    foreach ($exercise_info['question'] as $key => $question_array) {
        //2.create question
        $question = new Qti2Question();
        $question->import($question_array);
        if ($question->validate()) {
            // I need to save the question after the answer because I need question id in answers
            $question_id = $question->save();
            //3.create answers
            $question->setAnswer();
            $question->answer->import($question_array);
            if ($question->answer->validate()) {
                $question->setGrade($question->answer->getGrade());
                $question->save();
                // save computed grade
                $question->answer->save();
                $exercise->addQuestion($question_id);
            } else {
                $backlog->failure(get_lang('Invalid answer') . ' : ' . $key);
            }
        } else {
            $backlog->failure(get_lang('Invalid question') . ' : ' . $key);
        }
    }
    // delete the temp dir where the exercise was unzipped
    claro_delete_file($uploadDir);
    return $exercise_id;
}
Exemple #17
0
 /**
  *
  *
  * @author Sebastien Piraux <*****@*****.**>
  */
 public function moveAttachment()
 {
     if (!empty($this->attachment) && !empty($this->tmpQuestionDirSys)) {
         if (claro_move_file($this->tmpQuestionDirSys . $this->attachment, $this->questionDirSys . $this->attachment)) {
             claro_delete_file($this->tmpQuestionDirSys);
             $this->tmpQuestionDirSys = '';
             return true;
         } else {
             return false;
         }
     }
     return true;
 }
Exemple #18
0
 /*------------------------------------------------------------------------
                       MOVE FILE OR DIRECTORY : STEP 1
   --------------------------------------------------------------------------*/
 if ('rqMv' == $cmd) {
     $dialogBox->form(form_dir_list($_REQUEST['file'], $baseWorkDir));
 }
 /*= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
                         DELETE FILE OR DIRECTORY
   = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = */
 if ('exRm' == $cmd) {
     $file = secure_file_path($_REQUEST['file']);
     $checkFile = trim($file, '/');
     $checkFile = trim($checkFile);
     if (empty($checkFile)) {
         $dialogBox->error(get_lang('Cannot delete : missing file or directory name'));
     } elseif (!empty($checkFile) && claro_delete_file($baseWorkDir . $file)) {
         if ($courseContext) {
             update_db_info('delete', $file);
             update_Doc_Path_in_Assets('delete', $file, '');
         }
         //notify that a document has been deleted
         $eventNotifier->notifyCourseEvent("document_file_deleted", claro_get_current_course_id(), claro_get_current_tool_id(), $_REQUEST['file'], claro_get_current_group_id(), "0");
         $dialogBox->success(get_lang("Document deleted"));
     }
 }
 /*= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
                                   EDIT
   = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = */
 /*
  * The code begin with STEP 2
  * so it allows to return to STEP 1
Exemple #19
0
                $htmlContent .= get_lang('Attached file') . ' : ' . $submissionPrefix . $result['submitted_doc_path'] . '<br />' . "\n";
            }
            $htmlContent .= '<div>' . "\n" . '<h3>' . get_lang('Description') . '</h3>' . "\n" . $result['submitted_text'] . '</div>' . "\n" . '</body></html>';
            file_put_contents($zipPath . '/' . $submissionPrefix . $txtFileName, $htmlContent);
        }
        $zipFile = new PclZip($downloadArchiveFilePath);
        $created = $zipFile->create($zipPath, PCLZIP_OPT_REMOVE_PATH, $zipPath);
        if (!$created) {
            $dialogBox->error(get_lang('Unable to create the archive'));
        } else {
            claro_delete_file($zipPath);
            header('Content-Description: File Transfer');
            header('Content-Type: application/force-download');
            header('Content-Length: ' . filesize($downloadArchiveFilePath));
            header('Content-Disposition: attachment; filename=' . str_replace(',', '', replace_dangerous_char($zipName)));
            readfile($downloadArchiveFilePath);
            claro_delete_file($downloadArchiveFilePath);
            if (!empty($tmpFolderPath)) {
                $gc = new ClaroGarbageCollector($tmpFolderPath, 3600);
                $gc->run();
            }
            exit;
        }
    } else {
        $dialogBox->error(get_lang('There is no submission available for download with these settings.'));
    }
}
$out .= $dialogBox->render();
ClaroBreadCrumbs::getInstance()->prepend(get_lang('Assignments'), 'work.php');
$claroline->display->body->appendContent($out);
echo $claroline->display->render();
     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`\n                     WHERE `learnPath_id` = ?d\n                     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\n                FROM `lp_learnPath`\n                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`\n                SET `rank` = ?d,\n                    `name` = ?s,\n                    `comment` = ?s,\n                    `visible` = 1\n                WHERE `learnPath_id` = ?d\n                AND `course_id` = ?d", $rankMax, $lpName, $lpComment, $tempPathId, $course_id);
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);
}