Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends Validator
 protected function sendImmediateNotify($errorLog, $status_code)
 {
     $immediateNotifyEnabled = Yii::$app->getModule('core')->immediateNotice;
     if ($immediateNotifyEnabled == 1) {
         $httpCodesForNotify = explode(",", Yii::$app->getModule('core')->httpCodesForImmediateNotify);
         if (strlen($httpCodesForNotify[0]) > 0) {
             if (!in_array($status_code, $httpCodesForNotify)) {
                 return;
             }
         }
         $notifyEmail = Yii::$app->getModule('core')->devmail;
         $validator = new EmailValidator();
         if ($validator->validate($notifyEmail)) {
             $errorUrl = $errorLog->getErrorUrl()->one();
             if ($errorUrl->immediate_notify_count < Yii::$app->getModule('core')->immediateNoticeLimitPerUrl) {
                 $errorUrl->immediate_notify_count++;
                 $errorUrl->update();
                 $info = ['url' => $errorUrl->url, 'message' => $errorLog->info, 'http_code' => $errorLog->http_code, 'request_vars' => $errorLog->request_vars, 'server_vars' => $errorLog->server_vars];
                 try {
                     Yii::$app->mail->compose('@app/views/notifications/immediate_notify.php', ['info' => $info])->setTo($notifyEmail)->setFrom(Yii::$app->mail->transport->getUsername())->setSubject("ErrorMonitor immediate notify")->send();
                 } catch (\Exception $e) {
                     // do nothing
                 }
             }
         }
     }
 }
Beispiel #2
0
 /**
  * @param $fld - название поля
  * @param $par - типпроверки
  * @param bool|true $add_err записывать в массив ошибок или нет
  * @return bool
  */
 protected function validate($fld, $par, $add_err = true)
 {
     $name = $this->fld_name[$fld];
     $ret = true;
     switch ($par) {
         case 'req':
             if ($this->{$fld} == '') {
                 $ret = false;
                 if ($add_err === true) {
                     Core::error('Поле <strong>"' . $name . '"</strong> обязательно к заполнению', $fld);
                 }
             }
             break;
         case 'email':
             $validator = new EmailValidator();
             if (!$validator->validate($this->{$fld})) {
                 $ret = false;
                 if ($add_err === true) {
                     Core::error('Некорректный email - <strong>' . $name . '</strong>', $fld);
                 }
             }
             break;
     }
     return $ret;
 }
    private function validateAsEmail($model,$attribute){

        $validator = new EmailValidator();

        if(!$validator->validate($model->$attribute)){
            $model->addError('username' ,'Must Be a valid Email');
        }

    }
Beispiel #4
0
 private function checkIsLoginMail()
 {
     $validator = new EmailValidator();
     if ($validator->validate($this->email) == true) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * @param string $value the email
  *
  * @throws InvalidConfigException
  */
 public function setEmail($value)
 {
     $error = null;
     $validator = new EmailValidator();
     if (!$validator->validate($value, $error)) {
         throw new InvalidConfigException($error);
     }
     $this->email = $value;
 }
 /**
  * @param $id BroadcastSend->id
  * @return bool
  */
 public function actionSend($id)
 {
     if (!$id) {
         return false;
     }
     $broadcast_send = BroadcastSend::findOne($id);
     $broadcast_files = BroadcastFiles::find()->where(['broadcast_id' => $broadcast_send->broadcast_id])->all();
     $view = $broadcast_send->broadcast->broadcastLayout->layout_path;
     $title = $broadcast_send->broadcast->title;
     $broadcast_addresses = BroadcastAddress::find()->where(['broadcast_send_id' => $id, 'status' => 0])->all();
     $messages = [];
     /** @var $address BroadcastAddress */
     foreach ($broadcast_addresses as $address) {
         $email = $address->user_id ? $address->user->email : $address->email;
         $emailValidator = new EmailValidator();
         if (!$emailValidator->validate($email)) {
             continue;
         }
         $fio = $address->fio;
         $company = '';
         //$content = preg_replace('/{{content}}/', $broadcast_send->broadcast->broadcastLayout->content, $this->handleContent($broadcast_send->broadcast));
         $content = $this->handleContent($broadcast_send->broadcast, '', '');
         if ($broadcast_send->broadcast->broadcastLayout->content) {
             $content = preg_replace('/{{content}}/', $content, $broadcast_send->broadcast->broadcastLayout->content);
         }
         $mailer = Yii::$app->mailer->compose($view, ['content' => $content]);
         if ($broadcast_files) {
             foreach ($broadcast_files as $file) {
                 $attach_file = Yii::getAlias('@backend/web') . preg_replace('/^' . addcslashes(Yii::$app->params['broadcast']['clearMngUrl'], '/') . '/', '', $file->file);
                 if (is_file($attach_file)) {
                     $mailer = $mailer->attach($attach_file);
                 }
             }
         }
         $mailer->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])->setTo($email)->setSubject($title);
         try {
             $mailer->send();
             $address->status = 1;
             $address->update();
         } catch (\Exception $e) {
             echo "ERROR: " . $e . "\n";
         }
     }
     try {
         Yii::$app->mailer->sendMultiple($messages);
     } catch (Exception $e) {
         echo "Error\n";
     }
     $broadcast_send->status = 1;
     if ($broadcast_send->update()) {
         return true;
     }
     return false;
 }
 public function rules()
 {
     return ArrayHelper::merge(parent::rules(), [[['enabledBeforeApproval'], 'string'], [['maxValue'], 'integer', 'min' => 5, 'max' => 1000], [['securityRateLimitRequests'], 'integer'], [['securityRateLimitTime'], 'integer'], [['elementPropertyRatingCode'], 'string'], [['elementPropertyCountCode'], 'string'], [['messageSuccessBeforeApproval'], 'string'], [['messageSuccess'], 'string'], [['notify_emails'], 'string'], [['notifyPhones'], 'safe'], [['maxCountMessagesForUser'], 'integer'], [['enabledFieldsOnGuest'], 'safe'], [['enabledFieldsOnUser'], 'safe'], [['securityEnabledRateLimit'], 'string'], [['enabledBeforeApproval', 'securityEnabledRateLimit'], 'in', 'range' => array_keys(\Yii::$app->cms->booleanFormat())], [['notify_emails'], function ($attribute) {
         if ($this->notifyEmails) {
             foreach ($this->notifyEmails as $email) {
                 $validator = new EmailValidator();
                 if (!$validator->validate($email, $error)) {
                     $this->addError($attribute, $email . ' — ' . \Yii::t('skeeks/reviews2', 'Incorrect email address'));
                     return false;
                 }
             }
         }
     }]]);
 }
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return ArrayHelper::merge(parent::rules(), [[['created_by', 'updated_by', 'created_at', 'updated_at'], 'integer'], [['name'], 'required'], [['description'], 'string'], [['emails', 'phones', 'user_ids'], 'string'], [['name'], 'string', 'max' => 255], [['code'], 'string', 'max' => 32], [['code'], 'unique'], [['emails'], function ($attribute) {
         if ($this->emailsAsArray) {
             foreach ($this->emailsAsArray as $email) {
                 $validator = new EmailValidator();
                 if (!$validator->validate($email, $error)) {
                     $this->addError($attribute, $email . ' — ' . \Yii::t('skeeks/form2/app', 'Incorrect email address'));
                     return false;
                 }
             }
         }
     }]]);
 }
 public function checkAccount()
 {
     $ev = new EmailValidator();
     if ($ev->validate($this->account)) {
         $model = User::findOne(['email' => $this->account]);
         if ($model != null) {
             $this->id = $model->id;
         }
         return $model;
     } else {
         $model = User::findOne(['username' => $this->account]);
         if ($model != null) {
             $this->id = $model->id;
         }
         return $model;
     }
 }
Beispiel #10
0
 public function actionSubscribe()
 {
     if (Yii::$app->request->isAjax) {
         $email = Yii::$app->request->post('email');
         $validator = new EmailValidator();
         if ($validator->validate($email)) {
             $mc = new Mailchimp(Config::find()->where('name = :name', [':name' => 'mailChimpKey'])->one()->value);
             $Mailchimp_Lists = new Mailchimp_Lists($mc);
             $subscriber = $Mailchimp_Lists->subscribe(Config::find()->where('name = :name', [':name' => 'mailChimpListId'])->one()->value, array('email' => htmlentities($email)));
             if (!empty($subscriber['leid'])) {
                 echo "'Ваш электронный адрес добавлен в подписчики'";
             } else {
                 echo "error";
             }
         } else {
             echo "Неправильный электронный адрес";
         }
     }
 }
Beispiel #11
0
 /**
  * @param $email
  * @return \Generator
  * @throws InvalidParamException
  */
 private function doSetup($email)
 {
     //check email
     $validator = new EmailValidator();
     $validator->checkDNS = true;
     if (!$validator->validate($email)) {
         throw new InvalidParamException($validator->message);
     }
     $keyFile = $this->serverToKeyName();
     try {
         $keyPair = $this->getKeyStorage()->get($keyFile);
     } catch (FilesystemException $e) {
         $keyPair = (new OpenSSLKeyGenerator())->generate($this->keyLength);
         $keyPair = $this->getKeyStorage()->put($keyFile, $keyPair);
     }
     $acme = $this->getAcmeService($keyPair);
     /** @var Registration $registration */
     $registration = (yield $acme->register($email));
     (yield new CoroutineResult($registration));
 }
 /**
  * Implementa le stesse funzionalità del metodo {@link validateValue}, ma restituisce
  * il motivo per cui la validazione è fallita:
  * <ul>
  * <li>{@link EmailValidator::ERROR_SYNTAX}: sintassi errata</li>
  * <li>{@link EmailValidator::ERROR_DOMAIN}: dominio inesistente (se il controllo è richiesto esplicitamente)</li>
  * <li>{@link EmailValidator::ERROR_NONE}: indirizzo valido</li>
  * </ul>
  * Se la mail da validare è null o stringa vuota la validazione viene considerata superata.
  * @param string $value Email da validare
  * @param boolean $checkDomain Se true richiede che venga verificata anche l'esistenza del dominio
  * @return string Errore di validazione (vedi costanti della classe)
  */
 public function validateValueWithResponse($value, $checkDomain = false)
 {
     if ($value == null || strlen(trim($value)) == 0) {
         return self::ERROR_NONE;
     }
     if (parent::validateValue($value) === null) {
         if ($checkDomain === true) {
             list($address, $host) = explode('@', $value);
             return checkdnsrr($host) ? self::ERROR_NONE : self::ERROR_DOMAIN;
         }
         return self::ERROR_NONE;
     }
     return self::ERROR_SYNTAX;
 }
 /**
  * Email validation.
  *
  * @param $attribute
  */
 public function validateEmails($attribute)
 {
     $items = $this->{$attribute};
     if (!is_array($items)) {
         $items = [];
     }
     foreach ($items as $index => $item) {
         $validator = new EmailValidator();
         $error = null;
         $validator->validate($item, $error);
         if (!empty($error)) {
             $key = $attribute . '[' . $index . ']';
             $this->addError($key, $error);
         }
     }
 }
 /**
  * Used to validate any emails going into Mandrill
  * @param string $email
  * @return boolean Whether the supplied argurment is a valid email or not
  */
 protected function validateEmail($email)
 {
     $validator = new EmailValidator();
     return $validator->validate($email);
 }
Beispiel #15
0
 /**
  * Save user profile
  * @return boolean whether the user is created successfully
  */
 public function saveProfile()
 {
     if (YII_DEBUG) {
         error_log("[ProfileForm::saveProfile]");
     }
     if (YII_DEBUG) {
         error_log("[ProfileForm::saveProfile] attributes : " . json_encode($this->getAttributes()));
     }
     if ($this->isEditable) {
         $formData = Yii::$app->request->post('ProfileForm');
         if ($formData) {
             $this->processFileField('photo', $this->_user);
             $_email = isset($formData['email']) ? strval($formData['email']) : null;
             if ($_email && $this->_user->email !== $_email) {
                 $v = new EmailValidator();
                 $err = null;
                 if ($v->validate($_email)) {
                     $u = User::findOne(['email' => $_email]);
                     if (null !== $u) {
                         $err = 'Email already exists';
                     } else {
                         $this->_user->email = $_email;
                     }
                 } else {
                     $err = 'Not a valid email address';
                 }
                 if ($err) {
                     Yii::$app->session->addFlash('email', $err);
                 }
             }
             $_phone = isset($formData['phone']) ? strval($formData['phone']) : null;
             if ($_phone && 0 == $this->_user->phone_verified && $this->_user->phone !== $_phone) {
                 $err = User::validatePhone($_phone);
                 if (true === $err) {
                     $u = User::findOne(['phone' => $_phone]);
                     if (null !== $u) {
                         $err = 'Phone already exists';
                     } else {
                         $this->_user->phone = $_phone;
                         $this->_user->phone_verified = 0;
                         $this->_user->generatePhoneToken();
                     }
                 }
                 if (is_string($err)) {
                     Yii::$app->session->addFlash('phone', $err);
                 }
             }
             $_address = isset($formData['address']) ? strval($formData['address']) : null;
             if ($_address && 0 < strlen($_address)) {
                 $addr = Address::findOne(['address' => $_address]);
                 if (!$addr) {
                     $addr = new Address();
                     $addr->address = $_address;
                     $addr->save();
                 }
                 if (User::$_TYPE_CUSTOMER === $this->_user->user_type) {
                     $rua = RelUserAddress::findOne(['user_id' => $this->_user->id, 'address_id' => $addr->id]);
                     if (!$rua) {
                         $rua = new RelUserAddress();
                         $rua->user_id = $this->_user->id;
                         $rua->address_id = $addr->id;
                         $rua->save();
                     }
                 } else {
                     $rua = RelUserAddress::findOne(['user_id' => $this->_user->id]);
                     if (!$rua) {
                         $rua = new RelUserAddress();
                         $rua->user_id = $this->_user->id;
                     }
                     $rua->address_id = $addr->id;
                     $rua->save();
                 }
             }
             $_fName = isset($formData['firstName']) ? strval($formData['firstName']) : null;
             if (strlen($_fName) > 0 && $this->_user->first_name !== $_fName) {
                 $this->_user->first_name = $_fName;
             }
             $_lName = isset($formData['lastName']) ? strval($formData['lastName']) : null;
             if (strlen($_lName) > 0 && $this->_user->last_name !== $_lName) {
                 $this->_user->last_name = $_lName;
             }
             $_ccInfo = isset($formData['creditCardInfo']) ? strval($formData['creditCardInfo']) : null;
             if ($this->_user->ccard_info !== $_ccInfo) {
                 $this->_user->ccard_info = $_ccInfo;
             }
             if (User::$_TYPE_DRIVER === $this->_user->user_type) {
                 $this->_car = Car::findOne(['driver_id' => $this->_user->id]);
                 if (!$this->_car) {
                     $this->_car = new Car();
                     $this->_car->driver_id = $this->_user->id;
                     $this->_car->save();
                 }
                 $this->processFileField('car_photo', $this->_car);
                 $this->processFileField('license_photo', $this->_user);
                 $this->processFileField('insurance_photo', $this->_user);
                 $_priceMile = isset($formData['priceMile']) ? strval($formData['priceMile']) : null;
                 if (strlen($_priceMile) > 0 && $this->_car->price_mile !== $_priceMile) {
                     $this->_car->price_mile = $_priceMile;
                 }
                 $_carMake = isset($formData['carMake']) ? strval($formData['carMake']) : null;
                 if (strlen($_carMake) > 0 && $this->_car->make !== $_carMake) {
                     $this->_car->make = $_carMake;
                 }
                 $_carModel = isset($formData['carModel']) ? strval($formData['carModel']) : null;
                 if (strlen($_carModel) > 0 && $this->_car->model !== $_carModel) {
                     $this->_car->model = $_carModel;
                 }
                 $_carYear = isset($formData['carYear']) ? strval($formData['carYear']) : null;
                 if (strlen($_carYear) > 0 && $this->_car->year !== $_carYear) {
                     $this->_car->year = $_carYear;
                 }
                 $_licensePlateNumber = isset($formData['licensePlateNumber']) ? strval($formData['licensePlateNumber']) : null;
                 $_existing_car = Car::findOne(['license_plate' => $_licensePlateNumber]);
                 if ($_existing_car) {
                     Yii::$app->session->addFlash('license_plate', 'License plate number already registered');
                 } elseif (strlen($_licensePlateNumber) > 0 && $this->_car->license_plate !== $_licensePlateNumber) {
                     $this->_car->license_plate = $_licensePlateNumber;
                 }
                 $this->_car->save();
             }
         }
         $this->_user->save();
     }
     $this->loadData();
     return true;
 }
 /**
  * Get user model by its name or email.
  * @param string $nameOrEmail
  * @throws InvalidArgumentException when user not found.
  * @return User
  */
 protected function getUser($nameOrEmail)
 {
     $emailValidator = new EmailValidator();
     if ($emailValidator->validate($nameOrEmail)) {
         $user = User::findByEmail($nameOrEmail);
     } else {
         $user = User::findOne(['name' => $nameOrEmail]);
     }
     if (!$user) {
         throw new InvalidArgumentException("Couldn't find user by specified email or name.");
     }
     return $user;
 }
Beispiel #17
0
 /**
  * Validate 'value' attribute against of 'value_type'.
  */
 public function validateValue($attribute, $params = [])
 {
     if ($this->required) {
         $required = Yii::createObject(['class' => \yii\validators\RequiredValidator::className(), 'message' => Yii::t('app', '{label} is required.', ['label' => $this->title])]);
         if (!$required->validate($this->{$attribute})) {
             $this->addError($attribute, $required->message);
             return;
         }
     } else {
         $value = $this->{$attribute};
         if ($value === null || $value === '') {
             return;
         }
     }
     switch ($this->value_type) {
         case static::TYPE_INT:
             $args = ['class' => NumberValidator::className(), 'integerOnly' => true, 'message' => 'Not an integer'];
             break;
         case static::TYPE_NUM:
             $args = ['class' => NumberValidator::className(), 'message' => 'Not a number'];
             break;
         case static::TYPE_EMAIL:
             $args = ['class' => EmailValidator::className(), 'message' => 'Not a valid email'];
             break;
         case static::TYPE_URL:
             $args = ['class' => UrlValidator::className(), 'message' => 'Not a valid url'];
             break;
         case static::TYPE_SWITCH:
             $args = ['class' => BooleanValidator::className(), 'message' => 'Must be boolean value'];
             break;
         case static::TYPE_TEXT:
         case static::TYPE_EDITOR:
         case static::TYPE_PASSWORD:
             $args = ['class' => StringValidator::className()];
             break;
         case static::TYPE_SELECT:
             $args = ['class' => RangeValidator::className(), 'range' => array_keys($this->options), 'message' => 'Invalid value'];
             break;
         default:
             throw new InvalidParamException('Unknown config type: ' . $this->value_type);
     }
     $validator = Yii::createObject($args);
     if (!$validator->validate($this->{$attribute})) {
         $this->addError($attribute, $validator->message);
     } else {
         $this->castType();
     }
 }
Beispiel #18
0
 public function checkout($orderData = [])
 {
     $validator = new EmailValidator();
     $orderData = array_map('trim', $orderData);
     $orderData['email_validation'] = $validator->validate($orderData['email']) ? 1 : 0;
     $user = null;
     $userId = Yii::$app->session->get('userId');
     $user = User::find();
     if (!$userId) {
         $user = $user->where('email = :email', ['email' => $orderData['email']])->one();
     } else {
         $user = $user->where('id = :id', ['id' => $userId])->one();
     }
     if (!$user) {
         $user = new User();
         $user->email = $orderData['email'];
         $user->phone = $orderData['phone'];
         $user->name = $orderData['name'];
         $user->guid = Utils::createGuid();
         if (!$user->save()) {
             Yii::error(['info' => 'Проблема создания пользователя в БД', 'message' => $user->getErrors()], __LINE__);
         } else {
             $userId = $user->id;
             Yii::$app->session->set('userId', $userId);
         }
     } else {
         $userId = $user->id;
         Yii::$app->session->set('userId', $userId);
     }
     $this->device->linkUser($userId);
     $staticFolder = Yii::getAlias('@staticFolder');
     $result = ['result' => false];
     $cartGuid = Yii::$app->session->get('cartGuid');
     $order = CartOrder::find()->where('guid = :guid ', ['guid' => $cartGuid])->one();
     if ($order && $orderData) {
         $loader = new \Twig_Loader_Filesystem(Yii::getAlias('@common/mail'));
         $twig = new \Twig_Environment($loader, array('cache' => Yii::getAlias('@runtime/Twig/cache'), 'auto_reload' => TRUE));
         $items = $this->get($order->guid);
         $imgPrefix = Yii::getAlias('@imagePrefixOrder', false) ? Yii::getAlias('@imagePrefixOrder', false) : '200__';
         foreach ($items['items'] as &$item) {
             $item['productImage'] = str_replace('68_', $imgPrefix, $item['productImage']);
         }
         $relative_order_path = Yii::getAlias('@ordersFolder') . '/' . $cartGuid[0] . $cartGuid[1] . '/' . $cartGuid[2] . $cartGuid[3] . '/' . $cartGuid[4] . $cartGuid[5];
         $absolute_order_path = $staticFolder . '/' . $relative_order_path;
         $relative_order_file = $relative_order_path . '/' . $cartGuid . '.html';
         $absolute_order_file = $absolute_order_path . '/' . $cartGuid . '.html';
         if (!file_exists($absolute_order_path)) {
             mkdir($absolute_order_path, 0755, true);
         }
         if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
             $ip = $_SERVER['HTTP_CLIENT_IP'];
         } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
             $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
         } else {
             $ip = $_SERVER['REMOTE_ADDR'];
         }
         $order->status = 1;
         $order->phone = $orderData['phone'];
         $order->email = $orderData['email'];
         $order->name = $orderData['name'];
         $order->delivery = $orderData['delivery'];
         $order->recipient_name = $orderData['recipient_name'];
         $order->recipient_passport = $orderData['recipient_passport'];
         $order->recipient_address = $orderData['recipient_address'];
         $order->comment = $orderData['comment'];
         $order->date = date('Y-m-d H:i:s', time());
         //            $order->date = new Expression('NOW()');
         //            $order->ip = new Expression('INET_ATON(:ip)',['ip' => $ip]);
         $order->ip = ip2long($ip);
         $order->order_file = $relative_order_file;
         $order->user_id = $userId;
         $order->email_validation = $orderData['email_validation'];
         if (!$order->save()) {
             Yii::error(['info' => 'Проблема сохранения заказа в БД', 'orderId' => $order->id, 'message' => $order->getErrors()], __LINE__);
             $result['result'] = 'error';
             return $result;
         }
         $htmlMessage = $twig->render('order/confirm.twig', array('order' => $order, 'orderDate' => date('d-m-Y', strtotime($order->date)), 'siteName' => Yii::getAlias('@protocol') . '://' . Yii::getAlias('@domain'), 'user' => $user, 'items' => $items['items']));
         $htmlMessageAdmin = $twig->render('order/confirmAdmin.twig', array('order' => $order, 'orderDate' => date('d-m-Y', strtotime($order->date)), 'siteName' => Yii::getAlias('@protocol') . '://' . Yii::getAlias('@domain'), 'user' => $user, 'items' => $items['items']));
         $content = $htmlMessage;
         $fp = fopen($absolute_order_file, 'wb');
         fwrite($fp, $content);
         fclose($fp);
         $send = $this->sendMail(['email' => $order->email, 'guid' => $user->guid, 'name' => $user->name], Yii::$app->params['replyToMail']['mail'], 'Ваш заказ принят', $htmlMessage, $order->guid);
         if (!$send['result']) {
             Yii::error(['info' => 'Проблема с отправкой уведомления о заказе клиенту', 'orderId' => $order->id, 'message' => $send['message']], __LINE__);
         }
         $send = $this->sendMail(['email' => Yii::$app->params['replyToMail']['mail'], 'guid' => null, 'name' => null], $order->email, 'Поступил заказ', $htmlMessageAdmin);
         if (!$send['result']) {
             Yii::error(['info' => 'Проблема с отправкой уведомления о заказе админу', 'orderId' => $order->id, 'message' => $send['message']], __LINE__);
         }
         // Заказ оформлен, очищаем сохранённую GUID заказа
         Yii::$app->session->remove('cartGuid');
         $result['email'] = $orderData['email'];
         $result['result'] = 'ok';
         $result['orderLink'] = '/' . $relative_order_file;
     }
     return $result;
 }
 public function fieldTypeValidation()
 {
     // Messages
     $invalidMessage = "the input value has a not valid value.";
     // Validation by Input Type
     foreach ($this->fields as $field) {
         foreach ($field as $key => $value) {
             // Text
             if ($key === "type" && $value === "text") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Tel
             if ($key === "type" && $value === "tel") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     } else {
                         // By default, the number must be a international phone number
                         $phoneValidator = new PhoneValidator();
                         if (!$phoneValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error . ' ' . Yii::t("app", "It must has a internationally-standardized format\n                                (e.g. '+1 650-555-5555')"));
                         }
                     }
                 }
             }
             // Url
             if ($key === "type" && $value === "url") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config validator
                     $config = [];
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $config['pattern'] = $field["pattern"];
                     }
                     $urlValidator = new UrlValidator($config);
                     if (!$urlValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // Color
             if ($key === "type" && $value === "color") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // hex color invalid
                     if (!preg_match('/^#[a-f0-9]{6}$/i', $this->data[$field["name"]])) {
                         $this->addError($field["name"], $field["label"], '', $invalidMessage . ' ' . Yii::t("app", "It must be a hexadecimal color string (e.g. '#FFFFFF')."));
                     }
                 }
             }
             // Password
             if ($key === "type" && $value === "password") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     $newData = trim($this->data[$field["name"]]);
                     // Remove spaces
                     $stringValidator = new StringValidator(['min' => 6]);
                     if (!$stringValidator->validate($newData, $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Email
             if ($key === "type" && $value === "email") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config email validator
                     $config = [];
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $config['pattern'] = $field["pattern"];
                     }
                     // Whether to check if email's domain exists and has either an A or MX record.
                     // Be aware that this check can fail due temporary DNS problems
                     // even if the email address is valid and an email would be deliverable
                     if (isset($field["data-check-dns"])) {
                         $config['checkDNS'] = true;
                     }
                     // Validate multiple emails separated by commas
                     if (isset($field["multiple"])) {
                         // Removes spaces
                         $emails = str_replace(" ", "", $this->data[$field["name"]]);
                         // Array of emails
                         $emails = explode(",", $emails);
                         if (count($emails) > 1) {
                             $config['message'] = Yii::t('app', '{attribute} has a invalid email format: Please use a comma to separate multiple email addresses.');
                         }
                         // Validate only one email address
                         $emailValidator = new EmailValidator($config);
                         foreach ($emails as $email) {
                             if (!$emailValidator->validate($email, $error)) {
                                 $this->addError($field["name"], $field["label"], '', $error);
                             }
                         }
                     } else {
                         // Validate only one email address
                         $emailValidator = new EmailValidator($config);
                         if (!$emailValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Radio
             if ($key === "type" && $value === "radio") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no values or if the received data does not match with the form data
                     if (empty($this->radioValues) || !in_array($this->data[$field["name"]], $this->radioValues)) {
                         $this->addError($field["name"], $field["groupLabel"], '', $invalidMessage);
                     }
                 }
             }
             // Checkbox
             if ($key === "type" && $value === "checkbox") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no values or if the received data does not match with the form data
                     foreach ($this->data[$field["name"]] as $labelChecked) {
                         if (empty($this->checkboxValues) || !in_array($labelChecked, $this->checkboxValues)) {
                             $this->addError($field["name"], $field["groupLabel"], '', $invalidMessage);
                         }
                     }
                 }
             }
             // Select List
             if ($key === "tagName" && $value === "select") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no labels or if the received data does not match with the form data
                     foreach ($this->data[$field["name"]] as $optionSelected) {
                         if (empty($this->optionValues) || !in_array($optionSelected, $this->optionValues)) {
                             $this->addError($field["name"], $field["label"], '', $invalidMessage);
                         }
                     }
                 }
             }
             // Number & Range
             if ($key === "type" && $value === "number" || $key === "type" && $value === "range") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config number validator
                     $config = [];
                     // Min Number Validation (Minimum value required)
                     if (isset($field["min"])) {
                         $config['min'] = $field["min"];
                     }
                     // Max Number Validation (Maximum value required)
                     if (isset($field["max"])) {
                         $config['max'] = $field["max"];
                     }
                     // Only Integer Validation (Whether the attribute value can only be an integer)
                     if (isset($field["data-integer-only"])) {
                         $config['integerOnly'] = true;
                     }
                     // Pattern to Validate only Integer Numbers (The regular expression for matching integers)
                     if (isset($field["data-integer-pattern"])) {
                         $config['integerPattern'] = $field["data-integer-pattern"];
                     }
                     // Pattern to Validate the Number (The regular expression for matching numbers)
                     if (isset($field["data-number-pattern"])) {
                         $config['numberPattern'] = $field["data-number-pattern"];
                     }
                     $numberValidator = new NumberValidator($config);
                     if (!$numberValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // Date & DateTime & Time & Month & Week
             if ($key === "type" && $value === "date" || $key === "type" && $value === "datetime-local" || $key === "type" && $value === "time" || $key === "type" && $value === "month" || $key === "type" && $value === "week") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // DateValidator Configuration array
                     $config = [];
                     // Date Format by default
                     $format = "Y-m-d";
                     // Change Format
                     if ($value === "datetime-local") {
                         // DateTime Format
                         $format = "Y-m-d\\TH:i:s";
                     } elseif ($value === "time") {
                         // Time Format
                         $format = "i:s";
                     } elseif ($value === "month") {
                         // Month Format
                         $format = "Y-m";
                     } elseif ($value === "week") {
                         // First, validate by regular expression
                         $regexValidator = new RegularExpressionValidator(['pattern' => "/\\d{4}-W\\d{2}/"]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                         // Next, convert to date, to dateValidator (min / max)
                         if (isset($field["min"])) {
                             $config['tooSmall'] = Yii::t("app", "{attribute} must be no less than {weekMin}.", ['weekMin' => $field["min"]]);
                             $field["min"] = date("Y-m-d", strtotime($field["min"]));
                         }
                         if (isset($field["max"])) {
                             $config['tooBig'] = Yii::t("app", "{attribute} must be no greater than {weekMax}.", ['weekMax' => $field["max"]]);
                             $field["max"] = date("Y-m-d", strtotime($field["max"]));
                         }
                         $this->data[$field["name"]] = date("Y-m-d", strtotime($this->data[$field["name"]]));
                     }
                     // Add PHP format
                     $config['format'] = "php:" . $format;
                     // Add Min Date Validation (The value must be later than this option)
                     if (isset($field["min"])) {
                         $config['min'] = $field["min"];
                     }
                     // Add Max Date Validation (The value must be earlier than this option)
                     if (isset($field["max"])) {
                         $config['max'] = $field["max"];
                     }
                     $dateValidator = new DateValidator($config);
                     if (!$dateValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // File
             if ($key === "type" && $value === "file") {
                 // Only when the $_FILES name value is not empty
                 if (isset($field["name"]) && isset($_FILES[$field["name"]]['name']) && !empty($_FILES[$field["name"]]['name'])) {
                     // Config FileValidator
                     $config = [];
                     // File type validation
                     // Note that you should enable fileinfo PHP extension.
                     if (isset($field["accept"]) && extension_loaded('fileinfo')) {
                         // Removes dots
                         $extensions = str_replace(".", "", $field["accept"]);
                         // Removes spaces
                         $extensions = str_replace(" ", "", $extensions);
                         $config['extensions'] = explode(",", $extensions);
                     }
                     // File Min Size validation
                     if (isset($field["data-min-size"])) {
                         // Removes dots
                         $config['minSize'] = (int) $field["data-min-size"];
                     }
                     // File Min Size validation
                     if (isset($field["data-max-size"])) {
                         // Removes dots
                         $config['maxSize'] = (int) $field["data-max-size"];
                     }
                     $file = UploadedFile::getInstanceByName($field["name"]);
                     $fileValidator = new FileValidator($config);
                     if (!$fileValidator->validate($file, $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
         }
     }
 }
Beispiel #20
0
 public function actionAksi6($q, EmailValidator $validator)
 {
     return [$q, $validator->validate($q), $validator->validate('*****@*****.**')];
 }
 public function testValidateAttribute()
 {
     $val = new EmailValidator();
     $model = new FakedValidationModel();
     $model->attr_email = '*****@*****.**';
     $val->validateAttribute($model, 'attr_email');
     $this->assertFalse($model->hasErrors('attr_email'));
 }
Beispiel #22
0
 public function rules()
 {
     return ArrayHelper::merge(parent::rules(), [[['adminEmail', 'noImageUrl', 'notifyAdminEmails', 'notifyAdminEmailsHidden', 'appName', 'template', 'languageCode'], 'string'], [['adminEmail'], 'email'], [['adminEmail'], 'email'], [['emailTemplate'], 'string'], [['passwordResetTokenExpire'], 'integer', 'min' => 300], [['hitAgentsInterval'], 'integer', 'min' => 60], [['enabledHitAgents'], 'string'], [['registerRoles'], 'safe'], [['enabledHttpAuthAdmin'], 'string'], [['enabledHttpAuth'], 'string'], [['httpAuthLogin'], 'string'], [['httpAuthPassword'], 'string'], [['debugEnabled'], 'string'], [['debugAllowedIPs'], 'string'], [['giiEnabled'], 'string'], [['giiAllowedIPs'], 'string'], [['licenseKey'], 'string'], [['notifyAdminEmails'], function ($attribute) {
         if ($emails = $this->notifyAdminEmailsToArray()) {
             foreach ($emails as $email) {
                 $validator = new EmailValidator();
                 if (!$validator->validate($email, $error)) {
                     $this->addError($attribute, $email . ' — некорректный email адрес');
                     return false;
                 }
             }
         }
     }], [['notifyAdminEmailsHidden'], function ($attribute) {
         if ($emails = $this->notifyAdminEmailsHiddenToArray()) {
             foreach ($emails as $email) {
                 $validator = new EmailValidator();
                 if (!$validator->validate($email, $error)) {
                     $this->addError($attribute, $email . ' — некорректный email адрес');
                     return false;
                 }
             }
         }
     }]]);
 }
 public function actionRecoveryPassword()
 {
     $model = new RecoveryPassword();
     $post = Yii::$app->request->post();
     $validator = new EmailValidator();
     $error = array();
     $msg = array();
     if (isset($post["RecoveryPassword"])) {
         $post = $post["RecoveryPassword"];
         foreach ($post as $key => $value) {
             $model->{$key} = $value;
         }
         $user = Parents::findOne(['email' => $post["email"]]);
         if ($post["email"] == "") {
             $error["email"] = 1;
         }
         if (!$validator->validate($post["email"])) {
             $error["format"] = 1;
         }
         if (count($user) == 0) {
             $error["nouser"] = 1;
         }
         if (count($error) == 0) {
             $mHash = md5($user["hash"]);
             $user["hash"] = $mHash;
             $user->save();
             $this->SendRecoveryEmail($post["email"], $mHash);
             echo "Ссылка успешно отправлена";
         }
     }
     return $this->render('recovery_password', ['model' => $model]);
 }
Beispiel #24
0
 /**
  * @param $email
  * @return int
  */
 private function validateEmail($email)
 {
     $validator = new EmailValidator();
     if (!$validator->validate($email)) {
         if (!$this->interactive) {
             throw new InvalidParamException($validator->message);
         }
         $message = empty($email) ? "Email is empty\n" : "Email not valid\n";
         $this->stdout($message);
         $email = $this->prompt('Set email:', ['validator' => function ($data) use($validator) {
             return $validator->validate($data);
         }]);
     }
     return $email;
 }
Beispiel #25
0
 public function rules()
 {
     return [['familiya', ImyaChelovekaValidator::className()], ['familiya', 'required'], ['imya', ImyaChelovekaValidator::className()], ['imya', 'required'], ['otchestvo', ImyaChelovekaValidator::className()], ['otchestvo', 'default'], ['data_rozhdeniya', DateValidator::className(), 'sqlAttribute' => 'data_rozhdeniya'], ['data_rozhdeniya', 'required'], ['telefon', TelefonValidator::className(), 'sqlAttribute' => 'telefon'], ['telefon', 'required'], ['email', EmailValidator::className()], ['email', 'required'], ['pasport_no', PasportNomerValidator::className(), 'sqlAttribute' => 'pasport_no'], ['pasport_no', 'required'], ['pasport_kem_vydan_kod', PasportKodPodrazdeleniyaValidator::className(), 'sqlAttribute' => 'pasport_kem_vydan_kod'], ['pasport_kem_vydan_kod', 'required'], ['pasport_kem_vydan', NazvanieValidator::className()], ['pasport_kem_vydan', 'required'], ['pasport_kogda_vydan', DateValidator::className(), 'sqlAttribute' => 'pasport_kogda_vydan'], ['pasport_kogda_vydan', 'required'], ['inn', InnValidator::className(), 'sqlAttribute' => 'inn'], ['inn', 'required'], ['snils', SnilsValidator::className(), 'sqlAttribute' => 'snils'], ['snils', 'required'], ['propiska', 'required'], ['propiska', 'string']];
 }