/**
  * 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;
 }
Exemple #2
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());
Exemple #3
0
 $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
 //Register this rule for checking user input with our function, eF_checkParameter
 $form->addElement('text', 'email', _YOUREMAIL, 'class = "inputText"');
 $form->addRule('email', _THEFIELD . ' "' . _EMAIL . '" ' . _ISMANDATORY, 'required');
 $form->addRule('email', _INVALIDFIELDDATA, 'checkParameter', 'email');
 $form->addElement('text', 'message_subject', _MESSAGESUBJECT, 'class = "inputText"');
 //$form -> addRule('message_subject', _INVALIDFIELDDATA, 'checkParameter', 'text');
 $form->addElement('textarea', 'message_body', _TEXT, 'class = "inputText" id = "contact"');
 $form->addElement('submit', 'submit_contact', _SUBMIT, 'class = "flatButton"');
 if ($_GET['limit_reached']) {
     $form->setDefaults(array('message_subject' => _IWANTTOSIGNUPBUTMAXIMUMUSERSLIMITREACHED, 'message_body' => _IWANTTOSIGNUPBUTMAXIMUMUSERSLIMITREACHEDBODY));
 }
 if ($_SESSION['s_login']) {
     $form->setDefaults(array('email' => $currentUser->user['email']));
 }
 if ($form->isSubmitted()) {
     $fields_insert = array('users_LOGIN' => 'visitor', 'timestamp' => time(), 'action' => 'forms', 'comments' => 'contact', 'session_ip' => eF_encodeIP(eF_getRemoteAddress()));
     eF_insertTableData("logs", $fields_insert);
     if ($form->validate()) {
         $to = $form->exportValue("email");
         $subject = $form->exportValue("message_subject");
         $body = $form->exportValue("message_body") . "\r\n\r\n(" . $subject . " [" . _FROM . ": " . $to . "])";
         if (eF_mail($to, $GLOBALS['configuration']['system_email'], $subject . " [" . _FROM . ": " . $to . "]", $body, false, true)) {
             $copied_body = _THANKYOUFORCONTACTINGUSBODY . "<br/><hr/><br/>" . $form->exportValue("message_body");
             eF_mail($GLOBALS['configuration']['system_email'], $to, _THANKYOUFORCONTACTINGUS, $copied_body, false, false);
             $message = _SENDSUCCESS;
             $message_type = 'success';
             eF_redirect(basename($_SERVER['PHP_SELF']) . '?message=' . urlencode($message) . '&message_type=' . $message_type);
         } else {
             $message = _SENDFAILURE;
             $message_type = 'failure';
Exemple #4
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";
 }
Exemple #5
0
$modulesFolder = new FilesystemTree(G_MODULESPATH, true);
foreach (new EfrontDirectoryOnlyFilterIterator($modulesFolder->tree) as $value) {
    if (!in_array($value['name'], $existingModules)) {
        $modulesList[] = array('className' => $value['name'], 'not_installed' => 1, 'errors' => _MODULEFILESPRESENTNOTINSTALLED);
    }
}
$smarty->assign("T_MODULES", $modulesList);
$upload_form = new HTML_QuickForm("upload_file_form", "post", basename($_SERVER['PHP_SELF']) . '?ctg=modules', "", null, true);
$upload_form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
//Register this rule for checking user input with our function, eF_checkParameter
$upload_form->addElement('file', 'file_upload[0]', null, 'class = "inputText"');
$upload_form->addElement('checkbox', 'overwrite', _OVERWRITEIFFOLDEREXISTS);
$upload_form->setMaxFileSize(FileSystemTree::getUploadMaxSize() * 1024);
//getUploadMaxSize returns size in KB
$upload_form->addElement('submit', 'submit_upload_file', _UPLOAD, 'class = "flatButton"');
if ($upload_form->isSubmitted() && $upload_form->validate()) {
    $filesystem = new FileSystemTree(G_MODULESPATH);
    $uploadedFile = $filesystem->uploadFile('file_upload', G_MODULESPATH, 0);
    if (isset($_GET['upgrade'])) {
        $prev_module_version = eF_getTableData("modules", "position", "className = '" . $_GET['upgrade'] . "'");
        $prev_module_folder = $prev_module_version[0]['position'];
        // The name of the temp folder to extract the new version of the module
        $module_folder = $prev_module_folder;
        //basename($filename[0], '.zip') . time();
        $module_position = $prev_module_folder;
        //basename($filename[0], '.zip');
    } else {
        $module_folder = basename($uploadedFile['path'], '.zip');
        $module_position = $module_folder;
    }
    if (is_dir(G_MODULESPATH . $module_folder) && !isset($_GET['upgrade']) && !isset($_POST['overwrite'])) {
 /**
  * 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);
     $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;
 }
 $load_editor = true;
 if (G_VERSION_NUM != $GLOBALS['configuration']['database_version']) {
     $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
        $form->setDefaults(array('estimate_min' => $interval['minutes'], 'estimate_sec' => $interval['seconds']));
    }
    /*
    if ($currentQuestion -> question['type'] == "raw_text" && strpos($currentQuestion -> question['answer'],"<a href") !== false) {
    $smarty -> assign("T_HTML_ANSWER",$currentQuestion -> question['answer']);
    }
    */
    $form->freeze('question_type');
    //The question type cannot be changed
    $smarty->assign("T_HAS_EXPLANATION", $currentQuestion->question['explanation']);
    //If the question has an explanation, use this smarty tag to set explanation field to be visible by default.
}
switch ($_GET['question_type']) {
    //Depending on the question type, the user might have added new form fields. We need to recreate the form, in order to be able to handle them both in case of succes or failure.
    case 'multiple_one':
        if ($form->isSubmitted() || isset($currentQuestion)) {
            if (isset($currentQuestion) && !$form->isSubmitted()) {
                $values['multiple_one'] = array_values(unserialize($currentQuestion->question['options']));
                //We put array_values to make sure that the array starts from zero
                // Types are from K1-K4 for multiple_one
                //$qtype_ans = (sizeof($values['multiple_one']) < 6)?sizeof($values['multiple_one']):5;
                //$smarty -> assign("T_QUESTION_TYPE_CODE", "K" . ($qtype_ans-1));
                $values['correct_multiple_one'] = unserialize($currentQuestion->question['answer']);
                $values['correct_multiple_one'] = $values['correct_multiple_one'][0];
                //In multiple_one, only one value is valid. Get this out of the array
                $values['answers_explanation'] = $currentQuestion->answers_explanation;
            } else {
                $values = $form->getSubmitValues();
            }
            //Create each multiple choice from the beginning, this way including any choices the user added himself
            foreach ($values['multiple_one'] as $key => $value) {
 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;
 }
Exemple #11
0
 $externalFacebookForm->addElement("advcheckbox", "social_" . FB_FUNC_LOGGING, _FACEBOOKEXTERNALLOGGING, null, 'class = "inputCheckBox"', array(0, 1));
 $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");
Exemple #12
0
 public function getModule()
 {
     // Get smarty variable
     $smarty = $this->getSmartyVar();
     if (isset($_GET['delete_faq']) && eF_checkParameter($_GET['delete_faq'], 'id')) {
         eF_deleteTableData("module_faq", "id=" . $_GET['delete_faq']);
         eF_redirect("" . $this->moduleBaseUrl . "&message=" . urlencode(_FAQ_SUCCESFULLYDELETEDFAQENTRY) . "&message_type=success");
     } else {
         if (isset($_GET['add_faq']) || isset($_GET['edit_faq']) && eF_checkParameter($_GET['edit_faq'], 'id')) {
             $load_editor = true;
             //TODO
             $form = new HTML_QuickForm("faq_entry_form", "post", $_SERVER['REQUEST_URI'], "", null, true);
             $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
             //Register this rule for checking user input with our function, eF_checkParameter
             $form->addElement('textarea', 'question', null, 'class = "simpleEditor" style = "width:100%;height:5em;"');
             $form->addElement('textarea', 'answer', null, 'class = "simpleEditor" style = "width:100%;height:25em;"');
             $currentLesson = $this->getCurrentLesson();
             $units = eF_getTableDataFlat("content", "id, name", "lessons_ID = " . $currentLesson->lesson['id']);
             //$units['id'] = array_merge(array("0"), $units['id']);
             //$units['name'] = array_merge(array(_FAQ_GENERAL_LESSON), $units['name']);
             sizeof($units) > 0 ? $units = array(0 => _FAQ_GENERAL_LESSON) + array_combine($units['id'], $units['name']) : ($units = array("0" => _FAQ_GENERAL_LESSON));
             $form->addElement('select', 'related_content', _CONTENT, $units, 'class = "inputSelectLong"');
             $form->addElement('submit', 'submit_faq', _SUBMIT, 'class = "flatButton"');
             if (isset($_GET['edit_faq'])) {
                 $faq_entry = eF_getTableData("module_faq", "*", "id=" . $_GET['edit_faq']);
                 $form->setDefaults(array('related_content' => $faq_entry[0]['unit_ID'], 'question' => $faq_entry[0]['question'], 'answer' => $faq_entry[0]['answer']));
             }
             if ($form->isSubmitted() && $form->validate()) {
                 $fields = array('lessons_ID' => $_SESSION['s_lessons_ID'], 'unit_ID' => $form->exportValue('related_content'), 'question' => $form->exportValue('question'), 'answer' => $form->exportValue('answer'));
                 if (isset($_GET['edit_faq'])) {
                     if (eF_updateTableData("module_faq", $fields, "id=" . $_GET['edit_faq'])) {
                         eF_redirect("" . $this->moduleBaseUrl . "&message=" . urlencode(_FAQ_SUCCESFULLYUPDATEDFAQENTRY) . "&message_type=success");
                     } else {
                         $this->setMessageVar(_FAQ_PROBLEMUPDATINGFAQENTRY, 'failure');
                     }
                 } else {
                     if (eF_insertTableData("module_faq", $fields)) {
                         eF_redirect("" . $this->moduleBaseUrl . "&message=" . urlencode(_FAQ_SUCCESFULLYINSERTEDFAQENTRY) . "&message_type=success");
                     } else {
                         $this->setMessageVar(_FAQ_PROBLEMINSERTINGFAQENTRY, 'failure');
                     }
                 }
             }
             $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
             $form->accept($renderer);
             $smarty->assign('T_FAQ_FORM', $renderer->toArray());
         } else {
             $currentLesson = $this->getCurrentLesson();
             $faq = eF_getTableDataFlat("module_faq", "*", "lessons_ID=" . $currentLesson->lesson['id']);
             $currentUser = $this->getCurrentUser();
             $smarty->assign("T_FAQUSERLESSONROLE", $currentUser->getRole($currentLesson));
             $smarty->assign("T_FAQ", $faq);
             $smarty->assign("T_QUESTIONS_FOUND", sizeof($faq));
         }
     }
     return true;
 }
 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;
 }
Exemple #14
0
 $_SESSION['s_index_comply'] = 'password_change';
 $user = EfrontUserFactory::factory($_SESSION['s_login']);
 $changePasswordForm = new HTML_QuickForm("change_password_form", "post", basename($_SERVER['PHP_SELF']) . "?ctg=password_change", "", "class = 'indexForm'", true);
 $changePasswordForm->addElement('password', 'old_password', _OLDPASSWORD, 'class = "inputText"');
 // SMS: 7/23/2014 Changed to support vLab
 // $changePasswordForm -> addElement('password', 'password', _NEWPASSWORD, 'class = "inputText"');
 $changePasswordForm->addElement('password', 'password', _NEWPASSWORD, 'class = "inputText"');
 $changePasswordForm->addElement('password', 'passrepeat', _REPEATPASSWORD, 'class = "inputText"');
 $changePasswordForm->addRule('password', _THEFIELD . ' ' . _PASSWORD . ' ' . _ISMANDATORY, 'required', null, 'client');
 $changePasswordForm->addRule('passrepeat', _THEFIELD . ' ' . _REPEATPASSWORD . ' ' . _ISMANDATORY, 'required', null, 'client');
 // SMS: 7/23/2014 Changed to support vLab
 // $changePasswordForm -> addRule(array('password', 'passrepeat'), _PASSWORDSDONOTMATCH, 'compare', null, 'client');
 $changePasswordForm->addRule(array('password', 'passrepeat'), _PASSWORDSDONOTMATCH, 'compare', null, 'client');
 $changePasswordForm->addRule('passrepeat', str_replace("%x", $GLOBALS['configuration']['password_length'], _PASSWORDMUSTBE6CHARACTERS), 'minlength', $GLOBALS['configuration']['password_length'], 'client');
 $changePasswordForm->addElement('submit', 'submit', _SUBMIT, 'class = "flatButton"');
 if ($changePasswordForm->isSubmitted() && $changePasswordForm->validate()) {
     $newPassword = $changePasswordForm->exportValue('password');
     $newPassword = EfrontUser::createPassword($newPassword);
     if ($user->user['password'] != EfrontUser::createPassword($changePasswordForm->exportValue('old_password'))) {
         $message = _OLDPASSWORDWRONG;
         $message_type = 'failure';
     } else {
         if ($user->user['password'] == $newPassword) {
             $message = _PASSWORDISTHESAME;
             $message_type = 'failure';
         } else {
             $user->user['password'] = $newPassword;
             $user->user['need_pwd_change'] = 0;
             $user->persist();
             unset($_SESSION['s_index_comply']);
             if ($GLOBALS['configuration']['show_license_note'] && $user->user['viewed_license'] == 0) {
Exemple #15
0
$form->addElement("text", "firstName", "First name");
$form->addElement("text", "lastName", "Last name");
$form->addElement("text", "emailAddress", "Email address");
$form->addElement("text", "subject", "Message subject");
$form->addElement("textarea", "message", "Message", array("rows" => 10, "cols" => 50));
$form->addElement("submit", "sendButton", "Send Message");
$form->addRule("firstName", "Please enter your first name", "required");
$form->addRule("firstName", "The First Name field can contain only letters, digits, spaces, apostrophes, and hyphens", "regex", "/^[ \\'\\-a-zA-Z0-9]+\$/");
$form->addRule("lastName", "Please enter your last name", "required");
$form->addRule("lastName", "The Last Name field can contain only letters, digits, spaces, apostrophes, and hyphens", "regex", "/^[ \\'\\-a-zA-Z0-9]+\$/");
$form->addRule("emailAddress", "Please enter an email address", "required");
$form->addRule("emailAddress", "Please enter a valid email address", "email");
$form->addRule("subject", "Please enter a message subject", "required");
$form->addRule("subject", "Your subject can contain only letters, digits, spaces, apostrophes, commas, periods, and hyphens", "regex", "/^[ \\'\\,\\.\\-a-zA-Z0-9]+\$/");
$form->addRule("message", "Please enter your message", "required");
if ($form->isSubmitted() and $form->validate()) {
    $form->process("sendMessage");
} else {
    echo "<p>Please fill in all the fields below, then click Send Message to send us an email.</p>";
    $renderer = new HTML_QuickForm_Renderer_Tableless();
    $form->accept($renderer);
    echo $renderer->toHtml();
}
function sendMessage($values)
{
    $recipient = OWNER_FIRST_NAME . " " . OWNER_LAST_NAME . " <" . OWNER_EMAIL_ADDRESS . ">";
    $headers = "From: " . $values["firstName"] . " " . $values["lastName"] . " <" . $values["emailAddress"] . ">";
    if (mail($recipient, $values["subject"], $values["message"], $headers)) {
        echo "<p>Thanks for your message! Someone will be in touch shortly.</p>";
    } else {
        echo '<p>Sorry, your message could not be sent.</p>';
Exemple #16
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());
Exemple #17
0
 private function _validate()
 {
     if ($this->action == TIP_FORM_ACTION_DELETE || $this->action == TIP_FORM_ACTION_CUSTOM) {
         // Special case: GET driven form
         $this->_form->freeze();
         return TIP::getGet('process', 'int') == 1;
     }
     // Add element and form rules
     isset($this->validator) && $this->_form->addFormRule($this->validator);
     foreach (array_keys($this->fields) as $id) {
         if ($this->_form->elementExists($id)) {
             $this->_addGuessedRules($id);
             $this->_addCustomRules($id);
         }
     }
     $stage_id = $this->id . '.stage';
     $last_stage = HTTP_Session2::get($stage_id);
     if (!$this->_form->isSubmitted() || isset($last_stage) && $last_stage < $this->_stage) {
         HTTP_Session2::set($stage_id, $this->_stage);
         $valid = false;
     } elseif (is_null($last_stage)) {
         // No last stage defined
         TIP::notifyError('double');
         $valid = null;
     } else {
         // Validation
         $this->_form->applyFilter('__ALL__', array('TIP', 'extendedTrim'));
         $valid = $this->_form->validate();
     }
     // Perform uploads (if needed)
     if (is_callable(array('HTML_QuickForm_attachment', 'doUploads'))) {
         HTML_QuickForm_attachment::doUploads($this->_form);
     }
     return $valid;
 }
Exemple #18
0
 //The score must be between 0 and 100
 $config_form->addRule('notifications_messages_per_time', _THEFIELD . ' "' . _MESSAGESTOSENDEVERYTIME . '" ' . _MUSTBENUMERIC, 'numeric', null, 'client');
 $config_form->addRule('notifications_messages_per_time', _THEFIELD . ' "' . _MESSAGESTOSENDEVERYTIME . '" ' . _ISMANDATORY, 'required', null, 'client');
 $config_form->addElement('text', 'notifications_max_sent_messages', _MAXIMUMSENTMESSAGESSTORED, 'class = "inputText"');
 $config_form->addRule('notifications_max_sent_messages', _POSITIVENUMBERREQUIRED, 'callback', create_function('$a', 'return ($a > 0);'));
 //The score must be between 0 and 100
 $config_form->addRule('notifications_max_sent_messages', _THEFIELD . ' "' . _MAXIMUMSENTMESSAGESSTORED . '" ' . _MUSTBENUMERIC, 'numeric', null, 'client');
 $config_form->addRule('notifications_max_sent_messages', _THEFIELD . ' "' . _MAXIMUMSENTMESSAGESSTORED . '" ' . _ISMANDATORY, 'required', null, 'client');
 $config_form->addElement('select', 'notifications_send_mode', _SENDMODE, array(_EMAIL, _PERSONALMESSAGE, _EMAILANDPM));
 $config_form->addRule('notifications_max_sent_messages', _THEFIELD . ' "' . _MAXIMUMSENTMESSAGESSTORED . '" ' . _MUSTBENUMERIC, 'numeric', null, 'client');
 $config_form->addElement('submit', 'submit_variables', _SUBMIT, 'class = "flatButton"');
 $notification_configurations = array('notifications_use_cron', 'notifications_pageloads', 'notifications_maximum_inter_time', 'notifications_messages_per_time', 'notifications_max_sent_messages', 'notifications_send_mode');
 foreach ($notification_configurations as $conf_option) {
     $config_form->setDefaults(array($conf_option => $GLOBALS['configuration'][$conf_option]));
 }
 if ($config_form->isSubmitted()) {
     foreach ($notification_configurations as $conf_option) {
         EfrontConfiguration::setValue($conf_option, $config_form->exportValue($conf_option));
     }
     // Clear the stored sent messages according to the new limitations
     EfrontNotification::clearSentMessages();
     $message = _NOTIFICATIONCONFIGURATIONSUPDATEDSUCCESSFULLY;
     $message_type = 'success';
     eF_redirect("" . $_SESSION['s_type'] . ".php?ctg=digests&message=" . urlencode($message) . "&message_type=" . $message_type);
 }
 $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
 //Create a smarty renderer
 $renderer->setRequiredTemplate('{$html}{if $required}
         &nbsp;<span class = "formRequired">*</span>
     {/if}');
 if (isset($currentUser->coreAccess['notifications']) && $currentUser->coreAccess['notifications'] != 'change') {
Exemple #19
0
 public function getModule()
 {
     $currentLesson = $this->getCurrentLesson();
     $smarty = $this->getSmartyVar();
     $smarty->assign("T_LESSON_ID", $currentLesson->lesson['id']);
     if (isset($_GET['delete_link']) && eF_checkParameter($_GET['delete_link'], 'id')) {
         eF_deleteTableData("module_links", "id=" . $_GET['delete_link']);
         $this->setMessageVar(_LINKS_SUCCESFULLYDELETEDLINK, 'success');
         eF_redirect("" . $this->moduleBaseUrl . "&message=" . urlencode($message) . "&message_type={$message_type}");
     } else {
         if (isset($_GET['add_link']) || isset($_GET['edit_link']) && eF_checkParameter($_GET['edit_link'], 'id')) {
             $form = new HTML_QuickForm("link_entry_form", "POST", $_SERVER['REQUEST_URI'], "");
             $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
             //Register this rule for checking user input with our function, eF_checkParameter
             $form->addElement('text', 'display', null);
             $form->addElement('text', 'link', null);
             $form->addElement('textarea', 'description', null);
             $form->addElement('submit', 'submit_link', _SUBMIT, 'class = "flatButton"');
             $element =& $form->getElement('display');
             $element->setSize(50);
             $element =& $form->getElement('link');
             $element->setSize(50);
             $element =& $form->getElement('description');
             $element->setCols(50);
             if (isset($_GET['edit_link'])) {
                 $link_entry = eF_getTableData("module_links", "*", "id=" . $_GET['edit_link']);
                 $form->setDefaults(array('display' => $link_entry[0]['display'], 'link' => $link_entry[0]['link'], 'description' => $link_entry[0]['description']));
             } else {
                 $form->setDefaults(array('link' => "http://"));
             }
             if ($form->isSubmitted() && $form->validate()) {
                 $fields = array('lessons_ID' => $_SESSION['s_lessons_ID'], 'display' => $form->exportValue('display'), 'link' => $form->exportValue('link'), 'description' => $form->exportValue('description'));
                 if (isset($_GET['edit_link'])) {
                     if (eF_updateTableData("module_links", $fields, "id=" . $_GET['edit_link'])) {
                         $message = _LINKS_SUCCESFULLYUPDATEDLINKENTRY;
                         $message_type = 'success';
                         eF_redirect("" . $_SERVER['PHP_SELF'] . "?ctg=module&op=module_links&message=" . urlencode($message) . "&message_type={$message_type}");
                     } else {
                         $message = _LINKS_PROBLEMUPDATINGLINKENTRY;
                         $message_type = 'failure';
                         eF_redirect("" . $_SERVER['PHP_SELF'] . "?ctg=module&op=module_links&message=" . urlencode($message) . "&message_type={$message_type}");
                     }
                 } else {
                     if (eF_insertTableData("module_links", $fields)) {
                         $message = _LINKS_SUCCESFULLYINSERTEDLINKENTRY;
                         $message_type = 'success';
                         eF_redirect("" . $_SERVER['PHP_SELF'] . "?ctg=module&op=module_links&message=" . urlencode($message) . "&message_type={$message_type}");
                     } else {
                         $message = _LINKS_PROBLEMINSERTINGLINKENTRY;
                         $message_type = 'failure';
                         eF_redirect("" . $_SERVER['PHP_SELF'] . "?ctg=module&op=module_links&message=" . urlencode($message) . "&message_type={$message_type}");
                     }
                 }
             }
             $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
             $form->accept($renderer);
             $smarty->assign('T_LINKS_FORM', $renderer->toArray());
         } else {
             $links = eF_getTableDataFlat("module_links", "*", "lessons_ID = " . $_SESSION['s_lessons_ID']);
             $smarty->assign("T_LINKS", $links);
         }
     }
     return true;
 }
 public function getModule()
 {
     // Get smarty variable
     $smarty = $this->getSmartyVar();
     //This could become a module function...
     global $load_editor;
     $load_editor = true;
     //$smarty -> assign("T_HEADER_EDITOR", $load_editor);
     $form = new HTML_QuickForm("billboard_entry_form", "post", $_SERVER['REQUEST_URI'], "", null, true);
     $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
     //Register this rule for checking user input with our function, eF_checkParameter
     $form->addElement('textarea', 'data', _BILLBOARDCONTENT, 'class = "inputContentTextarea mceEditor" style = "width:100%;height:300px;"');
     //The unit content itself
     $form->addElement('submit', 'submit_billboard', _SUBMIT, 'class = "flatButton"');
     $currentLesson = $this->getCurrentLesson();
     $billboard = eF_getTableData("module_billboard", "*", "lessons_ID=" . $currentLesson->lesson['id']);
     $form->setDefaults(array('data' => $billboard[0]['data']));
     if ($form->isSubmitted() && $form->validate()) {
         $fields = array('lessons_ID' => $currentLesson->lesson['id'], 'data' => $form->exportValue('data'));
         $currentUser = $this->getCurrentUser();
         // if ($billboard[0]['data'] != "") {
         if (!empty($billboard)) {
             if (eF_updateTableData("module_billboard", $fields, "lessons_ID=" . $currentLesson->lesson['id'])) {
                 eF_redirect("professor.php?ctg=control_panel&message=" . urlencode(_BILLBOARD_SUCCESFULLYUPDATEDBILLBOARDENTRY) . "&message_type=success");
             } else {
                 $this->setMessageVar(_BILLBOARD_PROBLEMUPDATINGBILLBOARDENTRY, 'failure');
             }
         } else {
             if (eF_insertTableData("module_billboard", $fields)) {
                 eF_redirect("professor.php?ctg=control_panel&message=" . urlencode(_BILLBOARD_SUCCESFULLYUPDATEDBILLBOARDENTRY) . "&message_type=success");
                 //eF_redirect("".$this -> moduleBaseUrl."&message="._BILLBOARD_SUCCESFULLYINSERTEDBILLBOARDENTRY."&message_type=success");
             } else {
                 $this->setMessageVar(_BILLBOARD_PROBLEMINSERTINGBILLBOARDENTRY, 'failure');
             }
         }
     }
     $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
     $form->accept($renderer);
     $smarty->assign('T_BILLBOARD_FORM', $renderer->toArray());
     $smarty->assign("T_BILLBOARD", $billboard[0]['data']);
     return true;
 }
Exemple #21
0
 $form = new HTML_QuickForm("test_form", "post", basename($_SERVER['PHP_SELF']) . '?view_unit=' . $_GET['view_unit'], "", 'onsubmit = "$(\'submit_test\').disabled=true;"', true);
 switch ($status['status']) {
     case 'incomplete':
         //$test -> getQuestionsRandomTest(true);
         if (!($testInstance = unserialize($status['completedTest']['test']))) {
             throw new EfrontTestException(_TESTCORRUPTEDASKRESETEXECUTION, EfrontTestException::CORRUPTED_TEST);
         }
         if ($testInstance->time['pause'] && isset($_GET['resume'])) {
             $testInstance->time['pause'] = 0;
             $testInstance->time['resume'] = time();
             //unset($testInstance -> currentQuestion);
             $testInstance->save();
         }
         $remainingTime = $testInstance->options['duration'] - $testInstance->time['spent'] - (time() - $testInstance->time['resume']);
         $nocache = false;
         if ($form->isSubmitted() || $testInstance->options['duration'] && $remainingTime < 0 || $status['status'] == 'incomplete') {
             $nocache = true;
         }
         $testString = $testInstance->toHTMLQuickForm($form, false, false, false, $nocache);
         $testString = $testInstance->toHTML($testString, $remainingTime);
         if ($testInstance->options['duration'] && $remainingTime < 0) {
             try {
                 $values = $form->exportValues();
                 $testInstance->complete($values['question']);
                 if ($testInstance->completedTest['status'] == 'failed') {
                     $currentUser->setSeenUnit($currentUnit, $currentLesson, 0);
                 } else {
                     $currentUser->setSeenUnit($currentUnit, $currentLesson, 1);
                 }
                 eF_redirect(basename($_SERVER['PHP_SELF']) . "?view_unit=" . $_GET['view_unit']);
                 exit;
}
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
$importForm->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
$importForm->setRequiredNote(_REQUIREDNOTE);
$importForm->accept($renderer);
$smarty->assign('T_IMPORT_FORM', $renderer->toArray());
// ******************************************* Export form *******************************************
$exportForm = new HTML_QuickForm("export_form", "post", basename($_SERVER['PHP_SELF']) . "?ctg=import_export&op=export&tab=export", "", null, true);
unset($import_export_types['anything']);
$exportForm->addElement('select', 'export_type', _DATATYPE, $import_export_types, 'class = "inputCheckbox"', array(0, 1));
$exportForm->addElement("select", "date_format", _DATEFORMAT, array("DD/MM/YYYY" => "DD/MM/YYYY", "MM/DD/YYYY" => "MM/DD/YYYY", "YYYY/MM/DD" => "YYYY/MM/DD"));
$exportForm->addElement('radio', 'export_separator', _KEEPEXISTINGUSERS, null, 'csvA');
$exportForm->addElement('radio', 'export_separator', _KEEPEXISTINGUSERS, null, 'csvB');
$exportForm->setDefaults(array('export_separator' => "csvA"));
$exportForm->addElement('submit', 'submit_export', _EXPORTDATA, 'class = "flatButton"');
if ($exportForm->isSubmitted() && $exportForm->validate()) {
    $exportForm->exportValue('export_separator') == 'csvA' ? $separator = ',' : ($separator = ';');
    try {
        $options = array("separator" => $separator, "date_format" => $exportForm->exportValue('date_format'));
        $exporter = EfrontExportFactory::factory("csv", $options);
        $file = $exporter->export($exportForm->exportValue('export_type'));
        header("content-type:" . $file['mime_type']);
        header('content-disposition: attachment; filename= "' . $file['name'] . '"');
        readfile($file['path']);
        exit;
    } catch (Exception $e) {
        $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString());
        $message = _ERRORRESTORINGFILE . ': ' . $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_EXPORTED_FILE", $file);
 /**
  * The main functionality
  *
  * (non-PHPdoc)
  * @see libraries/EfrontModule#getModule()
  */
 public function getModule()
 {
     $smarty = $this->getSmartyVar();
     $currentUser = $this->getCurrentUser();
     $directionsTree = new EfrontDirectionsTree();
     $directionsPaths = $directionsTree->toPathString();
     $smarty->assign("T_MODULE_OUTLOOK_INVITATION_DIRECTION_PATHS", $directionsPaths);
     $temp = eF_getTableData("module_outlook_invitation as m,courses as c", "m.*,c.name,c.directions_ID", "m.courses_ID=c.id");
     $events = array();
     foreach ($temp as $value) {
         $events[$value['courses_ID']] = $value;
     }
     if (isset($_GET['delete_event']) && eF_checkParameter($_GET['delete_event'], 'id') && in_array($_GET['delete_event'], array_keys($events))) {
         try {
             $event = $events[$_GET['delete_event']];
             $course = new EfrontCourse($event['courses_ID']);
             $users = $course->getCourseUsers(array('active' => true, archive => false, 'return_objects' => false));
             $recipients = array();
             foreach ($users as $value) {
                 $recipients[] = $value['email'];
             }
             $this->cancelInvitation($course->course['id'], $recipients);
             eF_deleteTableData("module_outlook_invitation", "courses_ID=" . $_GET['delete_event']);
         } catch (Exception $e) {
             header("HTTP/1.0 500 ");
             echo $e->getMessage() . ' (' . $e->getCode() . ')';
         }
         exit;
     }
     if ($_SESSION['s_type'] != 'administrator') {
         $userCourses = $currentUser->getUserCourses(array('archive' => 0, 'active' => true, 'return_objects' => false));
         if (G_VERSIONTYPE == 'enterprise') {
             if ($_SESSION['s_current_branch']) {
                 $result = eF_getTableData("module_hcd_course_to_branch", "courses_ID", "branches_ID='{$_SESSION['s_current_branch']}'");
             } else {
                 if ($currentUser->aspects['hcd']->isSupervisor()) {
                     $result = eF_getTableData("module_hcd_course_to_branch", "courses_ID", "branches_ID in (select branches_ID from module_hcd_employee_works_at_branch where users_login='******'login']}' and supervisor=1)");
                 }
             }
             $branchCourses = array();
             foreach ($result as $value) {
                 $branchCourses[$value['courses_ID']] = $value['courses_ID'];
             }
             foreach ($events as $key => $value) {
                 if (!isset($branchCourses[$key]) && !isset($userCourses[$key])) {
                     unset($events[$key]);
                 }
             }
         } else {
             foreach ($events as $key => $value) {
                 if (!isset($userCourses[$key])) {
                     unset($events[$key]);
                 }
             }
         }
     }
     if (!isset($_GET['course'])) {
         $dataSource = $events;
         $tableName = 'outlookInvitationsTable';
         isset($_GET['limit']) && eF_checkParameter($_GET['limit'], 'uint') ? $limit = $_GET['limit'] : ($limit = G_DEFAULT_TABLE_SIZE);
         if (isset($_GET['sort']) && eF_checkParameter($_GET['sort'], 'text')) {
             $sort = $_GET['sort'];
             isset($_GET['order']) && $_GET['order'] == 'desc' ? $order = 'desc' : ($order = 'asc');
         } else {
             $sort = 'login';
         }
         $dataSource = eF_multiSort($dataSource, $sort, $order);
         $smarty->assign("T_TABLE_SIZE", sizeof($dataSource));
         if (isset($_GET['filter'])) {
             $dataSource = eF_filterData($dataSource, $_GET['filter']);
         }
         if (isset($_GET['limit']) && eF_checkParameter($_GET['limit'], 'int')) {
             isset($_GET['offset']) && eF_checkParameter($_GET['offset'], 'int') ? $offset = $_GET['offset'] : ($offset = 0);
             $dataSource = array_slice($dataSource, $offset, $limit);
         }
         $smarty->assign("T_DATA_SOURCE", $dataSource);
     } else {
         $course = new EfrontCourse($_GET['course']);
         $form = new HTML_QuickForm("import_outlook_invitation_form", "post", $this->moduleBaseUrl . "&course={$course->course['id']}&add_event=1" . (isset($_GET['popup']) ? '&popup=1' : ''), "", null, true);
         $form->registerRule('checkParameter', 'callback', 'eF_checkParameter');
         //Register this rule for checking user input with our function, eF_checkParameter
         $form->addElement('text', 'email', _SENDER, 'class = "inputText"');
         $form->addElement('text', 'location', _LOCATION, 'class = "inputText"');
         $form->addElement('text', 'subject', _SUBJECT, 'class = "inputText"');
         $form->addElement('textarea', 'description', _DESCRIPTION, 'class = "inputTestTextarea" style = "width:80%;height:6em;"');
         //$form -> addElement('checkbox', 'calendar', _MODULE_OUTLOOK_INVITATION_CREATE_CALENDAR);
         //$form -> addElement('static', 'static', _MODULE_OUTLOOK_INVITATION_INFO);
         $form->addElement('submit', 'submit_event_all', _MODULE_OUTLOOK_INVITATION_SENDALL, 'class=flatButton');
         $form->addElement('submit', 'submit_event_new', _MODULE_OUTLOOK_INVITATION_SENDNEW, 'class=flatButton');
         if (empty($events[$course->course['id']])) {
             //new invitation
             $currentEvent = null;
             $form->setDefaults(array('email' => $currentUser->user['email'], 'subject' => 'Invitation to attend training: ' . $course->course['name']));
         } else {
             //existing invitation
             $currentEvent = $events[$course->course['id']];
             $form->setDefaults(array('email' => $currentEvent['email'], 'description' => $currentEvent['description'], 'subject' => $currentEvent['subject'], 'location' => $currentEvent['location']));
         }
         if ($form->isSubmitted() && $form->validate()) {
             try {
                 $message = "";
                 // Set info to store into database
                 $permanent_info = array("courses_ID" => $course->course['id'], "email" => $form->exportValue('email') ? $form->exportValue('email') : $GLOBALS['configuration']['system_email'], "location" => $form->exportValue('location'), "subject" => $form->exportValue('subject'), "description" => $form->exportValue('description'));
                 if ($currentEvent) {
                     $permanent_info['sequence'] = $currentEvent['sequence'] + 1;
                     eF_updateTableData("module_outlook_invitation", $permanent_info, "courses_ID={$course->course['id']}");
                 } else {
                     eF_insertTableData("module_outlook_invitation", $permanent_info);
                 }
                 if ($form->exportValue('submit_event_all')) {
                     $users = $course->getCourseUsers(array('active' => true, archive => false, 'return_objects' => false));
                     $recipients = array();
                     foreach ($users as $value) {
                         $recipients[] = $value['email'];
                     }
                     $this->sendInvitation($course->course['id'], $recipients);
                 }
                 //					$smarty->assign('T_RELOAD', true);
                 if (isset($_GET['popup'])) {
                     $this->setMessageVar(_OPERATIONCOMPLETEDSUCCESSFULLY, 'success');
                 } else {
                     eF_redirect($this->moduleBaseUrl . "&message=" . urlencode(_OPERATIONCOMPLETEDSUCCESSFULLY) . "&message_type=success");
                 }
             } catch (Exception $e) {
                 $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString());
                 $this->setMessageVar($e->getMessage() . ' (' . $e->getCode() . ') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>', 'failure');
             }
         }
         $form->setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
         $form->setRequiredNote(_REQUIREDNOTE);
         $smarty->assign('T_MODULE_OUTLOOK_INVITATION_FORM', $form->toArray());
     }
     $smarty->assign("T_MODULE_BASEDIR", $this->moduleBaseDir);
     $smarty->assign("T_MODULE_BASELINK", $this->moduleBaseLink);
     $smarty->assign("T_MODULE_BASEURL", $this->moduleBaseUrl);
     return true;
 }
 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";
         }
     }
 }
 private function doJobCourses()
 {
     $smarty = $this->getSmartyVar();
     $currentUser = $this->getCurrentUser();
     $result = eF_getTableData("module_hcd_job_description j left outer join module_hcd_course_to_job_description cj on cj.job_description_ID=j.job_description_ID", "j.job_description_ID,description,branch_ID,count(courses_ID) as total_courses", "", "", "j.job_description_ID");
     $branchesTree = new EfrontBranchesTree();
     $branchesTreePaths = $branchesTree->toPathString();
     $jobs = array();
     foreach ($result as $value) {
         $jobsArray[$value['job_description_ID']] = $value;
         $jobs[$value['job_description_ID']] = $branchesTreePaths[$value['branch_ID']] . "&nbsp;&rarr;&nbsp;" . $value['description'] . " (" . $value['total_courses'] . ")";
     }
     $form = new HTML_QuickForm("job_courses_form", "post", basename($_SERVER['PHP_SELF']) . "?ctg=module&op=module_administrator_tools&tab=job_courses&do=enterprise", "", null, true);
     $form->addElement('select', 'job', _JOBDESCRIPTION, $jobs);
     $form->addElement("submit", "submit", _MODULE_ADMINISTRATOR_TOOLS_COPYCOURSESELECTION, 'class = "flatButton"');
     $form->addElement("static", "", _MODULE_ADMINISTRATOR_TOOLS_COPYCOURSESELECTIONTOALLSIMILARJOBS);
     $form->setDefaults(array("idle_from_timestamp" => $_SESSION['timestamp_from']));
     if ($form->isSubmitted() && $form->validate()) {
         $GLOBALS['currentEmployee'] = $currentUser->aspects['hcd'];
         $job = new EfrontJob($form->exportValue('job'));
         $courses = $job->getJobCourses();
         foreach ($sameJobs = $job->getSameDescriptions() as $value) {
             eF_deleteTableData("module_hcd_course_to_job_description", "job_description_id = '" . $value . "'");
         }
         $job->associateCoursesToJob($courses, true);
         $message = str_replace(array("%x", "%y"), array(sizeof($sameJobs), sizeof($courses)), _MODULE_ADMINISTRATOR_TOOLS_SUCCESSFULLYASSIGNEDCOURSESTOJOBS);
         $message_type = 'success';
         $this->setMessageVar($message, $message_type);
     }
     $smarty->assign("T_JOB_COURSES_FORM", $form->toArray());
 }
Exemple #26
0
     } catch (EfrontFileException $e) {
         $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString());
         $message = _SOMEPROBLEMOCCURED . ': ' . $e->getMessage() . ' &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>';
         $message_type = 'failure';
     }
 }
 $form = new HTML_QuickForm("upload_project_form", "post", basename($_SERVER['PHP_SELF']) . '?ctg=projects&view_project=' . $_GET['view_project'], "", null, true);
 if (!$projectFile) {
     $file = $form->addElement('file', 'filename', _FILE);
     $maxFileSize = FileSystemTree::getUploadMaxSize();
     $form->addRule('filename', _THEFIELD . ' "' . _FILE . '" ' . _ISMANDATORY, 'required', null, 'client');
     $form->setMaxFileSize($maxFileSize * 1024);
     $form->addElement('submit', 'submit_upload_project', _SENDPROJECT, 'class = "flatButton"');
 }
 $smarty->assign("T_MAX_FILE_SIZE", $maxFileSize);
 if ($form->isSubmitted() && $form->validate() && !$currentProject->expired) {
     try {
         $projectDirectory = G_UPLOADPATH . $currentUser->user['login'] . '/projects';
         if (!is_dir($projectDirectory)) {
             EfrontDirectory::createDirectory($projectDirectory);
         }
         $projectDirectory = G_UPLOADPATH . $currentUser->user['login'] . '/projects/' . $currentProject->project['id'];
         if (!is_dir($projectDirectory)) {
             EfrontDirectory::createDirectory($projectDirectory);
         }
         $filesystem = new FileSystemTree($projectDirectory);
         $uploadedFile = $filesystem->uploadFile('filename', $projectDirectory);
         //$uploadedFile -> rename($uploadedFile['directory'].'/project_'.$currentProject -> project['id'].'.'.$uploadedFile['extension']);
         $fields_update = array("filename" => $uploadedFile['id'], "upload_timestamp" => time());
         eF_updateTableData("users_to_projects", $fields_update, "users_LOGIN='******'login'] . "' AND projects_ID=" . $_GET['view_project']);
         EfrontEvent::triggerEvent(array("type" => EfrontEvent::PROJECT_SUBMISSION, "users_LOGIN" => $currentUser->user['login'], "lessons_ID" => $currentLesson->lesson['id'], "lessons_name" => $currentLesson->lesson['name'], "entity_ID" => $currentProject->project['id'], "entity_name" => $currentProject->project['title']));
 $form->addElement("select", "job", _JOBDESCRIPTION, $jobs, 'id="jobs_for_branch"');
 $form->addElement("select", "position", _POSITION, $positions, 'id="positions_for_branch"');
 if ($_change_placements_) {
     $form->addElement('submit', 'submit', _SUBMIT, 'class = "flatButton"');
 } else {
     $form->freeze();
 }
 $form->addRule('job', _PLEASESELECTAJOB, 'callback', create_function('$a', 'return ($a && $a != "#empty#");'));
 //The score must be between 0 and 100
 if ($_GET['edit_placement']) {
     $userJobs = $editedEmployee->getJobs();
     $job = $userJobs[$_GET['edit_placement']];
     $form->setDefaults(array('branch' => $job['branch_ID'], 'job' => $job['description'], 'position' => $job['supervisor']));
 }
 try {
     if ($form->isSubmitted() && $form->validate() && $_change_placements_) {
         $values = $form->exportValues();
         if ($values['job'] && $values['branch']) {
             require_once "module_hcd_tools.php";
             $newJob = eF_getJobDescriptionId($values['job'], $values['branch']);
             //pr($values);pr($_GET['edit_placement']);pr($newJob);echo "A";exit;
             if ($_GET['edit_placement']) {
                 if ($_GET['edit_placement'] != $newJob) {
                     $editedEmployee->removeJob($_GET['edit_placement']);
                 } elseif (isset($userJobs[$newJob]) && $userJobs[$newJob]['supervisor'] != $_POST['position']) {
                     $editedEmployee->removeJob($_GET['edit_placement']);
                 }
             }
             $editedEmployee->addJob($editedUser, $newJob, $values['branch'], $_POST['position']);
             $message = _OPERATIONCOMPLETEDSUCCESFULLY;
             $message_type = 'success';
    /**
     * 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;
    }
$form->addElement('file', 'import_file[0]', _IMPORTFILE);
for ($i = 1; $i < 10; $i++) {
    $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) {
Exemple #30
0
 } else {
     $target = basename($_SERVER['PHP_SELF']) . '?ctg=lessons&catalog=1&checkout=1';
     $cancelReturn = G_SERVERNAME . 'studentpage.php?message=' . urlencode(_YOUHAVECANCELLEDTHETRANSACTION);
 }
 $form = new HTML_QuickForm("my_checkout_form", "post", $target, "", 'style = "display:inline"', true);
 $form->addElement('text', 'coupon', null, 'style = "display:none" id = "coupon_code"');
 if (G_VERSIONTYPE != 'community') {
     #cpp#ifndef COMMUNITY
     if ($totalPrice > 0 && ($GLOBALS['configuration']['paypalbusiness'] || $GLOBALS['configuration']['enable_balance'] && $currentUser->user['balance'] && $currentUser->user['balance'] >= $totalPrice)) {
         if ($GLOBALS['configuration']['paypalbusiness']) {
             $GLOBALS['configuration']['paypalmode'] == 'sandbox' ? $paypalUrl = "www.sandbox.paypal.com" : ($paypalUrl = "www.paypal.com");
             //Toggle sandbox/normal use
             $GLOBALS['configuration']['paypaldebug'] ? $fieldType = 'text' : ($fieldType = 'hidden');
             //$form -> addElement('submit', 'submit_checkout_paypal', _PAYPALPAYNOW, 'class = "flatButton"');
             //Calculate price after discount, if any
             if ($form->isSubmitted() && $form->validate() && $form->exportValue('coupon') && ($coupon = new coupons($form->exportValue('coupon'), true))) {
                 if (!$coupon->checkEligibility($currentUser)) {
                     throw new Exception(_INVALIDCOUPON);
                 }
                 $totalPrice = $totalPrice * (1 - $coupon->{$coupon->entity}['discount'] / 100);
                 $useCoupon = 1;
             }
             $productNames = $lessonIds = $courseIds = array();
             foreach ($cart['lesson'] as $lesson) {
                 if ($lesson['recurring']) {
                     !$useCoupon or $lesson['price'] = $lesson['price'] * (1 - $coupon->{$coupon->entity}['discount'] / 100);
                     //$lesson['product_type'] = 'lesson';
                     $recurring = $lesson;
                 }
                 $productNames[] = $lesson['name'];
                 $lessonIds[] = $lesson['id'];