function assertNotValid($data, $errors)
 {
     $validator = new Validator();
     $validator->check($data, $this->schema);
     $this->assertEquals($errors, $validator->getErrors(), print_r($validator->getErrors(), true));
     $this->assertFalse($validator->isValid());
 }
Esempio n. 2
0
 protected function actionLogin()
 {
     if ($this->_auth->getAuthStatus()) {
         header("Location: /");
     }
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $validator = new Validator();
         $validator->setData($_POST);
         if ($validator->checkFieldsForEmpty(['email', 'password'])->validationResult()) {
             $email = $validator->getData('email');
             $password = md5(Config::SECRET . $validator->getData('password'));
             $login_result = $this->_link->select('users', ['id', 'login', 'role'])->selectWHERE_AND(['email' => $email, 'password' => $password])->sendSelectQuery();
             if ($login_result->num_rows != 0) {
                 $user = $login_result->fetch_assoc();
                 $_SESSION['user_id'] = $user['id'];
                 $_SESSION['role'] = $user['role'];
                 header("Location: " . $_SERVER['HTTP_REFERER']);
             } else {
                 $this->_error->loginError('auth falied');
             }
         } else {
             $this->_error->formError($validator->getErrors());
         }
     }
     $this->render('login');
 }
Esempio n. 3
0
 public function validateUniqueEmailFailed(array $data)
 {
     $v = new Validator($data, array(new Unique("email", "field must be unique", "customer")));
     if (!$v->execute()) {
         print_r($v->getErrors());
     } else {
         return true;
     }
 }
Esempio n. 4
0
 /**
  * Validate form arguments
  *
  * @param $args
  * @param $defaults
  * @return array
  * @throws \Exception
  */
 protected static function validate($args)
 {
     $validation = new Validator(static::$rules, $args, static::$defaults);
     if ($validation->fails()) {
         $errors = $validation->getErrors();
         $err_msg = self::validationErrorMsg($errors);
         throw new \Exception($err_msg);
     }
     return $validation->getArgs();
 }
Esempio n. 5
0
 /**
  * 验证数据
  */
 public function validate($data)
 {
     $fields = self::getFields();
     $validator = new Validator($fields, $data);
     $this->data = $validator->validate();
     if (!$this->data) {
         $this->errors = $validator->getErrors();
         return false;
     }
     return true;
 }
Esempio n. 6
0
 /**
  * @return array
  */
 public function getAttributes()
 {
     $attrs = array('id' => $this->FormName(), 'action' => $this->FormAction(), 'method' => $this->FormMethod(), 'enctype' => $this->getEncType(), 'target' => $this->target, 'class' => $this->extraClass());
     if ($this->validator && $this->validator->getErrors()) {
         if (!isset($attrs['class'])) {
             $attrs['class'] = '';
         }
         $attrs['class'] .= ' validationerror';
     }
     $attrs = array_merge($attrs, $this->attributes);
     return $attrs;
 }
Esempio n. 7
0
 /**
  * Returns the ValidationError objects for the errors and warnings that should be displayed.
  *
  * @since 0.4
  *
  * @return array of array of ValidationError
  */
 protected function getErrorsToDisplay()
 {
     $errors = array();
     $warnings = array();
     foreach ($this->validator->getErrors() as $error) {
         // Check if the severity of the error is high enough to display it.
         if ($error->shouldShow()) {
             $errors[] = $error;
         } elseif ($error->shouldWarn()) {
             $warnings[] = $error;
         }
     }
     return array('errors' => $errors, 'warnings' => $warnings);
 }
Esempio n. 8
0
 public function img_profil($db, $user_id, $image, $path)
 {
     $validator = new Validator($_POST);
     $validator->isSize($image, 'Votre photo est trop lourde.');
     $validator->isExtension($image, 'Vous ne pouvez mettre que des fichiers avec les extensions suivantes : png, gif, jpg, jpeg.');
     $uploadfile = basename($_FILES[$image]['name']);
     $uploadfile = strtr($uploadfile, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
     $img = $path . $uploadfile;
     if ($validator->isValid()) {
         $this->field_img($db, $user_id, $img, $image);
         move_uploaded_file($_FILES[$image]['tmp_name'], $img);
         $info_user = $this->checkId($db, $user_id);
         return $info_user->image = $img;
     } else {
         return $errors = $validator->getErrors();
     }
 }
Esempio n. 9
0
 /**
  * You can perform a single validation by using this method.
  * Result of validate() method (boolean) will be returned.
  *
  * @param $name string - Name of validator
  * @param $value mixed - Value to validate. If array,
  * all keys are taken as attributes and values as values.
  * @param $params array - Params for a validator
  * @return object
  * @throws \Exception
  */
 public static function validateFor($name, $value, array $params = [])
 {
     if (!is_string($name)) {
         throw new \UnexpectedValueException("Validator name must be a string, " . gettype($name) . " given");
     }
     $rules = [];
     # By default, empty value should be not valid
     $params = array_merge(['allowEmpty' => false], $params);
     if (is_array($value)) {
         $rules[] = array_merge([array_keys($value), $name], $params);
     } else {
         $rules[] = array_merge([$name, $name], $params);
         $value = [$name => $value];
     }
     $v = new Validator();
     $result = new \stdClass();
     $result->isValid = $v->setRules($rules)->loadData($value)->validate();
     $result->lastError = $v->getLastError();
     $result->errors = $v->getErrors();
     unset($v);
     return $result;
 }
Esempio n. 10
0
 /**
  * Validates the layer.
  * 
  * @since 0.7.1
  */
 protected function validate()
 {
     $validator = new Validator();
     $validator->setParameters($this->properties, $this->getParameterDefinitions(array()));
     $validator->validateParameters();
     if ($validator->hasFatalError() !== false) {
         $this->errors = $validator->getErrors();
     }
     $this->properties = $validator->getParameterValues();
 }
Esempio n. 11
0
<?php

require_once '../autoload.php';
require_once '../include/results.php';
//rajouter order bye et condition si reply ou origine et recuper donner(function dans class)
$tweet = new Tweet($user_id);
// $tweet->getIdTweet();
/*var_dump($p = new Tweet($user_id, 2));
var_dump($p->getIdTweet());*/
// var_dump($p = new Tweet($user_id));
// var_dump($p->Tweet_follower($user_id));
if (isset($_FILES['file-input']) && !empty($_FILES['file-input']['name'])) {
    $uploaddir = '../view/img-user/tweet/';
    $validator = new Validator($_POST);
    $validator->isSize('file-input', 'You picture is too oversized');
    $validator->isExtension('file-input', 'You must upload a type of picture with png, gif, jpg, jpeg, please.');
    $uploadfile = basename($_FILES['file-input']['name']);
    $uploadfile = strtr($uploadfile, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
    $img_tweet = $uploaddir . $uploadfile;
    if ($validator->isValid()) {
        move_uploaded_file($_FILES['file-input']['tmp_name'], $img_tweet);
        $tweet->newTweet($img_tweet);
        /*$info_user->avatar = $avatar;*/
    } else {
        $errors = $validator->getErrors();
    }
} else {
    $tweet->newTweet();
}
require_once '../view/accueil.php';
 public function testMixedTypes()
 {
     $tests = array(array("expect" => "array|bool|numeric|string", "got" => array("one"), "valid" => true), array("expect" => "array|bool|numeric|string", "got" => false, "valid" => true), array("expect" => "array|bool|numeric|string", "got" => 123, "valid" => true), array("expect" => "array|bool|numeric|string", "got" => "mystring", "valid" => true), array("expect" => "array|numeric", "got" => array("one"), "valid" => true), array("expect" => "array|numeric", "got" => 123, "valid" => true), array("expect" => "array|numeric", "got" => "mystring", "valid" => false), array("expect" => "array<string>|array<bool>", "got" => 123, "valid" => false), array("expect" => "array<string>|array<bool>", "got" => array("one", "two"), "valid" => true), array("expect" => "array<string>|array<bool>", "got" => array(true, true, false), "valid" => true), array("expect" => "array<string>|array<bool>", "got" => array(4.5, 7.8, 91.2), "valid" => false));
     foreach ($tests as $test) {
         $validation = new Validator(array('arg' => $test['expect']), array('arg' => $test['got']));
         $got = is_array($test['got']) ? implode(",", $test['got']) : $test['got'];
         $msg = sprintf("Testing %s with value=[%s], valid=%b.  Error: %s", $test['expect'], $got, $test['valid'], implode(" ", $validation->getErrors()));
         $this->assertEquals($test['valid'], $validation->passes(), $msg);
     }
 }
<?php

// Require app files
require 'app/User.php';
require 'app/Validator.php';
require 'app/Helper.php';
// Set data and validation rules
$rules = array('email' => 'required|email', 'password' => 'required|min:8');
$data = array('email' => '*****@*****.**', 'password' => '12346789');
// Run validation
$validator = new Validator();
if ($validator->validate($data, $rules) == true) {
    // Validation passed. Set user values.
    $joost = new User();
    // method chaining is used
    $joost->setEmail($data['email'])->setPassword(getHash($data['password']));
    // Dump user
    var_dump($joost);
} else {
    // Validation failed. Dump validation errors.
    var_dump($validator->getErrors());
}
<?php

if (!isset($_POST['name'])) {
    die;
}
require __DIR__ . '/Validator.php';
require __DIR__ . '/Mailer.php';
$validator = new Validator();
if (!$validator->validate()) {
    echo json_encode(array('success' => 'false', 'errors' => $validator->getErrors()));
    die;
}
$mail = new Mailer();
$mail->addAddress("*****@*****.**");
$msg = "\nHallo,<br /><br />\n\nHet contactformulier op uw website is ingevuld. Hieronder staan de ingevoerde gegevens:<br /><br />\n\n<table>";
if (isset($_POST['message'])) {
    $_POST['message'] = nl2br($_POST['message']);
}
foreach ($_POST as $key => $value) {
    if (is_array($value)) {
        $value = implode(", ", $value);
    }
    $msg .= "<tr>\n    <td>" . $key . "</td>\n    <td>" . $value . "</td>\n</tr>";
}
$msg .= "</table><br />";
$mail->setHTMLBody($msg);
if ($mail->send()) {
    echo json_encode(array('success' => true));
    exit;
}
echo json_encode(array('success' => false));
Esempio n. 15
0
 /**
  * Validates the layer.
  * 
  * @since 0.7.1
  */
 protected function validate()
 {
     if ($this->hasValidated) {
         return;
     }
     $this->hasValidated = true;
     $validator = new Validator();
     $validator->setParameters($this->properties, $this->getParameterDefinitions());
     $validator->validateParameters();
     if ($validator->hasErrors() !== false) {
         $this->errors = $validator->getErrors();
     }
     $params = $validator->getParameterValues();
     $this->properties = $params;
 }
 public function process_sagepay()
 {
     // pass the card and billing data to a static method in the
     // sagepay class to be formatted and returned.
     $data = SagePay::formatRawData($_POST);
     $validator = new Validator($data);
     $validator->filledIn("BillingFirstnames");
     $validator->filledIn("BillingSurname");
     $validator->filledIn("BillingAddress1");
     $validator->filledIn("BillingCity");
     $validator->filledIn("BillingCountry");
     $validator->filledIn("CardType");
     $validator->filledIn("CardNumber");
     $validator->filledIn("CV2");
     $validator->filledIn("ExpiryDateMonth");
     $validator->filledIn("ExpiryDateYear");
     $validator->filledIn("Amount");
     $errors = $validator->getErrors();
     $id = $validator->getId();
     $error_message = array('BillingFirstnames' => 'First name can not be left blank', 'BillingSurname' => 'Last name can not be left blank', 'BillingAddress1' => 'Address can not be left blank', 'BillingCity' => 'City can not be left blank', 'BillingCountry' => 'Country can not be left blank', 'Amount' => 'Amount can not be left blank', 'CardNumber' => 'Card number can not be left blank', 'ExpiryDateMonth' => 'Expiry month can not be left blank', 'ExpiryDateYear' => 'Expiry year can not be left blank', 'CardType' => 'Card type can not be left blank', 'CV2' => 'CV2 can not be left blank');
     if (!empty($errors)) {
         echo "Error:<br>";
         foreach ($errors as $key => $value) {
             echo $error_message[$key] . "<br>";
         }
         exit;
     }
     $description = isset($_SESSION['SAGEPAY_DATA']['description']) ? $_SESSION['SAGEPAY_DATA']['description'] : '';
     if (!empty($description)) {
         $data['description'] = $description;
     }
     // instantiate the SagePay object, passing it this formatted data.
     $payment = new SagePay($data);
     // execute the payment request
     $payment->execute();
     if ($payment->status == '3dAuth') {
         // SagePay has returned a request for 3DSecure authentication
         // returned by SagePay on request for 3DSecure authentication
         $_SESSION['payment']['acsurl'] = $payment->acsurl;
         // returned by SagePay on request for 3DSecure authentication
         $_SESSION['payment']['pareq'] = $payment->pareq;
         // Store the transaction code that you set for passing to 3DSecure
         $_SESSION['payment']['vendorTxCode'] = $payment->vendorTxCode;
         // returned by SagePay on request for 3DSecure authentication
         $_SESSION['payment']['md'] = $payment->md;
         // set a flag so your code knows to load the 3D Secure page.
         $secure_auth = true;
         echo "3dAuth";
         exit;
     } else {
         if ($payment->status == 'success') {
             // Transaction successful. Redirect to your complete page
             echo "success";
             exit;
         } else {
             echo $_SESSION['error'] = $payment->error;
         }
     }
 }
Esempio n. 17
0
})->name('password');
$app->post('/password', function () use($app) {
    $db = $app->db;
    $cookieGet = new Cookie();
    $cookie = $cookieGet->getCookie($app);
    $logged = new Logged();
    $user_id = $logged->getLogged($db, $cookie);
    $login = new Login();
    $log = $login->getLogin($user_id, $db);
    if ($log != 'Anonymous') {
        $app->redirect("/TwigBlog");
    } else {
        $userpost = new UserPost();
        $postarr = $userpost->post($_POST);
        $validator = new Validator($db, $app);
        $validator->getErrors($postarr);
    }
    //checking if user exists
    /*
            $user = new User();
            $user->login=$login;
            $user->email=$email;
            $Usermapper = new UserMapper($db);
            $users=$Usermapper->select($user);
            $errors = array();    
            if(!empty($users)){
         array_push($errors, "Such user already exists");
       $app->render('Password.php', ['login'=>$login, 'email'=>$email, 'errors'=>$errors]);
            }
            //cheking if password doesn't match
            elseif($password!=$confirmPass){
 /**
  * return errors which refer to object
  *
  * @return array
  */
 public function getErrors()
 {
     return $this->_validator->getErrors();
 }
Esempio n. 19
0
 /**
  * Runs all of the validation checks on the elements using the
  * validatiors that are stored
  *
  * @return bool
  */
 public function isValid()
 {
     if ($this->csrfToken === true && !$this->_input->checkToken()) {
         // CSRF protection failed!
         if ($this->storeErrors === true) {
             $this->_event->error(Input::csrfMsg());
         }
         return false;
     }
     foreach ($this->elements as $element) {
         try {
             $value = $this->_input->get($element['input_name'], $element['source']);
         } catch (Input_KeyNoExist $e) {
             if ($element['required'] === true) {
                 throw $e;
             } else {
                 continue;
             }
         }
         // Store the input names value correclty as a multi-dimensional array
         $tmpVal = $value;
         foreach (array_reverse(preg_split('#(?<!\\\\)/#', trim($element['input_name'], '/'))) as $v) {
             $tmpVal = array($v => $tmpVal);
         }
         $this->values = zula_merge_recursive($this->values, $tmpVal);
         $count = is_array($value) ? count($value) : strlen($value);
         if ($element['required'] === false && $count == 0) {
             continue;
         }
         // Check if it is valid
         $validator = new Validator($value, $element['title']);
         foreach (array_filter($element['validators']) as $tmpValidator) {
             $validator->add($tmpValidator);
         }
         if ($validator->validate() === false) {
             $this->valid = false;
             if ($this->storeErrors === true) {
                 // Store all errors (if any)
                 foreach ($validator->getErrors() as $error) {
                     $this->_event->error($error);
                 }
             }
         }
     }
     // Check if the antispam was successful, if enabled
     if ($this->valid && $this->antispam === true) {
         $antispam = new Antispam();
         if (!$antispam->check()) {
             $this->valid = false;
             if ($this->storeErrors === true) {
                 $this->_event->error(t('Sorry, incorrect answer to the captcha', I18n::_DTD));
             }
         }
     }
     return $this->valid;
 }