Exemplo n.º 1
0
 public function testValidateValueMx()
 {
     $validator = new EmailValidator();
     $validator->checkDNS = true;
     $this->assertTrue($validator->validate('*****@*****.**'));
     $validator->checkDNS = false;
     $this->assertTrue($validator->validate('*****@*****.**'));
     $validator->checkDNS = true;
     $this->assertFalse($validator->validate('*****@*****.**'));
 }
Exemplo n.º 2
0
 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
                 }
             }
         }
     }
 }
Exemplo n.º 3
0
 public function testValidateValueMx()
 {
     $validator = new EmailValidator();
     $validator->checkDNS = true;
     $this->assertTrue($validator->validate('*****@*****.**'));
     $validator->checkDNS = false;
     $this->assertTrue($validator->validate('*****@*****.**'));
     $validator->checkDNS = true;
     $this->assertFalse($validator->validate('*****@*****.**'));
     $validator->checkDNS = true;
     $validator->allowName = true;
     $emails = ['*****@*****.**', 'Ivan Petrov <*****@*****.**>'];
     foreach ($emails as $email) {
         $this->assertTrue($validator->validate($email), "Email: '{$email}' failed to validate(checkDNS=true, allowName=true)");
     }
 }
Exemplo n.º 4
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;
 }
Exemplo n.º 5
0
 private function checkIsLoginMail()
 {
     $validator = new EmailValidator();
     if ($validator->validate($this->email) == true) {
         return true;
     } else {
         return false;
     }
 }
Exemplo n.º 6
0
    private function validateAsEmail($model,$attribute){

        $validator = new EmailValidator();

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

    }
Exemplo n.º 7
0
 /**
  * @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;
 }
Exemplo n.º 8
0
 /**
  * @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;
                 }
             }
         }
     }]]);
 }
Exemplo n.º 10
0
 /**
  * @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;
     }
 }
Exemplo n.º 12
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 "Неправильный электронный адрес";
         }
     }
 }
Exemplo n.º 13
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));
 }
Exemplo n.º 14
0
 /**
  * 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);
         }
     }
 }
Exemplo n.º 15
0
 /**
  * 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);
 }
Exemplo n.º 16
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;
 }
Exemplo n.º 17
0
 /**
  * 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;
 }
Exemplo n.º 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;
 }
Exemplo n.º 19
0
 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);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 20
0
 public function actionAksi6($q, EmailValidator $validator)
 {
     return [$q, $validator->validate($q), $validator->validate('*****@*****.**')];
 }
Exemplo n.º 21
0
 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]);
 }
Exemplo n.º 22
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;
 }
Exemplo n.º 23
0
Arquivo: Cms.php Projeto: Liv1020/cms
 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;
                 }
             }
         }
     }]]);
 }