Example #1
0
 public function testLoadDataFromIgnoreFalseish()
 {
     $form = new Form(new Controller(), 'Form', new FieldList(new TextField('Biography', 'Biography', 'Custom Default')), new FieldList());
     $captainNoDetails = $this->objFromFixture('FormTest_Player', 'captainNoDetails');
     $captainWithDetails = $this->objFromFixture('FormTest_Player', 'captainWithDetails');
     $form->loadDataFrom($captainNoDetails, Form::MERGE_IGNORE_FALSEISH);
     $this->assertEquals($form->getData(), array('Biography' => 'Custom Default'), 'LoadDataFrom() doesn\'t overwrite fields when MERGE_IGNORE_FALSEISH set and values are false-ish');
     $form->loadDataFrom($captainWithDetails, Form::MERGE_IGNORE_FALSEISH);
     $this->assertEquals($form->getData(), array('Biography' => 'Bio 1'), 'LoadDataFrom() does overwrite fields when MERGE_IGNORE_FALSEISH set and values arent false-ish');
 }
Example #2
0
 public function testLoadDataFromClearMissingFields()
 {
     $form = new Form(new Controller(), 'Form', new FieldSet(new HeaderField('MyPlayerHeader', 'My Player'), new TextField('Name'), new TextareaField('Biography'), new DateField('Birthday'), new NumericField('BirthdayYear'), $unrelatedField = new TextField('UnrelatedFormField')), new FieldSet());
     $unrelatedField->setValue("random value");
     $captainWithDetails = $this->objFromFixture('FormTest_Player', 'captainWithDetails');
     $captainNoDetails = $this->objFromFixture('FormTest_Player', 'captainNoDetails');
     $form->loadDataFrom($captainWithDetails);
     $this->assertEquals($form->getData(), array('Name' => 'Captain Details', 'Biography' => 'Bio 1', 'Birthday' => '1982-01-01', 'BirthdayYear' => '1982', 'UnrelatedFormField' => 'random value'), 'LoadDataFrom() doesnt overwrite fields not found in the object');
     $captainWithDetails = $this->objFromFixture('FormTest_Player', 'captainNoDetails');
     $team2 = $this->objFromFixture('FormTest_Team', 'team2');
     $form->loadDataFrom($captainWithDetails);
     $form->loadDataFrom($team2, true);
     $this->assertEquals($form->getData(), array('Name' => 'Team 2', 'Biography' => '', 'Birthday' => '', 'BirthdayYear' => 0, 'UnrelatedFormField' => null), 'LoadDataFrom() overwrites fields not found in the object with $clearMissingFields=true');
 }
 /**
  * Make payment for a place order, where payment had previously failed.
  *
  * @param array $data
  * @param Form  $form
  *
  * @return boolean
  */
 public function dopayment($data, $form)
 {
     if (self::config()->allow_paying && $this->order && $this->order->canPay()) {
         // Save payment data from form and process payment
         $data = $form->getData();
         $gateway = !empty($data['PaymentMethod']) ? $data['PaymentMethod'] : null;
         if (!GatewayInfo::is_manual($gateway)) {
             $processor = OrderProcessor::create($this->order);
             $data['cancelUrl'] = $processor->getReturnUrl();
             $response = $processor->makePayment($gateway, $data);
             if ($response) {
                 if ($response->isRedirect() || $response->isSuccessful()) {
                     return $response->redirect();
                 }
                 $form->sessionMessage($response->getMessage(), 'bad');
             } else {
                 $form->sessionMessage($processor->getError(), 'bad');
             }
         } else {
             $form->sessionMessage(_t('OrderActionsForm.MANUAL_NOT_ALLOWED', "Manual payment not allowed"), 'bad');
         }
         return $this->controller->redirectBack();
     }
     $form->sessionMessage(_t('OrderForm.COULDNOTPROCESSPAYMENT', 'Payment could not be processed.'), 'bad');
     $this->controller->redirectBack();
 }
 public function validateStep($data, Form $form)
 {
     Session::set("FormInfo.{$form->FormName()}.data", $form->getData());
     $datetime = $this->getForm()->getController()->getDateTime();
     $session = $this->getForm()->getSession();
     $data = $form->getData();
     $has = false;
     if ($datetime->Event()->OneRegPerEmail) {
         if (Member::currentUserID()) {
             $email = Member::currentUser()->Email;
         } else {
             $email = $data['Email'];
         }
         $existing = DataObject::get_one('EventRegistration', sprintf('"Email" = \'%s\' AND "Status" <> \'Canceled\' AND "TimeID" = %d', Convert::raw2sql($email), $datetime->ID));
         if ($existing) {
             $form->addErrorMessage('Email', 'A registration for this email address already exists', 'required');
             return false;
         }
     }
     // Ensure that the entered ticket data is valid.
     if (!$this->form->validateTickets($data['Tickets'], $form)) {
         return false;
     }
     // Finally add the tickets to the actual registration.
     $registration = $this->form->getSession()->getRegistration();
     $hasLimit = (bool) $this->form->getController()->getDateTime()->Event()->RegistrationTimeLimit;
     if ($hasLimit && !$registration->isInDB()) {
         $registration->write();
     }
     $total = $this->getTotal();
     $registration->Total->setCurrency($total->getCurrency());
     $registration->Total->setAmount($total->getAmount());
     $registration->Name = $data['Name'];
     $registration->Email = $data['Email'];
     $registration->write();
     $registration->Tickets()->removeAll();
     foreach ($data['Tickets'] as $id => $quantity) {
         if ($quantity) {
             $registration->Tickets()->add($id, array('Quantity' => $quantity));
         }
     }
     return true;
 }
 public function doInvite($data, Form $form)
 {
     $data = $form->getData();
     $emails = $data['Emails']['new'];
     $sent = new DataObjectSet();
     if (!$emails) {
         $form->addErrorMessage('Emails', 'Please enter at least one person to invite.');
     }
     $time = DataObject::get_by_id('RegisterableDateTime', $data['TimeID']);
     $invite = new Email();
     $invite->setSubject(sprintf('Event Invitation For %s (%s)', $time->EventTitle(), SiteConfig::current_site_config()->Title));
     $invite->setTemplate('EventInvitationEmail');
     $invite->populateTemplate(array('Time' => $time, 'SiteConfig' => SiteConfig::current_site_config(), 'Link' => Director::absoluteURL($time->Link())));
     $count = count($emails['Name']);
     for ($i = 0; $i < $count; $i++) {
         $name = trim($emails['Name'][$i]);
         $email = trim($emails['Email'][$i]);
         if (!$name || !$email) {
             continue;
         }
         $regod = DataObject::get_one('EventRegistration', sprintf('"Email" = \'%s\' AND "TimeID" = \'%d\'', Convert::raw2sql($email), $time->ID));
         if ($regod) {
             $sent->push(new ArrayData(array('Name' => $name, 'Email' => $email, 'Sent' => false, 'Reason' => 'Already registered')));
             continue;
         }
         $invited = DataObject::get_one('EventInvitation', sprintf('"Email" = \'%s\' AND "TimeID" = \'%d\'', Convert::raw2sql($email), $time->ID));
         if ($invited) {
             $sent->push(new ArrayData(array('Name' => $name, 'Email' => $email, 'Sent' => false, 'Reason' => 'Already invited')));
             continue;
         }
         $invitation = new EventInvitation();
         $invitation->Name = $name;
         $invitation->Email = $email;
         $invitation->TimeID = $time->ID;
         $invitation->EventID = $time->EventID;
         $invitation->write();
         $_invite = clone $invite;
         $_invite->setTo($email);
         $_invite->populateTemplate(array('Name' => $name));
         $_invite->send();
         $sent->push(new ArrayData(array('Name' => $name, 'Email' => $email, 'Sent' => true)));
     }
     Requirements::clear();
     $controller = $this->customise(array('Result' => $sent));
     return $controller->renderWith('EventInvitationField_invite');
 }
Example #6
0
 /**
  * Customize the menu
  */
 public function index()
 {
     $items = MenuItem::getAll();
     $form = new Form(array('id' => 'set-menus-form', 'action' => App::router()->getUri('set-menu'), 'inputs' => array(new HiddenInput(array('name' => 'data', 'default' => json_encode($items, JSON_NUMERIC_CHECK), 'attributes' => array('e-value' => 'JSON.stringify(items.valueOf())'))), new SubmitInput(array('name' => 'valid', 'value' => Lang::get('main.valid-button')))), 'onsuccess' => 'app.refreshMenu()'));
     if (!$form->submitted()) {
         $this->addKeysToJavaScript($this->_plugin . '.plugins-advert-menu-changed');
         return View::make(Plugin::current()->getView('sort-main-menu.tpl'), array('form' => $form));
     } else {
         try {
             $items = MenuItem::getAll('id');
             $data = json_decode($form->getData('data'), true);
             foreach ($data as $line) {
                 $item = $items[$line['id']];
                 $item->set(array('active' => $line['active'], 'parentId' => $line['parentId'], 'order' => $line['order']));
                 $item->save();
             }
             return $form->response(Form::STATUS_SUCCESS, Lang::get($this->_plugin . '.sort-menu-success'));
         } catch (Exception $e) {
             return $form->response(Form::STATUS_ERROR, DEBUG_MODE ? $e->getMessage() : Lang::get($this->_plugin . '.sort-menu-error'));
         }
     }
 }
 /**
  * Make payment for a place order, where payment had previously failed.
  *
  * @param array $data
  * @param Form  $form
  *
  * @return boolean
  */
 public function dopayment($data, $form)
 {
     if (self::config()->allow_paying && $this->order && $this->order->canPay()) {
         // Save payment data from form and process payment
         $data = $form->getData();
         $gateway = !empty($data['PaymentMethod']) ? $data['PaymentMethod'] : null;
         if (!GatewayInfo::isManual($gateway)) {
             /** @var OrderProcessor $processor */
             $processor = OrderProcessor::create($this->order);
             $response = $processor->makePayment($gateway, $data, $processor->getReturnUrl());
             if ($response && !$response->isError()) {
                 return $response->redirectOrRespond();
             } else {
                 $form->sessionMessage($processor->getError(), 'bad');
             }
         } else {
             $form->sessionMessage(_t('OrderActionsForm.ManualNotAllowed', "Manual payment not allowed"), 'bad');
         }
         return $this->controller->redirectBack();
     }
     $form->sessionMessage(_t('OrderForm.CouldNotProcessPayment', 'Payment could not be processed.'), 'bad');
     $this->controller->redirectBack();
 }
Example #8
0
 /**
  * @param array $completions
  * @param array $uninputs
  * @return $this
  * @throws ErrorException
  * @throws NoLocationException
  * @throws StateException
  * @throws \Exception
  */
 public function submit(array $completions, array $uninputs = [])
 {
     $this->form->setSimpleXMLForm($this->_source)->addCompletions($completions);
     foreach ($uninputs as $uninput) {
         $this->form->removeInput($uninput);
     }
     $method = 'get';
     $action = $this->crawler->getUrl();
     if ($this->form->hasAttribute('method')) {
         $method = $this->form->getAttribute('method');
     }
     if ($this->form->hasAttribute('action')) {
         $action = $this->form->getAttribute('action');
         if (isset($action[0])) {
             if ('/' === $action[0]) {
                 $action = $this->crawler->getBaseUrl() . $action;
             } else {
                 throw new \Exception("TODO: " . __FILE__ . " L" . __LINE__);
             }
         }
     }
     $this->crawler->submit($method, $action, $this->form->getData());
     return $this;
 }
 /**
  * @return array Errors (if any)
  */
 function validate()
 {
     $this->errors = null;
     $this->php($this->form->getData());
     return $this->errors;
 }
Example #10
0
 /**
  * Install the application
  */
 public function settings()
 {
     $form = new Form(array('id' => 'install-settings-form', 'labelWidth' => '30em', 'fieldsets' => array('global' => array('legend' => Lang::get('install.settings-global-legend', null, null, $this->language), new TextInput(array('name' => 'title', 'required' => true, 'label' => Lang::get('install.settings-title-label', null, null, $this->language), 'default' => DEFAULT_HTML_TITLE)), new TextInput(array('name' => 'rooturl', 'required' => true, 'label' => Lang::get('install.settings-rooturl-label', null, null, $this->language), 'placeholder' => 'http://', 'default' => getenv('REQUEST_SCHEME') . '://' . getenv('SERVER_NAME'))), new SelectInput(array('name' => 'timezone', 'required' => true, 'options' => array_combine(\DateTimeZone::listIdentifiers(), \DateTimeZone::listIdentifiers()), 'default' => DEFAULT_TIMEZONE, 'label' => Lang::get('install.settings-timezone-label')))), 'database' => array('legend' => Lang::get('install.settings-database-legend', null, null, $this->language), new TextInput(array('name' => 'db[host]', 'required' => true, 'label' => Lang::get('install.settings-db-host-label', null, null, $this->language), 'default' => 'localhost')), new TextInput(array('name' => 'db[username]', 'required' => true, 'label' => Lang::get('install.settings-db-username-label', null, null, $this->language))), new PasswordInput(array('name' => 'db[password]', 'required' => true, 'label' => Lang::get('install.settings-db-password-label', null, null, $this->language), 'pattern' => '/^.*$/')), new TextInput(array('name' => 'db[dbname]', 'required' => true, 'pattern' => '/^\\w+$/', 'label' => Lang::get('install.settings-db-dbname-label', null, null, $this->language))), new TextInput(array('name' => 'db[prefix]', 'default' => 'Hawk', 'pattern' => '/^\\w+$/', 'label' => Lang::get('install.settings-db-prefix-label', null, null, $this->language)))), 'admin' => array('legend' => Lang::get('install.settings-admin-legend', null, null, $this->language), new TextInput(array('name' => 'admin[login]', 'required' => true, 'pattern' => '/^\\w+$/', 'label' => Lang::get('install.settings-admin-login-label', null, null, $this->language))), new EmailInput(array('name' => 'admin[email]', 'required' => true, 'label' => Lang::get('install.settings-admin-email-label', null, null, $this->language))), new PasswordInput(array('name' => 'admin[password]', 'required' => true, 'label' => Lang::get('install.settings-admin-password-label', null, null, $this->language))), new PasswordInput(array('name' => 'admin[passagain]', 'required' => true, 'compare' => 'admin[password]', 'label' => Lang::get('install.settings-admin-passagain-label', null, null, $this->language)))), '_submits' => array(new SubmitInput(array('name' => 'valid', 'value' => Lang::get('install.install-button', null, null, $this->language), 'icon' => 'cog')))), 'onsuccess' => 'location.href = data.rooturl;'));
     if (!$form->submitted()) {
         // Display the form
         $body = View::make(Plugin::current()->getView('settings.tpl'), array('form' => $form));
         return \Hawk\Plugins\Main\MainController::getInstance()->index($body);
     } else {
         // Make the installation
         if ($form->check()) {
             /**
              * Generate Crypto constants
              */
             $salt = Crypto::generateKey(24);
             $key = Crypto::generateKey(32);
             $iv = Crypto::generateKey(16);
             $configMode = 'prod';
             /**
              * Create the database and it tables
              */
             $tmpfile = tempnam(sys_get_temp_dir(), '');
             DB::add('tmp', array(array('host' => $form->getData('db[host]'), 'username' => $form->getData('db[username]'), 'password' => $form->getData('db[password]'))));
             try {
                 DB::get('tmp');
             } catch (DBException $e) {
                 return $form->response(Form::STATUS_ERROR, Lang::get('install.install-connection-error'));
             }
             try {
                 $param = array('{{ $dbname }}' => $form->getData('db[dbname]'), '{{ $prefix }}' => $form->getData('db[prefix]'), '{{ $language }}' => $this->language, '{{ $timezone }}' => $form->getData('timezone'), '{{ $title }}' => Db::get('tmp')->quote($form->getData('title')), '{{ $email }}' => Db::get('tmp')->quote($form->getData('admin[email]')), '{{ $login }}' => Db::get('tmp')->quote($form->getData('admin[login]')), '{{ $password }}' => Db::get('tmp')->quote(Crypto::saltHash($form->getData('admin[password]'), $salt)), '{{ $ip }}' => Db::get('tmp')->quote(App::request()->clientIp()));
                 $sql = strtr(file_get_contents(Plugin::current()->getRootDir() . 'templates/install.sql.tpl'), $param);
                 // file_put_contents($tmpfile, $sql);
                 Db::get('tmp')->query($sql);
                 /**
                  * Create the config file
                  */
                 $param = array('{{ $salt }}' => addcslashes($salt, "'"), '{{ $key }}' => addcslashes($key, "'"), '{{ $iv }}' => addcslashes($iv, "'"), '{{ $configMode }}' => $configMode, '{{ $rooturl }}' => $form->getData('rooturl'), '{{ $host }}' => $form->getData('db[host]'), '{{ $username }}' => $form->getData('db[username]'), '{{ $password }}' => $form->getData('db[password]'), '{{ $dbname }}' => $form->getData('db[dbname]'), '{{ $prefix }}' => $form->getData('db[prefix]'), '{{ $sessionEngine }}' => $form->getData('session'), '{{ $version }}' => $form->getData('version'));
                 $config = strtr(file_get_contents(Plugin::current()->getRootDir() . 'templates/config.php.tpl'), $param);
                 file_put_contents(INCLUDES_DIR . 'config.php', $config);
                 /**
                  * Create etc/dev.php
                  */
                 App::fs()->copy(Plugin::current()->getRootDir() . 'templates/etc-dev.php', ETC_DIR . 'dev.php');
                 /**
                  * Create etc/prod.php
                  */
                 App::fs()->copy(Plugin::current()->getRootDir() . 'templates/etc-prod.php', ETC_DIR . 'prod.php');
                 $form->addReturn('rooturl', $form->getData('rooturl'));
                 return $form->response(Form::STATUS_SUCCESS, Lang::get('install.install-success'));
             } catch (\Exception $e) {
                 return $form->response(Form::STATUS_ERROR, Lang::get('install.install-error'));
             }
         }
     }
 }
Example #11
0
 /**
  * Create a custom theme
  */
 public function create()
 {
     $form = new Form(array('id' => 'create-theme-form', 'labelWidth' => '20em', 'fieldsets' => array('form' => array(new TextInput(array('name' => 'name', 'required' => true, 'pattern' => '/^[\\w\\-]+$/', 'label' => Lang::get($this->_plugin . '.theme-create-name-label'))), new TextInput(array('name' => 'title', 'required' => true, 'label' => Lang::get($this->_plugin . '.theme-create-title-label'))), new SelectInput(array('name' => 'extends', 'invitation' => '-', 'options' => array_map(function ($theme) {
         return $theme->getTitle();
     }, Theme::getAll()), 'label' => Lang::get($this->_plugin . '.theme-create-extends-label'))), new TextInput(array('name' => 'version', 'required' => true, 'pattern' => '/^(\\d+\\.){2,3}\\d+$/', 'label' => Lang::get($this->_plugin . '.theme-create-version-label'), 'default' => '0.0.1')), new TextInput(array('name' => 'author', 'label' => Lang::get($this->_plugin . '.theme-create-author-label')))), 'submits' => array(new SubmitInput(array('name' => 'valid', 'value' => Lang::get('main.valid-button'))), new ButtonInput(array('name' => 'cancel', 'value' => Lang::get('main.cancel-button'), 'onclick' => 'app.dialog("close")')))), 'onsuccess' => 'app.dialog("close"); app.load(app.getUri("available-themes"), { selector : $("#admin-themes-select-tab")} );'));
     if (!$form->submitted()) {
         // Display the form
         return View::make(Theme::getSelected()->getView('dialogbox.tpl'), array('title' => Lang::get($this->_plugin . '.theme-create-title'), 'icon' => 'picture-o', 'page' => $form));
     } else {
         if ($form->check()) {
             $dir = THEMES_DIR . $form->getData('name') . '/';
             if (is_dir($dir)) {
                 $form->error('name', Lang::get($this->_plugin . '.theme-create-name-already-exists-error'));
                 return $form->response(Form::STATUS_CHECK_ERROR, Lang::get($this->_plugin . '.theme-create-name-already-exists-error'));
             }
             // The theme can be created
             try {
                 // Create the main directory
                 if (!mkdir($dir)) {
                     throw new \Exception('Impossible to create the directory ' . $dir);
                 }
                 // Create the directory views
                 if (!mkdir($dir . 'views')) {
                     throw new \Exception('Impossible to create the directory ' . $dir . 'views');
                 }
                 // Get the parent theme
                 $parent = null;
                 if ($form->getData('extends')) {
                     $parent = Theme::get($form->getData('extends'));
                 }
                 // Create the file manifest.json
                 $conf = array('title' => $form->getData('title'), 'version' => $form->getData('version'), 'author' => $form->getData('author'));
                 if ($parent) {
                     $conf['extends'] = $parent->getName();
                 }
                 if (file_put_contents($dir . Theme::MANIFEST_BASENAME, json_encode($conf, JSON_PRETTY_PRINT)) === false) {
                     throw new \Exception('Impossible to create the file ' . $dir . Theme::MANIFEST_BASENAME);
                 }
                 $theme = Theme::get($form->getData('name'));
                 if ($parent) {
                     // The theme extends another one, make a copy of the parent theme except manifest.json and views
                     foreach (glob($parent->getRootDir() . '*') as $element) {
                         if (!in_array(basename($element), array(Theme::MANIFEST_BASENAME, 'views'))) {
                             App::fs()->copy($element, $theme->getRootDir());
                         }
                     }
                 } else {
                     // Create the directory less
                     if (!mkdir($dir . 'less')) {
                         throw new \Exception('Impossible to create the directory ' . $dir . 'less');
                     }
                     // Create the file theme.less
                     if (!touch($theme->getBaseLessFile())) {
                         throw new \Exception('Impossible to create the file ' . $theme->getBaseLessFile());
                     }
                 }
                 return $form->response(Form::STATUS_SUCCESS, Lang::get($this->_plugin . '.theme-create-success'));
             } catch (\Exception $e) {
                 if (is_dir($dir)) {
                     App::fs()->remove($dir);
                 }
                 return $form->response(Form::STATUS_ERROR, DEBUG_MODE ? $e->getMessage() : Lang::get($this->_plugin . '.theme-create-error'));
             }
         }
     }
 }
Example #12
0
 /**
  * Change the current user password
  */
 public function changePassword()
 {
     $params = array('id' => 'update-password-form', 'fieldsets' => array('form' => array(new PasswordInput(array('name' => 'current-password', 'label' => Lang::get($this->_plugin . '.update-password-current-password-label'), 'required' => true)), new PasswordInput(array('name' => 'new-password', 'required' => true, 'label' => Lang::get($this->_plugin . '.update-password-new-password-label'))), new PasswordInput(array('name' => 'password-confirm', 'required' => true, 'label' => Lang::get($this->_plugin . '.update-password-new-password-confirm-label'), 'compare' => 'new-password'))), '_submits' => array(new SubmitInput(array('name' => 'valid', 'value' => Lang::get($this->_plugin . '.valid-button'))), new ButtonInput(array('name' => 'cancel', 'value' => Lang::get($this->_plugin . '.cancel-button'), 'onclick' => 'app.dialog("close")')))), 'onsuccess' => 'app.dialog("close")');
     $form = new Form($params);
     if (!$form->submitted()) {
         return View::make(Theme::getSelected()->getView("dialogbox.tpl"), array('title' => Lang::get($this->_plugin . '.update-password-title'), 'icon' => 'lock', 'page' => $form));
     } else {
         if ($form->check()) {
             $me = Session::getUser();
             if ($me->password != Crypto::saltHash($form->getData('current-password'))) {
                 return $form->response(Form::STATUS_ERROR, Lang::get($this->_plugin . '.update-password-bad-current-password'));
             }
             try {
                 $me->set('password', Crypto::saltHash($form->getData('new-password')));
                 $me->save();
                 return $form->response(Form::STATUS_SUCCESS, Lang::get($this->_plugin . '.update-password-success'));
             } catch (Exception $e) {
                 return $form->response(Form::STATUS_ERROR, DEBUG_MODE ? $e->getMessage() : Lang::get($this->_plugin . '.update-password-error'));
             }
         }
     }
 }
Example #13
0
 /**
  * Create new ChosenAdvertisement entity
  *
  * @param $advertisement
  * @param Form $form
  * @return ChosenAdvertisement
  */
 private function createChosenAdvertisement($advertisement, Form $form, Contact $contact)
 {
     $chosenAdvertisement = $contact->getAdvertisement() ?: new ChosenAdvertisement();
     if ($advertisement) {
         $chosenAdvertisement->setAdvertisement($advertisement);
     } else {
         $allowed = array_keys(Advertisement::$listOfTypes);
         $filtered = array('description' => null, 'choiceType' => null);
         $formData = $form->getData();
         foreach ($formData as $key => $value) {
             if (in_array(str_replace(AdvertisementType::EXTRA_FIELD_SUFFIX, '', $key), $allowed) && !empty($value)) {
                 $filtered['description'] = $value;
                 $filtered['choiceType'] = $key;
             }
         }
         $chosenAdvertisement->setAdvertisement(null);
         $chosenAdvertisement->setDescription($filtered['description']);
         $chosenAdvertisement->setExtraChoiceType(str_replace(AdvertisementType::EXTRA_FIELD_SUFFIX, '', $filtered['choiceType']));
     }
     return $chosenAdvertisement;
 }
Example #14
0
 /**
  * Edit a profile question
  */
 public function edit()
 {
     $q = ProfileQuestion::getByName($this->name);
     $roles = Role::getAll();
     // Get roles associate to this ProfileQuestion in json parameters
     if ($q) {
         $attributesRoles = $q->getRoles();
     } else {
         $attributesRoles = array();
     }
     $allowedTypes = ProfileQuestion::$allowedTypes;
     $param = array('id' => 'profile-question-form', 'model' => 'ProfileQuestion', 'reference' => array('name' => $this->name), 'labelWidth' => '200px', 'fieldsets' => array('general' => array('legend' => Lang::get($this->_plugin . '.profile-question-form-general-legend'), new TextInput(array('name' => 'name', 'unique' => true, 'maxlength' => 32, 'label' => Lang::get($this->_plugin . '.profile-question-form-name-label') . ' ' . Lang::get($this->_plugin . '.profile-question-form-name-description'), 'required' => true)), new SelectInput(array('name' => 'type', 'required' => true, 'options' => array_combine($allowedTypes, array_map(function ($type) {
         return Lang::get($this->_plugin . '.profile-question-form-type-' . $type);
     }, $allowedTypes)), 'label' => Lang::get($this->_plugin . '.profile-question-form-type-label'), 'attributes' => array('e-value' => 'type'))), new CheckboxInput(array('name' => 'displayInRegister', 'label' => Lang::get($this->_plugin . '.profile-question-form-displayInRegister-label'))), new CheckboxInput(array('name' => 'displayInProfile', 'label' => Lang::get($this->_plugin . '.profile-question-form-displayInProfile-label'))), new HiddenInput(array('name' => 'editable', 'value' => 1))), 'parameters' => array('legend' => Lang::get($this->_plugin . '.profile-question-form-parameters-legend'), new ObjectInput(array('name' => 'parameters', 'id' => 'question-form-parameters', 'hidden' => true, 'attributes' => array('e-value' => 'parameters'))), new CheckboxInput(array('name' => 'required', 'independant' => true, 'label' => Lang::get($this->_plugin . '.profile-question-form-required-label'), 'attributes' => array('e-value' => "required"))), new CheckboxInput(array('name' => 'readonly', 'independant' => true, 'label' => Lang::get($this->_plugin . '.profile-question-form-readonly-label'), 'attributes' => array('e-value' => "readonly"))), new DatetimeInput(array('name' => 'minDate', 'independant' => true, 'label' => Lang::get($this->_plugin . '.profile-question-form-minDate-label'), 'attributes' => array('e-value' => "minDate"))), new DatetimeInput(array('name' => 'maxDate', 'independant' => true, 'label' => Lang::get($this->_plugin . '.profile-question-form-maxDate-label'), 'attributes' => array('e-value' => "maxDate"))), new HtmlInput(array('name' => 'parameters-description', 'value' => '<p class="alert alert-info">' . Icon::make(array('icon' => 'exclamation-circle')) . Lang::get($this->_plugin . '.profile-question-form-translation-description') . '</p>')), new TextInput(array('name' => 'label', 'required' => true, 'independant' => true, 'label' => Lang::get($this->_plugin . '.profile-question-form-label-label'), 'default' => $this->name != '_new' ? Lang::get($this->_plugin . '.profile-question-' . $this->name . '-label') : '')), new TextareaInput(array('name' => 'options', 'independant' => true, 'required' => App::request()->getBody('type') == 'select' || App::request()->getBody('type') == 'radio', 'label' => Lang::get($this->_plugin . '.profile-question-form-options-label') . '<br />' . Lang::get($this->_plugin . '.profile-question-form-options-description'), 'labelClass' => 'required', 'attributes' => array('e-value' => "options"), 'cols' => 20, 'rows' => 10))), '_submits' => array(new SubmitInput(array('name' => 'valid', 'value' => Lang::get('main.valid-button'))), new DeleteInput(array('name' => 'delete', 'value' => Lang::get('main.delete-button'), 'notDisplayed' => $this->name == '_new')), new ButtonInput(array('name' => 'cancel', 'value' => Lang::get('main.cancel-button'), 'onclick' => 'app.dialog("close")')))), 'onsuccess' => 'app.dialog("close"); app.load(app.getUri("profile-questions"), {selector : "#admin-questions-tab"})');
     $form = new Form($param);
     if (!$form->submitted()) {
         $this->addJavaScript($this->getPlugin()->getJsUrl('question-form.js'));
         $content = View::make(Plugin::current()->getView("question-form.tpl"), array('form' => $form));
         return View::make(Theme::getSelected()->getView("dialogbox.tpl"), array('title' => Lang::get($this->_plugin . ".users-questions-title"), 'icon' => 'file-word-o', 'page' => $content));
     } else {
         if ($form->submitted() == "delete") {
             $this->delete();
             return $form->response(Form::STATUS_SUCCESS);
         } else {
             if ($form->check()) {
                 $form->register(Form::NO_EXIT);
                 Language::current()->saveTranslations(array('admin' => array('profile-question-' . $form->getData("name") . '-label' => App::request()->getBody('label'))));
                 // Create the lang options
                 if ($form->inputs['options']->required) {
                     $keys = array('admin' => array());
                     foreach (explode(PHP_EOL, $form->getData("options")) as $i => $option) {
                         if (!empty($option)) {
                             $keys['admin']['profile-question-' . $form->getData("name") . '-option-' . $i] = trim($option);
                         }
                     }
                     Language::current()->saveTranslations($keys);
                 }
                 return $form->response(Form::STATUS_SUCCESS);
             }
         }
     }
 }
 function testDataValue()
 {
     $tf = new TableField('TestTableField', 'TestTableField', array('Currency' => 'Currency'), array('Currency' => 'CurrencyField'));
     $form = new Form(new TableFieldTest_Controller(), "Form", new FieldSet($tf), new FieldSet());
     $tf->setValue(array('new' => array('Currency' => array('$1,234.56', '1234.57'))));
     $data = $form->getData();
     // @todo Fix getData()
     //$this->assertEquals($data['TestTableField']['new']['Currency'][0], 1234.56);
     //$this->assertEquals($data['TestTableField']['new']['Currency'][1], 1234.57);
 }
Example #16
0
 /**
  * Create a new plugin structure
  */
 public function create()
 {
     $form = new Form(array('id' => 'new-plugin-form', 'labelWidth' => '20em', 'fieldsets' => array('form' => array(new HtmlInput(array('name' => 'intro', 'value' => '<div class="alert alert-info">' . Lang::get($this->_plugin . '.new-plugin-intro') . '</div>')), new TextInput(array('name' => 'name', 'required' => true, 'pattern' => '/^[\\w\\-]+$/', 'label' => Lang::get($this->_plugin . '.new-plugin-name-label'))), new TextInput(array('name' => 'title', 'required' => true, 'label' => Lang::get($this->_plugin . '.new-plugin-title-label'))), new TextareaInput(array('name' => 'description', 'label' => Lang::get($this->_plugin . '.new-plugin-description-label'))), new TextInput(array('name' => 'version', 'required' => true, 'pattern' => '/^(\\d+\\.){2,3}\\d+$/', 'label' => Lang::get($this->_plugin . '.new-plugin-version-label'), 'default' => '0.0.1')), new TextInput(array('name' => 'author', 'label' => Lang::get($this->_plugin . '.new-plugin-author-label')))), 'submits' => array(new SubmitInput(array('name' => 'valid', 'value' => Lang::get('main.valid-button'))), new ButtonInput(array('name' => 'cancel', 'value' => Lang::get('main.cancel-button'), 'onclick' => 'app.dialog("close")')))), 'onsuccess' => 'app.dialog("close"); app.load(app.getUri("manage-plugins"));'));
     if (!$form->submitted()) {
         // Display the form
         return View::make(Theme::getSelected()->getView('dialogbox.tpl'), array('title' => Lang::get($this->_plugin . '.new-plugin-title'), 'icon' => 'plug', 'page' => $form));
     } else {
         // Create the plugin
         if ($form->check()) {
             if (in_array($form->getData('name'), Plugin::$forbiddenNames)) {
                 $message = Lang::get($this->_plugin . '.new-plugin-forbidden-name', array('forbidden' => implode(', ', Plugin::$forbiddenNames)));
                 $form->error('name', $message);
                 return $form->response(Form::STATUS_CHECK_ERROR, $message);
             }
             $namespace = Plugin::getNamespaceByName($form->getData('name'));
             // Check the plugin does not exists
             foreach (Plugin::getAll(false) as $plugin) {
                 if ($namespace === $plugin->getNamespace()) {
                     // A plugin with the same name already exists
                     $form->error('name', Lang::get($this->_plugin . '.new-plugin-already-exists-error'));
                     return $form->response(Form::STATUS_CHECK_ERROR, Lang::get($this->_plugin . '.new-plugin-already-exists-error'));
                 }
             }
             // The plugin can be created
             $dir = PLUGINS_DIR . $form->getData('name') . '/';
             try {
                 // Create the directories structure
                 if (!mkdir($dir)) {
                     throw new \Exception('Impossible to create the directory ' . $dir);
                 }
                 foreach (array('controllers', 'models', 'lib', 'lang', 'views', 'static', 'static/less', 'static/js', 'static/img', 'widgets') as $subdir) {
                     if (!mkdir($dir . $subdir, 0755, true)) {
                         throw new \Exception('Impossible to create the directory ' . $dir . $subdir);
                     }
                 }
                 // Create the file manifest.json
                 $conf = array('title' => $form->getData('title'), 'description' => $form->getData('description'), 'version' => $form->getData('version'), 'author' => $form->getData('author'), 'dependencies' => array());
                 if (file_put_contents($dir . Plugin::MANIFEST_BASENAME, json_encode($conf, JSON_PRETTY_PRINT)) === false) {
                     throw new \Exception('Impossible to create the file ' . Plugin::MANIFEST_BASENAME);
                 }
                 $plugin = Plugin::get($form->getData('name'));
                 $namespace = $plugin->getNamespace();
                 // Create the file start.php
                 $start = str_replace(array('{{ $namespace }}', '{{ $name }}'), array($namespace, $plugin->getName()), file_get_contents(Plugin::current()->getRootDir() . 'templates/start.tpl'));
                 if (file_put_contents($dir . 'start.php', $start) === false) {
                     throw new \Exceptio('Impossible to create the file start.php');
                 }
                 // Create the file Installer.php
                 $installer = str_replace(array('{{ $namespace }}', '{{ $name }}'), array($namespace, $plugin->getName()), file_get_contents(Plugin::current()->getRootDir() . 'templates/installer.tpl'));
                 if (file_put_contents($dir . 'Installer.php', $installer) === false) {
                     throw new \Exception('Impossible to create the file classes/Installer.php');
                 }
                 // Create the file BaseController.php
                 $controller = str_replace('{{ $namespace }}', $namespace, file_get_contents(Plugin::current()->getRootDir() . 'templates/base-controller.tpl'));
                 if (file_put_contents($dir . 'controllers/BaseController.php', $controller) === false) {
                     throw new \Exception('Impossible to create the file controllers/BaseController.php');
                 }
                 // Create the language file
                 $language = file_get_contents(Plugin::current()->getRootDir() . 'templates/lang.tpl');
                 if (file_put_contents($dir . 'lang/' . $plugin->getName() . '.en.lang', $language) === false) {
                     throw new \Exception('Impossible to create the file lang/' . $plugin->getName() . '.en.lang');
                 }
                 // Create the README file
                 if (touch($dir . 'README.md') === false) {
                     throw new \Exception('Impossible to create the README file');
                 }
                 return $form->response(Form::STATUS_SUCCESS, Lang::get($this->_plugin . '.new-plugin-success'));
             } catch (\Exception $e) {
                 if (is_dir($dir)) {
                     App::fs()->remove($dir);
                 }
                 return $form->response(Form::STATUS_ERROR, DEBUG_MODE ? $e->getMessage() : Lang::get($this->_plugin . '.new-plugin-error'));
             }
         }
     }
 }
 /**
  * Creates a workflow item - a definition, action, transition or any subclasses
  * of these.
  *
  * @param  array $data
  * @param  Form $form
  * @return string
  */
 public function doCreateWorkflowItem($data, $form)
 {
     // assume the form name is in the form CreateTypeForm
     $data = $form->getData();
     $type = 'Workflow' . substr($form->Name(), 6, -4);
     $allowSelf = $type != 'WorkflowAction';
     // determine the class to create - if it is manually specified then use that,
     // falling back to creating an object of the root type if allowed.
     if (isset($data['Class']) && class_exists($data['Class'])) {
         $class = $data['Class'];
         $valid = is_subclass_of($class, $type) || $allowSelf && $class == $type;
         if (!$valid) {
             return new SS_HTTPResponse(null, 400, _t('AdvancedWorkflowAdmin.INVALIDITEM', 'An invalid workflow item was specified.'));
         }
     } else {
         $class = $type;
         if (!$allowSelf) {
             return new SS_HTTPResponse(null, 400, _t('AdvancedWorkflowAdmin.MUSTSPECIFYITEM', 'You must specify a workflow item to create.'));
         }
     }
     // check that workflow actions and transitions have valid parent id values.
     if ($type != 'WorkflowDefinition') {
         $parentId = $data['ParentID'];
         $parentClass = $type == 'WorkflowAction' ? 'WorkflowDefinition' : 'WorkflowAction';
         if (!is_numeric($parentId) || !DataObject::get_by_id($parentClass, $parentId)) {
             return new SS_HTTPResponse(null, 400, _t('AdvancedWorkflowAdmin.INVALIDPARENT', 'An invalid parent was specified.'));
         }
     }
     // if an add form can be returned without writing a new rcord to the database,
     // then just do that
     if (array_key_exists($class, $this->getManagedModels())) {
         $form = $this->{$type}()->AddForm();
         $title = singleton($type)->singular_name();
         if ($type == 'WorkflowTransition') {
             $form->dataFieldByName('ActionID')->setValue($parentId);
         }
     } else {
         $record = new $class();
         $record->Title = sprintf(_t('AdvancedWorkflowAdmin.NEWITEM', 'New %s'), $record->singular_name());
         if ($type == 'WorkflowAction') {
             $record->WorkflowDefID = $parentId;
         } elseif ($type == 'WorkflowTransition') {
             $record->ActionID = $parentId;
         }
         $record->write();
         $control = $this->getRecordControllerClass('WorkflowDefinition');
         $control = new $control($this->{$type}(), null, $record->ID);
         $form = $control->EditForm();
         $title = $record->singular_name();
     }
     return new SS_HTTPResponse($this->isAjax() ? $form->forAjaxTemplate() : $form->forTemplate(), 200, sprintf(_t('AdvancedWorkflowAdmin.CREATEITEM', 'Fill out this form to create a "%s".'), $title));
 }
 public function docreateaccount($data, Form $form)
 {
     $this->registerconfig()->setData($form->getData());
     return Controller::curr()->redirect($this->NextStepLink());
 }
Example #19
0
 /**
  * Submits the form data to the API and returns info for use by register()!
  *
  * Should an error occur will this method append an error message to the form's error collection.
  *
  * @param Form $form
  *
  * @return mixed
  */
 protected function registerUserUsingForm($form)
 {
     $values = $form->getData();
     $userApi = $this->getUserApi();
     $result = false;
     try {
         $result = $userApi->register($values);
     } catch (\Exception $e) {
         $form->addError(new FormError('An error occurred while registering you: ' . $e->getMessage()));
     }
     return $result;
 }
 /**
  * @see Form::getData()
  */
 function getData($key)
 {
     $value = parent::getData($key);
     return $value;
 }
 /**
  * Handles requests to update the shipping
  * @param {array} $data Submitted data
  * @param {Form} $form Submitting form
  * @return {SS_HTTPResponse} Response Object
  */
 public function doUpdateShipping($data, Form $form)
 {
     //form validation has passed by this point, so we can save data
     $form->getConfig()->setData($form->getData());
     return $this->owner->redirectBack();
 }
Example #22
0
 /**
  * Display and treat the form to reset the user's password
  */
 public function resetPassword()
 {
     $form = new Form(array('id' => 'reset-password-form', 'fieldsets' => array('form' => array(new TextInput(array('name' => 'code', 'required' => true, 'label' => Lang::get($this->_plugin . '.reset-pwd-form-code-label'))), new PasswordInput(array('name' => 'password', 'required' => true, 'label' => Lang::get($this->_plugin . '.reset-pwd-form-password-label'), 'encrypt' => array('\\Hawk\\Crypto', 'saltHash'))), new PasswordInput(array('name' => 'confirmation', 'required' => true, 'compare' => 'password', 'label' => Lang::get($this->_plugin . '.reset-pwd-form-confirmation-label')))), 'submits' => array(new SubmitInput(array('name' => 'valid', 'label' => Lang::get($this->_plugin . '.valid-button'))), new ButtonInput(array('name' => 'cancel', 'label' => Lang::get($this->_plugin . '.cancel-button'), 'href' => App::router()->getUri('login'), 'target' => 'dialog')))), 'onsuccess' => 'app.dialog(app.getUri("login"));'));
     if (!$form->submitted()) {
         return Dialogbox::make(array('title' => Lang::get($this->_plugin . '.reset-pwd-form-title'), 'icon' => 'lock-alt', 'page' => $form));
     } else {
         if ($form->check()) {
             // Check the verficiation code
             if ($form->getData('code') !== Crypto::aes256Decode(App::session()->getData('forgottenPassword.code'))) {
                 $form->error('code', Lang::get($this->_plugin . '.reset-pwd-form-bad-verification-code'));
                 return $form->response(Form::STATUS_CHECK_ERROR);
             }
             try {
                 $user = User::getByEmail(App::session()->getData('forgottenPassword.email'));
                 if ($user) {
                     $user->set('password', $form->inputs['password']->dbvalue());
                     $user->save();
                 } else {
                     return $form->response(Form::STATUS_ERROR, App::session()->getData('forgottenPassword.email'));
                 }
                 return $form->response(Form::STATUS_SUCCESS, Lang::get($this->_plugin . '.reset-pwd-form-success'));
             } catch (\Exception $e) {
                 return $form->response(Form::STATUS_ERROR, Lang::get($this->_plugin . '.reset-pwd-form-error'));
             }
         }
     }
 }