Example #1
2
 /**
  * @abstract Displays and processes the edit news form
  * @param integer $id
  * @access public
  */
 public function edit($id = false)
 {
     if (!files()->setUploadDirectory()) {
         sml()->say("The file upload directory does not appear to be writable. Please create the folder and set proper permissions.");
     }
     $form = new Form('news', $id);
     if (!$id) {
         $form->setCurrentValue('timestamp', date("Y-m-d H:i:s"));
     }
     // if form has been submitted
     if ($form->isSubmitted()) {
         $file = files()->upload('pdf_filename');
         if (is_array($file) && !empty($file[0])) {
             $form->setCurrentValue('pdf_filename', $file[0]['file_name']);
         }
         if ($form->save($id)) {
             sml()->say('News entry has successfully been updated.');
             router()->redirect('view');
         }
     }
     // make sure the template has access to all current values
     $data['form'] = $form;
     template()->addCss('admin/datepicker.css');
     template()->addJs('admin/datepicker.js');
     template()->addJs('edit.js');
     template()->display($data);
 }
Example #2
1
 public function setForm(Form &$form, array $request)
 {
     $errors = array();
     $form->befor_set();
     $reflex = new ReflectionObject($form);
     $propts = $reflex->getParentClass()->getProperties();
     foreach ($propts as $propt) {
         $name = $propt->getName();
         $exis = method_exists($form, self::VALIDATE . $name);
         $value = isset($request[$name]) ? $request[$name] : null;
         $valid = self::VALIDATE . $name;
         $setvl = self::SET_METHOD . ucfirst($name);
         $respn = $exis ? $form->{$valid}($value) : true;
         if ($respn === true) {
             if (method_exists($form, $setvl)) {
                 if ($value != null) {
                     $form->{$setvl}($value);
                 }
             } else {
                 if ($value != null) {
                     $propt->setAccessible(true);
                     $propt->setValue($form, $value);
                     $propt->setAccessible(false);
                 }
             }
         } else {
             $errors[$name] = $respn;
         }
     }
     $form->after_set();
     return count($errors) > 0 ? $errors : true;
 }
 public function toBoolean(Form $form)
 {
     $left = $form->toFormValue($this->left);
     $right = $form->toFormValue($this->right);
     $value = $form->toFormValue($this->field);
     return $left <= $value && $value <= $right;
 }
 public function post($id = null)
 {
     if (empty($_POST)) {
         $this->_logger->debug("loading form at {$_SERVER['REQUEST_URI']}");
         if ($id !== null) {
             $post = $this->_factory->get('Post', $id);
             $this->view->aTitle = $post->title;
             $this->view->aBody = $post->body;
         }
         $this->view->display('blog/edit.tpl');
     } else {
         $this->_logger->debug("form at {$_SERVER['REQUEST_URI']} submitted");
         $validators = array('aTitle' => array('NotEmpty', 'messages' => 'Title is required'), 'aBody' => array('NotEmpty', 'messages' => 'Body is required'));
         $form = new Form($validators, $_POST);
         if (!$form->isValid()) {
             $this->_logger->debug("form at {$_SERVER['REQUEST_URI']} submitted but invalid");
             $this->view->assign($_POST);
             $this->view->assign($form->getMessages());
             $this->view->display('blog/edit.tpl');
         } else {
             $this->_logger->debug("form at {$_SERVER['REQUEST_URI']} successful ");
             $post = $this->_factory->get('Post', $id);
             $post->title = $form->getRaw('aTitle');
             $post->body = $form->getRaw('aBody');
             $post->create_dt_tm = date('Y-m-d H:i:s');
             $post->save();
             header('Location: /blog');
             exit;
         }
     }
 }
 function Form()
 {
     $form = new Form($this, 'Form', new FieldList(new EmailField('Email')), new FieldList(new FormAction('doSubmit')), new RequiredFields('Email'));
     // Disable CSRF protection for easier form submission handling
     $form->disableSecurityToken();
     return $form;
 }
 function saveNewsArticle($data, Form $form)
 {
     try {
         $form->clearMessage();
         $form->resetValidation();
         if ($data['newsID']) {
             $this->manager->updateNews($data);
         } else {
             $this->manager->postNews($data);
         }
         Session::clear("FormInfo.Form_NewsRequestForm.data");
         return Controller::curr()->redirect('/news-add/?saved=1');
     } catch (EntityValidationException $ex1) {
         $messages = $ex1->getMessages();
         $msg = $messages[0];
         $form->addErrorMessage('Headline', $msg['message'], 'bad');
         SS_Log::log($msg['message'], SS_Log::ERR);
         // Load errors into session and post back
         Session::set("FormInfo.Form_NewsRequestForm.data", $data);
         return $this->redirectBack();
     } catch (Exception $ex) {
         $form->addErrorMessage('Headline', 'Server Error', 'bad');
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         // Load errors into session and post back
         Session::set("FormInfo.Form_NewsRequestForm.data", $data);
         return $this->redirectBack();
     }
 }
Example #7
1
 public function _createForgotPassForm()
 {
     $form = new Form();
     $form->action = "/forgotpass";
     $form->add(EmailField::name('email')->label('Email')->help('What is your email address?')->required(true));
     return $form;
 }
 /**
  * Form Handler to save a content quick create.
  *
  * @param Form $form
  *
  * @return string|bool
  */
 public static function QuickDraftSave(Form $form)
 {
     if (!$form->getElementValue('title')) {
         \Core\set_message('All pages must have titles.', 'error');
         return false;
     }
     /** @var $model ContentModel */
     $model = new ContentModel();
     /** @var $page PageModel Page object for this model, already linked up! */
     $page = $model->getLink('Page');
     // The content nickname is derived from the page title.
     $model->set('nickname', $form->getElementValue('title'));
     $model->save();
     $ins = new InsertableModel();
     $ins->set('site', $page->get('site'));
     $ins->set('baseurl', '/content/view/' . $model->get('id'));
     $ins->set('name', 'body');
     $ins->set('value', '<p>' . nl2br($form->getElementValue('content')) . '</p>');
     $ins->save();
     $page->set('title', $form->getElementValue('title'));
     $page->set('published_status', 'draft');
     $page->set('editurl', '/content/edit/' . $model->get('id'));
     $page->set('deleteurl', '/content/delete/' . $model->get('id'));
     $page->set('component', 'content');
     $page->save();
     return true;
 }
 public function updateEditForm(\Form $form)
 {
     $record = $form->getRecord();
     $fields = $form->Fields()->dataFields();
     $separator = HasOneEditDataObjectExtension::separator;
     foreach ($fields as $name => $field) {
         // Replace shortcuts for separator
         $name = str_replace(array(':', '/'), $separator, $name);
         if (!strpos($name, $separator)) {
             // Also skip $name that starts with a separator
             continue;
         }
         $field->setName($name);
         if (!$record) {
             // No record to set value from
             continue;
         }
         if ($field->Value()) {
             // Skip fields that already have a value
             continue;
         }
         list($hasone, $key) = explode($separator, $name, 2);
         if ($record->has_one($hasone) || $record->belongs_to($hasone)) {
             $rel = $record->getComponent($hasone);
             // Copied from loadDataFrom()
             $exists = isset($rel->{$key}) || $rel->hasMethod($key) || $rel->hasMethod('hasField') && $rel->hasField($key);
             if ($exists) {
                 $value = $rel->__get($key);
                 $field->setValue($value);
             }
         }
     }
 }
 /**
  * @param Form $form
  *
  * @return string
  */
 public function generateFormID($form)
 {
     if ($id = $form->getHTMLID()) {
         return Convert::raw2htmlid($id);
     }
     return Convert::raw2htmlid(get_class($form) . '_' . str_replace(array('.', '/'), '', $form->getName()));
 }
Example #11
1
 protected function _buildRegistrationForm()
 {
     $Form = new Form('logon', $this->getRouter(), $this->getRequest());
     $Form->attach(new FormFieldset('personalInfo'));
     $Form->personalInfo->setLegend('Personal Info');
     $FormNoteInfo = new FormNote('info', FormNote::POSITIONRIGHT);
     $FormNoteInfo->addSection('First and Last Name', 'Enter your first and last name separately into the labeled text input boxes.');
     $FormNoteInfo->addSection('E-Mail Address', array('Enter a valid e-mail address into the labeled text input box; this value will also be your username to log onto this website.', 'Also note that to activate your account you will need to follow a link in an activation e-mail sent to this address. Make sure this is a valid e-mail.'));
     $FormNoteInfo->addSection('Password', 'You must enter a strong password that is at least six characters and contains at least one letter, one number, and one symbol.');
     $Form->personalInfo->attach($FormNoteInfo);
     $FormNoteUsage = new FormNote('logonmessage', FormNote::POSITIONNORMAL);
     $FormNoteUsage->addSection(false, 'Please completely fill out the below information. All fields are required.');
     $Form->personalInfo->attach($FormNoteUsage);
     $Form->personalInfo->attach(new FormInput('firstName', 'First Name'));
     $Form->personalInfo->firstName->restrict(new FormRestrictionNotEmpty());
     $Form->personalInfo->firstName->restrict(new FormRestrictionAlphanumeric());
     $Form->personalInfo->firstName->restrict(new FormRestrictionMaxLength(48));
     $Form->personalInfo->attach(new FormInput('lastName', 'Last Name'));
     $Form->personalInfo->lastName->restrict(new FormRestrictionNotEmpty());
     $Form->personalInfo->lastName->restrict(new FormRestrictionAlphanumeric());
     $Form->personalInfo->lastName->restrict(new FormRestrictionMaxLength(48));
     $Form->personalInfo->attach(new FormInput('email', 'E-Mail Address'));
     $Form->personalInfo->email->restrict(new FormRestrictionNotEmpty());
     $Form->personalInfo->email->restrict(new FormRestrictionEmail());
     $Form->personalInfo->email->restrict(new FormRestrictionMaxLength(48));
     $Form->personalInfo->attach(new FormInput('password', 'Password', 'password'));
     $Form->personalInfo->password->restrict(new FormRestrictionNotEmpty());
     $Form->personalInfo->password->restrict(new FormRestrictionMinLength(6));
     $Form->personalInfo->password->restrict(new FormRestrictionGoodPassword());
     $Form->personalInfo->attach(new FormInput('passwordc', 'Password (Confirm)', 'password'));
     $Form->personalInfo->passwordc->restrict(new FormRestrictionSameAsField($Form->personalInfo->password));
     $Form->personalInfo->attach(new FormInputSubmit('Register'));
     return $Form;
 }
 function updateLinkForm(Form $form)
 {
     $linkType = null;
     $fieldList = null;
     $fields = $form->Fields();
     //->fieldByName('Heading');
     foreach ($fields as $field) {
         $linkType = $field->fieldByName('LinkType');
         $fieldList = $field;
         if ($linkType) {
             break;
         }
         //break once we have the object
     }
     $source = $linkType->getSource();
     $source['document'] = 'Download a document';
     $linkType->setSource($source);
     $addExistingField = new DMSDocumentAddExistingField('AddExisting', 'Add Existing');
     $addExistingField->setForm($form);
     $addExistingField->setUseFieldClass(false);
     $fieldList->insertAfter($addExistingField, 'Description');
     //		Requirements::javascript(SAPPHIRE_DIR . "/thirdparty/behaviour/behaviour.js");
     //		Requirements::javascript(SAPPHIRE_DIR . "/javascript/tiny_mce_improvements.js");
     //
     //		// create additional field, rebase to 'documents' directory
     //		$documents = new TreeDropdownField('document', 'Document', 'File', 'ID', 'DocumentDropdownTitle', true);
     //		$documents->setSearchFunction(array($this, 'documentSearchCallback'));
     //		$baseFolder = Folder::find_or_make(Document::$directory);
     //		$documents->setTreeBaseID($baseFolder->ID);
     //return $form;
 }
Example #13
0
 /**
  * @param \Symfony\Component\Form\Form $form
  * @param \AppBundle\Entity\User $user
  * @return bool
  */
 public function createUser(Form $form, User $user) : bool
 {
     $return = false;
     if (!$this->checkUsername($user->getUsername())) {
         $return = true;
         $form->get('username')->addError(new FormError($this->translator->trans('users.registration.username_already_taken')));
     }
     if (!$this->checkEmail($user->getEmail())) {
         $return = true;
         $form->get('email')->addError(new FormError($this->translator->trans('users.registration.email_already_taken')));
     }
     if ($return) {
         return false;
     }
     $user->setSalt(uniqid('', true));
     $password = $this->encoder->encodePassword($user, $user->getPlainPassword());
     $user->setPassword($password);
     $user->addRole('ROLE_USER');
     $user->enable(false);
     $this->em->persist($user);
     $this->em->flush();
     $this->activationLinkManager->createActivationLink($user);
     $this->activationLinkManager->sendValidationMail($user);
     return true;
 }
Example #14
0
 public function Load()
 {
     parent::$PAGE_TITLE = __(ERROR_USER_BANNED) . " - " . __(SITE_NAME);
     parent::$PAGE_META_ROBOTS = "noindex, nofollow";
     $can_use_captacha = true;
     if (WspBannedVisitors::isBannedIp($this->getRemoteIP())) {
         $last_access = new DateTime(WspBannedVisitors::getBannedIpLastAccess($this->getRemoteIP()));
         $duration = WspBannedVisitors::getBannedIpDuration($this->getRemoteIP());
         $dte_ban = $last_access->modify("+" . $duration . " seconds");
         if ($dte_ban > new DateTime()) {
             $can_use_captacha = false;
         }
     }
     $obj_error_msg = new Object(new Picture("wsp/img/warning.png", 48, 48, 0, "absmidlle"), "<br/><br/>");
     $obj_error_msg->add(new Label(__(ERROR_USER_BANNED_MSG_1), true), "<br/>");
     if ($can_use_captacha) {
         $obj_error_msg->add(new Label(__(ERROR_USER_BANNED_MSG_2), true), "<br/><br/>");
         $this->captcha_error_obj = new Object();
         $form = new Form($this);
         $this->captcha = new Captcha($form);
         $this->captcha->setFocus();
         $unblock_btn = new Button($form);
         $unblock_btn->setValue(__(ERROR_USER_BUTTON))->onClick("onClickUnblock");
         $form->setContent(new Object($this->captcha, "<br/>", $unblock_btn));
         $obj_error_msg->add($this->captcha_error_obj, "<br/>", $form);
     }
     $obj_error_msg->add("<br/><br/>", __(MAIN_PAGE_GO_BACK), new Link(BASE_URL, Link::TARGET_NONE, __(SITE_NAME)));
     $this->render = new ErrorTemplate($obj_error_msg, __(ERROR_USER_BANNED));
 }
Example #15
0
 public function run($static = false)
 {
     $form = new Form();
     $form->post('login')->val('blank')->post('password')->val('blank');
     if (!$form->submit()) {
         // Error
         $this->_error($static);
         return false;
     }
     $data = $form->fetch();
     $login = $data['login'];
     $password = Hash::create('sha256', $data['password'], PASS_HASH_KEY);
     $query = "SELECT userid, login, role FROM user WHERE login = :login AND password = :password";
     if (!($result = $this->db->select($query, array(':login' => $login, ':password' => $password)))) {
         $this->_error($static);
         return false;
     }
     Session::init();
     Session::set('userid', $result[0]['userid']);
     Session::set('login', $result[0]['login']);
     Session::set('role', $result[0]['role']);
     Session::set('loggedIn', true);
     if ($static) {
         header('location:' . URL . 'dashboard');
     }
     echo json_encode('success');
 }
 protected function getContent()
 {
     // Prepara formulário de pesquisa
     $dataArr['ajax'] = ["type" => Config::read('form.hidden'), "data" => (object) ["value" => true]];
     $dataArr['page'] = ["type" => Config::read('form.hidden'), "data" => (object) ["value" => 1]];
     $dataArr['name'] = ["type" => Config::read('form.input'), "data" => (object) ["text" => Text::read('form.product')]];
     $dataArr['btnSearch'] = ["type" => Config::read('form.submit'), "data" => (object) ["text" => Text::read('form.search'), "class" => "primary", "icon" => "glyphicon-search"]];
     $form = new Form("mySearch");
     $form->setHorizontal();
     $searchForm = $form->createForm($dataArr);
     ob_start();
     ?>
         <div class="container">
           <div class="row">
             <a id="toogleFilter" class="pull-right" data-toggle="collapse" data-target="#collapseFilter" href="#">
                 <span class="text">Exibir Filtros </span><span class="glyphicon glyphicon-menu-down"></span>
             </a>
             <div id="collapseFilter" class="panel-body panel-collapse collapse">
                 <?php 
     echo $searchForm;
     ?>
             </div>
           </div>
         </div>
     
         <div id="resultPanel" class="panel-body table-responsive">
             <?php 
     echo $this->result;
     ?>
         </div>
     <?php 
     return ob_get_clean();
 }
 /**
  * @covers FormValidatorCustom
  * @covers FormValidator
  */
 public function testIsValid()
 {
     $form = new Form('some template');
     $validationFunction = array($this, 'userValidationFunction');
     // Tests are completely bypassed when the validation type is
     // "optional" and the test field is empty. We make sure this is the
     // case by returning 'false' for the custom validation function.
     $form->setData('testData', '');
     $validator = new FormValidatorCustom($form, 'testData', FORM_VALIDATOR_OPTIONAL_VALUE, 'some.message.key', $validationFunction, array(false));
     self::assertTrue($validator->isValid());
     self::assertSame(null, $this->checkedValue);
     // Simulate valid data
     $form->setData('testData', 'xyz');
     $validator = new FormValidatorCustom($form, 'testData', FORM_VALIDATOR_REQUIRED_VALUE, 'some.message.key', $validationFunction, array(true));
     self::assertTrue($validator->isValid());
     self::assertSame('xyz', $this->checkedValue);
     // Simulate invalid data
     $form->setData('testData', 'xyz');
     $validator = new FormValidatorCustom($form, 'testData', FORM_VALIDATOR_REQUIRED_VALUE, 'some.message.key', $validationFunction, array(false));
     self::assertFalse($validator->isValid());
     self::assertSame('xyz', $this->checkedValue);
     // Simulate valid data with negation of the user function return value
     $form->setData('testData', 'xyz');
     $validator = new FormValidatorCustom($form, 'testData', FORM_VALIDATOR_REQUIRED_VALUE, 'some.message.key', $validationFunction, array(false), true);
     self::assertTrue($validator->isValid());
     self::assertSame('xyz', $this->checkedValue);
 }
Example #18
0
 public function update($id)
 {
     $filename = get('filename');
     $page = $this->page($id);
     if (!$page) {
         return response::error(l('files.error.missing.page'));
     }
     $file = $page->file($filename);
     if (!$file) {
         return response::error(l('files.error.missing.file'));
     }
     $blueprint = blueprint::find($page);
     $fields = $blueprint->files()->fields($page);
     // trigger the validation
     $form = new Form($fields->toArray());
     $form->validate();
     // fetch the form data
     $data = filedata::createByInput($file, $form->serialize());
     // stop at invalid fields
     if (!$form->isValid()) {
         return response::error(l('files.show.error.form'), 400, array('fields' => $form->fields()->filterBy('error', true)->pluck('name')));
     }
     try {
         $file->update($data, app::$language);
         return response::success('success', array('data' => $data));
     } catch (Exception $e) {
         return response::error($e->getMessage());
     }
 }
 /**
  *  Return description of module
  *
  *  @return     string      Texte descripif
  */
 function info()
 {
     global $conf, $langs;
     $langs->load("bills");
     $form = new Form($this->db);
     $texte = $langs->trans('GenericNumRefModelDesc') . "<br>\n";
     $texte .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
     $texte .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
     $texte .= '<input type="hidden" name="action" value="updateMask">';
     $texte .= '<input type="hidden" name="maskconstpropal" value="PROPALE_SAPHIR_MASK">';
     $texte .= '<table class="nobordernopadding" width="100%">';
     $tooltip = $langs->trans("GenericMaskCodes", $langs->transnoentities("Proposal"), $langs->transnoentities("Proposal"));
     $tooltip .= $langs->trans("GenericMaskCodes2");
     $tooltip .= $langs->trans("GenericMaskCodes3");
     $tooltip .= $langs->trans("GenericMaskCodes4a", $langs->transnoentities("Proposal"), $langs->transnoentities("Proposal"));
     $tooltip .= $langs->trans("GenericMaskCodes5");
     // Parametrage du prefix
     $texte .= '<tr><td>' . $langs->trans("Mask") . ':</td>';
     $texte .= '<td align="right">' . $form->textwithpicto('<input type="text" class="flat" size="24" name="maskpropal" value="' . $conf->global->PROPALE_SAPHIR_MASK . '">', $tooltip, 1, 1) . '</td>';
     $texte .= '<td align="left" rowspan="2">&nbsp; <input type="submit" class="button" value="' . $langs->trans("Modify") . '" name="Button"></td>';
     $texte .= '</tr>';
     $texte .= '</table>';
     $texte .= '</form>';
     return $texte;
 }
 function updateImportForm(Form $form)
 {
     /* @var $owner ModelAdmin */
     $owner = $this->owner;
     $class = $owner->modelClass;
     // Overwrite model imports
     $importerClasses = $owner->stat('model_importers');
     if (is_null($importerClasses)) {
         $models = $owner->getManagedModels();
         foreach ($models as $modelName => $options) {
             $importerClasses[$modelName] = 'ExcelBulkLoader';
         }
         $owner->set_stat('model_importers', $importerClasses);
     }
     $modelSNG = singleton($class);
     $modelName = $modelSNG->i18n_singular_name();
     $fields = $form->Fields();
     $content = _t('ModelAdminExcelExtension.DownloadSample', '<div class="field"><a href="{link}">Download sample file</a></div>', array('link' => $owner->Link($class . '/downloadsample')));
     $file = $fields->dataFieldByName('_CsvFile');
     if ($file) {
         $file->setDescription(ExcelImportExport::getValidExtensionsText());
         $file->getValidator()->setAllowedExtensions(ExcelImportExport::getValidExtensions());
     }
     $fields->removeByName("SpecFor{$modelName}");
     $fields->insertAfter('EmptyBeforeImport', new LiteralField("SampleFor{$modelName}", $content));
     if (!$modelSNG->canDelete()) {
         $fields->removeByName('EmptyBeforeImport');
     }
     $actions = $form->Actions();
     $import = $actions->dataFieldByName('action_import');
     if ($import) {
         $import->setTitle(_t('ModelAdminExcelExtension.ImportExcel', "Import from Excel"));
     }
 }
 public function Form()
 {
     $fields = new FieldList();
     $source = array();
     $fields->push(new HeaderField('Header', _t('RemoveOrphanedPagesTask.HEADER', 'Remove all orphaned pages task')));
     $fields->push(new LiteralField('Description', $this->description));
     $orphans = $this->getOrphanedPages($this->orphanedSearchClass);
     if ($orphans) {
         foreach ($orphans as $orphan) {
             $latestVersion = Versioned::get_latest_version($this->orphanedSearchClass, $orphan->ID);
             $latestAuthor = DataObject::get_by_id('Member', $latestVersion->AuthorID);
             $stageRecord = Versioned::get_one_by_stage($this->orphanedSearchClass, 'Stage', sprintf("\"%s\".\"ID\" = %d", ClassInfo::baseDataClass($this->orphanedSearchClass), $orphan->ID));
             $liveRecord = Versioned::get_one_by_stage($this->orphanedSearchClass, 'Live', sprintf("\"%s\".\"ID\" = %d", ClassInfo::baseDataClass($this->orphanedSearchClass), $orphan->ID));
             $label = sprintf('<a href="admin/pages/edit/show/%d">%s</a> <small>(#%d, Last Modified Date: %s, Last Modifier: %s, %s)</small>', $orphan->ID, $orphan->Title, $orphan->ID, Date::create($orphan->LastEdited)->Nice(), $latestAuthor ? $latestAuthor->Title : 'unknown', $liveRecord ? 'is published' : 'not published');
             $source[$orphan->ID] = $label;
         }
     }
     if ($orphans && $orphans->Count()) {
         $fields->push(new CheckboxSetField('OrphanIDs', false, $source));
         $fields->push(new LiteralField('SelectAllLiteral', sprintf('<p><a href="#" onclick="javascript:jQuery(\'#Form_Form_OrphanIDs :checkbox\').attr(\'checked\', \'checked\'); return false;">%s</a>&nbsp;', _t('RemoveOrphanedPagesTask.SELECTALL', 'select all'))));
         $fields->push(new LiteralField('UnselectAllLiteral', sprintf('<a href="#" onclick="javascript:jQuery(\'#Form_Form_OrphanIDs :checkbox\').attr(\'checked\', \'\'); return false;">%s</a></p>', _t('RemoveOrphanedPagesTask.UNSELECTALL', 'unselect all'))));
         $fields->push(new OptionSetField('OrphanOperation', _t('RemoveOrphanedPagesTask.CHOOSEOPERATION', 'Choose operation:'), array('rebase' => _t('RemoveOrphanedPagesTask.OPERATION_REBASE', sprintf('Rebase selected to a new holder page "%s" and unpublish. None of these pages will show up for website visitors.', $this->rebaseHolderTitle())), 'remove' => _t('RemoveOrphanedPagesTask.OPERATION_REMOVE', 'Remove selected from all stages (WARNING: Will destroy all selected pages from both stage and live)')), 'rebase'));
         $fields->push(new LiteralField('Warning', sprintf('<p class="message">%s</p>', _t('RemoveOrphanedPagesTask.DELETEWARNING', 'Warning: These operations are not reversible. Please handle with care.'))));
     } else {
         $fields->push(new LiteralField('NotFoundLabel', sprintf('<p class="message">%s</p>', _t('RemoveOrphanedPagesTask.NONEFOUND', 'No orphans found'))));
     }
     $form = new Form($this, 'Form', $fields, new FieldList(new FormAction('doSubmit', _t('RemoveOrphanedPagesTask.BUTTONRUN', 'Run'))));
     if (!$orphans || !$orphans->Count()) {
         $form->makeReadonly();
     }
     return $form;
 }
 /**
  * 
  * @param Form $form
  * @return SignatureRecord
  */
 protected function updateRecord(Form $form)
 {
     $signature = $this->getSignatureRecord(true);
     $form->saveInto($signature);
     $signature->write();
     return $signature;
 }
 /**
  * Performs the login, but will also create and sync the Member record on-the-fly, if not found.
  *
  * @param array $data
  * @param Form $form
  * @return bool|Member|void
  * @throws SS_HTTPResponse_Exception
  */
 public static function authenticate($data, Form $form = null)
 {
     $service = Injector::inst()->get('LDAPService');
     $result = $service->authenticate($data['Username'], $data['Password']);
     $success = $result['success'] === true;
     if (!$success) {
         if ($form) {
             $form->sessionMessage($result['message'], 'bad');
         }
         return;
     }
     $data = $service->getUserByUsername($result['identity']);
     if (!$data) {
         if ($form) {
             $form->sessionMessage(_t('LDAPAuthenticator.PROBLEMFINDINGDATA', 'There was a problem retrieving your user data'), 'bad');
         }
         return;
     }
     // LDAPMemberExtension::memberLoggedIn() will update any other AD attributes mapped to Member fields
     $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
     if (!($member && $member->exists())) {
         $member = new Member();
         $member->GUID = $data['objectguid'];
         $member->write();
     }
     Session::clear('BackURL');
     return $member;
 }
 /**
  * Get form fields for manipulating the current order,
  * according to the responsibilty of this component.
  *
  * @param Order $order
  * @param Form  $form
  *
  * @return FieldList
  */
 public function getFormFields(Order $order, Form $form = null)
 {
     $gateway = $this->getGateway($order);
     if (!$this->isBraintree) {
         return parent::getFormFields($order);
     }
     // Generate the token for the javascript to use
     $clientToken = $gateway->clientToken()->send()->getToken();
     // Generate the standard set of fields and allow it to be customised
     $fields = FieldList::create([BraintreeHostedField::create('number', _t('BraintreePaymentCheckoutComponent.CardNumber', 'Debit/Credit Card Number')), BraintreeHostedField::create('cvv', _t('BraintreePaymentCheckoutComponent.CVV', 'Security Code')), BraintreeHostedField::create('expirationDate', _t('BraintreePaymentCheckoutComponent.ExpirationDate', 'Expiration Date (MM/YYYY)'))]);
     if ($this->config()->use_placeholders) {
         foreach ($fields as $field) {
             if ($field->Title()) {
                 $field->setAttribute('placeholder', $field->Title())->setTitle(null);
             }
         }
     }
     $this->extend('updateFormFields', $fields);
     // Generate a basic config and allow it to be customised
     $config = ['id' => $form ? $form->getHTMLID() : 'PaymentForm_OrderForm', 'hostedFields' => $this->getFieldConfig($fields)];
     $this->extend('updateBraintreeConfig', $config);
     $rawConfig = json_encode($config);
     $rawConfig = $this->injectCallbacks($rawConfig);
     $this->extend('updateRawBraintreeConfig', $rawConfig);
     // Finally, add the javascript to the page
     Requirements::javascript('https://js.braintreegateway.com/js/braintree-2.20.0.min.js');
     Requirements::customScript("braintree.setup('{$clientToken}', 'custom', {$rawConfig});", 'BrainTreeJS');
     return $fields;
 }
 /**
  * Form action handler for ContactInquiryForm.
  *
  * @param array $data The form request data submitted
  * @param Form $form The {@link Form} this was submitted on
  */
 function dosave(array $data, Form $form, SS_HTTPRequest $request)
 {
     $SQLData = Convert::raw2sql($data);
     $attrs = $form->getAttributes();
     if ($SQLData['Comment'] != '' || $SQLData['Url'] != '') {
         // most probably spam - terminate silently
         Director::redirect(Director::baseURL() . $this->URLSegment . "/success");
         return;
     }
     $item = new ContactInquiry();
     $form->saveInto($item);
     // $form->sessionMessage(_t("ContactPage.FORMMESSAGEGOOD", "Your inquiry has been submitted. Thanks!"), 'good');
     $item->write();
     $mailFrom = $this->currController->MailFrom ? $this->currController->MailFrom : $SQLData['Email'];
     $mailTo = $this->currController->MailTo ? $this->currController->MailTo : Email::getAdminEmail();
     $mailSubject = $this->currController->MailSubject ? $this->currController->MailSubject . ' - ' . $SQLData['Ref'] : _t('ContactPage.SUBJECT', '[web] New contact inquiry - ') . ' ' . $data['Ref'];
     $email = new Email($mailFrom, $mailTo, $mailSubject);
     $email->replyTo($SQLData['Email']);
     $email->setTemplate("ContactInquiry");
     $email->populateTemplate($SQLData);
     $email->send();
     // $this->controller->redirectBack();
     if ($email->send()) {
         $this->controller->redirect($this->controller->Link() . "success");
     } else {
         $this->controller->redirect($this->controller->Link() . "error");
     }
     return false;
 }
Example #26
0
 public function enable()
 {
     $this->validateScript = '';
     $this->toggleScript = '';
     $this->central = TRUE;
     foreach ($this->form->getControls() as $control) {
         $script = $this->getValidateScript($control->getRules());
         if ($script) {
             $this->validateScript .= "do {\n\t{$script}} while(0);\n\n\t";
         }
         $this->toggleScript .= $this->getToggleScript($control->getRules());
         if ($control instanceof ISubmitterControl && $control->getValidationScope() !== TRUE) {
             $this->central = FALSE;
         }
     }
     if ($this->validateScript || $this->toggleScript) {
         if ($this->central) {
             $this->form->getElementPrototype()->onsubmit("return {$this->validateFunction}(this)", TRUE);
         } else {
             foreach ($this->form->getComponents(TRUE, 'Nette\\Forms\\ISubmitterControl') as $control) {
                 if ($control->getValidationScope()) {
                     $control->getControlPrototype()->onclick("return {$this->validateFunction}(this)", TRUE);
                 }
             }
         }
     }
 }
Example #27
0
 /**
  * Adds the 'build' link to the CMS edit form after the gridsheet.
  *
  * @param Form $form
  */
 public function updateStreakAdminForm(Form $form)
 {
     $fields = $form->Fields();
     if ($gridField = $fields->fieldByName('StreakDiscountType')) {
         $fields->insertAfter(new LiteralField('buildLink', '<p><a class="build-link" href="/dev/build?flush=1"><strong>Add fields to disountable objects</strong></strong></a></p>'), 'StreakDiscountType');
     }
 }
 /**
  *	Output a combo list with projects qualified for a third party
  *
  *	@param	int		$socid      	Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
  *	@param  int		$selected   	Id project preselected
  *	@param  string	$htmlname   	Nom de la zone html
  *	@param	int		$maxlength		Maximum length of label
  *	@param	int		$option_only	Return only html options lines without the select tag
  *	@param	int		$show_empty		Add an empty line
  *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  *  @param	int		$forcefocus		Force focus on field (works with javascript only)
  *  @param	int		$disabled		Disabled
  *  @param  int     $mode           0 for HTML mode and 1 for JSON mode
  *  @param  string  $filterkey      Key to filter
  *	@return int         			Nber of project if OK, <0 if KO
  */
 function select_projects($socid = -1, $selected = '', $htmlname = 'projectid', $maxlength = 16, $option_only = 0, $show_empty = 1, $discard_closed = 0, $forcefocus = 0, $disabled = 0, $mode = 0, $filterkey = '')
 {
     global $langs, $conf, $form;
     if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
         $placeholder = '';
         if ($selected && empty($selected_input_value)) {
             require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
             $project = new Project($this->db);
             $project->fetch($selected);
             $selected_input_value = $project->ref;
         }
         $urloption = 'socid=' . $socid . '&htmlname=' . $htmlname;
         print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array());
         print '<input type="text" size="20" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' />';
     } else {
         print $this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey);
         if ($discard_closed) {
             if (class_exists('Form')) {
                 if (empty($form)) {
                     $form = new Form($this->db);
                 }
                 print $form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden"));
             }
         }
     }
 }
 /**     \brief      Renvoi la description du modele de numerotation
  *      \return     string      Texte descripif
  */
 function info()
 {
     global $conf, $langs;
     $langs->load("pos@pos");
     $form = new Form($db);
     $texte = $langs->trans('GenericNumRefModelDesc') . "<br>\n";
     $texte .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
     $texte .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
     $texte .= '<input type="hidden" name="action" value="updateMask">';
     $texte .= '<input type="hidden" name="maskconstfacsim" value="FACSIM_MURO_MASK">';
     $texte .= '<input type="hidden" name="maskconstfacsimcredit" value="FACSIM_MURO_MASK_CREDIT">';
     $texte .= '<table class="nobordernopadding" width="100%">';
     $tooltip = $langs->trans("GenericMaskCodes", $langs->transnoentities("Facsim"));
     $tooltip .= $langs->trans("GenericMaskCodes2");
     $tooltip .= $langs->trans("POSMaskCodes");
     $tooltip .= $langs->trans("GenericMaskCodes3");
     $tooltip .= $langs->trans("GenericMaskCodes4a", $langs->transnoentities("Facsim"), $langs->transnoentities("facsim"));
     $tooltip .= $langs->trans("GenericMaskCodes5");
     // Parametrage du prefix
     $texte .= '<tr><td>' . $langs->trans("Mask") . ' (' . $langs->trans("Facsim") . '):</td>';
     $texte .= '<td align="right">' . $form->textwithpicto('<input type="text" class="flat" size="24" name="maskfacsim" value="' . $conf->global->FACSIM_MURO_MASK . '">', $tooltip, 1, 1) . '</td>';
     $texte .= '<td align="left" rowspan="2">&nbsp; <input type="submit" class="button" value="' . $langs->trans("Modify") . '" name="Button"></td>';
     $texte .= '</tr>';
     // Parametrage du prefix des avoirs
     $texte .= '<tr><td>' . $langs->trans("Mask") . ' (' . $langs->trans("FacsimAvoir") . '):</td>';
     $texte .= '<td align="right">' . $form->textwithpicto('<input type="text" class="flat" size="24" name="maskfacsimcredit" value="' . $conf->global->FACSIM_MURO_MASK_CREDIT . '">', $tooltip, 1, 1) . '</td>';
     $texte .= '</tr>';
     $texte .= '</table>';
     $texte .= '</form>';
     return $texte;
 }
 /**
  * @return ModelAndView
  **/
 public function run(Prototyped $subject, Form $form, HttpRequest $request)
 {
     if ($object = $form->getValue('id')) {
         FormUtils::object2form($object, $form);
     }
     return ModelAndView::create();
 }