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; }
/** * 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; }
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\\-\\._\\?\\,\'/\\\\+&%\\$#\\=\\~])*[^\\.\\,\\)\\(\\s]$~')); $this->_setValue($value); if (!$validator->isValid($value)) { $this->_error(self::URL); return false; } return true; }
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'); } } }
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; }
/** * 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); }
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); }
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; }
/** * 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)); } } }
/** * 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; }
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 (strlen($this->code) > self::CODE_MAX_LENGTH) { return false; } if (empty($this->primaryLabel)) { return false; } $validatorInputType = $this->inputTypeValidatorFactory->create(); if (!$validatorInputType->isValid($this->inputType)) { return false; } return true; }
/** * @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/*/'); }
/** * @ZF-4352 */ public function testNonStringValidation() { $validator = new Zend_Validate_Regex('/'); $this->assertFalse($validator->isValid(array(1 => 1))); }
function isValid($value) { $nameValidator = new Zend_Validate_Regex("/^[0-9a-zA-ZÀ-ú]+[0-9A-Za-zÀ-ú\\'\\[\\]\\(\\)\\-\\.\\,\\:\\;\\!\\?\\/ ]{1,120}\$/"); return $nameValidator->isValid($value); }
/** * Filter post data * * @param array $data * @throws Mage_Core_Exception * @return array */ public function filterPostData($data) { if ($data) { //labels foreach ($data['frontend_label'] as &$value) { if ($value) { $value = $this->stripTags($value); } } //validate attribute_code if (isset($data['attribute_code'])) { $validatorAttrCode = new Zend_Validate_Regex(array('pattern' => '/^[a-z_0-9]{1,255}$/')); if (!$validatorAttrCode->isValid($data['attribute_code'])) { Mage::throwException(Mage::helper('enterprise_eav')->__('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 $data; }
$errors = array(); if ($_POST) { require_once 'library.php'; try { $val = new Zend_Validate_Alpha(TRUE); // Validate first name // $val = new Zend_Validate_Regex('/^[a-z]+[-\'a-z]+$/i'); if (!$val->isValid($_POST['first_name'])) { $errors['first_name'] = '<p class="add_user_error">' . 'Required field, with no numbers' . '</p>'; } // Validate surname // $val = new Zend_Validate_Regex('/^[a-z]+[-\'a-z]+$/i'); if (!$val->isValid($_POST['surname'])) { $errors['surname'] = '<p class="add_user_error">' . 'Required field, with no numbers' . '</p>'; } // Validate username // $val = new Zend_Validate(); $length = new Zend_Validate_StringLength(6, 15); $val->addValidator($length); $val->addValidator(new Zend_Validate_Alnum()); 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);
public function saveAction() { $data = $this->getRequest()->getPost(); $groupId = $this->getRequest()->getParam('group'); if ($data) { /** @var $session Mage_Backend_Model_Auth_Session */ $session = Mage::getSingleton('Mage_Adminhtml_Model_Session'); $isNewAttributeSet = false; if (isset($data['new_attribute_set_name']) && !empty($data['new_attribute_set_name'])) { /** @var $attributeSet Mage_Eav_Model_Entity_Attribute_Set */ $attributeSet = Mage::getModel('Mage_Eav_Model_Entity_Attribute_Set'); $name = Mage::helper('Mage_Adminhtml_Helper_Data')->stripTags($data['new_attribute_set_name']); $name = trim($name); $attributeSet->setEntityTypeId($this->_entityTypeId)->load($name, 'attribute_set_name'); if ($attributeSet->getId()) { $session->addError(Mage::helper('Mage_Catalog_Helper_Data')->__('Attribute Set with name \'%s\' already exists.', $name)); $session->setAttributeData($data); $this->_redirect('*/*/edit', array('_current' => true)); return; } try { $attributeSet->setAttributeSetName($name)->validate(); $attributeSet->save(); $attributeSet->initFromSkeleton($this->getRequest()->getParam('set'))->save(); /** @var $requestedGroup Mage_Catalog_Model_Product_Attribute_Group */ $requestedGroup = Mage::getModel('Mage_Catalog_Model_Product_Attribute_Group')->load($groupId); if (!$requestedGroup->getId()) { throw Mage::exception('Mage_Adminhtml', $this->_helper('Mage_Catalog_Helper_Data')->__('Specified Attribute group id is invalid.')); } foreach ($attributeSet->getGroups() as $group) { if ($group->getAttributeGroupName() == $requestedGroup->getAttributeGroupName()) { $targetGroupId = $group->getAttributeGroupId(); break; } } $isNewAttributeSet = true; } catch (Mage_Core_Exception $e) { $session->addError($e->getMessage()); } catch (Exception $e) { $session->addException($e, Mage::helper('Mage_Catalog_Helper_Data')->__('An error occurred while saving the attribute set.')); } } $redirectBack = $this->getRequest()->getParam('back', false); /* @var $model Mage_Catalog_Model_Entity_Attribute */ $model = Mage::getModel('Mage_Catalog_Model_Resource_Eav_Attribute'); /* @var $helper Mage_Catalog_Helper_Product */ $helper = Mage::helper('Mage_Catalog_Helper_Product'); $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('Mage_Catalog_Helper_Data')->__('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 $validatorInput Mage_Eav_Model_Adminhtml_System_Config_Source_Inputtype_Validator */ $validatorInput = Mage::getModel('Mage_Eav_Model_Adminhtml_System_Config_Source_Inputtype_Validator'); if (!$validatorInput->isValid($data['frontend_input'])) { foreach ($validatorInput->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('Mage_Catalog_Helper_Data')->__('This Attribute no longer exists')); $this->_redirect('*/*/'); return; } // entity type check if ($model->getEntityTypeId() != $this->_entityTypeId) { $session->addError(Mage::helper('Mage_Catalog_Helper_Data')->__('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') && $groupId) { // For creating product attribute on product page we need specify attribute set and group $attributeSetId = $isNewAttributeSet ? $attributeSet->getId() : $this->getRequest()->getParam('set'); $attributeGroupId = $isNewAttributeSet ? $targetGroupId : $groupId; $model->setAttributeSetId($attributeSetId); $model->setAttributeGroupId($attributeGroupId); } try { $model->save(); $session->addSuccess(Mage::helper('Mage_Catalog_Helper_Data')->__('The product 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')) { $requestParams = array('id' => $this->getRequest()->getParam('product'), 'attribute' => $model->getId(), '_current' => true); if ($isNewAttributeSet) { $requestParams['new_attribute_set_id'] = $attributeSetId; } $this->_redirect('adminhtml/catalog_product/addAttribute', $requestParams); } 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('*/*/'); }
/** * 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); } }
/** * Validate rule data * * @param Varien_Object $object * * @return bool|array - return true if validation passed successfully. Array with errors description otherwise */ public function validateData(Varien_Object $object) { $result = parent::validateData($object); if (!is_array($result)) { $result = array(); } $validator = new Zend_Validate_Regex(array('pattern' => '/^[a-z][a-z0-9_\\/]{1,255}$/')); $actionArgsList = $object->getData('rule'); if (is_array($actionArgsList) && isset($actionArgsList['actions'])) { foreach ($actionArgsList['actions'] as $actionArgsIndex => $actionArgs) { if (1 === $actionArgsIndex) { continue; } if (!$validator->isValid($actionArgs['type']) || isset($actionArgs['attribute']) && !$validator->isValid($actionArgs['attribute'])) { $result[] = Mage::helper('enterprise_targetrule')->__('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 !empty($result) ? $result : true; }
/** * Validate Data * * @param array $data Data * @return array|bool * @throws Mage_Core_Exception */ public function validateData(array $data) { $errors = parent::validateData($data); // Prevent to change/save the username if it is not allowed on the frontend to change the username if (!Mage::getStoreConfigFlag('username/general/frontend') && !Mage::app()->getStore()->isAdmin()) { return $errors; } if (!empty($data['username'])) { $model = Mage::getModel('customer/customer'); $customerId = Mage::app()->getFrontController()->getRequest()->getParam('customer_id'); if (!$customerId) { $customerId = Mage::app()->getFrontController()->getRequest()->getParam('id'); } if (!$customerId && !Mage::app()->getStore()->isAdmin()) { $customerId = Mage::getSingleton('customer/session')->getCustomer()->getId(); } // Prevent possible errors if (empty($customerId)) { return $errors; } if (isset($data['website_id']) && $data['website_id'] !== false) { $websiteId = $data['website_id']; } elseif ($customerId) { $customer = $model->load($customerId); $websiteId = $customer->getWebsiteId(); // don't make any test if the user has already a username if ($customer->getUsername() == $data['username']) { return $errors; } } else { $websiteId = Mage::app()->getWebsite()->getId(); } if (!is_array($errors)) { $errors = array(); } $isCheckoutAsGuest = Mage::getSingleton('checkout/type_onepage')->getCheckoutMethod(); if ($isCheckoutAsGuest != Mage_Checkout_Model_Type_Onepage::METHOD_GUEST && empty($data['username'])) { $message = Mage::helper('username')->__('Username is a required field.'); $errors = array_merge($errors, array($message)); } // Other rules are validated by the parent class because they are basic rules provided by Magento Core $inputValidation = Mage::getStoreConfig('username/general/input_validation'); $useInputValidation = $inputValidation == 'default' || $inputValidation == 'custom' ? true : false; if ($useInputValidation) { $validate = '/^*$/'; switch ($inputValidation) { case 'default': $validate = '/^[\\w-]*$/'; break; case 'custom': $validate = Mage::getStoreConfig('username/general/input_validation_custom'); break; } $validate = new Zend_Validate_Regex($validate); if (!$validate->isValid($data['username'])) { if ($inputValidation == 'custom') { $message = Mage::getStoreConfig('username/general/input_validation_custom_message'); } else { $message = Mage::helper('username')->__('Username is invalid! Only letters, digits and \'_-\' values are accepted.'); } $errors = array_merge($errors, array($message)); } } $result = $model->customerUsernameExists($data['username'], $websiteId); if ($result && $result->getId() != $customerId) { $message = Mage::helper('username')->__('Username already exists'); $errors = array_merge($errors, array($message)); } } if (count($errors) == 0) { return true; } return $errors; }
public function create($attributeCode, array $frontendLabel, $frontendInput = 'text', $isGlobal = 1, array $additionalParams = array()) { $validatorAttrCode = new Zend_Validate_Regex(array('pattern' => '/^[a-z][a-z_0-9]{1,254}$/')); if (!$validatorAttrCode->isValid($attributeCode)) { return false; } if (empty($frontendLabel)) { return false; } //@todo Now we can only handle type "text" or "textarea" if ($frontendInput != 'text' && $frontendInput != 'textarea') { return false; } /** @var $validatorInputType Mage_Eav_Model_Adminhtml_System_Config_Source_Inputtype_Validator */ // doesn't exist in magento <= 1.4.1.1 // $validatorInputType = Mage::getModel('eav/adminhtml_system_config_source_inputtype_validator'); // if (!$validatorInputType->isValid($frontendInput)) { // return false; // } $data = $additionalParams; $data['attribute_code'] = $attributeCode; $data['frontend_input'] = $frontendInput; $data['frontend_label'] = $frontendLabel; $data['is_global'] = (int) $isGlobal; $data['source_model'] = Mage::helper('catalog/product')->getAttributeSourceModelByInputType($frontendInput); $data['backend_model'] = Mage::helper('catalog/product')->getAttributeBackendModelByInputType($frontendInput); !isset($data['is_configurable']) && ($data['is_configurable'] = 0); !isset($data['is_filterable']) && ($data['is_filterable'] = 0); !isset($data['is_filterable_in_search']) && ($data['is_filterable_in_search'] = 0); /* @var $model Mage_Catalog_Model_Entity_Attribute */ $model = Mage::getModel('catalog/resource_eav_attribute'); if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) { $data['backend_type'] = $model->getBackendTypeByInput($frontendInput); } $defaultValueField = $model->getDefaultValueByInput($frontendInput); if ($defaultValueField && isset($data[$defaultValueField])) { $data['default_value'] = $data[$defaultValueField]; } !isset($data['apply_to']) && ($data['apply_to'] = array()); $model->addData($data); $model->setEntityTypeId(Mage::getModel('catalog/product')->getResource()->getTypeId()); $model->setIsUserDefined(1); try { $model->save(); } catch (Exception $e) { return false; } return (int) $model->getId(); }
/** * Method get a 'folder' name from request array and checks if this folder exists. * If not it creates this folder * @return string directory path or false if error */ private function _getSavePath() { $folder = trim(preg_replace('~[^\\w]+|[\\s\\-]+~ui', '-', filter_var($this->getRequest()->getParam('folder'), FILTER_SANITIZE_STRING)), '-'); if (!$folder || empty($folder)) { return array('error' => true, 'result' => 'No files uploaded. Please select folder.'); } $folder = trim($folder, ' \\/'); $folderValidator = new Zend_Validate_Regex('~^[^\\x00-\\x1F"<>\\|:\\*\\?/]+$~'); if (!$folderValidator->isValid($folder)) { return array('error' => true, 'result' => 'Bad folder name'); } $savePath = $this->_websiteConfig['path'] . $this->_websiteConfig['media'] . $folder . DIRECTORY_SEPARATOR; if (!is_dir($savePath)) { try { Tools_Filesystem_Tools::mkDir($savePath); } catch (Exceptions_SeotoasterException $e) { error_log($e->getMessage()); return false; } } return realpath($savePath); }
function createAttribute($data = array()) { $frontend_label = $this->getFrontendLabel(); $attribute_code = $this->getData('attribute_code'); if (isset($this->_attributeCodes[$attribute_code])) { return; } $data_default = array('is_global' => '2', 'attribute_code' => $attribute_code, 'frontend_input' => $this->getData('frontend_input'), 'default_value' => '', 'default_value_text' => '', 'default_value_yesno' => '0', 'default_value_date' => '', 'default_value_textarea' => '', 'is_unique' => '0', 'is_required' => '0', 'frontend_class' => '', 'is_searchable' => '0', 'is_visible_in_advanced_search' => '0', 'is_comparable' => '0', 'is_used_for_promo_rules' => '0', 'is_html_allowed_on_front' => '1', 'is_visible_on_front' => '1', 'used_in_product_listing' => '0', 'used_for_sort_by' => '0', 'is_configurable' => '0', 'is_filterable' => '0', 'is_filterable_in_search' => '0', 'backend_type' => $this->getData('backend_type')); $data = array_merge($data_default, $data); $data['frontend_label'] = array('0' => $this->getData('frontend_label')); /* @var $model Mage_Catalog_Model_Entity_Attribute */ $model = Mage::getModel('catalog/resource_eav_attribute'); /* @var $helper Mage_Catalog_Helper_Product */ $helper = Mage::helper('catalog/product'); //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'])) { Mage::log(Mage::helper('catalog')->__('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; } } //validate frontend_label if (!isset($data['frontend_label'])) { Mage::log(Mage::helper('catalog')->__('Attribute Text is required.')); } //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) { Mage::log($message); } return; } } $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']); } if (!isset($data['apply_to'])) { $data['apply_to'] = array(); } //filter $data = Mage::helper('tgeneral/catalog')->filterPostData($data); $model->addData($data); $entityTypeId = $this->getEntityTypeId(); $model->setEntityTypeId($entityTypeId); $model->setIsUserDefined(1); try { $model->save(); $this->_attributeCodes[$attribute_code] = $model->getData(); $this->_attributeCodes[$attribute_code]['id'] = $model->getId(); } catch (Exception $e) { Mage::log($e->getMessage()); } return; }
/** * валидация номера телефона * @param string $phoneNumber * @return bool */ private function _validate($phoneNumber) { $pattern = '/^([0-9]+)([0-9]+)$/'; $vlidator = new Zend_Validate_Regex($pattern); return $vlidator->isValid($phoneNumber); }
/** * Street Address check for US format #### Memory Lane * * @param string $street * @return boolean Valid? */ public function street($street) { $this->m_ErrorMessage = null; require_once 'Zend/Validate/Regex.php'; $validator = new Zend_Validate_Regex(""); $result = $validator->isValid($street); if (!$result) { $this->m_ErrorMessage = BizSystem::getMessage("VALIDATESVC_STREET_INVALID", array($this->m_FieldNameMask)); } return $result; }
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('*/*/'); }
public function validatePostResult() { $postData = $this->getPostData(); if (Mage::registry('webforms_errors_flag_' . $this->getId())) { return Mage::registry('webforms_errors_' . $this->getId()); } $errors = array(); // check captcha if ($this->useCaptcha()) { if (Mage::app()->getRequest()->getPost('recaptcha_response_field')) { $verify = Mage::helper('webforms')->getCaptcha()->verify(Mage::app()->getRequest()->getPost('recaptcha_challenge_field'), Mage::app()->getRequest()->getPost('recaptcha_response_field')); if (!$verify->isValid()) { $errors[] = Mage::helper('webforms')->__('Verification code was not correct. Please try again.'); } } else { $errors[] = Mage::helper('webforms')->__('Verification code was not correct. Please try again.'); } } // check honeypot captcha if (Mage::getStoreConfig('webforms/honeypot/enable')) { if (Mage::app()->getRequest()->getPost('message')) { $errors[] = Mage::helper('webforms')->__('Spam bot detected. Honeypot field should be empty.'); } } // check custom validation $logic_rules = $this->getLogic(); $fields_to_fieldsets = $this->getFieldsToFieldsets(); foreach ($fields_to_fieldsets as $fieldset_id => $fieldset) { foreach ($fieldset['fields'] as $field) { if ($field->getIsActive() && $field->getValidateRegex() && $field->getRequired()) { $pattern = $field->getValidateRegex(); $status = @preg_match($pattern, "Test"); if (false === $status) { $pattern = "/" . $pattern . "/"; } $validate = new Zend_Validate_Regex($pattern); foreach ($this->getPostData() as $key => $value) { if ($key == $field->getId() && !$validate->isValid($value)) { $errors[] = $field->getName() . ": " . $field->getValidateMessage(); } } } $hint = htmlspecialchars(trim($field->getHint())); if ($field->getRequired() && is_array($this->getPostData())) { foreach ($this->getPostData() as $key => $value) { if ($key == $field->getId() && $field->getType() == 'textarea') { // check profanity $target_field = array("id" => 'field_' . $field->getId(), 'logic_visibility' => $field->getData('logic_visibility')); $target_fieldset = array("id" => 'fieldset_' . $fieldset_id, 'logic_visibility' => $fieldset['logic_visibility']); $profanity = $this->is_profanity($value); if ((trim($value) != $hint || trim($value) != '') && $profanity) { $errors[] = Mage::helper('webforms')->__('%s is required', $field->getName()); } } if ($key == $field->getId() && $field->getType() != 'select/checkbox' && (trim($value) == $hint || trim($value) == '')) { // check logic visibility $target_field = array("id" => 'field_' . $field->getId(), 'logic_visibility' => $field->getData('logic_visibility')); $target_fieldset = array("id" => 'fieldset_' . $fieldset_id, 'logic_visibility' => $fieldset['logic_visibility']); if ($this->getLogicTargetVisibility($target_field, $logic_rules, $this->getPostData()) && $this->getLogicTargetVisibility($target_fieldset, $logic_rules, $this->getPostData())) { $errors[] = Mage::helper('webforms')->__('%s is required', $field->getName()); } } } } // check if the e-mail address is valid if ($this->getEmailSmtpValidation()) { if ($field->getIsActive() && $field->getType() == 'email') { if (!empty($postData[$field->getId()])) { $smtp_validate = new SMTP_validateEmail(); $smtp_validate_results = $smtp_validate->validate(array($postData[$field->getId()]), Mage::getStoreConfig('trans_email/ident_general/email')); if (!$smtp_validate_results[$postData[$field->getId()]]) { $errors[] = Mage::helper('webforms')->__('E-mail address does not seem to exist: %s', $postData[$field->getId()]); } } } } // check e-mail stoplist if ($field->getIsActive() && $field->getType() == 'email') { if (!empty($postData[$field->getId()])) { if (stristr(Mage::getStoreConfig('webforms/email/stoplist'), $postData[$field->getId()])) { $errors[] = Mage::helper('webforms')->__('E-mail address is blocked: %s', $postData[$field->getId()]); } } } } } // check files $files = $this->getUploadedFiles(); foreach ($files as $field_name => $file) { if (isset($file['name']) && file_exists($file['tmp_name'])) { $field_id = str_replace('file_', '', $field_name); $postData['field'][$field_id] = Varien_File_Uploader::getCorrectFileName($file['name']); $field = Mage::getModel('webforms/fields')->setStoreId($this->getStoreId())->load($field_id); $filesize = round($file['size'] / 1024); $images_upload_limit = Mage::getStoreConfig('webforms/images/upload_limit'); if ($this->getImagesUploadLimit() > 0) { $images_upload_limit = $this->getImagesUploadLimit(); } $files_upload_limit = Mage::getStoreConfig('webforms/files/upload_limit'); if ($this->getFilesUploadLimit() > 0) { $files_upload_limit = $this->getFilesUploadLimit(); } if ($field->getType() == 'image') { // check file size if ($filesize > $images_upload_limit && $images_upload_limit > 0) { $errors[] = Mage::helper('webforms')->__('Uploaded image %s (%s kB) exceeds allowed limit: %s kB', $file['name'], $filesize, $images_upload_limit); } // check that file is valid image if (!@getimagesize($file['tmp_name'])) { $errors[] = Mage::helper('webforms')->__('Unsupported image compression: %s', $file['name']); } } else { // check file size if ($filesize > $files_upload_limit && $files_upload_limit > 0) { $errors[] = Mage::helper('webforms')->__('Uploaded file %s (%s kB) exceeds allowed limit: %s kB', $file['name'], $filesize, $files_upload_limit); } } $allowed_extensions = $field->getAllowedExtensions(); // check for allowed extensions if (count($allowed_extensions)) { preg_match("/\\.([^\\.]+)\$/", $file['name'], $matches); $file_ext = strtolower($matches[1]); // check file extension if (!in_array($file_ext, $allowed_extensions)) { $errors[] = Mage::helper('webforms')->__('Uploaded file %s has none of allowed extensions: %s', $file['name'], implode(', ', $allowed_extensions)); } } // check for valid filename if (Mage::getStoreConfig('webforms/files/validate_filename') && !preg_match("/^[a-zA-Z0-9_\\s-\\.]+\$/", $file['name'])) { $errors[] = Mage::helper('webforms')->__('Uploaded file %s has non-latin characters in the name', $file['name']); } } } $validate = new Varien_Object(array('errors' => $errors)); Mage::dispatchEvent('webforms_validate_post_result', array('webform' => $this, 'validate' => $validate)); Mage::register('webforms_errors_flag_' . $this->getId(), true); Mage::register('webforms_errors_' . $this->getId(), $validate->getData('errors')); return $validate->getData('errors'); }
/** * 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; }
/** * Ensures that a bad pattern results in a thrown exception upon isValid() call * * @return void */ public function testBadPattern() { $validator = new Zend_Validate_Regex('/'); try { $validator->isValid('anything'); $this->fail('Expected Zend_Validate_Exception not thrown for bad pattern'); } catch (Zend_Validate_Exception $e) { $this->assertContains('Internal error matching pattern', $e->getMessage()); } }