Example #1
0
 public function body()
 {
     ob_start();
     //create default module form
     print '<div class="title">Select modules to disable</div>';
     print 'Selected modules will be marked as not installed but uninstall methods will not be called. Any database tables and other modifications made by modules\' install methods will not be reverted.<br><br>';
     print 'To uninstall module please use Modules Administration in Application.';
     print '<hr/><br/>';
     $form = new HTML_QuickForm('modulesform', 'post', $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET), '', null, true);
     $states = array(ModuleManager::MODULE_ENABLED => 'Active', ModuleManager::MODULE_DISABLED => 'Inactive');
     $modules = DB::GetAssoc('SELECT * FROM modules ORDER BY state, name');
     foreach ($modules as $m) {
         $name = $m['name'];
         $state = isset($m['state']) ? $m['state'] : ModuleManager::MODULE_ENABLED;
         if ($state == ModuleManager::MODULE_NOT_FOUND) {
             $state = ModuleManager::MODULE_DISABLED;
         }
         $form->addElement('select', $name, $name, $states);
         $form->setDefaults(array($name => $state));
     }
     $form->addElement('button', 'submit_button', 'Save', array('class' => 'button', 'onclick' => 'if(confirm("Are you sure?")) document.modulesform.submit();'));
     //validation or display
     if ($form->validate()) {
         //uninstall
         $vals = $form->exportValues();
         foreach ($vals as $k => $v) {
             if (isset($modules[$k]['state']) && $modules[$k]['state'] != $v) {
                 ModuleManager::set_module_state($k, $v);
             }
         }
     }
     $form->display();
     return ob_get_clean();
 }
Example #2
0
 public function __construct()
 {
     parent::__construct('delete_interest', 'Delete Interest', 'Admin/delete_interest.php');
     if ($this->loginError) {
         return;
     }
     $form = new HTML_QuickForm('deleter');
     $interest_list = new pdAuthInterests($this->db);
     $form->addElement('select', 'interests', 'Select interest(s) to delete:', $interest_list->list, array('multiple' => 'multiple', 'size' => 15));
     $form->addGroup(array(HTML_QuickForm::createElement('button', 'cancel', 'Cancel', array('onclick' => 'history.back()')), HTML_QuickForm::createElement('submit', 'submit', 'Delete')), null, null, '&nbsp;', false);
     if ($form->validate()) {
         $values = $form->exportValues();
         foreach ($values['interests'] as $interest_id) {
             $names[] = $interest_list->list[$interest_id];
         }
         $interest_list->dbDelete($this->db, $values['interests']);
         echo 'You have successfully removed the following interest from the ', 'database: <br/><b>', implode(', ', $names), '</b></p>', '<br><a href="', $_SERVER['PHP_SELF'], '">Delete another interest</a>';
     } else {
         $renderer =& $form->defaultRenderer();
         $form->accept($renderer);
         $this->form =& $form;
         $this->renderer =& $renderer;
         echo '<h3>Delete Interest </h3>';
     }
 }
Example #3
0
 public function __construct()
 {
     parent::__construct('view_publication', 'View Publication', 'view_publication.php');
     if ($this->loginError) {
         return;
     }
     $this->loadHttpVars();
     if (!isset($this->pub_id) || !is_numeric($this->pub_id)) {
         $this->pageError = true;
         return;
     }
     $pub = new pdPublication();
     $result = $pub->dbLoad($this->db, $this->pub_id);
     if (!$result) {
         echo 'Publication does not exist';
         return;
     }
     if (isset($this->submit_pending) && $this->submit_pending) {
         // check if this pub entry is pending
         $q = $this->db->selectRow('pub_pending', '*', array('pub_id' => $this->pub_id));
         assert('$q');
         $form = new HTML_QuickForm('submit_pending');
         $form->addElement('hidden', 'submit_pending', true);
         $form->addElement('hidden', 'pub_id', $this->pub_id);
         $elements = array();
         $elements[] = HTML_QuickForm::createElement('advcheckbox', 'valid', null, 'Valid', null, array(0, 1));
         $elements[] = HTML_QuickForm::createElement('submit', 'submit', 'Submit');
         $form->addGroup($elements, 'elgroup', '', '&nbsp', false);
         // create a new renderer because $form->defaultRenderer() creates
         // a single copy
         $renderer = new HTML_QuickForm_Renderer_Default();
         $form->accept($renderer);
         if ($form->validate()) {
             $values =& $form->exportValues();
             $pub->markValid($this->db);
             echo 'Publication entry marked as valid.';
             return;
         } else {
             echo "<h2>This publication entry requires validation</h2>\n";
             echo $renderer->toHtml();
         }
     }
     $this->showPublication($pub);
 }
Example #4
0
#cpp#endif
if (isset($_GET['ctg']) && $_GET['ctg'] == 'saml') {
    $saml = new EfrontSaml();
    $saml->authenticate();
}
/* -----------------End of Login part-----------------------------*/
if (isset($_GET['ctg']) && $_GET['ctg'] == 'agreement' && $_SESSION['s_login']) {
    //Display license agreement
    try {
        $_SESSION['s_index_comply'] = 'agreement';
        $user = EfrontUserFactory::factory($_SESSION['s_login']);
        $agreementForm = new HTML_QuickForm("agreement_form", "post", basename($_SERVER['PHP_SELF']) . "?ctg=agreement", "", "class = 'indexForm'", true);
        $agreementForm->addElement('submit', 'submit_decline', _NOTACCEPTANDEXIT, 'class = "flatButton"');
        $agreementForm->addElement('submit', 'submit_accept', _ACCEPTANDCONTINUE, 'class = "flatButton"');
        if ($agreementForm->isSubmitted() && $agreementForm->validate()) {
            $values = $agreementForm->exportValues();
            if ($values['submit_accept']) {
                $user->user['viewed_license'] = 1;
                $user->persist();
                unset($_SESSION['s_index_comply']);
                EfrontEvent::triggerEvent(array("type" => EfrontEvent::SYSTEM_VISITED, "users_LOGIN" => $user->user['login'], "users_name" => $user->user['name'], "users_surname" => $user->user['surname']));
                if ($_SESSION['login_mode']) {
                    eF_redirect("index.php?ctg=checkout&checkout=1");
                }
                loginRedirect($user->user['user_type']);
            } else {
                $user->logout(session_id());
                eF_redirect("index.php");
            }
        }
        $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
 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());
 }
Example #6
0
 /**
  * Returns 'safe' elements' values
  *
  * @param   mixed   Array/string of element names, whose values we want. If not set then return all elements.
  * @param   bool    Whether to remove internal (_qf_...) values from the resultant array
  */
 function exportValues($elementList = null, $filterInternal = false)
 {
     $values = parent::exportValues($elementList);
     if ($filterInternal) {
         foreach (array_keys($values) as $key) {
             if (0 === strpos($key, '_qf_')) {
                 unset($values[$key]);
             }
         }
     }
     return $values;
 }
 /**
  * The main functionality
  *
  * (non-PHPdoc)
  * @see libraries/EfrontModule#getModule()
  */
 public function getModule()
 {
     $smarty = $this->getSmartyVar();
     $smarty->assign("T_MODULE_BASEDIR", $this->moduleBaseDir);
     $smarty->assign("T_MODULE_BASELINK", $this->moduleBaseLink);
     $smarty->assign("T_MODULE_BASEURL", $this->moduleBaseUrl);
     $dir = $this->moduleBaseDir . 'assets/';
     if (!is_dir($dir)) {
         mkdir($dir, 0755);
     }
     if ($_SESSION['s_type'] == 'administrator') {
         try {
             $form = new HTML_QuickForm("upload_files_form", "post", $this->moduleBaseUrl . '&tab=upload', "", null, true);
             $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
             //Register this rule for checking user input with our function, eF_checkParameter
             $form->addElement('file', 'file', _UPLOADFILE);
             if (G_VERSIONTYPE == 'enterprise') {
                 $tree = new EfrontBranchesTree();
                 $pathString = $tree->toPathString();
                 //$result = eF_getTableData("module_hcd_branch", "*", "url is not null and url !=''");
                 $handle = '<img id = "busy" src = "images/16x16/clock.png" style = "display:none;" alt = "{$smarty.const._LOADING}" title = "{$smarty.const._LOADING}"/><div id = "autocomplete_leaflet_branches" class = "autocomplete"></div>&nbsp;&nbsp;&nbsp;';
                 $form->addElement('static', 'sidenote', $handle);
                 $form->addElement('text', 'leaflet_branch_autoselect', _BRANCH, 'class = "autoCompleteTextBox" id = "autocomplete"');
                 $form->addElement('hidden', 'leaflet_branch', '', 'id = "leaflet_branch_value"');
             }
             $form->setMaxFileSize(FileSystemTree::getUploadMaxSize() * 1024);
             $form->addElement('submit', 'submit_upload', _UPLOAD, 'class = "flatButton"');
             if ($form->isSubmitted() && $form->validate()) {
                 $values = $form->exportValues();
                 try {
                     if ($values['leaflet_branch'] && eF_checkParameter($values['leaflet_branch'], 'id')) {
                         $branch = new EfrontBranch($values['leaflet_branch']);
                         if (!$branch->branch['url']) {
                             throw new Exception("You must assign a url to the selected branch to upload files for it");
                         }
                         $dir = $this->moduleBaseDir . 'assets/' . $branch->branch['url'];
                         mkdir($dir, 0755);
                     }
                     $filesystem = new FileSystemTree($dir);
                     $file = $filesystem->uploadFile("file", $dir);
                 } 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;
                     $this->setMessageVar($message, $message_type);
                 }
             }
             $smarty->assign('T_UPLOAD_FORM', $form->toArray());
             $url = $this->moduleBaseUrl;
             $basedir = $dir;
             $options = array('zip' => false, 'upload' => false, 'create_folder' => false, 'folders' => true);
             /**The file manager*/
             include "file_manager.php";
         } 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';
             $this->setMessageVar($message, $message_type);
         }
     } else {
         if (defined('G_BRANCH_URL') && G_BRANCH_URL) {
             try {
                 $assets_path = $root_path = $this->moduleBaseDir . 'assets/' . G_BRANCH_URL;
             } catch (Exception $e) {
                 //do nothing here if the directory doesn't exist
             }
         } else {
             $assets_path = $root_path = $this->moduleBaseDir . 'assets/';
         }
         $files = array();
         if (!empty($_GET['folder'])) {
             $folder = urldecode($_GET['folder']);
             if (is_dir($assets_path . $folder)) {
                 $folder = new EfrontDirectory($assets_path . $folder);
                 if (strpos(realpath($folder['path']), $root_path) === false) {
                     throw new Exception("Invalid folder");
                 }
                 $parent_folder = dirname($folder['path']);
                 $url = urlencode(str_replace($root_path, '', $folder['path']));
                 $assets_path = $folder['path'];
                 $parent_url = $this->moduleBaseUrl . "&folder=" . urlencode(str_replace($root_path, '', dirname($folder['path']) . '/'));
                 $parent_url or $parent_url = $this->moduleBaseUrl . 'assets/';
                 $files[] = array('text' => '.. (Up one level)', 'image' => $this->moduleBaseLink . 'ico/folders.png', 'href' => $parent_url);
             }
         }
         //pr($url);pr($parent_url);
         //
         $filesystem = new FileSystemTree($assets_path, true);
         foreach ($filesystem->tree as $key => $value) {
             if ($value instanceof EfrontDirectory) {
                 $files[] = array('text' => basename($key), 'image' => $this->moduleBaseLink . 'ico/folders.png', 'href' => $this->moduleBaseUrl . "&folder=" . urlencode(str_replace($root_path, '', $value['path'] . '/')));
             }
         }
         foreach ($filesystem->tree as $key => $value) {
             if ($value instanceof EfrontFile) {
                 if (is_file($this->moduleBaseDir . 'ico/' . pathinfo($key, PATHINFO_EXTENSION) . '.png')) {
                     $icon = $this->moduleBaseLink . 'ico/' . pathinfo($key, PATHINFO_EXTENSION) . '.png';
                 } else {
                     $icon = $this->moduleBaseLink . 'ico/unknown.png';
                 }
                 $files[] = array('text' => basename($key), 'image' => $icon, 'href' => $this->moduleBaseLink . str_replace($this->moduleBaseDir, '', $key));
             }
         }
         $smarty->assign("T_FILES", $files);
     }
     return true;
 }
    /**
     * The main functionality
     *
     * (non-PHPdoc)
     * @see libraries/EfrontModule#getModule()
     */
    public function getModule()
    {
        $smarty = $this->getSmartyVar();
        $smarty->assign("T_MODULE_BASEDIR", $this->moduleBaseDir);
        $smarty->assign("T_MODULE_BASELINK", $this->moduleBaseLink);
        $smarty->assign("T_MODULE_BASEURL", $this->moduleBaseUrl);
        $form = new HTML_QuickForm("bootstrap_form", "post", $this->moduleBaseUrl, "", null, true);
        $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
        $form->addElement('text', 'name', _NAME, 'class = "inputText"');
        $form->addElement('static', '', _MODULE_BOOTSTRAP_WITHOUTTHECLASS, 'class = "inputText"');
        $form->addRule('name', _THEFIELD . ' ' . _NAME . ' ' . _ISMANDATORY, 'required', null, 'client');
        $form->addRule('name', _INVALIDFIELDDATA, 'checkParameter', 'alnum');
        $form->addElement('text', 'title', _TITLE, 'class = "inputText"');
        $form->addElement('text', 'creator', _MODULE_BOOTSTRAP_CREATOR, 'class = "inputText"');
        $form->addElement('checkbox', 'administrator', _ADMINISTRATOR);
        $form->addElement('checkbox', 'professor', _PROFESSOR);
        $form->addElement('checkbox', 'student', _STUDENT);
        $form->addElement('checkbox', 'supervisor', _MODULE_BOOTSTRAP_SUPERVISORONLY);
        $form->addElement('checkbox', 'tabber', _MODULE_BOOTSTRAP_TABBER);
        $form->addElement('textarea', 'form', _MODULE_BOOTSTRAP_FORMFIELDS, 'class = "inputTextarea" style = "height:40px"');
        $form->addElement('static', '', _MODULE_BOOTSTRAP_FORMINSTRUCTIONS);
        $form->addElement('textarea', 'grid', _MODULE_BOOTSTRAP_GRIDFIELDS, 'class = "inputTextarea" style = "height:40px"');
        $form->addElement('static', '', _MODULE_BOOTSTRAP_GRIDINSTRUCTIONS);
        $form->addElement('checkbox', 'filemanager', _MODULE_BOOTSTRAP_FILEMANAGER);
        $form->addElement('textarea', 'description', _DESCRIPTION, 'class = "inputTextarea" style = "height:80px"');
        //$form -> addElement('placing', 'student', _MODULE_BOOTSTRAP_NAME);
        $form->addElement('checkbox', 'overwrite', _MODULE_BOOTSTRAP_OVERWRITEIFEXISTS);
        $form->addElement('submit', 'submit', _INSTALL, 'class = "flatButton"');
        $form->setDefaults(array('creator' => $this->getCurrentUser()->user['name'] . ' ' . $this->getCurrentUser()->user['surname']));
        if ($form->isSubmitted() && $form->validate()) {
            try {
                $values = $form->exportValues();
                if (!$values['administrator'] && !$values['student'] && !$values['professor']) {
                    throw new Exception(_MODULE_BOOTSTRAP_YOUMUSTSELECTATLEASTATYPE);
                }
                $module_name = $values['name'];
                $module_dir = $this->moduleBaseDir . 'module_' . $module_name;
                if (!is_dir($module_dir)) {
                    mkdir($module_dir, 0755);
                }
                if (!is_dir("{$module_dir}/img")) {
                    mkdir("{$module_dir}/img", 0755);
                }
                if (!is_dir("{$module_dir}/assets")) {
                    mkdir("{$module_dir}/assets", 0755);
                }
                if ($values['administrator']) {
                    $roles[] = 'administrator';
                }
                if ($values['professor']) {
                    $roles[] = 'professor';
                }
                if ($values['student']) {
                    $roles[] = 'student';
                }
                $roles = '"' . implode('","', $roles) . '"';
                $contents = $tabber = $block = $grid_content = $fields_content = '';
                $fields = array();
                if ($values['form']) {
                    foreach (explode(",", $values['form']) as $property) {
                        $property = explode(":", $property);
                        array_walk($property, create_function('&$v', '$v = trim($v);'));
                        $fields[] = array('type' => $property[0], 'name' => $property[1], 'title' => $property[2], 'extra' => $property[3]);
                    }
                    foreach ($fields as $value) {
                        $fields_content .= '$form -> addElement("' . $value["type"] . '", "' . $value["name"] . '", "' . $value["title"] . '", "' . $value["extra"] . '");';
                    }
                } else {
                    $fields = "return false;";
                }
                if ($values['filemanager']) {
                    $file_manager = "true";
                } else {
                    $file_manager = "false";
                }
                if ($values['grid']) {
                    $headers = $rows = $grid_contents = array();
                    $grid_content = "\$data = array(array(";
                    foreach (explode(",", $values['grid']) as $property) {
                        $property = trim($property);
                        if ($property) {
                            $property = explode(":", $property);
                            array_walk($property, create_function('&$v', '$v = trim($v);'));
                            $headers[] = "\r\n\t\t\t\t\t\t\t\t<td class = 'topTitle' name = '{$property[0]}'>{$property[1]}</td>";
                            $rows[] = "\r\n\t\t\t\t\t\t\t\t<td>{\$item.{$property[0]}}</td>";
                            $grid_content .= "'{$property[0]}' => 'sample value',";
                        }
                    }
                    $grid_content .= "));";
                    $headers = implode("\n", $headers);
                    $rows = implode("\n", $rows);
                    $contents .= <<<GRID
{capture name = "t_grid_code"}
<!--ajax:{$module_name}Table-->
\t\t\t\t\t<table style = "width:100%" class = "sortedTable" size = "{\$T_TABLE_SIZE}" sortBy = "0" id = "{$module_name}Table" useAjax = "1" rowsPerPage = "{\$smarty.const.G_DEFAULT_TABLE_SIZE}" url = "{\$T_MODULE_BASEURL}&">
\t\t\t\t\t\t<tr class = "topTitle">
\t\t\t\t\t\t\t{$headers}
\t\t\t\t\t\t</tr>
\t{foreach name = 'demo_data_list' key = 'key' item = 'item' from = \$T_DATA_SOURCE}
\t\t\t\t\t\t<tr class = "defaultRowHeight {cycle values = "oddRowColor, evenRowColor"}">
\t\t\t\t\t\t\t{$rows}
\t\t\t\t\t\t</tr>
\t{foreachelse}
\t\t\t\t\t<tr class = "defaultRowHeight oddRowColor"><td class = "emptyCategory" colspan = "100%">{\$smarty.const._NODATAFOUND}</td></tr>
\t{/foreach}
\t\t\t\t</table>

<!--/ajax:{$module_name}Table-->

{/capture}

GRID;
                    if ($values['tabber']) {
                        $tabber = "tabber = \"{$module_name}_grid\"";
                    }
                    $block .= '{eF_template_printBlock ' . $tabber . ' title = "' . _MODULE_BOOTSTRAP_DATA . '" data = $smarty.capture.t_grid_code}' . "\n";
                }
                if ($values['form']) {
                    $contents .= <<<FORM
{capture name = "t_form_block_code"}
\t{eF_template_printForm form = \$T_FORM}
{/capture}
FORM;
                    if ($values['tabber']) {
                        $tabber = "tabber = \"{$module_name}_form\"";
                    }
                    $block .= '{eF_template_printBlock ' . $tabber . ' title = "' . _MODULE_BOOTSTRAP_FORM . '" data = $smarty.capture.t_form_block_code}' . "\n";
                }
                if ($values['filemanager']) {
                    $contents .= <<<FILEMANAGER
{capture name = "t_block_code"}
\t{\$T_FILE_MANAGER}
{/capture}
FILEMANAGER;
                    if ($values['tabber']) {
                        $tabber = "tabber = \"{$module_name}_filemanager\"";
                    }
                    $block .= '{eF_template_printBlock ' . $tabber . ' title = "' . _MODULE_BOOTSTRAP_FILES . '" data = $smarty.capture.t_block_code}';
                }
                if ($values['empty_page']) {
                    $contents .= <<<EMPTY
{capture name = "t_block_code"}
\tCode here
{/capture}
EMPTY;
                    if ($values['tabber']) {
                        $tabber = "tabber = \"{$module_name}_page\"";
                    }
                    $block .= '{eF_template_printBlock ' . $tabber . ' title = "' . _MODULE_BOOTSTRAP_PAGE . '" data = $smarty.capture.t_block_code}';
                }
                if ($values['tabber']) {
                    $contents = <<<CONTENTS
{$contents}
{capture name = "t_code"}
<div class = "tabber">
{$block}
</div>
{/capture}
{eF_template_printBlock title = "{$values["title"]}" data = \$smarty.capture.t_code}
CONTENTS;
                } else {
                    $contents = $contents . $block;
                }
                file_put_contents("{$module_dir}/module.tpl", $contents);
                $search = array("###NAME###", "###TITLE###", "###ROLES###", "###FIELDS###", "###FILE_MANAGER###", "###GRID_DATA###");
                $replace = array($module_name, $values['title'], $roles, $fields_content, $file_manager, $grid_content);
                $contents = file_get_contents($this->moduleBaseDir . "template/module_.class.php");
                $contents = str_replace($search, $replace, $contents);
                file_put_contents("{$module_dir}/module_{$module_name}.class.php", $contents);
                $date = date("Y m d");
                $xml = <<<XML
<?xml version="1.0" ?>
<module>
\t<title>{$values['title']}</title>
\t<author>{$values['creator']}</author>
\t<date>{$date}</date>
\t<version>1.0</version>
\t<description>{$values['description']}</description>
\t<className>module_{$module_name}</className>
\t<requires>3.6.11</requires>
</module>
XML;
                file_put_contents("{$module_dir}/module.xml", $xml);
                copy($this->moduleBaseDir . "img/logo.png", "{$module_dir}/img/logo.png");
                copy($this->moduleBaseDir . "img/generic.png", "{$module_dir}/img/generic.png");
                $directory = new EfrontDirectory($module_dir);
                if (is_dir(G_MODULESPATH . basename($module_dir))) {
                    if ($values['overwrite']) {
                        $file = $directory->copy(G_MODULESPATH . basename($module_dir), true);
                    } else {
                        throw new Exception(_MODULE_BOOTSTRAP_MODULEEXISTS);
                    }
                } else {
                    $file = $directory->copy(G_MODULESPATH . basename($module_dir));
                }
                $this->setMessageVar(_MODULE_BOOTSTRAP_MODULEINSTALLED, '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>';
                $this->setMessageVar($message, 'failure');
            }
        }
        $smarty->assign("T_FORM", $form->toArray());
        return true;
    }
Example #9
0
 public function getSmartyTpl()
 {
     $currentUser = $this->getCurrentUser();
     $rules = $this->getRules();
     $smarty = $this->getSmartyVar();
     if ($currentUser->getRole($this->getCurrentLesson()) == 'professor' || $currentUser->getRole($this->getCurrentLesson()) == 'student') {
         $currentLesson = $this->getCurrentLesson();
         $currentLessonID = $currentLesson->lesson['id'];
         if (!isset($_SESSION['module_journal_dimension']) || count($_GET) == 2 && $_GET['ctg'] == 'module' && $_GET['op'] == 'module_journal' || count($_GET) == 3 && $_GET['ctg'] == 'module' && $_GET['op'] == 'module_journal' && $_GET['new_lesson_id'] == $currentLessonID) {
             $_SESSION['module_journal_dimension'] = 'small';
         }
         if (!isset($_SESSION['module_journal_entries_from']) || count($_GET) == 2 && $_GET['ctg'] == 'module' && $_GET['op'] == 'module_journal' || count($_GET) == 3 && $_GET['ctg'] == 'module' && $_GET['op'] == 'module_journal' && $_GET['new_lesson_id'] == $currentLessonID) {
             $_SESSION['module_journal_entries_from'] = '-1';
         }
         if (isset($_SESSION['module_journal_scroll_position'])) {
             $smarty->assign("T_JOURNAL_SCROLL_POSITION", $_SESSION['module_journal_scroll_position']);
         }
         $smarty->assign("T_JOURNAL_DIMENSIONS", $_SESSION['module_journal_dimension']);
         $smarty->assign("T_JOURNAL_ENTRIES_FROM", $_SESSION['module_journal_entries_from']);
         $entries = $this->getEntries($currentUser->user['login'], $_SESSION['module_journal_entries_from']);
         global $popup;
         isset($popup) && $popup == 1 ? $popup_ = '&popup=1' : ($popup_ = '');
     }
     $smarty->assign("T_JOURNAL_BASEURL", $this->moduleBaseUrl);
     $smarty->assign("T_JOURNAL_BASELINK", $this->moduleBaseLink);
     if (isset($_GET['edit_allow_export']) && $_GET['edit_allow_export'] == '1' && isset($_GET['allow'])) {
         try {
             $object = eF_getTableData("module_journal_settings", "id", "name='export'");
             eF_updateTableData("module_journal_settings", array("value" => $_GET['allow']), "id=" . $object[0]['id']);
         } catch (Exception $e) {
             handleAjaxExceptions($e);
         }
         exit;
     }
     if (isset($_GET['edit_professor_preview']) && $_GET['edit_professor_preview'] == '1' && isset($_GET['preview'])) {
         try {
             $object = eF_getTableData("module_journal_settings", "id", "name='preview'");
             eF_updateTableData("module_journal_settings", array("value" => $_GET['preview']), "id=" . $object[0]['id']);
         } catch (Exception $e) {
             handleAjaxExceptions($e);
         }
         exit;
     }
     if (isset($_GET['dimension']) && eF_checkParameter($_GET['dimension'], 'string')) {
         $smarty->assign("T_JOURNAL_DIMENSIONS", $_GET['dimension']);
         $_SESSION['module_journal_dimension'] = $_GET['dimension'];
     }
     if (isset($_GET['entries_from'])) {
         $smarty->assign("T_JOURNAL_ENTRIES_FROM", $_GET['entries_from']);
         $_SESSION['module_journal_entries_from'] = $_GET['entries_from'];
     }
     if (isset($_GET['delete_rule']) && eF_checkParameter($_GET['delete_rule'], 'id') && in_array($_GET['delete_rule'], array_keys($rules))) {
         try {
             eF_deleteTableData("module_journal_rules", "id=" . $_GET['delete_rule']);
         } catch (Exception $e) {
             handleAjaxExceptions($e);
         }
         exit;
     }
     if (isset($_GET['deactivate_rule']) && eF_checkParameter($_GET['deactivate_rule'], 'id') && in_array($_GET['deactivate_rule'], array_keys($rules))) {
         eF_updateTableData("module_journal_rules", array('active' => 0), "id=" . $_GET['deactivate_rule']);
     }
     if (isset($_GET['activate_rule']) && eF_checkParameter($_GET['activate_rule'], 'id') && in_array($_GET['activate_rule'], array_keys($rules))) {
         eF_updateTableData("module_journal_rules", array('active' => 1), "id=" . $_GET['activate_rule']);
     }
     if (isset($_GET['delete_entry']) && eF_checkParameter($_GET['delete_entry'], 'id') && in_array($_GET['delete_entry'], array_keys($entries))) {
         $object = eF_getTableData("module_journal_entries", "users_LOGIN", "id=" . $_GET['delete_entry']);
         if ($object[0]['users_LOGIN'] != $_SESSION['s_login']) {
             eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_JOURNAL_NOACCESS) . $popup_);
             exit;
         }
         eF_deleteTableData("module_journal_entries", "id=" . $_GET['delete_entry']);
     }
     if (isset($_GET['saveas']) && $_GET['saveas'] == 'pdf') {
         $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
         $pdf->SetCreator(PDF_CREATOR);
         $pdf->SetAuthor(PDF_AUTHOR);
         $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
         $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
         $pdf->setFontSubsetting(false);
         $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
         $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
         $pdf->setHeaderFont(array('Freeserif', 'I', 11));
         $pdf->setFooterFont(array('Freeserif', '', 8));
         $pdf->setHeaderData('', '', '', _JOURNAL_NAME);
         $pdf->AliasNbPages();
         $pdf->AddPage();
         $pdf->SetFont('Freeserif', '', 10);
         $pdf->SetTextColor(0, 0, 0);
         foreach ($entries as $entry) {
             $pdf->Cell(0, 0, $entry['entry_date_formatted'], 0, 1, L, 0);
             $pdf->writeHTML('<br/>', true, false, true, false, '');
             $pdf->writeHTML($entry['entry_body'], true, false, true, false, '');
             $pdf->writeHTML('<div style="height: 5px;"></div>', true, false, true, false, '');
             $pdf->writeHTML('<hr>', true, false, true, false, '');
         }
         $fileNamePdf = "journal.pdf";
         header("Content-type: application/pdf");
         header("Content-disposition: attachment; filename=" . $fileNamePdf);
         echo $pdf->Output('', 'S');
         exit(0);
     }
     if (isset($_GET['saveas']) && $_GET['saveas'] == 'doc') {
         include dirname(__FILE__) . "/classes/html_to_doc.inc.php";
         $entriesHTML = '';
         foreach ($entries as $entry) {
             $entriesHTML .= $entry['entry_date_formatted'];
             $entriesHTML .= $entry['entry_body'];
             $entriesHTML .= '<hr><br/>';
         }
         $htmltodoc = new HTML_TO_DOC();
         $htmltodoc->createDoc($entriesHTML, "journal", true);
         exit(0);
     }
     if (isset($_GET['saveas']) && $_GET['saveas'] == 'txt') {
         include dirname(__FILE__) . "/classes/html2text.inc";
         header('Content-Type: text/plain');
         header('Content-Disposition: attachment; filename="journal.txt"');
         $entriesHTML = '';
         foreach ($entries as $entry) {
             $entriesHTML .= $entry['entry_date_formatted'];
             $entriesHTML .= $entry['entry_body'];
             $entriesHTML .= '<p></p>';
             $entriesHTML .= '_______________________________________________________';
             $entriesHTML .= '<p></p>';
         }
         $htmlToText = new Html2Text($entriesHTML, 100);
         $entriesHTMLtext = $htmlToText->convert();
         echo $entriesHTMLtext;
         exit(0);
     }
     if (isset($_GET['check_students_journals']) && $_GET['check_students_journals'] == '1') {
         $professorJournalLessons = $this->getProfessorJournalLessons($currentUser);
         $journalLessonsStudents = $this->getJournalLessonsStudents($professorJournalLessons);
         $smarty->assign("T_JOURNAL_STUDENTS", $journalLessonsStudents);
     }
     if (isset($_GET['preview_journal']) && $_GET['preview_journal'] == '1' && isset($_GET['student']) && eF_checkParameter($_GET['student'], 'login')) {
         $userLogin = $_GET['student'];
         $professorJournalLessons = $this->getProfessorJournalLessons($currentUser);
         $studentEntries = $this->getStudentEntries($userLogin, $professorJournalLessons);
         $smarty->assign("T_JOURNAL_STUDENT_ENTRIES", $studentEntries);
     }
     if (isset($_REQUEST['autosave']) && $_REQUEST['autosave'] == "1" && isset($_REQUEST['entry_body']) && isset($_REQUEST['edit_entry'])) {
         if ($_REQUEST['edit_entry'] != "-1") {
             if (eF_checkParameter($_GET['edit_entry'], 'id')) {
                 $object = eF_getTableData("module_journal_entries", "lessons_ID", "id=" . $_GET['edit_entry']);
                 $fields = array("entry_body" => $_REQUEST['entry_body'], "entry_date" => date('Y') . '-' . date('m') . '-' . date('d') . ' ' . date('H') . ':' . date('i') . ':' . date('s'), "lessons_ID" => $object[0]['lessons_ID'], "users_LOGIN" => $currentUser->user['login']);
                 eF_updateTableData("module_journal_entries", $fields, "id=" . $_REQUEST['edit_entry']);
             }
         } else {
             $fields = array("entry_body" => $_REQUEST['entry_body'], "entry_date" => date('Y') . '-' . date('m') . '-' . date('d') . ' ' . date('H') . ':' . date('i') . ':' . date('s'), "lessons_ID" => $currentLessonID, "users_LOGIN" => $currentUser->user['login']);
             $id = eF_insertTableData("module_journal_entries", $fields);
             if ($id) {
                 if (isset($_SESSION['module_journal_autosave_entry'])) {
                     $this->deleteAutoSaveEntry();
                     $_SESSION['module_journal_autosave_entry'] = $id;
                 } else {
                     $_SESSION['module_journal_autosave_entry'] = $id;
                 }
             }
         }
         exit(0);
     }
     if (isset($_REQUEST['show_right']) && $_REQUEST['show_right'] == "1" && isset($_REQUEST['entry_body']) && $_REQUEST['entry_body'] != "" && isset($_REQUEST['edit']) && isset($_REQUEST['edit_entry'])) {
         if (isset($_SESSION['module_journal_show_right_entry'])) {
             unset($_SESSION['module_journal_show_right_entry']);
         }
         $_SESSION['module_journal_show_right_entry'] = $_REQUEST['entry_body'];
     }
     if (isset($_REQUEST['hide_right']) && $_REQUEST['hide_right'] == "1" && isset($_REQUEST['entry_body']) && $_REQUEST['entry_body'] != "" && isset($_REQUEST['edit']) && isset($_REQUEST['edit_entry'])) {
         if (isset($_SESSION['module_journal_hide_right_entry'])) {
             unset($_SESSION['module_journal_hide_right_entry']);
         }
         $_SESSION['module_journal_hide_right_entry'] = $_REQUEST['entry_body'];
     }
     if (isset($_REQUEST['hide_left']) && $_REQUEST['hide_left'] == "1" && isset($_REQUEST['entry_body']) && $_REQUEST['entry_body'] != "" && isset($_REQUEST['edit']) && isset($_REQUEST['edit_entry'])) {
         if (isset($_SESSION['module_journal_hide_left_entry'])) {
             unset($_SESSION['module_journal_hide_left_entry']);
         }
         $_SESSION['module_journal_hide_left_entry'] = $_REQUEST['entry_body'];
     }
     if (isset($_REQUEST['scroll_position']) && eF_checkParameter($_REQUEST['scroll_position'], 'id')) {
         $_SESSION['module_journal_scroll_position'] = $_REQUEST['scroll_position'];
     }
     if (isset($_GET['add_rule']) || isset($_GET['edit_rule']) && eF_checkParameter($_GET['edit_rule'], 'id') && in_array($_GET['edit_rule'], array_keys($rules))) {
         if ($_SESSION['s_type'] != "administrator") {
             eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_JOURNAL_NOACCESS));
         }
         isset($_GET['add_rule']) ? $postTarget = "&add_rule=1" : ($postTarget = "&edit_rule=" . $_GET['edit_rule']);
         global $load_editor;
         $load_editor = true;
         $form = new HTML_QuickForm("add_edit_rule_form", "post", $this->moduleBaseUrl . $postTarget, "", null, true);
         $form->addElement('text', 'title', _TITLE, 'class="inputText" style="width:498px;"');
         $form->addRule('title', _THEFIELD . ' "' . _TITLE . '" ' . _ISMANDATORY, 'required', null, 'client');
         $form->addElement('textarea', 'description', _DESCRIPTION, 'class="inputContentTextarea simpleEditor" style="width:500px;height:20em;"');
         $form->addElement('submit', 'submit', _SUBMIT, 'class="flatButton"');
         if (isset($_GET['edit_rule'])) {
             $editRule = $rules[$_GET['edit_rule']];
             $form->setDefaults($editRule);
         }
         if ($form->isSubmitted() && $form->validate()) {
             $values = $form->exportValues();
             $fields = array("title" => $values['title'], "description" => $values['description']);
             if ($values['description'] == '') {
                 $message = _JOURNAL_EMPTY_RULE_DESCRIPTION;
                 if (isset($_GET['add_rule'])) {
                     eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=failure&add_rule=1");
                 } else {
                     eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=failure&edit_rule=" . $_GET['edit_rule']);
                 }
             }
             if (isset($_GET['add_rule'])) {
                 if (eF_insertTableData("module_journal_rules", $fields)) {
                     $message = _JOURNAL_RULE_SUCCESSFULLY_ADDED;
                     eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=success");
                 } else {
                     $message = _JOURNAL_RULE_ADD_PROBLEM;
                     eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=failure");
                 }
             } else {
                 if (eF_updateTableData("module_journal_rules", $fields, "id=" . $_GET['edit_rule'])) {
                     $message = _JOURNAL_RULE_SUCCESSFULLY_EDITED;
                     eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=success");
                 } else {
                     $message = _JOURNAL_RULE_EDIT_PROBLEM;
                     eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=failure");
                 }
             }
         }
         $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
         $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
         $form->setRequiredNote(_REQUIREDNOTE);
         $form->accept($renderer);
         $smarty->assign('T_JOURNAL_ADD_EDIT_RULE_FORM', $renderer->toArray());
     } else {
         $rules = $this->getRules();
         $smarty->assign("T_JOURNAL_RULES", $rules);
         $object = eF_getTableData("module_journal_settings", "value", "name='export'");
         $smarty->assign("T_JOURNAL_ALLOW_EXPORT", $object[0]['value']);
         $object = eF_getTableData("module_journal_settings", "value", "name='preview'");
         $smarty->assign("T_JOURNAL_ALLOW_PROFESSOR_PREVIEW", $object[0]['value']);
         if ($currentUser->getRole($this->getCurrentLesson()) == 'professor' || $currentUser->getRole($this->getCurrentLesson()) == 'student') {
             $activeRules = $this->getRules(true);
             $smarty->assign("T_JOURNAL_ACTIVE_RULES", $activeRules);
             $entries = $this->getEntries($currentUser->user['login'], $_SESSION['module_journal_entries_from']);
             $smarty->assign("T_JOURNAL_ENTRIES", $entries);
             $journalLessons = $this->getJournalLessons($currentUser->user['login']);
             $smarty->assign("T_JOURNAL_LESSONS", $journalLessons);
             /*					*/
             global $load_editor;
             $load_editor = true;
             if (isset($_GET['edit_entry']) && $_GET['edit_entry'] != '-1') {
                 $postTarget = "&edit_entry=" . $_GET['edit_entry'];
             } else {
                 $postTarget = "&add_entry=1";
             }
             if (isset($_GET['hide_right']) && $_GET['hide_right'] == '1') {
                 $editorStyle = array('small' => 'width:588px; height:320px;', 'medium' => 'width:673px; height:375px;', 'large' => 'width:759px; height:430px;');
             } else {
                 $editorStyle = array('small' => 'width:300px; height:320px;', 'medium' => 'width:344px; height:375px;', 'large' => 'width:388px; height:430px;');
             }
             $form = new HTML_QuickForm("add_edit_entry_form", "post", $this->moduleBaseUrl . $postTarget, "", null, true);
             $form->addElement('textarea', 'entry_body', _DESCRIPTION, 'class="inputContentTextarea simpleEditor" style="' . $editorStyle[$_SESSION['module_journal_dimension']] . '"');
             if (isset($_GET['edit_entry']) && $_GET['edit_entry'] != '-1') {
                 $form->addElement('submit', 'submit', _UPDATE . ' ' . _JOURNAL_ENTRY, 'class="flatButton"');
             } else {
                 $form->addElement('submit', 'submit', _SAVE . ' ' . _JOURNAL_ENTRY, 'class="flatButton"');
             }
             if (isset($_GET['edit_entry']) && $_GET['edit_entry'] != '-1') {
                 $editEntry = $entries[$_GET['edit_entry']];
                 $form->setDefaults($editEntry);
                 if (!in_array($_GET['edit_entry'], array_keys($entries))) {
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_JOURNAL_NOACCESS) . $popup_);
                 }
                 $object = eF_getTableData("module_journal_entries", "lessons_ID, users_LOGIN, entry_date", "id=" . $_GET['edit_entry']);
                 if ($object[0]['users_LOGIN'] != $_SESSION['s_login']) {
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_JOURNAL_NOACCESS) . $popup_);
                 }
             }
             if (isset($_GET['show_left']) && $_GET['show_left'] == '1' && isset($_GET['edit']) && isset($_GET['edit_entry'])) {
                 if (isset($_SESSION['module_journal_hide_left_entry'])) {
                     $form->setDefaults(array("entry_body" => $_SESSION['module_journal_hide_left_entry']));
                     unset($_SESSION['module_journal_hide_left_entry']);
                 }
             }
             if (isset($_GET['show_right']) && $_GET['show_right'] == '1' && isset($_GET['edit']) && isset($_GET['edit_entry'])) {
                 if (isset($_SESSION['module_journal_show_right_entry'])) {
                     $form->setDefaults(array("entry_body" => $_SESSION['module_journal_show_right_entry']));
                     unset($_SESSION['module_journal_show_right_entry']);
                 }
             }
             if (isset($_GET['hide_right']) && $_GET['hide_right'] == '1' && isset($_GET['edit']) && isset($_GET['edit_entry'])) {
                 if (isset($_SESSION['module_journal_hide_right_entry'])) {
                     $form->setDefaults(array("entry_body" => $_SESSION['module_journal_hide_right_entry']));
                     unset($_SESSION['module_journal_hide_right_entry']);
                 }
             }
             if ($form->isSubmitted() && $form->validate()) {
                 $values = $form->exportValues();
                 isset($_GET['add_entry']) ? $lessonID = $currentLessonID : ($lessonID = $object[0]['lessons_ID']);
                 if (isset($_GET['add_entry'])) {
                     $date = date('Y') . '-' . date('m') . '-' . date('d') . ' ' . date('H') . ':' . date('i') . ':' . date('s');
                 } else {
                     $date = $object[0]['entry_date'];
                 }
                 $fields = array("entry_body" => $values['entry_body'], "entry_date" => $date, "lessons_ID" => $lessonID, "users_LOGIN" => $currentUser->user['login']);
                 if ($values['entry_body'] == '') {
                     $message = _JOURNAL_EMPTY_ENTRY_BODY;
                     eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=failure" . $popup_);
                 }
                 if (isset($_GET['add_entry'])) {
                     if (eF_insertTableData("module_journal_entries", $fields)) {
                         if (isset($_SESSION['module_journal_autosave_entry'])) {
                             $this->deleteAutoSaveEntry();
                         }
                         $message = _JOURNAL_ENTRY_SUCCESSFULLY_ADDED;
                         eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=success" . $popup_);
                     } else {
                         $message = _JOURNAL_ENTRY_ADD_PROBLEM;
                         eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=failure" . $popup_);
                     }
                 } else {
                     if (eF_updateTableData("module_journal_entries", $fields, "id=" . $_GET['edit_entry'])) {
                         $message = _JOURNAL_ENTRY_SUCCESSFULLY_EDITED;
                         eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=success" . $popup_);
                     } else {
                         $message = _JOURNAL_ENTRY_EDIT_PROBLEM;
                         eF_redirect($this->moduleBaseUrl . "&message=" . $message . "&message_type=failure" . $popup_);
                     }
                 }
             }
             $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
             $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
             $form->setRequiredNote(_REQUIREDNOTE);
             $form->accept($renderer);
             $smarty->assign('T_JOURNAL_ADD_ENTRY_FORM', $renderer->toArray());
             if ($currentUser->getRole($this->getCurrentLesson()) == 'professor') {
                 $popupInfo[] = array('text' => _JOURNAL_POPUP_INFO, 'image' => $this->moduleBaseLink . 'images/info.png', 'href' => $this->moduleBaseUrl . '&popup_info=1&popup=1', 'onClick' => "eF_js_showDivPopup(event, '" . _JOURNAL_POPUP_INFO . "', 2)", 'target' => 'POPUP_FRAME', 'id' => 'popup_info');
                 $smarty->assign("T_JOURNAL_POPUP_INFO", $popupInfo);
             }
         }
     }
     if ($currentUser->getType() == 'administrator') {
         return $this->moduleBaseDir . "module_journal_admin.tpl";
     } else {
         if ($currentUser->getRole($this->getCurrentLesson()) == 'professor' || $currentUser->getRole($this->getCurrentLesson()) == 'student') {
             if (isset($_GET['hide_left']) && $_GET['hide_left'] == '1') {
                 return $this->moduleBaseDir . "module_journal_user_right.tpl";
             }
             if (isset($_GET['hide_right']) && $_GET['hide_right'] == '1') {
                 return $this->moduleBaseDir . "module_journal_user_left.tpl";
             }
             return $this->moduleBaseDir . "module_journal_user.tpl";
         }
     }
 }
 //Register this rule for checking user input with our function, eF_checkParameter
 $createForm->addElement('text', 'english_name', _ENGLISHNAME, 'class = "inputText" id = "language_name"');
 $createForm->addElement('text', 'translation', _TRANSLATION, 'class = "inputText" id = "language_translation"');
 $createForm->addElement("advcheckbox", "rtl", _RTLLANGUAGE, null, 'class = "inputCheckBox" id = "language_rtl"', array(0, 1));
 $createForm->addElement("advcheckbox", "custom", _CUSTOMLANGUAGEFILE, null, 'class = "inputCheckBox" id = "custom_language"', array(0, 1));
 $createForm->addElement('file', 'language_upload', _FILENAME, 'class = "inputText"');
 $createForm->addElement('hidden', 'selected_language', null, 'id = "selected_language"');
 $createForm->addElement('submit', 'submit_upload_language', _SUBMIT, 'class = "flatButton"');
 $createForm->setMaxFileSize(FileSystemTree::getUploadMaxSize() * 1024);
 //getUploadMaxSize returns size in KB
 $createForm->addRule('english_name', _THEFIELD . ' "' . _ENGLISHNAME . '" ' . _ISMANDATORY, 'required', null, 'client');
 $createForm->addRule('english_name', _INVALIDFIELDDATA . ': ' . _ENGLISHNAME, 'checkParameter', 'file');
 $createForm->addRule('translation', _THEFIELD . ' "' . _TRANSLATION . '" ' . _ISMANDATORY, 'required', null, 'client');
 //$createForm -> addRule('language_upload', _THEFIELD.' "'._FILENAME.'" '._ISMANDATORY, 'required', null, 'client');
 if ($createForm->isSubmitted() && $createForm->validate()) {
     $values = $createForm->exportValues();
     try {
         if ($values['selected_language']) {
             if ($_FILES['language_upload']['error'] == 0) {
                 $filesystem = new FileSystemTree(G_ROOTPATH . 'libraries/language');
                 $uploadedFile = $filesystem->uploadFile('language_upload', G_ROOTPATH . 'libraries/language');
                 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);
                 }
             }
             $fields = array("name" => $values['english_name'], "translation" => $values['translation'], "rtl" => $values['rtl']);
             eF_updateTableData("languages", $fields, "name='" . $values['selected_language'] . "'");
             EfrontCache::getInstance()->deleteCache('languages');
             //include "editor/tiny_mce/langs/language.php";
Example #11
0
    public static function mobile_rb_edit($tab,$id) {
        if($id===false)
            $rec = array();
        else
            $rec = self::get_record($tab,$id);
        $cols = Utils_RecordBrowserCommon::init($tab);

        $defaults = array();
        if($id===false) {
            $mode = 'add';
            $access = array();
			$defaults = self::record_processing($tab, $defaults, 'adding');
        } else {
            $mode = 'edit';
            $access = Utils_RecordBrowserCommon::get_access($tab, 'view',$rec);
            if (is_array($access))
                foreach ($access as $k=>$v)
                    if (!$v) unset($rec[$k]);
            $defaults = $rec = self::record_processing($tab, $rec, 'editing');
        }

        $QFfield_callback_table = array();
        $ret = DB::Execute('SELECT * FROM '.$tab.'_callback WHERE freezed=0');
        while ($row = $ret->FetchRow()) {
            $QFfield_callback_table[$row['field']] = explode('::',$row['callback']);
        }
        $defaults = array_merge($defaults,$_SESSION['rb_'.$tab.'_defaults']);

        $qf = new HTML_QuickForm('rb_edit', 'post', 'mobile.php?'.http_build_query($_GET));
        foreach($cols as $field=>$args) {
            if(isset($access[$args['id']]) && !$access[$args['id']]) continue;

            if(isset($rec[$args['id']]))
                $val = $rec[$args['id']];
            elseif(isset($defaults[$args['id']]))
                $val = $defaults[$args['id']];
            else
                $val = null;
            $label = _V($args['name']); // TRSL
            if(isset($QFfield_callback_table[$field])) {
                $ff = $QFfield_callback_table[$field];
				$mobile_rb = new Utils_RecordBrowserMobile($tab, $rec);
                call_user_func_array($ff, array(&$qf, $args['id'], $label, $mode, $val, $args, $mobile_rb, null));
                if($mode=='edit')
                    unset($defaults[$args['id']]);
                continue;
            }

            switch ($args['type']) {
                case 'calculated':
                    $qf->addElement('static', $args['id'], $label);
                    if (!is_array($rec))
                        $values = $defaults;
                    else {
                        $values = $rec;
                        if (is_array($defaults)) $values = $values + $defaults;
                    }
                    if(!isset($values[$args['id']])) $values[$args['id']] = '';
                    $val = Utils_RecordBrowserCommon::get_val($tab, $field, $values, true, $args);
                    if ($val !== null)
                        $qf->setDefaults(array($args['id'] => $val));
                    break;
                case 'integer':
                case 'float':
                    $qf->addElement('text', $args['id'], $label);
                    if ($args['type'] == 'integer')
                        $qf->addRule($args['id'], __('Only integer numbers are allowed.'), 'regex', '/^[0-9]*$/');
                    else
                        $qf->addRule($args['id'], __('Only numbers are allowed.'), 'numeric');
                    if ($val !== null)
                        $qf->setDefaults(array($args['id'] => $val));
                    break;
                case 'checkbox':
                    $qf->addElement('checkbox', $args['id'], $label, '');
                    if ($val !== null)
                        $qf->setDefaults(array($args['id'] => $val));
                    break;
                case 'currency':
                    $qf->addElement('currency', $args['id'], $label);
                    if ($val !== null)
                        $qf->setDefaults(array($args['id'] => $val));
                    break;
                case 'text':
                    $qf->addElement('text', $args['id'], $label, array('maxlength' => $args['param']));
                    $qf->addRule($args['id'], __('Maximum length for this field is %s characters.', array($args['param'])), 'maxlength', $args['param']);
                    if ($val !== null)
                        $qf->setDefaults(array($args['id'] => $val));
                    break;
                case 'long text':
                    $qf->addElement('textarea', $args['id'], $label, array('maxlength' => 200));
                    $qf->addRule($args['id'], __('Maximum length for this field in mobile edition is 200 chars.'), 'maxlengt', 200);
                    if ($val !== null)
                        $qf->setDefaults(array($args['id'] => $val));
                    break;
                case 'commondata':
                    $param = explode('::', $args['param']['array_id']);
                    foreach ($param as $k => $v) if ($k != 0) $param[$k] = self::get_field_id($v);
                    if (count($param) == 1) {
                        $qf->addElement($args['type'], $args['id'], $label, $param, array('empty_option' => true, 'id' => $args['id'], 'order_by_key' => $args['param']['order_by_key']));
                        if ($val !== null)
                            $qf->setDefaults(array($args['id'] => $val));
                    }
                    break;
                case 'select':      $comp = array();
                            $ref = explode(';',$args['param']);
                            if (isset($ref[1])) $crits_callback = $ref[1];
                                else $crits_callback = null;
                            if (isset($ref[2])) $multi_adv_params = call_user_func(explode('::',$ref[2]));
                                else $multi_adv_params = null;
                            if (!isset($multi_adv_params) || !is_array($multi_adv_params)) $multi_adv_params = array();
                            if (!isset($multi_adv_params['order'])) $multi_adv_params['order'] = array();
                            if (!isset($multi_adv_params['cols'])) $multi_adv_params['cols'] = array();
                            if (!isset($multi_adv_params['format_callback'])) $multi_adv_params['format_callback'] = array();
                            $ref = $ref[0];
                            @(list($tab2, $col) = explode('::',$ref));
                            if (!isset($col)) trigger_error($field);
                            if($tab2=='__RECORDSETS__') continue; //skip multi recordsets chained selector
                            if ($tab2=='__COMMON__') {
                                $data = Utils_CommonDataCommon::get_translated_tree($col);
                                if (!is_array($data)) $data = array();
                                $comp = $comp+$data;
                            } else {
                                if (isset($crits_callback)) {
                                    $crit_callback = explode('::',$crits_callback);
                                    if (is_callable($crit_callback)) {
                                        $crits = call_user_func($crit_callback, false, $rec);
                                        $adv_crits = call_user_func($crit_callback, true, $rec);
                                    } else $crits = $adv_crits = array();
                                    if ($adv_crits === $crits) $adv_crits = null;
                                    if ($adv_crits !== null) {
                                        continue; //skip record picker
                                    }
                                } else $crits = array();
                                $col = explode('|',$col);
                                $col_id = array();
                                foreach ($col as $c) $col_id[] = self::get_field_id($c);
                                $records = Utils_RecordBrowserCommon::get_records($tab2, $crits, empty($multi_adv_params['format_callback'])?$col_id:array(), !empty($multi_adv_params['order'])?$multi_adv_params['order']:array());
                                $ext_rec = array();
                                if (isset($rec[$args['id']])) {
                                    if (!is_array($rec[$args['id']])) {
                                        if ($rec[$args['id']]!='') $rec[$args['id']] = array($rec[$args['id']]=>$rec[$args['id']]); else $rec[$args['id']] = array();
                                    }
                                }
                                if (isset($defaults[$args['id']])) {
                                    if (!is_array($defaults[$args['id']]))
                                        $rec[$args['id']][$defaults[$args['id']]] = $defaults[$args['id']];
                                    else {
                                        foreach ($defaults[$args['id']] as $v)
                                            $rec[$args['id']][$v] = $v;
                                    }
                                }
                                $single_column = (count($col_id)==1);
                                if (isset($rec[$args['id']])) {
                                    $ext_rec = array_flip($rec[$args['id']]);
                                    foreach($ext_rec as $k=>$v) {
                                        $c = Utils_RecordBrowserCommon::get_record($tab2, $k);
                                        if (!empty($multi_adv_params['format_callback'])) $n = call_user_func($multi_adv_params['format_callback'], $c);
                                        else {
                                            if ($single_column) $n = $c[$col_id[0]];
                                            else {
                                                $n = array();
                                                foreach ($col_id as $cid) $n[] = $c[$cid];
                                                $n = implode(' ',$n);
                                            }
                                        }
                                        $comp[$k] = $n;
                                    }
                                }
                                if (!empty($multi_adv_params['order'])) natcasesort($comp);
                                foreach ($records as $k=>$v) {
                                    if (!empty($multi_adv_params['format_callback'])) $n = call_user_func($multi_adv_params['format_callback'], $v);
                                    else {
//                                      $n = $v[$col_id];
                                        if ($single_column) $n = $v[$col_id[0]];
                                        else {
                                            $n = array();
                                            foreach ($col_id as $cid) $n[] = $v[$cid];
                                            $n = implode(' ',$n);
                                        }
                                    }
                                    $comp[$k] = $n;
                                    unset($ext_rec[$v['id']]);
                                }
                                if (empty($multi_adv_params['order'])) natcasesort($comp);
                            }
                            if ($args['type']==='select') $comp = array(''=>'---')+$comp;
                            $qf->addElement($args['type'], $args['id'], $label, $comp, array('id'=>$args['id']));
                            if($id!==false)
                                $qf->setDefaults(array($args['id']=>$rec[$args['id']]));
                            break;
                case 'date':        $qf->addElement('date',$args['id'],$label,array('format'=>'d M Y', 'minYear'=>date('Y')-95,'maxYear'=>date('Y')+5, 'addEmptyOption'=>true, 'emptyOptionText'=>'--'));
                            if ($val)
                                $qf->setDefaults(array($args['id'] => $val));
                            break;
                case 'timestamp':   $qf->addElement('date',$args['id'],$label,array('format'=>'d M Y H:i', 'minYear'=>date('Y')-95,'maxYear'=>date('Y')+5, 'addEmptyOption'=>true, 'emptyOptionText'=>'--'));
                            if($val) {
                                $default = Base_RegionalSettingsCommon::time2reg($val, true, true, true, false);
                                $qf->setDefaults(array($args['id'] => $default));
                            }
                            break;
                case 'time':        $qf->addElement('date',$args['id'],$label,array('format'=>'H:i', 'addEmptyOption'=>true, 'emptyOptionText'=>'--'));
                            if($val) {
                                $default = Base_RegionalSettingsCommon::time2reg($val, true, true, true, false);
                                $qf->setDefaults(array($args['id'] => $default));
                            }
                            break;
                case 'multiselect': //ignore
                            if($id===false) continue;
                            $val = Utils_RecordBrowserCommon::get_val($tab,$field,$rec,true,$args);
                            if($val==='') continue;
                            $qf->addElement('static',$args['id'],$label);
                            $qf->setDefaults(array($args['id']=>$val));
                            unset($defaults[$args['id']]);
                            break;
            }
            if($args['required'])
                $qf->addRule($args['id'],__('Field required'),'required');
        }

        $qf->addElement('submit', 'submit_button', __('Save'),IPHONE?'class="button white"':'');

        if($qf->validate()) {
            $values = $qf->exportValues();
            foreach ($cols as $v) {
                if ($v['type']=='checkbox' && !isset($values[$v['id']])) $values[$v['id']]=0;
                elseif($v['type']=='date') {
                    if(is_array($values[$v['id']]) && $values[$v['id']]['Y']!=='' && $values[$v['id']]['M']!=='' && $values[$v['id']]['d']!=='')
                        $values[$v['id']] = sprintf("%d-%02d-%02d", $values[$v['id']]['Y'], $values[$v['id']]['M'], $values[$v['id']]['d']);
                    else
                        $values[$v['id']] = '';
                } elseif($v['type']=='timestamp') {
                    if($values[$v['id']]['Y']!=='' && $values[$v['id']]['M']!=='' && $values[$v['id']]['d']!=='' && $values[$v['id']]['H']!=='' && $values[$v['id']]['i']!=='') {
                        $timestamp = $values[$v['id']]['Y'] . '-' . $values[$v['id']]['M'] . '-' . $values[$v['id']]['d'] . ' ' . $values[$v['id']]['H'] . ':' . $values[$v['id']]['i'];
                        $values[$v['id']] = Base_RegionalSettingsCommon::reg2time($timestamp, true);
                    } else
                        $values[$v['id']] = '';
                } elseif($v['type']=='time') {
                    if($values[$v['id']]['H']!=='' && $values[$v['id']]['i']!=='') {
                        $time = recalculate_time(date('Y-m-d'), $values[$v['id']]);
                        $timestamp = Base_RegionalSettingsCommon::reg2time(date('1970-01-01 H:i:s', $time), true);
                        $values[$v['id']] = date('1970-01-01 H:i:s', $timestamp);
                    } else
                        $values[$v['id']] = '';
                }
            }
            foreach ($defaults as $k=>$v)
                if (!isset($values[$k])) $values[$k] = $v;
            if($id!==false) {
                $values['id'] = $id;
                Utils_RecordBrowserCommon::update_record($tab, $id, $values);
            } else {
                $id = Utils_RecordBrowserCommon::new_record($tab, $values);
            }
            return false;
        }

        $renderer =& $qf->defaultRenderer();
        $qf->accept($renderer);
        print($renderer->toHtml());
    }
    //$modeForm -> addElement("select", "mode_social_events",  _EVENTSLOGGING, $modes);
    $modeForm->addElement("select", "mode_system_timeline", _SYSTEMTIMELINES, $modes);
    $modeForm->addElement("select", "mode_lessons_timeline", _LESSONTIMELINES, $modes);
    $modeForm->addElement("select", "mode_func_people", _PEOPLECONNECTIONS, $modes);
    $modeForm->addElement("select", "mode_func_comments", _COMMENTSWALL, $modes);
    $modeForm->addElement("select", "mode_func_userstatus", _USERSTATUS, $modes);
}
#cpp#endif
$modeForm->setDefaults($GLOBALS['configuration']);
if (isset($currentUser->coreAccess['configuration']) && $currentUser->coreAccess['configuration'] != 'change') {
    $modeForm->freeze();
} else {
    $modeForm->addElement("submit", "submit", _SAVE, 'class = "flatButton"');
    if ($modeForm->isSubmitted() && $modeForm->validate()) {
        //If the form is submitted and validated
        $values = $modeForm->exportValues();
        unset($values['submit']);
        foreach ($values as $key => $value) {
            EfrontConfiguration::setValue($key, $value);
        }
        //@TODO review by mixalis
        /*
        		$socialModulesToBeActivated = 
        		EfrontUser::isOptionVisible('system_timeline') &
        		EfrontUser::isOptionVisible('lessons_timeline') &
        		EfrontUser::isOptionVisible('func_people') &
        		EfrontUser::isOptionVisible('func_comments') &
        		EfrontUser::isOptionVisible('func_userstatus');
        vd($socialModulesToBeActivated);
        */
        //EfrontConfiguration :: setValue('social_modules_activated', $socialModulesToBeActivated);
Example #13
0
} else {
    $checkbox->setChecked(false);
}
$sql_input_form->addElement('submit', 'execute_sql', 'Run Query');
if (isset($_SESSION['sql_select'])) {
    $sql_input_form->setDefaults(array('sql_select' => $_SESSION['sql_select'], 'sql_from' => $_SESSION['sql_from'], 'sql_where' => $_SESSION['sql_where'], 'sql_order' => $_SESSION['sql_order'], 'sql_order_dir' => $_SESSION['sql_order_dir'], 'sql_limit' => $_SESSION['sql_limit'], 'chart_period' => $_SESSION['chart_period']));
} else {
    $sql_input_form->setDefaults(array('sql_limit' => 10, 'sql_order_dir' => 'desc', 'chart_period' => 180));
}
if (isset($_POST['execute_sql'])) {
    if ($sql_input_form->validate()) {
        print '<table border="1" cellpadding="5" cellspacing="0" align="center"><tr><td align="center">';
        $sql_input_form->display();
        print '</td></tr>';
        // run the sql and return the results
        $data = $sql_input_form->exportValues();
        $_SESSION['sql_select'] = $sql_select = $data['sql_select'];
        $_SESSION['sql_from'] = $sql_from = $data['sql_from'];
        $_SESSION['sql_where'] = $sql_where = $data['sql_where'];
        $_SESSION['sql_order'] = $sql_order = $data['sql_order'];
        $_SESSION['sql_order_dir'] = $sql_order_dir = $data['sql_order_dir'];
        $_SESSION['sql_limit'] = $sql_limit = $data['sql_limit'];
        $_SESSION['chart_period'] = $chart_period = $data['chart_period'];
        $query = "select {$sql_select} from {$sql_from} where ({$sql_where}) and (quotes.date = '{$pf_working_date}' and quotes.exch = '{$pf_exch}') order by {$sql_order} {$sql_order_dir} limit {$sql_limit};";
        try {
            $pdo = new PDO("pgsql:host={$db_hostname};dbname={$db_database}", $db_user, $db_password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            die("ERROR: Cannot connect: " . $e->getMessage());
        }
        print '<tr>';
 public function getSmartyTpl()
 {
     $currentUser = $this->getCurrentUser();
     $smarty = $this->getSmartyVar();
     $ranges = $this->getRanges();
     $smarty->assign("T_GRADEBOOK_BASEURL", $this->moduleBaseUrl);
     $smarty->assign("T_GRADEBOOK_BASELINK", $this->moduleBaseLink);
     if ($currentUser->getRole($this->getCurrentLesson()) == 'professor') {
         $currentLesson = $this->getCurrentLesson();
         $currentLessonID = $currentLesson->lesson['id'];
         $lessonUsers = $currentLesson->getUsers('student');
         // get all students that have this lesson
         $lessonColumns = $this->getLessonColumns($currentLessonID);
         $allUsers = $this->getLessonUsers($currentLessonID, $lessonColumns);
         $gradeBookLessons = $this->getGradebookLessons($currentUser->getLessons(false, 'professor'), $currentLessonID);
     } else {
         if ($currentUser->getRole($this->getCurrentLesson()) == 'student') {
             $currentLesson = $this->getCurrentLesson();
             $currentLessonID = $currentLesson->lesson['id'];
         }
     }
     if (isset($_GET['import_grades']) && eF_checkParameter($_GET['import_grades'], 'id') && in_array($_GET['import_grades'], array_keys($lessonColumns))) {
         $object = eF_getTableData("module_gradebook_objects", "creator", "id=" . $_GET['import_grades']);
         //if($object[0]['creator'] != $_SESSION['s_login']){
         if ($currentUser->getRole($this->getCurrentLesson()) != 'professor') {
             eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_GRADEBOOK_NOACCESS));
             exit;
         }
         $result = eF_getTableData("module_gradebook_objects", "refers_to_type, refers_to_id", "id=" . $_GET['import_grades']);
         $type = $result[0]['refers_to_type'];
         $id = $result[0]['refers_to_id'];
         $oid = $_GET['import_grades'];
         foreach ($lessonUsers as $userLogin => $value) {
             $this->importGrades($type, $id, $oid, $userLogin);
         }
     } else {
         if (isset($_GET['delete_column']) && eF_checkParameter($_GET['delete_column'], 'id') && in_array($_GET['delete_column'], array_keys($lessonColumns))) {
             $object = eF_getTableData("module_gradebook_objects", "creator", "id=" . $_GET['delete_column']);
             //if($object[0]['creator'] != $_SESSION['s_login']){
             if ($currentUser->getRole($this->getCurrentLesson()) != 'professor') {
                 eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_GRADEBOOK_NOACCESS));
                 exit;
             }
             eF_deleteTableData("module_gradebook_objects", "id=" . $_GET['delete_column']);
             eF_deleteTableData("module_gradebook_grades", "oid=" . $_GET['delete_column']);
         } else {
             if (isset($_GET['compute_score_grade']) && $_GET['compute_score_grade'] == '1') {
                 foreach ($allUsers as $uid => $student) {
                     $this->computeScoreGrade($lessonColumns, $ranges, $student['users_LOGIN'], $uid);
                 }
             } else {
                 if (isset($_GET['export_excel']) && ($_GET['export_excel'] == 'one' || $_GET['export_excel'] == 'all')) {
                     require_once 'Spreadsheet/Excel/Writer.php';
                     $workBook = new Spreadsheet_Excel_Writer();
                     $workBook->setTempDir(G_UPLOADPATH);
                     $workBook->setVersion(8);
                     $workBook->send('GradeBook.xls');
                     if ($_GET['export_excel'] == 'one') {
                         $workSheet =& $workBook->addWorksheet($currentLesson->lesson['name']);
                         $this->professorLessonToExcel($currentLessonID, $currentLesson->lesson['name'], $workBook, $workSheet);
                     } else {
                         if ($_GET['export_excel'] == 'all') {
                             $professorLessons = $currentUser->getLessons(false, 'professor');
                             foreach ($professorLessons as $key => $value) {
                                 $subLesson = new EfrontLesson($key);
                                 $subLessonUsers = $subLesson->getUsers('student');
                                 // get all students that have this lesson
                                 $result = eF_getTableData("module_gradebook_users", "count(uid) as total_users", "lessons_ID=" . $key);
                                 if ($result[0]['total_users'] != 0) {
                                     // module installed for this lesson
                                     $workSheet =& $workBook->addWorksheet($subLesson->lesson['name']);
                                     $this->professorLessonToExcel($key, $subLesson->lesson['name'], $workBook, $workSheet);
                                 }
                             }
                         }
                     }
                     $workBook->close();
                     exit;
                 } else {
                     if (isset($_GET['export_student_excel']) && ($_GET['export_student_excel'] == 'current' || $_GET['export_student_excel'] == 'all')) {
                         require_once 'Spreadsheet/Excel/Writer.php';
                         $workBook = new Spreadsheet_Excel_Writer();
                         $workBook->setTempDir(G_UPLOADPATH);
                         $workBook->setVersion(8);
                         $workBook->send('GradeBook.xls');
                         if ($_GET['export_student_excel'] == 'current') {
                             $workSheet =& $workBook->addWorksheet($currentLesson->lesson['name']);
                             $this->studentLessonToExcel($currentLessonID, $currentLesson->lesson['name'], $currentUser, $workBook, $workSheet);
                         } else {
                             if ($_GET['export_student_excel'] == 'all') {
                                 $studentLessons = $currentUser->getLessons(false, 'student');
                                 foreach ($studentLessons as $key => $value) {
                                     // Is GradeBook installed for this lesson ?
                                     $installed = eF_getTableData("module_gradebook_users", "*", "lessons_ID=" . $key . " and users_LOGIN='******'login'] . "'");
                                     if (sizeof($installed) != 0) {
                                         $subLesson = new EfrontLesson($key);
                                         $workSheet =& $workBook->addWorksheet($subLesson->lesson['name']);
                                         $this->studentLessonToExcel($key, $subLesson->lesson['name'], $currentUser, $workBook, $workSheet);
                                     }
                                 }
                             }
                         }
                         $workBook->close();
                         exit;
                     } else {
                         if (isset($_GET['switch_lesson']) && eF_checkParameter($_GET['switch_lesson'], 'id') && in_array($_GET['switch_lesson'], array_keys($gradeBookLessons))) {
                             $lessonID = $_GET['switch_lesson'];
                             eF_redirect("location:" . $this->moduleBaseUrl . "&lessons_ID=" . $lessonID);
                         }
                     }
                 }
             }
         }
     }
     if (isset($_GET['delete_range']) && eF_checkParameter($_GET['delete_range'], 'id') && in_array($_GET['delete_range'], array_keys($ranges))) {
         try {
             eF_deleteTableData("module_gradebook_ranges", "id=" . $_GET['delete_range']);
         } catch (Exception $e) {
             handleAjaxExceptions($e);
         }
         exit;
     } else {
         if (isset($_GET['add_range']) || isset($_GET['edit_range']) && eF_checkParameter($_GET['edit_range'], 'id') && in_array($_GET['edit_range'], array_keys($ranges))) {
             $grades = array();
             for ($i = 0; $i <= 100; $i++) {
                 $grades[$i] = $i;
             }
             isset($_GET['add_range']) ? $postTarget = "&add_range=1" : ($postTarget = "&edit_range=" . $_GET['edit_range']);
             $form = new HTML_QuickForm("add_range_form", "post", $this->moduleBaseUrl . $postTarget, "", null, true);
             $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
             // XXX
             $form->addElement('select', 'range_from', _GRADEBOOK_RANGE_FROM, $grades);
             $form->addElement('select', 'range_to', _GRADEBOOK_RANGE_TO, $grades);
             $form->addElement('text', 'grade', _GRADEBOOK_GRADE, 'class = "inputText"');
             $form->addRule('grade', _THEFIELD . ' "' . _GRADEBOOK_GRADE . '" ' . _ISMANDATORY, 'required', null, 'client');
             $form->addRule('grade', _INVALIDFIELDDATA, 'checkParameter', 'text');
             // XXX
             $form->addElement('submit', 'submit', _SUBMIT, 'class = "flatButton"');
             if (isset($_GET['edit_range'])) {
                 $editRange = $ranges[$_GET['edit_range']];
                 $form->setDefaults($editRange);
             }
             if ($form->isSubmitted() && $form->validate()) {
                 $error = $invalid_range = false;
                 $values = $form->exportValues();
                 $fields = array("range_from" => $values['range_from'], "range_to" => $values['range_to'], "grade" => $values['grade']);
                 if (isset($_GET['edit_range'])) {
                     // do not check it below ...
                     unset($ranges[$_GET['edit_range']]);
                 }
                 foreach ($ranges as $range) {
                     if ($range['grade'] == $fields['grade']) {
                         $message = _GRADEBOOK_GRADE . " '" . $fields['grade'] . "' " . _GRADEBOOK_ALREADY_EXISTS;
                         $message_type = 'failure';
                         $error = true;
                         break;
                     }
                     if ($fields['range_from'] >= $range['range_from'] && $fields['range_to'] <= $range['range_to']) {
                         $invalid_range = true;
                     }
                     if ($fields['range_from'] >= $range['range_from'] && $fields['range_from'] < $range['range_to'] && $fields['range_to'] >= $range['range_to']) {
                         $invalid_range = true;
                     }
                     if ($fields['range_to'] > $range['range_from'] && $fields['range_to'] <= $range['range_to']) {
                         $invalid_range = true;
                     }
                     if ($fields['range_from'] <= $range['range_from'] && $fields['range_to'] >= $range['range_to']) {
                         $invalid_range = true;
                     }
                     if ($invalid_range) {
                         $message = _GRADEBOOK_INVALID_RANGE . ". " . _GRADEBOOK_RANGE;
                         $message .= " [" . $range['range_from'] . ", " . $range['range_to'] . "]" . " " . _GRADEBOOK_ALREADY_EXISTS;
                         $message_type = 'failure';
                         $error = true;
                         break;
                     }
                 }
                 if ($fields['range_from'] > $fields['range_to']) {
                     $message = _GRADEBOOK_RANGE_FROM . ' ' . _GRADEBOOK_GRATER_THAN . ' ' . _GRADEBOOK_RANGE_TO;
                     $message_type = 'failure';
                     $error = true;
                 }
                 if ($error == false) {
                     if (isset($_GET['add_range'])) {
                         if (eF_insertTableData("module_gradebook_ranges", $fields)) {
                             $smarty->assign("T_GRADEBOOK_MESSAGE", _GRADEBOOK_RANGE_SUCCESSFULLY_ADDED);
                         } else {
                             $message = _GRADEBOOK_RANGE_ADD_PROBLEM;
                             $message_type = 'failure';
                         }
                     } else {
                         if (eF_updateTableData("module_gradebook_ranges", $fields, "id=" . $_GET['edit_range'])) {
                             $smarty->assign("T_GRADEBOOK_MESSAGE", _GRADEBOOK_RANGE_SUCCESSFULLY_EDITED);
                         } else {
                             $message = _GRADEBOOK_RANGE_EDIT_PROBLEM;
                             $message_type = 'failure';
                         }
                     }
                 }
             }
             $renderer = prepareFormRenderer($form);
             $form->accept($renderer);
             $smarty->assign('T_GRADEBOOK_ADD_EDIT_RANGE_FORM', $renderer->toArray());
         } else {
             if (isset($_GET['add_column'])) {
                 $tests = $currentLesson->getTests(true, true);
                 $scormTests = $currentLesson->getScormTests();
                 $projects = $currentLesson->getProjects(false);
                 $weights = array();
                 $refersTo = array("real_world" => _GRADEBOOK_REAL_WORLD_OBJECT, "progress" => _LESSONPROGRESS);
                 for ($i = 1; $i <= 10; $i++) {
                     $weights[$i] = $i;
                 }
                 if ($currentLesson->options['tests'] == 1) {
                     foreach ($tests as $key => $test) {
                         $refersTo['test_' . $key] = _TEST . ': ' . $test->test['name'];
                     }
                 }
                 if ($currentLesson->options['scorm'] == 1) {
                     foreach ($scormTests as $key => $scormTest) {
                         $scorm = eF_getTableData("content", "name", "id=" . $scormTest);
                         $refersTo['scormtest_' . $scormTest] = _SCORM . ' ' . _TEST . ': ' . $scorm[0]['name'];
                     }
                 }
                 if ($currentLesson->options['projects'] == 1) {
                     foreach ($projects as $key => $project) {
                         $refersTo['project_' . $key] = _PROJECT . ': ' . $project['title'];
                     }
                 }
                 $form = new HTML_QuickForm("add_column_form", "post", $this->moduleBaseUrl . "&add_column=1", "", null, true);
                 $form->addElement('text', 'column_name', _GRADEBOOK_COLUMN_NAME, 'class = "inputText"');
                 $form->addElement('select', 'column_weight', _GRADEBOOK_COLUMN_WEIGHT, $weights);
                 $form->addElement('select', 'column_refers_to', _GRADEBOOK_COLUMN_REFERS_TO, $refersTo);
                 $form->addRule('column_name', _THEFIELD . ' "' . _GRADEBOOK_COLUMN_NAME . '" ' . _ISMANDATORY, 'required', null, 'client');
                 $form->addElement('submit', 'submit', _SUBMIT, 'class = "flatButton"');
                 if ($form->isSubmitted() && $form->validate()) {
                     $values = $form->exportValues();
                     $fields = array("name" => $values['column_name'], "weight" => $values['column_weight'], "lessons_ID" => $currentLessonID, "creator" => $_SESSION['s_login']);
                     if ($values['column_refers_to'] == "real_world") {
                         $fields['refers_to_type'] = 'real_world';
                         $fields['refers_to_id'] = -1;
                     } else {
                         if ($values['column_refers_to'] == "progress") {
                             $fields['refers_to_type'] = 'progress';
                             $fields['refers_to_id'] = $currentLessonID;
                         } else {
                             $type = explode('_', $values['column_refers_to']);
                             $fields['refers_to_type'] = $type[0];
                             $fields['refers_to_id'] = $type[1];
                         }
                     }
                     if ($objectID = eF_insertTableData("module_gradebook_objects", $fields)) {
                         $smarty->assign("T_GRADEBOOK_MESSAGE", _GRADEBOOK_COLUMN_SUCCESSFULLY_ADDED);
                         foreach ($lessonUsers as $userLogin => $value) {
                             $fieldsGrades = array("oid" => $objectID, "grade" => -1, "users_LOGIN" => $userLogin);
                             if (eF_insertTableData("module_gradebook_grades", $fieldsGrades)) {
                                 $smarty->assign("T_GRADEBOOK_MESSAGE", _GRADEBOOK_COLUMN_SUCCESSFULLY_ADDED);
                             } else {
                                 $message = _GRADEBOOK_COLUMN_ADD_PROBLEM;
                                 $message_type = 'failure';
                             }
                         }
                     } else {
                         $message = _GRADEBOOK_COLUMN_ADD_PROBLEM;
                         $message_type = 'failure';
                     }
                 }
                 $renderer = prepareFormRenderer($form);
                 $form->accept($renderer);
                 $smarty->assign('T_GRADEBOOK_ADD_COLUMN_FORM', $renderer->toArray());
             } else {
                 if (isset($_GET['edit_publish']) && isset($_GET['uid']) && isset($_GET['publish']) && eF_checkParameter($_GET['uid'], 'id') && in_array($_GET['uid'], array_keys($allUsers))) {
                     try {
                         $publish = !$allUsers[$_GET['uid']]['publish'];
                         eF_updateTableData("module_gradebook_users", array("publish" => $publish), "uid=" . $_GET['uid']);
                         echo json_encode(array('publish' => $publish));
                     } catch (Exception $e) {
                         handleAjaxExceptions($e);
                     }
                     exit;
                 } else {
                     if (isset($_GET['complete_lesson']) && isset($_GET['uid']) && eF_checkParameter($_GET['uid'], 'id') && in_array($_GET['uid'], array_keys($allUsers))) {
                         try {
                             $user = $allUsers[$_GET['uid']];
                             eF_updateTableData("users_to_lessons", array("completed" => 1, 'score' => $user['score']), "lessons_ID= " . $user['lessons_ID'] . " and users_LOGIN='******'users_LOGIN'] . "'");
                             echo json_encode(array('completed' => 1));
                         } catch (Exception $e) {
                             handleAjaxExceptions($e);
                         }
                         exit;
                     } else {
                         if (isset($_GET['change_grade']) && isset($_GET['grade']) && eF_checkParameter($_GET['change_grade'], 'id')) {
                             $newGrade = $_GET['grade'];
                             try {
                                 if ($newGrade != '') {
                                     if (!is_numeric($newGrade) || $newGrade > 100) {
                                         throw new EfrontContentException(_GRADEBOOK_INVALID_GRADE . ': "' . $newGrade . '". ' . _GRADEBOOK_VALID_GRADE_SPECS, EfrontContentException::INVALID_SCORE);
                                     }
                                 } else {
                                     $newGrade = -1;
                                 }
                                 $newGrade = str_replace(',', '.', $newGrade);
                                 eF_updateTableData("module_gradebook_grades", array("grade" => $newGrade), "gid=" . $_GET['change_grade']);
                             } catch (Exception $e) {
                                 header("HTTP/1.0 500");
                                 echo rawurlencode($e->getMessage());
                             }
                             exit;
                         } else {
                             $smarty->assign("T_GRADEBOOK_RANGES", $ranges);
                             if ($currentUser->getRole($this->getCurrentLesson()) == 'professor') {
                                 /* Add new students to GradeBook related tables */
                                 $result = eF_getTableData("module_gradebook_users", "users_LOGIN", "lessons_ID=" . $currentLessonID);
                                 $allLogins = array();
                                 foreach ($result as $user) {
                                     array_push($allLogins, $user['users_LOGIN']);
                                 }
                                 if (sizeof($result) != sizeof($lessonUsers)) {
                                     // FIXME
                                     $lessonColumns = $this->getLessonColumns($currentLessonID);
                                     foreach ($lessonUsers as $userLogin => $value) {
                                         if (!in_array($userLogin, $allLogins)) {
                                             $userFields = array("users_LOGIN" => $userLogin, "lessons_ID" => $currentLessonID, "score" => -1, "grade" => '-1');
                                             $uid = eF_insertTableData("module_gradebook_users", $userFields);
                                             foreach ($lessonColumns as $key => $column) {
                                                 $fieldsGrades = array("oid" => $key, "grade" => -1, "users_LOGIN" => $userLogin);
                                                 $type = $column['refers_to_type'];
                                                 $id = $column['refers_to_id'];
                                                 eF_insertTableData("module_gradebook_grades", $fieldsGrades);
                                                 if ($type != 'real_world') {
                                                     $this->importGrades($type, $id, $key, $userLogin);
                                                 }
                                             }
                                             $this->computeScoreGrade($lessonColumns, $ranges, $userLogin, $uid);
                                         }
                                     }
                                 }
                                 /* End */
                                 $lessonColumns = $this->getLessonColumns($currentLessonID);
                                 //$allUsers = $this->getLessonUsers($currentLessonID, $lessonColumns);	//we got this earlier
                                 $gradeBookLessons = $this->getGradebookLessons($currentUser->getLessons(false, 'professor'), $currentLessonID);
                                 $smarty->assign("T_GRADEBOOK_LESSON_COLUMNS", $lessonColumns);
                                 $smarty->assign("T_GRADEBOOK_GRADEBOOK_LESSONS", $gradeBookLessons);
                                 //Added by makriria because of #4613
                                 foreach ($allUsers as $key => $value) {
                                     if (!isset($lessonUsers[$value['users_LOGIN']])) {
                                         unset($allUsers[$key]);
                                     }
                                 }
                                 if ($_GET['ajax'] == 'usersTable') {
                                     list($tableSize, $allUsers) = filterSortPage($allUsers);
                                     $smarty->assign("T_SORTED_TABLE", $_GET['ajax']);
                                     $smarty->assign("T_TABLE_SIZE", $tableSize);
                                     $smarty->assign("T_DATA_SOURCE", $allUsers);
                                 }
                                 //$smarty->assign("T_DATA_SOURCE", $allUsers);
                             } else {
                                 if ($currentUser->getRole($this->getCurrentLesson()) == 'student') {
                                     $lessonColumns = $this->getLessonColumns($currentLessonID);
                                     $studentGrades = $this->getStudentGrades($currentUser, $currentLessonID, $lessonColumns);
                                     $smarty->assign("T_GRADEBOOK_LESSON_COLUMNS", $lessonColumns);
                                     $smarty->assign("T_GRADEBOOK_STUDENT_GRADES", $studentGrades);
                                     $smarty->assign("T_GRADEBOOK_CURRENT_LESSON_NAME", $currentLesson->lesson['name']);
                                     // Show all my lessons
                                     $studentLessons = $currentUser->getLessons(false, 'student');
                                     $studentLessonsNames = array();
                                     $studentLessonsColumns = array();
                                     $studentLessonsGrades = array();
                                     foreach ($studentLessons as $key => $value) {
                                         // Is GradeBook installed for this lesson ?
                                         $installed = eF_getTableData("module_gradebook_users", "*", "lessons_ID=" . $key . " and users_LOGIN='******'login'] . "'");
                                         if (sizeof($installed) != 0) {
                                             $lesson = new EfrontLesson($key);
                                             $columns = $this->getLessonColumns($key);
                                             $grades = $this->getStudentGrades($currentUser, $key, $columns);
                                             array_push($studentLessonsNames, $lesson->lesson['name']);
                                             $studentLessonsColumns[$lesson->lesson['name']] = $columns;
                                             $studentLessonsGrades[$lesson->lesson['name']] = $grades;
                                         }
                                     }
                                     $smarty->assign("T_GRADEBOOK_STUDENT_LESSON_NAMES", $studentLessonsNames);
                                     $smarty->assign("T_GRADEBOOK_STUDENT_LESSON_COLUMNS", $studentLessonsColumns);
                                     $smarty->assign("T_GRADEBOOK_STUDENT_LESSON_GRADES", $studentLessonsGrades);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($message) {
         $this->setMessageVar($message, $message_type);
     }
     if ($currentUser->getType() == 'administrator') {
         return $this->moduleBaseDir . "module_gradebook_admin.tpl";
     } else {
         if ($currentUser->getRole($this->getCurrentLesson()) == 'professor') {
             return $this->moduleBaseDir . "module_gradebook_professor.tpl";
         } else {
             if ($currentUser->getRole($this->getCurrentLesson()) == 'student') {
                 return $this->moduleBaseDir . "module_gradebook_student.tpl";
             }
         }
     }
 }
Example #15
0
$secondary[0][2] = 'Beck';
$secondary[1][3] = 'Noir Desir';
$secondary[1][4] = 'Violent Femmes';
$secondary[2][5] = 'Wagner';
$secondary[2][6] = 'Mozart';
$secondary[2][7] = 'Beethoven';
$select =& $form->addElement('hierselect', 'music', 'Please select:');
$select->setOptions(array($main, $secondary));
$form->addElement('textarea', 'message', 'Your message:', array('style' => 'width: 300px;', 'cols' => 50, 'rows' => '7'));
$form->addElement('submit', 'submit', 'Submit');
$form->addElement('hidden', 'hidden1', 'x');
$form->addElement('hidden', 'hidden2', 'y');
$form->addElement('hidden', 'hidden3', 'z');
$form->addRule('name', 'Please enter your name', 'required', null, 'client');
$form->addRule('email', 'Please enter your email address.', 'required', null, 'client');
$form->addRule('email', 'Please enter a valid email address.', 'email', null, 'client');
$form->addRule('subject', 'Please enter a subject.', 'required', null, 'client');
$form->addRule('message', 'Please enter a message.', 'required', null, 'client');
if ($form->isSubmitted() && $form->validate()) {
    $data = $form->exportValues();
    // do something with $data
    echo "<p>Thank you</p>\n";
} else {
    $renderer =& new HTML_QuickForm_Renderer_Tableless();
    $renderer->addStopFieldsetElements('submit');
    $form->accept($renderer);
    echo $renderer->toHtml();
}
?>
  </body>
</html>
Example #16
0
 public function editUser()
 {
     $this->db_authors = pdAuthorList::create($this->db, null, null, true);
     $user =& $_SESSION['user'];
     $user->collaboratorsDbLoad($this->db);
     $form = new HTML_QuickForm('userForm', 'post', '', '', array('onsubmit' => 'return check_authors("userForm");'));
     $form->addElement('static', 'login_label', 'Login:'******'hidden', 'status', 'edit');
     $form->addElement('hidden', 'login', $user->login);
     $form->addElement('text', 'name', 'Name:', array('size' => 50, 'maxlength' => 100));
     $form->addElement('text', 'email', 'E-mail:', array('size' => 50, 'maxlength' => 100));
     $form->addElement('textarea', 'authors', 'Authors:', array('cols' => 60, 'rows' => 5, 'class' => 'wickEnabled:MYCUSTOMFLOATER', 'wrap' => 'virtual'));
     $form->addElement('static', null, null, '<span class="small">' . 'There are ' . count($this->db_authors) . ' authors in the database. Type a partial name to ' . 'see a list of matching authors. Separate names ' . 'using commas.</span>');
     $form->addElement('advcheckbox', 'option_internal_info', 'Options:', 'show internal info', null, array('No', 'Yes'));
     $form->addElement('advcheckbox', 'option_user_info', 'Options:', 'show user info', null, array('No', 'Yes'));
     $auth_list = pdAuthorList::create($this->db);
     $form->addElement('submit', 'Submit', 'Save');
     if ($form->validate()) {
         $values = $form->exportValues();
         assert('$values["login"] == $user->login');
         $user->name = $values['name'];
         $user->email = $values['email'];
         $user->options = 0;
         if ($values['option_internal_info'] == 'Yes') {
             $user->options |= pdUser::OPTION_SHOW_INTERNAL_INFO;
         }
         if ($values['option_user_info'] == 'Yes') {
             $user->options |= pdUser::OPTION_SHOW_USER_INFO;
         }
         unset($user->collaborators);
         // need to retrieve author_ids for the selected authors
         $selAuthors = explode(', ', preg_replace('/\\s\\s+/', ' ', $values['authors']));
         $author_ids = array();
         foreach ($selAuthors as $author) {
             if (empty($author)) {
                 continue;
             }
             $result = array_search($author, $this->db_authors);
             if ($result !== false) {
                 $user->collaborators[$result] = $this->db_authors[$result];
             }
         }
         $user->dbSave($this->db);
         echo 'Change to user information submitted.<p/>';
         echo 'Click <a href="edit_user.php?status=edit">here</a> to edit your preferences again.';
     } else {
         echo '<h2>Login Information</h2>';
         $defaults = array('name' => $user->name, 'email' => $user->email);
         $defaults['option_internal_info'] = $user->showInternalInfo() ? 'Yes' : 'No';
         $defaults['option_user_info'] = $user->showUserInfo() ? 'Yes' : 'No';
         if (count($user->collaborators) > 0) {
             $author_names = pdAuthorList::createFromAuthorIds($this->db, array_keys($user->collaborators), true);
             $defaults['authors'] = implode(', ', array_values($author_names));
         }
         $form->setDefaults($defaults);
         $renderer =& $form->defaultRenderer();
         $form->accept($renderer);
         $this->form =& $form;
         $this->renderer =& $renderer;
         $this->javascript();
     }
 }
 public function getSmartyTpl()
 {
     $smarty = $this->getSmartyVar();
     $currentUser = $this->getCurrentUser();
     $currentLesson = $this->getCurrentLesson();
     $currentLessonID = $currentLesson->lesson['id'];
     if ($currentUser->getRole($this->getCurrentLesson()) == 'professor' || $currentUser->getRole($this->getCurrentLesson()) == 'student') {
         // XXX
         $workbookLessonName = _WORKBOOK_NAME . ' [' . $this->getWorkbookLessonName($currentLessonID) . ']';
         $smarty->assign("T_WORKBOOK_LESSON_NAME", $workbookLessonName);
         $lessonQuestions = $this->getLessonQuestions($currentLessonID);
         $workbookLessons = $this->isWorkbookInstalledByUser($currentUser, $currentUser->getRole($this->getCurrentLesson()), $currentLessonID);
         $workbookItems = $this->getWorkbookItems($currentLessonID);
         $nonOptionalQuestionsNr = $this->getNonOptionalQuestionsNr($workbookItems);
         if ($nonOptionalQuestionsNr != 0) {
             $questionPercentage = (double) (100 / $nonOptionalQuestionsNr);
             $questionPercentage = round($questionPercentage, 2);
         }
         $isWorkbookPublished = $this->isWorkbookPublished($currentLessonID);
     }
     if ($currentUser->getRole($this->getCurrentLesson()) == 'student') {
         $workbookSettings = $this->getWorkbookSettings($currentLessonID);
         $smarty->assign("T_WORKBOOK_SETTINGS", $workbookSettings);
     }
     $smarty->assign("T_WORKBOOK_BASEURL", $this->moduleBaseUrl);
     $smarty->assign("T_WORKBOOK_BASELINK", $this->moduleBaseLink);
     global $popup;
     isset($popup) && $popup == 1 ? $popup_ = '&popup=1' : ($popup_ = '');
     if (isset($_REQUEST['question_preview']) && $_REQUEST['question_preview'] == '1' && isset($_REQUEST['question_id']) && eF_checkParameter($_REQUEST['question_id'], 'id')) {
         $id = $_REQUEST['question_id'];
         if (!in_array($id, array_keys($lessonQuestions))) {
             // reused item
             $reusedQuestion = $this->getReusedQuestionDetails($id);
             $type = $reusedQuestion['type'];
         } else {
             $type = $lessonQuestions[$id]['type'];
         }
         echo $this->questionToHtml($id, $type);
         exit;
     }
     if (isset($_REQUEST['get_progress']) && $_REQUEST['get_progress'] == '1') {
         $isWorkbookCompleted = $this->isWorkbookCompleted($currentUser->user['login'], $currentLessonID, array_keys($workbookItems), $nonOptionalQuestionsNr);
         $studentProgress = $this->getStudentProgress($currentUser->user['login'], $currentLessonID);
         if ($isWorkbookCompleted['is_completed'] == 1) {
             $unitToComplete = $workbookSettings['unit_to_complete'];
             $result = eF_updateTableData('module_workbook_progress', array('completion_date' => time()), "lessons_ID='" . $currentLessonID . "' AND users_LOGIN='******'login'] . "'");
             if ($unitToComplete != -1) {
                 $currentUser->setSeenUnit($unitToComplete, $currentLessonID, true);
             }
         }
         echo $studentProgress . '-' . $isWorkbookCompleted['id'];
         exit;
     }
     if (isset($_GET['edit_settings']) && $_GET['edit_settings'] == '1') {
         if ($_SESSION['s_type'] != 'professor') {
             $message = _WORKBOOK_NOACCESS;
             $message_type = 'failure';
             $this->setMessageVar(urlencode($message), $message_type);
         }
         $content = new EfrontContentTree($currentLessonID);
         $iterator = new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($content->tree), RecursiveIteratorIterator::SELF_FIRST), array('ctg_type' => 'theory'));
         $contentOptions = $content->toHTMLSelectOptions($iterator);
         $contentOptions = array(-1 => '-------------') + $contentOptions;
         $workbookSettings = $this->getWorkbookSettings($currentLessonID);
         if ($isWorkbookPublished == 1) {
             $contentOptions[$workbookSettings['unit_to_complete']] = str_replace('&nbsp;', '', $contentOptions[$workbookSettings['unit_to_complete']]);
             $contentOptions[$workbookSettings['unit_to_complete']] = str_replace('&raquo;', '', $contentOptions[$workbookSettings['unit_to_complete']]);
         }
         $form = new HTML_QuickForm("edit_settings_form", "post", $this->moduleBaseUrl . "&edit_settings=1", "", null, true);
         $form->addElement('text', 'lesson_name', _WORKBOOK_LESSON_NAME, 'class="inputText"');
         $form->addRule('lesson_name', _THEFIELD . ' "' . _WORKBOOK_LESSON_NAME . '" ' . _ISMANDATORY, 'required', null, 'client');
         $form->addElement('advcheckbox', 'allow_print', _WORKBOOK_ALLOW_PRINT, null, 'class="inputCheckBox"', array(0, 1));
         $form->addElement('advcheckbox', 'allow_export', _WORKBOOK_ALLOW_EXPORT, null, 'class="inputCheckBox"', array(0, 1));
         $form->addElement('advcheckbox', 'edit_answers', _WORKBOOK_EDIT_ANSWERS, null, 'class="inputCheckBox"', array(0, 1));
         $form->addElement('select', 'unit_to_complete', _WORKBOOK_UNIT_TO_COMPLETE, $contentOptions);
         $form->addElement('submit', 'submit', _UPDATE, 'class="flatButton"');
         if ($isWorkbookPublished == 1) {
             $form->freeze('unit_to_complete');
         }
         $form->setDefaults($workbookSettings);
         if ($form->isSubmitted() && $form->validate()) {
             $values = $form->exportValues();
             $fields = array("lesson_name" => $values['lesson_name'], "allow_print" => $values['allow_print'], "allow_export" => $values['allow_export'], "edit_answers" => $values['edit_answers'], "unit_to_complete" => $values['unit_to_complete']);
             if (eF_updateTableData("module_workbook_settings", $fields, "id=" . $workbookSettings['id'])) {
                 $smarty->assign("T_WORKBOOK_MESSAGE", _WORKBOOK_SETTINGS_SUCCESSFULLY_EDITED);
                 $smarty->assign("T_WORKBOOK_MESSAGE_TYPE", 'success');
             } else {
                 $smarty->assign("T_WORKBOOK_MESSAGE", _WORKBOOK_SETTINGS_EDIT_PROBLEM);
                 $smarty->assign("T_WORKBOOK_MESSAGE_TYPE", 'failure');
             }
         }
         $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
         $renderer->setRequiredTemplate('{$html}{if $required}&nbsp;<span class="formRequired">*</span>{/if}');
         $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
         $form->setRequiredNote(_REQUIREDNOTE);
         $form->accept($renderer);
         $smarty->assign('T_WORKBOOK_EDIT_SETTINGS_FORM', $renderer->toArray());
     }
     if (isset($_GET['reuse_item']) && $_GET['reuse_item'] == '1') {
         if ($_SESSION['s_type'] != 'professor') {
             $message = _WORKBOOK_NOACCESS;
             $message_type = 'failure';
             $this->setMessageVar(urlencode($message), $message_type);
         }
         $form = new HTML_QuickForm("reuse_item_form", "post", $this->moduleBaseUrl . "&reuse_item=1", "", null, true);
         $form->addElement('text', 'item_id', _WORKBOOK_ITEM_ID, 'class="inputText"');
         $form->addRule('item_id', _THEFIELD . ' "' . _WORKBOOK_ITEM_ID . '" ' . _ISMANDATORY, 'required', null, 'client');
         $form->addElement('submit', 'submit', _WORKBOOK_REUSE_ITEM, 'class="flatButton"');
         if ($form->isSubmitted() && $form->validate()) {
             $values = $form->exportValues();
             $existingIDs = $this->getItemsUniqueIDs();
             if (!in_array($values['item_id'], $existingIDs)) {
                 $message = _WORKBOOK_INVALID_UNIQUE_ID;
                 $message_type = 'failure';
                 $this->setMessageVar(urlencode($message), $message_type);
             } else {
                 $item = $this->getItemByUniqueID($values['item_id']);
                 $fields = array("item_title" => $item['item_title'], "item_text" => $item['item_text'], "item_question" => $item['item_question'], "question_text" => $item['question_text'], "check_answer" => $item['check_answer'], "lessons_ID" => $currentLessonID, "unique_ID" => $this->generateItemID(), "position" => $this->itemPosition($currentLessonID));
                 if (eF_insertTableData("module_workbook_items", $fields)) {
                     $smarty->assign("T_WORKBOOK_MESSAGE", urlencode(_WORKBOOK_ITEM_SUCCESSFULLY_ADDED));
                     $smarty->assign("T_WORKBOOK_MESSAGE_TYPE", 'success');
                 } else {
                     $smarty->assign("T_WORKBOOK_MESSAGE", _WORKBOOK_ITEM_ADD_PROBLEM);
                     $smarty->assign("T_WORKBOOK_MESSAGE_TYPE", 'failure');
                 }
             }
         }
         $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
         $renderer->setRequiredTemplate('{$html}{if $required}&nbsp;<span class="formRequired">*</span>{/if}');
         $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
         $form->setRequiredNote(_REQUIREDNOTE);
         $form->accept($renderer);
         $smarty->assign('T_WORKBOOK_REUSE_ITEM_FORM', $renderer->toArray());
     }
     if (isset($_GET['move_item']) && eF_checkParameter($_GET['move_item'], 'id') && in_array($_GET['move_item'], array_keys($workbookItems))) {
         if ($_SESSION['s_type'] != 'professor') {
             $message = _WORKBOOK_NOACCESS;
             $message_type = 'failure';
             $this->setMessageVar(urlencode($message), $message_type);
         }
         $smarty->assign("T_WORKBOOK_ITEMS_COUNT", count($workbookItems));
         $itemPosition = $workbookItems[$_GET['move_item']]['position'];
         $availablePositions = array();
         foreach ($workbookItems as $key => $value) {
             if ($value['position'] != $itemPosition) {
                 $availablePositions[$value['position']] = $value['position'];
             }
         }
         $form = new HTML_QuickForm("move_item_form", "post", $this->moduleBaseUrl . "&move_item=" . $_GET['move_item'], "", null, true);
         $form->addElement('select', 'item_position', _WORKBOOK_ITEM_NEW_POSITION, $availablePositions, '');
         $form->addElement('submit', 'submit', _WORKBOOK_MOVE_ITEM, 'class="flatButton"');
         if ($form->isSubmitted() && $form->validate()) {
             $values = $form->exportValues();
             $newPosition = $values['item_position'];
             if ($newPosition > $itemPosition) {
                 foreach ($workbookItems as $key => $value) {
                     if ($value['position'] > $itemPosition && $value['position'] <= $newPosition) {
                         eF_updateTableData("module_workbook_items", array('position' => $value['position'] - 1), "id=" . $key);
                     }
                 }
             } else {
                 foreach ($workbookItems as $key => $value) {
                     if ($value['position'] < $itemPosition && $value['position'] >= $newPosition) {
                         eF_updateTableData("module_workbook_items", array('position' => $value['position'] + 1), "id=" . $key);
                     }
                 }
             }
             eF_updateTableData("module_workbook_items", array('position' => $newPosition), "id=" . $_GET['move_item']);
             $smarty->assign("T_WORKBOOK_MESSAGE", _WORKBOOK_ITEM_SUCCESSFULLY_MOVED);
             $smarty->assign("T_WORKBOOK_MESSAGE_TYPE", 'success');
         }
         $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
         $renderer->setRequiredTemplate('{$html}{if $required}&nbsp;<span class="formRequired">*</span>{/if}');
         $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
         $form->setRequiredNote(_REQUIREDNOTE);
         $form->accept($renderer);
         $smarty->assign('T_WORKBOOK_MOVE_ITEM_FORM', $renderer->toArray());
     }
     if (isset($_GET['delete_item']) && eF_checkParameter($_GET['delete_item'], 'id') && in_array($_GET['delete_item'], array_keys($workbookItems))) {
         $item_id = $_GET['delete_item'];
         $itemPosition = $workbookItems[$item_id]['position'];
         foreach ($workbookItems as $key => $value) {
             if ($value['position'] > $itemPosition) {
                 eF_updateTableData("module_workbook_items", array('position' => $value['position'] - 1), "id=" . $key);
             }
         }
         eF_deleteTableData("module_workbook_items", "id=" . $item_id);
     }
     if (isset($_GET['switch_lesson']) && eF_checkParameter($_GET['switch_lesson'], 'id') && in_array($_GET['switch_lesson'], array_keys($workbookLessons))) {
         $lessonID = $_GET['switch_lesson'];
         eF_redirect("location:" . $this->moduleBaseUrl . "&lessons_ID=" . $lessonID . $popup_);
     }
     if (isset($_GET['add_item']) && $_GET['add_item'] == '1' || isset($_GET['edit_item']) && eF_checkParameter($_GET['edit_item'], 'id') && in_array($_GET['edit_item'], array_keys($workbookItems))) {
         if ($_SESSION['s_type'] != "professor") {
             eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_WORKBOOK_NOACCESS) . $popup_);
         }
         global $load_editor;
         $load_editor = true;
         $questionsText = array();
         $questionsText[-1] = "-----------------------";
         foreach ($lessonQuestions as $key => $value) {
             $questionsText[$key] = $this->truncateText(strip_tags($value['text']), 70);
         }
         if (isset($_GET['edit_item'])) {
             $editItemID = $_GET['edit_item'];
             $editItemQuestion = $workbookItems[$editItemID]['item_question'];
             if ($editItemQuestion != '-1' && !in_array($editItemQuestion, array_keys($questionsText))) {
                 // reused item
                 $reusedQuestion = $this->getReusedQuestionDetails($editItemQuestion);
                 $questionsText[$editItemQuestion] = $this->truncateText(strip_tags($reusedQuestion['text']), 70);
             }
         }
         isset($_GET['add_item']) ? $postTarget = "&add_item=1" : ($postTarget = "&edit_item=" . $_GET['edit_item']);
         $form = new HTML_QuickForm("add_edit_item_form", "post", $this->moduleBaseUrl . $postTarget, "", null, true);
         $form->addElement('text', 'item_title', _WORKBOOK_ITEM_TITLE, 'class="inputText" style="width:500px;"');
         $form->addElement('textarea', 'item_text', _WORKBOOK_ITEM_TEXT, 'class="mceEditor" style="width:99%;height:300px;" id="editor_content_data"');
         $form->addElement('select', 'item_question', _WORKBOOK_ITEM_QUESTION, $questionsText, 'onchange="questionPreview(this)"');
         $form->addElement('advcheckbox', 'check_answer', _WORKBOOK_ITEM_GRADE_ANSWER, null, 'class="inputCheckBox"', array(0, 1));
         if (isset($_GET['add_item'])) {
             $form->addElement('submit', 'submit', _WORKBOOK_ADD_ITEM, 'class="flatButton"');
         } else {
             $form->addElement('submit', 'submit', _WORKBOOK_UPDATE_ITEM, 'class="flatButton"');
         }
         if (isset($_GET['edit_item'])) {
             $editItem = $workbookItems[$_GET['edit_item']];
             $form->setDefaults($editItem);
             if ($isWorkbookPublished == '1') {
                 $editItem['question_title'] = $questionsText[$editItem['item_question']];
                 if ($editItem['check_answer'] == '1') {
                     $editItem['check_answer_text'] = _YES;
                 } else {
                     $editItem['check_answer_text'] = _NO;
                 }
             }
             $smarty->assign('T_WORKBOOK_EDIT_ITEM_DETAILS', $editItem);
         }
         if ($form->isSubmitted() && $form->validate()) {
             $values = $form->exportValues();
             isset($_GET['add_item']) ? $lessonID = $currentLessonID : ($lessonID = $editItem['lessons_ID']);
             isset($_GET['add_item']) ? $uniqueID = $this->generateItemID() : ($uniqueID = $editItem['unique_ID']);
             isset($_GET['add_item']) ? $position = $this->itemPosition($currentLessonID) : ($position = $editItem['position']);
             if ($values['item_question'] != '-1') {
                 $id = $values['item_question'];
                 if (!in_array($id, array_keys($lessonQuestions))) {
                     // edit reused item
                     $reusedQuestion = $this->getReusedQuestionDetails($id);
                     $type = $reusedQuestion['type'];
                 } else {
                     $type = $lessonQuestions[$id]['type'];
                 }
                 $questionText = $this->questionToHtml($id, $type);
             } else {
                 $questionText = '';
             }
             $fields = array("item_title" => $values['item_title'], "item_text" => $values['item_text'], "item_question" => $values['item_question'], "question_text" => $questionText, "check_answer" => $values['check_answer'], "lessons_ID" => $lessonID, "unique_ID" => $uniqueID, "position" => $position);
             if ($values['item_title'] == '' && $values['item_text'] == '' && $values['item_question'] == '-1') {
                 $message = _WORKBOOK_ITEM_EMPTY_FIELDS;
                 if (isset($_GET['add_item'])) {
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=failure&add_item=1" . $popup_);
                 } else {
                     $itemID = $_GET['edit_item'];
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=failure&edit_item=" . $itemID . $popup_);
                 }
             }
             if (isset($_GET['add_item'])) {
                 if (eF_insertTableData("module_workbook_items", $fields)) {
                     $message = _WORKBOOK_ITEM_SUCCESSFULLY_ADDED;
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=success" . $popup_);
                 } else {
                     $message = _WORKBOOK_ITEM_ADD_PROBLEM;
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=failure" . $popup_);
                 }
             } else {
                 if (eF_updateTableData("module_workbook_items", $fields, "id=" . $_GET['edit_item'])) {
                     $message = _WORKBOOK_ITEM_SUCCESSFULLY_EDITED;
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=success" . $popup_);
                 } else {
                     $message = _WORKBOOK_ITEM_EDIT_PROBLEM;
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=failure" . $popup_);
                 }
             }
         }
         $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
         $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
         $form->setRequiredNote(_REQUIREDNOTE);
         $form->accept($renderer);
         $smarty->assign('T_WORKBOOK_ADD_EDIT_ITEM_FORM', $renderer->toArray());
         $basedir = $currentLesson->getDirectory();
         $options = array('lessons_ID' => $currentLessonID, 'metadata' => 0);
         $url = $_SERVER['REQUEST_URI'];
         $extraFileTools = array(array('image' => 'images/16x16/arrow_right.png', 'title' => _INSERTEDITOR, 'action' => 'insert_editor'));
         include "file_manager.php";
     }
     if (isset($_GET['publish_workbook']) && $_GET['publish_workbook'] == '1') {
         $result = eF_getTableData("module_workbook_publish", "publish", "lessons_ID=" . $currentLessonID);
         if (count($result) == 0) {
             if (eF_insertTableData("module_workbook_publish", array('lessons_ID' => $currentLessonID, 'publish' => 1))) {
                 $message = _WORKBOOK_SUCCESSFULLY_PUBLISHED;
                 eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=success" . $popup_);
             } else {
                 $message = _WORKBOOK_PUBLISH_PROBLEM;
                 eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=failure" . $popup_);
             }
         } else {
             if (eF_updateTableData("module_workbook_publish", array('publish' => 1), "lessons_ID=" . $currentLessonID)) {
                 $message = _WORKBOOK_SUCCESSFULLY_PUBLISHED;
                 eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=success" . $popup_);
             } else {
                 $message = _WORKBOOK_PUBLISH_PROBLEM;
                 eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=failure" . $popup_);
             }
         }
     }
     if (isset($_GET['reset_workbook_professor']) && $_GET['reset_workbook_professor'] == '1') {
         eF_updateTableData("module_workbook_publish", array('publish' => 0), "lessons_ID=" . $currentLessonID);
         foreach ($workbookItems as $key => $value) {
             eF_deleteTableData("module_workbook_answers", "item_id=" . $key);
             eF_deleteTableData("module_workbook_autosave", "item_id=" . $key);
             eF_deleteTableData("module_workbook_progress", "lessons_ID=" . $currentLessonID);
         }
     }
     if (isset($_GET['reset_workbook_student']) && eF_checkParameter($_GET['reset_workbook_student'], 'id')) {
         $id = $_GET['reset_workbook_student'];
         $result = eF_getTableData("module_workbook_progress", "users_LOGIN", "id=" . $id);
         if ($result[0]['users_LOGIN'] != $currentUser->user['login']) {
             eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_WORKBOOK_NOACCESS) . $popup_);
         }
         eF_deleteTableData("module_workbook_progress", "id=" . $id);
         foreach ($workbookItems as $key => $value) {
             eF_deleteTableData("module_workbook_answers", "item_id=" . $key . " AND users_LOGIN='******'login'] . "'");
         }
         $unitToComplete = $workbookSettings['unit_to_complete'];
         if ($unitToComplete != -1) {
             $currentUser->setSeenUnit($unitToComplete, $currentLessonID, false);
         }
     }
     if (isset($_GET['download_as']) && $_GET['download_as'] == 'doc') {
         include dirname(__FILE__) . "/classes/html_to_doc.inc.php";
         $workbookAnswers = $this->getWorkbookAnswers($currentUser->user['login'], array_keys($workbookItems));
         $workbookHTML = '';
         foreach ($workbookItems as $key => $value) {
             $workbookHTML .= '<div style="width:98%;float:left;border:1px dotted #808080;padding: 5px 10px;">';
             $workbookHTML .= '<div style="background-color: #EAEAEA;border: 1px solid #AAAAAA;padding: 2px;font-weight: bold;">';
             $workbookHTML .= _WORKBOOK_ITEMS_COUNT . $value['position'];
             if ($value['item_title'] != '') {
                 $workbookHTML .= '&nbsp;-&nbsp;' . $value['item_title'];
             }
             $workbookHTML .= '</div><br/>';
             if ($value['item_text'] != '') {
                 $workbookHTML .= '<div>' . $value['item_text'] . '</div><br/>';
             }
             if ($value['item_question'] != '-1') {
                 $questionType = $lessonQuestions[$value['item_question']]['type'];
                 if ($workbookAnswers[$value['id']] == '') {
                     if ($questionType == 'drag_drop') {
                         $dragDrop = eF_getTableData("questions", "options, answer, text", "id=" . $value['item_question']);
                         $options = unserialize($dragDrop[0]['options']);
                         $answer = unserialize($dragDrop[0]['answer']);
                         shuffle($options);
                         shuffle($answer);
                         $workbookHTML .= $dragDrop[0]['text'];
                         for ($i = 0; $i < count($options); $i++) {
                             $workbookHTML .= '<div>' . $options[$i] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                             $workbookHTML .= $answer[$i] . '</div>';
                         }
                     } else {
                         $workbookHTML .= '<div>' . $value['question_text'] . '</div>';
                     }
                 } else {
                     $workbookHTML .= '<div>' . $workbookAnswers[$value['id']] . '</div>';
                 }
             }
             $workbookHTML .= '</div><br/>';
         }
         $workbookHTML = preg_replace('/<script\\b[^>]*>(.*?)<\\/script>/is', "", $workbookHTML);
         $fileName = _WORKBOOK_NAME . '_' . $this->getWorkbookLessonName($currentLessonID);
         $fileName = preg_replace('/[\\s]+/', '_', $fileName);
         $htmltodoc = new HTML_TO_DOC();
         $htmltodoc->createDoc($workbookHTML, $fileName, true);
         exit(0);
     }
     if (isset($_GET['download_as']) && $_GET['download_as'] == 'pdf') {
         $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
         $pdf->SetCreator(PDF_CREATOR);
         $pdf->SetAuthor(PDF_AUTHOR);
         $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
         $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
         $pdf->setFontSubsetting(false);
         $pdf->AddPage();
         $completion_date = '';
         $resutlt = eF_getTableData('module_workbook_progress', 'completion_date', "users_LOGIN='******'login'] . "' and lessons_ID='" . $currentLessonID . "'");
         if ($resutlt) {
             $completion_date = $resutlt[0]['completion_date'];
         }
         $workbookHTML = '';
         $workbookHTML .= '<table>';
         $workbookHTML .= '<tr>';
         $workbookHTML .= '<td colspan="2">';
         $workbookHTML .= formatLogin($currentUser->user['login']);
         $workbookHTML .= '</td>';
         $workbookHTML .= '</tr>';
         $workbookHTML .= '<tr>';
         $workbookHTML .= '<td>';
         $workbookHTML .= $workbookLessonName;
         $workbookHTML .= '</td>';
         $workbookHTML .= '<td>';
         $workbookHTML .= formatTimestamp($completion_date);
         $workbookHTML .= '</td>';
         $workbookHTML .= '</tr>';
         $workbookHTML .= '</table>';
         $pdf->writeHTML($workbookHTML, true, false, true, false, '');
         $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
         $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
         $pdf->setHeaderFont(array('Freeserif', 'I', 11));
         $pdf->setFooterFont(array('Freeserif', '', 8));
         $pdf->setHeaderData('', '', '', $workbookLessonName);
         $pdf->AliasNbPages();
         $pdf->SetFont('Freeserif', '', 10);
         $pdf->SetTextColor(0, 0, 0);
         $pdf->SetFont('Freeserif', '', 10);
         $pdf->SetTextColor(0, 0, 0);
         $workbookAnswers = $this->getWorkbookAnswers($currentUser->user['login'], array_keys($workbookItems));
         $pdf->AddPage();
         $workbookHTML .= '';
         $itemLogo = new EfrontFile(G_DEFAULTIMAGESPATH . "32x32/unit.png");
         $itemLogoUrl = $itemLogo['path'];
         foreach ($workbookItems as $key => $value) {
             $workbookHTML .= '<div id="pdf-block" style="width:98%;float:left;border:1px dotted #808080;page-break-after:always;">';
             $workbookHTML .= '<div style="background-color: #EAEAEA;font-weight: bold;">';
             $workbookHTML .= '<img src="' . $itemLogoUrl . '"/>&nbsp;' . _WORKBOOK_ITEMS_COUNT . $value['position'];
             if ($value['item_title'] != '') {
                 $workbookHTML .= '&nbsp;-&nbsp;' . $value['item_title'];
             }
             $workbookHTML .= '</div>';
             if ($value['item_text'] != '') {
                 $workbookHTML .= '<div>' . $value['item_text'] . '</div>';
             }
             if ($value['item_question'] != '-1') {
                 $questionType = $lessonQuestions[$value['item_question']]['type'];
                 if ($workbookAnswers[$value['id']] == '') {
                     if ($questionType == 'drag_drop') {
                         $dragDrop = eF_getTableData("questions", "options, answer, text", "id=" . $value['item_question']);
                         $options = unserialize($dragDrop[0]['options']);
                         $answer = unserialize($dragDrop[0]['answer']);
                         shuffle($options);
                         shuffle($answer);
                         $workbookHTML .= $dragDrop[0]['text'];
                         for ($i = 0; $i < count($options); $i++) {
                             $workbookHTML .= '<div>' . $options[$i] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                             $workbookHTML .= $answer[$i] . '</div>';
                         }
                     } else {
                         $workbookHTML .= '<div>' . $value['question_text'] . '</div>';
                     }
                 } else {
                     $workbookHTML .= '<div>' . $workbookAnswers[$value['id']] . '</div>';
                 }
             }
             $workbookHTML .= '</div><br/>';
         }
         $workbookHTML = preg_replace('/<script\\b[^>]*>(.*?)<\\/script>/is', "", $workbookHTML);
         $pdf->writeHTML($workbookHTML, true, false, true, false, '');
         $fileName = _WORKBOOK_NAME . '_' . str_replace(' ', '_', $this->getWorkbookLessonName($currentLessonID)) . '.pdf';
         header("Content-type: application/pdf");
         header("Content-disposition: attachment; filename=" . $fileName);
         echo $pdf->Output('', 'S');
         exit(0);
     }
     if (isset($_GET['check_workbook_progress']) && $_GET['check_workbook_progress'] == '1') {
         $lessonStudents = $currentLesson->getUsers('student');
         $workbookStudents = array();
         foreach ($lessonStudents as $userLogin => $value) {
             if ($nonOptionalQuestionsNr != 0) {
                 $studentProgress = $this->getStudentProgress($userLogin, $currentLessonID);
                 $studentProgress .= '%';
             } else {
                 $studentProgress = '-';
             }
             $workbookStudents[$userLogin] = array('login' => $userLogin, 'progress' => $studentProgress);
         }
         $smarty->assign("T_WORKBOOK_STUDENTS", $workbookStudents);
     }
     if (isset($_GET['preview_workbook']) && $_GET['preview_workbook'] == '1' && isset($_GET['student']) && eF_checkParameter($_GET['student'], 'login')) {
         $userLogin = $_GET['student'];
         $studentProgress = $this->getStudentProgress($userLogin, $currentLessonID);
         $smarty->assign("T_WORKBOOK_PREVIEW_STUDENT_PROGRESS", $studentProgress);
         $workbookAnswers = $this->getWorkbookAnswers($userLogin, array_keys($workbookItems));
         $smarty->assign("T_WORKBOOK_PREVIEW_ANSWERS", $workbookAnswers);
     }
     if (isset($_GET['get_reset_message']) && $_GET['get_reset_message'] == '1') {
         echo $this->getResetMessage(array_keys($workbookItems));
         exit;
     }
     if (isset($_POST['item_submitted'])) {
         $itemID = $_POST['item_submitted'];
         $questionID = $workbookItems[$itemID]['item_question'];
         $checkAnswer = $workbookItems[$itemID]['check_answer'];
         if (!in_array($questionID, array_keys($lessonQuestions))) {
             // reused item
             $reusedQuestion = $this->getReusedQuestionDetails($questionID);
             $questionType = $reusedQuestion['type'];
         } else {
             $questionType = $lessonQuestions[$questionID]['type'];
         }
         $question = QuestionFactory::factory($questionID);
         $question->setDone($_POST['question'][$questionID]);
         $results = $question->correct();
         if ($questionType != 'raw_text' && !ef_compare_float($results['score'], 1)) {
             print '-1';
         } else {
             $form = new HTML_QuickForm("questionForm", "post", "", "", null, true);
             $fields = array('item_id' => $itemID, 'html_solved' => $question->toHTMLSolved($form), 'users_LOGIN' => $currentUser->user['login']);
             eF_insertTableData("module_workbook_answers", $fields);
             if ($checkAnswer == '1') {
                 $this->updateStudentProgress($currentUser->user['login'], $currentLessonID, $questionPercentage, $nonOptionalQuestionsNr);
             }
             echo $question->toHTMLSolved($form);
         }
         eF_deleteTableData("module_workbook_autosave", "item_id=" . $itemID . " AND users_LOGIN='******'login'] . "'");
         exit(0);
     }
     if (isset($_POST['item_submitted_autosave'])) {
         $itemID = $_POST['item_submitted_autosave'];
         $questionID = $workbookItems[$itemID]['item_question'];
         $question = QuestionFactory::factory($questionID);
         $form = new HTML_QuickForm("questionForm", "post", "", "", null, true);
         $form->setDefaults($_POST);
         $fields = array('item_id' => $itemID, 'autosave_text' => $question->toHTML($form), 'users_LOGIN' => $currentUser->user['login']);
         eF_deleteTableData("module_workbook_autosave", "item_id=" . $itemID . " AND users_LOGIN='******'login'] . "'");
         eF_insertTableData("module_workbook_autosave", $fields);
         exit(0);
     }
     if (isset($_POST['item_to_update'])) {
         $itemID = $_POST['item_to_update'];
         $questionID = $workbookItems[$itemID]['item_question'];
         $question = QuestionFactory::factory($questionID);
         $question->userAnswer = urldecode($_POST['ans']);
         $form = new HTML_QuickForm("questionForm", "post", "", "", null, true);
         $form->setDefaults($_POST);
         print $question->toHTML($form);
         exit(0);
     }
     if (isset($_POST['item_updated'])) {
         $itemID = $_POST['item_updated'];
         $questionID = $workbookItems[$itemID]['item_question'];
         $question = QuestionFactory::factory($questionID);
         $question->setDone($_POST['question'][$questionID]);
         $form = new HTML_QuickForm("questionForm", "post", "", "", null, true);
         $answerToUpdate = eF_getTableData("module_workbook_answers", "id", "item_id=" . $itemID . " AND users_LOGIN='******'login'] . "'");
         eF_updateTableData("module_workbook_answers", array('html_solved' => $question->toHTMLSolved($form)), "id=" . $answerToUpdate[0]['id']);
         echo $question->toHTMLSolved($form);
         eF_deleteTableData("module_workbook_autosave", "item_id=" . $itemID . " AND users_LOGIN='******'login'] . "'");
         exit(0);
     } else {
         if ($currentUser->getRole($this->getCurrentLesson()) == 'professor' || $currentUser->getRole($this->getCurrentLesson()) == 'student') {
             $workbookItems = $this->getWorkbookItems($currentLessonID);
             $smarty->assign("T_WORKBOOK_ITEMS", $workbookItems);
             $smarty->assign("T_WORKBOOK_LESSONS", $workbookLessons);
             $isWorkbookPublished = $this->isWorkbookPublished($currentLessonID);
             $smarty->assign("T_WORKBOOK_IS_PUBLISHED", $isWorkbookPublished);
             $smarty->assign("T_WORKBOOK_NON_OPTIONAL_QUESTIONS_NR", $nonOptionalQuestionsNr);
         }
         if ($currentUser->getRole($this->getCurrentLesson()) == 'professor') {
             $workbookOptions[] = array('text' => _SETTINGS, 'image' => $this->moduleBaseLink . 'images/settings.png', 'href' => $this->moduleBaseUrl . '&edit_settings=1&popup=1', 'onClick' => "eF_js_showDivPopup(event, '" . _SETTINGS . "', 0)", 'target' => 'POPUP_FRAME', 'id' => 'edit_settings');
             $workbookOptions[] = array('text' => _WORKBOOK_POPUP_INFO, 'image' => $this->moduleBaseLink . 'images/info.png', 'href' => $this->moduleBaseUrl . '&popup_info=1&popup=1', 'onClick' => "eF_js_showDivPopup(event, '" . _WORKBOOK_POPUP_INFO . "', 2)", 'target' => 'POPUP_FRAME', 'id' => 'popup_info');
             $smarty->assign("T_WORKBOOK_OPTIONS", $workbookOptions);
         } else {
             if ($currentUser->getRole($this->getCurrentLesson()) == 'student') {
                 $workbookAnswers = $this->getWorkbookAnswers($currentUser->user['login'], array_keys($workbookItems));
                 $smarty->assign("T_WORKBOOK_ANSWERS", $workbookAnswers);
                 $autoSaveAnswers = $this->getAutoSaveAnswers($currentUser->user['login'], array_keys($workbookItems));
                 $smarty->assign("T_WORKBOOK_AUTOSAVE_ANSWERS", $autoSaveAnswers);
                 $studentProgress = $this->getStudentProgress($currentUser->user['login'], $currentLessonID);
                 $smarty->assign("T_WORKBOOK_STUDENT_PROGRESS", $studentProgress);
                 $isWorkbookCompleted = $this->isWorkbookCompleted($currentUser->user['login'], $currentLessonID, array_keys($workbookItems), $nonOptionalQuestionsNr);
                 $smarty->assign("T_WORKBOOK_IS_COMPLETED", $isWorkbookCompleted);
             }
         }
     }
     if ($currentUser->getRole($this->getCurrentLesson()) == 'professor') {
         return $this->moduleBaseDir . "module_workbook_professor.tpl";
     } else {
         if ($currentUser->getRole($this->getCurrentLesson()) == 'student') {
             return $this->moduleBaseDir . "module_workbook_student.tpl";
         }
     }
 }
 /**
  * The main functionality
  *
  * (non-PHPdoc)
  * @see libraries/EfrontModule#getModule()
  */
 public function getModule()
 {
     $smarty = $this->getSmartyVar();
     $smarty->assign("T_MODULE_BASEDIR", $this->moduleBaseDir);
     $smarty->assign("T_MODULE_BASELINK", $this->moduleBaseLink);
     $smarty->assign("T_MODULE_BASEURL", $this->moduleBaseUrl);
     $currentUser = $this->getCurrentUser();
     if ($currentUser->user['user_type'] != 'administrator') {
         $currentEmployee = $this->getCurrentUser()->aspects['hcd'];
         if (!$currentEmployee || !$currentEmployee->isSupervisor()) {
             throw new Exception("You cannot access this module");
         }
     }
     $form = new HTML_QuickForm("user_activity_form", "post", basename($_SERVER['PHP_SELF']) . "?ctg=module&op=module_idle_users&tab=user_activity", "", null, true);
     $form->addElement('date', 'idle_from_timestamp', _MODULE_IDLE_USERS_SHOWINACTIVEUSERSSINCE, array('minYear' => 2005, 'maxYear' => date("Y")));
     $form->addElement("static", "", '<a href = "javascript:void(0)" onclick = "setFormDate(' . date("Y") . ',' . date("m") . ',' . (date("d") - 7) . ')">' . _LASTWEEK . '</a> - <a href = "javascript:void(0)" onclick = "setFormDate(' . date("Y") . ',' . (date("m") - 1) . ',' . date("d") . ')">' . _LASTMONTH . '</a> - <a href = "javascript:void(0)" onclick = "setFormDate(' . date("Y") . ',' . (date("m") - 3) . ',' . date("d") . ')">' . _MODULE_IDLE_USERS_LAST3MONTHS . '</a>');
     $form->addElement("submit", "submit", _SUBMIT, 'class = "flatButton"');
     if (!isset($_SESSION['timestamp_from'])) {
         $_SESSION['timestamp_from'] = time() - 86400 * 30;
     }
     $form->setDefaults(array("idle_from_timestamp" => $_SESSION['timestamp_from']));
     if ($form->isSubmitted() && $form->validate()) {
         $values = $form->exportValues();
         $_SESSION['timestamp_from'] = mktime(0, 0, 0, $values['idle_from_timestamp']['M'], $values['idle_from_timestamp']['d'], $values['idle_from_timestamp']['Y']);
     }
     $smarty->assign("T_IDLE_USER_FORM", $form->toArray());
     try {
         if ($currentEmployee) {
             if ($_SESSION['s_current_branch'] && in_array($_SESSION['s_current_branch'], $currentEmployee->supervisesBranches)) {
                 $currentBranch = new EfrontBranch($_SESSION['s_current_branch']);
                 $subbranches = $currentBranch->getSubbranches();
                 foreach ($subbranches as $subbranch) {
                     $branches[$subbranch['branch_ID']] = $subbranch['branch_ID'];
                 }
                 $branches[$_SESSION['s_current_branch']] = $_SESSION['s_current_branch'];
                 $result = eF_getTableData("users u JOIN module_hcd_employee_works_at_branch ewb on ewb.users_login=u.login", "u.login,u.name,u.surname,u.active,u.last_login as last_action", "ewb.branch_ID in (" . implode(',', $branches) . ") and u.last_login is null or u.last_login <= " . $_SESSION['timestamp_from']);
                 //$result = eF_getTableData("(select login,name,surname,active,max(l.timestamp) as last_action from users u left outer join logs l on u.login=l.users_LOGIN where u.archive=0 group by login) r join module_hcd_employee_works_at_branch ewb on ewb.users_login=r.login", "*", "ewb.branch_ID in (".implode(',', $branches) .") and (r.last_action is null or r.last_action <= ".$_SESSION['timestamp_from'].")");
             } else {
                 $result = eF_getTableData("users u JOIN module_hcd_employee_works_at_branch ewb on ewb.users_login=u.login", "u.login,u.name,u.surname,u.active,u.last_login as last_action", "ewb.branch_ID in (" . implode(',', $currentEmployee->supervisesBranches) . ") and u.last_login is null or u.last_login <= " . $_SESSION['timestamp_from']);
                 //$result = eF_getTableData("(select login,name,surname,active,max(l.timestamp) as last_action from users u left outer join logs l on u.login=l.users_LOGIN where u.archive=0 group by login) r join module_hcd_employee_works_at_branch ewb on ewb.users_login=r.login", "*", "ewb.branch_ID in (".implode(',', $currentEmployee->supervisesBranches).") and (r.last_action is null or r.last_action <= ".$_SESSION['timestamp_from'].")");
             }
         } else {
             $result = eF_getTableData("users", "login,name,surname,active,last_login as last_action", "last_login is null or last_login <= " . $_SESSION['timestamp_from']);
         }
         $users = array();
         foreach ($result as $value) {
             if ($value['last_action']) {
                 $value['last_action_since'] = eF_convertIntervalToTime(time() - $value['last_action'], true);
             } else {
                 $value['last_action_since'] = null;
             }
             $users[$value['login']] = $value;
         }
         foreach ($users as $key => $value) {
             if (isset($_COOKIE['toggle_active'])) {
                 if ($_COOKIE['toggle_active'] == 1 && !$value['active'] || $_COOKIE['toggle_active'] == -1 && $value['active']) {
                     unset($users[$key]);
                 }
             }
         }
         if (isset($_GET['excel'])) {
             $export_users[] = array(_USER, _MODULE_IDLE_USERS_LASTACTION, _STATUS);
             foreach ($users as $key => $value) {
                 $value['last_action'] ? $last_action = formatTimestamp($value['last_action']) : ($last_action = _NEVER);
                 $value['active'] ? $status = _ACTIVE : ($status = _INACTIVE);
                 $export_users[] = array(formatLogin($value['login']), $last_action, $status);
             }
             EfrontSystem::exportToCsv($export_users, true);
             exit;
         }
         if ($_GET['ajax'] == 'idleUsersTable') {
             list($tableSize, $users) = filterSortPage($users);
             $smarty->assign("T_SORTED_TABLE", $_GET['ajax']);
             $smarty->assign("T_TABLE_SIZE", $tableSize);
             $smarty->assign("T_DATA_SOURCE", $users);
         }
         if (isset($_GET['ajax']) && isset($_GET['archive_user'])) {
             if (isset($users[$_GET['archive_user']])) {
                 $user = EfrontUserFactory::factory($_GET['archive_user']);
                 $user->archive();
             }
             exit;
         } else {
             if (isset($_GET['ajax']) && isset($_GET['archive_all_users'])) {
                 //eF_updateTableData("users", array("archive" => 1, "active" => 0), "login in (select login from (select login,max(l.timestamp) as last_action from users u left outer join logs l on u.login=l.users_LOGIN where u.archive=0 and u.login != '".$_SESSION['s_login']."' group by login) r where r.last_action <= ".$_SESSION['timestamp_from']." or r.last_action is null)");
                 foreach ($users as $value) {
                     eF_updateTableData("users", array("archive" => 1, "active" => 0), "login='******'login'] . "'");
                 }
                 exit;
             } else {
                 if (isset($_GET['ajax']) && isset($_GET['toggle_user'])) {
                     if (isset($users[$_GET['toggle_user']])) {
                         $user = EfrontUserFactory::factory($_GET['toggle_user']);
                         if ($user->user['active']) {
                             $user->deactivate();
                         } else {
                             $user->activate();
                         }
                         echo json_encode(array('status' => 1, 'active' => $user->user['active']));
                     }
                     exit;
                 } else {
                     if (isset($_GET['ajax']) && isset($_GET['deactivate_all_users'])) {
                         //eF_updateTableData("users", array("active" => 0), "login in (select login from (select login,max(l.timestamp) as last_action from users u left outer join logs l on u.login=l.users_LOGIN where u.archive=0 and u.login != '".$_SESSION['s_login']."' group by login) r where r.last_action <= ".$_SESSION['timestamp_from']." or r.last_action is null)");
                         foreach ($users as $value) {
                             eF_updateTableData("users", array("active" => 0), "login='******'login'] . "'");
                         }
                         exit;
                     }
                 }
             }
         }
     } catch (Exception $e) {
         handleAjaxExceptions($e);
     }
     return true;
 }
Example #19
0
 public function __construct()
 {
     parent::__construct('add_category');
     $this->loadHttpVars();
     if ($this->loginError) {
         return;
     }
     $category = new pdCategory();
     if (isset($this->cat_id)) {
         if (!is_numeric($this->cat_id)) {
             $this->pageError = true;
             return;
         }
         $result = $category->dbLoad($this->db, $this->cat_id);
         if (!$result) {
             $this->pageError = true;
             return;
         }
     }
     if (isset($this->numNewFields)) {
         if (!is_numeric($this->numNewFields)) {
             $this->pageError = true;
             return;
         }
     } else {
         $this->numNewFields = 0;
     }
     if ($category->cat_id != '') {
         $label = 'Edit Category';
     } else {
         $label = 'Add Category';
     }
     $this->pageTitle = $label;
     $form = new HTML_QuickForm('catForm');
     $form->addElement('header', null, $this->helpTooltip($label, 'addCategoryPageHelp', 'helpHeading'));
     $form->addElement('text', 'catname', 'Category Name:', array('size' => 50, 'maxlength' => 250));
     $form->addRule('catname', 'category name cannot be empty', 'required', null, 'client');
     // info list
     $label = 'Related Fields:';
     $info_list = pdInfoList::create($this->db);
     foreach ($info_list as $info_id => $name) {
         $form->addElement('advcheckbox', 'info[' . $info_id . ']', $label, $name, null, array('', $name));
         $label = '';
     }
     for ($i = 0; $i < $this->numNewFields; $i++) {
         $form->addElement('text', 'new_fields[' . $i . ']', 'New field ' . ($i + 1) . ':', array('size' => 50, 'maxlength' => 250));
     }
     $form->addElement('hidden', 'numNewFields', $this->numNewFields);
     $form->addGroup(array(HTML_QuickForm::createElement('reset', 'reset', 'Reset'), HTML_QuickForm::createElement('button', 'add_field', 'Add Related Field', array('onClick' => 'dataKeep(' . ($this->numNewFields + 1) . ');')), HTML_QuickForm::createElement('submit', 'submit', 'Submit New Category')), 'submit_group', null, '&nbsp;');
     if ($form->validate()) {
         $values = $form->exportValues();
         $category->category = $values['catname'];
         if (isset($values['new_fields'])) {
             $values['info'] = array_merge($values['info'], $values['new_fields']);
         }
         foreach ($values['info'] as $infoname) {
             if ($infoname == '') {
                 continue;
             }
             $obj = new stdClass();
             $obj->name = $infoname;
             $category->info[] = $obj;
         }
         $category->dbSave($this->db);
         echo 'Category "', $category->category, '" succesfully added to the database.', '<p/>', '<a href="' . $_SERVER['PHP_SELF'] . '">', 'Add another new category</a>';
     } else {
         foreach (array_keys(get_class_vars(get_class($this))) as $member) {
             $defaults[$member] = $this->{$member};
         }
         $defaults['catname'] = $category->category;
         if (isset($category->info) && count($category->info) > 0) {
             foreach ($category->info as $info_id => $name) {
                 $defaults['info[' . $info_id . ']'] = $name;
             }
         }
         $form->setDefaults($defaults);
         $renderer =& $form->defaultRenderer();
         $form->accept($renderer);
         $this->form =& $form;
         $this->renderer =& $renderer;
         $this->javascript();
     }
 }
Example #20
0
 public function getModule()
 {
     $smarty = $this->getSmartyVar();
     $currentLesson = $this->getCurrentLesson();
     $currentUser = $this->getCurrentUser();
     try {
         $currentContent = new EfrontContentTree($_SESSION['s_lessons_ID']);
         //Initialize content
     } catch (Exception $e) {
         $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString());
         $message = _ERRORLOADINGCONTENT . ": " . $_SESSION['s_lessons_ID'] . ": " . $e->getMessage() . ' (' . $e->getCode() . ') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>';
     }
     //pr($currentUser);exit;
     $roles = EfrontUser::getRoles();
     //pr($roles);
     if ($roles[$currentUser->lessons[$_SESSION['s_lessons_ID']]] == "professor") {
         if (isset($_GET['view_list']) && eF_checkParameter($_GET['view_list'], 'id')) {
             $list = $currentContent->seekNode($_GET['view_list']);
             $questions = $list->getQuestions(true);
             $crosslists = array();
             $possibleCrosslistsIds = array();
             foreach ($questions as $key => $value) {
                 if ($value->question['type'] == 'empty_spaces') {
                     $crosslists[] = $value;
                     $possibleCrosslistsIds[] = $value->question['id'];
                 }
             }
             $questions = $crosslists;
             //pr($questions);
             foreach ($questions as $qid => $question) {
                 $questions[$qid]->question['text'] = str_replace('#', '_', strip_tags($question->question['text']));
                 //If we ommit this line, then the questions list is html formatted, images are displayed etc, which is *not* the intended behaviour
                 //$questions[$qid]->question['answer']           = unserialize($question->question['answer']);
             }
             $res = eF_getTableData("module_crossword_words", "crosslists,options", "content_ID=" . $_GET['view_list']);
             $resCrosslists = unserialize($res[0]['crosslists']);
             $smarty->assign("T_CROSSWORD_LIST_WORDS", $resCrosslists);
             $post_target = $this->moduleBaseUrl . '&view_list=' . $_GET['view_list'] . "&tab=options";
             //Create form elements
             $form = new HTML_QuickForm("list_options", "post", $post_target, "", null, true);
             $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
             $form->addElement('advcheckbox', 'active', _CROSSWORD_ACTIVE, null, 'class = "inputCheckbox"', array(0, 1));
             $form->addElement("text", "max_word", _LOW, 'size = "5"');
             $form->addRule('max_word', _INVALIDFIELDDATA . ":" . _LOW, 'checkParameter', 'id');
             $form->addElement('advcheckbox', 'reveal_answer', _CROSSWORD_SHOWANSWERFIRST, null, 'class = "inputCheckbox"', array(0, 1));
             $form->addElement('advcheckbox', 'save_pdf', _CROSSWORD_SAVEPDF, null, 'class = "inputCheckbox"', array(0, 1));
             $form->addElement('submit', 'submit_options', _SAVECHANGES, 'onclick ="return optionSubmit();" class = "flatButton"');
             //The submit content button
             $options = unserialize($res[0]['options']);
             $form->setDefaults(array('active' => $options['active'], 'reveal_answer' => $options['reveal_answer'], 'save_pdf' => $options['save_pdf'], 'max_word' => $options['max_word']));
             if ($form->isSubmitted() && $form->validate()) {
                 //If the form is submitted and validated
                 $values = $form->exportValues();
                 unset($values['submit_options']);
                 $options = serialize($values);
                 if (sizeof($res) != 0) {
                     $ok = eF_updateTableData("module_crossword_words", array('options' => $options), "content_ID=" . $_GET['view_list']);
                 } else {
                     $fields = array('content_ID' => $_GET['view_list'], 'options' => $options);
                     $ok = eF_insertTableData("module_crossword_words", $fields);
                 }
                 if ($ok !== false) {
                     $message = _CROSSWORD_SUCCESSFULLY;
                     $message_type = 'success';
                 } else {
                     $message = _CROSSWORD_PROBLEMOCCURED;
                     $message_type = 'failure';
                 }
                 eF_redirect("" . $this->moduleBaseUrl . "&view_list=" . $_GET['view_list'] . "&tab=options&message=" . urlencode($message) . "&message_type=" . $message_type);
             }
             $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
             //Create a smarty renderer
             $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
             //Set javascript error messages
             $form->setRequiredNote(_REQUIREDNOTE);
             $form->accept($renderer);
             //Assign this form to the renderer, so that corresponding template code is created
             $smarty->assign('T_CROSSWORD_OPTIONS', $renderer->toArray());
             //Assign the form to the template
             if (isset($_GET['postAjaxRequest'])) {
                 try {
                     $result = eF_getTableData("module_crossword_words", "crosslists", "content_ID=" . $_GET['view_list']);
                     //pr($result);exit;
                     $crosslistsArray = unserialize($result[0]['crosslists']);
                     if (isset($_GET['id']) && eF_checkParameter($_GET['id'], 'id')) {
                         if (!in_array($_GET['id'], array_values($crosslistsArray))) {
                             $crosslistsArray[] = $_GET['id'];
                             $crosslists = serialize($crosslistsArray);
                             if (sizeof($result) != 0) {
                                 $fields = array('crosslists' => $crosslists);
                                 eF_updateTableData("module_crossword_words", $fields, "content_ID=" . $_GET['view_list']);
                             } else {
                                 $fields = array('content_ID' => $_GET['view_list'], 'crosslists' => $crosslists);
                                 eF_insertTableData("module_crossword_words", $fields);
                             }
                         } elseif (in_array($_GET['id'], array_values($crosslistsArray))) {
                             unset($crosslistsArray[array_search($_GET['id'], $crosslistsArray)]);
                             if (!empty($crosslistsArray)) {
                                 $crosslists = serialize($crosslistsArray);
                                 $fields = array('crosslists' => $crosslists);
                                 eF_updateTableData("module_crossword_words", $fields, "content_ID=" . $_GET['view_list']);
                             } else {
                                 eF_deleteTableData("module_crossword_words", "content_ID=" . $_GET['view_list']);
                             }
                         }
                     } else {
                         if (isset($_GET['addAll'])) {
                             $crosslists = serialize($possibleCrosslistsIds);
                             if (sizeof($result) != 0) {
                                 $fields = array('crosslists' => $crosslists);
                                 eF_updateTableData("module_crossword_words", $fields, "content_ID=" . $_GET['view_list']);
                             } else {
                                 $fields = array('content_ID' => $_GET['view_list'], 'crosslists' => $crosslists);
                                 eF_insertTableData("module_crossword_words", $fields);
                             }
                         } else {
                             if (isset($_GET['removeAll'])) {
                                 $fields = array('crosslists' => "");
                                 eF_updateTableData("module_crossword_words", $fields, "content_ID=" . $_GET['view_list']);
                             }
                         }
                     }
                 } catch (Exception $e) {
                     header("HTTP/1.0 500 ");
                     echo $e->getMessage() . ' (' . $e->getCode() . ')';
                 }
                 exit;
             }
             $smarty->assign("T_CROSSWORD_CROSSLISTS", $crosslists);
             $smarty->assign("T_CROSSWORD_CROSSLISTS_SIZE", sizeof($crosslists));
         } else {
             $listsArray = array();
             $iterator = new EfrontContentFilterIterator(new EfrontNodeFilterIterator(new RecursiveIteratorIterator($currentContent->tree, RecursiveIteratorIterator::SELF_FIRST)));
             foreach ($iterator as $key => $value) {
                 $questions = $value->getQuestions(true);
                 $crosslists = array();
                 foreach ($questions as $key2 => $value2) {
                     if ($value2->question['type'] == 'empty_spaces') {
                         $crosslists[] = $value2;
                     }
                 }
                 if (sizeof($crosslists) > 0) {
                     $listsArray[$value['id']] = array('id' => $value['id'], 'name' => $value['name'], 'questions' => sizeof($crosslists));
                 }
             }
             if (!empty($listsArray)) {
                 $str = implode(",", array_keys($listsArray));
                 $lists = eF_getTableDataFlat("module_crossword_words", "*", "content_ID IN (" . $str . ")");
                 $listsTemp = array_combine(array_values($lists['content_ID']), array_values($lists['options']));
                 $listsTemp2 = array_combine(array_values($lists['content_ID']), array_values($lists['crosslists']));
                 foreach ($listsArray as $key => $value) {
                     $listsArray[$value['id']]['options'] = unserialize($listsTemp[$key]);
                     $crosslistsTemp = unserialize($listsTemp2[$key]);
                     $listsArray[$value['id']]['num_crosslists'] = empty($crosslistsTemp) ? 0 : sizeof($crosslistsTemp);
                 }
             }
             $smarty->assign("T_CROSSWORD_WORDS", $listsArray);
         }
     } elseif ($roles[$currentUser->lessons[$_SESSION['s_lessons_ID']]] == "student") {
         if (isset($_GET['restart_list']) && eF_checkParameter($_GET['restart_list'], 'id')) {
             eF_deleteTableData("module_crossword_users", "users_LOGIN='******'s_login'] . "' AND content_ID=" . $_GET['restart_list']);
         }
         if (isset($_GET['restart_lists'])) {
             eF_deleteTableData("module_crossword_users", "users_LOGIN='******'s_login'] . "'");
         }
         if ($_GET['answer'] == "true") {
             $resUserCard = eF_getTableData("module_crossword_users", "*", "crosslists_ID=" . $_GET['view_card'] . " and users_LOGIN='******'s_login'] . "'");
             if (sizeof($resUserCard) == 0) {
                 $fields = array('users_LOGIN' => $_SESSION['s_login'], 'content_ID' => $_GET['view_list'], 'crosslists_ID' => $_GET['view_card'], 'success' => '1');
                 eF_insertTableData("module_crossword_users", $fields);
             } else {
                 $success = $resUserCard[0]['success'] + 1;
                 eF_updateTableData("module_crossword_users", array('success' => $success), "crosslists_ID=" . $_GET['view_card'] . " and users_LOGIN='******'s_login'] . "'");
             }
         } elseif ($_GET['answer'] == "false") {
             $resUserCard = eF_getTableData("module_crossword_users", "*", "crosslists_ID=" . $_GET['view_card'] . " and users_LOGIN='******'s_login'] . "'");
             $currentListTemp = eF_getTableData("module_crossword_words", "options", "content_ID=" . $_GET['view_list']);
             $listTemp = unserialize($currentListTemp[0]['options']);
             if ($listTemp['wrong'] == 1 && sizeof($resUserCard) != 0 && $resUserCard[0]['success'] != 0) {
                 $success = $resUserCard[0]['success'] - 1;
                 eF_updateTableData("module_crossword_users", array('success' => $success), "crosslists_ID=" . $_GET['view_card'] . " and users_LOGIN='******'s_login'] . "'");
             }
         }
         $listsArray = array();
         $iterator = new EfrontContentFilterIterator(new EfrontNodeFilterIterator(new RecursiveIteratorIterator($currentContent->tree, RecursiveIteratorIterator::SELF_FIRST)));
         foreach ($iterator as $key => $value) {
             $listsArray[$value['id']] = array('id' => $value['id'], 'name' => $value['name']);
         }
         if (empty($listsArray)) {
             $smarty->assign("T_CROSSWORD_WORDSNAMES", $listsArray);
             return true;
         }
         $str = implode(",", array_keys($listsArray));
         $lists = eF_getTableData("module_crossword_words", "*", "content_ID IN (" . $str . ")");
         $mastery = eF_getTableDataFlat("module_crossword_users", "*", "content_ID IN (" . $str . ")");
         $masteryArray = array_combine(array_values($mastery['crosslists_ID']), array_values($mastery['success']));
         $questionsDiff = eF_getTableDataFlat("questions", "*", "content_ID IN (" . $str . ")");
         $questionsDiffArray = array_combine(array_values($questionsDiff['id']), array_values($questionsDiff['difficulty']));
         $validLists = array();
         foreach ($lists as $key => $value) {
             $opt = unserialize($value['options']);
             $crosslists = unserialize($value['crosslists']);
             if ($opt['active'] == 1 && !empty($crosslists)) {
                 $value['number_crosslists'] = empty($crosslists) ? 0 : sizeof($crosslists);
                 $validLists[$value['content_ID']] = $value;
                 $validLists[$value['content_ID']]['options'] = $opt;
                 $finishedCrosslists = 0;
                 foreach ($crosslists as $index => $item) {
                     if ($masteryArray[$item] == $opt[$questionsDiffArray[$item]]) {
                         $finishedCrosslists++;
                     }
                 }
                 $conid = $validLists[$value['content_ID']]['content_ID'];
                 $validLists[$value['content_ID']]['non_finished'] = $value['number_crosslists'] - $finishedCrosslists;
                 $validLists[$value['content_ID']]['mastery'] = (double) $finishedCrosslists / sizeof($crosslists) * 100;
                 $respoints = eF_getTableDataFlat("module_crossword_users", "*", "content_ID = '{$conid}' and users_LOGIN='******'s_login'] . "'");
                 $validLists[$value['content_ID']]['points'] = round($respoints['points'][0] / $respoints['totallength'][0] * 100);
                 $validLists[$value['content_ID']]['crosstime'] = $respoints['wordtime'][0];
             }
         }
         //print_r($validLists);
         $smarty->assign("T_CROSSWORD_WORDS", $validLists);
         $smarty->assign("T_CROSSWORD_WORDSNAMES", $listsArray);
         if (isset($_GET['view_list']) && !isset($_GET['pdf'])) {
             $resunit = eF_getTableData("content", "name", "id=" . $_GET['view_list']);
             $smarty->assign("T_CROSSWORD_UNITNAME", $resunit[0]['name']);
             $_SESSION['contentid'] = $_GET['view_list'];
             if (isset($_POST) && !empty($_POST['crosstime'])) {
                 $userlist = eF_getTableData("module_crossword_users", "*", "users_LOGIN='******'s_login'] . "' and content_ID=" . $_GET['view_list'] . "");
                 if (count($userlist) == 0) {
                     $fields = array('users_LOGIN' => $_SESSION['s_login'], 'content_ID' => $_GET['view_list'], 'points' => $_POST['points'], 'totallength' => $_SESSION['WORDLEN'], 'wordtime' => $_POST['crosstime']);
                     eF_insertTableData("module_crossword_users", $fields);
                 } else {
                     $fields = array('points' => $_POST['points'], 'totallength' => $_SESSION['WORDLEN'], 'wordtime' => $_POST['crosstime']);
                     eF_updateTableData("module_crossword_users", $fields, "content_ID=" . $_GET['view_list'] . " and users_LOGIN='******'s_login'] . "'");
                 }
                 $message_type = 'success';
                 $message = _CROSSWORD_GAME_SUCCESSFULLY;
                 eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=" . $message_type);
             }
             $contentid = $_GET['view_list'];
             $res = eF_getTableData("module_crossword_words", "crosslists,options", "content_ID=" . $_GET['view_list']);
             $reswords = unserialize($res[0]['crosslists']);
             $maxwords = unserialize($res[0]['options']);
             $maxwords1 = $maxwords['max_word'];
             $smarty->assign("T_CROSSWORD_REVEALANSWER", $maxwords['reveal_answer']);
             $smarty->assign("T_CROSSWORD_MAXWORD", $maxwords1 + 1);
             $_SESSION['CROSSWORD_MAXWORD'] = $maxwords1;
             require_once 'init.php';
             $rowquesans = "";
             foreach ($reswords as $rowques) {
                 $rowquesans .= $rowques . ",";
             }
             $quesids = mb_substr($rowquesans, 0, -1);
             $quesans = eF_getTableData("questions", "text,answer", "id IN({$quesids}) order by rand() limit {$maxwords1}");
             $value = array();
             foreach ($quesans as $row) {
                 $answer = unserialize($row['answer']);
                 $answer1 = explode("|", $answer['0']);
                 $value[] = array('ANSWER' => $answer1['0'], 'QUESTION' => $row['text']);
             }
             if (!empty($value)) {
                 //pr($value);exit;
                 $success = $pc->generateFromWords($value);
                 if (!$success) {
                     $message_type = 'failure';
                     $message = _CROSSWORD_UNABLEGENERATECROSSWORD;
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=" . $message_type);
                 } else {
                     $words = $pc->getWords();
                     $wordlen = "";
                     foreach ($words as $rowwords) {
                         $wordlen = $wordlen + $rowwords['wordlength'];
                     }
                     $_SESSION['WORDLEN'] = $wordlen;
                     $smarty->assign("T_CROSSWORD_LENGTH", $_SESSION['WORDLEN']);
                     //vd($words);
                     //because of #1599
                     foreach ($words as $key => $word) {
                         $words[$key]['question'] = str_replace(array("\r\n", "\n"), '<br/>', $word['question']);
                     }
                     //vd($words);
                     $smarty->assign("T_CROSSWORD_ANSWERS", $words);
                 }
             }
             $post_target = $this->moduleBaseUrl . "&view_list=" . $_GET['view_list'] . "";
             $form = new HTML_QuickForm("crossword_game", "post", $post_target, "", null, true);
             $form->addElement('submit', 'submit_crossword', 'SUBMIT', 'class = "flatButton"');
             //The submit content button
             $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
             //Create a smarty renderer
             $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
             //Set javascript error messages
             $form->setRequiredNote(_REQUIREDNOTE);
             $form->accept($renderer);
             //Assign this form to the renderer, so that corresponding template code is created
             $smarty->assign('T_CROSSWORD_SUBMIT', $renderer->toArray());
             //Assign the form to the template
             $message = "";
             //$message_type = 'success';
             // eF_redirect("".$this -> moduleBaseUrl."&popup=1&finish=1&message=".$message."&message_type=".$message_type);
         } else {
             if (isset($_GET['view_list']) && isset($_GET['pdf']) && $_GET['pdf'] == 'cross') {
                 $resunit = eF_getTableData("content", "name,lessons_ID", "id=" . $_GET['view_list']);
                 $reslesson = eF_getTableData("lessons", "name", "id=" . $resunit[0]['lessons_ID']);
                 $res = eF_getTableData("module_crossword_words", "crosslists,options", "content_ID=" . $_GET['view_list']);
                 $reswords = unserialize($res[0]['crosslists']);
                 $maxwords = unserialize($res[0]['options']);
                 $maxwords1 = $maxwords['max_word'];
                 $_SESSION['CROSSWORD_MAXWORD'] = $maxwords1;
                 require_once 'init.php';
                 $rowquesans = "";
                 foreach ($reswords as $rowques) {
                     $rowquesans .= $rowques . ",";
                 }
                 $quesids = mb_substr($rowquesans, 0, -1);
                 $quesans = eF_getTableData("questions", "text,answer", "id IN({$quesids}) order by rand() limit {$maxwords1}");
                 $value = array();
                 foreach ($quesans as $row) {
                     $answer = unserialize($row['answer']);
                     $answer1 = explode("|", $answer['0']);
                     $value[] = array('ANSWER' => $answer1['0'], 'QUESTION' => $row['text']);
                 }
                 $success = $pc->generateFromWords($value);
                 if (!$success) {
                     $message_type = 'failure';
                     $message = _CROSSWORD_UNABLEGENERATECROSSWORD;
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type=" . $message_type);
                 } else {
                     $currentlesson = $reslesson[0]['name'];
                     $words = $pc->getWords();
                     $answor = array();
                     $html1 = array();
                     $html2 = array();
                     $html1[] = $currentlesson;
                     $html1[] .= $resunit[0]['name'];
                     $html1[] .= _CROSSWORD_ACROSS;
                     $html2[] = _CROSSWORD_DOWN;
                     $k = 1;
                     //pr($words);
                     foreach ($words as $row) {
                         if ($row['axis'] == 1) {
                             $html1[] .= $k . '. ' . $row['question'];
                         } else {
                             $html2[] .= $k . '. ' . $row['question'];
                         }
                         $k++;
                     }
                     //pr($html1);
                     //pr($html2);
                     //exit;
                     $answor[] = array_merge($html1, $html2);
                     //pr($answor); exit;
                     $dd = $pc->getHTML($answor);
                     exit;
                 }
             }
         }
     }
     return true;
 }
Example #21
0
 $frmEdit->addElement('hidden', 'hidId', $initialGalleryImageId, array('id' => 'hidId'));
 $frmEdit->addElement('hidden', 'hidOffsetValue', $thumbOffsetValue, array('id' => 'hidOffsetValue'));
 $frmEdit->addElement('radio', 'radVisibility', 'Visibility:', 'Show', 'SHOW', array('id' => 'radVisibility', 'class' => 'editable'));
 $frmEdit->addElement('radio', 'radVisibility', '', 'Hide', 'HIDE', array('id' => 'radVisibility', 'class' => 'editable'));
 $frmEdit->addElement('select', 'selGallery', 'Gallery', $galleries, array('id' => 'selGallery', 'class' => 'editable'));
 $frmEdit->addElement('submit', 'btnEdit', "Save Changes", array('id' => 'btnEdit'));
 /* Set the default values of the radio buttons and the select box. */
 $frmEdit->setDefaults(array('radVisibility' => $visibility, 'selGallery' => $initialGalleryId));
 /* Define form validation rules. */
 $frmEdit->addRule('txtTitle', 'You must enter a title.', 'required');
 $frmEdit->addRule('txtTitle', 'The title must be no more than 64 characters long.', 'maxlength', '64');
 $frmEdit->addRule('selGallery', 'You must select a gallery.', 'required');
 /* Try to validate the form. */
 if ($frmEdit->validate()) {
     /* Get the values submitted by the form. */
     $values = $frmEdit->exportValues();
     /* The id of the image that is being updated. */
     $updatedGalleryImageId = $values['hidId'];
     /* If the image has been moved to another gallery, the submitted gallery id won't match the initial gallery id.
      * In this case, don't overwrite the initial gallery id. */
     if ($values['selGallery'] == $initialGalleryId) {
         /* Overwrite the already initialised thumbnail image with the properties of the updated gallery image id. ($updatedGalleryImageId) */
         $filename = $artworks[$updatedGalleryImageId]['filename'];
         $thumbOrientation = $artworks[$updatedGalleryImageId]['thumb_orientation'];
         $thumbOffsetMax = $artworks[$updatedGalleryImageId]['thumb_offset_max'];
         $thumbElement->setText('<div class="crop" data-orientation="' . $thumbOrientation . '" data-offset-max="' . $thumbOffsetMax . '"><img src="' . $filename . '" alt="" /></div>');
     }
     try {
         /* Save the updated properties of the artwork to the database. */
         $sql = "\n                    UPDATE\n                      gallery_images\n                    SET\n                      title = :title,\n                      thumb_offset_value = :thumb_offset_value,\n                      visibility = :visibility,\n                      gallery_id = :gallery_id\n                    WHERE\n                      id = :id\n                ";
         $stmt = $pdo->prepare($sql);
<?php

require 'include_elevforeningen_login.php';
$values = $auth->getContact($_SESSION['contact_id']);
$values = utf8_decoding($values);
$form = new HTML_QuickForm();
$form->addElement('hidden', 'id');
$form->addElement('text', 'name', 'Navn', array('size' => 40));
$form->addElement('text', 'address', 'Adresse', array('size' => 40));
$form->addElement('text', 'postcode', 'Postnr.', array('size' => 4));
$form->addElement('text', 'city', 'Postby', array('size' => 40));
$form->addElement('text', 'email', 'E-mail', array('size' => 40));
$form->addElement('text', 'phone', 'Telefon', array('size' => 8));
$form->addElement('submit', NULL, 'Gem');
$form->setDefaults(array('id' => $values['id'], 'name' => $values['name'], 'address' => $values['address'], 'postcode' => $values['postcode'], 'city' => $values['city'], 'phone' => $values['phone'], 'email' => $values['email']));
if ($form->validate()) {
    if ($auth->saveContact($form->exportValues())) {
        header('Location: index.php');
        exit;
    } else {
        trigger_error('Kunne ikke gemme', E_USER_ERROR);
    }
}
$tpl = new Template(PATH_TEMPLATE_KUNDELOGIN);
$tpl->set('content_main', '
    <h1>Ret oplysninger</h1>
    <p><a href="index.php">Luk uden at gemme</a></p>
    ' . $form->toHTML());
echo $tpl->fetch('main.tpl.php');
 /**
  * The main functionality
  *
  * (non-PHPdoc)
  * @see libraries/EfrontModule#getModule()
  */
 public function getModule()
 {
     $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_TABLE_OPTIONS", array(array('image' => $this->moduleBaseLink . 'img/order.png', 'text' => _MODULE_SECURITY_RECHECKLOCALFILES, 'href' => $this->moduleBaseUrl . '&delete_local_list=1'), array('image' => $this->moduleBaseLink . 'img/refresh.png', 'text' => _MODULE_SECURITY_RECHECKSERVERFILES, 'href' => $this->moduleBaseUrl . '&delete_remote_list=1'), array('image' => $this->moduleBaseLink . 'img/rules.png', 'text' => _MODULE_SECURITY_RESETIGNORELIST, 'href' => $this->moduleBaseUrl . '&delete_ignore_list=1')));
     if (isset($_GET['download_ignore_list'])) {
         try {
             $file = new EfrontFile($this->getIgnoreListName());
             $file->sendFile(true);
         } catch (Exception $e) {
             $this->setMessageVar('The list is empty', 'failure');
         }
     } else {
         if ($_GET['delete_remote_list']) {
             $file = new EfrontFile($this->getCachedRemoteListName());
             $file->delete();
         } else {
             if ($_GET['delete_local_list']) {
                 $file = new EfrontFile($this->getLocalListName());
                 $file->delete();
             } else {
                 if ($_GET['delete_ignore_list']) {
                     try {
                         $file = new EfrontFile($this->getIgnoreListName());
                         $file->delete();
                     } catch (Exception $e) {
                     }
                 }
             }
         }
     }
     if (isset($_GET['download'])) {
         $_GET['download'] = base64_decode($_GET['download']);
     }
     $form = new HTML_QuickForm("demo_form", "post", $this->moduleBaseUrl . "&type=" . $_GET['type'], "", null, true);
     switch ($_GET['type']) {
         case 'install':
             $form->addElement('submit', 'submit_delete_install', _MODULE_SECURITY_DELETEINSTALLDIRECTORY, 'class = "flatButton"');
             break;
         case 'magic_quotes_gpc':
             break;
         case 'default_accounts':
             $form->addElement('submit', 'submit_deactivate', _MODULE_SECURITY_DEACTIVATEDEFAULTACCOUNTS, 'class = "flatButton"  title = "Click this to deactivate these accounts"');
             break;
         case 'changed_files':
             list($changed_files, $new_files) = $this->checksumCheck();
             $smarty->assign("T_CHANGED_FILES", $changed_files);
             if (isset($_GET['download']) && in_array($_GET['download'], array_keys($changed_files)) && $_GET['download'] != 'libraries/configuration.php') {
                 try {
                     $file = new EfrontFile(G_ROOTPATH . $_GET['download']);
                     $file->sendFile(true);
                     exit;
                 } catch (Exception $e) {
                     $this->setMessageVar(_MODULE_SECURITY_FILECOULDNOTBEDELETED, 'failure');
                 }
             } else {
                 if (isset($_GET['ignore']) && in_array($_GET['ignore'], array_keys($changed_files))) {
                     $this->addToIgnoreList($_GET['ignore']);
                     echo json_encode(array('success' => true));
                     exit;
                 }
             }
             $form->addElement('submit', 'submit_recheck', _MODULE_SECURITY_RECHECKFILES, 'class = "flatButton" ');
             $form->addElement('submit', 'reset_ignore_list', _MODULE_SECURITY_RESETIGNORELIST, 'class = "flatButton" ');
             $form->addElement('submit', 'ignore_changed_all', _MODULE_SECURITY_IGNOREALL, 'class = "flatButton" ');
             break;
         case 'new_files':
             list($changed_files, $new_files) = $this->checksumCheck();
             if (isset($_GET['download']) && in_array($_GET['download'], array_keys($new_files)) && $_GET['download'] != 'libraries/configuration.php') {
                 try {
                     $file = new EfrontFile(G_ROOTPATH . $_GET['download']);
                     $file->sendFile(true);
                     exit;
                 } catch (Exception $e) {
                     $this->setMessageVar(_MODULE_SECURITY_FILECOULDNOTBEDELETED, 'failure');
                 }
             } else {
                 if (isset($_GET['ignore']) && in_array($_GET['ignore'], array_keys($new_files))) {
                     $this->addToIgnoreList($_GET['ignore']);
                 } else {
                     if (isset($_GET['delete']) && in_array($_GET['delete'], array_keys($new_files))) {
                         try {
                             $file = new EfrontFile(G_ROOTPATH . $_GET['delete']);
                             $file->delete();
                         } catch (Exception $e) {
                         }
                         $file = new EfrontFile($this->getLocalListName());
                         $file->delete();
                         list($changed_files, $new_files) = $this->checksumCheck();
                     }
                 }
             }
             $smarty->assign("T_NEW_FILES", $new_files);
             $form->addElement('submit', 'submit_recheck', _MODULE_SECURITY_RECHECKFILES, 'class = "flatButton" ');
             $form->addElement('submit', 'reset_ignore_list', _MODULE_SECURITY_RESETIGNORELIST, 'class = "flatButton" ');
             $form->addElement('submit', 'ignore_new_all', _MODULE_SECURITY_IGNOREALL, 'class = "flatButton" ');
             break;
         default:
             $smarty->assign("T_SECURITY_FEEDS", $this->getRssFeeds());
             try {
                 $smarty->assign("T_LOCAL_ISSUES", $this->checkLocalIssues());
             } catch (Exception $e) {
                 $this->setMessageVar($e->getMessage(), 'failure');
             }
             break;
     }
     if ($form->isSubmitted() && $form->validate()) {
         try {
             $values = $form->exportValues();
             if ($values['submit_recheck']) {
                 $file = new EfrontFile($this->getLocalListName());
                 $file->delete();
                 eF_redirect($this->moduleBaseUrl . '&type=' . $_GET['type'] . '&message=' . urlencode(_OPERATIONCOMPLETEDSUCCESSFULLY) . '&message_type=success');
             } else {
                 if ($values['submit_delete_install']) {
                     file_get_contents(G_SERVERNAME . 'index.php?delete_install=1');
                     eF_redirect($this->moduleBaseUrl . '&type=' . $_GET['type'] . '&message=' . urlencode(_OPERATIONCOMPLETEDSUCCESSFULLY) . '&message_type=success');
                 } else {
                     if ($values['submit_deactivate']) {
                         $result = eF_updateTableData("users", array('active' => 0), "(login = '******' and password = '******') or (login = '******' and password = '******')");
                         eF_redirect($this->moduleBaseUrl . '&message=' . urlencode(_OPERATIONCOMPLETEDSUCCESSFULLY) . '&message_type=success');
                     } else {
                         if ($values['reset_ignore_list']) {
                             try {
                                 $file = new EfrontFile($this->getIgnoreListName());
                                 $file->delete();
                                 eF_redirect($this->moduleBaseUrl . '&type=' . $_GET['type'] . '&message=' . urlencode(_OPERATIONCOMPLETEDSUCCESSFULLY) . '&message_type=success');
                             } catch (Exception $e) {
                                 $this->setMessageVar(_MODULE_SECURITY_THELISTISEMTPY, 'failure');
                             }
                         } else {
                             if ($values['ignore_new_all']) {
                                 list($changed_files, $new_files) = $this->checksumCheck();
                                 foreach ($new_files as $key => $value) {
                                     $this->addToIgnoreList($key);
                                 }
                                 eF_redirect($this->moduleBaseUrl . '&type=new_files&message=' . urlencode(_OPERATIONCOMPLETEDSUCCESSFULLY) . '&message_type=success');
                             } else {
                                 if ($values['ignore_changed_all']) {
                                     list($changed_files, $new_files) = $this->checksumCheck();
                                     foreach ($changed_files as $key => $value) {
                                         $this->addToIgnoreList($key);
                                     }
                                     eF_redirect($this->moduleBaseUrl . '&type=changed_files&message=' . urlencode(_OPERATIONCOMPLETEDSUCCESSFULLY) . '&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>';
             $this->setMessageVar($message, 'failure');
         }
     }
     $renderer = prepareFormRenderer($form);
     $smarty->assign('T_SECURITY_FORM', $renderer->toArray());
     //$feeds = $this->getRssFeeds(true, false);
     //$smarty->assign("T_SECURITY_FEEDS", $feeds);
     return true;
 }
 public function getModule()
 {
     $smarty = $this->getSmartyVar();
     global $load_editor;
     $load_editor = true;
     $current_user = $this->getCurrentUser();
     $smarty->assign("T_MODULE_CURRENT_USER", $current_user->getType());
     $form = new HTML_QuickForm("module_mail_form", "post", $this->moduleBaseUrl, "", "id = 'module_mail_form'");
     $form->addElement('hidden', 'recipients', $_GET['rec']);
     $form->addElement('text', 'subject', _SUBJECT, 'class = "inputText" style = "width:400px"');
     $form->addElement('textarea', 'body', _BODY, 'class = "simpleEditor" style = "width:100%;height:200px"');
     $form->addElement('checkbox', 'email', _SENDASEMAILALSO, null, 'id = "send_as_email" class = "inputCheckBox"');
     $form->addRule('subject', _THEFIELD . ' "' . _SUBJECT . '" ' . _ISMANDATORY, 'required', null, 'client');
     $form->addRule('recipients', _THEFIELD . ' "' . _RECIPIENTS . '" ' . _ISMANDATORY, 'required', null, 'client');
     $form->addElement('file', 'attachment[0]', _ATTACHMENT, null, 'class = "inputText"');
     $form->addElement('submit', 'submit_mail', _SEND, 'class = "flatButton"');
     if ($form->isSubmitted() && $form->validate()) {
         $values = $form->exportValues();
         switch ($values['recipients']) {
             case "lesson_students":
                 $lesson = new EfrontLesson($_SESSION['s_lessons_ID']);
                 $lessonUsers = $lesson->getUsers("student");
                 foreach ($lessonUsers as $value) {
                     $mail_recipients[] = $value['login'];
                 }
                 //pr($mail_recipients);return;
                 break;
             case "lesson_professors":
                 $lesson = new EfrontLesson($_SESSION['s_lessons_ID']);
                 $lessonUsers = $lesson->getUsers("professor");
                 if (isset($_SESSION['s_courses_ID'])) {
                     $course = new EfrontCourse($_SESSION['s_courses_ID']);
                     $course_users = $course->getCourseUsers();
                     foreach ($lessonUsers as $key => $value) {
                         if (!isset($course_users[$key])) {
                             unset($lessonUsers[$key]);
                         }
                     }
                 }
                 foreach ($lessonUsers as $value) {
                     $mail_recipients[] = $value['login'];
                 }
                 break;
             case "admin":
                 $result = eF_getTableData("users", "*", "user_type='administrator' and user_types_ID=0 and archive = 0");
                 //not
                 foreach ($result as $value) {
                     $mail_recipients[] = $value['login'];
                 }
                 break;
         }
         //$list = implode(",",$mail_recipients);
         $pm = new eF_PersonalMessage($_SESSION['s_login'], $mail_recipients, $values['subject'], $values['body']);
         if ($_FILES['attachment']['name'][0] != "") {
             $maxFileSize = FileSystemTree::getUploadMaxSize();
             if ($_FILES['attachment']['size'][0] == 0 || $_FILES['attachment']['size'][0] > $maxFileSize * 1024) {
                 //	G_MAXFILESIZE is deprecated
                 $message = _EACHFILESIZEMUSTBESMALLERTHAN . " " . G_MAXFILESIZE . " Bytes";
                 $message_type = 'failure';
             }
             //Upload user avatar file
             $pm->sender_attachment_timestamp = time();
             $user_dir = G_UPLOADPATH . $_SESSION['s_login'] . '/message_attachments/Sent/' . $pm->sender_attachment_timestamp . '/';
             mkdir($user_dir, 0755);
             $filesystem = new FileSystemTree($user_dir);
             $uploadedFile = $filesystem->uploadFile('attachment', $user_dir, 0);
             $pm->sender_attachment_fileId = $uploadedFile['id'];
             $pm->setAttachment($uploadedFile['path']);
         }
         if ($pm->send($values['email'], $values)) {
             $message = _MESSAGEWASSENT;
             $message_type = 'success';
         } else {
             $message = $pm->errorMessage;
             $message_type = 'failure';
         }
     }
     $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
     //Create a smarty renderer
     $renderer->setRequiredTemplate('{$html}{if $required}
     	&nbsp;<span class = "formRequired">*</span>
 		{/if}');
     $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
     //Set javascript error messages
     $form->setRequiredNote(_REQUIREDNOTE);
     $form->accept($renderer);
     //Assign this form to the renderer, so that corresponding template code is created
     $smarty->assign('T_MODULE_MAIL_FORM', $renderer->toArray());
     $smarty->assign("T_MESSAGE_MAIL", $message);
     $smarty->assign("T_MESSAGE_MAIL_TYPE", $message_type);
     //pr($renderer -> toArray());
     return true;
 }
Example #25
0
 public function getSmartyTpl()
 {
     $smarty = $this->getSmartyVar();
     $smarty->assign("T_RSS_MODULE_BASEURL", $this->moduleBaseUrl);
     $smarty->assign("T_RSS_MODULE_BASELINK", $this->moduleBaseLink);
     $smarty->assign("T_RSS_PROVIDED_FEEDS_MODES", $this->feedProviderModes);
     $smarty->assign("T_RSS_PROVIDED_FEEDS_TYPES", $this->providedFeeds);
     $smarty->assign("T_RSS_PROVIDED_FEEDS_LESSON_TYPES", $this->lessonProvidedFeeds);
     if (isset($_GET['delete_feed']) && eF_checkParameter($_GET['delete_feed'], 'id')) {
         try {
             if ($_GET['type'] == 'provider') {
                 eF_deleteTableData("module_rss_provider", "id=" . $_GET['delete_feed']);
             } else {
                 eF_deleteTableData("module_rss_feeds", "id=" . $_GET['delete_feed']);
             }
         } catch (Exception $e) {
             handleAjaxExceptions($e);
         }
         exit;
     } elseif (isset($_GET['deactivate_feed']) && eF_checkParameter($_GET['deactivate_feed'], 'id')) {
         try {
             if ($_GET['type'] == 'provider') {
                 eF_updateTableData("module_rss_provider", array("active" => 0), "id=" . $_GET['deactivate_feed']);
             } else {
                 eF_updateTableData("module_rss_feeds", array("active" => 0), "id=" . $_GET['deactivate_feed']);
             }
             echo 0;
         } catch (Exception $e) {
             handleAjaxExceptions($e);
         }
         exit;
     } elseif (isset($_GET['activate_feed']) && eF_checkParameter($_GET['activate_feed'], 'file')) {
         //Although db operations do not support exceptions (yet), we leave this here for future support
         try {
             if ($_GET['type'] == 'provider') {
                 eF_updateTableData("module_rss_provider", array("active" => 1), "id=" . $_GET['activate_feed']);
             } else {
                 eF_updateTableData("module_rss_feeds", array("active" => 1), "id=" . $_GET['activate_feed']);
             }
             echo 1;
         } catch (Exception $e) {
             handleAjaxExceptions($e);
         }
         exit;
     } else {
         if (isset($_GET['add_feed']) || isset($_GET['edit_feed']) && eF_checkParameter($_GET['edit_feed'], 'id')) {
             if ($_SESSION['s_lesson_user_type']) {
                 $type = $_SESSION['s_lesson_user_type'];
             } else {
                 $type = $this->getCurrentUser()->getType();
             }
             $smarty->assign("T_RSS_USERTYPE", $type);
             $feeds = $this->getFeeds();
             $lessons = array(-1 => _RSS_NONE, 0 => _ALLLESSONS);
             $result = EfrontLesson::getLessons();
             foreach ($result as $key => $lesson) {
                 $lessons[$key] = $lesson['name'];
             }
             isset($_GET['add_feed']) ? $postTarget = "&add_feed=1" : ($postTarget = "&edit_feed=" . $_GET['edit_feed']);
             $form = new HTML_QuickForm("add_feed_form", "post", $this->moduleBaseUrl . $postTarget, "", null, true);
             $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
             $form->addElement('text', 'title', _RSS_FEEDTITLE, 'class = "inputText"');
             $form->addElement('text', 'url', _RSS_FEEDURL, 'class = "inputText"');
             $form->addElement('select', 'lessons_ID', _LESSON, $lessons);
             if ($type != 'administrator' && $_SESSION['s_lessons_ID']) {
                 $form->setDefaults(array('lessons_ID' => $_SESSION['s_lessons_ID']));
                 $form->freeze(array('lessons_ID'));
             }
             $form->addElement("advcheckbox", "active", _RSS_ACTIVE, null, 'class = "inputCheckBox"', array(0, 1));
             $form->setDefaults(array('active' => 1));
             $form->addElement("advcheckbox", "only_summary", _RSS_ONLYSUMMARY, null, 'class = "inputCheckBox"', array(0, 1));
             $form->addRule('title', _THEFIELD . ' "' . _RSS_FEEDTITLE . '" ' . _ISMANDATORY, 'required', null, 'client');
             $form->addRule('url', _THEFIELD . ' "' . _RSS_FEEDURL . '" ' . _ISMANDATORY, 'required', null, 'client');
             $form->addRule('title', _INVALIDFIELDDATA, 'checkParameter', 'text');
             $form->addElement('submit', 'submit', _SUBMIT, 'class = "flatButton"');
             if (isset($_GET['edit_feed'])) {
                 $editFeed = $feeds[$_GET['edit_feed']];
                 $form->setDefaults($editFeed);
             }
             if ($form->isSubmitted() && $form->validate()) {
                 //If the form is submitted and validated
                 $values = $form->exportValues();
                 $fields = array("title" => $values['title'], "url" => $values['url'], "active" => $values['active'], "only_summary" => $values['only_summary'], "lessons_ID" => $values['lessons_ID']);
                 if (isset($_GET['add_feed'])) {
                     eF_insertTableData("module_rss_feeds", $fields);
                     $smarty->assign("T_RSS_RSS_MESSAGE", _RSS_SUCCESSFULLYADDEDFEED);
                 } else {
                     eF_updateTableData("module_rss_feeds", $fields, "id=" . $_GET['edit_feed']);
                     $smarty->assign("T_RSS_RSS_MESSAGE", _RSS_SUCCESSFULLYEDITEDFEED);
                     EfrontCache::getInstance()->deleteCache('rss_cache:' . $_GET['edit_feed']);
                 }
             }
             $smarty->assign("T_RSS_ADD_RSS_FORM", $form->toArray());
         } else {
             if (isset($_GET['add_feed_provider']) || isset($_GET['edit_feed_provider']) && eF_checkParameter($_GET['edit_feed_provider'], 'id')) {
                 if ($_SESSION['s_lesson_user_type']) {
                     $type = $_SESSION['s_lesson_user_type'];
                 } else {
                     $type = $this->getCurrentUser()->getType();
                 }
                 $smarty->assign("T_RSS_USERTYPE", $type);
                 $feeds = $this->getProvidedFeeds();
                 isset($_GET['add_feed_provider']) ? $postTarget = "&add_feed_provider=1" : ($postTarget = "&edit_feed_provider=" . $_GET['edit_feed_provider']);
                 !isset($_GET['lesson']) or $postTarget .= '&lesson=1';
                 $form = new HTML_QuickForm("add_feed_provider_form", "post", $this->moduleBaseUrl . $postTarget . '&tab=rss_provider', "", null, true);
                 $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
                 if ($_GET['lesson']) {
                     $lessons = array(0 => _ALLLESSONS);
                     $result = EfrontLesson::getLessons();
                     foreach ($result as $key => $lesson) {
                         $lessons[$key] = $lesson['name'];
                     }
                     $form->addElement('select', 'feeds_provided', _RSS_PROVIDEDFEEDS, $this->lessonProvidedFeeds);
                     $form->addElement('select', 'lessons_ID', _LESSON, $lessons);
                     if ($type != 'administrator' && $_SESSION['s_lessons_ID']) {
                         $form->setDefaults(array('lessons_ID' => $_SESSION['s_lessons_ID']));
                         $form->freeze(array('lessons_ID'));
                     }
                 } else {
                     $form->addElement('select', 'feeds_provided', _RSS_PROVIDEDFEEDS, $this->providedFeeds);
                 }
                 $form->addElement("advcheckbox", "active", _RSS_ACTIVE, null, 'class = "inputCheckBox"', array(0, 1));
                 $form->setDefaults(array('active' => 1));
                 $form->addElement('submit', 'submit', _SUBMIT, 'class = "flatButton"');
                 if (isset($_GET['edit_feed_provider'])) {
                     $editFeed = $feeds[$_GET['edit_feed_provider']];
                     $form->setDefaults($editFeed);
                 }
                 try {
                     if ($form->isSubmitted() && $form->validate()) {
                         //If the form is submitted and validated
                         $values = $form->exportValues();
                         $fields = array("mode" => $_GET['lesson'] ? 'lesson' : 'system', "type" => $values['feeds_provided'], "active" => $values['active'], "lessons_ID" => $values['lessons_ID']);
                         foreach ($feeds as $feed) {
                             if ($feed['type'] == $fields['type'] && $feed['mode'] == $fields['mode'] && $feed['lessons_ID'] == $fields['lessons_ID']) {
                                 throw new Exception(_FEEDALREADYEXISTS);
                             }
                         }
                         if (isset($_GET['add_feed_provider'])) {
                             eF_insertTableData("module_rss_provider", $fields);
                             $smarty->assign("T_RSS_RSS_MESSAGE", _RSS_SUCCESSFULLYADDEDFEED);
                         } else {
                             eF_updateTableData("module_rss_provider", $fields, "id=" . $_GET['edit_feed_provider']);
                             $smarty->assign("T_RSS_RSS_MESSAGE", _RSS_SUCCESSFULLYEDITEDFEED);
                         }
                     }
                 } 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';
                 }
                 $smarty->assign("T_RSS_PROVIDE_RSS_FORM", $form->toArray());
             } else {
                 if (isset($_GET['ajax'])) {
                     echo $this->getRssFeeds($_GET['refresh']);
                     //echo $this -> getRssFeeds(true);
                     exit;
                 } else {
                     $lessons = array(0 => _ALLLESSONS);
                     $result = EfrontLesson::getLessons();
                     foreach ($result as $key => $lesson) {
                         $lessons[$key] = $lesson['name'];
                     }
                     $smarty->assign("T_LESSON_NAMES", $lessons);
                     if ($_SESSION['s_lesson_user_type']) {
                         $type = $_SESSION['s_lesson_user_type'];
                         $smarty->assign("T_RSS_PROVIDED_FEEDS", $this->getProvidedFeeds($_SESSION['s_lessons_ID']));
                         $smarty->assign("T_RSS_FEEDS", $this->getFeeds(false, $_SESSION['s_lessons_ID']));
                     } else {
                         $type = $this->getCurrentUser()->getType();
                         $smarty->assign("T_RSS_PROVIDED_FEEDS", $this->getProvidedFeeds());
                         $smarty->assign("T_RSS_FEEDS", $this->getFeeds());
                     }
                     $smarty->assign("T_RSS_USERTYPE", $type);
                 }
             }
         }
     }
     if ($message) {
         $this->setMessageVar($message, $message_type);
     }
     return $this->moduleBaseDir . "module_rss.tpl";
 }
Example #26
0
 $externalFacebookForm->addElement("advcheckbox", "social_" . FB_FUNC_CONNECT, _FACEBOOKCONNECT, null, 'class = "inputCheckBox"', array(0, 1));
 $externalFacebookForm->addElement("text", "facebook_api_key", _FACEBOOKAPIKEY, 'class = "inputText"');
 $externalFacebookForm->addElement("text", "facebook_secret", _FACEBOOKSECRET, 'class = "inputText"');
 // Initialize values
 for ($i = 1; $i < $all_social_enabled_value; $i = $i << 1) {
     if ($i & $socialModulesActivated) {
         $externalFacebookForm->setDefaults(array('social_' . $i => 1));
     }
 }
 $externalFacebookForm->setDefaults(array("facebook_api_key" => $GLOBALS['configuration']['facebook_api_key'], "facebook_secret" => $GLOBALS['configuration']['facebook_secret']));
 if (isset($currentUser->coreAccess['configuration']) && $currentUser->coreAccess['configuration'] != 'change') {
     $externalFacebookForm->freeze();
 } else {
     $externalFacebookForm->addElement("submit", "submit", _SAVE, 'class = "flatButton"');
     if ($externalFacebookForm->isSubmitted() && $externalFacebookForm->validate()) {
         $values = $externalFacebookForm->exportValues();
         unset($values['submit']);
         EfrontConfiguration::setValue('facebook_api_key', $values['facebook_api_key']);
         unset($values['facebook_api_key']);
         EfrontConfiguration::setValue('facebook_secret', $values['facebook_secret']);
         unset($values['facebook_secret']);
         // Create the new binary map
         $socialModulesToBeActivated = 0;
         foreach ($values as $key => $value) {
             if ($value == 1) {
                 $socialModulesToBeActivated += intval(substr($key, 7));
             }
         }
         EfrontConfiguration::setValue('social_modules_activated', $socialModulesToBeActivated);
         eF_redirect(basename($_SERVER['PHP_SELF']) . "?ctg=system_config&op=external&tab=facebook&message=" . urlencode(_SUCCESFULLYUPDATECONFIGURATION) . "&message_type=success");
     }
Example #27
0
}
$backup_form = new HTML_QuickForm("backup_form", "post", basename($_SERVER['PHP_SELF']) . '?ctg=backup', "", null, true);
$backup_form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
//Register this rule for checking user input with our function, eF_checkParameter
$backup_form->addElement('text', 'backupname', null, 'class = "inputText"');
$backup_form->addRule('backupname', _THEFIELD . ' ' . _FILENAME . ' ' . _ISMANDATORY, 'required', null, 'client');
$backup_form->setDefaults(array("backupname" => "backup_" . date('Y_m_d_h.i.s', time())));
if ($GLOBALS['configuration']['version_hosted']) {
    $backupTypes = array("0" => _DATABASEONLY);
} else {
    $backupTypes = array("0" => _DATABASEONLY, "1" => _ALLDATABACKUP);
    if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
        $backupTypes[3] = _ALLDATASYSTEMBACKUP;
    }
}
$backup_form->addElement('select', 'backuptype', null, $backupTypes);
$backup_form->addElement('submit', 'submit_backup', _TAKEBACKUP, 'class = "flatButton" onclick = "$(\'backup_image\').show();"');
if ($backup_form->isSubmitted() && $backup_form->validate()) {
    $values = $backup_form->exportValues();
    try {
        $backupFile = EfrontSystem::backup($values['backupname'] . '.zip', $values['backuptype']);
        eF_redirect("" . basename($_SERVER['PHP_SELF']) . "?ctg=backup&message=" . urlencode(_SUCCESFULLYBACKEDUP) . "&message_type=success");
    } catch (EfrontFileException $e) {
        $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString());
        $message = $e->getMessage() . ' &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>';
        $message_type = failure;
    }
}
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
$backup_form->accept($renderer);
$smarty->assign('T_BACKUP_FORM', $renderer->toArray());
     $smarty->assign("T_DIFFERENT_VERSIONS", true);
 }
 $lockdown_form = new HTML_QuickForm("lockdown_form", "post", basename($_SERVER['PHP_SELF']) . "?ctg=maintenance&tab=lock_down", "", null, true);
 //Build the form
 $lockdown_form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
 //Register our custom input check function
 $lockdown_form->addElement('textarea', 'lock_message', _LOCKDOWNMESSAGE, 'class = "inputContentTextarea mceEditor" style = "width:100%;height:20em;"');
 $lockdown_form->addElement('checkbox', 'logout_users', null, null, 'class = "inputCheckBox"');
 $lockdown_form->setDefaults(array("lock_message" => $GLOBALS['configuration']['lock_message'] ? $GLOBALS['configuration']['lock_message'] : _SYSTEMDOWNFORMAINTENANCE, "logout_users" => true));
 $lockdown_form->addElement('submit', 'submit_lockdown', _LOCKDOWN, 'class = "flatButton"');
 $lockdown_form->addElement('submit', 'submit_message', _SAVECHANGES, 'class = "flatButton"');
 $lockdown_form->addElement('submit', 'submit_unlock', _UNLOCK, 'class = "flatButton"');
 //Check here, whether the system is already locked, and present unlock button
 if ($lockdown_form->isSubmitted() && $lockdown_form->validate()) {
     //If the form is submitted and validated
     $values = $lockdown_form->exportValues();
     if ($GLOBALS['configuration']['lock_down'] && isset($values['submit_unlock'])) {
         EfrontSystem::unlockSystem();
     } elseif (isset($values['submit_lockdown'])) {
         EfrontSystem::lockSystem($values['lock_message'], $values['logout_users']);
     } elseif (isset($values['submit_message'])) {
         EfrontConfiguration::setValue('lock_message', $values['lock_message']);
     }
     eF_redirect(basename($_SERVER['PHP_SELF']) . "?ctg=maintenance&tab=lock_down");
 }
 $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
 //Create a smarty renderer
 $lockdown_form->accept($renderer);
 //Assign this form to the renderer, so that corresponding template code is created
 $smarty->assign('T_LOCKDOWN_FORM', $renderer->toArray());
 //Assign the form to the template
Example #29
0
    $form->addElement('file', "import_file[{$i}]", null);
}
$form->addElement('text', "import_url[0]", _IMPORTFROMURL, 'class = "inputText"');
for ($i = 1; $i < 10; $i++) {
    $form->addElement('text', "import_url[{$i}]", null, 'class = "inputText"');
}
$form->addElement('text', "import_path[0]", _IMPORTFROMPATH, 'class = "inputText"');
for ($i = 1; $i < 10; $i++) {
    $form->addElement('text', "import_path[{$i}]", null, 'class = "inputText"');
}
$form->setMaxFileSize(FileSystemTree::getUploadMaxSize() * 1024);
//getUploadMaxSize returns size in KB
$form->addElement('submit', 'import_submit', _IMPORT, 'class = "flatButton"');
if ($form->isSubmitted() && $form->validate()) {
    try {
        $values = $form->exportValues();
        $errors = $uploadedFiles = array();
        //Create, if it does not exist, the folder where the files will be uploaded
        //is_dir($uploadDir = $currentUser -> getDirectory().'temp/') OR mkdir($uploadDir, 0755);
        $uploadDir = $currentLesson->getDirectory();
        $filesystem = new FileSystemTree($uploadDir, true);
        //Perform any direct file uploads
        foreach ($_FILES['import_file']['name'] as $key => $name) {
            if (!in_array($name, $uploadedFiles)) {
                //This way we bypass duplicates
                try {
                    $uploadedFiles[$name] = $filesystem->uploadFile("import_file", $uploadDir, $key);
                } catch (EfrontFileException $e) {
                    if ($e->getCode() != UPLOAD_ERR_NO_FILE) {
                        $errors[] = $e->getMessage();
                    }
Example #30
0
        $multipleLogins = array('global' => $values['global'] ? 1 : 0, 'user_types' => $values['user_types'], 'groups' => $values['groups']);
        EfrontConfiguration::setValue('multiple_logins', serialize($multipleLogins));
        eF_redirect(basename($_SERVER['PHP_SELF']) . "?ctg=system_config&op=user&tab=multiple_logins&message=" . urlencode(_SUCCESFULLYUPDATECONFIGURATION) . "&message_type=success");
    }
}
$smarty->assign("T_USER_MULTIPLE_LOGINS_FORM", $userMultipleLoginsForm->toArray());
$userWebserverAuthenticationForm = new HTML_QuickForm("user_webserver_authentication_form", "post", basename($_SERVER['PHP_SELF']) . "?ctg=system_config&op=user&tab=webserver_authentication", "", null, true);
$userWebserverAuthenticationForm->registerRule('checkParameter', 'callback', 'eF_checkParameter');
$userWebserverAuthenticationForm->addElement("advcheckbox", "webserver_auth", _WEBSERVERAUTHENTICATION, null, 'class = "inputCheckBox"', array(0, 1));
$userWebserverAuthenticationForm->addElement("advcheckbox", "webserver_registration", _WEBSERVERREGISTRATION, null, 'class = "inputCheckBox"', array(0, 1));
$userWebserverAuthenticationForm->addElement("text", "error_page", _ERRORPAGEFORINVALIDLOGIN, 'class = "inputText"');
$userWebserverAuthenticationForm->addElement("text", "unauthorized_page", _ERRORPAGEFORUNAUTHORIZED, 'class = "inputText"');
$userWebserverAuthenticationForm->addElement("text", "username_variable", _VARIABLEFORUSERNAME, 'class = "inputText"');
$userWebserverAuthenticationForm->addElement("text", "registration_file", _INCLUDEFILETHATHANDLESUSERCREATION, 'class = "inputText"');
eval('$usernameVar=' . $GLOBALS['configuration']['username_variable'] . ';');
$userWebserverAuthenticationForm->addRule('webserver_auth', str_replace(array("%x", "%y"), array($GLOBALS['configuration']['username_variable'], $_SESSION['s_login']), _VARIABLEMUSTCONTAINLOGIN), 'callback', create_function('$checkbox', "if (\$GLOBALS['usernameVar'] == \$_SESSION['s_login']) {return true;}"));
$userWebserverAuthenticationForm->setDefaults($GLOBALS['configuration']);
if (isset($currentUser->coreAccess['configuration']) && $currentUser->coreAccess['configuration'] != 'change') {
    $userWebserverAuthenticationForm->freeze();
} else {
    $userWebserverAuthenticationForm->addElement("submit", "submit", _SAVE, 'class = "flatButton"');
    if ($userWebserverAuthenticationForm->isSubmitted() && $userWebserverAuthenticationForm->validate()) {
        $values = $userWebserverAuthenticationForm->exportValues();
        unset($values['submit']);
        foreach ($values as $key => $value) {
            EfrontConfiguration::setValue($key, $value);
        }
        eF_redirect(basename($_SERVER['PHP_SELF']) . "?ctg=system_config&op=user&tab=webserver_authentication&message=" . urlencode(_SUCCESFULLYUPDATECONFIGURATION) . "&message_type=success");
    }
}
$smarty->assign("T_USER_WEBSERVER_AUTHENTICATION_FORM", $userWebserverAuthenticationForm->toArray());