public function validate(ValidationResult $validationResult) { if ($this->owner->ID > 0 && $this->hasTokenChanged()) { $validationResult->combineAnd(new ValidationResult(false, _t('OptimisticLocking.NOSAVEREFRESH', "Save aborted as information has changed. Please refresh the page and try again.", 'User tried to save the dataobject but it had changed since they started working on it.'))); } return $validationResult; }
/** * @param String $password * @param Member $member * @return ValidationResult */ public function validate($password, $member) { $valid = new ValidationResult(); if ($this->minLength) { if (strlen($password) < $this->minLength) { $valid->error(sprintf("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::$character_strength_tests[$name], $password)) { $score++; } else { $missedTests[] = $name; } } if ($score < $this->minScore) { $valid->error("You need to increase the strength of your passwords by adding some of the following characters: " . implode(", ", $missedTests), "LOW_CHARACTER_STRENGTH"); } } if ($this->historicalPasswordCount) { $previousPasswords = DataObject::get("MemberPassword", "\"MemberID\" = {$member->ID}", "\"Created\" DESC, \"ID\" Desc", "", $this->historicalPasswordCount); if ($previousPasswords) { foreach ($previousPasswords as $previousPasswords) { if ($previousPasswords->checkPassword($password)) { $valid->error("You've already used that password in the past, please choose a new password", "PREVIOUS_PASSWORD"); break; } } } } return $valid; }
/** * Add errors from a validation object * * @param ValidationResult $validation * @param string $prefix */ public function add(ValidationResult $validation, $prefix = null) { $prefix = $this->translate($prefix); foreach ($validation->getErrors() as $err) { $this->errors[] = ($prefix ? trim($prefix) . ' ' : '') . $err; } }
/** * Validate the owner object - check for existence of infinite loops. */ function validate(ValidationResult $validationResult) { if (!$this->owner->ID) { return; } // The object is new, won't be looping. if (!$this->owner->ParentID) { return; } // The object has no parent, won't be looping. if (!$this->owner->isChanged('ParentID')) { return; } // The parent has not changed, skip the check for performance reasons. // Walk the hierarchy upwards until we reach the top, or until we reach the originating node again. $node = $this->owner; while ($node) { if ($node->ParentID == $this->owner->ID) { // Hierarchy is looping. $validationResult->error(_t('Hierarchy.InfiniteLoopNotAllowed', 'Infinite loop found within the "{type}" hierarchy. Please change the parent to resolve this', 'First argument is the class that makes up the hierarchy.', array('type' => $this->owner->class)), 'INFINITE_LOOP'); break; } $node = $node->ParentID ? $node->Parent() : null; } // At this point the $validationResult contains the response. }
/** * @param String $password * @param Member $member * @return ValidationResult */ public function validate($password, $member) { $valid = new ValidationResult(); 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 = DataObject::get("MemberPassword", "\"MemberID\" = {$member->ID}", "\"Created\" DESC, \"ID\" DESC", "", $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; }
/** * Attempt to find and authenticate member if possible from the given data. * * @param array $data * @param Form $form * @param bool &$success Success flag * @return Member Found member, regardless of successful login * @see MemberAuthenticator::authenticate_member() */ protected static function authenticate_member($data, $form, &$success) { // Default success to false $success = false; // Attempt to identify by temporary ID $member = null; $email = null; if (!empty($data['tempid'])) { // Find user by tempid, in case they are re-validating an existing session $member = Member::member_from_tempid($data['tempid']); if ($member) { $email = $member->Email; } } // Otherwise, get email from posted value instead if (!$member && !empty($data['Email'])) { $email = $data['Email']; } // Check default login (see Security::setDefaultAdmin()) the standard way and the "extension"-way :-) $asDefaultAdmin = $email === Security::default_admin_username(); if ($asDefaultAdmin || isset($GLOBALS['_DEFAULT_ADMINS']) && array_key_exists($email, $GLOBALS['_DEFAULT_ADMINS'])) { // If logging is as default admin, ensure record is setup correctly $member = Member::default_admin(); $success = Security::check_default_admin($email, $data['Password']); // If not already true check if one of the extra admins match if (!$success) { $success = $GLOBALS['_DEFAULT_ADMINS'][$email] == $data['Password']; } if ($success) { return $member; } } // Attempt to identify user by email if (!$member && $email) { // Find user by email $member = Member::get()->filter(Member::config()->unique_identifier_field, $email)->first(); } // Validate against member if possible if ($member && !$asDefaultAdmin) { $result = $member->checkPassword($data['Password']); $success = $result->valid(); } else { $result = new ValidationResult(false, _t('Member.ERRORWRONGCRED')); } // Emit failure to member and form (if available) if (!$success) { if ($member) { $member->registerFailedLogin(); } if ($form) { $form->sessionMessage($result->message(), 'bad'); } } else { if ($member) { $member->registerSuccessfulLogin(); } } return $member; }
public function validate() { $result = new ValidationResult(); if (!$this->Title || !$this->Currency || !$this->Rate) { $result->error('Please fill in all fields', 'ExchangeRateInvalidError'); } return $result; }
public function validate() { $result = new ValidationResult(); if (!$this->Title || !$this->Currency || !$this->Rate) { $result->error('Rate is missing a required field', 'ExchangeRateInvalidError'); } return $result; }
public function validate(\ValidationResult $validationResult) { $constraints = $this->getConstraints(); foreach ($constraints as $constraint) { if (!$constraint->holds()) { $validationResult->error($constraint->message()); } } }
public function validateData(Order $order, array $data) { $result = new ValidationResult(); //TODO: validate credit card data if (!Helper::validateLuhn($data['number'])) { $result->error('Credit card is invalid'); throw new ValidationException($result); } }
/** * Check if the user has verified their email address. * * @param ValidationResult $result * @return ValidationResult */ public function canLogIn(&$result) { if (!$this->owner->Verified) { // Don't require administrators to be verified if (Permission::checkMember($this->owner, 'ADMIN')) { return $result; } $result->error(_t('MemberEmailVerification.ERROREMAILNOTVERIFIED', 'Sorry, you need to verify your email address before you can log in.')); } return $result; }
public function validate(ValidationResult $validationResult) { $mailblockRecipients = $this->owner->getField('MailblockRecipients'); if (!$this->validateEmailAddresses($mailblockRecipients)) { $validationResult->error(_t('Mailblock.RecipientError', 'There are invalid email addresses in the Recipient(s) field.')); } $whitelist = $this->owner->getField('MailblockWhitelist'); if (!$this->validateEmailAddresses($whitelist)) { $validationResult->error(_t('Mailblock.WhitelistError', 'There are invalid email addresses in the Whitelist field.')); } }
public function validateData(Order $order, array $data) { $result = new ValidationResult(); if (!isset($data['ShippingMethodID'])) { $result->error(_t('ShippingCheckoutComponent.ShippingMethodNotProvidedMessage', "Shipping method not provided"), _t('ShippingCheckoutComponent.ShippingMethodErrorCode', "ShippingMethod")); throw new ValidationException($result); } if (!ShippingMethod::get()->byID($data['ShippingMethodID'])) { $result->error(_t('ShippingCheckoutComponent.ShippingMethodDoesNotExistMessage', "Shipping Method does not exist"), _t('ShippingCheckoutComponent.ShippingMethodErrorCode', "ShippingMethod")); throw new ValidationException($result); } }
/** * Check if the user has verified their email address. * * @param ValidationResult $result * @return ValidationResult */ function canLogIn(&$result) { if (!Permission::check('ADMIN')) { if (!$this->owner->Verified) { $result->error(_t('EmailVerifiedMember.ERRORNOTEMAILVERIFIED', 'Please verify your email address before login.')); } if (!$this->owner->Moderated && $this->owner->requiresModeration()) { $result->error(_t('EmailVerifiedMember.ERRORNOTMODERATED', 'A moderator needs to approve your account before you can log in.')); } } return $result; }
public function validateData(Order $order, array $data) { $result = new ValidationResult(); if (!isset($data['PaymentMethod'])) { $result->error("Payment method not provided", "PaymentMethod"); throw new ValidationException($result); } $methods = GatewayInfo::get_supported_gateways(); if (!isset($methods[$data['PaymentMethod']])) { $result->error("Gateway not supported", "PaymentMethod"); throw new ValidationException($result); } }
/** * Test combining validation results together */ public function testCombineResults() { $result = new ValidationResult(); $anotherresult = new ValidationResult(); $yetanotherresult = new ValidationResult(); $anotherresult->error("Eat with your mouth closed", "EATING101"); $yetanotherresult->error("You didn't wash your hands", "BECLEAN"); $this->assertTrue($result->valid()); $this->assertFalse($anotherresult->valid()); $this->assertFalse($yetanotherresult->valid()); $result->combineAnd($anotherresult)->combineAnd($yetanotherresult); $this->assertFalse($result->valid()); $this->assertEquals(array("EATING101" => "Eat with your mouth closed", "BECLEAN" => "You didn't wash your hands"), $result->messageList()); }
/** * @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 (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); } }
public function validateData(Order $order, array $data) { if (isset($data['RegisterAnAccount']) && $data['RegisterAnAccount']) { return parent::validateData($order, $data); } return ValidationResult::create(); }
/** * Validate * @return ValidationResult **/ protected function validate() { $valid = true; $message = null; $result = ValidationResult::create($valid, $message); return $result; }
/** * Construct a new ValidationException with an optional ValidationResult object * * @param ValidationResult|string $result The ValidationResult containing the * failed result. Can be substituted with an error message instead if no * ValidationResult exists. * @param string|integer $message The error message. If $result was given the * message string rather than a ValidationResult object then this will have * the error code number. * @param integer $code The error code number, if not given in the second parameter */ public function __construct($result = null, $message = null, $code = 0) { // Check arguments if (!$result instanceof ValidationResult) { // Shift parameters if no ValidationResult is given $code = $message; $message = $result; // Infer ValidationResult from parameters $result = new ValidationResult(false, $message); } elseif (empty($message)) { // Infer message if not given $message = $result->message(); } // Construct $this->result = $result; parent::__construct($message, $code); }
/** * 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 = new ValidationResult(); 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 (ShopMember::get_by_identifier($idval)) { $result->error(sprintf(_t("Checkout.MEMBEREXISTS", "A member already exists with the %s %s"), _t("Member." . $idfield, $idfield), $idval)); throw new ValidationException($result); } $member = new Member(Convert::raw2sql($data)); $validation = $member->validate(); if (!$validation->valid()) { //TODO need to handle i18n here? $result->error($validation->message()); } if (!$result->valid()) { throw new ValidationException($result); } return $member; }
/** * Check if the file must be accepted, or not * * @param \SplFileInfo $archive * @return bool */ public function validate(\SplFileInfo $archive) { $zip = new \ZipArchive(); $pathname = $archive->getPathname(); $result = new ValidationResult(); $open = $zip->open($pathname, \ZipArchive::CHECKCONS); if (true === $open) { $result->setValid(true); } else { switch ((int) $open) { case \ZipArchive::ER_NOZIP: $result->setMessage('Not a zip archive:' . $pathname); break; case \ZipArchive::ER_INCONS: $result->setMessage('Zip archive inconsistent:' . $pathname); break; case \ZipArchive::ER_CRC: $result->setMessage('CRC error:' . $pathname); break; case \ZipArchive::ER_OPEN: $result->setMessage('Can\'t open file:' . $pathname); break; } } return $result; }
public function validate(ValidationResult $validationResult) { if (!$this->owner->Category) { $validationResult->combineAnd(new ValidationResult(false, _t('DMSTagExtension.NoCategory', 'You must at least enter a category.'))); } else { $this->owner->Category = trim($this->owner->Category); // this is done to prevent the method 'removeTag' in 'DMSDocument' to erase all the tags with same category if no value is defined on the removing Tag if (!$this->owner->Value) { $this->owner->Value = self::$undefinedValue; } else { $this->owner->Value = trim($this->owner->Value); } $query = "SELECT COUNT(*) FROM \"DMSTag\" WHERE \"DMSTag\".\"Category\" LIKE '{$this->owner->Category}' AND \"DMSTag\".\"Value\" LIKE '{$this->owner->Value}'"; if (DB::query($query)->value()) { $validationResult->combineAnd(new ValidationResult(false, _t('DMSTagExtension.CategoryValueNotUnique', 'This tag already exists. Please select it from the multiselect box.'))); } } }
/** * Validate the form controls, validates by the required status, and some specific control validations * such as email control * @return \bootbuilder\Validation\ValidationResult */ public function validate() { $status = new ValidationResult(); // Check if the form is loaded if (!$this->form instanceof \bootbuilder\Form) { $status->setError(true); return $status; } // Validate form controls (and panes) foreach ($this->form->getRawControls() as $nr => $control) { if (!$this->validateControl($control, $status)) { $status->setError(true); $control->setErrorState(true); } $this->form->replaceControl($nr, $control); } return $status; }
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); } }
public function validateData(Order $order, array $data) { $result = new ValidationResult(); $code = $data['Code']; if ($this->validwhenblank && !$code) { return $result; } //check the coupon exists, and can be used if ($coupon = OrderCoupon::get_by_code($code)) { if (!$coupon->validateOrder($order, array("CouponCode" => $code))) { $result->error($coupon->getMessage(), "Code"); throw new ValidationException($result); } } else { $result->error(_t("OrderCouponModifier.NOTFOUND", "Coupon could not be found"), "Code"); throw new ValidationException($result); } return $result; }
/** * @param $value * @param IValidationData $data * * @return ValidationResult */ public function check($value, IValidationData $data = null) { $result = new ValidationResult(); foreach ($this->getConstraints() as $constraint) { if (!$constraint->check($value, $data)) { $result->addError(new ValidationError($this->getName(), $value, $constraint)); } } return $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; }