public function unitExport(EfrontUnit $unit)
 {
     $currentLesson = $this->getCurrentLesson();
     $unitExportFolder = $this->moduleBaseDir . "assets/";
     try {
         $dir = new EfrontDirectory($unitExportFolder);
         $dir->delete();
     } catch (Exception $e) {
     }
     $htmlExportFolder = $unitExportFolder . 'html/';
     $filesExportFolder = $unitExportFolder . 'html/files/';
     is_dir($filesExportFolder) or mkdir($filesExportFolder, 0755, true);
     //is_dir($htmlExportFolder)  OR mkdir($htmlExportFolder, 0755, true);
     $filelist = array();
     $unitFiles = $unit->getFiles(true);
     $units[] = $unit;
     $data = $unit['data'];
     foreach ($unitFiles as $file) {
         $filePath = str_replace($currentLesson->getDirectory(), "/", EfrontFile::encode($file['path']));
         //Added this line in case of a space in path(urlencode makes it + and rawurlencode convers also slashes ) (#2143)
         $data = str_replace("content/lessons/" . ($currentLesson->lesson['share_folder'] ? $currentLesson->lesson['share_folder'] : $currentLesson->lesson['id']) . str_replace(' ', '%20', $filePath), "files" . str_replace(' ', '%20', $filePath), $data);
         $data = str_replace("content/lessons/" . ($currentLesson->lesson['share_folder'] ? $currentLesson->lesson['share_folder'] : $currentLesson->lesson['id']) . $filePath, "files" . $filePath, $data);
         $data = str_replace("view_file.php?file=" . $file['id'], "files" . $filePath, $data);
     }
     $unitContent = $data;
     $unitFilename = $htmlExportFolder . $unit['name'] . ".html";
     file_put_contents(EfrontFile::encode($unitFilename), $unitContent);
     $filelist = array_merge($filelist, $unitFiles);
     foreach ($filelist as $file) {
         $filePath = str_replace($currentLesson->getDirectory(), "", $file['path']);
         if (!is_dir($filesExportFolder . dirname($filePath))) {
             mkdir($filesExportFolder . dirname($filePath), 0755, true);
         }
         $file->copy($filesExportFolder . $filePath);
     }
     $unitDirectory = new EfrontDirectory($unitExportFolder);
     if (eF_checkParameter($unit['name'], 'file')) {
         $filename = $unit['name'] . '.zip';
     } else {
         $filename = 'unit.zip';
     }
     $compressedFile = $unitDirectory->compress($filename, false);
     //$unitDirectory -> delete();
     return $compressedFile;
 }
 /**
  * Create The MS Word Document from given HTML
  *
  * @param String $html :: HTML Content or HTML File Name like path/to/html/file.html
  * @param String $file :: Document File Name
  * @param Boolean $download :: Wheather to download the file or save the file
  * @return boolean 
  */
 function createDoc($html, $file, $download = false)
 {
     if (is_file($html)) {
         $html = @file_get_contents($html);
     }
     $this->_parseHtml($html);
     $this->setDocFileName($file);
     $doc = $this->getHeader();
     $doc .= $this->htmlBody;
     $doc .= $this->getFotter();
     if ($download) {
         if (!empty($this->localimgs)) {
             if (file_exists($this->lessonDirectory . $file)) {
                 $tmpDir = new EfrontDirectory($this->lessonDirectory . $file);
             } else {
                 $tmpDir = EfrontDirectory::createDirectory($this->lessonDirectory . $file);
             }
             $array_cp = $tmpDir->getArrayCopy();
             foreach ($this->localimgs as $img) {
                 $file = new EfrontFile($img['path'] . $img['src']);
                 $file->copy($array_cp['path'] . "/" . $img['src']);
             }
             $this->write_file($array_cp['path'] . "/" . $this->docFile, $doc);
             $zipfile = $tmpDir->compress();
             $tmpDir->delete();
             $zipfile->sendFile();
             exit;
         } else {
             @header("Cache-Control: ");
             // leave blank to avoid IE errors
             @header("Pragma: ");
             // leave blank to avoid IE errors
             @header("Content-type: application/octet-stream");
             @header("Content-Disposition: attachment; filename=\"{$this->docFile}\"");
             echo $doc;
         }
         return true;
     } else {
         return $this->write_file($this->docFile, $doc);
     }
 }
    }
    $lesson = new EfrontLesson($_GET['export_chat']);
    file_put_contents(G_UPLOADPATH . $_SESSION['s_login'] . '/chat_' . $lesson->lesson['name'] . '.txt', $data);
    $dataFile = new EfrontFile(G_UPLOADPATH . $_SESSION['s_login'] . '/chat_' . $lesson->lesson['name'] . '.txt');
    $file = $dataFile->compress();
    echo json_encode(array('file' => $file['path']));
    exit;
} elseif (isset($_GET['export_chat']) && eF_checkParameter($_GET['export_chat'], 'login')) {
    //$sql = "select * from module_chat where (module_chat.to_user = '******'export_chat']."' and module_chat.from_user ='******') or (module_chat.from_user = '******'export_chat']."' and module_chat.to_user ='******')  order by id ASC";
    $messages = eF_getTableData("module_chat", "*", "(module_chat.to_user = '******'export_chat'] . "' and module_chat.from_user ='******') or (module_chat.from_user = '******'export_chat'] . "' and module_chat.to_user ='******')", "id ASC");
    $data = "";
    foreach ($messages as $message) {
        $data .= $message['from_user'] . "\t" . $message['message'] . "\t" . $message['sent'] . "\r\n";
    }
    file_put_contents(G_UPLOADPATH . $_SESSION['s_login'] . '/chat_' . $_GET['export_chat'] . '.txt', $data);
    $dataFile = new EfrontFile(G_UPLOADPATH . $_SESSION['s_login'] . '/chat_' . $_GET['export_chat'] . '.txt');
    $file = $dataFile->compress();
    echo json_encode(array('file' => $file['path']));
    exit;
}
if ($_SESSION['s_lessons_ID']) {
    if (!isset($_SESSION["lessonid"]) || $_SESSION["lessonid"] != $_SESSION['s_lessons_ID']) {
        $lsn = eF_getTableData("lessons", "name", "id='" . $_SESSION['s_lessons_ID'] . "'");
        foreach ($lsn as $lesson) {
            $link = $lesson['name'];
            //$room = str_replace(' ','_',$lesson['name']);
            //$room = str_replace('"','',$room);
            //$room = str_replace('\'','',$room);
            $_SESSION["lessonid"] = $_SESSION['s_lessons_ID'];
            $_SESSION["lessonname"] = str_replace(' ', '_', $lesson['name']);
            $_SESSION["room_" . $_SESSION["lessonid"]] = $_SESSION["lessonname"];
                 if ($course->options['custom2'] != '') {
                     $course->options['custom2'] = replaceCustomFieldsCertificate($course->options['custom2'], $issued_data['date']);
                     $xmlExport->showCustomTwo($pdf, $course->options['custom2']);
                 }
                 if ($course->options['custom3'] != '') {
                     $course->options['custom3'] = replaceCustomFieldsCertificate($course->options['custom3'], $issued_data['date']);
                     $xmlExport->showCustomThree($pdf, $course->options['custom3']);
                 }
                 //				$fileNamePdf = "certificate_preview.pdf";
                 //				$pdf->Output($fileNamePdf, 'D');
                 $fileNamePdf = "certificate_preview.pdf";
             }
             $output = $pdf->Output('', 'S');
             $pathname = $currentUser->getDirectory() . str_replace(array('/', ':', '\\', '?', '&'), '_', $fileNamePdf);
             file_put_contents($pathname, $output);
             $file = new EfrontFile($pathname, $output);
             $file->sendFile();
         }
     }
 } else {
     if ($_GET['op'] == 'format_certificate') {
         if ($currentCourse->options['certificate_export_method'] == 'rtf' && !isset($_GET['switch'])) {
             eF_redirect(basename($_SERVER['PHP_SELF']) . "?" . $baseUrl . "&op=format_certificate_docx");
         }
         if (G_VERSIONTYPE != 'community') {
             #cpp#ifndef COMMUNITY
             if ($currentCourse->options['certificate_tpl_id'] > 0) {
                 $currentTemplate = eF_getTableData("certificate_templates", "certificate_type", "id=" . $currentCourse->options['certificate_tpl_id']);
                 $currentTemplateType = $currentTemplate[0]['certificate_type'];
                 $currentTemplate = $currentCourse->options['certificate_tpl_id'] . '-' . $currentTemplateType;
                 $smarty->assign('T_CURRENT_TEMPLATE_TYPE', $currentTemplateType);
 /**
  * Delete a personal message
  *
  * This function is used to delete a message, including any attachments it may have
  *
  * @param int $msg_id The message id
  * @return bool True if the deletion was succesful
  * @version 0.1
  * @deprecated
  */
 public static function eF_deletePersonalMessage($msg_id)
 {
     if (eF_checkParameter($msg_id, 'id')) {
         $res = eF_getTableData("f_personal_messages", "users_LOGIN, attachments, f_folders_ID", "id=" . $msg_id);
         if ($_SESSION['s_login'] == $res[0]['users_LOGIN'] || $_SESSION['s_type'] == 'administrator') {
             eF_deleteTableData("f_personal_messages", "id=" . $msg_id);
             if ($res[0]['attachments'] != '') {
                 $attached_file = new EfrontFile($res[0]['attachments']);
                 $attached_file->delete();
             }
             return true;
         } else {
             $message = 'You cannot delete this message';
             return $message;
         }
     } else {
         $message = _INVALIDID;
         return $message;
     }
 }
    private function buildSCORMManifestResources($units)
    {
        $resource_str = '';
        $dependency_str = '';
        for ($i = 0; $i < sizeof($units); $i++) {
            $resource_str .= '
			<resource identifier="' . $units[$i]['id'] . '" type="webcontent" adlcp:scormtype="sco" href="html/' . rawurlencode(EfrontFile::encode(str_replace('?', ' ', $units[$i]['name']))) . '.html">
				<metadata></metadata>
				<file href="html/' . rawurlencode(EfrontFile::encode(str_replace('?', ' ', $units[$i]['name']))) . '.html"/>
				<dependency identifierref="dep_SPECIAL"/>';
            $unitFiles = $units[$i]->getFiles(true);
            for ($j = 0; $j < sizeof($unitFiles); $j++) {
                $file = str_replace($this->getDirectory(), "", $unitFiles[$j]['path']);
                $resource_str .= '
				<dependency identifierref="dep_' . $i . '_' . $j . '"/>';
                $dependency_str .= '
					<resource identifier="dep_' . $i . '_' . $j . '" type="webcontent" adlcp:scormtype="asset" href="' . rawurlencode(EfrontFile::encode(str_replace('?', ' ', $file))) . '">
						<metadata></metadata>
						<file href="' . rawurlencode(EfrontFile::encode(str_replace('?', ' ', $file))) . '"/>
					</resource>';
            }
            $resource_str .= '
			</resource>';
        }
        $SPECIAL_str = '
			<resource identifier="dep_SPECIAL" adlcp:scormtype="asset" type="webcontent">
				<file href="SCOFunctions.js"/>
				<file href="APIWrapper.js"/>
			</resource>';
        $final_str = '
		<resources>' . $resource_str . $dependency_str . $SPECIAL_str . '
		</resources>';
        return $final_str;
    }
 private function doCategoryReports()
 {
     $smarty = $this->getSmartyVar();
     $currentUser = $this->getCurrentUser();
     $directionsTree = new EfrontDirectionsTree();
     $directionPaths = $directionsTree->toPathString();
     $form = new HTML_QuickForm("category_form", "post", basename($_SERVER['PHP_SELF']) . "?ctg=module&op=module_administrator_tools&tab=category_reports&do=enterprise", "", null, true);
     $form->addElement('select', 'category', _CATEGORY, $directionPaths);
     $form->addElement('checkbox', 'incomplete', _MODULE_ADMINISTRATOR_TOOLS_SHOWINCOMPLETE);
     $form->addElement('checkbox', 'inactive', _MODULE_ADMINISTRATOR_TOOLS_SHOWINACTIVECOURSES);
     $form->addElement('date', 'from_timestamp', _MODULE_ADMINISTRATOR_TOOLS_COMPLETEDFROM, array('minYear' => 1970, 'maxYear' => date("Y")));
     $form->addElement('date', 'to_timestamp', _MODULE_ADMINISTRATOR_TOOLS_COMPLETEDTO, array('minYear' => 1970, 'maxYear' => date("Y")));
     $form->addElement("submit", "submit", _SUBMIT, 'class = "flatButton"');
     $form->setDefaults(array("from_timestamp" => mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")), "to_timestamp" => time()));
     if ($form->isSubmitted() && $form->validate()) {
         $values = $form->exportValues();
         $_SESSION['from_timestamp'] = mktime(0, 0, 0, $_POST['from_timestamp']['M'], $_POST['from_timestamp']['d'], $_POST['from_timestamp']['Y']);
         $_SESSION['to_timestamp'] = mktime(23, 59, 59, $_POST['to_timestamp']['M'], $_POST['to_timestamp']['d'], $_POST['to_timestamp']['Y']);
         $_SESSION['category'] = $values['category'];
         $_SESSION['incomplete'] = $values['incomplete'];
         $_SESSION['inactive'] = $values['inactive'];
         $smarty->assign("T_SHOW_TABLE", true);
     }
     if (isset($_GET['ajax']) && $_GET['ajax'] == 'categoryUsersTable' || $_GET['ajax'] == 'xls' || $_GET['ajax'] == 'show_xls') {
         $smarty->assign("T_SHOW_TABLE", true);
         $smarty->assign("T_DIRECTIONS_TREE", $directionPaths);
         $branchesTree = new EfrontBranchesTree();
         $branchesPaths = $branchesTree->toPathString();
         $category = new EfrontDirection($_SESSION['category']);
         $directionsTree = new EfrontDirectionsTree();
         $children = $directionsTree->getNodeChildren($_SESSION['category']);
         foreach (new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($children)), array('id')) as $value) {
             $siblings[] = $value;
         }
         $result = eF_getTableDataFlat("courses", "id", "archive = 0 && directions_ID in (" . implode(",", $siblings) . ")");
         $categoryCourses = $result['id'];
         $resultCourses = eF_getTableDataFlat("users_to_courses uc, courses c", "distinct c.id", 'c.id=uc.courses_ID ' . (!$_SESSION['inactive'] ? 'and c.active=1' : '') . ' and uc.archive=0 and uc.completed=1 and uc.to_timestamp >= ' . $_SESSION['from_timestamp'] . ' and uc.to_timestamp <= ' . $_SESSION['to_timestamp']);
         $resultEvents = eF_getTableDataFlat("events e, courses c", "distinct c.id", 'c.id=e.lessons_ID ' . (!$_SESSION['inactive'] ? 'and c.active=1' : '') . ' and e.type=54 and e.timestamp >= ' . $_SESSION['from_timestamp'] . ' and e.timestamp <= ' . $_SESSION['to_timestamp']);
         if (empty($resultEvents)) {
             $resultEvents['id'] = array();
         }
         $result = array_unique(array_merge($resultCourses['id'], $resultEvents['id']));
         $categoryCourses = array_intersect(array_unique($categoryCourses), $result);
         //count only courses that have users completed them
         if ($_SESSION['incomplete']) {
             $constraints = array('archive' => false, 'condition' => '(to_timestamp is null OR to_timestamp = 0 OR (to_timestamp >= ' . $_SESSION['from_timestamp'] . ' and to_timestamp <= ' . $_SESSION['to_timestamp'] . '))');
         } else {
             $constraints = array('archive' => false, 'condition' => 'completed=1 and to_timestamp >= ' . $_SESSION['from_timestamp'] . ' and to_timestamp <= ' . $_SESSION['to_timestamp']);
         }
         foreach ($categoryCourses as $courseId) {
             $course = new EfrontCourse($courseId);
             foreach ($course->getCourseUsers($constraints) as $value) {
                 $userBranches = $value->aspects['hcd']->getBranches();
                 $userSupervisors = $value->aspects['hcd']->getSupervisors();
                 $userSupervisor = end($userSupervisors);
                 $value->user['course_active'] = $course->course['active'];
                 $value->user['course_id'] = $course->course['id'];
                 $value->user['category'] = $directionPaths[$course->course['directions_ID']];
                 $value->user['course'] = $course->course['name'];
                 $value->user['directions_ID'] = $course->course['directions_ID'];
                 $value->user['branch'] = $branchesPaths[current($userBranches['employee'])];
                 $value->user['branch_ID'] = current($userBranches['employee']);
                 $value->user['supervisor'] = $userSupervisor;
                 $value->user['historic'] = false;
                 $unique = md5($value->user['to_timestamp'] . $value->user['course_id'] . $value->user['login']);
                 $courseUsers[$unique] = $value->user;
             }
             $result = eF_getTableData("events", "*", 'type=54 and lessons_ID=' . $courseId . ' and timestamp >= ' . $_SESSION['from_timestamp'] . ' and timestamp <= ' . $_SESSION['to_timestamp']);
             //exit;
             foreach ($result as $entry) {
                 try {
                     $value = EfrontUserFactory::factory($entry['users_LOGIN']);
                     if (!$value->user['archive']) {
                         $userBranches = $value->aspects['hcd']->getBranches();
                         $userSupervisors = $value->aspects['hcd']->getSupervisors();
                         //pr($entry['users_LOGIN']);pr($userSupervisors);pr(current($userSupervisors));
                         $userSupervisor = current($userSupervisors);
                         $value->user['course_active'] = $course->course['active'];
                         $value->user['course_id'] = $course->course['id'];
                         $value->user['category'] = $directionPaths[$course->course['directions_ID']];
                         $value->user['course'] = $course->course['name'];
                         $value->user['directions_ID'] = $course->course['directions_ID'];
                         $value->user['branch'] = $branchesPaths[current($userBranches['employee'])];
                         $value->user['branch_ID'] = current($userBranches['employee']);
                         $value->user['supervisor'] = $userSupervisor;
                         $value->user['to_timestamp'] = $entry['timestamp'];
                         $value->user['completed'] = 1;
                         $value->user['score'] = '';
                         $value->user['historic'] = true;
                         $unique = md5($value->user['to_timestamp'] . $value->user['course_id'] . $value->user['login']);
                         if (!isset($courseUsers[$unique])) {
                             $courseUsers[$unique] = $value->user;
                         }
                     }
                 } catch (Exception $e) {
                     /*Bypass non-existing users*/
                 }
             }
         }
         if ($_GET['ajax'] == 'xls') {
             $xlsFilePath = $currentUser->getDirectory() . 'category_report.xls';
             unlink($xlsFilePath);
             $_GET['limit'] = sizeof($courseUsers);
             $_GET['sort'] = 'category';
             list($tableSize, $courseUsers) = filterSortPage($courseUsers);
             $header = array('category' => _CATEGORY, 'course' => _NAME, 'login' => _USER, 'to_timestamp' => _COMPLETED, 'score' => _SCORE, 'supervisor' => _SUPERVISOR, 'branch' => _BRANCH, 'historic' => _MODULE_ADMINISTRATOR_TOOLS_HISTORICENTRY);
             foreach ($courseUsers as $value) {
                 $rows[] = array(_CATEGORY => str_replace("&nbsp;&rarr;&nbsp;", " -> ", $value['category']), _COURSE => $value['course'], _USER => formatLogin($value['login']), _COMPLETED => formatTimestamp($value['to_timestamp']), _SCORE => $value['historic'] ? '' : formatScore($value['score']) . '%', _SUPERVISOR => formatLogin($value['supervisor']), _BRANCH => str_replace("&nbsp;&rarr;&nbsp;", " -> ", $value['branch']), _MODULE_ADMINISTRATOR_TOOLS_HISTORICENTRY => $value['historic'] ? _YES : _NO);
             }
             EfrontSystem::exportToXls($rows, $xlsFilePath);
             exit;
         } else {
             if ($_GET['ajax'] == 'show_xls') {
                 $xlsFilePath = $currentUser->getDirectory() . 'category_report.xls';
                 $file = new EfrontFile($xlsFilePath);
                 $file->sendFile(true);
                 exit;
             } else {
                 list($tableSize, $courseUsers) = filterSortPage($courseUsers);
                 $smarty->assign("T_SORTED_TABLE", $_GET['ajax']);
                 $smarty->assign("T_TABLE_SIZE", $tableSize);
                 $smarty->assign("T_DATA_SOURCE", $courseUsers);
             }
         }
     }
     $smarty->assign("T_CATEGORY_FORM", $form->toArray());
 }
 /**
  * Copy simple unit
  *
  * This function copies a unit (NOT its children) into the current content tree
  * <br/>Example:
  * <code>
  * $currentContent = new EfrontContentTree(5);           //Initialize content for lesson with id 5
  * $sourceUnit = new EfrontUnit(20);                     //Get the unit with id = 20
  * $currentContent -> copySimpleUnit($sourceUnit, false);   //Copy the source unit into the content tree (at its end)
  * </code>
  *
  * @param EfrontUnit $sourceUnit The unit object to be copied
  * @param mixed $targetUnit The id of the parent unit (or the parent EfrontUnit)in which the new unit will be copied, or false (the unit will be appended at the end)
  * @param mixed $previousUnit The id of the previous unit (or the unit itself) of the new unit, or false (the unit will be put to the end of the units)
  * @param boolean $copyFiles whether to copy files as well.
  * @param boolean $copyQuestions Whether to copy questions as well
  * @return EfrontUnit The newly created unit object
  * @since 3.5.0
  * @access public
  */
 public function copySimpleUnit($sourceUnit, $targetUnit = false, $previousUnit = false, $copyFiles = true, $copyQuestions = true)
 {
     if (!$sourceUnit instanceof EfrontUnit) {
         $sourceUnit = new EfrontUnit($sourceUnit);
     }
     $newUnit['name'] = $sourceUnit->offsetGet('name');
     $newUnit['ctg_type'] = $sourceUnit->offsetGet('ctg_type');
     $newUnit['data'] = $sourceUnit->offsetGet('data');
     $options = $sourceUnit->offsetGet('options');
     $newOptions['complete_unit_setting'] = $options['complete_unit_setting'];
     $newOptions['hide_navigation'] = $options['hide_navigation'];
     $newOptions['maximize_viewport'] = $options['maximize_viewport'];
     $newOptions['object_ids'] = $options['object_ids'];
     $newUnit['options'] = serialize($newOptions);
     $newUnit['lessons_ID'] = $this->lessonId;
     if ($targetUnit) {
         if ($targetUnit instanceof EfrontUnit) {
             $newUnit['parent_content_ID'] = $targetUnit->offsetGet('id');
         } else {
             if (eF_checkParameter($targetUnit, 'id')) {
                 $newUnit['parent_content_ID'] = $targetUnit;
             }
         }
         if ($previousUnit instanceof EfrontUnit) {
             $newUnit['previous_content_ID'] = $previousUnit->offsetGet('id');
         } else {
             if (eF_checkParameter($previousUnit, 'id')) {
                 $newUnit['previous_content_ID'] = $previousUnit;
             }
         }
         $unit = $this->insertNode($newUnit);
     } else {
         $unit = $this->appendUnit($newUnit);
     }
     if ($copyFiles) {
         $files = $unit->getFiles();
         $lesson = new EfrontLesson($this->lessonId);
         $data = $unit->offsetGet('data');
         foreach ($files as $file) {
             try {
                 $sourceFile = new EfrontFile($file);
                 $sourceFileOffset = preg_replace("#" . G_LESSONSPATH . "#", "", $sourceFile['directory']);
                 $position = strpos($sourceFileOffset, "/");
                 //check case that the file is in a subfolder of the lesson
                 if ($position !== false) {
                     $sourceLink = mb_substr($sourceFileOffset, $position + 1);
                     mkdir($lesson->getDirectory() . $sourceLink . '/', 0755, true);
                     $destinationPath = $lesson->getDirectory() . $sourceLink . '/' . basename($sourceFile['path']);
                     $copiedFile = $sourceFile->copy($destinationPath, false);
                 } else {
                     $destinationPath = $lesson->getDirectory() . basename($sourceFile['path']);
                     $copiedFile = $sourceFile->copy($destinationPath, false);
                 }
                 //@todo view_file.php?action=download&file=10410
                 //$data = str_replace("view_file.php?file=".$file, "view_file.php?file=".$copiedFile -> offsetGet('id'), $data);
                 //$data = str_replace("&file=".$file, "&file=".$copiedFile -> offsetGet('id'), $data);
                 //$data = str_replace("&amp;file=".$file, "&amp;file=".$copiedFile -> offsetGet('id'), $data);
                 $data = preg_replace('#view_file\\.php(.*)file=' . $file . '#', 'view_file.php${1}file=' . $copiedFile->offsetGet('id'), $data);
                 $folderId = $lesson->lesson['share_folder'] ? $lesson->lesson['share_folder'] : $lesson->lesson['id'];
                 $data = preg_replace("#(" . G_SERVERNAME . ")*content/lessons/" . $sourceUnit['lessons_ID'] . "/(.*)#", "content/lessons/" . $folderId . '/${2}', $data);
             } catch (EfrontFileException $e) {
                 if ($e->getCode() == EfrontFileException::FILE_ALREADY_EXISTS) {
                     $copiedFile = new EfrontFile($destinationPath);
                     //$data = str_replace("view_file.php?file=".$file, "view_file.php?file=".$copiedFile -> offsetGet('id'), $data);
                     //$data = str_replace("&file=".$file, "&file=".$copiedFile -> offsetGet('id'), $data);
                     //$data = str_replace("&amp;file=".$file, "&amp;file=".$copiedFile -> offsetGet('id'), $data);
                     $data = preg_replace('#view_file\\.php(.*)file=' . $file . '#', 'view_file.php${1}file=' . $copiedFile->offsetGet('id'), $data);
                     $folderId = $lesson->lesson['share_folder'] ? $lesson->lesson['share_folder'] : $lesson->lesson['id'];
                     $data = preg_replace("#(" . G_SERVERNAME . ")*content/lessons/" . $sourceUnit['lessons_ID'] . "/(.*)#", "content/lessons/" . $folderId . '/${2}', $data, -1, $count);
                 }
             }
             //this means that the file already exists
         }
         $unit->offsetSet('data', $data);
         if ($file && $unit['ctg_type'] == 'scorm' || $unit['ctg_type'] == 'scorm_test') {
             $d = new EfrontDirectory(dirname($file));
             $d->copy($lesson->getDirectory() . basename(dirname($file)), true);
         }
     }
     $unit->persist();
     // copying questions that belong to this unit
     if ($copyQuestions) {
         $questions = eF_getTableData("questions", "*", "content_ID=" . $sourceUnit->offsetGet('id'));
         if ($copyFiles) {
             $folderId = $lesson->lesson['share_folder'] ? $lesson->lesson['share_folder'] : $lesson->lesson['id'];
         }
         for ($k = 0; $k < sizeof($questions); $k++) {
             if ($copyFiles) {
                 $questions[$k]['text'] = replaceQuestionPaths($questions[$k]['text'], $questions[$k]['lessons_ID'], $folderId);
                 $questions[$k]['explanation'] = replaceQuestionPaths($questions[$k]['explanation'], $questions[$k]['lessons_ID'], $folderId);
             }
             $questions[$k]['content_ID'] = $unit->offsetGet('id');
             $questions[$k]['lessons_ID'] = $unit->offsetGet('lessons_ID');
             unset($questions[$k]['id']);
             eF_insertTableData("questions", $questions[$k]);
         }
     }
     return $unit;
 }
Example #9
0
 /**
  * Handle AJAX actions
  *
  * This function is used to perform the necessary ajax actions,
  * that may be used in tests
  * <br/>Example:
  * <code>
  * $result     = eF_getTableData("completed_tests", "*", "id=".$_GET['show_solved_test']);
  * $showTest   = unserialize($result[0]['test']);
  * $status     = $showTest -> getStatus($result[0]['users_LOGIN']);
  * $testString = $showTest -> toHTMLQuickForm(new HTML_Quickform(), false, true, true);
  * $testString = $showTest -> toHTMLSolved($testString, true);
  * if (isset($_GET['ajax'])) {
  *     $showTest -> handleAjaxActions();
  * }
  * </code>
  *
  * @since 3.5.2
  * @access public
  */
 public function handleAjaxActions()
 {
     try {
         if (isset($_GET['test_score'])) {
             if (mb_strpos($_GET['test_score'], ",") !== false) {
                 $_GET['test_score'] = str_replace(",", ".", $_GET['test_score']);
             }
             if (is_numeric($_GET['test_score']) && $_GET['test_score'] <= 100 && $_GET['test_score'] >= 0) {
                 $this->completedTest['score'] = $_GET['test_score'];
                 foreach ($this->questions as $id => $question) {
                     if ($question->pending) {
                         $this->questions[$id]->pending = 0;
                         $this->questions[$id]->score = $this->completedTest['score'];
                     }
                 }
                 if ($this->test['mastery_score'] && $this->test['mastery_score'] > $this->completedTest['score']) {
                     $this->completedTest['status'] = 'failed';
                 } else {
                     if ($this->test['mastery_score'] && $this->test['mastery_score'] <= $this->completedTest['score']) {
                         $this->completedTest['status'] = 'passed';
                     }
                 }
                 $this->completedTest['pending'] = 0;
                 $this->save();
                 $result = eF_getTableData("completed_tests", "archive", "id=" . $this->completedTest['id']);
                 if (!$result[0]['archive']) {
                     $testUser = EfrontUserFactory::factory($this->completedTest['login']);
                     if ($this->completedTest['status'] == 'failed') {
                         $testUser->setSeenUnit($this->test['content_ID'], $this->test['lessons_ID'], 0);
                     } else {
                         $testUser->setSeenUnit($this->test['content_ID'], $this->test['lessons_ID'], 1);
                     }
                 }
                 echo $this->completedTest['status'];
             } else {
                 throw new EfrontTestException(_INVALIDSCORE . ': ' . $_GET['test_score'], EfrontTestException::INVALID_SCORE);
             }
             exit;
         } else {
             if (isset($_GET['test_feedback'])) {
                 $this->completedTest['feedback'] = $_GET['test_feedback'];
                 $this->save();
                 echo $_GET['test_feedback'];
                 exit;
             } else {
                 if (isset($_GET['redo_test']) && eF_checkParameter($_GET['redo_test'], 'id')) {
                     $result = eF_getTableData("completed_tests", "tests_ID, users_LOGIN", "id=" . $_GET['redo_test']);
                     $test = new EfrontTest($result[0]['tests_ID']);
                     $test->redo($result[0]['users_LOGIN']);
                     exit;
                 } else {
                     if (isset($_GET['redo_wrong_test']) && eF_checkParameter($_GET['redo_wrong_test'], 'id')) {
                         $result = eF_getTableData("completed_tests", "tests_ID, users_LOGIN", "id=" . $_GET['redo_wrong_test']);
                         $test = new EfrontTest($result[0]['tests_ID']);
                         $test->redoOnlyWrong($result[0]['users_LOGIN']);
                         exit;
                     } else {
                         if (isset($_GET['delete_done_test'])) {
                             if (isset($_GET['all'])) {
                                 $this->undo($this->completedTest['login']);
                                 //eF_deleteTableData("completed_tests", "users_LOGIN='******'login']."' and tests_ID=".$this -> completedTest['testsId']);
                             } else {
                                 $this->undo($this->completedTest['login'], $this->completedTest['id']);
                                 //eF_deleteTableData("completed_tests", "id=".$this -> completedTest['id']);
                             }
                             exit;
                         } else {
                             if (isset($_GET['question_score'])) {
                                 if (mb_strpos($_GET['question_score'], ",") !== false) {
                                     $_GET['question_score'] = str_replace(",", ".", $_GET['question_score']);
                                 }
                                 if (in_array($_GET['question'], array_keys($this->questions))) {
                                     if (is_numeric($_GET['question_score']) && $_GET['question_score'] <= 100 && $_GET['question_score'] >= 0) {
                                         $this->questions[$_GET['question']]->score = $_GET['question_score'];
                                         $this->questions[$_GET['question']]->scoreInTest = round($_GET['question_score'] * $this->getQuestionWeight($_GET['question']), 3);
                                         $this->questions[$_GET['question']]->pending = 0;
                                         $score = 0;
                                         foreach ($this->questions as $question) {
                                             $this->completedTest['scoreInTest'][$question->question['id']] = $question->scoreInTest;
                                             $score += $question->scoreInTest;
                                         }
                                         $this->completedTest['score'] = round($score, 2);
                                         $testUser = EfrontUserFactory::factory($this->completedTest['login']);
                                         if ($this->test['mastery_score'] && $this->test['mastery_score'] > $this->completedTest['score']) {
                                             if ($this->getPotentialScore() < $this->test['mastery_score']) {
                                                 $this->completedTest['status'] = 'failed';
                                                 $flag = 0;
                                                 //$testUser -> setSeenUnit($this -> test['content_ID'], $this -> test['lessons_ID'], 0);
                                             }
                                         } else {
                                             if ($this->test['mastery_score'] && $this->test['mastery_score'] <= $this->completedTest['score']) {
                                                 $this->completedTest['status'] = 'passed';
                                                 $flag = 1;
                                                 //$testUser -> setSeenUnit($this -> test['content_ID'], $this -> test['lessons_ID'], 1);
                                             }
                                         }
                                         $this->completedTest['pending'] = 0;
                                         foreach ($this->getQuestions(true) as $question) {
                                             if ($question->pending) {
                                                 $this->completedTest['pending'] = 1;
                                             }
                                         }
                                         try {
                                             $lesson = new EfrontLesson($this->test['lessons_ID']);
                                             $lesson_name = $lesson->lesson['name'];
                                         } catch (EfrontLessonException $e) {
                                             $lesson_name = _SKILLGAPTESTS;
                                         }
                                         if (!$this->completedTest['pending']) {
                                             EfrontEvent::triggerEvent(array("type" => EfrontEvent::TEST_MARKED, "users_LOGIN" => $this->completedTest['login'], "lessons_ID" => $this->test['lessons_ID'], "lessons_name" => $lesson_name, "entity_ID" => $this->test['id'], "entity_name" => $this->test['name']));
                                         }
                                         if ($this->completedTest['status'] == 'failed' && $this->completedTest['pending'] != 1) {
                                             EfrontEvent::triggerEvent(array("type" => EfrontEvent::TEST_FAILURE, "users_LOGIN" => $this->completedTest['login'], "lessons_ID" => $this->test['lessons_ID'], "lessons_name" => $lesson_name, "entity_ID" => $this->test['id'], "entity_name" => $this->test['name']));
                                         }
                                         $this->save();
                                         $testUser->setSeenUnit($this->test['content_ID'], $this->test['lessons_ID'], $flag);
                                         echo json_encode($this->completedTest);
                                     } else {
                                         throw new EfrontTestException(_INVALIDSCORE . ': ' . $_GET['test_score'], EfrontTestException::INVALID_SCORE);
                                     }
                                 } else {
                                     throw new EfrontTestException(_INVALIDID . ': ' . $_GET['question'], EfrontTestException::QUESTION_NOT_EXISTS);
                                 }
                                 exit;
                             } else {
                                 if (isset($_GET['question_feedback'])) {
                                     if (in_array($_GET['question'], array_keys($this->questions))) {
                                         $this->questions[$_GET['question']]->feedback = $_GET['question_feedback'];
                                         $this->save();
                                         echo $_GET['question_feedback'];
                                     } else {
                                         throw new EfrontTestException(_INVALIDID . ': ' . $_GET['question'], EfrontTestException::QUESTION_NOT_EXISTS);
                                     }
                                     exit;
                                 } else {
                                     if (isset($_GET['delete_file'])) {
                                         $file = new EfrontFile($_GET['delete_file']);
                                         $testDirectory = $this->getDirectory();
                                         if (strpos($file['path'], $testDirectory['path']) !== false) {
                                             $file->delete();
                                         }
                                         exit;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     } catch (Exception $e) {
         handleAjaxExceptions($e);
     }
 }
Example #10
0
                 if (!isset($GLOBALS['currentUser']->coreAccess['personal_messages']) || $GLOBALS['currentUser']->coreAccess['personal_messages'] != 'hidden') {
                     $search_results_pmsgs[] = array('message_subject' => EfrontSearch::highlightText($res1[0]['title'], $cr, 'resultsTitleBold'), 'message_id' => $res1[0]['id'], 'folder_name' => $res1[0]['name'], 'folder_id' => $res1[0]['folder_id'], 'body' => EfrontSearch::highlightText($res1[0]['body'], $cr, 'resultsTitleBold'), 'recipient' => $res1[0]['recipient'], 'sender' => $res1[0]['sender'], 'position' => $position_str);
                 }
             } elseif ($results[$i]['table_name'] == 'files') {
                 $pos1 = strpos($res1[0]['path'], '/content/lessons/');
                 //echo $pos1;
                 if ($pos1 !== false) {
                     $pos2 = strpos($res1[0]['path'], '/', $pos1 + mb_strlen('/content/lessons/'));
                     //echo $pos2;
                     $lessonID = mb_substr($res1[0]['path'], $pos1 + mb_strlen('/content/lessons/'), $pos2 - $pos1 - mb_strlen('/content/lessons/'));
                     //echo $lessonID;
                 } else {
                     $lessonID = 0;
                 }
                 try {
                     $file = new EfrontFile($res1[0]['id']);
                     $fileIcon = $file->getTypeImage();
                     if ($_SESSION['s_type'] == 'student' && in_array($lessonID, $lessons_have) && $res1[0]['shared'] != 0) {
                         $search_results_files[] = array('id' => $res1[0]['id'], 'path' => $res1[0]['path'], 'login' => $res1[0]['users_LOGIN'], 'date' => formatTimestamp($res1[0]['timestamp'], 'time_nosec'), 'name' => $file['name'], 'extension' => $file['extension'], 'icon' => $fileIcon);
                     } elseif ($_SESSION['s_type'] == 'professor' && in_array($lessonID, $lessons_have)) {
                         $search_results_files[] = array('id' => $res1[0]['id'], 'path' => $res1[0]['path'], 'login' => $res1[0]['users_LOGIN'], 'date' => formatTimestamp($res1[0]['timestamp'], 'time_nosec'), 'name' => $file['name'], 'extension' => $file['extension'], 'icon' => $fileIcon);
                     } elseif ($_SESSION['s_type'] == 'administrator') {
                         $search_results_files[] = array('id' => $res1[0]['id'], 'path' => $res1[0]['path'], 'login' => $res1[0]['users_LOGIN'], 'date' => formatTimestamp($res1[0]['timestamp'], 'time_nosec'), 'name' => $file['name'], 'extension' => $file['extension'], 'icon' => ${$fileIcon});
                     }
                 } catch (Exception $e) {
                     /*Do nothing, just skip the file*/
                 }
             }
         }
     }
 }
                 $lang_zip_file = $lang_zip_file_temp->uncompress(false);
                 $lang_file_rename = new EfrontFile($lang_zip_file[0]);
                 if ($values['custom']) {
                     $lang_file_rename->rename(dirname($uploadedFile['path']) . '/custom-' . $values['english_name'] . '.php.inc', true);
                 } else {
                     $lang_file_rename->rename(dirname($uploadedFile['path']) . '/lang-' . $values['english_name'] . '.php.inc', true);
                 }
             } else {
                 if ($values['custom']) {
                     $uploadedFile->rename(dirname($uploadedFile['path']) . '/custom-' . $values['english_name'] . '.php.inc', true);
                 } else {
                     $uploadedFile->rename(dirname($uploadedFile['path']) . '/lang-' . $values['english_name'] . '.php.inc', true);
                 }
             }
         } else {
             $file = new EfrontFile(G_ROOTPATH . 'libraries/language/lang-english.php.inc');
             $file->copy(G_ROOTPATH . 'libraries/language/lang-' . $values['english_name'] . '.php.inc');
         }
         $fields = array("name" => $values['english_name'], "translation" => $values['translation'], "active" => 1, "rtl" => $values['rtl']);
         if (!$values['custom']) {
             eF_insertTableData("languages", $fields);
         }
         EfrontCache::getInstance()->deleteCache('languages');
         //$RetValues = file(G_SERVERNAME."/editor/tiny_mce/langs/language.php?langname=".$values['english_name']);
         eF_redirect("" . basename($_SERVER['PHP_SELF']) . "?ctg=languages&message=" . urlencode(_SUCCESSFULLYADDEDLANGUAGE) . "&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(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>';
     $message_type = 'failure';
 }
Example #12
0
            $message_type = 'failure';
        }
    }
    $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
    $form->accept($renderer);
    $smarty->assign('T_IMPORT_LESSON_FORM', $renderer->toArray());
} elseif ($_GET['op'] == 'export_lesson') {
    if (isset($currentUser->coreAccess['content']) && $currentUser->coreAccess['content'] != 'change') {
        eF_redirect("" . basename($_SERVER['PHP_SELF']) . "?ctg=control_panel&message=" . urlencode(_UNAUTHORIZEDACCESS) . "&message_type=failure");
    }
    /* Export part */
    $form = new HTML_QuickForm("export_lesson_form", "post", basename($_SERVER['PHP_SELF']) . '?' . $baseUrl . '&op=export_lesson', "", null, true);
    $form->addElement('checkbox', 'export_files', _EXPORTFILES, null, 'class = "inputCheckBox"');
    $form->addElement('submit', 'submit_export_lesson', _EXPORT, 'class = "flatButton"');
    try {
        $currentExportedFile = new EfrontFile($currentUser->user['directory'] . '/temp/' . EfrontFile::encode($currentLesson->lesson['name']) . '.zip');
        $smarty->assign("T_EXPORTED_FILE", $currentExportedFile);
    } catch (Exception $e) {
    }
    if ($form->isSubmitted() && $form->validate()) {
        try {
            $file = $currentLesson->export(false, true, $form->exportValue('export_files'));
            $smarty->assign("T_NEW_EXPORTED_FILE", $file);
            $message = _LESSONEXPORTEDSUCCESFULLY;
            $message_type = 'success';
        } catch (Exception $e) {
            handleNormalFlowExceptions($e);
        }
    }
    $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
    $form->accept($renderer);
Example #13
0
 public function search($query_string)
 {
     $database = new XapianDatabase(self::$_database_path);
     // Start an enquire session.
     $enquire = new XapianEnquire($database);
     $qp = new XapianQueryParser();
     $stemmer = new XapianStem("english");
     $qp->set_stemmer($stemmer);
     $qp->set_database($database);
     $qp->set_stemming_strategy(XapianQueryParser::STEM_SOME);
     $query = $qp->parse_query($query_string);
     // Find the top 10 results for the query.
     $enquire->set_query($query);
     $enquire->set_collapse_key(0, 1);
     //index '0' holds the file path, so we're collapsing on that value in order for a single value to be returned by the system
     $matches = $enquire->get_mset(0, $database->get_doccount());
     $i = $matches->begin();
     $results = array();
     while (!$i->equals($matches->end())) {
         $n = $i->get_rank() + 1;
         try {
             $fileobj = new EfrontFile($i->get_document()->get_value('file'));
             $results[] = array('id' => $fileobj['id'], 'path' => str_replace(G_ROOTPATH, '', $fileobj['path']), 'login' => $fileobj['users_LOGIN'] ? $fileobj['users_LOGIN'] : '', 'date' => formatTimestamp(filemtime($fileobj['path']), 'time_nosec'), 'name' => $fileobj['name'], 'extension' => $fileobj['extension'], 'score' => $i->get_percent(), 'content' => $i->get_document()->get_data(), 'icon' => $fileobj->getTypeImage());
         } catch (Exception $e) {
             //don't halt for missing files
         }
         $i->next();
     }
     return $results;
 }
Example #14
0
function replaceQuestionPaths($data, $sourceId, $newId)
{
    //$data = $question['text'];
    preg_match_all("/view_file\\.php\\?file=(\\d+)/", $data, $matchesId);
    $filesId = $matchesId[1];
    preg_match_all("#(" . G_SERVERNAME . ")*content/lessons/(.*)\"#U", $data, $matchesPath);
    $filesPath = $matchesPath[2];
    foreach ($filesId as $file) {
        $files[] = $file;
    }
    foreach ($filesPath as $file) {
        $files[] = G_LESSONSPATH . html_entity_decode($file);
    }
    $lesson = new EfrontLesson($newId);
    //$data   = $unit -> offsetGet('data');
    foreach ($files as $file) {
        try {
            $sourceFile = new EfrontFile($file);
            $sourceFileOffset = preg_replace("#" . G_LESSONSPATH . "#", "", $sourceFile['directory']);
            $position = strpos($sourceFileOffset, "/");
            //check case that the file is in a subfolder of the lesson
            if ($position !== false) {
                $sourceLink = mb_substr($sourceFileOffset, $position + 1);
                mkdir($lesson->getDirectory() . $sourceLink . '/', 0755, true);
                $destinationPath = $lesson->getDirectory() . $sourceLink . '/' . basename($sourceFile['path']);
                $copiedFile = $sourceFile->copy($lesson->getDirectory() . $sourceLink . '/' . basename($sourceFile['path']), false);
            } else {
                $destinationPath = $lesson->getDirectory() . basename($sourceFile['path']);
                $copiedFile = $sourceFile->copy($lesson->getDirectory() . basename($sourceFile['path']), false);
            }
            str_replace("view_file.php?file=" . $file, "view_file.php?file=" . $copiedFile->offsetGet('id'), $data);
            $data = preg_replace("#(" . G_SERVERNAME . ")*content/lessons/" . $sourceId . "/(.*)#", "content/lessons/" . $newId . '/${2}', $data);
        } catch (EfrontFileException $e) {
            if ($e->getCode() == EfrontFileException::FILE_ALREADY_EXISTS) {
                $copiedFile = new EfrontFile($destinationPath);
                str_replace("view_file.php?file=" . $file, "view_file.php?file=" . $copiedFile->offsetGet('id'), $data);
                $data = preg_replace("#(" . G_SERVERNAME . ")*content/lessons/" . $sourceId . "/(.*)#", "content/lessons/" . $newId . '/${2}', $data, -1, $count);
            }
        }
        //this means that the file already exists
    }
    //$question['text'] = $data;
    return $data;
}
 public function getControlPanelModule()
 {
     $smarty = $this->getSmartyVar();
     $smarty->assign("T_MODULE_BASEDIR", $this->moduleBaseDir);
     $smarty->assign("T_MODULE_BASELINK", $this->moduleBaseLink);
     $smarty->assign("T_MODULE_BASEURL", $this->moduleBaseUrl);
     $smarty->assign("T_MODULE_OPTIONS", array(array('text' => _MODULE_SECURITY_PAGE, 'image' => "{$this->moduleBaseLink}img/go_into.png", 'href' => $this->moduleBaseUrl)));
     $feeds = $this->getRssFeeds();
     $smarty->assign("T_SECURITY_FEEDS", $feeds);
     try {
         if ($GLOBALS['configuration']['module_security_last_check'] < time() - 2 * 86400) {
             //check every 2 days
             EfrontConfiguration::setValue('module_security_last_check', time());
             $file = new EfrontFile($this->getLocalListName());
             $file->delete();
         }
         $localIssues = $this->checkLocalIssues();
         $smarty->assign("T_LOCAL_ISSUES", $localIssues);
     } catch (Exception $e) {
     }
     //Do nothing in the control panel in case of an exception
     return true;
 }
 /**
  * Import files to filesystem
  *
  * This function imports the specified files (in $list array) to the filesystem,
  * by creating a corresponding database representation. The $list
  * array should contain full paths to the files. The function returns an array
  * of the same size and contents as $list , but this time the file ids being the keys
  * <br/>Example:
  * <code>
  * $list = array('/var/www/text.txt', '/var/www/user.txt');
  * $newList = FileSystemTree :: importFiles($list);
  * </code>
  *
  * @param array $list The files list
  * @param array $options extra options to set for the files, such as whether they should be renamed, or the proper permissions
  * @return array An array with the new file ids
  * @access public
  * @since 3.0
  * @static
  */
 public static function importFiles($list, $options = array())
 {
     if (!is_array($list)) {
         $list = array($list);
     }
     $allFiles = eF_getTableDataFlat("files", "path");
     //Get all files, so that if a file already exists, a duplicate entry in the database won't be created
     for ($i = 0; $i < sizeof($list); $i++) {
         $list[$i] = EfrontFile::encode($list[$i]);
         if (!in_array($list[$i], $allFiles['path']) && strpos(dirname($list[$i]), rtrim(G_ROOTPATH, "/")) !== false) {
             $fileMetadata = array('title' => basename($list[$i]), 'creator' => $GLOBALS['currentUser']->user['name'] . ' ' . $GLOBALS['currentUser']->user['surname'], 'publisher' => $GLOBALS['currentUser']->user['name'] . ' ' . $GLOBALS['currentUser']->user['surname'], 'contributor' => $GLOBALS['currentUser']->user['name'] . ' ' . $GLOBALS['currentUser']->user['surname'], 'date' => date("Y/m/d", time()), 'type' => 'file');
             $fields = array('path' => str_replace(G_ROOTPATH, '', $list[$i]), 'users_LOGIN' => isset($_SESSION['s_login']) ? $_SESSION['s_login'] : '', 'timestamp' => time(), 'metadata' => serialize($fileMetadata));
             isset($options['access']) ? $fields['access'] = $options['access'] : null;
             $fileId = eF_insertTableData("files", $fields);
             if ($fileId) {
                 $newList[$fileId] = $list[$i];
                 foreach ($fileMetadata as $key => $value) {
                     EfrontSearch::insertText($value, $fileId, "files", "data");
                 }
             }
         }
     }
     return $newList;
 }
Example #17
0
     $result = eF_getTableData("projects p, users_to_projects up", "p.*, up.grade, up.comments, up.filename,up.last_comment", "up.users_LOGIN = '******'compress_user'] . "' and up.projects_ID = p.id and p.lessons_ID=" . $currentLesson->lesson['id']);
     $projectFiles = array();
     foreach ($result as $project) {
         $projectFiles[$project['title']] = new EfrontFile($project['filename']);
     }
     if (!is_dir($currentUser->user['directory'] . '/projects/')) {
         mkdir($currentUser->user['directory'] . '/projects/', 0755);
     }
     $projectDir = $currentUser->user['directory'] . '/projects/' . $_GET['compress_user'];
     if (!is_dir($projectDir)) {
         mkdir($projectDir, 0755);
     }
     $projectDirectory = new EfrontDirectory($projectDir);
     foreach ($projectFiles as $title => $file) {
         try {
             $projectFile = new EfrontFile($file['id']);
             $newFileName = EfrontFile::encode($title . '_' . date("d.m.Y", $file['upload_timestamp']) . '_' . $projectFile['name']);
             $projectFile->copy($projectDir . '/' . $newFileName);
         } catch (EfrontFileException $e) {
             //Don't halt for a single file
             $message .= $e->getMessage() . ' (' . $e->getCode() . ')';
         }
     }
     $zipFileName = $currentUser->user['directory'] . '/projects/' . EfrontFile::encode($_GET['compress_user']) . '.zip';
     $zipFile = $projectDirectory->compress($zipFileName, false, true);
     $projectDirectory->delete();
     eF_redirect("view_file.php?file=" . urlencode($zipFile['path']) . "&action=download");
 } catch (Exception $e) {
     $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString());
     $message = _FILESCOULDNOTBEDOWNLOADED . ': ' . $e->getMessage() . ' (' . $e->getCode() . ') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>';
     $message_type = 'failure';
Example #18
0
     $layoutTheme->layout['positions']['centerList'] = $centerList;
     $layoutTheme->layout['positions']['rightList'] = $rightList;
     $layoutTheme->layout['positions']['layout'] = $_POST['layout'];
     $layoutTheme->persist();
     echo "set";
     exit;
 } else {
     if (isset($_GET['ajax']) && $_GET['ajax'] == 'reset_layout') {
         $layoutTheme->applySettings('layout');
         echo "reset";
         exit;
     } else {
         if (isset($_GET['delete_block'])) {
             //Remove the block's file
             if (is_file($file = G_EXTERNALPATH . $customBlocks[$_GET['delete_block']]['name'] . '.tpl')) {
                 $file = new EfrontFile($file);
                 $file->delete();
             }
             //Remove the block from the custom blocks list
             unset($customBlocks[$_GET['delete_block']]);
             $layoutTheme->layout['custom_blocks'] = $customBlocks;
             //Remove the deleted block from any position it may occupy
             foreach ($layoutTheme->layout['positions'] as $key => $value) {
                 if (is_array($value) && ($offset = array_search($_GET['delete_block'], $value)) !== false) {
                     array_splice($layoutTheme->layout['positions'][$key], $offset, 1);
                 }
             }
             $layoutTheme->persist();
             exit;
         } else {
             if (isset($_GET['toggle_block'])) {
Example #19
0
             $attached_file = new EfrontFile($result[0]['attachments']);
             $attached_file->delete();
         }
     } catch (Exception $e) {
         header("HTTP/1.0 500 ");
         echo rawurlencode($e->getMessage()) . ' (' . $e->getCode() . ')';
     }
     exit;
 } elseif (isset($_GET['ajax']) && isset($_GET['delete_messages'])) {
     try {
         $messages = json_decode($_GET['delete_messages']);
         foreach ($messages as $message) {
             $result = eF_getTableData("f_personal_messages", "users_LOGIN, attachments, f_folders_ID", "id=" . $message);
             eF_deleteTableData("f_personal_messages", "id=" . $message);
             if ($result[0]['attachments'] != '') {
                 $attached_file = new EfrontFile($result[0]['attachments']);
                 $attached_file->delete();
             }
         }
     } catch (Exception $e) {
         handleAjaxExceptions($e);
     }
     exit;
 } elseif (isset($_GET['ajax']) && isset($_GET['move_messages'])) {
     try {
         $messages = json_decode($_GET['move_messages']);
         foreach ($messages as $message) {
             eF_updateTableData("f_personal_messages", array("f_folders_ID" => $_GET['folder']), "id=" . $message);
         }
     } catch (Exception $e) {
         handleAjaxExceptions($e);
 //$currentUnit['options']['complete_unit_setting'] == COMPLETION_OPTIONS_COMPLETEWITHQUESTION ? $form -> updateElementAttr(array('complete_question'), array('style' => 'display:""')) : null;
 //$currentUnit['options']['complete_unit_setting'] == COMPLETION_OPTIONS_COMPLETEAFTERSECONDS ? $form -> updateElementAttr(array('complete_time'), array('style' => 'display:""')) : null;
 //Check whether it is a pdf content and handle accordingly
 if (mb_strpos($currentUnit['data'], "<iframe") !== false && mb_strpos($currentUnit['data'], "pdfaccept") !== false && mb_strpos($currentUnit['data'], "google.com/viewer") === false) {
     $fileEnd = mb_strpos($currentUnit['data'], ".pdf");
     if ($fileEnd != "") {
         $contentParts = explode("/", mb_substr($currentUnit['data'], 0, $fileEnd));
         try {
             $pdfFile = new EfrontFile(G_RELATIVELESSONSLINK . $_SESSION['s_lessons_ID'] . '/' . EfrontFile::decode(htmlspecialchars_decode(urldecode($contentParts[sizeof($contentParts) - 1] . '.pdf'))));
             if ($pdfFile['id']) {
                 $form->setDefaults(array('data' => '<iframe src="view_file.php?file=' . $pdfFile['id'] . '"  name="pdfaccept" width="100%" height="600"></iframe>'));
             }
         } catch (Exception $e) {
             //in case file is not found in database, don't do anything
         }
         $form->setDefaults(array('pdf_content' => EfrontFile::decode(htmlspecialchars_decode(urldecode($contentParts[sizeof($contentParts) - 1] . '.pdf')))));
     } else {
         preg_match("/view_file.php\\?file=\\d+/", $currentUnit['data'], $matches);
         $pdfId = explode("=", $matches[0]);
         try {
             $pdfFile = new EfrontFile($pdfId[1]);
         } catch (Exception $e) {
             $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString());
             $message = _SOMEPROBLEMOCCURED . ': ' . $e->getMessage() . ' (' . $e->getCode() . ') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>';
             $message_type = 'failure';
         }
         $form->setDefaults(array('pdf_content' => $pdfFile['physical_name']));
     }
     $form->setDefaults(array('pdf_check' => 1));
     $smarty->assign("T_EDITPDFCONTENT", true);
 }
 /**
  * Reset the project completion
  *
  * This function is used to reset the current project completion.
  * All related information is lost, as well as files associated
  * with the project.
  * <br/>Example:
  * <code>
  * $project = new EfrontProject(12);                //Instantiate project with id 12
  * $project -> reset($login);                            //Reset project completion for $login and all associated information
  * </code>
  *
  * @since 3.5.0
  * @access public
  * @todo delete project files
  */
 public function reset($login = false)
 {
     $users = $this->getUsers();
     if (!in_array($login, array_keys($users))) {
         throw new EfrontContentException(_USERDOESNOTHAVETHISPROJECT, EfrontContentException::INVALID_LOGIN);
     }
     $fields = array('grade' => NULL, 'comments' => NULL, 'upload_timestamp' => NULL, 'filename' => NULL, 'text_grade' => NULL, 'professor_upload_filename' => NULL);
     eF_updateTableData("users_to_projects", $fields, "users_LOGIN='******' and projects_ID=" . $this->project['id']);
     try {
         $file = new EfrontFile($users[$login]['filename']);
         $file->delete();
     } catch (Exception $e) {
         /*Do nothing if a file does not exist*/
     }
     return true;
 }
Example #22
0
 public static function exportToCsv($data, $download = false, $name = "data.csv")
 {
     $currentUser = EfrontUserFactory::factory($_SESSION['s_login']);
     $fp = fopen($currentUser->getDirectory() . $name, 'w');
     foreach ($data as $fields) {
         fputcsv($fp, $fields);
     }
     fclose($fp);
     $file = new EfrontFile($currentUser->getDirectory() . $name);
     if ($download) {
         $file->sendFile(true);
     } else {
         return $file;
     }
 }
Example #23
0
             if (!in_array($value, $imsFiles)) {
                 //This way we bypass duplicates
                 try {
                     $imsFiles[$value] = $filesystem->uploadFile("ims_file", $currentLesson->getDirectory(), $key);
                 } catch (EfrontFileException $e) {
                     if ($e->getCode() != UPLOAD_ERR_NO_FILE) {
                         throw $e;
                     }
                 }
             }
         }
     }
     //pr($imsFiles);exit;
     foreach ($imsFiles as $imsFile) {
         /* Imports ims package to database */
         $imsFolderName = EfrontFile::encode(eFront_basename($imsFile['name'], '.zip'));
         $imsPath = $currentLesson->getDirectory() . $imsFolderName . '/';
         is_dir($imsPath) or mkdir($imsPath, 0755);
         //pr($imsPath.$imsFile['name']);
         //try {
         $imsFile->rename($imsPath . $imsFile['name'], true);
         //} catch (Exception $e) {pr($e);throw $e;}
         $fileList = $imsFile->uncompress(false);
         $imsFile->delete();
         $total_fields = array();
         $resources = array();
         $manifestFile = new EfrontFile($imsPath . 'imsmanifest.xml');
         EfrontIMS::import($currentLesson, $manifestFile, $imsFolderName, array('embed_type' => $values['embed_type'], 'popup_parameters' => $values['popup_parameters']));
     }
     eF_redirect("" . basename($_SERVER['PHP_SELF']) . "?ctg=ims&message=" . urlencode(_SUCCESSFULLYIMPORTEDIMSFILE) . "&message_type=success");
 } catch (Exception $e) {
Example #24
0
 /**
  * Uncompress exported file and get data
  *
  * This function uncompresses the exported course file and reads the serialized database
  * data into an array
  *
  * @param EfrontFile $file The exported file
  * @return array The serialized course data
  * @since 3.6.1
  * @access private
  */
 private function getCourseDataFromExportedFile($file)
 {
     $fileList = $file->uncompress();
     $fileList = array_unique(array_reverse($fileList, true));
     $dataFile = new EfrontFile($file['directory'] . '/data.dat');
     $filedata = file_get_contents($dataFile['path']);
     $dataFile->delete();
     $data = unserialize($filedata);
     unset($data['courses'][0]['id']);
     unset($data['courses'][0]['instance_source']);
     return $data;
 }
try {
    if (isset($_GET['server'])) {
        $url = $_SERVER['REQUEST_URI'];
        if (strpos($url, 'http') !== 0) {
            //Otherwise, depending on the QUERY_STRING, parse_url() may not work
            $url = G_PROTOCOL . '://' . $_SERVER["HTTP_HOST"] . $url;
        }
        $urlParts = parse_url($url);
        $filePath = G_ROOTPATH . 'www/' . str_replace(G_SERVERNAME, '', G_PROTOCOL . '://' . getHttpHost() . $urlParts['path']);
        try {
            $file = new EfrontFile(urldecode($filePath));
        } catch (Exception $e) {
            $file = new EfrontFile($filePath);
        }
    } else {
        $file = new EfrontFile($_GET['file']);
    }
    if (!$bypass_check) {
        if (preg_match("#content/lessons/(\\d+)/#", $file['path'], $matches)) {
            //the file is a content file. Available to any user enrolled to this lesson.
            $result = eF_getTableDataFlat("lessons l, users_to_lessons ul", "id, share_folder", "l.archive=0 and l.id=ul.lessons_ID and ul.archive=0 and ul.users_LOGIN='******'login'] . "'");
            $legalFolders = array_unique(array_merge($result['id'], $result['share_folder']));
            if ($currentUser->user['user_type'] != 'administrator' && $matches[1] && !in_array($matches[1], $legalFolders)) {
                // fix due to ticket #5594
                $results = eF_getTableData("content", "linked_to", "lessons_ID=" . $_SESSION['s_lessons_ID']);
                foreach ($results as $result) {
                    $linked_content[] = $result['linked_to'];
                }
                $results = eF_getTableData("content", "lessons_ID", "id in (" . implode(",", $linked_content) . ") OR linked_to in (" . implode(",", $linked_content) . ")");
                foreach ($results as $result) {
                    $lessons_with_linked_content[] = $result['lessons_ID'];
Example #26
0
     throw new Exception(implode("<br>", $errors));
 }
 //Re-index $uploadedFiles
 $uploadedFiles = array_values($uploadedFiles);
 //We use for instead of foreach, because the 'uncompress_recursive' parameter may augment the $uploadedFiles array
 $unzipFlag = true;
 for ($i = 0; $i < sizeof($uploadedFiles); $i++) {
     $emptyUnits = array();
     $file = $uploadedFiles[$i];
     $pathParts = pathinfo($file['name']);
     if ($pathParts['extension'] == 'zip' && $unzipFlag == true) {
         $fileContents = $file->listContents();
         sort($fileContents);
         //Check if it is a SCORM file
         if (in_array("imsmanifest.xml", $fileContents)) {
             $scormFolderName = EfrontFile::encode(eFront_basename($file['name'], '.zip'));
             $scormPath = $currentLesson->getDirectory() . $scormFolderName . '/';
             is_dir($scormPath) or mkdir($scormPath, 0755);
             $file->rename($scormPath . $file['name'], true);
             $file->uncompress(false);
             $manifestFile = new EfrontFile($scormPath . 'imsmanifest.xml');
             EfrontScorm::import($currentLesson, $manifestFile, $scormFolderName);
         } elseif (in_array("data.dat", $fileContents)) {
             $currentLesson->import($file);
         } else {
             $file->uncompress();
             if ($values['uncompress_recursive']) {
                 $unzipFlag = false;
                 foreach ($fileContents as $additionalFile) {
                     if (!is_dir($uploadDir . $additionalFile)) {
                         //Add to the list of the uploaded files, all those that where extracted
Example #27
0
define("PASSWORD","' . $defaultConfig['phplivedocx_password'] . '");
define("PHPLIVEDOCXAPI","' . $defaultConfig['phplivedocx_server'] . '");
?>';
                file_put_contents($path . "phplivedocx_config.php", $phplivedocxConfig);
                eF_updateTableData("users", array('email' => $values['admin_email'], 'password' => EfrontUser::createPassword($values['admin_password']), 'last_login' => '0'));
                eF_updateTableData("users", array('login' => $values['admin_name']), "id=1");
                eF_updateTableData("courses", array('created' => time()));
                eF_updateTableData("courses", array('created' => time(), 'creator_LOGIN' => $values['admin_name']));
                eF_updateTableData("lessons", array('created' => time(), 'creator_LOGIN' => $values['admin_name']));
                eF_updateTableData("users_to_courses", array('from_timestamp' => time()));
                eF_updateTableData("users_to_lessons", array('from_timestamp' => time()));
                eF_deleteTableData("logs", "");
                eF_deleteTableData("events", "");
                EfrontConfiguration::setValue("database_version", G_VERSION_NUM);
                EfrontConfiguration::setValue("system_Email", $values['admin_email']);
                $file = new EfrontFile(EfrontDirectory::normalize(getcwd()) . '/lessons.zip');
                $newFile = $file->copy(G_LESSONSPATH, true);
                $newFile->uncompress();
                $newFile->delete();
                if (G_VERSIONTYPE == 'community') {
                    #cpp#ifdef COMMUNITY
                    $modulesToRemove[] = 'content_reports';
                    $modulesToRemove[] = 'course_reports';
                    $modulesToRemove[] = 'fuze_meetings';
                    $modulesToRemove[] = 'training_reports';
                }
                #cpp#endif
                if (G_VERSIONTYPE != 'enterprise') {
                    #cpp#ifndef ENTERPRISE
                    $modulesToRemove[] = 'branch_reports';
                    $modulesToRemove[] = 'jobs_manager';