<?php

        $options = array(array('image' => '16x16/about.png',       'title' => _INFORMATION,  'link' => $_GET['op'] != 'course_info'        ? basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_info'         : 'javascript:void(0)', 'selected' => $_GET['op'] != 'course_info'         ? false : true),
                         array('image' => '16x16/certificate.png', 'title' => _CERTIFICATES, 'link' => $_GET['op'] != 'course_certificate' ? basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_certificates' : 'javascript:void(0)', 'selected' => $_GET['op'] != 'course_certificates' ? false : true),
                         array('image' => '16x16/recycle.png',     'title' => _RULES,        'link' => $_GET['op'] != 'course_rules'       ? basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_rules'        : 'javascript:void(0)', 'selected' => $_GET['op'] != 'course_rules'        ? false : true),
                         array('image' => '16x16/replace2.png',    'title' => _ORDER,        'link' => $_GET['op'] != 'course_order'       ? basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_order'        : 'javascript:void(0)', 'selected' => $_GET['op'] != 'course_order'        ? false : true),
                         array('image' => '16x16/calendar.png',    'title' => _SCHEDULING,   'link' => $_GET['op'] != 'course_scheduling'  ? basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_scheduling'   : 'javascript:void(0)', 'selected' => $_GET['op'] != 'course_scheduling'   ? false : true),
                         array('image' => '16x16/export1.png',     'title' => _EXPORT,       'link' => $_GET['op'] != 'export_course'      ? basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=export_course'       : 'javascript:void(0)', 'selected' => $_GET['op'] != 'export_course'       ? false : true),
                         array('image' => '16x16/import2.png',     'title' => _IMPORT,       'link' => $_GET['op'] != 'import_course'      ? basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=import_course'       : 'javascript:void(0)', 'selected' => $_GET['op'] != 'import_course'       ? false : true));
        $smarty -> assign("T_TABLE_OPTIONS", $options);

        if ($currentUser -> user['user_type'] == 'administrator') {
            $smarty -> assign("T_COURSE_OPTIONS", array(array('text' => _EDITCOURSE,  'image' => "16x16/edit.png", 'href' => basename($_SERVER['PHP_SELF'])."?ctg=courses&edit_course=".$_GET['course'])));
        }

        if ($_GET['op'] == 'course_info') {
            $form = new HTML_QuickForm("empty_form", "post", null, null, null, true);

            $courseInformation = unserialize($currentCourse -> course['info']);
            $information       = new LearningObjectInformation($courseInformation);
            $smarty -> assign("T_COURSE_INFO_HTML", $information -> toHTML($form, false));

            $courseMetadata = unserialize($currentCourse -> course['metadata']);
            $metadata       = new DublinCoreMetadata($courseMetadata);
            $smarty -> assign("T_COURSE_METADATA_HTML", $metadata -> toHTML($form));

            if (isset($_GET['postAjaxRequest'])) {
                if (in_array($_GET['dc'], array_keys($information -> metadataAttributes))) {
                    if ($_GET['value']) {
                        $courseInformation[$_GET['dc']] = $_GET['value'];
                    } else {
                        unset($courseInformation[$_GET['dc']]);
                    }
                    $currentCourse -> course['info'] = serialize($courseInformation);
                } elseif (in_array($_GET['dc'], array_keys($metadata -> metadataAttributes))) {
                    if ($_GET['value']) {
                        $courseMetadata[$_GET['dc']] = $_GET['value'];
                    } else {
                        unset($courseMetadata[$_GET['dc']]);
                    }
                    $currentCourse -> course['metadata'] = serialize($courseMetadata);
                }

                $currentCourse -> persist();
                echo $_GET['value'];
                exit;
            }

        } else if ($_GET['op'] == 'course_certificates') {

            $users = EfrontStats::getUsersCourseStatus($currentCourse);
            $users = $users[$currentCourse -> course['id']];
            if (isset($_GET['edit_user']) && in_array($_GET['edit_user'], array_keys($users))) {
                $userStats = $users[$_GET['edit_user']];
                $form = new HTML_QuickForm("edit_user_complete_course_form", "post", basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_certificates&edit_user='.$_GET['edit_user'].'&popup=1', "", null, true);
                $form -> registerRule('checkParameter', 'callback', 'eF_checkParameter');                   //Register this rule for checking user input with our function, eF_checkParameter

                $form -> addElement('advcheckbox', 'completed', _COMPLETED, null, 'class = "inputCheckbox"');            //Whether the user has completed the course
                $form -> addElement('text', 'score', _SCORE, 'class = "inputText" style = "width:40px;"');                                                        //The user course score
                $form -> addRule('score', _THEFIELD.' "'._SCORE.'" '._MUSTBENUMERIC, 'numeric', null, 'client');                            //The score must be numeric
                $form -> addRule('score', _RATEMUSTBEBETWEEN0100, 'callback', create_function('&$a', 'return ($a >= 0 && $a <= 100);'));    //The score must be between 0 and 100

                $form -> addElement('textarea', 'comments', _COMMENTS, 'class = "inputContentTextarea simpleEditor" style = "width:100%;height:5em;"');      //Comments on student's performance
                $form -> addElement('submit', 'submit_course_complete', _SUBMIT, 'class = "flatButton"');       //The submit button

                $totalScore = 0;
                foreach ($userStats['lesson_status'] as $stat) {
                    $totalScore += $stat['score'] / sizeof($userStats['lesson_status']);
                }

                $form -> setDefaults(array("completed" => $userStats['completed'],
                                           "score"     => $userStats['completed'] ? $userStats['score'] : round($totalScore),
                                           "comments"  => $userStats['comments']));

                if ($form -> isSubmitted() && $form -> validate()) {
                    $fields = array("completed" => $form -> exportValue('completed') ? 1 : 0,
                                    "score"     => $form -> exportValue('completed') ? $form -> exportValue('score')    : 0,
                                    "comments"  => $form -> exportValue('completed') ? $form -> exportValue('comments') : '');
                    eF_updateTableData("users_to_courses", $fields, "users_LOGIN = '".$_GET['edit_user']."' and courses_ID=".$currentCourse -> course['id']);
                    echo '<script>parent.location="'.basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_certificates&message='.urlencode(_STUDENTSTATUSCHANGED).'&message_type=success"</script>';//header('location:'.ltrim("/", basename($_SERVER['PHP_SELF'])).'?'.$baseUrl.'&op=course_certificates&message='.urlencode(_STUDENTSTATUSCHANGED).'&message_type=success');
                }

                $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);

                $form -> setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
                $form -> setRequiredNote(_REQUIREDNOTE);
                $form -> accept($renderer);

                $smarty -> assign('T_COMPLETE_COURSE_FORM', $renderer -> toArray());
                $smarty -> assign("T_USER_PROGRESS", $userStats);
            } else if (isset($_GET['issue_certificate']) && in_array($_GET['issue_certificate'], array_keys($users))) {
                try {
                    $certificate = $currentCourse -> prepareCertificate($_GET['issue_certificate']);
                    $currentCourse -> issueCertificate($_GET['issue_certificate'], $certificate);
                    header('location:'.basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_certificates&message='.urlencode(_STUDENTSTATUSCHANGED).'&message_type=success');
                } catch (Exception $e) {
                    $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                    $message      = _PROBLEMISSUINGCERTIFICATE.': '.$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
                    $message_type = 'failure';
                }
            } else if (isset($_GET['revoke_certificate']) && in_array($_GET['revoke_certificate'], array_keys($users))) {
                try {
                    $currentCourse -> revokeCertificate($_GET['revoke_certificate']);
                    header('location:'.basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=course_certificates&message='.urlencode(_CERTIFICATEREVOKED).'&message_type=success');
                } catch (Exception $e) {
                    $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                    $message      = _PROBLEMREVOKINGCERTIFICATE.': '.$e -> getMessage().' &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
                    $message_type = 'failure';
                }
            } else if (isset($_GET['auto_complete'])) {
                if ($currentCourse -> course['auto_complete']) {
                    $currentCourse -> course['auto_complete']    = 0;
                    $currentCourse -> course['auto_certificate'] = 0;
                } else {
                    $currentCourse -> course['auto_complete'] = 1;
                }
                $currentCourse -> persist();
            } else if (isset($_GET['auto_certificate'])) {
                if ($currentCourse -> course['auto_certificate']) {
                    $currentCourse -> course['auto_certificate'] = 0;
                } else {
                    $currentCourse -> course['auto_certificate'] = 1;
                }
                $currentCourse -> persist();
            }

            if (isset($_GET['ajax']) && $_GET['ajax'] == 'usersTable') {
                foreach ($users as $key => $user) {
                    if ($user['user_type'] != 'student') {
                        unset($users[$key]);
                    }
                }

                isset($_GET['limit']) && eF_checkParameter($_GET['limit'], 'uint') ? $limit = $_GET['limit'] : $limit = G_DEFAULT_TABLE_SIZE;

                if (isset($_GET['sort']) && eF_checkParameter($_GET['sort'], 'text')) {
                    $sort = $_GET['sort'];
                    isset($_GET['order']) && $_GET['order'] == 'desc' ? $order = 'desc' : $order = 'asc';
                } else {
                    $sort = 'login';
                }
                $users = eF_multiSort($users, $sort, $order);
                $smarty -> assign("T_USERS_SIZE", sizeof($users));
                if (isset($_GET['filter'])) {
                    $users = eF_filterData($users, $_GET['filter']);
                }
                if (isset($_GET['limit']) && eF_checkParameter($_GET['limit'], 'int')) {
                    isset($_GET['offset']) && eF_checkParameter($_GET['offset'], 'int') ? $offset = $_GET['offset'] : $offset = 0;
                    $users = array_slice($users, $offset, $limit);
                }
                foreach ($users as $key => $value) {
                    $users[$key]['issued_certificate'] = $value['issued_certificate'];
                }
                $smarty -> assign("T_USERS_PROGRESS", $users);
                $smarty -> display('includes/course_settings.tpl');
                exit;
            }

            if (isset($_GET['export']) && $_GET['export'] == 'rtf') {
                $result = eF_getTableData("users_to_courses", "*", "users_LOGIN = '".$_GET['user']."' and courses_ID = '".$_GET['course']."' limit 1");
                if (sizeof($result) == 1 || isset($_GET['preview'])) {
                    $course = new EfrontCourse($_GET['course']);
                    if (!isset($_GET['preview'])){
                        $certificate_tpl_id = $course -> course['certificate_tpl_id'];
                        if ($certificate_tpl_id <= 0) {
                            $cfile = new EfrontFile(G_CERTIFICATETEMPLATEPATH."certificate1.rtf");
                        } else {
                            $cfile = new EfrontFile($certificate_tpl_id);
                        }
                        $template_data = file_get_contents($cfile['path']);
                        $issued_data   = unserialize($result[0]['issued_certificate']);
                        if (sizeof($issued_data) > 1){
                            $certificate   = $template_data;
                            $certificate   = str_replace("#organization#", utf8ToUnicode($issued_data['organization']), $certificate);
                            $certificate   = str_replace("#user_name#", utf8ToUnicode($issued_data['user_name']), $certificate);
                            $certificate   = str_replace("#user_surname#", utf8ToUnicode($issued_data['user_surname']), $certificate);
                            $certificate   = str_replace("#course_name#", utf8ToUnicode($issued_data['course_name']), $certificate);
                            $certificate   = str_replace("#grade#", utf8ToUnicode($issued_data['grade']), $certificate);
                            $certificate   = str_replace("#date#", utf8ToUnicode($issued_data['date']), $certificate);
                        }                       
                        $filename = "certificate_".$_GET['user'].".rtf"; 
                    } else {
                        $certificateDirectory = G_CERTIFICATETEMPLATEPATH;
                        $selectedCertificate  = $_GET['certificate_tpl'];
                        $certificate          = file_get_contents($certificateDirectory.$selectedCertificate);
                        $filename = $_GET['certificate_tpl'];
                    }   
                                        
                    header("Content-type: application/rtf");
                    header('Content-disposition: attachment; filename = "'.$filename.'"');
                    header("Content-length: " . mb_strlen($certificate));
                    echo $certificate;
                    exit;
                }
            }
        } else if ($_GET['op'] == 'format_certificate') {

            if ($currentCourse -> course['certificate_tpl_id'] > 0){
                $certificateFile = new EfrontFile($currentCourse -> course['certificate_tpl_id']);
                $dname = $certificateFile -> offsetGet('name');
            }

            try {
                $certificateFileSystemTree = new FileSystemTree(G_CERTIFICATETEMPLATEPATH);
                foreach (new EfrontFileTypeFilterIterator(new EfrontFileOnlyFilterIterator(new EfrontNodeFilterIterator(new RecursiveIteratorIterator($certificateFileSystemTree -> tree, RecursiveIteratorIterator :: SELF_FIRST))), array('rtf')) as $key => $value) {
                    $existingCertificates[basename($key)] = basename($key);
                }
            } catch (Exception $e) {
                $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                $message = $e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
            }


            $form = new HTML_QuickForm("edit_course_certificate_form", "post", basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=format_certificate', "", null, true);
            $form -> registerRule('checkParameter', 'callback', 'eF_checkParameter');                   //Register this rule for checking user input with our function, eF_checkParameter
            $form -> addElement('file', 'file_upload', _CERTIFICATETEMPLATE, 'class = "inputText"');
            $form -> addElement('select', 'existing_certificate', _ORSELECTONEFROMLIST, $existingCertificates, "id = 'select_certificate'");
            $form -> addElement('button', 'preview', _PREVIEW, 'onclick = "location = (\''.basename($_SERVER['PHP_SELF']).'?ctg=courses&course='.$currentCourse -> course['id'].'&op=course_certificates&export=rtf&preview=1&certificate_tpl=\'+document.forms[0].existing_certificate.value)"
            title = "'._VIEWCERTIFICATE.'" class = "flatButton"');
            $form -> addElement('submit', 'submit_certificate', _SAVE, 'class = "flatButton"');
            $form -> setDefaults(array('existing_certificate' => $dname));
            $form -> setMaxFileSize(FileSystemTree :: getUploadMaxSize() * 1024);

            if ($form -> isSubmitted() && $form -> validate()) {
                $certificateDirectory = G_CERTIFICATETEMPLATEPATH;
                if (!is_dir($certificateDirectory)) {
                    mkdir($certificateDirectory);
                }
                $logoid = 0;
                try {
                    if ($_FILES['file_upload']['size'] > 0) {
                        $filesystem   = new FileSystemTree($certificateDirectory);
                        $uploadedFile = $filesystem -> uploadFile('file_upload', $certificateDirectory);
                        $certificateid = $uploadedFile['id'];
                    } else {
                        $selectedCertificate = $form -> exportValue('existing_certificate');
                        $certificateFile = new EfrontFile(G_CERTIFICATETEMPLATEPATH.$selectedCertificate);
                        if ($certificateFile['id'] < 0) { //if the file doesn't exist, then import it 
                            $selectedCertificate = $certificateFileSystemTree -> seekNode(G_CERTIFICATETEMPLATEPATH.$selectedCertificate);    
                            $newList             = FileSystemTree :: importFiles($selectedCertificate['path']);
                            $certificateid       = key($newList);
                        }
                        else {
                            $certificateid = $certificateFile['id'];
                        }
                    }
                    $currentCourse -> course['certificate_tpl_id'] = $certificateid;
                    $currentCourse -> persist();
                    header("location:".basename($_SERVER['PHP_SELF'])."?".$baseUrl."&op=course_certificates&message=".urlencode(_SUCCESFULLYUPDATEDCERTIFICATE)."&message_type=success");
                } catch (Exception $e) {
                    $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                    $message      = _SOMEPROBLEMEMERGED.': '.$e -> getMessage().' &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
                    $message_type = 'failure';
                }
            }

            $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);

            $form -> setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
            $form -> setRequiredNote(_REQUIREDNOTE);
            $form -> accept($renderer);
            $smarty -> assign('T_CERTIFICATE_FORM', $renderer -> toArray());
        } else if ($_GET['op'] == 'course_rules') {
            $courseLessons = $currentCourse -> getLessons();

            $rules_form = new HTML_QuickForm("course_rules_form", "post", basename($_SERVER['PHP_SELF'])."?".$baseUrl."&op=course_rules", "", null, true);
            $rules_form -> addElement('submit', 'submit_rule', _SUBMIT, 'class = "flatButton"');
            if ($rules_form -> isSubmitted() && $rules_form -> validate()) {
                foreach ($_POST['rules'] as $rule_lesson) {
                    if (sizeof(array_unique($rule_lesson['lesson'])) != sizeof($rule_lesson['lesson'])) {
                        $duplicate = true;
                    }
                }
                if (!isset($duplicate)) {
                    try {
                        $currentCourse -> rules = $_POST['rules'];
                        $currentCourse -> persist();
                        header("location:".basename($_SERVER['PHP_SELF'])."?".$baseUrl."&op=course_rules&message=".urlencode(_SUCCESFULLYSETORDER)."&message_type=success");
                    } catch (Exception $e) {
                        $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                        $message      = _PROBLEMSETTINGORDER.': '.$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
                        $message_type = 'failure';
                    }
                } else {
                    $message      = _DUPLICATESARENOTALLOWED;
                    $message_type = 'failure';
                }
            }
            $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);

            $rules_form -> accept($renderer);
            $smarty -> assign('T_COURSE_RULES_FORM', $renderer -> toArray());
            $smarty -> assign("T_COURSE_RULES", $currentCourse -> rules);
            $smarty -> assign('T_COURSE_LESSONS', $courseLessons);

            $smarty -> assign('T_COURSE', $currentCourse -> course);
            $smarty -> assign('T_COURSE_LESSONS', $courseLessons);
        } else if ($_GET['op'] == 'course_order') {
            $loadScripts[] = 'drag-drop-folder-tree';
            $courseLessons = $currentCourse -> getLessons();

            $smarty -> assign('T_COURSE', $currentCourse -> course);
            $smarty -> assign('T_COURSE_LESSONS', $courseLessons);

            if (isset($_GET['ajax']) && isset($_GET['order'])) {
                $order    = explode(",", $_GET['order']);
                $previous = 0;
                foreach ($order as $value) {
                    $result = explode("-", $value);
                    if (in_array($value, array_keys($courseLessons))) {
                        eF_updateTableData("lessons_to_courses", array("previous_lessons_ID" => $previous), "courses_ID=".$currentCourse -> course['id']." and lessons_ID=".$result[0]);
                    }
                    $previous = $result[0];
                }
                echo _TREESAVEDSUCCESSFULLY;
                exit;
            }
        } else if ($_GET['op'] == 'course_scheduling') {
            $courseLessons = $currentCourse -> getLessons();
            if (isset($_GET['set_schedule']) && in_array($_GET['set_schedule'], array_keys($courseLessons))) {
                try {
                    $lesson        = new EfrontLesson($_GET['set_schedule']);
                    $fromTimestamp = mktime($_GET['from_Hour'], $_GET['from_Minute'], 0, $_GET['from_Month'], $_GET['from_Day'], $_GET['from_Year']);
                    $toTimestamp   = mktime($_GET['to_Hour'],   $_GET['to_Minute'],   0, $_GET['to_Month'],   $_GET['to_Day'],   $_GET['to_Year']);
                    if ($fromTimestamp < $toTimestamp) {
                        $lesson -> lesson['from_timestamp'] = $fromTimestamp;
                        $lesson -> lesson['to_timestamp']   = $toTimestamp;
//                        $lesson -> lesson['shift']          = $form -> exportValue('shift') ? 1 : 0;

                        $lesson -> persist();
                        echo _FROM.' '.formatTimestamp($fromTimestamp, 'time_nosec').' '._TO.' '.formatTimestamp($toTimestamp, 'time_nosec').'&nbsp;';
                    } else {
                        header("HTTP/1.0 500");
                        echo _ENDDATEMUSTBEBEFORESTARTDATE;
                    }
                } catch (Exception $e) {
                    header("HTTP/1.0 500");
                    echo $e -> getMessage().' ('.$e -> getCode().')';
                }

                exit;
            } else if (isset($_GET['delete_schedule']) && in_array($_GET['delete_schedule'], array_keys($courseLessons))) {
                try {
                    $lesson = new EfrontLesson($_GET['delete_schedule']);
                    $lesson -> lesson['from_timestamp'] = '';
                    $lesson -> lesson['to_timestamp']   = '';
                    $lesson -> lesson['shift']          = 0;

                    $lesson -> persist();
                } catch (Exception $e) {
                    header("HTTP/1.0 500 ");
                    echo $e -> getMessage().' ('.$e -> getCode().')';
                }
                exit;
            }

            $smarty -> assign("T_COURSE_LESSONS", $courseLessons);
            //pr($courseLessons);
        } else if ($_GET['op'] == 'export_course') {
            if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
                header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
            }

            /* Export part */
            $form = new HTML_QuickForm("export_course_form", "post", basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=export_course', "", null, true);
            $form -> addElement('submit', 'submit_export_course', _EXPORT, 'class = "flatButton"');

            try {
                $currentExportedFile = new EfrontFile($currentUser -> user['directory'].'/temp/'.EfrontFile :: encode($currentCourse -> course['name']).'.zip');
                $smarty -> assign("T_EXPORTED_FILE", $currentExportedFile);
            } catch (Exception $e) {}

            if ($form -> isSubmitted() && $form -> validate()) {
                try {                   
                    $file   = $currentCourse -> export();
                    $smarty -> assign("T_NEW_EXPORTED_FILE", $file);

                    $message      = _COURSEEXPORTEDSUCCESFULLY;
                    $message_type = 'success';
                } catch (Exception $e) {
                    $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                    $message = $e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
                }
            }

            $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
            $form -> accept($renderer);
            $smarty -> assign('T_EXPORT_COURSE_FORM', $renderer -> toArray());
        } else if ($_GET['op'] == 'import_course') {
            if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
                header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
            }
            
            /* Import part */
            $form = new HTML_QuickForm("import_course_form", "post", basename($_SERVER['PHP_SELF']).'?'.$baseUrl.'&op=import_course', "", null, true);
            $form -> addElement('file', 'file_upload', null, 'class = "inputText"');                    //Lesson file
            $form -> setMaxFileSize(FileSystemTree :: getUploadMaxSize() * 1024);            //getUploadMaxSize returns size in KB
            $form -> addElement('submit', 'submit_import_course', _SUBMIT, 'class = "flatButton"');

            $smarty -> assign("T_MAX_FILESIZE", FileSystemTree :: getUploadMaxSize());

            if ($form -> isSubmitted() && $form -> validate()) {
                try {
                    $userTempDir   = $GLOBALS['currentUser'] -> user['directory'].'/temp';
                    if (!is_dir($userTempDir)) {                                                                    //If the user's temp directory does not exist, create it
                        $userTempDir = EfrontDirectory :: createDirectory($userTempDir, false);            
                    } else {
                    	$userTempDir = new EfrontDirectory($userTempDir);
                    }
                    
                    $filesystem     = new FileSystemTree($userTempDir);
                    $uploadedFile   = $filesystem -> uploadFile('file_upload', $userTempDir);
                    $currentCourse -> import($uploadedFile);

                    $message      = _COURSEIMPORTEDSUCCESFULLY;
                    $message_type = 'success';
                } catch (Exception $e) {
                	pr($e);
                    $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                    $message      = _PROBLEMIMPORTINGFILE.': '.$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
                    $message_type = 'failure';
                }
            }

            $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
            $form -> accept($renderer);
            $smarty -> assign('T_IMPORT_COURSE_FORM', $renderer -> toArray());
        }
        
?>