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;
         }
     }
 }
Example #2
0
 function testShouldSetNameToCategory()
 {
     $form = new Form(null);
     $this->assertTrue($form->isValid(['name' => 'wheels']));
     $category = $form->getValues();
     $this->assertEquals('wheels', $category['name'], 'should copy name from form to category');
 }
Example #3
0
 public function update($id = '')
 {
     $page = $this->page($id);
     if (!$page) {
         return response::error(l('pages.error.missing'));
     }
     $blueprint = blueprint::find($page);
     $fields = $blueprint->fields($page);
     $oldTitle = (string) $page->title();
     // trigger the validation
     $form = new Form($fields->toArray());
     $form->validate();
     // fetch the data for the form
     $data = pagedata::createByInput($page, $form->serialize());
     // stop at invalid fields
     if (!$form->isValid()) {
         return response::error(l('pages.show.error.form'), 400, array('fields' => $form->fields()->filterBy('error', true)->pluck('name')));
     }
     try {
         $page->update($data);
         // make sure that the sorting number is correct
         if ($page->isVisible()) {
             $num = api::createPageNum($page);
             if ($num !== $page->num()) {
                 if ($num > 0) {
                     $page->sort($num);
                 }
             }
         }
         history::visit($page->id());
         return response::success('success', array('file' => $page->content()->root(), 'data' => $data, 'uid' => $page->uid(), 'uri' => $page->id()));
     } catch (Exception $e) {
         return response::error($e->getMessage());
     }
 }
Example #4
0
 public function index()
 {
     $language = OW::getLanguage();
     $billingService = BOL_BillingService::getInstance();
     $adminForm = new Form('adminForm');
     $element = new TextField('creditValue');
     $element->setRequired(true);
     $element->setLabel($language->text('billingcredits', 'admin_usd_credit_value'));
     $element->setDescription($language->text('billingcredits', 'admin_usd_credit_value_desc'));
     $element->setValue($billingService->getGatewayConfigValue('billingcredits', 'creditValue'));
     $validator = new FloatValidator(0.1);
     $validator->setErrorMessage($language->text('billingcredits', 'invalid_numeric_format'));
     $element->addValidator($validator);
     $adminForm->addElement($element);
     $element = new Submit('saveSettings');
     $element->setValue($language->text('billingcredits', 'admin_save_settings'));
     $adminForm->addElement($element);
     if (OW::getRequest()->isPost()) {
         if ($adminForm->isValid($_POST)) {
             $values = $adminForm->getValues();
             $billingService->setGatewayConfigValue('billingcredits', 'creditValue', $values['creditValue']);
             OW::getFeedback()->info($language->text('billingcredits', 'user_save_success'));
         }
     }
     $this->addForm($adminForm);
     $this->setPageHeading(OW::getLanguage()->text('billingcredits', 'config_page_heading'));
     $this->setPageTitle(OW::getLanguage()->text('billingcredits', 'config_page_heading'));
     $this->setPageHeadingIconClass('ow_ic_app');
 }
Example #5
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());
     }
 }
Example #6
0
 public function settings()
 {
     $adminForm = new Form('adminForm');
     $language = OW::getLanguage();
     $config = OW::getConfig();
     $element = new TextField('autoclick');
     $element->setRequired(true);
     $validator = new IntValidator(1);
     $validator->setErrorMessage($language->text('autoviewmore', 'admin_invalid_number_error'));
     $element->addValidator($validator);
     $element->setLabel($language->text('autoviewmore', 'admin_auto_click'));
     $element->setValue($config->getValue('autoviewmore', 'autoclick'));
     $adminForm->addElement($element);
     $element = new Submit('saveSettings');
     $element->setValue($language->text('autoviewmore', 'admin_save_settings'));
     $adminForm->addElement($element);
     if (OW::getRequest()->isPost()) {
         if ($adminForm->isValid($_POST)) {
             $values = $adminForm->getValues();
             $config = OW::getConfig();
             $config->saveConfig('autoviewmore', 'autoclick', $values['autoclick']);
             OW::getFeedback()->info($language->text('autoviewmore', 'user_save_success'));
         }
     }
     $this->addForm($adminForm);
 }
Example #7
0
 public function testHTMLEntities()
 {
     $input = array('Username' => 'gerard', 'Password' => 'pass&');
     $form = new Form($this->_validators, $input);
     $this->assertTrue($form->isValid());
     $this->assertEquals($form->getHTMLEntities('Password'), 'pass&');
 }
Example #8
0
 public function isValid($data)
 {
     $this->albumPhotosValidator->setAlbumId($data['from-album']);
     if (!empty($data['to-album'])) {
         $this->getElement('to-album')->setRequired()->addValidator(new PHOTO_CLASS_AlbumOwnerValidator());
     }
     return parent::isValid($data);
 }
Example #9
0
 /**
  * Test validate
  */
 public function testIsValid()
 {
     $this->form->add('<div>Test</div>');
     $element_valid = $this->getMockBuilder('Jasny\\FormBuilder\\Element')->getMockForAbstractClass();
     $element_valid->expects($this->exactly(2))->method('isValid')->will($this->returnValue(true));
     $element_invalid = $this->getMockBuilder('Jasny\\FormBuilder\\Element')->getMockForAbstractClass();
     $element_invalid->expects($this->once())->method('isValid')->will($this->returnValue(false));
     $this->form->add($element_valid);
     $this->assertTrue($this->form->isValid());
     $this->form->add($element_invalid);
     $this->assertFalse($this->form->isValid());
 }
Example #10
0
 private function exampleForm()
 {
     $countries = array('Select your country', 'Europe' => array('CZ' => 'Czech Republic', 'FR' => 'France', 'DE' => 'Germany', 'GR' => 'Greece', 'HU' => 'Hungary', 'IE' => 'Ireland', 'IT' => 'Italy', 'NL' => 'Netherlands', 'PL' => 'Poland', 'SK' => 'Slovakia', 'ES' => 'Spain', 'CH' => 'Switzerland', 'UA' => 'Ukraine', 'GB' => 'United Kingdom'), 'AU' => 'Australia', 'CA' => 'Canada', 'EG' => 'Egypt', 'JP' => 'Japan', 'US' => 'United States', '?' => 'other');
     $sex = array('m' => 'male', 'f' => 'female');
     // Step 1: Define form with validation rules
     $form = new Form();
     // group Personal data
     $form->addGroup('Personal data')->setOption('description', 'We value your privacy and we ensure that the information you give to us will not be shared to other entities.');
     $form->addText('name', 'Your name:', 35)->addRule(Form::FILLED, 'Enter your name');
     $form->addText('age', 'Your age:', 5)->addRule(Form::FILLED, 'Enter your age')->addRule(Form::INTEGER, 'Age must be numeric value')->addRule(Form::RANGE, 'Age must be in range from %.2f to %.2f', array(9.9, 100));
     $form->addRadioList('gender', 'Your gender:', $sex);
     $form->addText('email', 'E-mail:', 35)->setEmptyValue('@')->addCondition(Form::FILLED)->addRule(Form::EMAIL, 'Incorrect E-mail Address');
     // ... then check email
     // group Shipping address
     $form->addGroup('Shipping address')->setOption('embedNext', TRUE);
     $form->addCheckbox('send', 'Ship to address')->addCondition(Form::EQUAL, TRUE)->toggle('sendBox');
     // toggle div #sendBox
     // subgroup
     $form->addGroup()->setOption('container', Html::el('div')->id('sendBox'));
     $form->addText('street', 'Street:', 35);
     $form->addText('city', 'City:', 35)->addConditionOn($form['send'], Form::EQUAL, TRUE)->addRule(Form::FILLED, 'Enter your shipping address');
     $form->addSelect('country', 'Country:', $countries)->skipFirst()->addConditionOn($form['send'], Form::EQUAL, TRUE)->addRule(Form::FILLED, 'Select your country');
     // group Your account
     $form->addGroup('Your account');
     $form->addPassword('password', 'Choose password:'******'Choose your password')->addRule(Form::MIN_LENGTH, 'The password is too short: it must be at least %d characters', 3);
     $form->addPassword('password2', 'Reenter password:'******'password'], Form::VALID)->addRule(Form::FILLED, 'Reenter your password')->addRule(Form::EQUAL, 'Passwords do not match', $form['password']);
     $form->addFile('avatar', 'Picture:')->addCondition(Form::FILLED)->addRule(Form::MIME_TYPE, 'Uploaded file is not image', 'image/*');
     $form->addHidden('userid');
     $form->addTextArea('note', 'Comment:', 30, 5);
     // group for buttons
     $form->addGroup();
     $form->addSubmit('submit1', 'Send');
     // Step 2: Check if form was submitted?
     if ($form->isSubmitted()) {
         // Step 2c: Check if form is valid
         if ($form->isValid()) {
             echo '<h2>Form was submitted and successfully validated</h2>';
             $values = $form->getValues();
             Debug::dump($values);
             // this is the end, my friend :-)
             if (empty($disableExit)) {
                 exit;
             }
         }
     } else {
         // not submitted, define default values
         $defaults = array('name' => 'John Doe', 'userid' => 231, 'country' => 'CZ');
         $form->setDefaults($defaults);
     }
     return $form;
 }
Example #11
0
 public function __construct()
 {
     parent::__construct();
     $language = OW::getLanguage();
     $form = new Form("change-user-password");
     $form->setId("change-user-password");
     $oldPassword = new PasswordField('oldPassword');
     $oldPassword->setLabel($language->text('base', 'change_password_old_password'));
     $oldPassword->addValidator(new OldPasswordValidator());
     $oldPassword->setRequired();
     $form->addElement($oldPassword);
     $newPassword = new PasswordField('password');
     $newPassword->setLabel($language->text('base', 'change_password_new_password'));
     $newPassword->setRequired();
     $newPassword->addValidator(new NewPasswordValidator());
     $form->addElement($newPassword);
     $repeatPassword = new PasswordField('repeatPassword');
     $repeatPassword->setLabel($language->text('base', 'change_password_repeat_password'));
     $repeatPassword->setRequired();
     $form->addElement($repeatPassword);
     $submit = new Submit("change");
     $submit->setLabel($language->text('base', 'change_password_submit'));
     $form->setAjax(true);
     $form->addElement($submit);
     if (OW::getRequest()->isAjax()) {
         $result = false;
         if ($form->isValid($_POST)) {
             $data = $form->getValues();
             BOL_UserService::getInstance()->updatePassword(OW::getUser()->getId(), $data['password']);
             $result = true;
         }
         echo json_encode(array('result' => $result));
         exit;
     } else {
         $messageError = $language->text('base', 'change_password_error');
         $messageSuccess = $language->text('base', 'change_password_success');
         $js = " owForms['" . $form->getName() . "'].bind( 'success',\n            function( json )\n            {\n            \tif( json.result == true )\n            \t{\n            \t    \$('#TB_closeWindowButton').click();\n            \t    OW.info('{$messageSuccess}');\n                }\n                else\n                {\n                    OW.error('{$messageError}');\n                }\n\n            } ); ";
         OW::getDocument()->addOnloadScript($js);
         $this->addForm($form);
         $language->addKeyForJs('base', 'join_error_password_not_valid');
         $language->addKeyForJs('base', 'join_error_password_too_short');
         $language->addKeyForJs('base', 'join_error_password_too_long');
         //include js
         $onLoadJs = " window.changePassword = new OW_BaseFieldValidators( " . json_encode(array('formName' => $form->getName(), 'responderUrl' => OW::getRouter()->urlFor("BASE_CTRL_Join", "ajaxResponder"), 'passwordMaxLength' => UTIL_Validator::PASSWORD_MAX_LENGTH, 'passwordMinLength' => UTIL_Validator::PASSWORD_MIN_LENGTH)) . ",\n                                                            " . UTIL_Validator::EMAIL_PATTERN . ", " . UTIL_Validator::USER_NAME_PATTERN . " ); ";
         $onLoadJs .= " window.oldPassword = new OW_ChangePassword( " . json_encode(array('formName' => $form->getName(), 'responderUrl' => OW::getRouter()->urlFor("BASE_CTRL_Edit", "ajaxResponder"))) . " ); ";
         OW::getDocument()->addOnloadScript($onLoadJs);
         $jsDir = OW::getPluginManager()->getPlugin("base")->getStaticJsUrl();
         OW::getDocument()->addScript($jsDir . "base_field_validators.js");
         OW::getDocument()->addScript($jsDir . "change_password.js");
     }
 }
 public function validateForm($form_slug = "default")
 {
     $valid = false;
     if ($_SERVER['REQUEST_METHOD'] == "POST" && Form::isValid($form_slug, false)) {
         $valid = true;
         Form::clearValues($form_slug);
     } else {
         if ($_SERVER['REQUEST_METHOD'] == "GET" || isset($_POST['RM_CLEAR_ERROR']) && $_POST['RM_CLEAR_ERROR'] === 'true') {
             Form::clearErrors($form_slug);
             Form::clearValues($form_slug);
         }
     }
     return $valid;
 }
 /**
  * @param BlockInterface $block
  */
 public function load(BlockInterface $block)
 {
     $this->form = $this->formFactory->create(SubscribeType::class, $this->subscription);
     $this->form->handleRequest($this->request);
     if ($this->form->isValid()) {
         foreach ($this->getMailingLists($block) as $mailingList) {
             $this->subscription->setMailingList($mailingList);
             $this->em->persist($this->subscription);
             $this->em->flush($this->subscription);
             // Reset to add to another mailing list
             $this->em->detach($this->subscription);
             $this->subscription = clone $this->subscription;
             $this->subscription->setId(null);
         }
         $this->subscribed = true;
     }
 }
Example #14
0
 /**
  * @param BlockInterface $block
  */
 public function load(BlockInterface $block)
 {
     $properties = $block->getProperties();
     $opts = array();
     if (isset($properties['responseType']) && $properties['responseType'] == 'redirect') {
         $opts['action'] = $this->router->generate('opifer_mailing_list_subscribe_block', ['id' => $block->getId()]);
     }
     $this->form = $this->formFactory->create(SubscribeType::class, $this->subscription, $opts);
     $this->form->handleRequest($this->request);
     if ($this->form->isValid()) {
         foreach ($this->getMailingLists($block) as $list) {
             $subscription = $this->subscriptionManager->findOrCreate($list, $this->subscription->getEmail());
             $this->subscriptionManager->save($subscription);
         }
         $this->subscribed = true;
     }
 }
Example #15
0
 public function update($id = '')
 {
     $page = $this->page($id);
     if (!$page) {
         return response::error(l('pages.error.missing'));
     }
     $blueprint = blueprint::find($page);
     $fields = $blueprint->fields($page);
     $oldTitle = (string) $page->title();
     // trigger the validation
     $form = new Form($fields->toArray());
     $form->validate();
     // fetch the data for the form
     $data = pagedata::createByInput($page, $form->serialize());
     // stop at invalid fields
     if (!$form->isValid()) {
         return response::error(l('pages.show.error.form'), 400, array('fields' => $form->fields()->filterBy('error', true)->pluck('name')));
     }
     try {
         PageStore::discard($page);
         $page->update($data);
         // make sure that the sorting number is correct
         if ($page->isVisible()) {
             $num = api::createPageNum($page);
             if ($num !== $page->num()) {
                 if ($num > 0) {
                     $page->sort($num);
                 }
             }
         }
         // get the blueprint of the parent page to find the
         // correct sorting mode for this page
         $parentBlueprint = blueprint::find($page->parent());
         // auto-update the uid if the sorting mode is set to zero
         if ($parentBlueprint->pages()->num()->mode() == 'zero') {
             $uid = str::slug($page->title());
             $page->move($uid);
         }
         history::visit($page->id());
         kirby()->trigger('panel.page.update', $page);
         return response::success('success', array('file' => $page->content()->root(), 'data' => $data, 'uid' => $page->uid(), 'uri' => $page->id()));
     } catch (Exception $e) {
         return response::error($e->getMessage());
     }
 }
Example #16
0
 public function fillAccountType($params)
 {
     if (!OW::getUser()->isAuthenticated()) {
         throw new AuthenticateException();
     }
     $user = OW::getUser()->getUserObject();
     $accountType = BOL_QuestionService::getInstance()->findAccountTypeByName($user->accountType);
     if (!empty($accountType)) {
         throw new Redirect404Exception();
     }
     $event = new OW_Event(OW_EventManager::ON_BEFORE_USER_COMPLETE_ACCOUNT_TYPE, array('user' => $user));
     OW::getEventManager()->trigger($event);
     $accounts = $this->getAccountTypes();
     if (count($accounts) == 1) {
         $accountTypeList = array_keys($accounts);
         $firstAccountType = reset($accountTypeList);
         $accountType = BOL_QuestionService::getInstance()->findAccountTypeByName($firstAccountType);
         if ($accountType) {
             $user->accountType = $firstAccountType;
             BOL_UserService::getInstance()->saveOrUpdate($user);
             //BOL_PreferenceService::getInstance()->savePreferenceValue('profile_details_update_stamp', time(), $user->getId());
             $this->redirect(OW::getRouter()->urlForRoute('base_default_index'));
         }
     }
     $form = new Form('accountTypeForm');
     $joinAccountType = new Selectbox('accountType');
     $joinAccountType->setLabel(OW::getLanguage()->text('base', 'questions_question_account_type_label'));
     $joinAccountType->setRequired();
     $joinAccountType->setOptions($accounts);
     $joinAccountType->setHasInvitation(false);
     $form->addElement($joinAccountType);
     $submit = new Submit('submit');
     $submit->addAttribute('class', 'ow_button ow_ic_save');
     $submit->setValue(OW::getLanguage()->text('base', 'continue_button'));
     $form->addElement($submit);
     if (OW::getRequest()->isPost()) {
         if ($form->isValid($_POST)) {
             $data = $form->getValues();
             $this->saveRequiredQuestionsData($data, $user->id);
         }
     } else {
         OW::getDocument()->addOnloadScript(" OW.info(" . json_encode(OW::getLanguage()->text('base', 'complete_profile_info')) . ") ");
     }
     $this->addForm($form);
 }
 public function onChangeLoginFormSubmit(Form $form)
 {
     if (!$form->isValid()) {
         return;
     }
     if ($form['old_password']->getValue() !== Environment::expand('%adminPassword%')) {
         $form->addError(__('Bad old password.'));
         return;
     }
     $content = "<?php\nreturn " . var_export(array('username' => $form['username']->getValue(), 'password' => $form['new_password']->getValue()), TRUE) . ";\n";
     if (!@file_put_contents(Environment::expand('%adminLoginFile%'), $content)) {
         $form->addError(__('Cannot write new login settings.'));
         return;
     }
     Environment::getUser()->signOut(TRUE);
     adminlog::log(__('Changed login credentials, logging out'));
     $this->redirect('this');
     $this->terminate();
 }
Example #18
0
 public function index()
 {
     $language = OW::getLanguage();
     $config = OW::getConfig();
     $adminForm = new Form('adminForm');
     $element = new Selectbox('actionMember');
     $element->setLabel($language->text('grouprss', 'action_member_label'));
     $element->setDescription($language->text('grouprss', 'action_member_desc'));
     $element->setValue($config->getValue('grouprss', 'actionMember'));
     $element->setRequired();
     $element->addOption('admin', $language->text('grouprss', 'site_admin'));
     $element->addOption('owner', $language->text('grouprss', 'group_owner'));
     $element->addOption('both', $language->text('grouprss', 'both_admin_owner'));
     $adminForm->addElement($element);
     $element = new Selectbox('postLocation');
     $element->setLabel($language->text('grouprss', 'post_location_label'));
     $element->setDescription($language->text('grouprss', 'post_location_desc'));
     $element->setValue($config->getValue('grouprss', 'postLocation'));
     $element->setRequired();
     $element->addOption('wall', $language->text('grouprss', 'wall_location'));
     $element->addOption('newsfeed', $language->text('grouprss', 'newsfeed_location'));
     $adminForm->addElement($element);
     $element = new CheckboxField('disablePosting');
     $element->setLabel($language->text('grouprss', 'disable_posting_label'));
     $element->setDescription($language->text('grouprss', 'disable_posting_desc'));
     $element->setValue($config->getValue('grouprss', 'disablePosting'));
     $adminForm->addElement($element);
     $element = new Submit('saveSettings');
     $element->setValue(OW::getLanguage()->text('grouprss', 'admin_save_settings'));
     $adminForm->addElement($element);
     if (OW::getRequest()->isPost()) {
         if ($adminForm->isValid($_POST)) {
             $values = $adminForm->getValues();
             $config->saveConfig('grouprss', 'actionMember', $values['actionMember']);
             $config->saveConfig('grouprss', 'postLocation', $values['postLocation']);
             $config->saveConfig('grouprss', 'disablePosting', $values['disablePosting']);
             GROUPRSS_BOL_FeedService::getInstance()->addAllGroupFeed();
             //OW::getFeedback()->info($language->text('grouprss', 'user_save_success'));
         }
     }
     $this->addForm($adminForm);
 }
Example #19
0
 public function index()
 {
     $language = OW::getLanguage();
     $config = OW::getConfig();
     $adminForm = new Form('adminForm');
     $element = new TextField('logsPerPage');
     $element->setRequired(true);
     $element->setValue($config->getValue('credits', 'logsPerPage'));
     $element->setLabel($language->text('credits', 'logs_per_page'));
     $element->addValidator(new IntValidator(1));
     $adminForm->addElement($element);
     $element = new CheckboxField('enableEmail');
     $element->setLabel(OW::getLanguage()->text('credits', 'admin_enable_email'));
     $element->setDescription(OW::getLanguage()->text('credits', 'admin_enable_email_desc'));
     $element->setValue($config->getValue('credits', 'enableEmail'));
     $adminForm->addElement($element);
     $element = new CheckboxField('enablePM');
     $element->setLabel(OW::getLanguage()->text('credits', 'admin_enable_pm'));
     $element->setDescription(OW::getLanguage()->text('credits', 'admin_enable_pm_desc'));
     $element->setValue($config->getValue('credits', 'enablePM'));
     $adminForm->addElement($element);
     $element = new CheckboxField('enableNotification');
     $element->setLabel(OW::getLanguage()->text('credits', 'admin_enable_notification'));
     $element->setDescription(OW::getLanguage()->text('credits', 'admin_enable_notification_desc'));
     $element->setValue($config->getValue('credits', 'enableNotification'));
     $adminForm->addElement($element);
     $element = new Submit('saveSettings');
     $element->setValue(OW::getLanguage()->text('credits', 'admin_save_settings'));
     $adminForm->addElement($element);
     if (OW::getRequest()->isPost()) {
         if ($adminForm->isValid($_POST)) {
             $values = $adminForm->getValues();
             $config->saveConfig('credits', 'logsPerPage', $values['logsPerPage']);
             $config->saveConfig('credits', 'enableEmail', $values['enableEmail']);
             $config->saveConfig('credits', 'enablePM', $values['enablePM']);
             $config->saveConfig('credits', 'enableNotification', $values['enableNotification']);
             OW::getFeedback()->info($language->text('credits', 'save_sucess_msg'));
         }
     }
     $this->addForm($adminForm);
 }
Example #20
0
 public function index()
 {
     $this->setPageHeading(OW::getLanguage()->text('ganalytics', 'admin_index_heading'));
     $this->setPageHeadingIconClass('ow_ic_gear_wheel');
     $form = new Form('ganalytics_web_id');
     $element = new TextField('web_property_id');
     $form->addElement($element);
     $submit = new Submit('submit');
     $submit->setValue(OW::getLanguage()->text('admin', 'save_btn_label'));
     $form->addElement($submit);
     if (OW::getRequest()->isPost() && $form->isValid($_POST)) {
         $data = $form->getValues();
         if (!empty($data['web_property_id']) && strlen(trim($data['web_property_id'])) > 0) {
             OW::getConfig()->saveConfig('ganalytics', 'web_property_id', trim($data['web_property_id']));
             OW::getFeedback()->info(OW::getLanguage()->text('ganalytics', 'admin_index_property_id_save_success_message'));
         } else {
             OW::getFeedback()->error(OW::getLanguage()->text('ganalytics', 'admin_index_property_id_save_error_message'));
         }
         $this->redirect();
     }
     $element->setValue(OW::getConfig()->getValue('ganalytics', 'web_property_id'));
     $this->addForm($form);
 }
Example #21
0
 public function categories()
 {
     $adminForm = new Form('categoriesForm');
     $language = OW::getLanguage();
     $element = new TextField('categoryName');
     $element->setRequired();
     $element->setInvitation($language->text('advancedphoto', 'admin_category_name'));
     $element->setHasInvitation(true);
     $adminForm->addElement($element);
     $element = new Submit('addCategory');
     $element->setValue($language->text('advancedphoto', 'admin_add_category'));
     $adminForm->addElement($element);
     if (OW::getRequest()->isPost()) {
         if ($adminForm->isValid($_POST)) {
             $values = $adminForm->getValues();
             $name = ucwords(strtolower($values['categoryName']));
             $desc = ucwords(strtolower($values['categoryDesc']));
             if (ADVANCEDPHOTO_BOL_CategoryService::getInstance()->addCategory($name, $desc)) {
                 OW::getFeedback()->info($language->text('advancedphoto', 'admin_add_category_success'));
             } else {
                 OW::getFeedback()->error($language->text('advancedphoto', 'admin_add_category_error'));
             }
             $this->redirect();
         }
     }
     $this->addForm($adminForm);
     $allCategories = array();
     $deleteUrls = array();
     $categories = ADVANCEDPHOTO_BOL_CategoryService::getInstance()->getCategoriesList();
     foreach ($categories as $category) {
         $allCategories[$category->id]['id'] = $category->id;
         $allCategories[$category->id]['name'] = $category->name;
         $deleteUrls[$category->id] = OW::getRouter()->urlFor(__CLASS__, 'delete', array('id' => $category->id));
     }
     $this->assign('allCategories', $allCategories);
     $this->assign('deleteUrls', $deleteUrls);
 }
 public function onTitlePageFormSubmit(Form $form)
 {
     if (!$form->isValid()) {
         return;
     }
     $content = "<?php\nreturn ";
     $content .= var_export($form['content']->getValue(), TRUE);
     $content .= ";";
     if (!@file_put_contents('safe://' . Environment::expand('%titlePageFile%'), $content)) {
         $form->addError(__('Cannot write to file.'));
         return;
     }
     adminlog::log(__('Updated title page'), $form['content']->getValue());
     $this->redirect('this');
     $this->terminate();
 }
Example #23
0
<?php

session_start();
error_reporting(E_ALL);
include "PFBC/Form.php";
if (isset($_POST["form"])) {
    Form::isValid($_POST["form"]);
    header("Location: " . $_SERVER["PHP_SELF"]);
    exit;
}
include "header.php";
$version = file_get_contents("version");
?>

<div class="hero-unit">
	<h1>PHP Form Builder Class</h1>
	<p>This project promotes rapid development of HTML forms through an object-oriented PHP framework.</p>
	<p><a href="http://code.google.com/p/php-form-builder-class/downloads/list" class="btn btn-primary btn-large"><i class="icon-download icon-white"></i> Download PFBC <?php 
echo $version;
?>
</a></p>
</div>

<a name="whats-new-in-3x"></a>
<h2>What's New in 3.x</h2>
<p>Unlike the 2.x branch, version 3.x doesn't represent a complete rewrite from its previous version.  In fact, most of the PHP code for creating
and validating forms has remained unchanged in this new major version release.  So, what's different?</p>

<p>The most significant enhancement is the integration with <a href="http://twitter.github.com/bootstrap/">Bootstrap</a> - a front-end 
framework from Twitter.  Bootstrap incorporates responsive CSS, which means your forms not only look and behave great in the latest 
desktop browser, but in tablet and smartphone browsers as well.  To see responsive CSS in action, resize your browser window and watch how the 
 public function onSendMailFormSubmit(Form $form)
 {
     if (!$form->isValid()) {
         return;
     }
     $active = FALSE;
     try {
         dibi::begin();
         $active = TRUE;
         mapper::order_emails()->insertOne(array('order_id' => $form['order_id']->getValue(), 'subject' => $form['subject']->getValue(), 'body' => $form['body']->getValue()));
         $mail = new Mail();
         $mail->setFrom(Environment::expand('%shopName% <%shopEmail%>'))->addTo($form['to']->getValue())->setSubject($form['subject']->getValue())->setBody($form['body']->getValue())->send();
         adminlog::log(__('Sent e-mail to "%s" with subject "%s"'), $form['to']->getValue(), $form['subject']->getValue());
         $this->redirect('this');
         $this->terminate();
     } catch (RedirectingException $e) {
         dibi::commit();
         throw $e;
     } catch (Exception $e) {
         if ($active) {
             dibi::rollback();
         }
         $form->addError(__('Cannot send e-mail.'));
     }
 }
Example #25
0
 /**
  * Data form
  * @param string
  */
 public function onDataFormSubmit(Form $form)
 {
     // check for validity
     if (!$form->isValid()) {
         return;
     }
     // get data
     $order = Environment::getSession(SESSION_ORDER_NS);
     $order->data = $form->getValues();
     if ($order->data['same_delivery']) {
         foreach ($order->data as $k => $v) {
             if (strncmp($k, 'payer_', strlen('payer_')) === 0) {
                 $order->data['delivery_' . substr($k, strlen('payer_'))] = $v;
             }
         }
     }
     $this->redirect('complete');
 }
Example #26
0
 public function edit($params)
 {
     if (!isset($params['id']) || !($id = (int) $params['id'])) {
         throw new Redirect404Exception();
         return;
     }
     $language = OW::getLanguage();
     $config = OW::getConfig();
     $sponsor = SPONSORS_BOL_Service::getInstance()->findSponsorById($id);
     if (!$sponsor->id) {
         throw new Redirect404Exception();
         return;
     }
     $sponsorForm = new Form('sponsorForm');
     $sponsorForm->setEnctype('multipart/form-data');
     $element = new TextField('sponsorName');
     $element->setRequired(true);
     $element->setLabel($language->text('sponsors', 'sponsor_name'));
     $element->setInvitation($language->text('sponsors', 'sponsor_name_desc'));
     $element->setValue($sponsor->name);
     $element->setHasInvitation(true);
     $sponsorForm->addElement($element);
     $element = new TextField('sponsorEmail');
     $element->setRequired(true);
     $validator = new EmailValidator();
     $validator->setErrorMessage($language->text('sponsors', 'invalid_email_format'));
     $element->addValidator($validator);
     $element->setLabel($language->text('sponsors', 'sponsor_email'));
     $element->setInvitation($language->text('sponsors', 'sponsor_email_desc'));
     $element->setValue($sponsor->email);
     $element->setHasInvitation(true);
     $sponsorForm->addElement($element);
     $element = new TextField('sponsorWebsite');
     $element->setRequired(true);
     $validator = new UrlValidator();
     $validator->setErrorMessage($language->text('sponsors', 'invalid_url_format'));
     $element->addValidator($validator);
     $element->setLabel($language->text('sponsors', 'sponsor_website'));
     $element->setInvitation($language->text('sponsors', 'sponsor_website_desc'));
     $element->setHasInvitation(true);
     $element->setValue($sponsor->website);
     $sponsorForm->addElement($element);
     $element = new TextField('sponsorAmount');
     $element->setRequired(true);
     $minAmount = $config->getValue('sponsors', 'minimumPayment');
     $validator = new FloatValidator(0);
     $validator->setErrorMessage($language->text('sponsors', 'invalid_amount_value'));
     $element->addValidator($validator);
     $element->setLabel($language->text('sponsors', 'sponsor_payment_amount'));
     $element->setInvitation($language->text('sponsors', 'admin_payment_amount_desc'));
     $element->setHasInvitation(true);
     $element->setValue($sponsor->price);
     $sponsorForm->addElement($element);
     $element = new TextField('sponsorValidity');
     $element->setRequired(true);
     $element->setValue($sponsor->validity);
     $validator = new IntValidator(0);
     $validator->setErrorMessage($language->text('sponsors', 'invalid_numeric_format'));
     $element->addValidator($validator);
     $element->setLabel($language->text('sponsors', 'sponsorship_validatity'));
     $element->setInvitation($language->text('sponsors', 'sponsorship_validatity_desc'));
     $element->setHasInvitation(true);
     $sponsorForm->addElement($element);
     $element = new FileField('sponsorImage');
     $element->setLabel($language->text('sponsors', 'sponsorsh_image_file'));
     $sponsorForm->addElement($element);
     $element = new Submit('editSponsor');
     $element->setValue(OW::getLanguage()->text('sponsors', 'edit_sponsor_btn'));
     $sponsorForm->addElement($element);
     if (OW::getRequest()->isPost()) {
         if ($sponsorForm->isValid($_POST)) {
             $values = $sponsorForm->getValues();
             $allowedImageExtensions = array('jpg', 'jpeg', 'gif', 'png', 'tiff');
             $sponsorImageFile = "";
             if (isset($_FILES['sponsorImage']) && in_array(UTIL_File::getExtension($_FILES['sponsorImage']['name']), $allowedImageExtensions)) {
                 $backupPath = OW::getPluginManager()->getPlugin('sponsors')->getUserFilesDir() . $_FILES['sponsorImage']['name'];
                 move_uploaded_file($_FILES['sponsorImage']['tmp_name'], $backupPath);
                 $sponsorImageFile = $_FILES['sponsorImage']['name'];
             }
             $sponsor->name = $values['sponsorName'];
             $sponsor->email = $values['sponsorEmail'];
             $sponsor->website = $values['sponsorWebsite'];
             $sponsor->price = $values['sponsorAmount'];
             if (!empty($sponsorImageFile)) {
                 $sponsor->image = $sponsorImageFile;
             }
             $sponsor->userId = $sponsor->userId;
             $sponsor->status = $sponsor->status;
             $sponsor->validity = $values['sponsorValidity'];
             if (SPONSORS_BOL_Service::getInstance()->addSponsor($sponsor)) {
                 OW::getFeedback()->info(OW::getLanguage()->text('sponsors', 'sponsor_edit_ok'));
             } else {
                 OW::getFeedback()->error(OW::getLanguage()->text('sponsors', 'sponsor_edit_error'));
             }
         }
     }
     $this->addForm($sponsorForm);
     $fields = array();
     foreach ($sponsorForm->getElements() as $element) {
         if (!$element instanceof HiddenField) {
             $fields[$element->getName()] = $element->getName();
         }
     }
     $this->assign('formData', $fields);
     $this->assign('currentLogoImage', OW::getPluginManager()->getPlugin('sponsors')->getUserFilesUrl() . $sponsor->image);
     $this->setPageHeading(OW::getLanguage()->text('sponsors', 'edit_sponsor_heading'));
     $this->setPageTitle(OW::getLanguage()->text('sponsors', 'edit_sponsor_heading'));
     $this->setPageHeadingIconClass('ow_ic_edit');
 }
Example #27
0
 public function index($params)
 {
     $userId = OW::getUser()->getId();
     if (OW::getRequest()->isAjax()) {
         exit;
     }
     if (!OW::getUser()->isAuthenticated() || $userId === null) {
         throw new AuthenticateException();
     }
     $contentMenu = new BASE_CMP_PreferenceContentMenu();
     $contentMenu->getElement('privacy')->setActive(true);
     $this->addComponent('contentMenu', $contentMenu);
     $language = OW::getLanguage();
     $this->setPageHeading($language->text('privacy', 'privacy_index'));
     $this->setPageHeadingIconClass('ow_ic_lock');
     // -- Action form --
     $privacyForm = new Form('privacyForm');
     $privacyForm->setId('privacyForm');
     $actionSubmit = new Submit('privacySubmit');
     $actionSubmit->addAttribute('class', 'ow_button ow_ic_save');
     $actionSubmit->setValue($language->text('privacy', 'privacy_submit_button'));
     $privacyForm->addElement($actionSubmit);
     // --
     $actionList = PRIVACY_BOL_ActionService::getInstance()->findAllAction();
     $actionNameList = array();
     foreach ($actionList as $action) {
         $actionNameList[$action->key] = $action->key;
     }
     $actionValueList = PRIVACY_BOL_ActionService::getInstance()->getActionValueList($actionNameList, $userId);
     $actionValuesEvent = new BASE_CLASS_EventCollector(PRIVACY_BOL_ActionService::EVENT_GET_PRIVACY_LIST);
     OW::getEventManager()->trigger($actionValuesEvent);
     $data = $actionValuesEvent->getData();
     $actionValuesInfo = empty($data) ? array() : $data;
     $optionsList = array();
     $sortOptionsList = array();
     $order = array();
     // -- sort action values
     foreach ($actionValuesInfo as $value) {
         $optionsList[$value['key']] = $value['label'];
         $order[$value['sortOrder']] = $value['key'];
     }
     asort($order);
     foreach ($order as $key) {
         $sortOptionsList[$key] = $optionsList[$key];
     }
     // --
     $resultList = array();
     foreach ($actionList as $action) {
         /* @var $action PRIVACY_CLASS_Action */
         if (!empty($action->label)) {
             $formElement = new Selectbox($action->key);
             $formElement->setLabel($action->label);
             $formElement->setDescription('');
             if (!empty($action->description)) {
                 $formElement->setDescription($action->description);
             }
             $formElement->setOptions($sortOptionsList);
             $formElement->setHasInvitation(false);
             if (!empty($actionValueList[$action->key])) {
                 $formElement->setValue($actionValueList[$action->key]);
                 if (array_key_exists($actionValueList[$action->key], $sortOptionsList)) {
                     $formElement->setValue($actionValueList[$action->key]);
                 } else {
                     if ($actionValueList[$action->key] != 'everybody') {
                         $formElement->setValue('only_for_me');
                     }
                 }
             }
             $privacyForm->addElement($formElement);
             $resultList[$action->key] = $action->key;
         }
     }
     if (OW::getRequest()->isPost()) {
         if ($privacyForm->isValid($_POST)) {
             $values = $privacyForm->getValues();
             $restul = PRIVACY_BOL_ActionService::getInstance()->saveActionValues($values, $userId);
             if ($restul) {
                 OW::getFeedback()->info($language->text('privacy', 'action_action_data_was_saved'));
             } else {
                 OW::getFeedback()->warning($language->text('privacy', 'action_action_data_not_changed'));
             }
             $this->redirect();
         }
     }
     $this->addForm($privacyForm);
     $this->assign('actionList', $resultList);
 }
Example #28
0
// Step 1: Define form with validation rules
$form = new Form();
$form->encoding = 'ISO-8859-1';
// group Personal data
$form->addGroup('Personal data');
$form->addText('name', 'Your name:', 35);
$form->addMultiSelect('country', 'Country:')->skipFirst()->setItems($countries, FALSE);
$form->addHidden('userid');
$form->addTextArea('note', 'Comment:', 30, 5);
// group for buttons
$form->addGroup();
$form->addSubmit('submit1', 'Send');
// Step 2: Check if form was submitted?
if ($form->isSubmitted()) {
    // Step 2c: Check if form is valid
    if ($form->isValid()) {
        header('Content-type: text/html; charset=utf-8');
        echo '<h2>Form was submitted and successfully validated</h2>';
        $values = $form->getValues();
        Debug::dump($values);
        // this is the end, my friend :-)
        if (empty($disableExit)) {
            exit;
        }
    }
} else {
    // not submitted, define default values
    $defaults = array('name' => 'Žluťoučký kůň', 'userid' => 'kůň', 'note' => 'жед', 'country' => 'Česká republika');
    $form->setDefaults($defaults);
}
// Step 3: Render form
Example #29
0
 public function defaultImage()
 {
     $this->contentMenu->getElement('socialsharing_default_image')->setActive(true);
     $settings = new Form('default_image');
     $settings->setEnctype("multipart/form-data");
     $file = new FileField('image');
     $validator = new SocialSharingImageValidator(true);
     $file->addValidator($validator);
     $settings->addElement($file);
     $submit = new Submit('upload');
     $submit->setValue(OW::getLanguage()->text('socialsharing', 'upload'));
     $settings->addElement($submit);
     //printVar($config->getValue('socialsharing', 'facebook'));
     if (OW::getRequest()->isPost()) {
         if ($settings->isValid($_POST)) {
             SOCIALSHARING_BOL_Service::getInstance()->uploadImage($_FILES['image']['tmp_name']);
             OW::getFeedback()->info(OW::getLanguage()->text('socialsharing', 'upload_complite'));
             //Setting succsessfully saved
         } else {
             $message = OW::getLanguage()->text('base', 'upload_file_fail');
             switch ($_FILES['image']['error']) {
                 case UPLOAD_ERR_INI_SIZE:
                     $message = $language->text('base', 'upload_file_max_upload_filesize_error');
                     break;
                 case UPLOAD_ERR_PARTIAL:
                     $message = $language->text('base', 'upload_file_file_partially_uploaded_error');
                     break;
                 case UPLOAD_ERR_NO_FILE:
                     $message = $language->text('base', 'upload_file_no_file_error');
                     break;
                 case UPLOAD_ERR_NO_TMP_DIR:
                     $message = $language->text('base', 'upload_file_no_tmp_dir_error');
                     break;
                 case UPLOAD_ERR_CANT_WRITE:
                     $message = $language->text('base', 'upload_file_cant_write_file_error');
                     break;
                 case UPLOAD_ERR_EXTENSION:
                     $message = $language->text('base', 'upload_file_invalid_extention_error');
                     break;
             }
             OW::getFeedback()->error($message);
         }
         $this->redirect();
     }
     $this->addForm($settings);
     $this->assign('imageUrl', SOCIALSHARING_BOL_Service::getInstance()->getDefaultImageUrl());
 }
Example #30
0
 public function send(array $params = null)
 {
     if (!OW::getUser()->isAuthenticated()) {
         throw new AuthenticateException();
     }
     $receiveUser = $params['id'];
     if (!OW::getUser()->isAuthorized('credits', 'send') || !OW::getAuthorization()->isUserAuthorized($receiveUser, 'credits', 'receive') || !isset($params['id'])) {
         $this->setTemplate(OW::getPluginManager()->getPlugin('base')->getCtrlViewDir() . 'authorization_failed.html');
         return;
     }
     $language = OW::getLanguage();
     $config = OW::getConfig();
     $userId = OW::getUser()->getId();
     $userCredits = USERCREDITS_BOL_CreditsService::getInstance()->getCreditsBalance($userId);
     $this->assign('userCredits', $userCredits);
     $this->assign('receiveUserName', BOL_UserService::getInstance()->getDisplayName($receiveUser));
     $form = new Form('creditForm');
     $element = new TextField('creditPoint');
     $element->setRequired(true);
     $element->setLabel($language->text('credits', 'credits_to_send'));
     $element->addAttribute("style", "width: 100px;");
     $validator = new IntValidator(1, $userCredits);
     $validator->setErrorMessage($language->text('credits', 'credit_value_error'));
     $element->addValidator($validator);
     $form->addElement($element);
     $element = new Submit('sendCredit');
     $element->setValue($language->text('credits', 'send_credits'));
     $form->addElement($element);
     if (OW::getRequest()->isPost()) {
         if ($form->isValid($_POST)) {
             $values = $form->getValues();
             $creditValue = (int) $values['creditPoint'];
             if (CREDITS_BOL_Service::getInstance()->transferCredits($userId, $receiveUser, $creditValue)) {
                 OW::getFeedback()->info($language->text('credits', 'credit_transfer_ok'));
                 $this->redirect(OW::getRouter()->urlForRoute('credits_transfer'));
             } else {
                 OW::getFeedback()->error($language->text('credits', 'credit_transfer_fail'));
             }
         }
     }
     $this->addForm($form);
     $this->setPageHeading($language->text('credits', 'transfer_credits_label'));
     $this->setPageTitle($language->text('credits', 'transfer_credits_label'));
     $this->setPageHeadingIconClass('ow_ic_gear_wheel');
 }