示例#1
0
 /**
  *
  */
 protected function initStatusValidator()
 {
     $validator = new ZendValidator();
     $validator->addValidator($this->getNotEmpty());
     $validator->addValidator($this->getDigits());
     $this->elements['status'] = $validator;
 }
示例#2
0
 /**
  * Make sure the user is valid
  *
  * @return void
  */
 public function isValid($value)
 {
     $valid = true;
     $this->_user = $value;
     $namePartsValidator = new Zend_Validate();
     $namePartsValidator->addValidator(new Zend_Validate_NotEmpty(Zend_Validate_NotEmpty::STRING))->addValidator(new Zend_Validate_Alpha(array('allowWhiteSpace' => true)))->addValidator(new Zend_Validate_StringLength(array('min' => 2)));
     if (!$namePartsValidator->isValid($this->_user->getFirstName())) {
         $valid = false;
         $this->_error($this->_view->translate('The first name must have at least 2 characters and consist only of letters'));
     }
     if (!$namePartsValidator->isValid($this->_user->getLastName())) {
         $valid = false;
         $this->_error($this->_view->translate('The last name must have at least 2 characters and consist only of letters'));
     }
     $emailValidator = new Zend_Validate_EmailAddress();
     if (!$emailValidator->isValid($this->_user->getEmail())) {
         $valid = false;
         $this->_error($this->_view->translate('You must entre a valid email'));
     }
     if ($this->_user->isNew()) {
         $usernameValidator = new Zend_Validate();
         $usernameValidator->addValidator(new Zend_Validate_NotEmpty(Zend_Validate_NotEmpty::STRING))->addValidator(new Zend_Validate_Alnum(array('allowWhiteSpace' => false)))->addValidator(new Zend_Validate_StringLength(array('min' => 5)));
         if (!$usernameValidator->isValid($this->_user->getUsername())) {
             $this->_error($this->_view->translate('The username must have at least 5 characters and contains no white spaces'));
         }
     }
     return $valid;
 }
示例#3
0
 /**
  * Ensures that a validator may break the chain
  *
  * @return void
  */
 public function testBreakChainOnFailure()
 {
     $this->_validator->addValidator(new Zend_ValidateTest_False(), true)->addValidator(new Zend_ValidateTest_False());
     $this->assertFalse($this->_validator->isValid(null));
     $this->assertEquals(array('validation failed'), $this->_validator->getMessages());
     $this->assertEquals(array('error'), $this->_validator->getErrors());
 }
 public function mailAction()
 {
     $error = array();
     $posts = array('First Name' => $_POST['first_name'], 'Last Name' => $_POST['last_name'], 'Email' => $_POST['email'], 'Message' => $_POST['message']);
     $validatorChain = new Zend_Validate();
     $validatorChain->addValidator(new Zend_Validate_NotEmpty());
     $valid_email = new Zend_Validate_EmailAddress();
     if ($valid_email->isValid($posts['Email'])) {
     } else {
         foreach ($valid_email->getMessages() as $message) {
             $error[] = "Email {$message}\n";
         }
     }
     foreach ($posts as $key => $post) {
         if ($validatorChain->isValid($post)) {
         } else {
             foreach ($validatorChain->getMessages() as $message) {
                 $error[] = "{$key} {$message}\n";
             }
         }
     }
     if (count($error) != 0) {
         $this->view->alerts = $error;
     } else {
         $to = '*****@*****.**';
         $subject = 'Email from Illustrated Portland';
         $message = $posts['Message'];
         $headers = "From: {$posts['First Name']} {$posts['Last Name']} <{$posts['Email']}>";
         mail($to, $subject, $message, $headers);
         //$this->view->alerts = array("Thank You! Your message has been sent.");
     }
 }
 /**
  * Save changes to an existing panel. This can be expanded to allow adding of new Panels in the future.
  *
  * @return void
  */
 protected function _savePanel()
 {
     // First of all we need to validate and sanitise the input from the form
     $urlFilter = new Zend_Filter();
     $urlFilter->addFilter(new Zend_Filter_StringTrim());
     $urlFilter->addFilter(new Zend_Filter_StringTrim('/'));
     $requiredText = new Zend_Validate();
     $requiredText->addValidator(new Zend_Validate_NotEmpty());
     $filters = array('id' => 'Digits');
     $validators = array('id' => array('allowEmpty' => true), 'content' => array('allowEmpty' => true));
     $input = new Zend_Filter_Input($filters, $validators, $_POST);
     if ($input->isValid()) {
         // Data is all valid, formatted and sanitized so we can save it in the database
         $panel = new Datasource_Cms_Panels();
         if (!$input->id) {
             // This is a new panel so we need to create a new ID
             // NOT IMPLEMENTED - YET
         } else {
             $panel->saveChanges($input->id, $input->getUnescaped('content'));
             $panelID = $input->id;
         }
         // Changes saved - so send them back with a nice success message
         $this->_helper->getHelper('FlashMessenger')->addMessage(array('saved' => true));
         $this->_helper->getHelper('Redirector')->goToUrl('/cms-admin/panels/edit?id=' . $panelID);
     } else {
         // Invalid data in form
         /*
         print_r($_POST);
         print_r($input->getErrors());
         print_r($input->getInvalid());
         */
     }
 }
示例#6
0
 /**
  * Initializes the form element.
  */
 function init()
 {
     // set label
     $this->setLabel('Email');
     // set required
     $this->setRequired(true);
     // set filter
     $this->addFilter('StringTrim');
     // add validator for max string length
     $this->addValidator('StringLength', false, array(0, 256));
     // add validator for email addresses
     $emailValidator = new Zend_Validate_EmailAddress(Zend_Validate_Hostname::ALLOW_DNS | Zend_Validate_Hostname::ALLOW_LOCAL);
     $this->addValidator($emailValidator);
     // add validator for beeing unique in the database
     $validator = new Zend_Validate();
     $message = 'The email is already in the database, please check if you are already registered.';
     $userTableValidator = new Zend_Validate_Db_NoRecordExists('Auth_User', 'email');
     $userTableValidator->setMessage($message);
     if (!empty($this->_excludeId)) {
         $userTableValidator->setExclude(array('field' => 'id', 'value' => $this->_excludeId));
     }
     $registrationTableValidator = new Zend_Validate_Db_NoRecordExists('Auth_Registration', 'email');
     $registrationTableValidator->setMessage($message);
     // chainvalidators and add to field
     $validator->addValidator($userTableValidator)->addValidator($registrationTableValidator);
     $this->addValidator($validator);
 }
示例#7
0
 /**
  * Initializes the form element.
  */
 function init()
 {
     $this->setLabel('Email');
     // set required
     $this->setRequired(true);
     // set filter
     $this->addFilter('StringTrim');
     // add validator for max string length
     $this->addValidator('StringLength', false, array(0, 256));
     // add validator for email addresses
     $this->addValidator('emailAddress');
     // add validator for beeing unique in the database
     $validator = new Zend_Validate();
     $message = 'The email is already in the database, please check if you are already registered.';
     $participantsTableValidator = new Meetings_Form_Validate_Email('Meetings_Participants', 'email');
     $participantsTableValidator->setMessage($message);
     $participantsTableValidator->setMeetingId($this->_meetingId);
     if (!empty($this->_excludeId)) {
         $participantsTableValidator->setExcludeId($this->_excludeId);
     }
     $registrationTableValidator = new Meetings_Form_Validate_Email('Meetings_Registration', 'email');
     $registrationTableValidator->setMessage($message);
     $registrationTableValidator->setMeetingId($this->_meetingId);
     // chainvalidators and add to field
     $validator->addValidator($participantsTableValidator)->addValidator($registrationTableValidator);
     $this->addValidator($validator);
 }
示例#8
0
 /**
  * Initializes the form element.
  */
 function init()
 {
     // set filter
     $this->addFilter('StringTrim');
     // set required
     $this->setRequired(true);
     // set label
     $this->setLabel(ucfirst($this->getName()));
     // set validator for lowercase or regular alnum
     if (Daiquiri_Config::getInstance()->auth->lowerCaseUsernames) {
         $this->addValidator(new Daiquiri_Form_Validator_LowerCaseAlnum());
     } else {
         $this->addValidator(new Daiquiri_Form_Validator_AlnumUnderscore());
     }
     // add validator for min and max string length
     $minLength = Daiquiri_Config::getInstance()->auth->usernameMinLength;
     $this->addValidator('StringLength', false, array($minLength, 256));
     // add validator for beeing unique in the database
     $validator = new Zend_Validate();
     $message = 'The username is in use, please use another username.';
     $userTableValidator = new Zend_Validate_Db_NoRecordExists('Auth_User', 'username');
     $userTableValidator->setMessage($message);
     if (!empty($this->_excludeId)) {
         $userTableValidator->setExclude(array('field' => 'id', 'value' => $this->_excludeId));
     }
     $registrationTableValidator = new Zend_Validate_Db_NoRecordExists('Auth_Registration', 'username');
     $registrationTableValidator->setMessage($message);
     $appTableValidator = new Zend_Validate_Db_NoRecordExists('Auth_Apps', 'appname');
     $appTableValidator->setMessage($message);
     $validator->addValidator($userTableValidator)->addValidator($registrationTableValidator)->addValidator($appTableValidator);
     $this->addValidator($validator);
 }
 public function indexAction()
 {
     $emailValidator = new Zend_Validate_EmailAddress();
     $nameValidator = new Zend_Validate_NotEmpty(array(Zend_Validate_NotEmpty::STRING, Zend_Validate_NotEmpty::SPACE));
     $password1_Validator = new Zend_Validate();
     $password1_Validator->addValidator(new Zend_Validate_StringLength(array('min' => 6, 'max' => 12)))->addValidator(new Zend_Validate_Alnum());
     $password2_Validator = new Zend_Validate();
     $password2_Validator->addValidator(new Zend_Validate_StringLength(array('min' => 6, 'max' => 12)))->addValidator(new Zend_Validate_Alnum());
     $captcha = new Zend_Captcha_Image();
     $captcha->setName('captchaword')->setFont(APPLICATION_PATH . '/data/arial.ttf')->setFontSize(28)->setImgDir(APPLICATION_PATH . '/../public/img')->setImgUrl('/img')->setWordLen(5)->setDotNoiseLevel(20)->setExpiration(300);
     $request = $this->getRequest();
     $post = $request->getPost();
     // $passwordIdentical = new Zend_Validate_Identical(array('token' => $post['password1']));
     $messages = array();
     $error = array();
     $noValiError = true;
     if ($this->getRequest()->isPost()) {
         if (!$emailValidator->isValid($post['user-email'])) {
             $error['user-emailVali'] = '請輸入正確的Email帳號';
             $noValiError = false;
         }
         if (!$nameValidator->isValid($post['name'])) {
             $error['nameVali'] = '姓名必填';
             $noValiError = false;
         }
         if (!$password1_Validator->isValid($post['password1'])) {
             $error['password1_Vali'] = '1.密碼長度需介於6~12之間,而且只能使用數字、英文';
             $noValiError = false;
         }
         if (!$password2_Validator->isValid($post['password2'])) {
             $error['password2_Vali'] = '1.密碼長度需介於6~12之間,而且只能使用數字、英文';
             $noValiError = false;
         }
         if (isset($post['password1']) && isset($post['password2']) && !($post['password1'] == $post['password2'])) {
             $error['passwordIdentical'] = '2.密碼輸入不同';
             $noValiError = false;
         }
         if (!($post['agree'] == 1)) {
             $error['agreeVali'] = '需同意服務條款及隱私權政策,才可以註冊';
             $noValiError = false;
         }
         if (!$captcha->isValid($post['captchaword'])) {
             $error['captchawordVali'] = '認證碼輸入錯誤';
             $noValiError = false;
         }
         if ($noValiError) {
             // register process
             $this->_signup($post);
             $this->view->messages = $post;
             $this->redirect('index/index');
         } else {
             $this->_genCaptcha($captcha);
             $this->view->error = $error;
             $this->view->messages = $post;
         }
     } else {
         $this->_genCaptcha($captcha);
     }
 }
示例#10
0
 /**
  * Constructor.
  *
  * @param  string  $host OPTIONAL Hostname of remote connection (default: 127.0.0.1)
  * @param  integer $port OPTIONAL Port number (default: null)
  * @throws Zend_Mail_Protocol_Exception
  * @return void
  */
 public function __construct($host = '127.0.0.1', $port = null)
 {
     $this->_validHost = new Zend_Validate();
     $this->_validHost->addValidator(new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_ALL));
     if (!$this->_validHost->isValid($host)) {
         require_once 'Zend/Mail/Protocol/Exception.php';
         throw new Zend_Mail_Protocol_Exception(join(', ', $this->_validHost->getMessages()));
     }
     $this->_host = $host;
     $this->_port = $port;
 }
 public function __construct($arrParam = array(), $options = null)
 {
     //////////////////////////////////
     //Kiem tra Name /////////////
     //////////////////////////////////
     if ($arrParam['action'] == 'add') {
         $options = array('table' => 'da_album', 'field' => 'album_name');
     } elseif ($arrParam['action'] == 'edit') {
         $options = array('table' => 'da_album', 'field' => 'album_name', 'exclude' => array('field' => 'id', 'value' => $arrParam['id']));
     }
     $validator = new Zend_Validate();
     $validator->addValidator(new Zend_Validate_NotEmpty(), true)->addValidator(new Zend_Validate_StringLength(3, 100), true);
     if (!$validator->isValid($arrParam['album_name'])) {
         $message = $validator->getMessages();
         $this->_messageError['album_name'] = 'Tên album: ' . current($message);
         $arrParam['album_name'] = '';
     }
     //////////////////////////////////
     //Kiem tra Picture small ///////////
     //////////////////////////////////
     $upload = new Zend_File_Transfer_Adapter_Http();
     $fileInfo = $upload->getFileInfo('picture');
     $fileName = $fileInfo['picture']['name'];
     if (!empty($fileName)) {
         $upload->addValidator('Extension', true, array('jpg', 'gif', 'png'), 'picture');
         $upload->addValidator('Size', true, array('min' => '2KB', 'max' => '1000KB'), 'picture');
         if (!$upload->isValid('picture')) {
             $message = $upload->getMessages();
             $this->_messageError['picture'] = 'Hình ảnh đại diện: ' . current($message);
         }
     }
     //////////////////////////////////
     //Kiem tra Order /////////////
     //////////////////////////////////
     $validator = new Zend_Validate();
     $validator->addValidator(new Zend_Validate_StringLength(1, 10), true)->addValidator(new Zend_Validate_Digits(), true);
     if (!$validator->isValid($arrParam['order'])) {
         $message = $validator->getMessages();
         $this->_messageError['order'] = 'Sắp xếp: ' . current($message);
         $arrParam['order'] = '';
     }
     //////////////////////////////////
     //Kiem tra Status /////////////
     //////////////////////////////////
     if (empty($arrParam['status']) || !isset($arrParam['status'])) {
         $arrParam['status'] = 0;
     }
     //========================================
     // TRUYEN CAC GIA TRI DUNG VAO MANG $_arrData
     //========================================
     $this->_arrData = $arrParam;
 }
示例#12
0
 public function __construct()
 {
     $idValidator = new Zend_Validate();
     $idValidator->addValidator(new Zend_Validate_StringLength(array('min' => 3)));
     $idValidator->addValidator(new Zend_Validate_Regex('/^[A-Za-z0-9\\/:_]+$/'));
     $resourceValidator = new Zend_Validate();
     $resourceValidator->addValidator(new Zend_Validate_StringLength(array('min' => 8)));
     $resourceValidator->addValidator(new Zend_Validate_Regex('/^[A-Z]+[a-z0-9]{1,}_[A-Z]+[A-Z0-9a-z]{1,}::[A-Za-z_0-9]{1,}$/'));
     $attributeValidator = new Zend_Validate();
     $attributeValidator->addValidator(new Zend_Validate_StringLength(array('min' => 3)));
     $attributeValidator->addValidator(new Zend_Validate_Regex('/^[A-Za-z0-9\\/_]+$/'));
     $textValidator = new Zend_Validate_StringLength(array('min' => 3, 'max' => 50));
     $titleValidator = $tooltipValidator = $textValidator;
     $actionValidator = $moduleDepValidator = $configDepValidator = $attributeValidator;
     $this->_validators['id'] = $idValidator;
     $this->_validators['title'] = $titleValidator;
     $this->_validators['action'] = $actionValidator;
     $this->_validators['resource'] = $resourceValidator;
     $this->_validators['dependsOnModule'] = $moduleDepValidator;
     $this->_validators['dependsOnConfig'] = $configDepValidator;
     $this->_validators['toolTip'] = $tooltipValidator;
 }
示例#13
0
 /**
  * Add rule to be applied to a validation scope
  *
  * @param \Zend_Validate_Interface $validator
  * @param string $fieldName Field name to apply validation to, or empty value to validate entity as a whole
  * @return \Magento\Framework\Validator\DataObject
  * @api
  */
 public function addRule(\Zend_Validate_Interface $validator, $fieldName = '')
 {
     if (!array_key_exists($fieldName, $this->_rules)) {
         $this->_rules[$fieldName] = $validator;
     } else {
         $existingValidator = $this->_rules[$fieldName];
         if (!$existingValidator instanceof \Zend_Validate) {
             $compositeValidator = new \Zend_Validate();
             $compositeValidator->addValidator($existingValidator);
             $this->_rules[$fieldName] = $compositeValidator;
         }
         $this->_rules[$fieldName]->addValidator($validator);
     }
     return $this;
 }
示例#14
0
 public function isValidText($value, $maxLenghtValue)
 {
     $validator = new Zend_Validate();
     // Create a validator chain and add validators to it
     $validator->addValidator(new Zend_Validate_NotEmpty())->addValidator(new Zend_Validate_StringLength(1, $maxLenghtValue));
     // Validate the value
     if ($validator->isValid($value)) {
         return true;
     } else {
         // value failed validation; print reasons
         foreach ($validator->getMessages() as $message) {
             return array('Error' => $message);
         }
     }
 }
示例#15
0
文件: Record.php 项目: niieani/nandu
	/**
	 * Attach a Zend_Validate validator chain to a field
	 *
	 * @param string $field
	 * @param array $validators Array of Zend_Validate
	 */
	protected function setColumnValidators($field, array $validators) {
		$validate = new Zend_Validate();
		foreach ($validators as $validator) {
			$validate->addValidator($validator);
		}
		$extra = $this->getColumnOption($field, 'extra');
		$options = array('validators' => $validators, 'validate' => $validate);
		if (is_array($extra)) {
			$extra = array_merge($extra, $options);
		} elseif ($extra === null) {
			$extra = $options;
		} else {
			throw new Doctrine_Record_Exception("Column '%s' 'extra' option is neighter an array nor NULL, don't know what to do.", Doctrine_Core::ERR_UNSUPPORTED);
		}
		$this->setColumnOption($field, 'extra', $extra);
	}
 /**
  * login page : 1. Validation 2. Login process
  */
 public function indexAction()
 {
     $passwordValidator = new Zend_Validate();
     $passwordValidator->addValidator(new Zend_Validate_StringLength(array('min' => 6, 'max' => 12)))->addValidator(new Zend_Validate_Alnum());
     $emailValidator = new Zend_Validate_EmailAddress();
     $captcha = new Zend_Captcha_Image();
     $captcha->setName('captchaword')->setFont(APPLICATION_PATH . '/data/arial.ttf')->setFontSize(28)->setImgDir(APPLICATION_PATH . '/../public/img')->setImgUrl('/img')->setWordLen(5)->setDotNoiseLevel(20)->setExpiration(300);
     $request = $this->getRequest();
     $post = $request->getPost();
     $messages = array();
     $noValiError = true;
     if ($this->getRequest()->isPost()) {
         if (!$passwordValidator->isValid($post['password'])) {
             $messages['passwordVali'] = '密碼長度需介於6~12之間,而且只能使用數字、英文';
             $noValiError = false;
         }
         if (!$emailValidator->isValid($post['user-email'])) {
             $messages['user-emailVali'] = '請輸入正確的Email帳號';
             $noValiError = false;
         }
         if (!$captcha->isValid($post['captchaword'])) {
             $messages['captchawordVali'] = '認證碼輸入錯誤';
             $noValiError = false;
         }
         $messages['password'] = $post['password'];
         $messages['user-email'] = $post['user-email'];
         if ($noValiError) {
             // login process
             $this->_checkAccount($post);
             $this->view->messages = $messages;
         } else {
             $this->_genCaptcha($captcha);
             $this->view->messages = $messages;
         }
     } else {
         $this->_genCaptcha($captcha);
     }
     if (Zend_Auth::getInstance()->hasIdentity() && $noValiError) {
         $this->redirect('index/index');
     }
 }
 public function loadById($globalData, $object_id)
 {
     $validatorChain = new Zend_Validate();
     $validatorChain->addValidator(new Zend_Validate_Int());
     if (!$validatorChain->isValid($object_id)) {
         return NULL;
     }
     $db = $globalData->takeConnection();
     $table = new RealEstateAgency_Database_Area_Table(array('db' => $db));
     $where = $db->quoteInto('obj_id = ?', $object_id);
     $rowset = $table->fetchAll($where);
     $row = $rowset->current();
     if ($row) {
         $new_object = new RealEstateAgency_Object_Area();
         $new_object->setGlobalData($globalData);
         $new_object->fillByZendRow($row);
         return $new_object;
     } else {
         return NULL;
     }
 }
示例#18
0
 /**
  * Check if data is valid
  * @access public
  * @return bool
  */
 public function isValid()
 {
     $this->_data = array();
     $this->_error = array();
     $values = $this->_options['values'];
     //validate the input data - username, password and email will be also filtered
     $validatorChain = new Zend_Validate();
     $dotFilter = new Dot_Filter();
     //validate details parameters
     if (array_key_exists('details', $values)) {
         $validatorChain->addValidator(new Zend_Validate_StringLength(array('min' => $this->option->validate->details->lengthMin)));
         $this->_callFilter($validatorChain, $values['details']);
     }
     //validate username
     if (array_key_exists('username', $values)) {
         $validatorChain = new Zend_Validate();
         $validatorChain->addValidator(new Zend_Validate_Alnum())->addValidator(new Zend_Validate_StringLength($this->option->validate->details->lengthMin, $this->option->validate->details->lengthMax));
         $this->_callFilter($validatorChain, $values['username']);
         if (in_array($this->_options['action'], array('add', 'update'))) {
             $uniqueError = $this->_validateUnique('username', $values['username']['username']);
             $this->_error = array_merge($this->_error, $uniqueError);
         }
     }
     //validate email
     if (array_key_exists('email', $values)) {
         $validatorEmail = new Zend_Validate_EmailAddress();
         $this->_callFilter($validatorEmail, $values['email']);
         if (in_array($this->_options['action'], array('add', 'update'))) {
             $uniqueError = $this->_validateUnique('email', $values['email']['email']);
             $this->_error = array_merge($this->_error, $uniqueError);
         }
     }
     //validate enum
     if (array_key_exists('enum', $values)) {
         $validatorEnum = new Zend_Validate_InArray(explode(',', $values['enum'][0]));
         unset($values['enum'][0]);
         $this->_callFilter($validatorEnum, $values['enum']);
     }
     //validate phone
     if (array_key_exists('phone', $values)) {
         //filter, then valid, so we wont use _callFilter() method
         $phoneOptions = array('countryCode' => 'US');
         $phoneOptions['values'] = $values['phone']['phone'];
         $dotValidatorPhone = new Dot_Validate_Phone($phoneOptions);
         if ($dotValidatorPhone->isValid()) {
             $this->_data = array_merge($this->_data, array('phone' => $dotValidatorPhone->getData()));
         } else {
             $this->_error = array_merge($this->_error, array('phone' => $dotValidatorPhone->getError()));
         }
     }
     //validate password
     if (array_key_exists('password', $values) && isset($values['password']['password'])) {
         if (isset($values['password']['password2']) && $values['password']['password'] != $values['password']['password2']) {
             $this->_error['password'] = $this->option->errorMessage->passwordTwice;
         } else {
             if (isset($values['password']['password2'])) {
                 unset($values['password']['password2']);
             }
             $validatorChain = new Zend_Validate();
             $validatorChain->addValidator(new Zend_Validate_StringLength($this->option->validate->password->lengthMin, $this->option->validate->password->lengthMax));
             $this->_callFilter($validatorChain, $values['password']);
         }
     }
     // validate captcha
     if (array_key_exists('captcha', $values)) {
         if (!array_key_exists('recaptcha_response_field', $values['captcha']) || strlen($values['captcha']['recaptcha_response_field']) == 0) {
             $this->_error = array_merge($this->_error, array('Secure Image' => $this->option->errorMessage->captcha));
         } else {
             // validate secure image code
             try {
                 // just in frontend is recaptcha included.
                 // if you want it in other modules, add getRecaptcha() method from frontend/View.php in others View.php of the modules
                 $view = View::getInstance();
                 $result = $view->getRecaptcha()->verify($values['captcha']['recaptcha_challenge_field'], $values['captcha']['recaptcha_response_field']);
                 if (!$result->isValid()) {
                     $this->_error = array_merge($this->_error, array('Secure Image' => $this->option->errorMessage->captcha));
                 }
             } catch (Zend_Exception $e) {
                 $this->_error = array_merge($this->_error, array('Secure Image' => $this->option->errorMessage->captcha . ' ' . $e->getMessage()));
             }
         }
     }
     if (empty($this->_error)) {
         return true;
     } else {
         return false;
     }
 }
示例#19
0
 /**
  * @return void
  */
 public function init()
 {
     $objZMail = new \Zend_Mail();
     $this->setObjZMail($objZMail);
     $objZValidate = new \Zend_Validate();
     $objZValidate->addValidator(new Zend_Validate_EmailAddress());
     $this->setValidators($objZValidate);
     $config = \Zend_Registry::get('configs');
     $this->setConfig($config['resources']['mail']);
 }
示例#20
0
 /**
  * @param \Zend_File_Transfer_Adapter_Http|\Zend_Validate $object
  * @param \Magento\Catalog\Model\Product\Option $option
  * @param array $fileFullPath
  * @return \Zend_File_Transfer_Adapter_Http|\Zend_Validate $object
  * @throws \Magento\Framework\Exception\InputException
  */
 protected function buildImageValidator($object, $option, $fileFullPath = null)
 {
     $dimensions = [];
     if ($option->getImageSizeX() > 0) {
         $dimensions['maxwidth'] = $option->getImageSizeX();
     }
     if ($option->getImageSizeY() > 0) {
         $dimensions['maxheight'] = $option->getImageSizeY();
     }
     if (count($dimensions) > 0) {
         if ($fileFullPath !== null && !$this->isImage($fileFullPath)) {
             throw new \Magento\Framework\Exception\InputException(__('File \'%1\' is not an image.', $option->getTitle()));
         }
         $object->addValidator(new \Zend_Validate_File_ImageSize($dimensions));
     }
     // File extension
     $allowed = $this->parseExtensionsString($option->getFileExtension());
     if ($allowed !== null) {
         $object->addValidator(new \Zend_Validate_File_Extension($allowed));
     } else {
         $forbidden = $this->parseExtensionsString($this->getConfigData('forbidden_extensions'));
         if ($forbidden !== null) {
             $object->addValidator(new \Zend_Validate_File_ExcludeExtension($forbidden));
         }
     }
     $object->addValidator(new \Zend_Validate_File_FilesSize(['max' => $this->fileSize->getMaxFileSize()]));
     return $object;
 }
示例#21
0
 function editAction()
 {
     $errors = array();
     $users_table = new Users();
     $users_roles_table = new UsersRoles();
     $request = new Bolts_Request($this->getRequest());
     $countries_table = new Countries();
     $this->view->countries = $countries_table->getCountriesArray('Choose a country...');
     $roles_table = new Roles();
     $roles = $roles_table->fetchAll(NULL, "shortname ASC");
     $arRoles = array();
     foreach ($roles as $role) {
         if (!strpos($role->shortname, "-base")) {
             $arRoles[$role->id] = $role->description;
         }
     }
     $this->view->roles = $arRoles;
     $is_new = true;
     $user = array();
     if ($request->has('username')) {
         $obUser = $users_table->fetchByUsername($request->username);
         if (!is_null($obUser)) {
             $is_new = false;
             $user_roles = $users_roles_table->fetchAll($users_roles_table->select()->where("username = ?", $obUser->username));
             if (count($user_roles) > 0) {
                 $tmp_selected = array();
                 foreach ($user_roles as $user_role) {
                     $tmp_selected[] = $user_role->role_id;
                 }
                 $this->view->selected_roles = $tmp_selected;
             }
             $user = $obUser->toArray();
         }
     }
     $this->view->is_new = $is_new;
     if ($is_new) {
         // defaults for form fields
         $user['username'] = "";
         $user['full_name'] = "";
         $user['aboutme'] = "";
     }
     $pre_render = $this->_Bolts_plugin->doFilter($this->_mca . "_pre_render", array('user' => $user, 'request' => $this->_request));
     // FILTER HOOK
     $user = $pre_render['user'];
     foreach ($pre_render as $key => $value) {
         if ($key != "user") {
             $this->view->{$key} = $value;
         }
     }
     // $tags = unserialize($user['tags']);
     if ($this->getRequest()->isPost()) {
         $errors = array();
         $request->stripTags(array('full_name', 'email', 'newpassword', 'confirm'));
         // $request->stripTags(array('full_name', 'email', 'newpassword', 'confirm', 'aboutme'));
         $user['username'] = $request->username;
         $user['email'] = $request->email;
         $user['password'] = $request->newpassword;
         $user['confirm'] = $request->confirm;
         $user['full_name'] = $request->full_name;
         $user['birthday'] = $birthday = strtotime($request->Birthday_Day . $request->Birthday_Month . $request->Birthday_Year);
         $user['gender'] = $request->gender;
         $user['country_code'] = $request->country_code;
         $user['aboutme'] = $request->aboutme;
         // validate username
         $username_validator = new Zend_Validate();
         $username_validator->addValidator(new Zend_Validate_StringLength(1, Bolts_Registry::get('username_length')));
         $username_validator->addValidator(new Zend_Validate_Alnum());
         if (!$username_validator->isValid($user['username'])) {
             $show_username = "******" . $user['username'] . "'";
             if (trim($user['username']) == "") {
                 $show_username = "******" . $this->_T("empty") . "]";
             }
             $errors[] = $this->_T("%s isn't a valid username. (Between %d and %d characters, only letters and numbers)", array($show_username, 1, Bolts_Registry::get('username_length')));
         }
         if ($is_new) {
             $user_where = $users_table->getAdapter()->quoteInto('username = ?', $user['username']);
             if ($users_table->getCountByWhereClause($user_where) > 0) {
                 $errors[] = $this->_T("The username '%s' is already in use", $user['username']);
             }
         }
         // validate email
         if (!Bolts_Validate::checkEmail($user['email'])) {
             $errors[] = $this->_T("Email is not valid");
         }
         // check to see if email is in use already by someone else
         if ($users_table->isEmailInUse($user['email'], $user['username'])) {
             $errors[] = $this->_T("Email already in use");
         }
         // if password isn't blank, validate it
         if ($user['password'] != "") {
             if (!Bolts_Validate::checkLength($user['password'], 6, Bolts_Registry::get('password_length'))) {
                 $errors[] = $this->_T("Password must be between 6 and 32 characters");
             }
             // if password is set, make sure it matches confirm
             if ($user['password'] != $user['confirm']) {
                 $errors[] = $this->_T("Passwords don't match");
             }
         }
         // convert birthday_ts to mysql date
         $birthday = date("Y-m-d H:i:s", $user['birthday']);
         $params = array('request' => $request, 'user' => $user, 'errors' => $errors);
         // upload new avatar image if present
         if (array_key_exists('filedata', $_FILES)) {
             if ($_FILES['filedata']['tmp_name'] != '') {
                 $destination_path = Bolts_Registry::get('upload_path') . "/" . $user['username'] . "/original";
                 if (!is_dir($destination_path)) {
                     mkdir($destination_path, 0777, true);
                     Bolts_Log::report("Creating user folder at " . $destination_path, null, Zend_Log::DEBUG);
                 }
                 if (file_exists($destination_path . "/avatar")) {
                     unlink($destination_path . "/avatar");
                     Bolts_Log::report("Deleted existing user avatar from " . $destination_path, null, Zend_Log::DEBUG);
                 } else {
                     Bolts_Log::report("User avatar did not exist in " . $destination_path, null, Zend_Log::DEBUG);
                 }
                 move_uploaded_file($_FILES['filedata']['tmp_name'], $destination_path . "/avatar");
                 Users::clearUserCache($user['username']);
                 Bolts_Log::report("User avatar uploaded to " . $destination_path, null, Zend_Log::DEBUG);
                 $params['user']['hasnewfile'] = true;
             } else {
                 $params['user']['hasnewfile'] = false;
             }
         }
         $additional = $this->_Bolts_plugin->doFilter($this->_mca . "_pre_save", $params);
         // FILTER HOOK
         $errors = $additional['errors'];
         $user = $additional['user'];
         $users_roles_table->delete($users_roles_table->getAdapter()->quoteInto("username = ?", $user['username']));
         foreach ($request->role_ids as $role_id) {
             $role_data = array("username" => $user['username'], "role_id" => $role_id);
             $users_roles_table->insert($role_data);
         }
         if (count($errors) == 0) {
             /**********  Commented out due to Plug-in compatibility issues. 
             			$data = array(
             				'email' => $user['email'],
             				'birthday' => $birthday,
             				'aboutme' => nl2br($user['aboutme']),
             				'gender' => $user['gender'],
             				'full_name' => $user['full_name'],
             				'country_code' => $user['country_code'],
             				'last_modified_on' => date(DB_DATETIME_FORMAT),
             			);
             			**********/
             $user['birthday'] = $birthday;
             $user['aboutme'] = nl2br($user['aboutme']);
             $user['last_modified_on'] = date(DB_DATETIME_FORMAT);
             // This is a hold-over value from the form.
             unset($user['confirm']);
             if ($user['password'] != "") {
                 #$data['password'] = $user['password'];
             } else {
                 unset($user['password']);
             }
             if ($is_new) {
                 // TODO - stuff?  really?
                 $stuff = array('request' => $request, 'user' => $user, 'errors' => $errors);
                 $additional1 = $this->_Bolts_plugin->doFilter($this->_mca, $stuff);
                 // FILTER HOOK
                 $errors = $additional1['errors'];
                 $user = $additional1['user'];
                 $data['username'] = $user['username'];
                 #$data['created_on'] = date(DB_DATETIME_FORMAT);
                 $user['created_on'] = date(DB_DATETIME_FORMAT);
                 $users_table->insert($user);
                 $this->view->success = "Profile created.";
             } else {
                 $where = $users_table->getAdapter()->quoteInto('username = ?', $user['username']);
                 #$users_table->update($data, $where);
                 $users_table->update($user, $where);
                 $this->view->success = "Profile updated.";
             }
         } else {
             $this->view->errors = $errors;
         }
     }
     $this->view->end_year = -Bolts_Registry::get('minimum_registration_age');
     $this->view->genders = Bolts_Common::getGenderArray();
     $user['aboutme'] = Bolts_Common::br2nl($user['aboutme']);
     $this->view->user = $user;
 }
示例#22
0
 if (!$val->isValid($_POST['username'])) {
     $errors['username'] = '******' . 'User name must be 6-15 letters or numbers' . '</p>';
 } else {
     // Check if username already exists
     //
     $sql = $dbRead->quoteInto('SELECT user_id FROM users WHERE username = ?', $_POST['username']);
     $result = $dbRead->fetchAll($sql);
     if ($result) {
         $errors['username'] = '******' . $_POST['username'] . ' already exists' . '</p>';
     }
 }
 // Validate password
 //
 $length->setMin(8);
 $val = new Zend_Validate();
 $val->addValidator($length);
 $val->addValidator(new Zend_Validate_Alnum());
 if (!$val->isValid($_POST['password'])) {
     $errors['password'] = '******' . 'Password must be 8-15 characters' . '</p>';
 }
 // Confirm passwords
 //
 $val = new Zend_Validate_Identical($_POST['password']);
 if (!$val->isValid($_POST['conf_password'])) {
     $errors['conf_password'] = '******' . 'Passwords don\'t match' . '</p>';
 }
 // Validate email
 //
 $val = new Zend_Validate_EmailAddress();
 if (!$val->isValid($_POST['email'])) {
     $errors['email'] = '<p class="add_user_error">' . 'Invalid email address' . '</p>';
示例#23
0
 public function savenewpermissionAction()
 {
     $auth = Zend_Auth::getInstance();
     if ($auth->hasIdentity()) {
         Zend_Session::regenerateId();
         if (!$this->getRequest()->isXmlHttpRequest()) {
             $this->view->msg = 'Not Ajax Request';
             $this->_forward('error', 'error');
         } else {
             $filterChain = new Zend_Filter();
             $filterChain->addFilter(new Zend_Filter_Digits());
             $default = null;
             $zoneId = $filterChain->filter($_POST['ZONE_ID']);
             $contextId = $filterChain->filter($_POST['CONTEXT_ID']);
             $agentId = $filterChain->filter($_POST['AGENT_ID']);
             $dataObjectId = $filterChain->filter($_POST['DATA_OBJECT_ID']);
             $provide = $filterChain->filter(Utility::convertCheckBoxValue(isset($_POST['PROVIDE']) ? $_POST['PROVIDE'] : $default));
             $subscribe = $filterChain->filter(Utility::convertCheckBoxValue(isset($_POST['SUBSCRIBE']) ? $_POST['SUBSCRIBE'] : $default));
             $request = $filterChain->filter(Utility::convertCheckBoxValue(isset($_POST['REQUEST']) ? $_POST['REQUEST'] : $default));
             $respond = $filterChain->filter(Utility::convertCheckBoxValue(isset($_POST['RESPOND']) ? $_POST['RESPOND'] : $default));
             $add = $filterChain->filter(Utility::convertCheckBoxValue(isset($_POST['ADD']) ? $_POST['ADD'] : $default));
             $change = $filterChain->filter(Utility::convertCheckBoxValue(isset($_POST['CHANGE']) ? $_POST['CHANGE'] : $default));
             $delete = $filterChain->filter(Utility::convertCheckBoxValue(isset($_POST['DELETE']) ? $_POST['DELETE'] : $default));
             $validatorChain = new Zend_Validate();
             $validatorChain->addValidator(new Zend_Validate_Digits())->addValidator(new Zend_Validate_Between(array('min' => 0, 'max' => 1)));
             /*
             if (!$validatorChain->isValid($provide) &&
             	!$validatorChain->isValid($subscribe) &&
             	!$validatorChain->isValid($request) &&
             	!$validatorChain->isValid($respond) &&
             	!$validatorChain->isValid($add) &&
             	!$validatorChain->isValid($change) &&
             	!$validatorChain->isValid($delete)
             ) {
             	$this->view->msg = 'Data Validation Error';
             	$this->_forward('error', 'error');			
             }
             */
             $exist = Permission::checkIfPermissionExist($zoneId, $agentId, $contextId, $dataObjectId);
             if ($exist) {
                 $this->view->msg = 'Permission Already Exists';
                 $this->_forward('error', 'error');
             } else {
                 Permission::addPermission($zoneId, $agentId, $contextId, $dataObjectId, $provide, $subscribe, $add, $change, $delete, $request, $respond);
                 $this->render('ajaxsuccessjson');
             }
         }
     } else {
         if (!$this->getRequest()->isXmlHttpRequest()) {
             $this->view->msg = 'Not Ajax Request';
             $this->_forward('error', 'error');
         } else {
             $this->view->msg = 'Invalid User';
             $this->_forward('error', 'error');
         }
     }
 }
示例#24
0
文件: Input.php 项目: cljk/kimai
 /**
  * @param array $validatorRule
  * @return void
  */
 protected function _validateRule(array $validatorRule)
 {
     /**
      * Get one or more data values from input, and check for missing fields.
      * Apply defaults if fields are missing.
      */
     $data = array();
     foreach ((array) $validatorRule[self::FIELDS] as $key => $field) {
         if (array_key_exists($field, $this->_data)) {
             $data[$field] = $this->_data[$field];
         } else {
             if (isset($validatorRule[self::DEFAULT_VALUE])) {
                 /** @todo according to this code default value can't be an array. It has to be reviewed */
                 if (!is_array($validatorRule[self::DEFAULT_VALUE])) {
                     // Default value is a scalar
                     $data[$field] = $validatorRule[self::DEFAULT_VALUE];
                 } else {
                     // Default value is an array. Search for corresponding key
                     if (isset($validatorRule[self::DEFAULT_VALUE][$key])) {
                         $data[$field] = $validatorRule[self::DEFAULT_VALUE][$key];
                     } else {
                         if ($validatorRule[self::PRESENCE] == self::PRESENCE_REQUIRED) {
                             // Default value array is provided, but it doesn't have an entry for current field
                             // and presence is required
                             $this->_missingFields[$validatorRule[self::RULE]][] = $this->_getMissingMessage($validatorRule[self::RULE], $field);
                         }
                     }
                 }
             } else {
                 if ($validatorRule[self::PRESENCE] == self::PRESENCE_REQUIRED) {
                     $this->_missingFields[$validatorRule[self::RULE]][] = $this->_getMissingMessage($validatorRule[self::RULE], $field);
                 }
             }
         }
     }
     /**
      * If any required fields are missing, break the loop.
      */
     if (isset($this->_missingFields[$validatorRule[self::RULE]]) && count($this->_missingFields[$validatorRule[self::RULE]]) > 0) {
         return;
     }
     /**
      * Evaluate the inputs against the validator chain.
      */
     if (count((array) $validatorRule[self::FIELDS]) > 1) {
         if (!$validatorRule[self::ALLOW_EMPTY]) {
             $emptyFieldsFound = false;
             $errorsList = array();
             $messages = array();
             foreach ($data as $fieldKey => $field) {
                 // if there is no Zend_Validate_NotEmpty instance in the rules, we will use the default
                 if (!($notEmptyValidator = $this->_getNotEmptyValidatorInstance($validatorRule))) {
                     $notEmptyValidator = $this->_getValidator('NotEmpty');
                     $notEmptyValidator->setMessage($this->_getNotEmptyMessage($validatorRule[self::RULE], $fieldKey));
                 }
                 if (!$notEmptyValidator->isValid($field)) {
                     foreach ($notEmptyValidator->getMessages() as $messageKey => $message) {
                         if (!isset($messages[$messageKey])) {
                             $messages[$messageKey] = $message;
                         } else {
                             $messages[] = $message;
                         }
                     }
                     $errorsList[] = $notEmptyValidator->getErrors();
                     $emptyFieldsFound = true;
                 }
             }
             if ($emptyFieldsFound) {
                 $this->_invalidMessages[$validatorRule[self::RULE]] = $messages;
                 $this->_invalidErrors[$validatorRule[self::RULE]] = array_unique(call_user_func_array('array_merge', $errorsList));
                 return;
             }
         }
         if (!$validatorRule[self::VALIDATOR_CHAIN]->isValid($data)) {
             $this->_invalidMessages[$validatorRule[self::RULE]] = $validatorRule[self::VALIDATOR_CHAIN]->getMessages();
             $this->_invalidErrors[$validatorRule[self::RULE]] = $validatorRule[self::VALIDATOR_CHAIN]->getErrors();
             return;
         }
     } else {
         if (count($data) > 0) {
             // $data is actually a one element array
             $fieldNames = array_keys($data);
             $fieldName = reset($fieldNames);
             $field = reset($data);
             $failed = false;
             if (!is_array($field)) {
                 $field = array($field);
             }
             // if there is no Zend_Validate_NotEmpty instance in the rules, we will use the default
             if (!($notEmptyValidator = $this->_getNotEmptyValidatorInstance($validatorRule))) {
                 $notEmptyValidator = $this->_getValidator('NotEmpty');
                 $notEmptyValidator->setMessage($this->_getNotEmptyMessage($validatorRule[self::RULE], $fieldName));
             }
             if ($validatorRule[self::ALLOW_EMPTY]) {
                 $validatorChain = $validatorRule[self::VALIDATOR_CHAIN];
             } else {
                 $validatorChain = new Zend_Validate();
                 $validatorChain->addValidator($notEmptyValidator, true);
                 $validatorChain->addValidator($validatorRule[self::VALIDATOR_CHAIN]);
             }
             foreach ($field as $key => $value) {
                 if ($validatorRule[self::ALLOW_EMPTY] && !$notEmptyValidator->isValid($value)) {
                     // Field is empty AND it's allowed. Do nothing.
                     continue;
                 }
                 if (!$validatorChain->isValid($value)) {
                     if (isset($this->_invalidMessages[$validatorRule[self::RULE]])) {
                         $collectedMessages = $this->_invalidMessages[$validatorRule[self::RULE]];
                     } else {
                         $collectedMessages = array();
                     }
                     foreach ($validatorChain->getMessages() as $messageKey => $message) {
                         if (!isset($collectedMessages[$messageKey])) {
                             $collectedMessages[$messageKey] = $message;
                         } else {
                             $collectedMessages[] = $message;
                         }
                     }
                     $this->_invalidMessages[$validatorRule[self::RULE]] = $collectedMessages;
                     if (isset($this->_invalidErrors[$validatorRule[self::RULE]])) {
                         $this->_invalidErrors[$validatorRule[self::RULE]] = array_merge($this->_invalidErrors[$validatorRule[self::RULE]], $validatorChain->getErrors());
                     } else {
                         $this->_invalidErrors[$validatorRule[self::RULE]] = $validatorChain->getErrors();
                     }
                     unset($this->_validFields[$fieldName]);
                     $failed = true;
                     if ($validatorRule[self::BREAK_CHAIN]) {
                         return;
                     }
                 }
             }
             if ($failed) {
                 return;
             }
         }
     }
     /**
      * If we got this far, the inputs for this rule pass validation.
      */
     foreach ((array) $validatorRule[self::FIELDS] as $field) {
         if (array_key_exists($field, $data)) {
             $this->_validFields[$field] = $data[$field];
         }
     }
 }
 public function __construct($arrParam = array(), $options = null)
 {
     //////////////////////////////////
     //Kiem tra group_name /////////////
     //////////////////////////////////
     if ($arrParam['action'] == 'add') {
         $options = array('table' => 'da_user_group', 'field' => 'group_name');
     } elseif ($arrParam['action'] == 'edit') {
         $options = array('table' => 'da_user_group', 'field' => 'group_name', 'exclude' => array('field' => 'id', 'value' => $arrParam['id']));
     }
     $validator = new Zend_Validate();
     $validator->addValidator(new Zend_Validate_NotEmpty(), true)->addValidator(new Zend_Validate_StringLength(3, 32), true)->addValidator(new Zend_Validate_Regex('#^[a-zA-Z0-9\\-_\\.\\s]+$#'), true)->addValidator(new Zend_Validate_Db_NoRecordExists($options), true);
     if (!$validator->isValid($arrParam['group_name'])) {
         $message = $validator->getMessages();
         $this->_messageError['group_name'] = 'Group name: ' . current($message);
         $arrParam['group_name'] = '';
     }
     //////////////////////////////////
     //Kiem tra Avatar ///////////
     //////////////////////////////////
     $upload = new Zend_File_Transfer_Adapter_Http();
     $fileInfo = $upload->getFileInfo('avatar');
     $fileName = $fileInfo['avatar']['name'];
     if (!empty($fileName)) {
         $upload->addValidator('Extension', true, array('jpg', 'gif', 'png'), 'avatar');
         $upload->addValidator('Size', true, array('min' => '2KB', 'max' => '1000KB'), 'avatar');
         if (!$upload->isValid('avatar')) {
             $message = $upload->getMessages();
             $this->_messageError['avatar'] = 'Avatar: ' . current($message);
         }
     }
     //////////////////////////////////
     //Kiem tra ranking ///////////
     //////////////////////////////////
     $upload = new Zend_File_Transfer_Adapter_Http();
     $fileInfo = $upload->getFileInfo('ranking');
     $fileName = $fileInfo['ranking']['name'];
     if (!empty($fileName)) {
         $upload->addValidator('Extension', true, array('jpg', 'gif', 'png'), 'ranking');
         $upload->addValidator('Size', true, array('min' => '2KB', 'max' => '1000KB'), 'ranking');
         if (!$upload->isValid('ranking')) {
             $message = $upload->getMessages();
             $this->_messageError['ranking'] = 'Ranking: ' . current($message);
         }
     }
     //////////////////////////////////
     //Kiem tra Admin Control Panel /////////////
     //////////////////////////////////
     if (empty($arrParam['group_acp']) || !isset($arrParam['group_acp'])) {
         $arrParam['group_acp'] = 0;
     }
     //////////////////////////////////
     //Kiem tra Group Default /////////////
     //////////////////////////////////
     if (empty($arrParam['group_default']) || !isset($arrParam['group_default'])) {
         $arrParam['group_default'] = 0;
     }
     //////////////////////////////////
     //Kiem tra Status /////////////
     //////////////////////////////////
     if (empty($arrParam['status']) || !isset($arrParam['status'])) {
         $arrParam['status'] = 0;
     }
     //////////////////////////////////
     //Kiem tra order /////////////
     //////////////////////////////////
     $validator = new Zend_Validate();
     $validator->addValidator(new Zend_Validate_Digits(), true);
     if (!$validator->isValid($arrParam['order'])) {
         $message = $validator->getMessages();
         $this->_messageError['order'] = 'Order: ' . current($message);
         $arrParam['order'] = '';
     }
     //========================================
     // TRUYEN CAC GIA TRI DUNG VAO MANG $_arrData
     //========================================
     $this->_arrData = $arrParam;
 }
示例#26
0
 /**
  * Validate file
  *
  * @throws Mage_Core_Exception
  * @param array $optionValue
  * @return Mage_Catalog_Model_Product_Option_Type_Default
  */
 protected function _validateFile($optionValue)
 {
     $option = $this->getOption();
     /**
      * @see Mage_Catalog_Model_Product_Option_Type_File::_validateUploadFile()
      *              There setUserValue() sets correct fileFullPath only for
      *              quote_path. So we must form both full paths manually and
      *              check them.
      */
     $checkPaths = array();
     if (isset($optionValue['quote_path'])) {
         $checkPaths[] = Mage::getBaseDir() . $optionValue['quote_path'];
     }
     if (isset($optionValue['order_path']) && !$this->getUseQuotePath()) {
         $checkPaths[] = Mage::getBaseDir() . $optionValue['order_path'];
     }
     $fileFullPath = null;
     foreach ($checkPaths as $path) {
         if (!$this->_filesystem->isFile($path)) {
             if (!Mage::helper('Mage_Core_Helper_File_Storage_Database')->saveFileToFilesystem($fileFullPath)) {
                 continue;
             }
         }
         $fileFullPath = $path;
         break;
     }
     if ($fileFullPath === null) {
         return false;
     }
     $validatorChain = new Zend_Validate();
     $_dimentions = array();
     if ($option->getImageSizeX() > 0) {
         $_dimentions['maxwidth'] = $option->getImageSizeX();
     }
     if ($option->getImageSizeY() > 0) {
         $_dimentions['maxheight'] = $option->getImageSizeY();
     }
     if (count($_dimentions) > 0 && !$this->_isImage($fileFullPath)) {
         return false;
     }
     if (count($_dimentions) > 0) {
         $validatorChain->addValidator(new Zend_Validate_File_ImageSize($_dimentions));
     }
     // File extension
     $_allowed = $this->_parseExtensionsString($option->getFileExtension());
     if ($_allowed !== null) {
         $validatorChain->addValidator(new Zend_Validate_File_Extension($_allowed));
     } else {
         $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions'));
         if ($_forbidden !== null) {
             $validatorChain->addValidator(new Zend_Validate_File_ExcludeExtension($_forbidden));
         }
     }
     // Maximum file size
     $maxFileSize = $this->getFileSizeService()->getMaxFileSize();
     $validatorChain->addValidator(new Zend_Validate_File_FilesSize(array('max' => $maxFileSize)));
     if ($validatorChain->isValid($fileFullPath)) {
         $ok = $this->_filesystem->isReadable($fileFullPath) && isset($optionValue['secret_key']) && substr(md5($this->_filesystem->read($fileFullPath)), 0, 20) == $optionValue['secret_key'];
         return $ok;
     } elseif ($validatorChain->getErrors()) {
         $errors = $this->_getValidatorErrors($validatorChain->getErrors(), $optionValue);
         if (count($errors) > 0) {
             $this->setIsValid(false);
             Mage::throwException(implode("\n", $errors));
         }
     } else {
         $this->setIsValid(false);
         Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('Please specify the product required option(s)'));
     }
 }
示例#27
0
 /**
  * Creates validator for the model with all validation rules in it.
  * Returns FALSE, if no validation rules exist.
  *
  * @return \Zend_Validate_Interface|bool
  */
 protected function _createValidatorBeforeSave()
 {
     $modelRules = $this->_getValidationRulesBeforeSave();
     $resourceRules = $this->_getResource()->getValidationRulesBeforeSave();
     if (!$modelRules && !$resourceRules) {
         return false;
     }
     if ($modelRules && $resourceRules) {
         $validator = new \Zend_Validate();
         $validator->addValidator($modelRules);
         $validator->addValidator($resourceRules);
     } elseif ($modelRules) {
         $validator = $modelRules;
     } else {
         $validator = $resourceRules;
     }
     return $validator;
 }
示例#28
0
 /**
  * Build validator chain with config data
  *
  * @param array $validationConfig
  * @throws Exception If validator type is not set
  * @throws Exception If validator is not exist
  */
 protected function _buildValidatorsChain(array $validationConfig)
 {
     foreach ($validationConfig as $field => $validatorsConfig) {
         if (count($validatorsConfig)) {
             $chainForOneField = new Zend_Validate();
             foreach ($validatorsConfig as $validatorName => $validatorConfig) {
                 // it is required field
                 if ('required' == $validatorName && 1 == $validatorConfig) {
                     $this->_requiredFields[] = $field;
                     continue;
                 }
                 // instantiation of the validator class
                 if (!isset($validatorConfig['type'])) {
                     throw new Exception("Validator type is not set for {$validatorName}");
                 }
                 $validator = $this->_getValidatorInstance($validatorConfig['type'], !empty($validatorConfig['options']) ? $validatorConfig['options'] : array());
                 // set custom message
                 if (isset($validatorConfig['message'])) {
                     $validator->setMessage($validatorConfig['message']);
                 }
                 // add to list of validators
                 $chainForOneField->addValidator($validator);
             }
             $this->_validators[$field] = $chainForOneField;
         }
     }
 }
示例#29
0
 /**
  * Get all validators attached to a property
  * 
  * @param String $property Name of property
  * @return Zend_Validate
  **/
 public function getValidators($property)
 {
     $validators = new Zend_Validate();
     // Return if no requirements are set for this property
     if (!array_key_exists($property, $this->_docRequirements)) {
         return $validators;
     }
     foreach ($this->_docRequirements[$property] as $requirement => $options) {
         // continue if requirement does not exist or is not a validator requirement
         $validator = Shanty_Mongo::retrieveRequirement($requirement, $options);
         if (!$validator || !$validator instanceof Zend_Validate_Interface) {
             continue;
         }
         $validators->addValidator($validator);
     }
     return $validators;
 }
示例#30
0
 /**
  * Load the requirements as validators or filters for a given property,
  * and cache them as validators or filters, respectively.
  *
  * @param String $property Name of property
  * @return boolean whether or not cache was used. 
  */
 public function loadRequirements($property)
 {
     if (isset($this->_validators[$property]) || isset($this->_filters[$property])) {
         return true;
     }
     $validators = new Zend_Validate();
     $filters = new Zend_Filter();
     if (!isset($this->_docRequirements[$property])) {
         $this->_filters[$property] = $filters;
         $this->_validators[$property] = $validators;
         return false;
     }
     foreach ($this->_docRequirements[$property] as $requirement => $options) {
         $req = Shanty_Mongo::retrieveRequirement($requirement, $options);
         if ($req instanceof Zend_Validate_Interface) {
             $validators->addValidator($req);
         } else {
             if ($req instanceof Zend_Filter_Interface) {
                 $filters->addFilter($req);
             }
         }
     }
     $this->_filters[$property] = $filters;
     $this->_validators[$property] = $validators;
     return false;
 }