private function getForm(EditedCssFile $css) { $form = new Form($this->getValidator('cssFile', $this->request)); $form->setData($css->toArray()); $form->set('code', ''); $form->set('fileName', $css->getFileName()); $form->set('file', $css->getTheme()); return $form; }
/** */ public function testFormOptions() { $this->object->set('test', 'existing'); $this->assertFalse($this->object->get('nonExisting')); $this->assertEquals('existing', $this->object->get('test')); $this->assertEquals('default', $this->object->get('nonExists', 'default')); $this->assertTrue(is_array($this->object->getAll())); $this->assertEquals(1, count($this->object->getAll())); $this->object->setAll(array('test' => 'merged', 'second' => 'test')); $this->assertEquals(2, count($this->object->getAll())); $this->assertEquals('merged', $this->object->get('test')); }
public function index() { $view = $this->getView(); $request = $this->getPageRequest(); if (!\Core\user()->checkAccess('g:admin')) { return View::ERROR_ACCESSDENIED; } if ($request->isPost()) { // Update/save the site id. ConfigHandler::Set('/livefyre/siteid', $_POST['siteid']); \Core\set_message('Set Site ID Successfully!', 'success'); \Core\reload(); } // Pull the configuration options to see if livefyre is currently setup. $siteid = ConfigHandler::Get('/livefyre/siteid'); // Generate the form to either set or update the siteid. $form = new Form(); $form->set('method', 'POST'); $form->addElement('text', ['name' => 'siteid', 'title' => 'Site ID', 'value' => $siteid]); $view->assign('siteid', $siteid); $view->assign('url', ROOT_URL_NOSSL); $view->assign('form', $form); // Setup instructions: // http://www.livefyre.com/install/ }
/** * Widget to quickly create a new Content page as a draft. */ public function quickdraft() { $view = $this->getView(); if (!\Core\user()->checkAccess('p:/content/manage_all')) { // Users who do not have access to manage page content do not get this. return ''; } $form = new Form(); $form->set('orientation', 'vertical'); $form->set('callsmethod', 'ContentAdminWidget::QuickDraftSave'); $form->addElement('text', ['name' => 'title', 'placeholder' => 'Page or Post Title']); $form->addElement('textarea', ['name' => 'content', 'placeholder' => "What's up?", 'cols' => 50]); $form->addElement('submit', ['value' => 'Save Draft']); // Load in all the pages on the site that are currently set as draft too, why not? ;) $drafts = PageModel::Find(['published_status = draft'], 10, 'updated DESC'); $view->assign('form', $form); $view->assign('drafts', $drafts); }
function render($page = false) { global $DB, $Controller; if (!$page && isset($this)) { $page = $this; } elseif (!is_object($page)) { $page = $Controller->retrieve($page); } $r = $DB->formfields->get(array('id' => $page->ID, 'language' => $page->loadedLanguage), '*', false, 'sort'); if (!Database::numRows($r)) { return ''; } $uForm = new Form('uform'); $form = array(); while (false !== ($field = Database::fetchAssoc($r))) { $fieldName = 'uform[' . $field['field_id'] . ']'; switch ($field['type']) { case 'Checkbox': case 'pCheckbox': $Values = array_filter(array_map('trim', explode(',', $field['value']))); $Names = array_map('idfy', $Values); if (count($Values) > 1) { $form[] = new checkset($field['label'], $fieldName, array_combine($Names, $Values), $field['type'] == 'pCheckbox'); } else { $form[] = new Checkbox($field['label'], $fieldName, $field['type'] == 'pCheckbox'); } break; case 'select': case 'mselect': $Values = array_map('trim', explode(',', $field['value'])); $Names = array_map('idfy', $Values); $form[] = new select($field['label'], $fieldName, array_combine($Names, $Values), false, $field['type'] == 'mselect'); break; case 'Radio': $Values = array_map('trim', explode(',', $field['value'])); $Names = array_map('idfy', $Values); $form[] = new Radioset($field['label'], $fieldName, array_combine($Names, $Values)); break; case 'input': case 'textarea': case 'htmlfield': $form[] = new $field['type']($field['label'], $fieldName, $field['value']); break; } } if (empty($form)) { return ''; } return $uForm->set($form); }
public function admin() { $view = $this->getView(); $request = $this->getPageRequest(); if (!\Core\user()->checkAccess('g:admin')) { return View::ERROR_ACCESSDENIED; } $image = ConfigHandler::Get('/favicon/image'); $form = new Form(); $form->set('callsmethod', 'AdminController::_ConfigSubmit'); $form->addElement(ConfigHandler::GetConfig('/favicon/image')->getAsFormElement()); $form->addElement('submit', ['value' => t('STRING_SAVE')]); $view->title = 'Site Favicon'; $view->assign('current', $image); $view->assign('form', $form); }
public function postResetPassword($p, $z) { Form::set('Person', function ($person) { $person->password = Person::hashPassword($person->password); }); $objects = Form::save(); $person = current($objects); assert($person instanceof Person); $person->login(); $message = new GuiMessage(); $message->setFrom('*****@*****.**', 'The System'); $message->addTo($person->username); $message->setSubject("{$person->firstname}, your password has been reset"); $message->assign('person', $person); $message->send('messages/confirmPasswordReset.tpl'); BaseRedirect('install/list'); }
function run() { global $DB, $Templates; if (!$this->mayI(READ)) { errorPage(401); } $_REQUEST->setType('delsd', 'string'); $_REQUEST->setType('editsd', 'string'); $_POST->setType('sdname', 'string'); $_POST->setType('sdassoc', 'string'); if ($_POST['sdname']) { if ($_REQUEST['editsd']) { if ($DB->subdomains->update(array('subdomain' => $_POST['sdname'], 'assoc' => $_POST['sdassoc']), array('subdomain' => $_REQUEST['editsd']))) { Flash::create(__('Subdomain updated'), 'confirmation'); } else { Flash::create(__('Subdomain in use'), 'warning'); } } else { if ($DB->subdomains->insert(array('subdomain' => $_POST['sdname'], 'assoc' => $_POST['sdassoc']))) { Flash::create(__('New subdomain inserted'), 'confirmation'); } else { Flash::create(__('Subdomain in use'), 'warning'); } } } elseif ($_REQUEST['delsd'] && $this->mayI(EDIT)) { $DB->subdomains->delete(array('subdomain' => $_REQUEST['delsd'])); } $r = $DB->subdomains->get(false, false, false, 'subdomain'); $tablerows = array(); while (false !== ($subdomain = Database::fetchAssoc($r))) { $tablerows[] = new Tablerow($subdomain['subdomain'], $subdomain['assoc'], icon('small/delete', __('Delete subdomain'), url(array('delsd' => $subdomain['subdomain']), 'id')) . icon('small/pencil', __('Edit subdomain'), url(array('editsd' => $subdomain['subdomain']), 'id'))); } if ($_REQUEST['editsd']) { $sd = $DB->subdomains->getRow(array('subdomain' => $_REQUEST['editsd'])); $form = new Form('editSubdomain'); } else { $sd = false; $form = new Form('newSubdomain'); } $this->setContent('main', (!empty($tablerows) ? new Table(new Tableheader(__('Subdomain'), __('Associated with..'), __('Actions')), $tablerows) : '') . $form->set($_REQUEST['editsd'] ? new Hidden('editsd', $_REQUEST['editsd']) : null, new input(__('Subdomain'), 'sdname', @$sd['subdomain']), new input(__('Associate with'), 'sdassoc', @$sd['assoc'], false, __('ID or alias to associate with the subdomain')))); $Templates->render(); }
/** * View to set google API keys and other configuration options. */ public function configure() { $view = $this->getView(); $request = $this->getPageRequest(); $configs = ['general' => ['title' => 'General', 'configs' => ['/google/services/public_api_key']], 'analytics' => ['title' => 'Analytics', 'configs' => ['/google-analytics/accountid', '/google/tagmanager/tagid']], 'maps' => ['title' => 'Maps', 'configs' => ['/googlemaps/enterprise/privatekey', '/googlemaps/enterprise/clientname']], 'cse' => ['title' => 'Custom Search', 'configs' => ['/google/cse/key']]]; $form = new Form(); $form->set('callsmethod', 'GoogleController::ConfigureSave'); foreach ($configs as $gk => $gdat) { $group = new FormTabsGroup(['name' => $gk, 'title' => $gdat['title']]); foreach ($gdat['configs'] as $c) { /** @var ConfigModel $config */ $config = ConfigHandler::GetConfig($c); $group->addElement($config->getAsFormElement()); } $form->addElement($group); } $form->addElement('submit', ['name' => 'submit', 'value' => 'Update Settings']); $view->title = 'Google Keys and Apps '; $view->assign('form', $form); }
/** * Get the form for article creation and updating. * * @param BlogArticleModel $article * * @return Form */ public static function GetArticleForm(BlogArticleModel $article) { $page = $article->getLink('Page'); $blog = $article->getLink('Blog'); $page->set('parenturl', $blog->get('baseurl')); $form = new Form(); $form->set('callsmethod', 'BlogHelper::BlogArticleFormHandler'); $form->addModel($page, 'page'); $form->addModel($article, 'model'); if (Core::IsComponentAvailable('facebook') && Core::IsLibraryAvailable('jquery')) { // Is this article already posted? if ($article->get('fb_post_id')) { $form->addElement('select', ['disabled' => true, 'title' => 'Post to Facebook', 'options' => ['' => 'Posted!'], 'group' => 'Publish Settings']); } else { $form->addElement('select', ['class' => 'facebook-post-to-select', 'title' => 'Post to Facebook', 'name' => 'facebook_post', 'options' => ['' => '-- Please enable javascript --'], 'group' => 'Publish Settings']); } } // Lock in some elements for this blog article page. $form->getElement('page[parenturl]')->setFromArray(array('value' => $blog->get('baseurl'), 'readonly' => 'readonly')); // And remove a few other elements. $form->removeElement('model[title]'); return $form; }
public function edit() { $request = $this->getPageRequest(); $view = $this->getView(); $manager = \Core\user()->checkAccess('p:/package_repository/licenses/manager'); if (!$manager) { return View::ERROR_ACCESSDENIED; } $model = PackageRepositoryLicenseModel::Construct($request->getParameter(0)); if (!$model->exists()) { return View::ERROR_NOTFOUND; } $form = new Form(); $form->set('callsmethod', 'PackageRepositoryLicenseController::_SaveLicense'); $form->addModel($model); $form->addElement('submit', ['value' => 'Update License']); $view->title = 'Edit License'; $view->assign('form', $form); }
/** * @param \UserModel|null $user * * @return \Form */ public static function GetForm($user = null){ $form = new \Form(); if($user === null) $user = new \UserModel(); $type = ($user->exists()) ? 'edit' : 'registration'; $usermanager = \Core\user()->checkAccess('p:/user/users/manage'); $groupmanager = \Core\user()->checkAccess('p:/user/groups/manage'); $allowemailchanging = \ConfigHandler::Get('/user/email/allowchanging'); if($type == 'registration'){ $form->set('callsmethod', 'Core\\User\\Helper::RegisterHandler'); } else{ $form->set('callsmethod', 'Core\\User\\Helper::UpdateHandler'); } $form->addElement('system', ['name' => 'user', 'value' => $user]); // Because the user system may not use a traditional Model for the backend, (think LDAP), // I cannot simply do a setModel() call here. // Only enable email changes if the current user is an admin or it's new. // (Unless the admin allows it via the site config) if($type != 'registration' && ( $usermanager || $allowemailchanging)){ $form->addElement('text', array('name' => 'email', 'title' => 'Email', 'required' => true, 'value' => $user->get('email'))); } // Tack on the active option if the current user is an admin. if($usermanager){ $form->addElement( 'checkbox', array( 'name' => 'active', 'title' => 'Active', 'checked' => ($user->get('active') == 1), ) ); $form->addElement( 'checkbox', array( 'name' => 'admin', 'title' => 'System Admin', 'checked' => $user->get('admin'), 'description' => 'The system admin, (or root user), has complete control over the site and all systems.', ) ); } if($usermanager){ $elements = array_keys($user->getKeySchemas()); } elseif($type == 'registration'){ $elements = explode('|', \ConfigHandler::Get('/user/register/form_elements')); } else{ $elements = explode('|', \ConfigHandler::Get('/user/edit/form_elements')); } // If avatars are disabled globally, remove that from the list if it's set. if(!\ConfigHandler::Get('/user/enableavatar') && in_array('avatar', $elements)){ array_splice($elements, array_search('avatar', $elements), 1); } foreach($elements as $k){ if($k){ // Skip blank elements that can be caused by string|param|foo| or empty strings. $el = $user->getColumn($k)->getAsFormElement(); if($el){ $form->addElement($el); } } } // Tack on the group registration if the current user is an admin. if($groupmanager){ // Find all the groups currently on the site. $where = new DatasetWhereClause(); $where->addWhere('context = '); if(\Core::IsComponentAvailable('multisite') && \MultiSiteHelper::IsEnabled()){ $where->addWhereSub('OR', ['site = ' . \MultiSiteHelper::GetCurrentSiteID(), 'site = -1']); } $groups = \UserGroupModel::Find($where, null, 'name'); if(sizeof($groups)){ $groupopts = array(); foreach($groups as $g){ $groupopts[$g->get('id')] = $g->get('name'); } $form->addElement( 'checkboxes', array( 'name' => 'groups[]', 'title' => 'Group Membership', 'options' => $groupopts, 'value' => $user->getGroups() ) ); } $where = new DatasetWhereClause(); $where->addWhere('context != '); if(\Core::IsComponentAvailable('multisite') && \MultiSiteHelper::IsEnabled()){ $w = new DatasetWhereClause(); $w->setSeparator('or'); $w->addWhere('site = ' . \MultiSiteHelper::GetCurrentSiteID()); $w->addWhere('site = -1'); $where->addWhere($w); } $contextgroups = \UserGroupModel::Count($where); if($contextgroups > 0){ // If this is a non-global context. // Good enough to stop here! $form->addElement( new \FormGroup( [ 'name' => 'context-groups', 'id' => 'context-groups', 'title' => 'Context Group Membership', ] ) ); // So that these elements will be registered on the form object... $form->addElement('hidden', ['name' => 'contextgroup[]', 'persistent' => false]); $form->addElement('hidden', ['name' => 'contextgroupcontext[]', 'persistent' => false]); } } // If the config is enabled and the current user is guest... if($type == 'registration' && \ConfigHandler::Get('/user/register/requirecaptcha') && !\Core\user()->exists()){ $form->addElement('captcha'); } $form->addElement( 'submit', [ 'value' => (($type == 'registration') ? 'Register' : 'Update'), 'name' => 'submit', ] ); return $form; }
public function buildCreditCardForm(CreditCardPayment $ccHandler) { $form = new Form($this->buildCreditCardValidator($ccHandler)); $form->set('ccExpiryMonth', date('n')); $form->set('ccExpiryYear', date('Y')); return $form; }
/** * Change currency options * @role update * @return ActionResponse */ public function options() { $form = new Form($this->buildOptionsValidator()); $form->set('updateCb', $this->config->get('currencyAutoUpdate')); $form->set('frequency', $this->config->get('currencyUpdateFrequency')); // get all feeds $dir = new DirectoryIterator(ClassLoader::getRealPath('library.currency')); foreach ($dir as $file) { $p = pathinfo($file->getFilename()); if ($p['extension'] == 'php') { include_once $file->getPathName(); $className = basename($file->getFilename(), '.php'); $classInfo = new ReflectionClass($className); if (!$classInfo->isAbstract()) { $feeds[$className] = call_user_func(array($className, 'getName')); } } } // get currency settings $currencies = $this->getCurrencySet()->toArray(); $settings = $this->config->get('currencyFeeds'); foreach ($currencies as $id => &$currency) { if (isset($settings[$currency['ID']])) { $form->set('curr_' . $currency['ID'], $settings[$currency['ID']]['enabled']); $form->set('feed_' . $currency['ID'], $settings[$currency['ID']]['feed']); } } $frequency = array(); foreach (array(15, 60, 240, 1440) as $mins) { $frequency[$mins] = $this->translate('_freq_' . $mins); } $response = new ActionResponse(); $response->set('form', $form); $response->set('currencies', $currencies); $response->set('frequency', $frequency); $response->set('feeds', $feeds); return $response; }
public function payment() { if ($this->config->get('REQUIRE_SAME_ADDRESS')) { $this->order->billingAddress->set($this->order->shippingAddress->get()); $this->order->billingAddress->resetModifiedStatus(); } $this->ignoreValidation = true; $response = $this->postProcessResponse($this->pay()); $this->ignoreValidation = false; $paymentMethodForm = new Form($this->getPaymentMethodValidator()); if ($this->isTosRequired) { $paymentMethodForm->set('tos', $this->session->get('tos')); } $paymentMethodForm->set('payMethod', $this->session->get('paymentMethod')); $response->set('form', $paymentMethodForm); $response->set('selectedMethod', $this->session->get('paymentMethod')); $response->set('requireTos', $this->isTosRequired); return $response; }
/** * Interface to "train" the system to learn spam keywords. * * A block of content can be submitted to this page, where the user has the options to score phrases and words. */ public function spam_train() { $view = $this->getView(); $request = $this->getPageRequest(); if (!\Core\user()->checkAccess('g:admin')) { return View::ERROR_ACCESSDENIED; } $view->title = 'Spam Training'; $view->mastertemplate = 'admin'; if ($request->isPost() && $request->getPost('keywords')) { foreach ($_POST['keywords'] as $w => $s) { if ($s == 0) { // Populating the database with a bunch of neutral scores is pointless. continue; } $k = SpamHamKeywordModel::Construct($w); $k->set('score', $s); $k->save(); } \Core\set_message('Trained keywords successfully!', 'success'); \Core\redirect('/security/spam/keywords'); } elseif (!$request->isPost() || !$request->getPost('content')) { // Step 1 for training with content, provide a text area to submit content! $view->templatename = 'pages/security/spam_train_1.tpl'; $form = new Form(); $form->addElement('textarea', ['name' => 'content', 'value' => '', 'title' => t('STRING_CONTENT'), 'description' => 'Paste in the content to parse for keywords. You will have the ability to fine-tune specific keywords on the next page.', 'rows' => 6]); $form->addElement('submit', ['value' => 'Next']); $view->assign('form', $form); } else { // Step 2, $view->templatename = 'pages/security/spam_train_2.tpl'; $check = new \SecuritySuite\SpamCan\SpamCheck($request->getPost('content')); $keywords = $check->getKeywords(); $form = new Form(); $form->set('orientation', 'grid'); foreach ($keywords as $dat) { if ($dat['score'] != 0) { // Skip keywords that are already weighted. continue; } if (preg_match_all('# #', $dat['keyword']) == 1) { // Skip keywords that only contain one space. // Here, we only want single words and 3-word phrases. continue; } $form->addElement('text', ['name' => 'keywords[' . $dat['keyword'] . ']', 'title' => $dat['keyword'], 'value' => 0]); } $form->addElement('submit', ['value' => 'Train!']); $view->assign('form', $form); } }
function render($force = false) { global $DB, $Controller, $USER; if (!$force && !$this->isActive('form') || $USER->ID == NOBODY) { return ''; } if ($this->_Limit > 0 && $this->PostCount >= $this->_Limit) { return '<span class="forminfo">' . __('Form posts has reached the limit') . '</span>'; } $this->saveFormData(); $r = $DB->formfields->get(array('id' => $this->ID, 'language' => $this->loadedLanguage), '*', false, 'sort'); if (!Database::numRows($r)) { return ''; } $uForm = new Form('uform'); $form = array(); while (false !== ($field = Database::fetchAssoc($r))) { $fieldName = 'uform[' . $field['field_id'] . ']'; $fieldLabel = self::fieldlabel($field['label'], $this->loadedLanguage); switch ($field['type']) { case 'Checkbox': case 'pCheckbox': $Values = array_map('trim', explode(',', $field['value'])); $Names = array_map('md5', $Values); if (count($Values) > 1) { $form[] = new checkset($fieldLabel, $fieldName, array_combine($Names, $Values), $field['type'] == 'pCheckbox'); } else { $form[] = new Checkbox($fieldLabel, $fieldName, $field['type'] == 'pCheckbox'); } break; case 'select': case 'mselect': $Values = array_map('trim', explode(',', $field['value'])); $Names = array_map('md5', $Values); $form[] = new select($fieldLabel, $fieldName, array_combine($Names, $Values), false, $field['type'] == 'mselect'); break; case 'Radio': $Values = array_map('trim', explode(',', $field['value'])); $Names = array_map('md5', $Values); $form[] = new Radioset($fieldLabel, $fieldName, array_combine($Names, $Values)); break; case 'input': case 'textarea': case 'htmlfield': $form[] = new $field['type']($fieldLabel, $fieldName, $field['value']); break; case 'hidden': $form[] = new Hidden($fieldName, $field['value']); break; } } if (empty($form)) { return ''; } $form[] = new Hidden('uform[userformsubmittrigger]', 1); $a = $this->getActive('form'); $forminfo = ''; if (@$a['stop']) { $forminfo .= __('Open for submission until') . ' ' . date('Y-m-d H:i', $a['stop']) . '. '; } if ($this->_Limit > 0) { $forminfo .= $this->PostCount . ' ' . __('of') . ' ' . $this->_Limit . ' ' . __('submissions received') . '.'; } if ($forminfo) { $forminfo = '<span class="forminfo">' . $forminfo . '</span>'; } if ($this->_Form_Title) { $forminfo = '<h2>' . $this->_Form_Title . '</h2>' . $forminfo; } return $forminfo . $uForm->set($form); }
public function config() { // Admin-only page. if (!\Core\user()->checkAccess('g:admin')) { return View::ERROR_ACCESSDENIED; } $view = $this->getView(); $keys = ['/package_repository/base_directory', '/package_repository/is_private', '/package_repository/description', '/package_repository/auto_ip_restrict']; $form = new Form(); $form->set('callsmethod', 'AdminController::_ConfigSubmit'); foreach ($keys as $k) { $c = ConfigHandler::GetConfig($k); $f = $c->asFormElement(); // Don't need them grouped $f->set('group', ''); $form->addElement($f); } $form->addElement('submit', ['value' => 'Save Options']); $view->title = 'Package Repository Configuration'; $view->mastertemplate = 'admin'; $view->assign('form', $form); }
/** * @return Form */ private function buildSortForm($order) { $form = new Form($this->getValidator("productSort", $this->request)); $form->enableClientSideValidation(false); $form->set('sort', $order); return $form; }
private function getForm($settings, $validation) { $form = new Form($this->buildValidator($settings, $validation)); // set multi-select values foreach ($settings as $key => $value) { if ('multi' == $value['extra']) { $values = $this->config->get($value['title']); if (is_array($values)) { foreach ($values as $key => $val) { $form->set($value['title'] . '[' . $key . ']', 1); } } } } return $form; }
private function _viewAlbum(GalleryAlbumModel $album) { $view = $this->getView(); $manager = \Core\user()->checkAccess('p:/gallery/manage_all'); $editor = \Core\user()->checkAccess($album->get('editpermissions')) || $manager; $uploader = \Core\user()->checkAccess($album->get('uploadpermissions')) || $editor; $url = $album->get('rewriteurl'); $images = $album->getLink('GalleryImage', 'weight'); $lastupdated = $album->get('updated'); if ($uploader) { $uploadform = new Form(); $uploadform->set('action', \Core\resolve_link('/gallery/images_update/' . $album->get('id'))); $uploadform->addElement('multifile', array('basedir' => $album->getFullUploadDirectory(), 'title' => 'Bulk Upload Files', 'name' => 'images', 'accept' => $album->get('accepttypes'))); $uploadform->addElement('submit', array('value' => 'Save Gallery Changes')); } else { $uploadform = false; } // I need to attach a friendly URL for each image. // This gets a little tricky since each image doesn't have a unique title necessarily. foreach ($images as $i) { // I would like to know when the last change overall was, not just for the gallery. $lastupdated = max($lastupdated, $i->get('updated')); } $view->templatename = '/pages/gallery/view.tpl'; $view->assign('album', $album); $view->assign('images', $images); $view->assign('editor', $editor); $view->assign('manager', $manager); $view->assign('uploader', $uploader); $view->assign('uploadform', $uploadform); $view->assign('userid', \Core\user()->get('id')); $view->updated = $lastupdated; // If there are images in this gallery, grab the first one to show as a preview! if (count($images)) { $view->meta['og:image'] = $images[0]->getFile()->getPreviewURL('200x200'); } if ($editor) { $view->addControl('Gallery Albums Administration', '/gallery/admin', 'directory'); $view->addControl('Edit Gallery Album', '/gallery/edit/' . $album->get('id'), 'edit'); } if ($uploader) { // If they can upload images, they can rearrange them! $view->addControl(array('title' => 'Rearrange Images', 'link' => '/gallery/order/' . $album->get('id'), 'icon' => 'move')); } }
/** * * Este método monta um array com as chaves baseadas * nos parâmetros passados pela URL (GET) * ou pelo método POST. */ private static function mountForm() { $form = new Form(); //MOUNT FORM $kps = array_keys($_POST); foreach ($kps as $key) { $form->set($key, $_POST[$key]); unset($_POST[$key]); } //MOUNT FORM $kgs = array_keys($_GET); foreach ($kgs as $key) { $form->set($key, $_GET[$key]); unset($_GET[$key]); } //MOUNT FORM if (is_array($_FILES)) { $kfs = array_keys($_FILES); foreach ($kfs as $key) { $form->set($key, $_FILES[$key]); unset($_FILES[$key]); } } return $form; }
/** * Page to display the currently installed themes and shortcuts to various operations therein. */ public function index() { $view = $this->getView(); $selected = ConfigHandler::Get('/theme/selected'); $themes = ThemeHandler::GetAllThemes(); $current = ThemeHandler::GetTheme($selected); // Set to true if multisite is enabled AND the page is currently on a child site. $multisite = Core::IsLibraryAvailable('multisite') && MultiSiteHelper::IsEnabled() && MultiSiteHelper::GetCurrentSiteID() != 0; $configDefault = ConfigHandler::GetConfig('/theme/default_template'); $configSelected = ConfigHandler::GetConfig('/theme/selected'); $configEmailDefault = ConfigHandler::GetConfig('/theme/default_email_template'); // Only allow changing the theme if it's on the root site OR both config options are overrideable. $themeSelectionEnabled = !$multisite || $configDefault->get('overrideable') && $configSelected->get('overrideable'); $emailSelectionEnabled = !$multisite || $configEmailDefault->get('overrideable'); $configOptions = $current->getConfigs(); if (!sizeof($configOptions)) { $optionForm = null; } else { $optionForm = new Form(); $optionForm->set('callsmethod', 'AdminController::_ConfigSubmit'); foreach ($configOptions as $c) { /** @var $c ConfigModel */ if ($multisite) { // Only pull the config options that are enabled for this specific site. if ($c->get('overrideable')) { $optionForm->addElement($c->getAsFormElement()); } } else { // Sites that either // do NOT have multisite installed // nor have multisite enabled // or on the root site, get all options. $optionForm->addElement($c->getAsFormElement()); } } if (sizeof($optionForm->getElements()) > 0) { // There is at least one element in the option forms! $optionForm->addElement('submit', ['value' => 'Save Configurable Options']); } else { // Reset the form back to null so that the section doesn't display. $optionForm = null; } } // The source objects to look for assets in. // Set initially to all the installed components. $assetsources = Core::GetComponents(); // And add on the current theme. $assetsources[] = $current; // Load in all asset files available from the installed components and current theme. // these are assembled into a virtual directory listing. $assets = array(); // Give me the current theme! foreach ($assetsources as $source) { /** @var Component_2_1 $source */ $dir = $source->getAssetDir(); if (!$dir) { continue; } $dirlen = strlen($dir); $name = $source->getName(); $dh = \Core\Filestore\Factory::Directory($dir); $ls = $dh->ls(null, true); foreach ($ls as $obj) { // Skip directories. if (!$obj instanceof \Core\Filestore\File) { continue; } /** @var $obj \Core\Filestore\File */ $file = 'assets/' . substr($obj->getFilename(), $dirlen); // Since this is a template, it may actually be in a different location than where the package maintainer put it. // ie: user template user/templates/pages/user/view.tpl may be installed to themes/myawesometheme/pages/user/view.tpl instead. $newobj = \Core\Filestore\Factory::File($file); $assets[$file] = array('file' => $file, 'obj' => $newobj, 'component' => $name); } } // Now that the asset files have been loaded into a flat array, I need to convert that to the properly nested version. ksort($assets); $nestedassets = array(); foreach ($assets as $k => $obj) { $parts = explode('/', $k); $lastkey = sizeof($parts) - 1; $thistarget =& $nestedassets; foreach ($parts as $i => $bit) { if ($i == $lastkey) { $thistarget[$bit] = $obj; } else { if (!isset($thistarget[$bit])) { $thistarget[$bit] = []; } $thistarget =& $thistarget[$bit]; } } } // Get the templates throughout the site. These can include pages, emails, form elements, etc. $components = Core::GetComponents(); $templates = array(); foreach ($components as $c) { /** @var $c Component_2_1 */ $dir = $c->getViewSearchDir(); if (!$dir) { continue; } $dirlen = strlen($dir); $component = $c->getName(); $dh = \Core\Filestore\Factory::Directory($dir); //$pagetplfiles = $dh->ls('tpl', true); $pagetplfiles = $dh->ls(null, true); // not sure why getFilename(path) isn't working as expected, but this works too. foreach ($pagetplfiles as $obj) { // I don't want directories. if ($obj instanceof \Core\Filestore\Directory) { continue; } /** @var $obj \Core\Filestore\File */ $file = substr($obj->getFilename(), $dirlen); // Since this is a template, it may actually be in a different location than where the package maintainer put it. // ie: user template user/templates/pages/user/view.tpl may be installed to themes/myawesometheme/pages/user/view.tpl instead. $tpl = Core\Templates\Template::Factory($file); $resolved = Core\Templates\Template::ResolveFile($file); $newobj = \Core\Filestore\Factory::File($resolved); $templates[$file] = array('file' => $file, 'resolved' => $resolved, 'obj' => $newobj, 'haswidgets' => $tpl->hasWidgetAreas(), 'component' => $component, 'has_stylesheets' => $tpl->hasOptionalStylesheets()); } } // Now that the template files have been loaded into a flat array, I need to convert that to the properly nested version. ksort($templates); $nestedtemplates = array(); foreach ($templates as $k => $obj) { $parts = explode('/', $k); $lastkey = sizeof($parts) - 1; $thistarget =& $nestedtemplates; foreach ($parts as $i => $bit) { if ($i == $lastkey) { $thistarget[$bit] = $obj; } else { if (!isset($thistarget[$bit])) { $thistarget[$bit] = []; } $thistarget =& $thistarget[$bit]; } } } $siteskinform = new Form(); $siteskinform->set('callsmethod', 'ThemeController::SaveSiteSkins'); $opts = ['' => '-- Public Default --']; foreach ($current->getSkins() as $skin) { $opts[$skin['file']] = $skin['title']; } foreach (ConfigHandler::FindConfigs('/theme/siteskin/') as $k => $config) { $siteskinform->addElement('select', ['name' => 'config[' . $k . ']', 'title' => $config->get('description'), 'value' => $config->getValue(), 'options' => $opts]); } $siteskinform->addElement('submit', ['value' => t('STRING_SAVE')]); $customdest = \Core\directory('themes/custom'); $cssform = false; $cssprintform = false; if ($customdest->isWritable()) { $sets = [['file' => 'css/custom.css', 'form' => null], ['file' => 'css/custom_print.css', 'form' => null]]; foreach ($sets as $k => $set) { // Load the editor for the custom CSS file, as this is a very common thing to do! $file = $set['file']; // And try to look up and find this damn file... $srcdirs = array(); $srcdirs[] = ROOT_PDIR . 'themes/custom/assets/'; $srcdirs[] = ROOT_PDIR . 'themes/' . ConfigHandler::Get('/theme/selected') . '/assets/'; foreach (Core::GetComponents() as $c) { if ($c->getAssetDir()) { $srcdirs[] = $c->getAssetDir(); } } foreach ($srcdirs as $dir) { if (file_exists($dir . $file)) { $file = $dir . $file; break; } } $fh = \Core\Filestore\Factory::File($file); $content = $fh->getContents(); $m = new ThemeTemplateChangeModel(); $m->set('content', $content); $m->set('filename', 'assets/css/custom.css'); $form = Form::BuildFromModel($m); $form->set('callsmethod', 'ThemeController::_SaveEditorHandler'); // I need to add the file as a system element so core doesn't try to reuse the same forms on concurrent edits. //$form->addElement('system', array('name' => 'revision', 'value' => $revision)); $form->addElement('system', array('name' => 'file', 'value' => 'assets/' . $set['file'])); $form->addElement('system', array('name' => 'filetype', 'value' => 'file')); // No one uses this anyways! $form->switchElementType('model[comment]', 'hidden'); $form->getElement('model[content]')->set('id', 'custom_content_' . $k); $form->addElement('submit', array('value' => 'Save Custom CSS')); // Save it back down to the original array $sets[$k]['form'] = $form; } $cssform = $sets[0]['form']; $cssprintform = $sets[1]['form']; } $view->title = 'Theme Manager'; $view->assign('themes', $themes); $view->assign('current', $current); $view->assign('options_form', $optionForm); $view->assign('assets', $nestedassets); $view->assign('templates', $nestedtemplates); $view->assign('url_themeeditor', \Core\resolve_link('/theme/editor')); $view->assign('url_themewidgets', \Core\resolve_link('/theme/widgets')); $view->assign('url_themestylesheets', \Core\resolve_link('/theme/selectstylesheets')); $view->assign('site_skins_form', $siteskinform); $view->assign('cssform', $cssform); $view->assign('cssprintform', $cssprintform); $view->assign('multisite', $multisite); $view->assign('theme_selection_enabled', $themeSelectionEnabled); $view->assign('email_selection_enabled', $emailSelectionEnabled); }
/** * Page to test the UI of form elements. * * This will generate a form with every registered form element. */ public function testui(){ $view = $this->getView(); $request = $this->getPageRequest(); if(!\Core\user()->checkAccess('g:admin')){ // This test page is an admin-only utility. return View::ERROR_ACCESSDENIED; } $form = new Form(); // What type of orientation do you want to see? $orientation = $request->getParameter('orientation'); if(!$orientation){ $orientation = 'horizontal'; } $required = ($request->getParameter('required')); $error = ($request->getParameter('error')); $form->set('orientation', $orientation); $mappings = Form::$Mappings; // Make them alphabetical. ksort($mappings); foreach($mappings as $k => $v){ try{ $atts = [ 'name' => $k, 'title' => $v, 'description' => 'This form element is a ' . $v . ', registered to the key ' . $k . '.', ]; if($required) $atts['required'] = true; // Some form elements have particular requirements. switch($v){ case 'FormFileInput': case 'MultiFileInput': $atts['basedir'] = 'tmp/form/testui'; break; case 'FormPagePageSelectInput': $atts['templatename'] = 'foo'; break; case 'FormPageInsertables': $atts['baseurl'] = '/'; break; case 'FormPageMeta': $atts['name'] = 'test'; break; case 'FormCheckboxesInput': case 'FormRadioInput': $atts['options'] = ['key1' => 'Key 1', 'key2' => 'Key 2']; break; } $el = FormElement::Factory($k, $atts); if($error && $el instanceof FormElement){ $el->setError('Something bad happened', false); } $form->addElement( $el ); } catch(Exception $e){ \Core\set_message('Form element ' . $v . ' failed to load due to ' . $e->getMessage(), 'error'); } } $view->title = 'Test Form Element UI/UX'; $view->assign('form', $form); $view->assign('orientation', $orientation); $view->assign('required', $required); $view->assign('error', $error); }
private function getEmailTemplateForm(EmailTemplate $template) { $form = new Form($this->getValidator('template', $this->request)); $form->setData($template->toArray()); $form->set('code', ''); foreach ($template->getOtherLanguages() as $lang => $temp) { $form->set('body_' . $lang, $temp->getBody()); $form->set('html_' . $lang, $temp->getHTML()); $form->set('subject_' . $lang, $temp->getSubject()); } return $form; }
/** * View to manually upload a package to the system. * * This shouldn't be used too often, but can be used for one-off packages that may not reside in a public repository. */ public function upload(){ $request = $this->getPageRequest(); $view = $this->getView(); $form = new Form(); $form->set('callsmethod', 'UpdaterController::_UploadHandler'); $form->addElement( 'file', [ 'name' => 'upload', 'title' => t('STRING_FILE'), 'description' => t('MESSAGE_UPLOAD_TGZ_TO_MANUALLY_INSTALL_PACKAGE'), 'required' => true, //'accept' => ['application/pgp', 'application/gzip'], 'basedir' => '/tmp', ] ); $form->addElement('submit', ['value' => t('STRING_INSTALL')]); $view->title = 't:STRING_MANUALLY_UPLOAD_PACKAGE'; $view->assign('form', $form); }
protected function boxSearchBlock() { ClassLoader::import('application.model.category.Category'); $category = $this->getCategory(); $search = $this->getCategory()->getPathNodeArray(); $subCategories = $category->getSubCategoryArray(); if ($subCategories) { if ($category->getID() != Category::ROOT_ID) { $search[] = $category->toArray(); } $search = array_merge($search, $subCategories); } if (!$search) { $category = Category::getInstanceById(Category::ROOT_ID, Category::LOAD_DATA); $subCategories = $category->getSubCategorySet(); foreach ($subCategories as $category) { $search[] = $category->toArray(); } } $options = array(1 => $this->translate('_all_products')); foreach ($search as $cat) { if ($cat['isEnabled']) { $options[$cat['ID']] = $cat['name_lang']; } } $form = new Form($this->getValidator("productSearch", $this->request)); $form->enableClientSideValidation(false); $form->set('id', $this->getCategory()->getID()); $form->set('q', $this->request->get('q')); if ($this->filters && is_array($this->filters)) { foreach ($this->filters as $filter) { if ($filter instanceof SearchFilter) { $form->set('q', $filter->getKeywords()); } } } $response = new BlockResponse(); $response->set('categories', $options); $response->set('form', $form); return $response; }
private function appendCalendarForm($response) { $dateForm = new Form($this->getDateCompletedValidator($this->getRequest())); $order = $response->get('order'); foreach (array('dateCompleted', 'dateCreated') as $key) { if (isset($order[$key])) { $dateForm->set($key, $order[$key]); } } $response->set('dateForm', $dateForm); }
private function setFormItem(OrderedItem $item, Form $form) { $name = 'item_' . $item->getID(); $form->set($name, $item->count->get()); foreach ($item->getOptions() as $option) { $productOption = $option->choice->get()->option->get(); if ($productOption->isBool()) { $value = true; } else { if ($productOption->isText()) { $value = $option->optionText->get(); } else { if ($productOption->isSelect()) { $value = $option->choice->get()->getID(); } else { if ($productOption->isFile()) { $value = $option->optionText->get(); } } } } $form->set($this->getFormFieldName($item, $productOption), $value); } }
private function _forgotPassword2(){ $view = $this->getView(); $request = $this->getPageRequest(); $genericauth = new \Core\User\AuthDrivers\datastore(); // Create a simple form to render. This is better than doing it in the template. $form = new Form(); $form->set('method', 'POST'); $form->addElement('password', ['name' => 'p1', 'title' => 'Password', 'required' => true]); $form->addElement('password', ['name' => 'p2', 'title' => 'Confirm', 'required' => true]); $form->addElement('submit', ['name' => 'submit', 'value' => 'Set New Password']); $view->title = 'Forgot Password'; $view->assign('step', 2); $view->assign('form', $form); $view->assign('requirements', $genericauth->getPasswordComplexityAsHTML()); $n = $request->getParameter(0); /** @var $nonce NonceModel */ $nonce = NonceModel::Construct($n); if(!$nonce->isValid()){ SystemLogModel::LogSecurityEvent('/user/forgotpassword/confirm', 'Failed Forgot Password. Invalid nonce requested: [' . $n . ']'); \Core\set_message('t:MESSAGE_ERROR_USER_LOGIN_EMAIL_NOT_FOUND'); \core\redirect('/'); return; } $nonce->decryptData(); $data = $nonce->get('data'); /** @var UserModel $u */ $u = UserModel::Construct($data['user']); if(!$u){ SystemLogModel::LogSecurityEvent('/user/forgotpassword/confirm', 'Failed Forgot Password. Invalid user account requested: [' . $data['user'] . ']'); \Core\set_message('t:MESSAGE_ERROR_USER_LOGIN_EMAIL_NOT_FOUND'); \core\redirect('/'); return; } if($request->isPost()){ // Validate the password. if($_POST['p1'] != $_POST['p2']){ \Core\set_message('t:MESSAGE_ERROR_USER_REGISTER_PASSWORD_MISMATCH'); return; } // Else, try to set it... the user model will complain if it's invalid. try{ $u->enableAuthDriver('datastore'); /** @var \Core\User\AuthDrivers\datastore $auth */ $auth = $u->getAuthDriver('datastore'); $auth->setPassword($_POST['p1']); $u->save(); // NOW I can invalidate that nonce! $nonce->markUsed(); SystemLogModel::LogSecurityEvent('/user/forgotpassword/confirm', 'Reset password successfully!', null, $u->get('id')); \Core\set_message('Reset password successfully', 'success'); if($u->get('active')){ \Core\Session::SetUser($u); } \core\redirect('/'); } catch(ModelValidationException $e){ SystemLogModel::LogSecurityEvent('/user/forgotpassword/confirm', 'Failed Forgot Password. ' . $e->getMessage(), null, $u->get('id')); \Core\set_message($e->getMessage(), 'error'); return; } catch(Exception $e){ SystemLogModel::LogSecurityEvent('/user/forgotpassword/confirm', 'Failed Forgot Password. ' . $e->getMessage(), null, $u->get('id')); \Core\set_message((DEVELOPMENT_MODE ? $e->getMessage() : 'An unknown error occured'), 'error'); return; } } }