예제 #1
1
 function handle(&$params)
 {
     if (!@$_REQUEST['email']) {
         return PEAR::raiseError("No email address  specified");
     }
     import('HTML/QuickForm.php');
     $form = new HTML_QuickForm('opt_out_form', 'post');
     $form->addElement('hidden', 'email', $_REQUEST['email']);
     $form->addElement('hidden', '-action', 'email_opt_out');
     $form->addElement('submit', 'submit', 'Cancel Subscription');
     if ($form->validate()) {
         $res = mysql_query("replace into dataface__email_blacklist (email) values ('" . addslashes($_REQUEST['email']) . "')", df_db());
         if (!$res) {
             trigger_error(mysql_error(df_db()), E_USER_ERROR);
         }
         header('Location: ' . DATAFACE_SITE_HREF . '?--msg=' . urlencode('You have successfully opted out of our mail list.  You will no longer receive emails from us.'));
         exit;
     }
     ob_start();
     $form->display();
     $html = ob_get_contents();
     ob_end_clean();
     $context = array();
     $context['form'] = $html;
     df_register_skin('email', DATAFACE_PATH . '/modules/Email/templates');
     df_display($context, 'email/opt_out_form.html');
 }
예제 #2
0
파일: Modules.php 프로젝트: cretzu89/EPESI
 public function body()
 {
     ob_start();
     //create default module form
     print '<div class="title">Select modules to disable</div>';
     print 'Selected modules will be marked as not installed but uninstall methods will not be called. Any database tables and other modifications made by modules\' install methods will not be reverted.<br><br>';
     print 'To uninstall module please use Modules Administration in Application.';
     print '<hr/><br/>';
     $form = new HTML_QuickForm('modulesform', 'post', $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET), '', null, true);
     $states = array(ModuleManager::MODULE_ENABLED => 'Active', ModuleManager::MODULE_DISABLED => 'Inactive');
     $modules = DB::GetAssoc('SELECT * FROM modules ORDER BY state, name');
     foreach ($modules as $m) {
         $name = $m['name'];
         $state = isset($m['state']) ? $m['state'] : ModuleManager::MODULE_ENABLED;
         if ($state == ModuleManager::MODULE_NOT_FOUND) {
             $state = ModuleManager::MODULE_DISABLED;
         }
         $form->addElement('select', $name, $name, $states);
         $form->setDefaults(array($name => $state));
     }
     $form->addElement('button', 'submit_button', 'Save', array('class' => 'button', 'onclick' => 'if(confirm("Are you sure?")) document.modulesform.submit();'));
     //validation or display
     if ($form->validate()) {
         //uninstall
         $vals = $form->exportValues();
         foreach ($vals as $k => $v) {
             if (isset($modules[$k]['state']) && $modules[$k]['state'] != $v) {
                 ModuleManager::set_module_state($k, $v);
             }
         }
     }
     $form->display();
     return ob_get_clean();
 }
예제 #3
0
 public function __construct()
 {
     parent::__construct();
     if ($this->loginError) {
         return;
     }
     $this->use_mootools = true;
     $this->pub =& $_SESSION['pub'];
     if (isset($this->pub->pub_id)) {
         $this->page_title = 'Edit Publication';
     }
     // initialize attachments
     if (!isset($_SESSION['paper']) && !isset($_SESSION['attachments'])) {
         $_SESSION['paper'] = $this->pub->paperFilenameGet();
         if (count($this->pub->additional_info) > 0) {
             for ($i = 0, $n = count($this->pub->additional_info); $i < $n; $i++) {
                 $_SESSION['attachments'][$i] = $this->pub->attFilenameGet($i);
                 $_SESSION['att_types'][$i] = $this->pub->additional_info[$i]->type;
             }
         }
     }
     $form = new HTML_QuickForm('add_pub4');
     $this->form =& $form;
     $this->formAddAttachments();
     $this->formAddWebLinks();
     $this->formRelatedPubs();
     $pos = strpos($_SERVER['PHP_SELF'], 'papersdb');
     $url = substr($_SERVER['PHP_SELF'], 0, $pos) . 'papersdb';
     $form->addGroup(array(HTML_QuickForm::createElement('submit', 'prev_step', '<< Previous Step'), HTML_QuickForm::createElement('button', 'cancel', 'Cancel', array('onclick' => "cancelConfirm();")), HTML_QuickForm::createElement('reset', 'reset', 'Reset'), HTML_QuickForm::createElement('submit', 'finish', 'Finish')), 'buttons', null, '&nbsp;', false);
     if ($form->validate()) {
         $this->processForm();
     } else {
         $this->renderForm();
     }
 }
예제 #4
0
 /**
  * function_description
  *
  * @author	John.meng
  * @since    version - Jan 5, 2006
  * @param	datatype paramname description
  * @return   datatype description
  */
 function drawLogin()
 {
     global $__Lang__, $UrlParameter, $SiteDB, $AddIPObj, $FlushPHPObj, $form, $smarty;
     include_once PEAR_DIR . 'HTML/QuickForm.php';
     $form = new HTML_QuickForm('firstForm');
     $replace_str = "../";
     $html_code = str_replace(ROOT_DIR, $replace_str, THEMES_DIR);
     echo "<link href='" . $html_code . "style.css' rel='stylesheet' type='text/css'>";
     $renderer =& $form->defaultRenderer();
     $renderer->setFormTemplate("\n<form{attributes}>\n<table border=\"0\" class=\"log_table\" align=\"center\">\n{content}\n</table>\n</form>");
     $renderer->setHeaderTemplate("\n\t<tr>\n\t\t<td class=\"log_table_head\" align=\"left\" valign=\"top\" colspan=\"2\" ><b>{header}</b></td>\n\t</tr>");
     $form->addElement('header', null, "<img src=\"" . $html_code . "images/logo.gif\" border=\"0\" >");
     $form->addElement('text', 'user_name', $__Lang__['langMenuUser'] . $__Lang__['langGeneralName'] . ' : ');
     $form->addElement('password', 'user_passwd', $__Lang__['langMenuUser'] . $__Lang__['langGeneralPassword'] . ' : ');
     $form->addRule('user_name', $__Lang__['langGeneralPleaseEnter'] . " " . $__Lang__['langMenuUser'] . " " . $__Lang__['langGeneralName'], 'required');
     $form->addRule('user_passwd', $__Lang__['langGeneralPleaseEnter'] . " " . $__Lang__['langMenuUser'] . " " . $__Lang__['langGeneralPassword'], 'required');
     $form->addElement('hidden', 'Action', 'LOGON');
     $form->setDefaults(array('user_name' => $_COOKIE['UserName']));
     $form->addElement('submit', null, $__Lang__['langGeneralSubmit']);
     $form->addElement('static', 'login_message');
     if ($form->validate() && $_POST['Action'] == 'LOGON') {
         $user_name = $_POST['user_name'];
         $user_password = md5($_POST['user_passwd']);
         $this->checkAuth($user_name, $user_password);
     }
     $form->display();
     exit;
 }
function makeExportForm($selfurl, $inbox)
{
    global $uid;
    $form = new HTML_QuickForm('export', 'post', "{$selfurl}&op=export&noheaderfooter=true");
    $msg = "<p>You can export this data as a CSV (comma-separated values) file, " . "<br/>which can then be imported into Excel for analysis and graphing." . "</p><br/>";
    $form->addElement('header', '', 'Export');
    $form->addElement('static', '', '', $msg);
    $datatype = $form->addElement('select', 'datatype', "Export What", array(EXPORT_ALLDATA => 'All Data', EXPORT_HISTOGRAM_MSG => 'Histogram by Message', EXPORT_HISTOGRAM_DAY => 'Histogram by Day', EXPORT_HISTOGRAM_MONTH => 'Histogram by Month'));
    $form->addElement('submit', 'submit', 'Export');
    if ($form->validate()) {
        $datatypeval = $datatype->getValue();
        switch ($datatypeval[0]) {
            case EXPORT_ALLDATA:
                exportAllData($inbox);
                break;
            default:
                $uidquery = $uid;
                if (isadmin() && !$uid) {
                    unset($uidquery);
                }
                if ($inbox) {
                    $counts = generateHistogramInbox($datatypeval[0], $uid);
                } else {
                    $counts = generateHistogramOutbox($datatypeval[0], $uid);
                }
                $filename = $inbox ? 'inbox-hist-export.csv' : 'outbox-hist-export.csv';
                exportHistogram($counts, $filename);
                break;
        }
        exit;
    }
    $form->display();
}
예제 #6
0
 public function __construct()
 {
     parent::__construct('authorize_new_users');
     if ($this->loginError) {
         return;
     }
     $this->loadHttpVars(true, true);
     $this->users = pdUserList::getNotVerified($this->db);
     echo '<h2>Users Requiring Authentication</h2>';
     if ($this->users == null || count($this->users) == 0) {
         echo 'All users authorized.';
         return;
     }
     $form = new HTML_QuickForm('authorizeUsers', 'post');
     foreach ($this->users as $user) {
         $form->addGroup(array(HTML_QuickForm::createElement('advcheckbox', "submit[auth][{$user->login}]", null, null, null, array('no', 'yes')), HTML_QuickForm::createElement('select', "submit[access][{$user->login}]", null, AccessLevel::getAccessLevels()), HTML_QuickForm::createElement('static', null, null, $user->login), HTML_QuickForm::createElement('static', null, null, $user->name), HTML_QuickForm::createElement('static', null, null, $user->email)), 'all', null, '</td><td class="stats_odd">', false);
     }
     $form->addElement('submit', null, 'Submit');
     $this->form =& $form;
     if ($form->validate()) {
         $this->processForm();
     } else {
         $this->renderForm();
     }
 }
예제 #7
0
 public function __construct()
 {
     parent::__construct('delete_interest', 'Delete Interest', 'Admin/delete_interest.php');
     if ($this->loginError) {
         return;
     }
     $form = new HTML_QuickForm('deleter');
     $interest_list = new pdAuthInterests($this->db);
     $form->addElement('select', 'interests', 'Select interest(s) to delete:', $interest_list->list, array('multiple' => 'multiple', 'size' => 15));
     $form->addGroup(array(HTML_QuickForm::createElement('button', 'cancel', 'Cancel', array('onclick' => 'history.back()')), HTML_QuickForm::createElement('submit', 'submit', 'Delete')), null, null, '&nbsp;', false);
     if ($form->validate()) {
         $values = $form->exportValues();
         foreach ($values['interests'] as $interest_id) {
             $names[] = $interest_list->list[$interest_id];
         }
         $interest_list->dbDelete($this->db, $values['interests']);
         echo 'You have successfully removed the following interest from the ', 'database: <br/><b>', implode(', ', $names), '</b></p>', '<br><a href="', $_SERVER['PHP_SELF'], '">Delete another interest</a>';
     } else {
         $renderer =& $form->defaultRenderer();
         $form->accept($renderer);
         $this->form =& $form;
         $this->renderer =& $renderer;
         echo '<h3>Delete Interest </h3>';
     }
 }
예제 #8
0
 function renderHtml()
 {
     $type_key = $this->context->getTypeKeys();
     if (is_numeric($this->query('sletbillede'))) {
         $fields = array('date_updated', 'pic_id');
         $values = array('NOW()', 0);
         $sth = $this->db->autoPrepare('langtkursus_tilmelding', $fields, DB_AUTOQUERY_UPDATE, 'id = ' . $this->query('id'));
         $res = $this->db->execute($sth, $values);
         if (PEAR::isError($res)) {
             throw new Exception($res->getMessage());
         }
     }
     $form = new HTML_QuickForm();
     $form->addElement('hidden', 'id', $this->name());
     $form->addElement('file', 'userfile', 'Fil');
     $form->addElement('submit', null, 'Upload');
     if ($form->validate()) {
         $file = new VIH_FileHandler();
         if ($file->upload('userfile')) {
             $fields = array('date_updated', 'pic_id');
             $values = array('NOW()', $file->get('id'));
             $sth = $this->db->autoPrepare('langtkursus_tilmelding', $fields, DB_AUTOQUERY_UPDATE, 'id = ' . $form->exportValue('id'));
             $res = $this->db->execute($sth, $values);
             if (PEAR::isError($res)) {
                 throw new Exception($res->getMessage());
             }
             return new k_SeeOther($this->url('./'));
         }
     }
     $tilmelding = new VIH_Model_LangtKursus_Tilmelding($this->name());
     if ($tilmelding->get('id') == 0) {
         throw new k_http_Response(404);
     }
     $file = new VIH_FileHandler($tilmelding->get('pic_id'));
     $file->loadInstance('small');
     $extra_html = $file->getImageHtml($tilmelding->get('name'), 'width="100""');
     $file->loadInstance('medium');
     $stor = $file->get('file_uri');
     if (empty($extra_html)) {
         $extra_html = $form->toHTML();
     } else {
         $extra_html .= ' <br /><a href="' . $stor . '">stor</a> <a href="' . url('./') . '?sletbillede=' . $this->name() . '" onclick="return confirm(\'Er du sikker\');">slet billede</a>';
     }
     $res = $this->db->query('SELECT *, DATE_FORMAT(date_start, "%d-%m %H:%i") AS date_start_dk, DATE_FORMAT(date_end, "%d-%m %H:%i") AS date_end_dk FROM langtkursus_tilmelding_protokol_item WHERE tilmelding_id = ' . (int) $this->name() . ' ORDER BY date_start DESC, date_end DESC');
     if (PEAR::isError($res)) {
         throw new Exception($res->getMessage());
     }
     $data = array('items' => $res, 'type_key' => $type_key, 'vis_navn' => false);
     $this->document->setTitle($tilmelding->get('navn'));
     $this->document->addOption('Ret', $this->url('../../../langekurser/tilmeldinger/' . $tilmelding->get('id')));
     $this->document->addOption('Indtast', $this->url('indtast'));
     $this->document->addOption('Tilmelding', $this->url('../../../langekurser/tilmeldinger/' . $tilmelding->get('id')));
     $this->document->addOption('F*g', $this->url('../../../langekurser/tilmeldinger/' . $tilmelding->get('id') . '/f*g'));
     $this->document->addOption('Holdliste', $this->context->url());
     $this->document->addOption('Diplom', $this->url('../../../langekurser/tilmeldinger/' . $tilmelding->get('id') . '/diplom'));
     $tpl = $this->template->create('protokol/liste');
     return '<div style="border: 1px solid #ccc; padding: 0.5em; float: right;">' . $extra_html . '</div>
         ' . $tpl->render($this, $data);
 }
 /**
  * function_description
  *
  * @author	John.meng
  * @since    version - Jan 19, 2006
  * @param	datatype paramname description
  * @return   datatype description
  */
 function opAdd()
 {
     global $__Lang__, $UrlParameter, $SiteDB, $AddIPObj, $__SITE_VAR__, $form, $FlushPHPObj, $thisDAO, $smarty, $class_path;
     include_once PEAR_DIR . 'HTML/QuickForm.php';
     $form = new HTML_QuickForm('firstForm', 'post', '', '_self', "onsubmit='save_in_textarea_all();'");
     $renderer =& $form->defaultRenderer();
     $renderer->setFormTemplate("\n<form{attributes}>\n<table border=\"0\" class=\"new_table\" width='100%'>\n{content}\n</table>\n</form>");
     $renderer->setHeaderTemplate("\n\t<tr>\n\t\t<td class=\"grid_table_head\" align=\"left\" valign=\"top\" colspan=\"2\"><b>{header}</b></td>\n\t</tr>");
     $Content = $_POST['Content'];
     if ($_REQUEST['Action'] == 'Update') {
         $this_data = $this->_DAO->getRowByID(SITE_NEWS_TABLE, "NewsID", $_REQUEST['ID']);
         $form->setDefaults(array("Title" => $this_data['Title'], "Summary" => $this_data['Summary'], "Source" => $this_data['Source'], "Author" => $this_data['Author']));
         $Content = $this_data['Content'];
         $form->addElement('hidden', 'ID', $this_data['NewsID']);
     }
     $class_path = INCLUDE_DIR . "editor/";
     $CurrentUserPathImages = HTML_IMAGES_DIR;
     $SiteCssFile = CURRENT_HTML_DIR . "style.css";
     $ed_4 =& new rich("", 'Content', $Content, "380", "350", "../../" . $CurrentUserPathImages, "../../" . $CurrentUserPathImages, false, false);
     $ed_4->set_default_stylesheet($SiteCssFile);
     $ed_4->myModule(true);
     $editors = $ed_4->draw();
     $smarty->assign("class_path_editor", $class_path);
     $form->addElement('header', null, $__Lang__['langGeneralAdd'] . " " . $__Lang__['langSiteModuleNews']);
     $form->addElement('text', 'Title', $__Lang__['langModuleNewsTitle'] . ' : ', array('size' => 40));
     $form->addElement('textarea', 'Summary', $__Lang__['langModuleNewsSummary'] . ' : ', array('rows' => 5, 'cols' => 40));
     $form->addElement('static', 'Content', NULL, $editors);
     $form->addElement('text', 'Source', $__Lang__['langModuleNewsSource'] . ' : ', array('size' => 30));
     $form->addElement('text', 'Author', $__Lang__['langModuleNewsAuthor'] . ' : ', array('size' => 20));
     $form->addElement('submit', null, $__Lang__['langGeneralSubmit']);
     $form->addRule('Title', $__Lang__['langGeneralPleaseEnter'] . " " . $__Lang__['langModuleNewsTitle'], 'required');
     $form->addElement('hidden', 'Module', $_REQUEST['Module']);
     $form->addElement('hidden', 'Page', $_REQUEST['Page']);
     $form->addElement('hidden', 'Action', $_REQUEST['Action']);
     $form->addElement('hidden', 'MenuID', $_GET['MenuID']);
     if ($form->validate()) {
         if (get_magic_quotes_gpc()) {
             $record["Content"] = stripslashes($_POST['Content']);
         } else {
             $record["Content"] = $_POST['Content'];
         }
         $record["Title"] = $_POST['Title'];
         $record["Summary"] = $_POST['Summary'];
         $record["Source"] = $_POST['Source'];
         $record["Author"] = $_POST['Author'];
         $record["SiteMenuID"] = $_POST['MenuID'];
         $record = $record + $this->_DAO->baseField();
         if ($_POST['ID'] && $_POST['Action'] == 'Update') {
             $this->_DAO->opUpdate(SITE_NEWS_TABLE, $record, " NewsID = " . $_POST['ID']);
         } else {
             $this->_DAO->opAdd(SITE_NEWS_TABLE, $record);
         }
         echo "<SCRIPT LANGUAGE='JavaScript'>opener.window.location.reload();window.close();</SCRIPT>";
     }
     $html_code = "<link rel=\"StyleSheet\" type=\"text/css\" href=\"" . $class_path . "rich_files/rich.css\"><script language=\"JScript.Encode\" src=\"" . $class_path . "rich_files/rich.js\"></script>" . $form->toHTML();
     $smarty->assign("Main", str_replace(ROOT_DIR, "../", $html_code));
 }
예제 #10
0
 function handle(&$params)
 {
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $this->table =& Dataface_Table::loadTable($query['-table']);
     $translations =& $this->table->getTranslations();
     foreach (array_keys($translations) as $trans) {
         $this->table->getTranslation($trans);
     }
     //print_r($translations);
     if (!isset($translations) || count($translations) < 2) {
         // there are no translations to be made
         trigger_error('Attempt to translate a record in a table "' . $this->table->tablename . '" that contains no translations.', E_USER_ERROR);
     }
     $this->translatableLanguages = array_keys($translations);
     $translatableLanguages =& $this->translatableLanguages;
     $this->languageCodes = new I18Nv2_Language($app->_conf['lang']);
     $languageCodes =& $this->languageCodes;
     $currentLanguage = $languageCodes->getName($app->_conf['lang']);
     if (count($translatableLanguages) < 2) {
         return PEAR::raiseError(df_translate('Not enough languages to translate', 'There aren\'t enough languages available to translate.'), DATAFACE_E_ERROR);
     }
     //$defaultSource = $translatableLanguages[0];
     //$defaultDest = $translatableLanguages[1];
     $options = array();
     foreach ($translatableLanguages as $lang) {
         $options[$lang] = $languageCodes->getName($lang);
     }
     unset($options[$app->_conf['default_language']]);
     $tt = new Dataface_TranslationTool();
     $form = new HTML_QuickForm('StatusForm', 'POST');
     $form->addElement('select', '--language', 'Translation', $options);
     $form->addElement('select', '--status', 'Status', $tt->translation_status_codes);
     //$form->setDefaults( array('-sourceLanguage'=>$defaultSource, '-destinationLanguage'=>$defaultDest));
     $form->addElement('submit', '--set_status', 'Set Status');
     foreach ($query as $key => $value) {
         $form->addElement('hidden', $key);
         $form->setDefaults(array($key => $value));
     }
     if ($form->validate()) {
         $res = $form->process(array(&$this, 'processForm'));
         if (PEAR::isError($res)) {
             return $res;
         } else {
             header('Location: ' . $app->url('-action=list&-sourceLanguage=&-destinationLanguage=&-translate=') . '&--msg=' . urlencode('Translation status successfully set.'));
             exit;
         }
     }
     ob_start();
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $records =& $this->getRecords();
     df_display(array('form' => $out, 'translationTool' => &$tt, 'records' => &$records, 'translations' => &$options, 'context' => &$this), 'Dataface_set_translation_status.html');
 }
예제 #11
0
 function validate()
 {
     $ret = parent::validate();
     if (!$ret) {
         // The form returned an error. We need to generate a new CSRF token, in any.
         $token = $this->getElement('token');
         if (!empty($token) && !PEAR::isError($token)) {
             $token->setValue(phpAds_SessionGetToken());
         }
     }
     return $ret;
 }
예제 #12
0
    public function __construct()
    {
        parent::__construct();
        if ($this->loginError) {
            return;
        }
        $this->use_mootools = true;
        $this->pub =& $_SESSION['pub'];
        if (isset($this->pub->pub_id)) {
            $this->page_title = 'Edit Publication';
        }
        $this->authors = pdAuthorList::create($this->db, null, null, true);
        $form = new HTML_QuickForm('add_pub2', 'post', '', '', array('onsubmit' => 'return check_authors("add_pub2");'));
        $form->addElement('header', null, 'Select from Authors in Database');
        $tooltip = 'Authors::The authors of the publication. Listed in the
same order as in the publication
&lt;p/&gt;
If an author is not already in the database press the &lt;b&gt;Add Author not
in DB&lt;/b&gt; button.';
        $form->addElement('textarea', 'authors', "<div id=\"MYCUSTOMFLOATER\"  class=\"myCustomFloater\" style=\"position:absolute;top:200px;left:600px;background-color:#cecece;display:none;visibility:hidden\"><div class=\"myCustomFloaterContent\"></div></div>" . "<span class=\"Tips1\" title=\"{$tooltip}\">Authors</span>:", array('cols' => 60, 'rows' => 5, 'class' => 'wickEnabled:MYCUSTOMFLOATER', 'wrap' => 'virtual'));
        $form->addElement('static', null, null, '<span class="small">' . 'There are ' . count($this->authors) . ' authors in the database. Type a partial name to ' . 'see a list of matching authors. Separate names ' . 'using commas.</span>');
        $form->addElement('submit', 'add_new_author', 'Add Author not in DB');
        // collaborations radio selections
        $tooltip = 'Collaborations::If the publication is a collaboration,
select the options that apply to this paper.';
        $form->addElement('header', null, "<span class=\"Tips1\" title=\"{$tooltip}\">Collaborations</span>");
        $collaborations = pdPublication::collaborationsGet($this->db);
        foreach ($collaborations as $col_id => $description) {
            $radio_cols[] = HTML_QuickForm::createElement('checkbox', 'paper_col[' . $col_id . ']', null, $description, 1);
        }
        $form->addGroup($radio_cols, 'group_collaboration', null, '<br/>', false);
        $pos = strpos($_SERVER['PHP_SELF'], 'papersdb');
        $url = substr($_SERVER['PHP_SELF'], 0, $pos) . 'papersdb';
        $buttons[] = HTML_QuickForm::createElement('submit', 'prev_step', '<< Previous Step');
        $buttons[] = HTML_QuickForm::createElement('button', 'cancel', 'Cancel', array('onclick' => "cancelConfirm();"));
        $buttons[] = HTML_QuickForm::createElement('submit', 'next_step', 'Next Step >>');
        if ($this->pub->pub_id != '') {
            $buttons[] = HTML_QuickForm::createElement('submit', 'finish', 'Finish');
        }
        $form->addGroup($buttons, 'buttons', '', '&nbsp;', false);
        $this->form =& $form;
        if ($form->validate()) {
            $this->processForm();
        } else {
            $this->renderForm();
        }
    }
예제 #13
0
 public function __construct()
 {
     parent::__construct('view_publication', 'View Publication', 'view_publication.php');
     if ($this->loginError) {
         return;
     }
     $this->loadHttpVars();
     if (!isset($this->pub_id) || !is_numeric($this->pub_id)) {
         $this->pageError = true;
         return;
     }
     $pub = new pdPublication();
     $result = $pub->dbLoad($this->db, $this->pub_id);
     if (!$result) {
         echo 'Publication does not exist';
         return;
     }
     if (isset($this->submit_pending) && $this->submit_pending) {
         // check if this pub entry is pending
         $q = $this->db->selectRow('pub_pending', '*', array('pub_id' => $this->pub_id));
         assert('$q');
         $form = new HTML_QuickForm('submit_pending');
         $form->addElement('hidden', 'submit_pending', true);
         $form->addElement('hidden', 'pub_id', $this->pub_id);
         $elements = array();
         $elements[] = HTML_QuickForm::createElement('advcheckbox', 'valid', null, 'Valid', null, array(0, 1));
         $elements[] = HTML_QuickForm::createElement('submit', 'submit', 'Submit');
         $form->addGroup($elements, 'elgroup', '', '&nbsp', false);
         // create a new renderer because $form->defaultRenderer() creates
         // a single copy
         $renderer = new HTML_QuickForm_Renderer_Default();
         $form->accept($renderer);
         if ($form->validate()) {
             $values =& $form->exportValues();
             $pub->markValid($this->db);
             echo 'Publication entry marked as valid.';
             return;
         } else {
             echo "<h2>This publication entry requires validation</h2>\n";
             echo $renderer->toHtml();
         }
     }
     $this->showPublication($pub);
 }
예제 #14
0
파일: login.php 프로젝트: papersdb/papersdb
 public function __construct()
 {
     parent::__construct('login');
     if ($this->loginError) {
         return;
     }
     $this->loadHttpVars(true, false);
     $this->password_hash = "aicml";
     if ($this->access_level > 0) {
         echo 'You are already logged in as ', $_SESSION['user']->login, '.';
         $this->pageError = true;
         return;
     }
     if (empty($this->redirect) || strpos($this->redirect, 'login.php') !== false) {
         // never redirect to the login page
         $this->redirect = 'index.php';
     }
     $form = new HTML_QuickForm('login');
     $form->addElement('header', 'login_header', 'Login');
     $form->addElement('text', 'username', 'Login:'******'size' => 25, 'maxlength' => 40));
     $form->addRule('username', 'login cannot be empty', 'required', null, 'client');
     $form->addElement('password', 'password', 'Password:'******'size' => 25, 'maxlength' => 40));
     $form->addRule('password', 'password cannot be empty', 'required', null, 'client');
     $form->addElement('submit', 'submit_username', 'Login');
     $form->addElement('header', 'new_users', 'New Users Only');
     $form->addElement('password', 'password_again', 'Confirm Password:'******'size' => 25, 'maxlength' => 40));
     $form->addElement('text', 'email', 'email:', array('size' => 25, 'maxlength' => 80));
     $form->addRule('email', 'invalid email address', 'email', null, 'client');
     $form->addElement('text', 'realname', 'Real Name:', array('size' => 25, 'maxlength' => 80));
     $form->addElement('submit', 'newaccount', 'Create new account');
     $form->addElement('hidden', 'redirect', $this->redirect);
     $this->form =& $form;
     if ($form->validate()) {
         $this->processForm();
         return;
     }
     // only get here if form hasn't been submitted
     echo '<h2><a href="#">Log In or Create a New Account</a></h2>';
 }
예제 #15
0
function manage_display($task)
{
    global $cfg, $db, $cache;
    if ($task == '') {
        $task = 'status';
    }
    // Verify that the user has management perms for the selected contest
    $res =& db_query('contest_by_id', $_GET['id']);
    $res->fetchInto($row);
    $res->free();
    if ($_SESSION['user_id'] != $row['manager'] && !auth_user_in_group('Administrators')) {
        error("Access denied. You are not the contest-manager for this contest.");
    }
    switch ($task) {
        case 'status':
            $table = new HTML_Table();
            // Re-use $row from above
            if ($row['show_future'] == 1) {
                $status = 'Hidden (not activated yet)';
            } else {
                if ($row['begin_future'] == 1) {
                    $status = 'Not started';
                } else {
                    if ($row['end_future'] == 1) {
                        $status = 'Running';
                    } else {
                        $status = 'Ended';
                    }
                }
            }
            $table->addRow(array('Contest status: ', $status), null, 'TH');
            $table->addRow(array('Name: ', $row['name']));
            $table->addRow(array('Description: ', $row['description']));
            $table->addRow(array('Activation time: ', $row['show_time']));
            $table->addRow(array('Begin time: ', $row['begin_time']));
            $table->addRow(array('End time: ', $row['end_time']));
            if ($row['team_size'] != 1) {
                $table->addRow(array('Max size of team: ', $row['team_size']));
                $prefix = 'Teams';
            } else {
                $table->addRow(array('Individual event: ', 'Yes'));
                $prefix = 'Participants';
            }
            // No. of registered teams
            $res =& db_query('count_teams_by_contest_id', $_GET['id']);
            $res->fetchInto($row);
            $res->free();
            $table->addRow(array($prefix . ' registered: ', $row['count']));
            // No. of teams logged in
            $res =& db_query('count_last_teams_by_contest_id', $_GET['id']);
            $res->fetchInto($row);
            $res->free();
            $table->addRow(array($prefix . ' seen in last 30 minutes: ', $row['count']));
            $table->altRowAttributes(1, null, array("class" => "altrow"));
            echo '<div class="overflow">' . $table->toHtml() . '</div>';
            break;
        case 'problems':
            // display problem info as table
            $table = new HTML_Table();
            $res =& db_query('problems_by_contest_id', $_GET['id']);
            if (!$res->fetchInto($row)) {
                ?>
<p>No problems added yet.</p>			
			<?php 
            } else {
                // extra attributes
                $row['content'] = null;
                $row['actions'] = null;
                $table->addRow(array_keys($row), null, 'TH');
                while ($row) {
                    $row['content'] = "<a href=\"index.php?view=manage&amp;task=show_problem&amp;id={$_GET['id']}&amp;prob_id={$row['prob_id']}\">show</a>";
                    $row['actions'] = "<a href=\"index.php?view=manage&amp;task=edit_problem&amp;id={$_GET['id']}&amp;prob_id={$row['prob_id']}\">edit</a>, " . "<a href=\"index.php?view=manage&amp;task=del_problem&amp;id={$_GET['id']}&amp;prob_id={$row['prob_id']}\">delete</a>";
                    $table->addRow(array_values($row));
                    $res->fetchInto($row);
                }
                $res->free();
                // display tables
                $table->altRowAttributes(1, null, array("class" => "altrow"));
                echo '<div class="overflow">' . $table->toHtml() . '</div>';
            }
            echo "<hr />";
            // form for adding a problem
            $form = new HTML_QuickForm('problemAddForm', 'post', selflink());
            $form->addElement('header', null, 'Add a problem');
            $form->addElement('text', 'prob_id', 'Name (one word ID): ');
            $form->addElement('text', 'summary', 'Summary: ');
            $form->addElement('text', 'weight', 'Points weightage: ');
            $form->addElement('text', 'time_limit', 'Time limit: ');
            $form->addElement('text', 'mem_limit', 'Memory limit: ');
            $elem =& $form->addElement('textarea', 'content', 'Problem content (XML): ');
            $elem->setRows(10);
            $elem->setCols(80);
            $form->addElement('submit', null, 'Submit');
            $form->applyFilter('prob_id', 'trim');
            $form->applyFilter('summary', 'trim');
            $form->applyFilter('weight', 'trim');
            $form->applyFilter('time_limit', 'trim');
            $form->applyFilter('mem_limit', 'trim');
            $form->addRule('prob_id', 'Problem ID is required', 'required', null, 'client');
            $form->addRule('summary', 'Problem summary is required', 'required', null, 'client');
            $form->addRule('weight', 'Points weightage is required', 'required', null, 'client');
            $form->addRule('time_limit', 'Time limit is required', 'required', null, 'client');
            $form->addRule('mem_limit', 'Memory limit is required', 'required', null, 'client');
            $form->addRule('content', 'Problem content in XML is required', 'required', null, 'client');
            if ($form->validate()) {
                $data = $form->getSubmitValues();
                $errs = problem_check($data['content']);
                if ($errs == null) {
                    $data['contest_id'] = $_GET['id'];
                    $res =& $db->autoExecute('problems', $data, DB_AUTOQUERY_INSERT);
                    if (PEAR::isError($res)) {
                        error($res->toString());
                    }
                    $cache->remove(problem_cache_id($_GET['id'], $data['prob_id']) . '.htm');
                    $cache->remove(problem_cache_id($_GET['id'], $data['prob_id']) . '.prob');
                    redirect('index.php?view=manage&task=problems&id=' . $_GET['id']);
                } else {
                    ?>
<p><b>Error:</b> The problem could not be added due to the following errors encountered while
parsing the problem XML file. Please fix them and try submitting again.</p>
				<?php 
                    echo "<ol class=\"errors\">\n";
                    foreach ($errs as $line) {
                        echo "<li>{$line}</li>\n";
                    }
                    echo "</ol>\n<hr />\n";
                }
            }
            $form->display();
            break;
        case 'del_problem':
            db_query('del_problem_by_id', array($_GET['prob_id'], $_GET['id']));
            redirect('index.php?view=manage&task=problems&id=' . $_GET['id']);
            break;
        case 'edit_problem':
            $res =& db_query('problem_by_id', array($_GET['prob_id'], $_GET['id']));
            $res->fetchInto($row);
            $res->free();
            // Get XML content too
            $res =& db_query('problem_content_by_id', array($_GET['prob_id'], $_GET['id']));
            $res->fetchInto($row2);
            $res->free();
            $row['content'] =& $row2['content'];
            // form for editing a problem
            $form = new HTML_QuickForm('problemAddForm', 'post', selflink());
            $form->addElement('header', null, 'Edit a problem');
            $form->addElement('text', 'prob_id', 'Name (one word ID): ');
            $form->addElement('text', 'summary', 'Summary: ');
            $form->addElement('text', 'weight', 'Points weightage: ');
            $form->addElement('text', 'time_limit', 'Time limit: ');
            $form->addElement('text', 'mem_limit', 'Memory limit: ');
            $elem =& $form->addElement('textarea', 'content', 'Problem content (XML): ');
            $elem->setRows(10);
            $elem->setCols(80);
            $form->addElement('submit', null, 'Submit');
            $form->applyFilter('prob_id', 'trim');
            $form->applyFilter('summary', 'trim');
            $form->applyFilter('weight', 'trim');
            $form->applyFilter('time_limit', 'trim');
            $form->applyFilter('mem_limit', 'trim');
            $form->addRule('prob_id', 'Problem ID is required', 'required', null, 'client');
            $form->addRule('summary', 'Problem summary is required', 'required', null, 'client');
            $form->addRule('weight', 'Points weightage is required', 'required', null, 'client');
            $form->addRule('time_limit', 'Time limit is required', 'required', null, 'client');
            $form->addRule('mem_limit', 'Memory limit is required', 'required', null, 'client');
            $form->addRule('content', 'Problem content in XML is required', 'required', null, 'client');
            $form->setDefaults($row);
            if ($form->validate()) {
                $data = $form->getSubmitValues();
                $errs = problem_check($data['content']);
                if ($errs == null) {
                    //$data['contest_id'] = $_GET['id'];
                    $data['version'] = $row['version'] + 1;
                    // increment version
                    $res =& $db->autoExecute('problems', $data, DB_AUTOQUERY_UPDATE, 'contest_id=' . $_GET['id'] . " AND prob_id='" . $data['prob_id'] . "'");
                    if (PEAR::isError($res)) {
                        error($res->toString());
                    }
                    $cache->remove(problem_cache_id($_GET['id'], $data['prob_id']) . '.htm');
                    $cache->remove(problem_cache_id($_GET['id'], $data['prob_id']) . '.prob');
                    redirect('index.php?view=manage&task=problems&id=' . $_GET['id']);
                } else {
                    ?>
<p><b>Error:</b> The changes could not be saved due to the following errors encountered while
parsing the problem XML file. Please fix them and try submitting again.</p>
				<?php 
                    echo "<ol class=\"errors\">\n";
                    foreach ($errs as $line) {
                        echo "<li>{$line}</li>\n";
                    }
                    echo "</ol>\n<hr />\n";
                }
            }
            $form->display();
            break;
        case 'show_problem':
            $res =& db_query('problem_by_id', array($_GET['prob_id'], $_GET['id']));
            $res->fetchInto($problem);
            $res->free();
            problem_display($problem);
            break;
        case 'settings':
            // Re-using $row from above
            // form for editing the contest
            $form = new HTML_QuickForm('contestEditForm', 'post', selflink());
            $form->addElement('header', null, "Edit contest {$row['name']} (id: {$row['contest_id']})");
            $form->addElement('text', 'name', 'Name: ');
            $form->addElement('text', 'description', 'Description: ');
            $elem =& $form->addElement('text', 'team_size', 'Size of team: ');
            $elem->setValue('1');
            $date = getdate();
            $form->addElement('date', 'show_time', 'Activation time: ', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('date', 'begin_time', 'Begin time: ', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('date', 'end_time', 'End time: ', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('text', 'rules', 'Rules URL: ');
            $form->addElement('submit', null, 'Submit');
            // convert date format and store default values
            $row['show_time'] = sql2form_datetime($row['show_time']);
            $row['begin_time'] = sql2form_datetime($row['begin_time']);
            $row['end_time'] = sql2form_datetime($row['end_time']);
            $form->setDefaults($row);
            $form->applyFilter('name', 'trim');
            $form->applyFilter('description', 'trim');
            $form->applyFilter('team_size', 'trim');
            $form->addRule('name', 'Contest name is required.', 'required', null, 'client');
            $form->addRule('team_size', 'Team size is required.', 'required', null, 'client');
            // validate or display form
            if ($form->validate()) {
                $data = $form->getSubmitValues();
                $data['show_time'] = form2sql_datetime($data['show_time']);
                $data['begin_time'] = form2sql_datetime($data['begin_time']);
                $data['end_time'] = form2sql_datetime($data['end_time']);
                $db->autoExecute('contests', $data, DB_AUTOQUERY_UPDATE, 'contest_id=' . $_GET['id']);
                if (PEAR::isError($res)) {
                    error($db->toString());
                }
                redirect('index.php?view=manage&id=' . $_GET['id']);
            } else {
                $form->display();
            }
            break;
        case 'submissions':
            // Re-use $row from above
            if ($row['end_future'] != '1') {
                // Contest has ended, show system test button
                if ($row['tested'] != 1) {
                    ?>
    <p>Contest has ended. 
    <a class="button" href="index.php?view=manage&amp;&amp;task=test&amp;updateratings=false&amp;id=<?php 
                    echo $_GET['id'];
                    ?>
">Test and grade all submissions.</a>
    <a class="button" href="index.php?view=manage&amp;task=test&amp;updateratings=true&amp;id=<?php 
                    echo $_GET['id'];
                    ?>
">Update Ratings</a>

    </p>
                <?php 
                } else {
                    ?>
    <p>Contest has ended and system tests are over.
    <a class="button" href="index.php?view=manage&amp;task=test&amp;id=<?php 
                    echo $_GET['id'];
                    ?>
">Re-run system tests.</a>
    </p>
                <?php 
                }
            }
            // Show table of all solutions in the contest
            $table = new HTML_Table();
            $res =& db_query('solutions_by_contest_id', $_GET['id']);
            if (!$res->fetchInto($row)) {
                // If no solutions in yet
                ?>
<p>Sorry, no solutions have been submitted yet.</p>
			<?php 
            } else {
                $table->addRow(array_keys($row), null, 'TH');
                if ($row['score'] == '') {
                    $row['score'] = 'n/a';
                }
                if ($row['passed'] == '') {
                    $row['passed'] = 'n/a';
                }
                $table->addRow(array_values($row));
                while ($res->fetchInto($row)) {
                    if ($row['score'] == '') {
                        $row['score'] = 'n/a';
                    }
                    if ($row['passed'] == '') {
                        $row['passed'] = 'n/a';
                    }
                    $table->addRow(array_values($row));
                }
                $table->altRowAttributes(1, null, array("class" => "altrow"));
                echo '<div class="overflow">' . $table->toHtml() . '</div>';
            }
            break;
        case 'test':
            require_once 'tester.php';
            ob_end_clean();
            html_reset();
            html_header(null, $cfg["dir"]["themes"] . '/' . $_SESSION["theme"] . '.css', $cfg["dir"]["themes"] . '/' . $_SESSION["theme"] . '-ie.css', null, "submit_frame");
            $contest_id = $_GET['id'];
            $update_ratings = $_GET['updateratings'];
            session_write_close();
            test_contest($update_ratings, $contest_id);
            echo ' <a class="white" href="index.php?view=statistics&amp;task=contest&amp;id=' . $_GET['id'] . '">See the results.</a>';
            html_footer();
            exit;
    }
}
예제 #16
0
    public function __construct()
    {
        parent::__construct('add_author');
        $this->loadHttpVars();
        $this->use_mootools = true;
        $this->all_interests = pdAuthInterests::createList($this->db);
        // before showing a loggin error, show the correct title for the page
        if (isset($_SESSION['state']) && $_SESSION['state'] == 'pub_add') {
            $pub =& $_SESSION['pub'];
            if (isset($pub->pub_id)) {
                $this->page_title = 'Edit Publication';
            } else {
                $this->page_title = 'Add Publication';
            }
        } else {
            if ($this->author_id == null) {
                $this->page_title = 'Add Author';
            } else {
                $this->page_title = 'Edit Author';
            }
        }
        if ($this->loginError) {
            return;
        }
        $author = new pdAuthor();
        if ($this->author_id != null) {
            $result = $author->dbLoad($this->db, $this->author_id, pdAuthor::DB_LOAD_BASIC | pdAuthor::DB_LOAD_INTERESTS);
            if (!$result) {
                $this->pageError = true;
                return;
            }
        }
        $form = new HTML_QuickForm('authorForm');
        $form->addElement('hidden', 'author_id', $this->author_id);
        if ($this->author_id == null) {
            $form->addElement('header', 'add_author_hdr', '<span class="Tips1" title="Adding an Author::Input the
 author\'s first name, last name, email address and organization. Optionally,
 interests may be selected from the list given or new interest can be added to
 the database.
 &lt;p/&gt;
 Multiple interests can be selected by holding down the control
 key and then left-clicking on the text. If you do not see the
 appropriate interests you can add them using the &lt;b&gt;Add
 Interest&lt;/b&gt; link.
 &lt;p/&gt;
 Clicking the &lt;b&gt;Add Interest&lt;/b&gt; link will bring up a
 new field each it is pressed. Type the text of the new interest into the
 this field.">Add Author</span>');
        } else {
            $form->addElement('header', null, 'Edit Author');
        }
        $form->addElement('text', 'firstname', 'First Name:', array('size' => 50, 'maxlength' => 250));
        $form->registerRule('invalid_punct', 'regex', '/^[^()\\/\\*\\^\\?#!@$%+=,\\"\'><~\\[\\]{}]+$/');
        $form->addRule('firstname', 'the first name cannot contain punctuation', 'invalid_punct', null, 'client');
        $form->addElement('text', 'lastname', 'Last Name:', array('size' => 50, 'maxlength' => 250));
        $form->addElement('select', 'authors_in_db', null, pdAuthorList::create($this->db), array('style' => 'overflow: hidden; visibility: hidden; width: 1px; height: 0;'));
        $tooltip = 'Title::The author\'s formal title. For example:
 &lt;ul&gt;
 &lt;li&gt;Professor&lt;/li&gt;
 &lt;li&gt;PostDoc&lt;/li&gt;
 &lt;li&gt;PhD Student&lt;/li&gt;
 &lt;li&gt;MSc Student&lt;/li&gt;
 &lt;li&gt;Colleague&lt;/li&gt;
 &lt;/ul&gt;';
        $form->addElement('text', 'title', "<span class=\"Tips1\" title=\"{$tooltip}\">Title:</span>", array('size' => 50, 'maxlength' => 250));
        $form->addElement('text', 'email', 'email:', array('size' => 50, 'maxlength' => 250));
        $form->addRule('email', 'invalid email address', 'email', null, 'client');
        $form->addElement('text', 'organization', 'Organization:', array('size' => 50, 'maxlength' => 250));
        $form->addElement('text', 'webpage', 'Webpage:', array('size' => 50, 'maxlength' => 250));
        $ref = '<br/><div class="small"><a href="javascript:dataKeep(' . ($this->numNewInterests + 1) . ')">[Add Interest]</a></div>';
        $ams = $form->addElement('advmultiselect', 'interests', null, $this->all_interests, array('size' => 15, 'class' => 'pool', 'style' => 'width:200px;'));
        $ams->setLabel(array('Interests:' . $ref, 'Available', 'Selected'));
        $ams->setButtonAttributes('add', array('value' => 'Add >>', 'class' => 'inputCommand'));
        $ams->setButtonAttributes('remove', array('value' => '<< Remove', 'class' => 'inputCommand'));
        $template = <<<TEMPLATE_END
{javascript}
<table{class}>
  <thead>
    <tr>
      <!-- BEGIN label_2 --><tr><th align="center">{label_2}</th><!-- END label_2 -->
      <!-- BEGIN label_3 --><th align="center">{label_3}</th><!-- END label_3 -->
    <tr>
  </thead>
<tr>
  <td>{unselected}</td>
  <td>{selected}</td>
</tr>
<tr>
  <td>{add}</td>
  <td>{remove}</td>
</tr>
</table>
TEMPLATE_END;
        $ams->setElementTemplate($template);
        if (isset($_SESSION['state']) && $_SESSION['state'] == 'pub_add') {
            $form->addElement('static', null, null, '<span class="small">When done adding new authors press the "Next Step" button</span>');
        }
        for ($i = 0; $i < $this->numNewInterests; $i++) {
            $form->addElement('text', 'newInterests[' . $i . ']', 'Interest Name ' . ($i + 1) . ':', array('size' => 50, 'maxlength' => 250));
        }
        if (isset($_SESSION['state']) && $_SESSION['state'] == 'pub_add') {
            $pos = strpos($_SERVER['PHP_SELF'], 'papersdb');
            $next_page = substr($_SERVER['PHP_SELF'], 0, $pos) . 'papersdb/Admin/add_pub2.php';
            $url = substr($_SERVER['PHP_SELF'], 0, $pos) . 'papersdb';
            $buttons[] = HTML_QuickForm::createElement('button', 'prev_step', '<< Previous Step', array('onClick' => "location.href='" . $next_page . "';"));
            $buttons[] = HTML_QuickForm::createElement('button', 'cancel', 'Cancel', array('onclick' => "cancelConfirm();"));
            $buttons[] = HTML_QuickForm::createElement('reset', 'reset', 'Reset');
            $buttons[] = HTML_QuickForm::createElement('submit', 'add_another', 'Submit and Add Another Author');
            $buttons[] = HTML_QuickForm::createElement('submit', 'next_step', 'Next Step >>');
            if ($pub->pub_id != '') {
                $buttons[] = HTML_QuickForm::createElement('submit', 'finish', 'Finish');
            }
            $form->addGroup($buttons, 'buttons', '', '&nbsp', false);
            add_pub_base::addPubDisableMenuItems();
        } else {
            $form->addRule('firstname', 'a first name is required', 'required', null, 'client');
            $form->addRule('lastname', 'a last name is required', 'required', null, 'client');
            if ($this->author_id == null) {
                $button_label = 'Add Author';
            } else {
                $button_label = 'Submit';
            }
            $form->addGroup(array(HTML_QuickForm::createElement('reset', 'reset', 'Reset'), HTML_QuickForm::createElement('submit', 'submit', $button_label)), null, null, '&nbsp;');
        }
        $form->addElement('hidden', 'numNewInterests', $this->numNewInterests);
        $this->form =& $form;
        if ($form->validate()) {
            $this->processForm();
        } else {
            $this->renderForm($author);
        }
    }
 /**
  * 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;
 }
예제 #18
0
$form->addElement('hidden', 'params', $form_params);
include 'action/persona_form.php';
$form->addElement('submit', 'btnSubmit', 'Confirmar borrado');
// defaults del form
$db = DB::connect($config['db']);
if (PEAR::isError($db)) {
    die($db->getMessage());
}
$edit_sql = 'select * from ' . $params['table'] . ' where ' . $params['primary_key'] . ' = ?';
$edit_sql_data = array($record_id);
$edit_row = $db->getRow($edit_sql, $edit_sql_data, DB_FETCHMODE_ASSOC);
foreach ($edit_row as $key => $value) {
    $defaults['new_row[' . $key . ']'] = stripslashes($value);
}
$form->setDefaults($defaults);
if (isset($_REQUEST['btnSubmit']) and $_REQUEST['btnSubmit'] == 'Confirmar borrado' and $form->validate()) {
    $new_row = cleanup_new_row($_POST['new_row']);
    $res = $db->query("delete from {$params['table']} where {$params['primary_key']} = ?", array($record_id));
    if (PEAR::isError($res)) {
        die($res->getMessage());
    }
    $params_cont['msg'] = "El registro a sido borrado satisfactoriamente.";
    $params_cont = params_encode($params_cont);
    $continue = 'action=' . $params['continue'] . '&params=' . $params_cont;
} else {
    // <UI>
    include_once 'header.php';
    if (isset($params['msg'])) {
        echo $params['msg'];
    }
    echo '<br>';
예제 #19
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";
 }
예제 #20
0
    $phone = str_replace(')', '', $phone);
    $phone = str_replace('-', '', $phone);
    $phone = str_replace('.', '', $phone);
    return $phone;
}
require_once 'HTML/QuickForm.php';
$uploadForm = new HTML_QuickForm('upload_form', 'post');
$uploadForm->setRequiredNote('<span style="color:#ff0000;">*</span> = campos requeridos.');
$uploadForm->addElement('header', 'MyHeader', 'Importar alumnos desde una planilla');
$uploadForm->addElement('hidden', 'action', 'alumno_import');
$file =& $uploadForm->addElement('file', 'filename', 'Archivo:');
$uploadForm->setMaxFileSize(5120000);
$uploadForm->addRule('filename', 'Debe seleccionar un archivo', 'uploadedfile');
$uploadForm->addElement('submit', 'btnUpload', 'Cargar Base');
$field_names_ok = array('legajo', 'nombre', 'doc_nro', 'email', 'telefono', 'orientacion', 'notas');
if ($uploadForm->validate()) {
    unset($params);
    $params['time0'] = time();
    $uploaded_file = $_FILES['filename']['tmp_name'];
    $handle = fopen($uploaded_file, 'r');
    if (!$handle) {
        die('Error al abrir el archivo ' . $uploaded_file);
    }
    // get field names in the first line
    $field_names = fgetcsv($handle, 4096, chr(9));
    // check field names
    $field_diff = array_diff($field_names_ok, $field_names);
    if (count($field_diff) > 0) {
        echo 'Los nombres de los campos en el archivo subido estan mal.<br>';
        print_r($field_diff);
        exit;
예제 #21
0
파일: modules.php 프로젝트: bqq1986/efront
$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'])) {
예제 #22
0
파일: backup.php 프로젝트: bqq1986/efront
}
$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());
 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());
 }
예제 #24
0
    public function execute() {

       	$request = $this->getContext()->getRequest();

    	$postLoginUser = $request->getParameter('user');
    	$postLoginId = $postLoginUser['id'];

    	$id = $request->getParameter('id');

		$login = $this->getContext()->getUser()->getAttribute('Login');
    	$loginRole = $this->getLoginRole();

    	if ($loginRole == 'editor'){
    		if ($id != $login->id && $postLoginId != $login->id){

				$this->log("Unauthorized attempt edit login record. Login id: $id, user name: ". $login->name);
    					
    			$this->getContext()->getController()->forward('Default', "Secure");	
    		}
    	}

//    	$this->checkAdminAuth();

		if($request->getParameter('cancel')) {

			if ($loginRole == 'admin'){
				$this->getContext()->getController()->forward('Default', "ListLogin");
			} else {
				header("Location:Search?searchFor=Member");
			}

			return View::NONE;
		}
        
    	$form = new HTML_QuickForm("loginForm", 'post');

    	$loginDao = new BaseDao("Login");

		$affDao = new BaseDao("Affiliate"); 

    	if ($id){
    		$user = $loginDao->get($id);	

			$this->log("Editing login: "******" ,name: ".$user->name);
			$this->log("Editing login: "******" ,name: ".$user->name, true);

    		$affiliate = $affDao->getPattern();
    		$affiliate->editor = $user->id;
			$currentAffs = $affDao->search($affiliate);
			$affIds = $this->getListOfCertainFieldValues($currentAffs, 'id');

    		$form->setDefaults(array('user' => (array) $user, 
    								 "password2" => $user->password,
    								 "affiliates" => $affIds));
    	} else{
			$this->log("Creating new login.", true);

	    	$user = $loginDao->getPattern();
    	}

		$request->setAttribute('user', $user);

		$roleDao = new BaseDao("Role"); 
		$roles = $this->prepareDropdown($roleDao->search(), 'id', 'name');

		$affs = $this->prepareDropdown($affDao->searchWhereWithOrder($affDao->getPattern(), "1=1", 'name'), 'id', 'name');

		$form->addElement("text", "user[name]", "Name:", array('size' => 50, "maxlength" => 255));
		$form->addElement("text", "user[login]", "Login:"******"maxlength" => 255));
		$form->addElement("password", "user[password]", "Password:"******"maxlength" => 255));
		$form->addElement("password", "password2", "Repeat Password:"******"maxlength" => 255));
		$form->addElement('text', "user[email]", 'Email:', array('size' => 50, "maxlength" => 255));
		$form->addElement('select', "user[roleFid]", "User Role:", $roles);
		$form->addElement('select', "affiliates", "Affiliate:", $affs, array('multiple' => 'multiple', 'id' => "affDropdown") );
		$form->addElement('checkbox', "user[nationalOfficer]", "National Officer:", "", array());

		$element =& $form->getElement("affiliates");
		$element->setSize(5);
		if ($loginRole != 'admin') $element->freeze();

		$form->addElement('hidden', 'user[id]');
		$form->addElement("submit", null, "Save Changes");
		$form->addElement("submit", 'cancel', "Cancel");

		$form->addRule("user[name]", "Please enter your name.", 'required', null);
		$form->addRule("user[login]", "Login can't be blank.", 'required', null);
		$form->addRule("user[password]", "You haven't entered password.", 'required', null);
		$form->addRule("user[email]", "Please enter your email.", 'required', null);
		$form->addRule("user[email]", "Please enter valid email.", 'email', null);

		$form->addFormRule(array(&$this, "validatePassword"));
		$form->addFormRule(array(&$this, "checkEmail"));
		$form->addFormRule(array(&$this, "max5admins"));



		if (!$form->validate()) {

			$request->setAttribute("editLoginForm", $form->toHtml());

			return 'Form';
		}
		else{	
			$reqUser = $request->getParameter('user');

			$user->id = $reqUser['id'];
			$user->login = $reqUser['login'];
			$user->password = $reqUser['password'];
			$user->email = $reqUser['email'];
			$user->roleFid = $reqUser['roleFid'];
			$user->name = $reqUser['name'];

			if ($reqUser["nationalOfficer"]){
				$this->log("Assigng new national Officer: ".$user->login." ,name: ".$user->name, true);

				$user->nationalOfficer = 1;		
				$db = new PearDBStorage();
				$db->invoke("update logins set nationalOfficer=0 where nationalOfficer=1");
			}

			$loginDao->save($user);

			$affiliates = $reqUser = $request->getParameter("affiliates");
			$affText = "";
			if ($affiliates){
				foreach($affiliates as $affId){
					$affiliate = $affDao->get($affId);
					$affiliate->editor = $user->id;
					$affDao->save($affiliate);

					$affText .= $affiliate->name." ";
				}
			}

			if (!$user->id){

				$emailMessage = "Dear ".$user->name.":\n\n
				You have been assigned the role of Editor in the American Council of the Blind membership database for ".$affText.".\n
				Your User ID is ".$user->login." and your default password is ".$user->password.".  Please change this password immediately when you log into the database.\n\n
				Thank you for your work both in your affiliate and with the ACB management of the most precious resource we have:  Our members.\n\n
				Sincerely,\n\n
				The Database Management Team";

				mail($user->email, "ACB mail", $emailMessage);
			}

			if ($loginRole == 'admin'){
				$this->log("Saving login: "******" ,name: ".$user->name, true);

				$this->getContext()->getController()->forward('Default', "ListLogin");
			} else {
				$this->log("Saving login: "******" ,name: ".$user->name);

				header("Location:Search?searchFor=Member");
			}

			return View::NONE;
		}
    }
예제 #25
0
 $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';
예제 #26
0
$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) {
예제 #27
0
파일: installer.php 프로젝트: promoso/HVAC
 function db2app()
 {
     require_once 'HTML/QuickForm.php';
     $form = new HTML_QuickForm('db2app');
     $res = mysql_list_dbs(db());
     if (!$res) {
         trigger_error(mysql_error(db()), E_USER_ERROR);
     }
     $options = array('' => 'Please Select Database ...');
     while ($row = mysql_fetch_row($res)) {
         $options[$row[0]] = $row[0];
     }
     $form->addElement('hidden', '-action', 'db2app');
     $form->addElement('select', 'database_name', 'Select Database' . $this->infoLink('archive2app.database_name'), $options, array('onchange' => 'listeners.database_name.onchange(this)'));
     $form->addElement('header', 'db_info', 'Database connection details');
     //$form->addElement('html', 'this is a test');
     $form->addElement('text', 'mysql_user', 'MySQL Username ' . $this->infoLink('archive2app.mysql_user'));
     $form->addElement('password', 'mysql_password', 'MySQL Password');
     //$form->addElement('radio','output_format','Output options','Download as tar.gz archive','download');
     //$form->addElement('radio','output_format','','Install on webserver in apps directory','install');
     $form->addElement('select', 'install_type', 'Installation type ' . $this->infoLink('archive2app.install_type'), array('' => 'Please select ...', 'download_tarball' => 'Download Tarball', 'ftp_install' => 'Install on server (using FTP)'), array('onchange' => "listeners.install_type.onchange(this);"));
     $form->addElement('header', 'ftp_info', 'FTP Connection Info');
     $form->addElement('text', 'ftp_host', 'FTP Host');
     $form->addElement('checkbox', 'ftp_ssl', 'Use SSL');
     $form->setDefaults(array('ftp_host' => DB_HOST));
     $form->addElement('text', 'ftp_path', 'FTP Path', array('size' => 50));
     $form->setDefaults(array('ftp_path' => $_SERVER['DOCUMENT_ROOT']));
     $form->addElement('text', 'ftp_username', 'FTP Username');
     $form->addElement('password', 'ftp_password', 'FTP Password');
     $form->addElement('submit', 'submit', 'Submit');
     $form->addRule('database_name', 'Please select a database', 'required', null, 'client');
     $form->addRule('mysql_user', 'Please enter a mysql username that the application can connect as.', 'required', null, 'client');
     $form->addRule('install_type', 'Please select an installation type and then click submit.', 'required', null, 'client');
     $form->setDefaults(array('mysql_user' => $_SERVER['PHP_AUTH_USER'], 'mysql_password' => $_SERVER['PHP_AUTH_PW']));
     if ($form->validate()) {
         $tarpath = $form->process(array(&$this, 'db2app__process'), true);
         header('Content-type: application/x-gzip');
         header('Content-Disposition: attachment; filename="' . basename($tarpath) . '.tar.gz"');
         echo file_get_contents($tarpath);
         exit;
     }
     require_once 'HTML/QuickForm/Renderer/Array.php';
     $renderer = new HTML_QuickForm_Renderer_Array(true, true, true);
     $form->accept($renderer);
     $context = $renderer->toArray();
     //print_r($context);
     ob_start();
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     include 'install' . DIRECTORY_SEPARATOR . 'db2app.inc.php';
 }
예제 #28
0
require_once 'HTML/QuickForm.php';
include 'share/form_common.php';
$form = new HTML_QuickForm('form', 'get');
$form->addElement('hidden', 'action', 'noticia_search');
$form->addElement('text', 'new_row[titulo]', ' Título:', $campo_largo);
$form->addElement('submit', 'btnSubmit', 'Buscar');
include_once 'header.php';
echo '<h2>Buscar noticias</h2>';
$form->display();
$link_url = 'index.php?action=noticia_insert';
$link_label = 'Ingresar noticia nueva';
echo '<br>';
echo "<a href=\"{$link_url}\">{$link_label}</a>";
echo '<br>';
echo '<br>';
if (isset($_REQUEST['btnSubmit']) and $_REQUEST['btnSubmit'] == 'Buscar' and $form->validate()) {
    $sql_where = '';
    $sql_data = array();
    $new_row = $_GET['new_row'];
    if ($new_row['titulo'] != '') {
        $sql_where .= ' and titulo ilike ? ';
        $sql_data[] = '%' . $new_row['titulo'] . '%';
    }
    $sql = $sql_list . ' where 1 = 1 ' . $sql_where . ' order by fecha_registro desc';
    //    var_dump($sql);
    //    var_dump($sql_data);
    $db = new PDO($config['db']['dsn']);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $st = $db->prepare($sql);
    $st->execute($sql_data);
    unset($params);
예제 #29
0
 $opts[0] = 'Select One';
 $tax_rates = $ushop->getTaxRates(true);
 foreach ($tax_rates as $rate) {
     $opts[$rate->tax_rate_id] = ucwords($rate->tax_rate);
 }
 $form->addElement('html', '<fieldset>');
 $form->addElement('header', 'edit_tax_code', 'Edit Tax Code');
 $form->addElement('text', 'tax_code', 'Tax Code:', array('size' => 2, 'maxlength' => 2, 'class' => 'inputbox'));
 $s->loadArray($opts);
 $form->addElement($s);
 $form->addElement('text', 'description', 'Description:', array('size' => 20, 'maxlength' => 20, 'class' => 'inputbox'));
 $form->addElement('html', '</fieldset>');
 $form->addRule('description', 'Please enter a decription', 'required');
 $form->addRule('tax_code', 'Please enter a tax code', 'required');
 $form->addRule('tax_code', 'Tax codes have only letters', 'lettersonly');
 if ($form->validate()) {
     $form->freeze();
     $values = $form->process(array(&$this, 'formValues'), false);
     $menuBar['back'] = '/ushop/tax/overview';
     $values['tax_code'] = strtoupper($values['tax_code']);
     //check then enter the record.
     $res = $this->update($values, $ushop->db_name . 'tax_codes', array('where' => 'tax_code_id=' . $this->registry->params['id']));
     if ($res) {
         $params['TYPE'] = 'pass';
         $params['MESSAGE'] = '<h2>Tax code was successfully edited.</h2>';
     } else {
         $params['TYPE'] = 'error';
         $params['MESSAGE'] = '<h2>Tax code could not be edited due to an error.</h2>';
     }
     // done!
 } else {
예제 #30
0
function admin_display($task)
{
    global $db, $cfg;
    if ($task == NULL) {
        $task = 'contests';
    }
    switch ($task) {
        case 'users':
            $table = new HTML_Table();
            $res =& db_query('users_list');
            $res->fetchInto($row);
            // add users table headers
            $headers = array_keys($row);
            array_push($headers, 'groups');
            array_push($headers, 'actions');
            $table->addRow($headers, null, 'TH');
            // add user records
            while ($row) {
                $res2 =& db_query('groups_by_user_id', $row['user_id']);
                // get list of gourps for this user
                $groups = '';
                $res2->fetchInto($row2);
                while ($row2) {
                    $groups .= $row2['name'];
                    if ($res2->fetchInto($row2)) {
                        $groups .= ', ';
                    }
                }
                $res2->free();
                array_push($row, $groups);
                // actions
                array_push($row, "<a href=\"index.php?view=admin&amp;task=edit_user&amp;id={$row['user_id']}\">edit</a>" . ", <a href=\"index.php?view=admin&amp;task=del_user&amp;id={$row['user_id']}\">delete</a>");
                $table->addRow(array_values($row));
                $res->fetchInto($row);
            }
            $res->free();
            $table->altRowAttributes(1, null, array("class" => "altrow"));
            echo '<div class="overflow">' . $table->toHtml() . '</div>';
            break;
        case 'del_user':
            db_query('del_user_by_id', $_GET['id']);
            db_query('del_user_perms_by_id', $_GET['id']);
            redirect('index.php?view=admin&task=users');
            break;
        case 'edit_user':
            // user id to edit given as arg
            $res =& db_query('groups_by_user_id', $_GET['id']);
            // get list of all groups for this user
            $user_groups = array();
            while ($res->fetchInto($row)) {
                array_push($user_groups, $row['group_id']);
            }
            $res->free();
            // get hanndle of user
            $res =& db_query('user_by_id', $_GET['id']);
            $res->fetchInto($row);
            $handle = $row['handle'];
            $res->free();
            $form = new HTML_QuickForm('userForm', 'post', 'index.php?view=admin&task=edit_user&id=' . $_GET['id']);
            $form->addElement('header', null, 'Groups for user ' . $handle . ' (id: ' . $_GET['id'] . ')');
            // get list of all available groups
            $res =& db_query('groups_list');
            // add checkbox for each group
            $groups = array();
            while ($res->fetchInto($row)) {
                $elem =& $form->addElement('checkbox', $row['group_id'], $row['name']);
                if (in_array($row['group_id'], $user_groups)) {
                    $elem->setChecked(true);
                }
                $groups[$row['group_id']] = $row['name'];
            }
            $res->free();
            $form->addElement('submit', 'submit', 'Apply Changes');
            if ($form->validate()) {
                $data = $form->getSubmitValues();
                foreach ($groups as $gid => $name) {
                    $elem =& $form->getElement($gid);
                    if ($data[$gid] == 1) {
                        auth_set_perm($_GET['id'], $gid);
                        $elem->setChecked(true);
                    } else {
                        auth_clear_perm($_GET['id'], $gid);
                        $elem->setChecked(false);
                    }
                }
            }
            $form->display();
            break;
        case 'groups':
            $table = new HTML_Table();
            $res =& db_query('groups_list');
            $res->fetchInto($row);
            // add groups table header
            $headers = array_keys($row);
            array_push($headers, 'views');
            array_push($headers, 'actions');
            $table->addRow($headers, null, 'TH');
            // add group records
            while ($row) {
                $res2 =& db_query('views_by_group_id', $row['group_id']);
                // get list of views allowed for this group
                $views = '';
                $res2->fetchInto($row2);
                while ($row2) {
                    $views .= $row2['view'];
                    if ($res2->fetchInto($row2)) {
                        $views .= ', ';
                    }
                }
                $res2->free();
                array_push($row, $views);
                array_push($row, "<a href=\"index.php?view=admin&amp;task=edit_group&amp;id={$row['group_id']}\">edit</a>" . ", <a href=\"index.php?view=admin&amp;task=del_group&amp;id={$row['group_id']}\">delete</a>");
                $table->addRow(array_values($row));
                $res->fetchInto($row);
            }
            $res->free();
            // decor
            $table->altRowAttributes(1, null, array("class" => "altrow"));
            echo '<div class="overflow">' . $table->toHtml() . '</div>';
            echo "<hr />";
            // form for adding a group
            $form = new HTML_QuickForm('addGroupForm', 'post', 'index.php?view=admin&task=groups');
            $form->addElement('header', null, 'Add a group');
            $form->addElement('text', 'name', 'Name: ');
            $form->addElement('submit', null, 'Submit');
            $form->applyFilter('name', 'trim');
            $form->addRule('name', 'Group name is required.', 'required', null, 'client');
            if ($form->validate()) {
                $res =& $db->autoExecute('groups', $form->getSubmitValues(), DB_AUTOQUERY_INSERT);
                if (PEAR::isError($res)) {
                    error($db->toString());
                }
                redirect('index.php?view=admin&task=groups');
            }
            $form->display();
            break;
        case 'del_group':
            db_query('del_group_by_id', $_GET['id']);
            redirect('index.php?view=admin&task=groups');
            break;
        case 'edit_group':
            // get list of views allowed for this group
            $group_views = array();
            $res =& db_query('views_by_group_id', $_GET['id']);
            while ($res->fetchInto($row)) {
                array_push($group_views, $row['view']);
            }
            $res->free();
            // get name of group
            $res =& db_query('group_by_id', $_GET['id']);
            $res->fetchInto($row);
            $name = $row['name'];
            $res->free();
            $form = new HTML_QuickForm('groupForm', 'post', 'index.php?view=admin&task=edit_group&id=' . $_GET['id']);
            $form->addElement('header', null, 'Views for group ' . $name . ' (id: ' . $_GET['id'] . ')');
            // get list of all available views
            $view_paths = glob($cfg['dir']['views'] . '/*.php');
            $views = array();
            // create the checkboxes, add each view to $views for later checking
            foreach ($view_paths as $path) {
                $tmp = explode('.', basename($path));
                $elem =& $form->addElement('checkbox', $tmp[0], $tmp[0]);
                if (in_array($tmp[0], $group_views)) {
                    $elem->setChecked(true);
                }
                array_push($views, $tmp[0]);
            }
            $form->addElement('submit', 'submit', 'Apply Changes');
            if ($form->validate()) {
                $data = $form->getSubmitValues();
                foreach ($views as $view) {
                    $elem =& $form->getElement($view);
                    if ($data[$view] == 1) {
                        auth_set_view($_GET['id'], $view);
                        $elem->setChecked(true);
                    } else {
                        auth_clear_view($_GET['id'], $view);
                        $elem->setChecked(false);
                    }
                }
            }
            $form->display();
            break;
        case 'views':
            $table = new HTML_Table();
            $table->addRow(array('name', 'path'), null, 'TH');
            // display list of views
            $view_paths = glob($cfg['dir']['views'] . '/*.php');
            foreach ($view_paths as $path) {
                $tmp = explode('.', basename($path));
                $table->addRow(array($tmp[0], $path));
            }
            $table->altRowAttributes(1, null, array("class" => "altrow"));
            echo '<div class="overflow">' . $table->toHtml() . '</div>';
            ?>
<p>To add a view, just drop a .php view-module file inside the views directory.
You can remove a view by deleting or renaming the corresponding file
inside the views directory.
</p> 
		<?php 
            break;
        case 'contests':
            $table = new HTML_Table();
            $res =& db_query('contests_list');
            $res->fetchInto($row);
            if ($row) {
                // add contests table headers
                $headers = array_keys($row);
                array_push($headers, 'actions');
                $table->addRow($headers, null, 'TH');
                // add contests table records
                while ($row) {
                    // Get the handle of the manager for displaying
                    $manager_name = '[none]';
                    $res2 =& $db->query($cfg['sql']['user_by_id'], $row['manager']);
                    if (!PEAR::isError($res2)) {
                        $res2->fetchInto($row2);
                        $manager_name = $row2['handle'];
                        $res2->free();
                    }
                    $row['manager'] = $manager_name;
                    // add edit,delete actions
                    $row['actions'] = "<a href=\"index.php?view=admin&amp;task=edit_contest&amp;id={$row['contest_id']}\">edit</a>, " . "<a href=\"index.php?view=admin&amp;task=del_contest&amp;id={$row['contest_id']}\">delete</a>";
                    $table->addRow(array_values($row));
                    $res->fetchInto($row);
                }
                $res->free();
                // decoration
                $table->altRowAttributes(1, null, array("class" => "altrow"));
                echo '<div class="overflow">' . $table->toHtml() . '</div>';
            } else {
                ?>
<p>No contests added yet.</p>			
			<?php 
            }
            echo "<hr />";
            // get list of all available managers
            $res =& db_query('users_by_group_name', 'Managers');
            while ($res->fetchInto($row)) {
                $managers[$row['user_id']] = $row['handle'];
            }
            // form for adding a contest
            $form = new HTML_QuickForm('contestAddForm', 'post', selflink());
            $form->addElement('header', null, 'Add a contest');
            $form->addElement('text', 'name', 'Name:');
            $form->addElement('text', 'description', 'Description:');
            $elem =& $form->addElement('text', 'team_size', 'Size of team:');
            $form->addElement('select', 'division', 'Division:', $cfg['tcl']['divisions']);
            $elem->setValue('1');
            $date = getdate();
            $form->addElement('date', 'show_time', 'Activation time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('date', 'begin_time', 'Begin time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('date', 'end_time', 'End time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('select', 'manager', 'Contest manager:', $managers);
            $form->addElement('submit', null, 'Submit');
            $form->applyFilter('name', 'trim');
            $form->applyFilter('description', 'trim');
            $form->applyFilter('team_size', 'trim');
            $form->addRule('name', 'Contest name is required.', 'required', null, 'client');
            $form->addRule('manager', 'Contest manager is required.', 'required', null, 'client');
            $form->addRule('team_size', 'Team size is required.', 'required', null, 'client');
            // validate or display form
            if ($form->validate()) {
                $data = $form->getSubmitValues();
                $data['show_time'] = form2sql_datetime($data['show_time']);
                $data['begin_time'] = form2sql_datetime($data['begin_time']);
                $data['end_time'] = form2sql_datetime($data['end_time']);
                $db->autoExecute('contests', $data, DB_AUTOQUERY_INSERT);
                if (PEAR::isError($res)) {
                    error($db->toString());
                }
                redirect('index.php?view=admin&task=contests');
            } else {
                $form->display();
            }
            break;
        case 'del_contest':
            $res =& db_query('del_contest_by_id', $_GET['id']);
            redirect('index.php?view=admin&task=contests');
            break;
        case 'edit_contest':
            // contest to edit given as arg
            $res =& db_query('contest_by_id', $_GET['id']);
            $res->fetchInto($row);
            $res->free();
            // get list of all available managers
            $res =& db_query('users_by_group_name', 'Managers');
            while ($res->fetchInto($row2)) {
                $managers[$row2['user_id']] = $row2['handle'];
            }
            // form for editing the contest
            $form = new HTML_QuickForm('contestEditForm', 'post', selflink());
            $form->addElement('header', null, "Edit contest {$row['name']} (id: {$row['contest_id']})");
            $form->addElement('text', 'name', 'Name:');
            $form->addElement('text', 'description', 'Description:');
            $elem =& $form->addElement('text', 'team_size', 'Size of team:');
            $elem->setValue('1');
            $form->addElement('select', 'division', 'Division:', $cfg['tcl']['divisions']);
            $date = getdate();
            $form->addElement('date', 'show_time', 'Activation time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('date', 'begin_time', 'Begin time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('date', 'end_time', 'End time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5));
            $form->addElement('select', 'manager', 'Contest manager:', $managers);
            $form->addElement('text', 'rules', 'Rules URL:');
            $form->addElement('submit', null, 'Submit');
            // convert date format and dtore default values
            $row['show_time'] = sql2form_datetime($row['show_time']);
            $row['begin_time'] = sql2form_datetime($row['begin_time']);
            $row['end_time'] = sql2form_datetime($row['end_time']);
            $form->setDefaults($row);
            $form->applyFilter('name', 'trim');
            $form->applyFilter('description', 'trim');
            $form->applyFilter('team_size', 'trim');
            $form->addRule('name', 'Contest name is required.', 'required', null, 'client');
            $form->addRule('manager', 'Contest manager is required.', 'required', null, 'client');
            $form->addRule('team_size', 'Team size is required.', 'required', null, 'client');
            // validate or display form
            if ($form->validate()) {
                $data = $form->getSubmitValues();
                $data['show_time'] = form2sql_datetime($data['show_time']);
                $data['begin_time'] = form2sql_datetime($data['begin_time']);
                $data['end_time'] = form2sql_datetime($data['end_time']);
                $db->autoExecute('contests', $data, DB_AUTOQUERY_UPDATE, 'contest_id=' . $_GET['id']);
                if (PEAR::isError($res)) {
                    error($db->toString());
                }
                redirect('index.php?view=admin&task=contests');
            } else {
                $form->display();
            }
            break;
        case 'shell':
            $form = new HTML_QuickForm('shellForm', 'post', selflink());
            $field =& $form->addElement('text', 'command', 'Command:');
            $field->setSize(100);
            $ifield =& $form->addElement('textarea', 'input', 'Standard Input:');
            $ifield->setRows(10);
            $ifield->SetCols(80);
            $form->addElement('submit', null, 'Submit');
            $form->display();
            if ($form->validate()) {
                // Write std input file
                $iname = tempnam("/tmp", "in");
                $ifile = fopen($iname, 'w');
                fwrite($ifile, $form->getSubmitValue('input'));
                fclose($ifile);
                $cmd = $form->getSubmitValue('command');
                echo "<pre class=\"shell_output\">";
                echo "<b>\$ " . html_escape($cmd) . "</b>\n";
                exec("{$cmd} 2>&1 < {$iname}", $out, $ret);
                foreach ($out as $line) {
                    echo html_escape($line) . "\n";
                }
                echo "</pre>\n";
                echo "<p>Command returned: {$ret}</p>\n";
            }
            break;
        case 'uploader':
            // Get list of directories to which files can be uploaded
            $dirs = subdir_list('.');
            array_unshift($dirs, './');
            $form = new HTML_QuickForm('uploaderForm', 'post', selflink());
            $form->addElement('header', null, 'Upload a File:');
            $file =& $form->addElement('file', 'file', 'File:');
            $form->addElement('select', 'dir', 'Destination:', $dirs);
            $form->addElement('submit', 'upload', 'Upload');
            $form->addRule('file', 'Please select file to upload.', 'required', null, 'client');
            $form->setMaxFileSize(10485760);
            // try 10 MB max file size
            if ($form->validate()) {
                if ($file->isUploadedFile()) {
                    $dir = $dirs[$form->getSubmitValue('dir')];
                    if ($file->moveUploadedFile($dir)) {
                        echo "<p>File uploaded successfully to {$dir}.</p>";
                    } else {
                        echo "<p>Failed to save uploaded file to {$dir} (insufficient permissions?).</p>";
                    }
                } else {
                    echo "<p>File upload did not finish successfully</p>";
                }
            }
            $form->display();
            echo "<p><b>Note:</b> Any previous file with the same name will be replaced.</p>";
            echo "<hr />";
            $form = new HTML_QuickForm('mkdirForm', 'post', selflink());
            $form->addElement('header', null, 'Create a Directory:');
            $form->addElement('text', 'name', 'Name:');
            $form->addElement('select', 'dir', 'Destination:', $dirs);
            $form->addElement('submit', 'mkdir', 'Mkdir');
            $form->addRule('name', 'Please enter directory name.', 'required', null, 'client');
            if ($form->validate()) {
                $path = $dirs[$form->getSubmitValue('dir')] . '/' . $form->getSubmitValue('name');
                if (file_exists($path)) {
                    echo "<p><b>Warning:</b> File or directory {$path} already exists.</p>";
                } else {
                    if (mkdir($path)) {
                        echo "<p>Directory {$path} created.</p>";
                    } else {
                        echo "<p>Failed to create directory {$path}. Make sure parent directory permissions allow it.</p>";
                    }
                }
            }
            $form->display();
            break;
        case 'phpinfo':
            phpinfo();
            break;
    }
}