/**
  * @param Order $order
  * @param array $data
  *
  * @throws ValidationException
  */
 public function validateData(Order $order, array $data)
 {
     $result = ValidationResult::create();
     $existingID = !empty($data[$this->addresstype . "AddressID"]) ? (int) $data[$this->addresstype . "AddressID"] : 0;
     if ($existingID) {
         // If existing address selected, check that it exists in $member->AddressBook
         if (!Member::currentUserID() || !Member::currentUser()->AddressBook()->byID($existingID)) {
             $result->error("Invalid address supplied", $this->addresstype . "AddressID");
             throw new ValidationException($result);
         }
     } else {
         // Otherwise, require the normal address fields
         $required = parent::getRequiredFields($order);
         $addressLabels = singleton('Address')->fieldLabels(false);
         foreach ($required as $fieldName) {
             if (empty($data[$fieldName])) {
                 // attempt to get the translated field name
                 $fieldLabel = isset($addressLabels[$fieldName]) ? $addressLabels[$fieldName] : $fieldName;
                 $errorMessage = _t('Form.FIELDISREQUIRED', '{name} is required', array('name' => $fieldLabel));
                 $result->error($errorMessage, $fieldName);
                 throw new ValidationException($result);
             }
         }
     }
 }
 public function validateData(Order $order, array $data)
 {
     if (isset($data['RegisterAnAccount']) && $data['RegisterAnAccount']) {
         return parent::validateData($order, $data);
     }
     return ValidationResult::create();
 }
 public function validateData(Order $order, array $data)
 {
     if (Member::currentUserID()) {
         return;
     }
     $result = ValidationResult::create();
     if (Checkout::membership_required() || !empty($data['Password'])) {
         $member = Member::create($data);
         $idfield = Member::config()->unique_identifier_field;
         $idval = $data[$idfield];
         if (ShopMember::get_by_identifier($idval)) {
             // get localized field labels
             $fieldLabels = $member->fieldLabels(false);
             // if a localized value exists, use this for our error-message
             $fieldLabel = isset($fieldLabels[$idfield]) ? $fieldLabels[$idfield] : $idfield;
             $result->error(sprintf(_t("Checkout.MEMBEREXISTS", "A member already exists with the %s %s"), $fieldLabel, $idval), $idval);
         }
         $passwordresult = $this->passwordvalidator->validate($data['Password'], $member);
         if (!$passwordresult->valid()) {
             $result->error($passwordresult->message(), "Password");
         }
     }
     if (!$result->valid()) {
         throw new ValidationException($result);
     }
 }
 /**
  * Validate
  * @return ValidationResult
  **/
 protected function validate()
 {
     $valid = true;
     $message = null;
     $result = ValidationResult::create($valid, $message);
     return $result;
 }
 /**
  * @param String $password
  * @param Member $member
  * @return ValidationResult
  */
 public function validate($password, $member)
 {
     $valid = ValidationResult::create();
     if ($this->minLength) {
         if (strlen($password) < $this->minLength) {
             $valid->error(sprintf(_t('PasswordValidator.TOOSHORT', 'Password is too short, it must be %s or more characters long'), $this->minLength), 'TOO_SHORT');
         }
     }
     if ($this->minScore) {
         $score = 0;
         $missedTests = array();
         foreach ($this->testNames as $name) {
             if (preg_match(self::config()->character_strength_tests[$name], $password)) {
                 $score++;
             } else {
                 $missedTests[] = _t('PasswordValidator.STRENGTHTEST' . strtoupper($name), $name, 'The user needs to add this to their password for more complexity');
             }
         }
         if ($score < $this->minScore) {
             $valid->error(sprintf(_t('PasswordValidator.LOWCHARSTRENGTH', 'Please increase password strength by adding some of the following characters: %s'), implode(', ', $missedTests)), 'LOW_CHARACTER_STRENGTH');
         }
     }
     if ($this->historicalPasswordCount) {
         $previousPasswords = MemberPassword::get()->where(array('"MemberPassword"."MemberID"' => $member->ID))->sort('"Created" DESC, "ID" DESC')->limit($this->historicalPasswordCount);
         if ($previousPasswords) {
             foreach ($previousPasswords as $previousPasswords) {
                 if ($previousPasswords->checkPassword($password)) {
                     $valid->error(_t('PasswordValidator.PREVPASSWORD', 'You\'ve already used that password in the past, please choose a new password'), 'PREVIOUS_PASSWORD');
                     break;
                 }
             }
         }
     }
     return $valid;
 }
 public function validate()
 {
     if ($this->pages > 100) {
         $result = ValidationResult::create(false, 'Too many pages');
     } else {
         $result = ValidationResult::create(true);
     }
     return $result;
 }
 public function validateData(Order $order, array $data)
 {
     $result = ValidationResult::create();
     //TODO: validate credit card data
     if (!Helper::validateLuhn($data['number'])) {
         $result->error(_t('OnsitePaymentCheckoutComponent.CREDIT_CARD_INVALID', 'Credit card is invalid'));
         throw new ValidationException($result);
     }
 }
 /**
  * @return ValidationResult
  */
 protected function validate()
 {
     $result = ValidationResult::create();
     $link = trim($this->Link);
     if (empty($link)) {
         return $result->error('you must set an url for Presentation Link!');
     }
     if (filter_var($link, FILTER_VALIDATE_URL) === false) {
         return $result->error('you must set a valid url for Presentation Link!');
     }
     return $result;
 }
 public function validateData(Order $order, array $data)
 {
     $result = ValidationResult::create();
     if (!isset($data['PaymentMethod'])) {
         $result->error(_t('PaymentCheckoutComponent.NO_PAYMENT_METHOD', "Payment method not provided"), "PaymentMethod");
         throw new ValidationException($result);
     }
     $methods = GatewayInfo::get_supported_gateways();
     if (!isset($methods[$data['PaymentMethod']])) {
         $result->error(_t('PaymentCheckoutComponent.UNSUPPORTED_GATEWAY', "Gateway not supported"), "PaymentMethod");
         throw new ValidationException($result);
     }
 }
 public function validateData(Order $order, array $data)
 {
     $result = ValidationResult::create();
     if (!isset($data['PaymentMethod'])) {
         $result->error(_t('PaymentCheckoutComponent.NoPaymentMethod', "Payment method not provided"), "PaymentMethod");
         throw new ValidationException($result);
     }
     $methods = GatewayInfo::getSupportedGateways();
     if (!isset($methods[$data['PaymentMethod']])) {
         $result->error(_t('PaymentCheckoutComponent.UnsupportedGateway', "Gateway not supported"), "PaymentMethod");
         throw new ValidationException($result);
     }
 }
 protected function validate()
 {
     $valid = ValidationResult::create();
     if (!$valid->valid()) {
         return $valid;
     }
     if (empty($this->Name)) {
         return $valid->error('Name is empty!');
     }
     $res = DB::query("SELECT COUNT(Q.ID) FROM RSVPQuestionTemplate Q\n                          INNER JOIN `RSVPTemplate` T ON T.ID = Q.RSVPTemplateID\n                          WHERE Q.Name = '{$this->Name}' AND Q.ID <> {$this->ID} AND Q.RSVPTemplateID = {$this->RSVPTemplateID}")->value();
     if (intval($res) > 0) {
         return $valid->error('There is already another Question on the rsvp form with that name!');
     }
     return $valid;
 }
 protected function validate()
 {
     $valid = ValidationResult::create();
     if (!$valid->valid()) {
         return $valid;
     }
     if (empty($this->Name)) {
         return $valid->error('Name is empty!');
     }
     $res = DB::query("SELECT COUNT(Q.ID) FROM SurveyQuestionTemplate Q\n                          INNER JOIN `SurveyStepTemplate` S ON S.ID = Q.StepID\n                          INNER JOIN `SurveyTemplate` T ON T.ID = S.`SurveyTemplateID`\n                          WHERE Q.Name = '{$this->Name}' AND Q.ID <> {$this->ID};")->value();
     if (intval($res) > 0) {
         return $valid->error('There is already another Question on the survey with that name!');
     }
     return $valid;
 }
 protected function validate()
 {
     $valid = ValidationResult::create();
     if (empty($this->EntityName)) {
         return $valid->error('Entity Name is empty!');
     }
     if (!preg_match('/^[a-z_091A-Z]*$/', $this->EntityName)) {
         return $valid->error('Entity Name has an Invalid Format!');
     }
     $title = $this->EntityName;
     $id = $this->ID;
     $owner_id = $this->ParentID;
     $res = DB::query("SELECT COUNT(ID) FROM EntitySurveyTemplate WHERE EntityName = '{$title}' AND ID <> {$id} AND ParentID = {$owner_id}")->value();
     if (intval($res) > 0) {
         return $valid->error('There is already another entity survey with that name!');
     }
     return $valid;
 }
 /**
  * Create member account from data array.
  * Data must contain unique identifier.
  *
  * @throws ValidationException
  *
  * @param $data - map of member data
  *
  * @return Member|boolean - new member (not saved to db), or false if there is an error.
  */
 public function create($data)
 {
     $result = ValidationResult::create();
     if (!Checkout::member_creation_enabled()) {
         $result->error(_t("Checkout.MEMBERSHIPSNOTALLOWED", "Creating new memberships is not allowed"));
         throw new ValidationException($result);
     }
     $idfield = Config::inst()->get('Member', 'unique_identifier_field');
     if (!isset($data[$idfield]) || empty($data[$idfield])) {
         $result->error(sprintf(_t("Checkout.IDFIELDNOTFOUND", "Required field not found: %s"), $idfield));
         throw new ValidationException($result);
     }
     if (!isset($data['Password']) || empty($data['Password'])) {
         $result->error(_t("Checkout.PASSWORDREQUIRED", "A password is required"));
         throw new ValidationException($result);
     }
     $idval = $data[$idfield];
     if ($member = ShopMember::get_by_identifier($idval)) {
         // get localized field labels
         $fieldLabels = $member->fieldLabels(false);
         // if a localized value exists, use this for our error-message
         $fieldLabel = isset($fieldLabels[$idfield]) ? $fieldLabels[$idfield] : $idfield;
         $result->error(sprintf(_t("Checkout.MEMBEREXISTS", "A member already exists with the %s %s"), $fieldLabel, $idval));
         throw new ValidationException($result);
     }
     $member = Member::create(Convert::raw2sql($data));
     // 3.2 changed validate to protected which made this fall through the DataExtension and error out
     $validation = $member->hasMethod('doValidate') ? $member->doValidate() : $member->validate();
     if (!$validation->valid()) {
         //TODO need to handle i18n here?
         $result->error($validation->message());
     }
     if (!$result->valid()) {
         throw new ValidationException($result);
     }
     return $member;
 }
 /**
  * Create member account from data array.
  * Data must contain unique identifier.
  *
  * @throws ValidationException
  *
  * @param $data - map of member data
  *
  * @return Member|boolean - new member (not saved to db), or false if there is an error.
  */
 public function create($data)
 {
     $result = ValidationResult::create();
     if (!Checkout::member_creation_enabled()) {
         $result->error(_t("Checkout.MembershipIsNotAllowed", "Creating new memberships is not allowed"));
         throw new ValidationException($result);
     }
     $idfield = Config::inst()->get('Member', 'unique_identifier_field');
     if (!isset($data[$idfield]) || empty($data[$idfield])) {
         $result->error(_t('Checkout.IdFieldNotFound', 'Required field not found: {IdentifierField}', 'Identifier is the field that holds the unique user-identifier, commonly this is \'Email\'', array('IdentifierField' => $idfield)));
         throw new ValidationException($result);
     }
     if (!isset($data['Password']) || empty($data['Password'])) {
         $result->error(_t("Checkout.PasswordRequired", "A password is required"));
         throw new ValidationException($result);
     }
     $idval = $data[$idfield];
     if ($member = ShopMember::get_by_identifier($idval)) {
         // get localized field labels
         $fieldLabels = $member->fieldLabels(false);
         // if a localized value exists, use this for our error-message
         $fieldLabel = isset($fieldLabels[$idfield]) ? $fieldLabels[$idfield] : $idfield;
         $result->error(_t('Checkout.MemberExists', 'A member already exists with the {Field} {Identifier}', '', array('Field' => $fieldLabel, 'Identifier' => $idval)));
         throw new ValidationException($result);
     }
     $member = Member::create(Convert::raw2sql($data));
     // 3.2 changed validate to protected which made this fall through the DataExtension and error out
     $validation = $member->hasMethod('doValidate') ? $member->doValidate() : $member->validate();
     if (!$validation->valid()) {
         //TODO need to handle i18n here?
         $result->error($validation->message());
     }
     if (!$result->valid()) {
         throw new ValidationException($result);
     }
     return $member;
 }
 /**
  * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
  * password in the `unicodePwd` attribute.
  *
  * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
  * an abstract way, so it works on other LDAP directories, not just Active Directory.
  *
  * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
  *
  * @param Member $member
  * @param string $password
  * @return ValidationResult
  * @throws Exception
  */
 public function setPassword(Member $member, $password)
 {
     $validationResult = ValidationResult::create(true);
     if (!$member->GUID) {
         SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
         $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
         return $validationResult;
     }
     $userData = $this->getUserByGUID($member->GUID);
     if (empty($userData['distinguishedname'])) {
         $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
         return $validationResult;
     }
     try {
         $this->update($userData['distinguishedname'], array('unicodePwd' => iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $password))));
     } catch (Exception $e) {
         // Try to parse the exception to get the error message to display to user, eg:
         // Can't change password for Member.ID "13": 0x13 (Constraint violation; 0000052D: Constraint violation - check_password_restrictions: the password does not meet the complexity criteria!): updating: CN=User Name,OU=Users,DC=foo,DC=company,DC=com
         $pattern = '/^([^\\s])*\\s([^\\;]*);\\s([^\\:]*):\\s([^\\:]*):\\s([^\\)]*)/i';
         if (preg_match($pattern, $e->getMessage(), $matches) && !empty($matches[5])) {
             $validationResult->error($matches[5]);
         } else {
             // Unparsable exception, an administrator should check the logs
             $validationResult->error(_t('LDAPAuthenticator.CANTCHANGEPASSWORD', 'We couldn\'t change your password, please contact an administrator.'));
         }
     }
     return $validationResult;
 }
Esempio n. 17
0
 /**
  * Event handler called before writing to the database.
  */
 public function onBeforeWrite()
 {
     if ($this->SetPassword) {
         $this->Password = $this->SetPassword;
     }
     // If a member with the same "unique identifier" already exists with a different ID, don't allow merging.
     // Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form),
     // but rather a last line of defense against data inconsistencies.
     $identifierField = Member::config()->unique_identifier_field;
     if ($this->{$identifierField}) {
         // Note: Same logic as Member_Validator class
         $filter = array("\"{$identifierField}\"" => $this->{$identifierField});
         if ($this->ID) {
             $filter[] = array('"Member"."ID" <> ?' => $this->ID);
         }
         $existingRecord = DataObject::get_one('Member', $filter);
         if ($existingRecord) {
             throw new ValidationException(ValidationResult::create(false, _t('Member.ValidationIdentifierFailed', 'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))', 'Values in brackets show "fieldname = value", usually denoting an existing email address', array('id' => $existingRecord->ID, 'name' => $identifierField, 'value' => $this->{$identifierField}))));
         }
     }
     // We don't send emails out on dev/tests sites to prevent accidentally spamming users.
     // However, if TestMailer is in use this isn't a risk.
     if ((Director::isLive() || Email::mailer() instanceof TestMailer) && $this->isChanged('Password') && $this->record['Password'] && $this->config()->notify_password_change) {
         $e = Member_ChangePasswordEmail::create();
         $e->populateTemplate($this);
         $e->setTo($this->Email);
         $e->send();
     }
     // The test on $this->ID is used for when records are initially created.
     // Note that this only works with cleartext passwords, as we can't rehash
     // existing passwords.
     if (!$this->ID && $this->Password || $this->isChanged('Password')) {
         // Password was changed: encrypt the password according the settings
         $encryption_details = Security::encrypt_password($this->Password, $this->Salt, $this->PasswordEncryption ? $this->PasswordEncryption : Security::config()->password_encryption_algorithm, $this);
         // Overwrite the Password property with the hashed value
         $this->Password = $encryption_details['password'];
         $this->Salt = $encryption_details['salt'];
         $this->PasswordEncryption = $encryption_details['algorithm'];
         // If we haven't manually set a password expiry
         if (!$this->isChanged('PasswordExpiry')) {
             // then set it for us
             if (self::config()->password_expiry_days) {
                 $this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::config()->password_expiry_days);
             } else {
                 $this->PasswordExpiry = null;
             }
         }
     }
     // save locale
     if (!$this->Locale) {
         $this->Locale = i18n::get_locale();
     }
     parent::onBeforeWrite();
 }
Esempio n. 18
0
 /**
  * Validate
  *
  * @return ValidationResult
  **/
 protected function validate()
 {
     $valid = true;
     $message = null;
     $type = $this->Type;
     // Check if empty strings
     switch ($type) {
         case 'URL':
         case 'Email':
         case 'Phone':
             if ($this->{$type} == '') {
                 $valid = false;
                 $message = _t('Linkable.VALIDATIONERROR_EMPTY' . strtoupper($type), "You must enter a {$type} for a link type of \"{$this->LinkType}\"");
             }
             break;
         default:
             if ($this->TypeHasDbField) {
                 if ($type && empty($this->{$type})) {
                     $valid = false;
                     $message = _t('Linkable.VALIDATIONERROR_EMPTY', "You must enter a {$type} for a link type of \"{$this->LinkType}\"");
                 }
             } else {
                 if ($type && empty($this->{$type . 'ID'})) {
                     $valid = false;
                     $message = _t('Linkable.VALIDATIONERROR_OBJECT', "Please select a {value} object to link to", array('value' => $type));
                 }
             }
             break;
     }
     // if its already failed don't bother checking the rest
     if ($valid) {
         switch ($type) {
             case 'URL':
                 $allowedFirst = array('#', '/');
                 if (!in_array(substr($this->URL, 0, 1), $allowedFirst) && !filter_var($this->URL, FILTER_VALIDATE_URL)) {
                     $valid = false;
                     $message = _t('Linkable.VALIDATIONERROR_VALIDURL', 'Please enter a valid URL. Be sure to include http:// for an external URL. Or begin your internal url/anchor with a "/" character');
                 }
                 break;
             case 'Email':
                 if (!filter_var($this->Email, FILTER_VALIDATE_EMAIL)) {
                     $valid = false;
                     $message = _t('Linkable.VALIDATIONERROR_VALIDEMAIL', 'Please enter a valid Email address');
                 }
                 break;
             case 'Phone':
                 if (!preg_match("/^\\+?[0-9]{1,5}[- ]{0,1}[0-9]{3,4}[- ]{0,1}[0-9]{4}\$/", $this->Phone)) {
                     $valid = false;
                     $message = _t('Linkable.VALIDATIONERROR_VALIDPHONE', 'Please enter a valid Phone number');
                 }
                 break;
         }
     }
     $result = ValidationResult::create($valid, $message);
     $this->extend('updateValidate', $result);
     return $result;
 }
Esempio n. 19
0
 /**
  * Validate the current object.
  *
  * By default, there is no validation - objects are always valid!  However, you can overload this method in your
  * DataObject sub-classes to specify custom validation, or use the hook through DataExtension.
  * 
  * Invalid objects won't be able to be written - a warning will be thrown and no write will occur.  onBeforeWrite()
  * and onAfterWrite() won't get called either.
  * 
  * It is expected that you call validate() in your own application to test that an object is valid before
  * attempting a write, and respond appropriately if it isn't.
  * 
  * @see {@link ValidationResult}
  * @return ValidationResult
  */
 protected function validate()
 {
     $result = ValidationResult::create();
     $this->extend('validate', $result);
     return $result;
 }
 /**
  * Validate every component against given data.
  *
  * @param  array $data data to validate
  *
  * @return boolean validation result
  * @throws ValidationException
  */
 public function validateData($data)
 {
     $result = ValidationResult::create();
     foreach ($this->getComponents() as $component) {
         try {
             $component->validateData($this->order, $this->dependantData($component, $data));
         } catch (ValidationException $e) {
             //transfer messages into a single result
             foreach ($e->getResult()->messageList() as $code => $message) {
                 if (is_numeric($code)) {
                     $code = null;
                 }
                 if ($this->namespaced) {
                     $code = $component->namespaceFieldName($code);
                 }
                 $result->error($message, $code);
             }
         }
     }
     $this->order->extend('onValidateDataOnCheckout', $result);
     if (!$result->valid()) {
         throw new ValidationException($result);
     }
     return true;
 }
Esempio n. 21
0
 /**
  * Validate
  * @return ValidationResult
  **/
 protected function validate()
 {
     $valid = true;
     $message = null;
     if ($this->Type == 'URL') {
         if ($this->URL == '') {
             $valid = false;
             $message = _t('Linkable.VALIDATIONERROR_EMPTYURL', 'You must enter a URL for a link type of "URL"');
         } else {
             $allowedFirst = array('#', '/');
             if (!in_array(substr($this->URL, 0, 1), $allowedFirst) && !filter_var($this->URL, FILTER_VALIDATE_URL)) {
                 $valid = false;
                 $message = _t('Linkable.VALIDATIONERROR_VALIDURL', 'Please enter a valid URL. Be sure to include http:// for an external URL. Or begin your internal url/anchor with a "/" character');
             }
         }
     } elseif ($this->Type == 'Email') {
         if ($this->Email == '') {
             $valid = false;
             $message = _t('Linkable.VALIDATIONERROR_EMPTYEMAIL', 'You must enter an Email Address for a link type of "Email"');
         } else {
             if (!filter_var($this->Email, FILTER_VALIDATE_EMAIL)) {
                 $valid = false;
                 $message = _t('Linkable.VALIDATIONERROR_VALIDEMAIL', 'Please enter a valid Email address');
             }
         }
     } else {
         if ($this->Type && empty($this->{$this->Type . 'ID'})) {
             $valid = false;
             $message = _t('Linkable.VALIDATIONERROR_OBJECT', "Please select a {value} object to link to", array('value' => $this->Type));
         }
     }
     $result = ValidationResult::create($valid, $message);
     $this->extend('validate', $result);
     return $result;
 }