示例#1
0
 /**
  * Overrides init() in Zend_Form
  * 
  * @access public
  * @return void
  */
 public function init()
 {
     // init the parent
     parent::init();
     // set the form's method
     $this->setMethod('post');
     $user = Zend_Auth::getInstance()->getIdentity();
     $oldPasswordValidator = new App_Validate_PasswordExists(array('table' => 'backoffice_users', 'field' => 'password', 'treatment' => 'BackofficeUser::hashPassword', 'userPkValue' => $user->id));
     $complexityValidator = new Zend_Validate_Regex('/^(?=.*\\d)(?=.*[a-z|A-Z]).{7,}$/');
     $complexityValidator->setMessage('The selected password does not meet the required complexity requirements');
     $stringLengthValidator = new Zend_Validate_StringLength();
     $stringLengthValidator->setMin(7);
     $stringLengthValidator->setMessage('Your password must be at least 7 characters long');
     $passwordHistoryValidator = new App_Validate_NoPasswordExists(array('table' => 'password_log', 'field' => 'password', 'treatment' => 'BackofficeUser::hashPassword', 'userPkField' => 'user_id', 'userPkValue' => $user->id));
     $oldPassword = new Zend_Form_Element_Password('old_password');
     $oldPassword->setOptions(array('label' => $this->t('Old password'), 'required' => TRUE, 'filters' => array('StringTrim', 'StripTags'), 'validators' => array('NotEmpty', $oldPasswordValidator)));
     $this->addElement($oldPassword);
     $password = new Zend_Form_Element_Password('password');
     $password->setOptions(array('label' => $this->t('New password'), 'required' => TRUE, 'filters' => array('StringTrim', 'StripTags'), 'validators' => array('NotEmpty', $stringLengthValidator, $complexityValidator, $passwordHistoryValidator)));
     $this->addElement($password);
     $sameAsValidator = new App_Validate_SameAs($password);
     $sameAsValidator->setMessage('The two passwords do not coincide.', App_Validate_SameAs::NOT_THE_SAME);
     $retypeNewPassword = new Zend_Form_Element_Password('retype_new_password');
     $retypeNewPassword->setOptions(array('label' => $this->t('Retype new password'), 'required' => TRUE, 'filters' => array('StringTrim', 'StripTags'), 'validators' => array('NotEmpty', $sameAsValidator)));
     $this->addElement($retypeNewPassword);
     $submit = new Zend_Form_Element_Submit('submit');
     $submit->setOptions(array('label' => $this->t('Save password'), 'required' => TRUE));
     $this->addElement($submit);
 }
示例#2
0
 protected function _initFields()
 {
     parent::_initFields();
     $this->add(new Kwf_Form_Field_TextField('title', trlKwf('Title')))->setAllowBlank(false)->setWidth(500);
     $this->add(new Kwf_Form_Field_TextArea('teaser', trlKwf('Teaser')))->setWidth(500)->setHeight(100);
     $this->add(new Kwf_Form_Field_DateField('date', trlKwf('Publication')))->setAllowBlank(false);
     $this->add(new Kwf_Form_Field_Select('author_id', trlKwf('Author')))->setAllowBlank(false)->setWidth(200)->setValues(Kwf_Model_Abstract::getInstance('Kwc_Articles_Directory_AuthorsModel')->getRows());
     $v = new Zend_Validate_Regex('/^[0-9]{4}\\/[0-9]{2}$/');
     $v->setMessage(trlKwf('Please use this format -> Year / Month'), Zend_Validate_Regex::NOT_MATCH);
     $this->add(new Kwf_Form_Field_TextField('vi_nr', trlKwf('VI-Number')))->setWidth(70)->addValidator($v);
     $this->add(Kwc_Abstract_Form::createComponentFormByDbIdTemplate('article_{0}-previewImage', 'previewImage'));
     $columns = $this->add(new Kwf_Form_Container_Columns('is_top'));
     $col = $columns->add(new Kwf_Form_Container_Column());
     $col->setStyle('margin-left: 0px');
     $col->add(new Kwf_Form_Field_Checkbox('is_top_checked', trlKwf('Hot-topic')));
     $col = $columns->add(new Kwf_Form_Container_Column());
     $col->setLabelWidth(50);
     $col->add(new Kwf_Form_Field_DateField('is_top_expire', trlKwf('Ends at')));
     $this->add(new Kwf_Form_Field_Checkbox('read_required', trlKwf('Required reading')));
     $this->add(new Kwf_Form_Field_Checkbox('only_intern', trlKwf('Only intern')));
     $priority = array();
     for ($i = 1; $i <= 10; $i++) {
         $priority[$i] = $i;
     }
     $this->add(new Kwf_Form_Field_Select('priority', trlKwf('Priority')))->setAllowBlank(false)->setValues($priority)->setWidth(40)->setHelpText(trlKwfStatic('For sorting articles if they have same date'));
 }
示例#3
0
 public static function getPreview($page, $crop = false)
 {
     $websiteHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('website');
     $configHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('config');
     $path = (bool) $crop ? $websiteHelper->getPreviewCrop() : $websiteHelper->getPreview();
     if (is_numeric($page)) {
         $page = Application_Model_Mappers_PageMapper::getInstance()->find(intval($page));
     }
     if ($page instanceof Application_Model_Models_Page) {
         $validator = new Zend_Validate_Regex('~^https?://.*~');
         $preview = $page->getPreviewImage();
         if (!is_null($preview)) {
             if ($validator->isValid($preview)) {
                 return $preview;
             } else {
                 $websiteUrl = $configHelper->getConfig('mediaServers') ? Tools_Content_Tools::applyMediaServers($websiteHelper->getUrl()) : $websiteHelper->getUrl();
                 $previewPath = $websiteHelper->getPath() . $path . $preview;
                 if (is_file($previewPath)) {
                     return $websiteUrl . $path . $preview;
                 }
             }
         }
     }
     return $websiteHelper->getUrl() . self::PLACEHOLDER_NOIMAGE;
 }
 public function init()
 {
     Zend_Loader::loadClass('Zend_Validate_Regex');
     $this->translate = Zend_Registry::get('translate');
     //Zend_Form::setDefaultTranslator( Zend_Registry::get('translate') );
     // set method to POST
     $this->setMethod('post');
     /*
      * hidden fields
      */
     $acl = $this->addElement('hidden', 'acl', array('decorators' => $this->elDecorators));
     $role_id = $this->addElement('hidden', 'role_id', array('decorators' => $this->elDecorators));
     /*
      * Order role
      */
     $order = $this->createElement('text', 'order', array('label' => $this->translate->_('Order') . '*', 'required' => true, 'size' => 3, 'maxlength' => 5));
     $order->addValidator('Int')->setRequired(true);
     /*
      * Name role
      */
     $name = $this->createElement('text', 'role_name', array('label' => $this->translate->_('Name') . '*', 'required' => true, 'size' => 30, 'maxlength' => 50));
     $name_validator = new Zend_Validate_Regex('/^[a-zA-Z0-9_]+$/');
     $name_validator->setMessage($this->translate->_('Role name incorrect. This contains only english alphabetical characters, digits and underscore.'));
     $name->addValidator('StringLength', false, array(2, 50))->addValidator($name_validator)->setRequired(true);
     /*
      * Description role
      */
     $description = $this->createElement('textarea', 'description', array('label' => $this->translate->_('Description') . '*', 'required' => true, 'cols' => 50, 'rows' => 3));
     $description->setRequired(true);
     /*
      * Inherited role id
      */
     Zend_Loader::loadClass('Wbroles');
     $table = new Wbroles();
     if ($this->_roleid) {
         $where = $table->getAdapter()->quoteInto('id != ?', $this->_roleid);
     } else {
         $where = null;
     }
     $rows = $table->fetchAll($where, 'id');
     // create element
     $inherit_id = $this->createElement('select', 'inherit_id', array('label' => $this->translate->_('Inherited role'), 'class' => 'ui-select', 'size' => 10));
     $inherit_id->addMultiOption('', '');
     foreach ($rows as $v) {
         $inherit_id->addMultiOption($v['id'], $v['name']);
     }
     unset($table);
     /*
      * submit button
      */
     $submit = new Zend_Form_Element_Submit('submit', array('decorators' => $this->elDecorators, 'id' => 'ok_' . __CLASS__, 'class' => 'prefer_btn', 'label' => $this->translate->_('Submit Form')));
     /*
      * reset button
      */
     $reset = new Zend_Form_Element_Reset('reset', array('decorators' => $this->elDecorators, 'id' => 'reset_' . __CLASS__, 'label' => $this->translate->_('Cancel')));
     /*
      *  add elements to form
      */
     $this->addElements(array($order, $name, $description, $inherit_id, $submit, $reset));
 }
示例#5
0
 public function init()
 {
     Zend_Loader::loadClass('Zend_Validate_Regex');
     // translate
     $this->translate = Zend_Registry::get('translate');
     //Zend_Form::setDefaultTranslator( Zend_Registry::get('translate') );
     // login attempt
     $defNamespace = new Zend_Session_Namespace('Default');
     $use_captcha = $defNamespace->numLoginFails >= self::MAX_LOGIN_ATTEMPT ? TRUE : FALSE;
     $this->setMethod('post');
     // username
     $login = $this->createElement('text', 'login', array('decorators' => $this->elDecorators, 'required' => true, 'label' => $this->translate->_('Username'), 'size' => 25, 'maxlength' => 50));
     $login->addDecorator('FormElements', array('tag' => 'div', 'style' => 'width:10em; background-color:#E0F0FF;'));
     $login_validator = new Zend_Validate_Regex('/^[a-z0-9\\-_@\\.]+$/i');
     $login_validator->setMessage($this->translate->_('Login characters incorrect. Allowed: alphabetical characters, digits, and "- . _ @" characters.'));
     $login->addValidator($login_validator)->addValidator('stringLength', false, array(1, 50))->setRequired(true);
     // password
     $password = $this->createElement('password', 'pwd', array('decorators' => $this->elDecorators, 'required' => true, 'label' => $this->translate->_('Password'), 'size' => 25, 'maxlength' => 50));
     $password->addValidator('StringLength', false, array(1, 50))->setRequired(true);
     // remember me
     $checkbox = $this->createElement('checkbox', 'rememberme', array('decorators' => $this->elDecorators, 'label' => $this->translate->_('Remember me'), 'checked' => 1));
     // login
     $submit = $this->createElement('submit', 'submit', array('decorators' => array('ViewHelper', 'Errors'), 'class' => 'login-btn', 'id' => 'submit', 'label' => $this->translate->_('Log In')));
     // add elements to form
     $this->addElement($login)->addElement($password)->addElement($checkbox)->addElement($submit);
     if ($use_captcha) {
         // create captcha
         $captcha = $this->createElement('captcha', 'captcha', array('label' => $this->translate->_('Type the characters:'), 'captcha' => array('captcha' => 'Figlet', 'wordLen' => 3, 'timeout' => 120)));
         // And finally add some CSRF protection
         $csrf = $this->createElement('hash', 'csrf', array('ignore' => true));
         // add captcha to form
         $this->addElement($captcha)->addElement($csrf);
     }
 }
示例#6
0
 /**
  * Processing object before save data
  *
  * @return Mage_Core_Model_Abstract
  */
 protected function _beforeSave()
 {
     //validate attribute_code
     $validatorAttrCode = new Zend_Validate_Regex(array('pattern' => '/^[a-z][a-z_0-9]{1,254}$/'));
     if (!$validatorAttrCode->isValid($this->getAttributeCode())) {
         Mage::throwException(Mage::helper('mep')->__('Attribute code is invalid. Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'));
     }
     return parent::_beforeSave();
 }
 /**
  * Validate element value
  *
  * @param  array   $data
  * @param  mixed   $context
  * @return boolean
  */
 public function isValid($value, $context = null)
 {
     $v1 = new Zend_Validate_Regex('/^\\d{4}\\-\\d{2}\\-\\d{2}$/');
     $v2 = new Zend_Validate_Date(array('format' => 'Y-m-d'));
     if (!$v1->isValid($value) || !$v2->isValid($value)) {
         $this->_messages = array(self::INVALID_DATE_FORMAT => $this->_templateMessages[self::INVALID_DATE_FORMAT]);
         return false;
     }
     return true;
 }
示例#8
0
 public function isValid($value)
 {
     $validator = new Zend_Validate_Regex(array('pattern' => '~^(http|https|ftp)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\'/\\\\+&amp;%\\$#\\=\\~])*[^\\.\\,\\)\\(\\s]$~'));
     $this->_setValue($value);
     if (!$validator->isValid($value)) {
         $this->_error(self::URL);
         return false;
     }
     return true;
 }
示例#9
0
 protected function _initFields()
 {
     parent::_initFields();
     $this->add(new Kwf_Form_Field_ShowField('original_url', trlKwf('Original Url')))->setData(new Kwf_Data_Trl_OriginalComponent('url'));
     $fs = $this->add(new Kwf_Form_Container_FieldSet(trlKwf('Own Url')));
     $fs->setCheckboxToggle(true);
     $fs->setCheckboxName('own_url');
     $validator = new Zend_Validate_Regex(array('pattern' => Kwc_Advanced_Youtube_Component::REGEX));
     $validator->setMessage(trlKwf('No valid youtube url'), Zend_Validate_Regex::NOT_MATCH);
     $fs->add(new Kwf_Form_Field_UrlField('url', trlKwfStatic('URL')))->addValidator($validator)->setAllowBlank(false)->setWidth(400);
 }
示例#10
0
 public function validate($object)
 {
     $validator = new Zend_Validate_Regex(array('pattern' => '/(^\\d+(\\.{0,1}\\d{0,})(;\\d+(\\.{0,1}\\d{0,}))+$)|^$/'));
     $attrCode = $this->getAttribute()->getAttributeCode();
     $value = $object->getData($attrCode);
     $price = $object->getData('price');
     if (!($price > 0)) {
         if (!$validator->isValid($value)) {
             Mage::throwException('Not correct value. Example: 100;200.33;300.56');
         }
     }
 }
示例#11
0
文件: Date.php 项目: alexukua/opus4
 /**
  * Modified function validates input pattern.
  * @param string $value
  * @return boolean - True only if date input is valid for Opus requirements
  */
 public function isValid($value)
 {
     $this->_setValue($value);
     // Check first if input matches expected pattern
     $datePattern = $this->getInputPattern();
     $validator = new Zend_Validate_Regex($datePattern);
     if (!$validator->isValid($value)) {
         $this->_error(Zend_Validate_Date::FALSEFORMAT);
         return false;
     }
     // Perform check in parent class
     return parent::isValid($value);
 }
示例#12
0
 public function login($username, $password)
 {
     // Remove backslashes
     $username = str_replace("\\", "", $username);
     // filter data from the user
     $f = new Zend_Filter_StripTags();
     $this->user = $f->filter($username);
     $this->pwd = $f->filter($password);
     // Validate credentials
     if (empty($username)) {
         throw new Exception('Invalid username');
     }
     if (empty($password)) {
         throw new Exception('Invalid password');
     }
     // Username can be alphanum with dash, underscore, @, periods and apostrophe
     $usernameValidator = new Zend_Validate_Regex('/^([A-Za-z0-9-_@\\.\']+)$/');
     if (!$usernameValidator->isValid($username)) {
         throw new Exception('Please enter a valid username');
     }
     // setup Zend_Auth adapter for a database table
     $this->db->setFetchMode(Zend_Db::FETCH_ASSOC);
     $authAdapter = new Zend_Auth_Adapter_DbTable($this->db);
     $authAdapter->setTableName('ol_admins');
     $authAdapter->setIdentityColumn('user');
     $authAdapter->setCredentialColumn('password');
     // Set the input credential values to authenticate against
     $authAdapter->setIdentity($username);
     $authAdapter->setCredential(md5($password));
     $authAdapter->getDbSelect()->where('active = ?', 1);
     // MUST be an active account
     // do the authentication
     $result = $this->auth->authenticate($authAdapter);
     $this->db->setFetchMode(Zend_Db::FETCH_OBJ);
     if (!$result->isValid()) {
         throw new Exception('Login failed.');
     }
     //var_dump($authAdapter->getResultRowObject()); exit();
     // Update last login date
     $users = new OneLogin_Acl_Users();
     $users->updateLastLoginDate($username);
     // Define object and set auth information
     $objUser = new stdClass();
     $objUser->user_id = $authAdapter->getResultRowObject()->id;
     $objUser->api_user_username = $username;
     $objUser->api_user_password = $password;
     $objUser->active = $authAdapter->getResultRowObject()->active;
     $this->auth->getStorage()->write($objUser);
 }
示例#13
0
文件: Builder.php 项目: Vitafy/M2E
 private function validate()
 {
     $validatorAttrCode = new Zend_Validate_Regex(array('pattern' => '/^[a-z][a-z_0-9]{1,254}$/'));
     if (!$validatorAttrCode->isValid($this->code)) {
         return false;
     }
     if (empty($this->primaryLabel)) {
         return false;
     }
     /** @var $validatorInputType Mage_Eav_Model_Adminhtml_System_Config_Source_Inputtype_Validator */
     $validatorInputType = Mage::getModel('eav/adminhtml_system_config_source_inputtype_validator');
     if (!$validatorInputType->isValid($this->inputType)) {
         return false;
     }
     return true;
 }
示例#14
0
 /**
  * Ensures that the validator follows expected behavior
  *
  * @return void
  */
 public function testBasic()
 {
     /**
      * The elements of each array are, in order:
      *      - pattern
      *      - expected validation result
      *      - array of test input values
      */
     $valuesExpected = array(array('/[a-z]/', true, array('abc123', 'foo', 'a', 'z')), array('/[a-z]/', false, array('123', 'A')));
     foreach ($valuesExpected as $element) {
         $validator = new Zend_Validate_Regex($element[0]);
         foreach ($element[2] as $input) {
             $this->assertEquals($element[1], $validator->isValid($input));
         }
     }
 }
示例#15
0
文件: Email.php 项目: anunay/stentors
 /**
  * Class constructor.
  * Set the value of the pattern and validate the email.
  *
  * @param  string $regexp <Optional> Regular expression to validate the value.
  *
  * @return void
  */
 public function __construct($regexp = "")
 {
     if (!empty($regexp)) {
         $this->_pattern = $regexp;
     }
     parent::__construct($this->_pattern);
 }
示例#16
0
 /**
  * Validate element value
  *
  * @param  array   $data
  * @param  mixed   $context
  * @return boolean
  */
 public function isValid($value, $context = array())
 {
     // Optional?
     if (empty($value) && $this->_optional) {
         return true;
     }
     $lengthValidator = new Zend_Validate_StringLength(array('min' => 5, 'max' => 62));
     if (!$lengthValidator->isValid($value)) {
         $this->_messages = $lengthValidator->getMessages();
         return false;
     }
     $regexValidator = new Zend_Validate_Regex(array('pattern' => '/^(?!(RAC|LAC|SGSN|RNC|\\.))(\\.?[0-9a-z]+(\\-[0-9a-z]+)*)+(?<!(\\.GPRS$))$/i'));
     if (!$regexValidator->isValid($value)) {
         $this->_messages = $regexValidator->getMessages();
         return false;
     }
     return true;
 }
 public function init()
 {
     Zend_Loader::loadClass('Zend_Validate_Regex');
     Zend_Loader::loadClass('Zend_Validate_EmailAddress');
     // translate
     $this->translate = Zend_Registry::get('translate');
     Zend_Form::setDefaultTranslator(Zend_Registry::get('translate'));
     $this->setMethod('post');
     $this->setDecorators(array(array('ViewScript', array('viewScript' => 'forgot-password.phtml'))));
     /*
      * username
      */
     $login = $this->createElement('text', 'login', array('decorators' => $this->elDecorators, 'required' => true, 'label' => $this->translate->_('Username'), 'size' => 25, 'maxlength' => 50));
     $login->addDecorator('FormElements', array('tag' => 'div', 'style' => 'width:10em; background-color:#E0F0FF;'));
     $login_validator = new Zend_Validate_Regex('/^[a-z0-9\\-_@\\.]+$/i');
     $login_validator->setMessage($this->translate->_('Login characters incorrect. Allowed: alphabetical characters, digits, and "- . _ @" characters.'));
     $login->addValidator($login_validator)->addValidator('stringLength', false, array(1, 50))->setRequired(true);
     /*
      * email
      */
     $email = $this->createElement('text', 'email', array('decorators' => $this->elDecorators, 'required' => true, 'label' => $this->translate->_('Email'), 'size' => 25, 'maxlength' => 50));
     $email->addDecorator('FormElements', array('tag' => 'div', 'style' => 'width:10em; background-color:#E0F0FF;'));
     $email_validator = new Zend_Validate_Regex('/^(.+)@([^@]+)$/');
     // $email_validator = new Zend_Validate_EmailAddress();
     $email_validator->setMessage($this->translate->_('Email address incorrect.'));
     $email->addValidator($email_validator)->setRequired(true);
     /*
      * submit
      */
     $submit = $this->createElement('submit', 'submit', array('decorators' => array('ViewHelper', 'Errors'), 'class' => 'forgot-btn', 'id' => 'submit', 'label' => $this->translate->_('Submit new password')));
     /*
      * create captcha
      */
     $captcha = $this->createElement('captcha', 'captcha', array('label' => $this->translate->_('Type the characters:'), 'captcha' => array('captcha' => 'Figlet', 'wordLen' => 5, 'timeout' => 120)));
     // And finally add some CSRF protection
     $csrf = $this->createElement('hash', 'csrf', array('ignore' => true));
     // add elements to form
     $this->addElement($login)->addElement($email)->addElement($submit)->addElement($captcha)->addElement($csrf);
 }
示例#18
0
文件: Contact.php 项目: niavok/syj
 public function init()
 {
     $formErrors = $this->getView()->getHelper('FormErrors');
     $formErrors->setElementStart("<div%s>")->setElementEnd("</div>")->setElementSeparator("<br>");
     // required needs following string to be translated
     __("Value is required and can't be empty");
     // we are less strict than Zend_Validate_Email because we want a user
     // with a strange email to be able to still contact us with the form
     $emailValidator = new Zend_Validate_Regex('/^[A-Z0-9._-]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\\.[A-Z.]{2,6}$/i');
     $emailValidator->setMessage(__("Invalid email"), $emailValidator::NOT_MATCH);
     $email = array('Text', 'contact_email', array('required' => 'true', 'validators' => array($emailValidator), 'label' => __("Email:")));
     $maxSubjLength = 80;
     $subjectValidator = new Zend_Validate_StringLength(0, $maxSubjLength);
     $subjectValidator->setMessage(__("Subject must be %max% characters long or less", $subjectValidator::TOO_LONG));
     $subject = array('Text', 'contact_subject', array('required' => 'true', 'maxlength' => $maxSubjLength, 'validators' => array($subjectValidator), 'label' => __("Subject:")));
     $contentFilter = new Zend_Filter_PregReplace('/\\r\\n/', "\n");
     $content = array('Textarea', 'contact_content', array('label' => __("Message:"), 'cols' => 40, 'filters' => array($contentFilter), 'required' => 'true', 'rows' => 10));
     $submit = array('Submit', 'contact_submit', array('label' => __("Send"), 'decorators' => array('ViewHelper')));
     $this->addElements(array($email, $subject, $content, $submit));
     // fieldset around form
     $this->addDisplayGroup(array_keys($this->_elements), 'main', array('decorators' => array('FormElements', array('fieldset', array('legend' => __("Send a message"))))));
 }
示例#19
0
 public function isValid($value)
 {
     if (!parent::isValid($value)) {
         return false;
     }
     $validator = new \Zend_Validate_StringLength();
     $validator->setMax(128);
     if (!$validator->isValid($value)) {
         $this->_messages = $validator->getMessages();
         return false;
     }
     return true;
 }
示例#20
0
 protected function _initFields()
 {
     parent::_initFields();
     $validator = new Zend_Validate_Regex(array('pattern' => Kwc_Advanced_Youtube_Component::REGEX));
     $validator->setMessage(trlKwf('No valid youtube url'), Zend_Validate_Regex::NOT_MATCH);
     $this->add(new Kwf_Form_Field_UrlField('url', trlKwf('URL')))->addValidator($validator)->setAllowBlank(false)->setWidth(400);
     if (Kwc_Abstract::getSetting($this->getClass(), 'videoWidth') == Kwc_Advanced_Youtube_Component::USER_SELECT) {
         $cards = new Kwf_Form_Container_Cards('size', trlKwf('Size'));
         $cards->setDefaultValue('fullWidth');
         $cards->setAllowBlank(false);
         $card = $cards->add();
         $card->setTitle(trlKwfStatic('full width'));
         $card->setName('fullWidth');
         $card = $cards->add();
         $card->setTitle(trlKwfStatic('user-defined'));
         $card->setName('custom');
         $card->add(new Kwf_Form_Field_TextField('video_width', trlKwf('Width')))->setAllowBlank(false);
         $this->add($cards);
     }
     $this->add(new Kwf_Form_Field_Select('dimensions', trlKwf('Dimension')))->setDefaultValue('16x9')->setValues(array('16x9' => trlStatic('16:9'), '4x3' => trlStatic('4:3')));
     $this->add(new Kwf_Form_Field_Checkbox('autoplay', trlKwf('Autoplay')));
 }
 public function __construct($options = null)
 {
     parent::__construct($options);
     $status = $options['status'];
     $planedDate = $options['planedDate'];
     $planedTime = $options['planedTime'];
     $collectionsData = $options['filterList'];
     $statusOptions = new Zend_Form_Element_Select('NR_Status');
     $statusOptions->setLabel('Action')->setAttrib('class', 'largeSelect');
     $statusOptions->addMultiOption('1', 'Terminé (Ne pas envoyer à nouveau)');
     $statusOptions->addMultiOption('2', "Envoyez à ceux qui ne l'ont pas reçu");
     $statusOptions->addMultiOption('3', 'Envoyez à tous les destinataires');
     $this->addElement($statusOptions);
     $send = new Zend_Form_Element_Submit('newsletter_send');
     $send->setLabel('Envoyer')->setAttrib('class', 'stdButton')->setOrder(2);
     $this->addActionButton($send);
     $collectionFilters = new Zend_Form_Element_Select('NR_CollectionFiltersID');
     $collectionFilters->setLabel($this->getView()->getCibleText('form_label_collection_name'))->setAttrib('class', 'largeSelect');
     //            $collectionsSelect = new NewsletterFilterCollectionsSet();
     //            $select = $collectionsSelect->select()
     //            ->order('NFCS_Name');
     //            $collectionsData = $collectionsSelect->fetchAll($select);
     $collectionFilters->addMultiOption(0, $this->getView()->getCibleText('newsletter_send_filter_selectOne'));
     foreach ($collectionsData as $key => $collection) {
         $collectionFilters->addMultiOption($key, $collection);
     }
     $this->addElement($collectionFilters);
     // MailingDateScheduled
     $datePicker = new Cible_Form_Element_DatePicker('NR_MailingDate', array('jquery.params' => array('changeYear' => true, 'changeMonth' => true)));
     $datePicker->setLabel($this->getView()->getCibleText('form_label_releaseDate_planned_date'))->setAttrib('class', 'stdTextInput')->setValue($planedDate)->setRequired(true)->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => $this->getView()->getCibleText('validation_message_empty_field'))))->addValidator('Date', true, array('messages' => array('dateNotYYYY-MM-DD' => $this->getView()->getCibleText('validation_message_invalid_date'), 'dateInvalid' => $this->getView()->getCibleText('validation_message_invalid_date'), 'dateFalseFormat' => $this->getView()->getCibleText('validation_message_invalid_date'))));
     $this->addElement($datePicker);
     // MailingTimeScheduled
     $regexValidate = new Zend_Validate_Regex('/^([0-1]\\d|2[0-3]):([0-5]\\d)$/');
     $regexValidate->setMessage('Temps invalide (HH:MM)', 'regexNotMatch');
     $time = new Zend_Form_Element_Text('NR_MailingTime');
     $time->setLabel('HH:MM')->setRequired(true)->addFilter('StripTags')->addFilter('StringTrim')->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => $this->getView()->getCibleText('validation_message_empty_field'))))->addValidator($regexValidate)->setValue($planedTime);
     $this->addElement($time);
 }
示例#22
0
 /**
  * Creates a random password
  *
  * @return void
  */
 protected function _createRandomPassword()
 {
     $i = 0;
     if (empty($this->_randomPassword) || '' == $this->_randomPassword) {
         $randomPassword = '';
         while ($i < $this->_getAttrib('passwordLength')) {
             mt_srand((double) microtime() * 1000000);
             // random limits within ASCII table
             $randNum = mt_rand($this->_getAttrib('lowerAsciiBound'), $this->_getAttrib('upperAsciiBound'));
             if (!in_array($randNum, $this->_notUse)) {
                 $randomPassword = $randomPassword . chr($randNum);
                 $i++;
             }
         }
         // check password against regex
         $validator = new Zend_Validate_Regex($this->_getAttrib('regex'));
         if ($validator->isValid($randomPassword)) {
             $this->_randomPassword = $randomPassword;
         } else {
             $this->_randomPassword = '';
             $this->_createRandomPassword();
         }
     }
 }
 public function saveAction()
 {
     $data = $this->getRequest()->getPost();
     if ($data) {
         /** @var $session Mage_Admin_Model_Session */
         $session = Mage::getSingleton('adminhtml/session');
         $redirectBack = $this->getRequest()->getParam('back', false);
         /* @var $model Mage_Catalog_Model_Entity_Attribute */
         $model = Mage::getModel('catalog/resource_eav_attribute');
         /* @var $helper Mage_Catalog_Helper_Product */
         $helper = Mage::helper('catalogattribute');
         $id = $this->getRequest()->getParam('attribute_id');
         //validate attribute_code
         if (isset($data['attribute_code'])) {
             $validatorAttrCode = new Zend_Validate_Regex(array('pattern' => '/^[a-z][a-z_0-9]{1,254}$/'));
             if (!$validatorAttrCode->isValid($data['attribute_code'])) {
                 $session->addError(Mage::helper('catalogattribute')->__('Attribute code is invalid. Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'));
                 $this->_redirect('*/*/edit', array('attribute_id' => $id, '_current' => true));
                 return;
             }
         }
         //validate frontend_input
         if (isset($data['frontend_input'])) {
             /** @var $validatorInputType Mage_Eav_Model_Adminhtml_System_Config_Source_Inputtype_Validator */
             $validatorInputType = Mage::getModel('eav/adminhtml_system_config_source_inputtype_validator');
             if (!$validatorInputType->isValid($data['frontend_input'])) {
                 foreach ($validatorInputType->getMessages() as $message) {
                     $session->addError($message);
                 }
                 $this->_redirect('*/*/edit', array('attribute_id' => $id, '_current' => true));
                 return;
             }
         }
         if ($id) {
             $model->load($id);
             if (!$model->getId()) {
                 $session->addError(Mage::helper('catalogattribute')->__('This Attribute no longer exists'));
                 $this->_redirect('*/*/');
                 return;
             }
             // entity type check
             if ($model->getEntityTypeId() != $this->_entityTypeId) {
                 $session->addError(Mage::helper('catalogattribute')->__('This attribute cannot be updated.'));
                 $session->setAttributeData($data);
                 $this->_redirect('*/*/');
                 return;
             }
             $data['attribute_code'] = $model->getAttributeCode();
             $data['is_user_defined'] = $model->getIsUserDefined();
             $data['frontend_input'] = $model->getFrontendInput();
         } else {
             /**
              * @todo add to helper and specify all relations for properties
              */
             $data['source_model'] = $helper->getAttributeSourceModelByInputType($data['frontend_input']);
             $data['backend_model'] = $helper->getAttributeBackendModelByInputType($data['frontend_input']);
         }
         //            if (!isset($data['is_configurable'])) {
         //                $data['is_configurable'] = 0;
         ////            }
         //            if (!isset($data['is_filterable'])) {
         //                $data['is_filterable'] = 0;
         //            }
         //            if (!isset($data['is_filterable_in_search'])) {
         //                $data['is_filterable_in_search'] = 0;
         //            }
         if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) {
             $data['backend_type'] = $model->getBackendTypeByInput($data['frontend_input']);
         }
         $defaultValueField = $model->getDefaultValueByInput($data['frontend_input']);
         if ($defaultValueField) {
             $data['default_value'] = $this->getRequest()->getParam($defaultValueField);
         }
         //            if(!isset($data['apply_to'])) {
         //                $data['apply_to'] = array();
         //            }
         //filter
         $data = $this->_filterPostData($data);
         $model->addData($data);
         if (!$id) {
             $model->setEntityTypeId($this->_entityTypeId);
             $model->setIsUserDefined(1);
         }
         //            if ($this->getRequest()->getParam('set') && $this->getRequest()->getParam('group')) {
         //                // For creating product attribute on product page we need specify attribute set and group
         //                $model->setAttributeSetId($this->getRequest()->getParam('set'));
         //                $model->setAttributeGroupId($this->getRequest()->getParam('group'));
         //            }
         try {
             $model->save();
             $session->addSuccess(Mage::helper('catalogattribute')->__('The category attribute has been saved.'));
             /**
              * Clear translation cache because attribute labels are stored in translation
              */
             Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
             $session->setAttributeData(false);
             if ($this->getRequest()->getParam('popup')) {
                 $this->_redirect('adminhtml/catalog_category_atribute/addAttribute', array('id' => $this->getRequest()->getParam('product'), 'attribute' => $model->getId(), '_current' => true));
             } elseif ($redirectBack) {
                 $this->_redirect('*/*/edit', array('attribute_id' => $model->getId(), '_current' => true));
             } else {
                 $this->_redirect('*/*/', array());
             }
             return;
         } catch (Exception $e) {
             $session->addError($e->getMessage());
             $session->setAttributeData($data);
             $this->_redirect('*/*/edit', array('attribute_id' => $id, '_current' => true));
             return;
         }
     }
     $this->_redirect('*/*/');
 }
示例#24
0
 /**
  * Validation rules for store
  *
  * @return \Zend_Validate_Interface|null
  */
 protected function _getValidationRulesBeforeSave()
 {
     $validator = new \Magento\Framework\Validator\DataObject();
     $storeLabelRule = new \Zend_Validate_NotEmpty();
     $storeLabelRule->setMessage(__('Name is required'), \Zend_Validate_NotEmpty::IS_EMPTY);
     $validator->addRule($storeLabelRule, 'name');
     $storeCodeRule = new \Zend_Validate_Regex('/^[a-z]+[a-z0-9_]*$/');
     $storeCodeRule->setMessage(__('The store code may contain only letters (a-z), numbers (0-9) or underscore (_),' . ' and the first character must be a letter.'), \Zend_Validate_Regex::NOT_MATCH);
     $validator->addRule($storeCodeRule, 'code');
     return $validator;
 }
示例#25
0
 /**
  * валидация номера телефона
  * @param string $phoneNumber
  * @return bool
  */
 private function _validate($phoneNumber)
 {
     $pattern = '/^([0-9]+)([0-9]+)$/';
     $vlidator = new Zend_Validate_Regex($pattern);
     return $vlidator->isValid($phoneNumber);
 }
示例#26
0
 /**
  * @return \Magento\Backend\Model\View\Result\Redirect
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function execute()
 {
     $data = $this->getRequest()->getPostValue();
     $resultRedirect = $this->resultRedirectFactory->create();
     if ($data) {
         $setId = $this->getRequest()->getParam('set');
         $attributeSet = null;
         if (!empty($data['new_attribute_set_name'])) {
             $name = $this->filterManager->stripTags($data['new_attribute_set_name']);
             $name = trim($name);
             try {
                 /** @var $attributeSet \Magento\Eav\Model\Entity\Attribute\Set */
                 $attributeSet = $this->buildFactory->create()->setEntityTypeId($this->_entityTypeId)->setSkeletonId($setId)->setName($name)->getAttributeSet();
             } catch (AlreadyExistsException $alreadyExists) {
                 $this->messageManager->addError(__('An attribute set named \'%1\' already exists.', $name));
                 $this->messageManager->setAttributeData($data);
                 return $resultRedirect->setPath('catalog/*/edit', ['_current' => true]);
             } catch (\Magento\Framework\Exception\LocalizedException $e) {
                 $this->messageManager->addError($e->getMessage());
             } catch (\Exception $e) {
                 $this->messageManager->addException($e, __('Something went wrong while saving the attribute.'));
             }
         }
         $redirectBack = $this->getRequest()->getParam('back', false);
         /* @var $model \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
         $model = $this->attributeFactory->create();
         $attributeId = $this->getRequest()->getParam('attribute_id');
         $attributeCode = $this->getRequest()->getParam('attribute_code');
         $frontendLabel = $this->getRequest()->getParam('frontend_label');
         $attributeCode = $attributeCode ?: $this->generateCode($frontendLabel[0]);
         if (strlen($this->getRequest()->getParam('attribute_code')) > 0) {
             $validatorAttrCode = new \Zend_Validate_Regex(['pattern' => '/^[a-z][a-z_0-9]{0,30}$/']);
             if (!$validatorAttrCode->isValid($attributeCode)) {
                 $this->messageManager->addError(__('Attribute code "%1" is invalid. Please use only letters (a-z), ' . 'numbers (0-9) or underscore(_) in this field, first character should be a letter.', $attributeCode));
                 return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]);
             }
         }
         $data['attribute_code'] = $attributeCode;
         //validate frontend_input
         if (isset($data['frontend_input'])) {
             /** @var $inputType \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator */
             $inputType = $this->validatorFactory->create();
             if (!$inputType->isValid($data['frontend_input'])) {
                 foreach ($inputType->getMessages() as $message) {
                     $this->messageManager->addError($message);
                 }
                 return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]);
             }
         }
         if ($attributeId) {
             $model->load($attributeId);
             if (!$model->getId()) {
                 $this->messageManager->addError(__('This attribute no longer exists.'));
                 return $resultRedirect->setPath('catalog/*/');
             }
             // entity type check
             if ($model->getEntityTypeId() != $this->_entityTypeId) {
                 $this->messageManager->addError(__('We can\'t update the attribute.'));
                 $this->_session->setAttributeData($data);
                 return $resultRedirect->setPath('catalog/*/');
             }
             $data['attribute_code'] = $model->getAttributeCode();
             $data['is_user_defined'] = $model->getIsUserDefined();
             $data['frontend_input'] = $model->getFrontendInput();
         } else {
             /**
              * @todo add to helper and specify all relations for properties
              */
             $data['source_model'] = $this->productHelper->getAttributeSourceModelByInputType($data['frontend_input']);
             $data['backend_model'] = $this->productHelper->getAttributeBackendModelByInputType($data['frontend_input']);
         }
         $data += ['is_filterable' => 0, 'is_filterable_in_search' => 0, 'apply_to' => []];
         if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) {
             $data['backend_type'] = $model->getBackendTypeByInput($data['frontend_input']);
         }
         $defaultValueField = $model->getDefaultValueByInput($data['frontend_input']);
         if ($defaultValueField) {
             $data['default_value'] = $this->getRequest()->getParam($defaultValueField);
         }
         if (!$model->getIsUserDefined() && $model->getId()) {
             // Unset attribute field for system attributes
             unset($data['apply_to']);
         }
         $model->addData($data);
         if (!$attributeId) {
             $model->setEntityTypeId($this->_entityTypeId);
             $model->setIsUserDefined(1);
         }
         $groupCode = $this->getRequest()->getParam('group');
         if ($setId && $groupCode) {
             // For creating product attribute on product page we need specify attribute set and group
             $attributeSetId = $attributeSet ? $attributeSet->getId() : $setId;
             $groupCollection = $attributeSet ? $attributeSet->getGroups() : $this->groupCollectionFactory->create()->setAttributeSetFilter($attributeSetId)->load();
             foreach ($groupCollection as $group) {
                 if ($group->getAttributeGroupCode() == $groupCode) {
                     $attributeGroupId = $group->getAttributeGroupId();
                     break;
                 }
             }
             $model->setAttributeSetId($attributeSetId);
             $model->setAttributeGroupId($attributeGroupId);
         }
         try {
             $model->save();
             $this->messageManager->addSuccess(__('You saved the product attribute.'));
             $this->_attributeLabelCache->clean();
             $this->_session->setAttributeData(false);
             if ($this->getRequest()->getParam('popup')) {
                 $requestParams = ['attributeId' => $this->getRequest()->getParam('product'), 'attribute' => $model->getId(), '_current' => true, 'product_tab' => $this->getRequest()->getParam('product_tab')];
                 if (!is_null($attributeSet)) {
                     $requestParams['new_attribute_set_id'] = $attributeSet->getId();
                 }
                 $resultRedirect->setPath('catalog/product/addAttribute', $requestParams);
             } elseif ($redirectBack) {
                 $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $model->getId(), '_current' => true]);
             } else {
                 $resultRedirect->setPath('catalog/*/');
             }
             return $resultRedirect;
         } catch (\Exception $e) {
             $this->messageManager->addError($e->getMessage());
             $this->_session->setAttributeData($data);
             return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]);
         }
     }
     return $resultRedirect->setPath('catalog/*/');
 }
示例#27
0
 function isValid($value)
 {
     $nameValidator = new Zend_Validate_Regex("/^[0-9a-zA-ZÀ-ú]+[0-9A-Za-zÀ-ú\\'\\[\\]\\(\\)\\-\\.\\,\\:\\;\\!\\?\\/ ]{1,120}\$/");
     return $nameValidator->isValid($value);
 }
示例#28
0
 /**
  * Validate attribute code
  *
  * @param string $code
  * @return void
  * @throws \Magento\Framework\Exception\InputException
  */
 protected function validateCode($code)
 {
     $validatorAttrCode = new \Zend_Validate_Regex(['pattern' => '/^[a-z][a-z_0-9]{0,30}$/']);
     if (!$validatorAttrCode->isValid($code)) {
         throw InputException::invalidFieldValue('attribute_code', $code);
     }
 }
示例#29
0
 /**
  * Generate code from label
  *
  * @param string $label
  * @return string
  */
 protected function generateCode($label)
 {
     $code = substr(preg_replace('/[^a-z_0-9]/', '_', $this->_objectManager->create('Magento\\Catalog\\Model\\Product\\Url')->formatUrlKey($label)), 0, 30);
     $validatorAttrCode = new \Zend_Validate_Regex(['pattern' => '/^[a-z][a-z_0-9]{0,29}[a-z0-9]$/']);
     if (!$validatorAttrCode->isValid($code)) {
         $code = 'attr_' . ($code ?: substr(md5(time()), 0, 8));
     }
     return $code;
 }
示例#30
0
 /**
  * @ZF-4352
  */
 public function testNonStringValidation()
 {
     $validator = new Zend_Validate_Regex('/');
     $this->assertFalse($validator->isValid(array(1 => 1)));
 }