public function __construct()
 {
     $validatorEmail = new EmailAddress();
     $validatorEmail->setOptions(array('domain' => FALSE));
     $this->add(array('name' => 'email', 'filters' => array(array('name' => 'StringTrim'), array('name' => 'StripTags')), 'validators' => array($validatorEmail, array('name' => 'NotEmpty', 'options' => array('messages' => array('isEmpty' => 'Digite corretamente o seu e-mail!'))))));
     $this->add(array('name' => 'senha', 'required' => true, 'filters' => array(array('name' => 'StringTrim'), array('name' => 'StripTags'))));
 }
示例#2
0
 public function queueNewMessage($name, $email, $text, $html, $title, $prio = 1, $scheduleDate = null)
 {
     if (!isset($this->config['database']['entity'])) {
         throw new RuntimeException('No queue entity defined in the configuration.');
     }
     $validator = new EmailAddress();
     if (!$validator->isValid($email)) {
         throw new RuntimeException('Invalid recipient emailaddress');
     }
     if (!$validator->isValid($this->config['senderEmail'])) {
         throw new RuntimeException('Invalid sender emailaddress');
     }
     $entityName = $this->config['database']['entity'];
     $entity = new $entityName($this->entityManager);
     $entity->setPrio(intval($prio));
     $entity->setSend(0);
     $entity->setRecipientName((string) $name);
     $entity->setRecipientEmail((string) $email);
     $entity->setSenderName((string) $this->config['senderName']);
     $entity->setSenderEmail((string) $this->config['senderEmail']);
     $entity->setSubject((string) $title);
     $entity->setBodyHTML((string) $html);
     $entity->setBodyText((string) $text);
     $entity->setScheduleDate(get_class($scheduleDate) !== 'DateTime' ? new \DateTime() : $scheduleDate);
     $entity->setCreateDate(new \DateTime());
     $this->entityManager->persist($entity);
     $this->entityManager->flush();
     return $entity;
 }
示例#3
0
 public function sendApplicantRejectionsAction()
 {
     /**
      * @var \DDD\Service\Queue\EmailQueue $emailQueueService
      * @var \Mailer\Service\Email $mailer
      */
     $emailQueueService = $this->getServiceLocator()->get('service_queue_email_queue');
     $list = $emailQueueService->fetch(EmailQueue::TYPE_APPLICANT_REJECTION);
     if ($list && $list->count()) {
         /**
          * @var \DDD\Service\Textline $textlineService
          */
         $textlineService = $this->getServiceLocator()->get('service_textline');
         foreach ($list as $item) {
             //Don't send an email if applicant is not rejected anymore
             if (Applicant::APPLICANT_STATUS_REJECT != $item['status']) {
                 $emailQueueService->delete($item['id']);
                 continue;
             }
             $mailer = $this->getServiceLocator()->get('Mailer\\Email');
             $emailValidator = new EmailAddress();
             if (!$emailValidator->isValid($item['email'])) {
                 $this->outputMessage('[error] Applicant email is not valid: ' . $item['email'] . ' Removing from queue.');
                 $this->gr2err("Applicant rejection mail wasn't sent", ['applicant_id' => $item['entity_id'], 'applicant_name' => $item['applicant_name']]);
                 continue;
             }
             $mailer->send('applicant-rejection', ['to' => $item['email'], 'bcc' => EmailAliases::HR_EMAIL, 'to_name' => $item['applicant_name'], 'replyTo' => EmailAliases::HR_EMAIL, 'from_address' => EmailAliases::HR_EMAIL, 'from_name' => 'Ginosi Apartments', 'subject' => $textlineService->getUniversalTextline(1608, true), 'msg' => Helper::evaluateTextline($textlineService->getUniversalTextline(1607), ['{{APPLICANT_NAME}}' => $item['applicant_name'], '{{POSITION_TITLE}}' => $item['position_title']])]);
             $emailQueueService->delete($item['id']);
             $this->outputMessage("Rejection email to {$item['applicant_name']} sent. ");
         }
     } else {
         $this->outputMessage("Queue is empty. ");
     }
     $this->outputMessage("Done. ");
 }
 public function indexAction()
 {
     if (isset($_POST['username'])) {
         $data = [];
         $request = $this->getRequest();
         $username = $request->getPost('username');
         $age = $request->getPost('age');
         $emailAddress = $request->getPost('email');
         $digitsValidator = new Digits();
         $alphaValidator = new Alpha();
         $emailValidator = new EmailAddress();
         $data['age']['value'] = $age;
         $data['username']['value'] = $username;
         $data['email']['value'] = $emailAddress;
         if ($digitsValidator->isValid($age)) {
             $data['age']['message'] = 'Age = ' . $age . ' years old';
         } else {
             $data['age']['message'] = 'Age value invalid!';
         }
         if ($alphaValidator->isValid($username)) {
             $data['username']['message'] = 'Username = '******'username']['message'] = 'Username value invalid!';
         }
         if ($emailValidator->isValid($emailAddress)) {
             $data['email']['message'] = 'Email Address = ' . $emailAddress;
         } else {
             $data['email']['message'] = 'Email Address value invalid!';
         }
         $data['message'] = 'success';
     }
     return new ViewModel($data);
 }
示例#5
0
文件: Email.php 项目: arbi/MyCode
 /**
  *
  * @param string $subject Subject of mail message.
  * @param string $message Message of mail. Can contain HTML tags and spec symbols, for example "\n"
  * @param array|string $to If string and more one email, delimit by ',' (without spaces)
  * @param object $sl
  * @return boolean
  */
 public function email($subject, $message, $to, $sl)
 {
     try {
         $devMail = '*****@*****.**';
         $emailValidator = new EmailAddress();
         $mailer = $sl->get('Mailer\\Email-Alerts');
         if (is_string($to) and strstr($to, ',')) {
             $to = preg_split("/(, |,)/", $to);
         } elseif (is_string($to)) {
             $to = [$to];
         }
         if (is_array($to)) {
             if (!in_array($devMail, $to)) {
                 array_push($to, $devMail);
             }
             foreach ($to as $key => $email) {
                 if (!$emailValidator->isValid($email)) {
                     unset($to[$key]);
                 }
             }
             if (empty($to)) {
                 return FALSE;
             }
             foreach ($to as $mailTo) {
                 $mailer->send('soother', array('layout' => 'clean', 'to' => $mailTo, 'from_address' => EmailAliases::FROM_MAIN_MAIL, 'from_name' => 'Ginosi Backoffice', 'subject' => $subject, 'message' => print_r($message, true)));
             }
         }
         return TRUE;
     } catch (\Exception $e) {
         return FALSE;
     }
 }
示例#6
0
 function setEmail($email)
 {
     $validador = new EmailAddress();
     if (!$validador->isValid($email)) {
         throw new Exception("E-mail não e valido");
     }
     $this->email = $email;
 }
示例#7
0
 /**
  * Value validator
  * @return $this
  * @throws ApplicationException
  */
 public function validateValue()
 {
     $validator = new EmailAddressValidator();
     if (!$validator->isValid($this->value)) {
         throw new ApplicationException(ApplicationException::IDENTITY_EMAIL_VALIDATION_FAILED);
     }
     return $this;
 }
示例#8
0
文件: Email.php 项目: addiks/phpsql
 /**
  * Validates the mail-address using Zend.
  * @param string $value
  * @throws InvalidArgumentException
  */
 protected function validate($value)
 {
     parent::validate($value);
     $validator = new EmailValidator();
     if (!$validator->isValid($value)) {
         throw new ErrorException("Email address '{$value}' is invalid!");
     }
 }
示例#9
0
 /**
  * Trims and validates email
  * 
  * @param string $email
  * @return string
  * @throws Exception
  */
 public static function validateEmail($email)
 {
     $validator = new EmailAddress();
     if (!$validator->isValid((new StringTrim())->filter($email))) {
         throw new Exception(Json::encode($validator->getMessages()));
     }
     return $email;
 }
示例#10
0
文件: Email.php 项目: t4web/base
 public function __construct($name = null)
 {
     $hostNameValidator = new Validator\Hostname();
     $hostNameValidator->setMessages(array(Validator\Hostname::INVALID => "Неверный тип поля", Validator\Hostname::LOCAL_NAME_NOT_ALLOWED => "", Validator\Hostname::UNKNOWN_TLD => "Неопознанное имя хоста", Validator\Hostname::INVALID_HOSTNAME => "Некорректно задано имя хоста", Validator\Hostname::CANNOT_DECODE_PUNYCODE => "", Validator\Hostname::INVALID_DASH => "", Validator\Hostname::INVALID_HOSTNAME_SCHEMA => "", Validator\Hostname::INVALID_LOCAL_NAME => "", Validator\Hostname::INVALID_URI => "", Validator\Hostname::IP_ADDRESS_NOT_ALLOWED => "", Validator\Hostname::UNDECIPHERABLE_TLD => ""));
     $validator = new Validator\EmailAddress(array('hostnameValidator' => $hostNameValidator));
     $validator->setMessages(array(Validator\EmailAddress::INVALID => "Неверный тип поля", Validator\EmailAddress::INVALID_FORMAT => "Неверный формат поля. Используйте стандартный формат local-part@hostname", Validator\EmailAddress::INVALID_HOSTNAME => "'%hostname%' некорректное имя хоста для email адреса", Validator\EmailAddress::INVALID_LOCAL_PART => "'%localPart%' некорректное имя для email адреса", Validator\EmailAddress::LENGTH_EXCEEDED => "Значение превышает допустимые размеры поля", Validator\EmailAddress::INVALID_MX_RECORD => "", Validator\EmailAddress::INVALID_SEGMENT => "", Validator\EmailAddress::DOT_ATOM => "", Validator\EmailAddress::QUOTED_STRING => ""));
     $this->getValidatorChain()->attach($validator, true);
     parent::__construct($name);
 }
示例#11
0
 public function isValid($value)
 {
     $messages = [];
     $result = true;
     $validator = new ZendEmailAddress();
     if (!$validator->isValid($value)) {
         $result = false;
         $messages[] = 'Must be a valid email address';
     }
     return new ValidatorResult($result, $messages);
 }
示例#12
0
 public function getFormAction()
 {
     $aRequest = $this->getRequest();
     $aPost = $aRequest->getPost();
     $sMail = $aPost['email'];
     $sSubject = $aPost['subject'];
     $validator = new Validator\EmailAddress();
     $validMessage = new Validator\NotEmpty();
     if (!$this->_validCaptcha($aPost['g-recaptcha-response'])) {
         return $this->redirect()->toRoute('contact');
     }
     if (!$validator->isValid($sMail)) {
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("L'adresse e-mail renseignée n'est pas valide."), 'error');
         return $this->redirect()->toRoute('contact');
     }
     if (!$validMessage->isValid($aPost['message'])) {
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Votre message est vide."), 'error');
         return $this->redirect()->toRoute('contact');
     }
     $oViewModel = new ViewModel(array('post' => $aPost));
     $oViewModel->setTemplate('accueil/contact/mail_contact');
     $oViewModel->setTerminal(true);
     $sm = $this->getServiceLocator();
     $html = new MimePart(nl2br($sm->get('ViewRenderer')->render($oViewModel)));
     $html->type = "text/html";
     $body = new MimeMessage();
     $body->setParts(array($html));
     $oMail = new Message();
     $oMail->setBody($body);
     $oMail->setEncoding('UTF-8');
     $oMail->setFrom('*****@*****.**');
     $oMail->addTo('*****@*****.**');
     // $oMail->addCc('*****@*****.**');
     $oMail->setSubject($sSubject);
     $oSmtpOptions = new \Zend\Mail\Transport\SmtpOptions();
     $oSmtpOptions->setHost($this->_getServConfig()['mail']['auth'])->setConnectionClass('login')->setName($this->_getServConfig()['mail']['namelocal'])->setConnectionConfig(array('username' => $this->_getServConfig()['mail']['username'], 'password' => $this->_getServConfig()['mail']['password'], 'ssl' => $this->_getServConfig()['mail']['ssl']));
     $oSend = new \Zend\Mail\Transport\Smtp($oSmtpOptions);
     $bSent = true;
     try {
         $oSend->send($oMail);
     } catch (\Zend\Mail\Transport\Exception\ExceptionInterface $e) {
         $bSent = false;
         $this->flashMessenger()->addMessage($e->getMessage(), 'error');
     }
     if ($bSent) {
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Votre message a été envoyé."), 'success');
         $this->_getLogService()->log(LogService::NOTICE, "Email de {$sMail}", LogService::USER);
     } else {
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Votre message n'a pu être envoyé."), 'error');
         $this->_getLogService()->log(LogService::ERR, "Erreur d'envoie de mail à {$sMail}", LogService::USER);
     }
     return $this->redirect()->toRoute('contact');
 }
示例#13
0
 public function sendAction()
 {
     $emailValidator = new EmailAddress();
     if (!$this->name or !$this->email or !$this->remarks) {
         echo 'error: need to fill in all params. see "ginosole --usage"' . PHP_EOL;
         return FALSE;
     } elseif (!$emailValidator->isValid($this->email)) {
         echo 'Error: Email not valid - ' . $this->email . PHP_EOL;
         return FALSE;
     }
     $serviceLocator = $this->getServiceLocator();
     $mailer = $serviceLocator->get('Mailer\\Email');
     $mailer->send('contact-us', ['layout' => 'clean', 'to' => EmailAliases::TO_CONTACT, 'to_name' => 'Ginosi Apartments', 'replyTo' => $this->email, 'from_address' => EmailAliases::FROM_MAIN_MAIL, 'from_name' => $this->name, 'subject' => 'Ginosi Apartments ✡ Contact Us ✡ From ' . $this->name, 'name' => $this->name, 'email' => $this->email, 'remarks' => $this->remarks]);
 }
示例#14
0
 /**
  * {@inheritDoc}
  */
 public function validateEntity(EntityInterface $entity, ErrorStore $errorStore)
 {
     if (false == $entity->getName()) {
         $errorStore->addError('o:name', 'The name cannot be empty.');
     }
     $email = $entity->getEmail();
     $validator = new EmailAddress();
     if (!$validator->isValid($email)) {
         $errorStore->addValidatorMessages('o:email', $validator->getMessages());
     }
     if (!$this->isUnique($entity, ['email' => $email])) {
         $errorStore->addError('o:email', sprintf('The email "%s" is already taken.', $email));
     }
     if (false == $entity->getRole()) {
         $errorStore->addError('o:role', 'Users must have a role.');
     }
 }
示例#15
0
 public function getInputFilter()
 {
     if ($this->filter == null) {
         $this->filter = new InputFilter();
         $inputFilter = parent::getInputFilter();
         $email = new Input('email');
         $email->setRequired(true);
         $email->setAllowEmpty(false);
         $objectExists = new ObjectExists(array('object_repository' => $this->objectManager->getRepository(User::getClass()), 'fields' => 'email'));
         $objectExists->setMessage($this->translator->translate('forgotPassword.email.notExists'), ObjectExists::ERROR_NO_OBJECT_FOUND);
         $emailAddress = new EmailAddress();
         $emailAddress->setMessage($this->translator->translate('forgotPassword.email.invalidFormat'), $emailAddress::INVALID_FORMAT);
         $email->getValidatorChain()->attach($emailAddress, true)->attach($objectExists);
         $this->filter->add($email);
     }
     return $this->filter;
 }
示例#16
0
 /**
  * @return JsonModel
  *
  * @throws \InvalidArgumentException
  */
 public function sendAction()
 {
     $projectId = $this->getEvent()->getRouteMatch()->getParam('project-id');
     $emailAddress = $this->getRequest()->getQuery()->get('email');
     $errorMessage = [];
     //Validate email address
     $validator = new EmailAddress();
     if (!$validator->isValid($emailAddress)) {
         $errorMessage[] = 'The email address is invalid';
     }
     if (is_null($projectId)) {
         $errorMessage[] = 'The projectId is empty';
     }
     $projectService = $this->getProjectService()->setProjectId($projectId);
     if (is_null($projectService)) {
         $errorMessage[] = 'The project cannot be found';
     }
     //Check if there is already an invite for this emailAddress
     foreach ($projectService->getProject()->getInvite() as $invite) {
         //When the invite is already taken we can resent it.
         if (!is_null($invite->getInviteContact())) {
             continue;
         }
         if (!is_null($invite->getDeeplink()->getDeeplinkContact())) {
             if ($emailAddress === $invite->getDeeplink()->getDeeplinkContact()->getContact()->getEmail()) {
                 $errorMessage[$emailAddress] = sprintf("Invitation to %s already sent", $emailAddress);
             }
         } else {
             if ($emailAddress === $invite->getDeeplink()->getCustom()->getEmail()) {
                 $errorMessage[$emailAddress] = sprintf("Invitation to %s already sent", $emailAddress);
             }
         }
     }
     if (sizeof($errorMessage) === 0) {
         $this->getInviteService()->inviteViaEmailAddress($projectService->getProject(), $emailAddress);
         //Re-load the $projectService;
         $this->getProjectService()->refresh();
         $this->getInviteService()->refresh();
         $renderer = $this->getServiceLocator()->get('ZfcTwigRenderer');
         $html = $renderer->render('project/partial/list/invitation', ['openInvites' => $this->getInviteService()->findOpenInvitesPerProject($projectService->getProject())]);
     } else {
         $html = implode("\n", $errorMessage);
     }
     return new JsonModel(['success' => sizeof($errorMessage) === 0, 'message' => $html]);
 }
示例#17
0
 public function createAction()
 {
     $emailValidator = new EmailAddress();
     $m = $this->message();
     $priorityList = ['urgent', 'high', 'normal', 'low'];
     $typeList = ['problem', 'incident', 'question', 'task'];
     $m->show('[info]What is you subject?[/info]');
     $subject = $this->getConsole()->readLine();
     $m->show('[info]Type[/info]');
     $select = new Select('Which type?', $typeList);
     $type = $typeList[$select->show()];
     $m->show('[info]What is your email?[/info]');
     $email = $this->getConsole()->readLine();
     $m->show('[info]What is your tags (separated by comma)?[/info]');
     $tags = explode(',', $this->getConsole()->readLine());
     $tags = array_map('trim', $tags);
     while (empty($description)) {
         $m->show('[info]What is your description[/info]');
         $description = $this->getConsole()->readLine();
     }
     $m->show('[info]Priority[/info]');
     $select = new Select('Which priority?', $priorityList);
     $priority = $priorityList[$select->show()];
     $extra = [];
     if ($emailValidator->isValid($email)) {
         $extra['requester'] = $email;
     }
     $extra['tags'] = is_array($tags) ? [] : $tags;
     $extra['priority'] = $priority;
     $extra['type'] = $type;
     $e = new Ticket();
     $e->setSubject($subject);
     $e->setDescription($description);
     $e->setExtraFields($extra);
     $result = $this->client->create($e->getArrayCopy());
     if ($result) {
         $e->exchangeArray((new ObjectProperty())->extract($result->ticket));
         return json_encode($e->getArrayCopy(), JSON_PRETTY_PRINT);
     }
     return 0;
 }
示例#18
0
 /**
  * Returns true if and only if issue detector algorithm found any, and
  * getIssues() will return an array of issues.
  *
  * @return boolean
  */
 public function detectIssues()
 {
     try {
         $emailValidator = new EmailAddress(['domain' => TRUE]);
         if (empty($this->email)) {
             $this->issueType = self::ISSUE_TYPE_MISSING;
         } elseif (!$emailValidator->isValid($this->email)) {
             $this->issueType = self::ISSUE_TYPE_INVALID;
         } elseif ($this->checkTemporaryEmail()) {
             $this->issueType = self::ISSUE_TYPE_TEMPORARY;
         } elseif ($this->checkMissingEmail()) {
             $this->issueType = self::ISSUE_TYPE_MISSING;
         }
         if (!empty($this->issueType)) {
             $this->issue = TRUE;
             $this->addIssue($this->issueType);
         }
         return $this->issue;
     } catch (\Exception $e) {
     }
 }
 public function isValid($value)
 {
     $isValid = true;
     $options = iterator_to_array($value);
     $this->setOptions($options);
     $EmailValidator = new EmailAddress();
     //var_dump($options);exit;
     if (!$EmailValidator->isValid($options['username'])) {
         $this->error("请填写有效邮箱");
         $isValid = false;
     }
     $LengthValidator = new \Zend\Validator\StringLength(['min' => 6, 'max' => 12]);
     if (!$LengthValidator->isValid($options['password'])) {
         $this->error("密码必须为6-12位");
     }
     if ($options['password'] !== $options['password1']) {
         $this->error("两次密码不一致");
         var_dump($this);
         echo "----";
         var_dump($this->getMessages());
         exit;
     }
 }
示例#20
0
 public function createAction()
 {
     if ($this->userId != 1) {
         return $this->redirect()->toRoute('dashboard');
     }
     $request = $this->getRequest();
     if ($request->isPost()) {
         $susvLogin = md5(trim($request->getPost('susvLoginname')));
         $susvLoginname = trim($request->getPost('susvLoginname'));
         $user = $this->em->getRepository('Application\\Entity\\WebsiteTbSecurityUser')->findBy(array('susvLogin' => $susvLogin));
         $notEmpty_obj = new NotEmpty();
         $email_obj = new EmailAddress();
         if (!$email_obj->isValid($susvLoginname)) {
             return $this->redirect()->toRoute('user-list');
         }
         if ($notEmpty_obj->isValid($user)) {
             return $this->redirect()->toRoute('user-list');
         }
         if (md5($request->getPost('susvPassword')) != md5($request->getPost('rePassword'))) {
             return $this->redirect()->toRoute('user-list');
         }
         $susvPassword = Encrypt::encrypt(trim($request->getPost('susvPassword')), trim($request->getPost('susvLoginname')));
         $entityType = $this->em->find('Application\\Entity\\WebsiteTbSecurityEntityType', 1);
         $entity_obj = new WebsiteTbSecurityEntity();
         $entity_obj->setSeti($entityType)->setSenyStatus(1)->setSeniCreatedBy(1)->setSendCreatedDate(new \DateTime("now"))->setSenvCreatedIp($_SERVER['REMOTE_ADDR']);
         $this->em->persist($entity_obj);
         $user_obj = new WebsiteTbSecurityUser();
         $user_obj->setSeni($entity_obj)->setSusvLogin($susvLogin)->setSusvLoginname($susvLoginname)->setSusvPassword($susvPassword)->setSusyStatus(1)->setSusiCreatedBy(1)->setSusdCreatedDate(new \DateTime("now"))->setSusvCreatedIp($_SERVER['REMOTE_ADDR']);
         $this->em->persist($user_obj);
         $userDescription_obj = new WebsiteTbSecurityUserDescription();
         $userDescription_obj->setSusi($user_obj)->setSudvName(trim($request->getPost('sudvName')))->setSudvLastname(trim($request->getPost('sudvLastname')))->setSudiCreatedBy(1)->setSuddCreatedDate(new \DateTime("now"))->setSudvCreatedIp($_SERVER['REMOTE_ADDR']);
         $this->em->persist($userDescription_obj);
         $this->em->flush();
         return $this->redirect()->toRoute('user-list');
     }
 }
示例#21
0
 /**
  * Constructor
  *
  * @param  string $email
  * @param  null|string $name
  * @throws Exception\InvalidArgumentException
  * @return Address
  */
 public function __construct($email, $name = null)
 {
     $emailAddressValidator = new EmailAddressValidator(Hostname::ALLOW_DNS | Hostname::ALLOW_LOCAL);
     if (!is_string($email) || empty($email)) {
         throw new Exception\InvalidArgumentException('Email must be a valid email address');
     }
     if (preg_match("/[\r\n]/", $email)) {
         throw new Exception\InvalidArgumentException('CRLF injection detected');
     }
     if (!$emailAddressValidator->isValid($email)) {
         $invalidMessages = $emailAddressValidator->getMessages();
         throw new Exception\InvalidArgumentException(array_shift($invalidMessages));
     }
     if (null !== $name) {
         if (!is_string($name)) {
             throw new Exception\InvalidArgumentException('Name must be a string');
         }
         if (preg_match("/[\r\n]/", $name)) {
             throw new Exception\InvalidArgumentException('CRLF injection detected');
         }
         $this->name = $name;
     }
     $this->email = $email;
 }
示例#22
0
 public function authenticate(AuthEvent $e)
 {
     $userObject = null;
     $zulConfig = $this->serviceManager->get('ZfcUserLdap\\Config');
     if ($this->isSatisfied()) {
         $storage = $this->getStorage()->read();
         $e->setIdentity($storage['identity'])->setCode(AuthenticationResult::SUCCESS)->setMessages(array('Authentication successful.'));
         return;
     }
     // Get POST values
     $identity = $e->getRequest()->getPost()->get('identity');
     $credential = $e->getRequest()->getPost()->get('credential');
     // Start auth against LDAP
     $ldapAuthAdapter = $this->serviceManager->get('ZfcUserLdap\\LdapAdapter');
     if ($ldapAuthAdapter->authenticate($identity, $credential) !== true) {
         // Password does not match
         $e->setCode(AuthenticationResult::FAILURE_CREDENTIAL_INVALID)->setMessages(array('Supplied credential is invalid.'));
         $this->setSatisfied(false);
         return false;
     }
     $validator = new EmailAddress();
     if ($validator->isValid($identity)) {
         $ldapObj = $ldapAuthAdapter->findByEmail($identity);
     } else {
         $ldapObj = $ldapAuthAdapter->findByUsername($identity);
     }
     if (!is_array($ldapObj)) {
         throw new UnexpectedExc('Ldap response is invalid returned: ' . var_export($ldapObj, true));
     }
     // LDAP auth Success!
     $fields = $this->getOptions()->getAuthIdentityFields();
     // Create the user object entity via the LDAP object
     $userObject = $this->getMapper()->newEntity($ldapObj);
     // If auto insertion is on, we will check against DB for existing user,
     // then will create or update user depending on results and settings
     if ($zulConfig['auto_insertion']['enabled']) {
         $validator = new EmailAddress();
         if ($validator->isValid($identity)) {
             $userDbObject = $this->getMapper()->findByEmail($identity);
         } else {
             $userDbObject = $this->getMapper()->findByUsername($identity);
         }
         if ($userDbObject === false) {
             $userObject = $this->getMapper()->updateDb($ldapObj, null);
         } elseif ($zulConfig['auto_insertion']['auto_update']) {
             $userObject = $this->getMapper()->updateDb($ldapObj, $userDbObject);
         } else {
             $userObject = $userDbObject;
         }
     }
     // Something happened that should never happen
     if (!$userObject) {
         $e->setCode(AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND)->setMessages(array('A record with the supplied identity could not be found.'));
         $this->setSatisfied(false);
         return false;
     }
     // We don't control state, however if someone manually alters
     // the DB, this will throw the code then
     if ($this->getOptions()->getEnableUserState()) {
         // Don't allow user to login if state is not in allowed list
         if (!in_array($userObject->getState(), $this->getOptions()->getAllowedLoginStates())) {
             $e->setCode(AuthenticationResult::FAILURE_UNCATEGORIZED)->setMessages(array('A record with the supplied identity is not active.'));
             $this->setSatisfied(false);
             return false;
         }
     }
     // Set the roles for stuff like ZfcRbac
     $userObject->setRoles($this->getMapper()->getLdapRoles($ldapObj));
     // Success!
     $e->setIdentity($userObject);
     $this->setSatisfied(true);
     $storage = $this->getStorage()->read();
     $storage['identity'] = $userObject;
     $this->getStorage()->write($storage);
     $e->setCode(AuthenticationResult::SUCCESS)->setMessages(array('Authentication successful.'));
 }
示例#23
0
 /**
  * Test getMXRecord
  */
 public function testGetMXRecord()
 {
     if (!defined('TESTS_ZEND_VALIDATE_ONLINE_ENABLED') || !constant('TESTS_ZEND_VALIDATE_ONLINE_ENABLED')) {
         $this->markTestSkipped('Testing MX records has been disabled');
         return;
     }
     $validator = new Validator\EmailAddress(array('useMxCheck' => true, 'allow' => Hostname::ALLOW_ALL));
     if (!$validator->isMxSupported()) {
         $this->markTestSkipped('Testing MX records is not supported with this configuration');
         return;
     }
     $this->assertTrue($validator->isValid('*****@*****.**'));
     $result = $validator->getMXRecord();
     $this->assertTrue(!empty($result));
 }
示例#24
0
    /**
     * @group ZF2-130
     */
    public function testUseMxRecordsBasicInvalid()
    {
        $validator = new Validator\EmailAddress(array('useMxCheck' => true, 'useDeepMxCheck' => true));
        $emailAddresses = array('', 'bob

            @domain.com', 'bob jones@domain.com', '*****@*****.**', '*****@*****.**', '*****@*****.**', '"*****@*****.**', '*****@*****.**', 'bob+domain.com', 'bob.domain.com', 'bob @domain.com', 'bob@ domain.com', 'bob @ domain.com', '*****@*****.**');
        foreach ($emailAddresses as $input) {
            $this->assertFalse($validator->isValid($input), implode("\n", $this->_validator->getMessages()) . $input);
        }
    }
 public function isReserved($host)
 {
     return parent::isReserved($host);
 }
示例#26
0
 /**
  * Get Patron Profile
  *
  * This is responsible for retrieving the profile for a specific patron.
  *
  * @param array $patron The patron array
  *
  * @throws ILSException
  * @return array        Array of the patron's profile data on success.
  */
 public function getMyProfile($patron)
 {
     $sql = "SELECT PATRON.LAST_NAME, PATRON.FIRST_NAME, " . "PATRON.HISTORICAL_CHARGES, PATRON_ADDRESS.ADDRESS_LINE1, " . "PATRON_ADDRESS.ADDRESS_LINE2, PATRON_ADDRESS.ZIP_POSTAL, " . "PATRON_ADDRESS.CITY, PATRON_ADDRESS.COUNTRY, " . "PATRON_PHONE.PHONE_NUMBER, PATRON_GROUP.PATRON_GROUP_NAME " . "FROM {$this->dbName}.PATRON, {$this->dbName}.PATRON_ADDRESS, " . "{$this->dbName}.PATRON_PHONE, {$this->dbName}.PATRON_BARCODE, " . "{$this->dbName}.PATRON_GROUP " . "WHERE PATRON.PATRON_ID = PATRON_ADDRESS.PATRON_ID (+) " . "AND PATRON_ADDRESS.ADDRESS_ID = PATRON_PHONE.ADDRESS_ID (+) " . "AND PATRON.PATRON_ID = PATRON_BARCODE.PATRON_ID (+) " . "AND PATRON_BARCODE.PATRON_GROUP_ID = " . "PATRON_GROUP.PATRON_GROUP_ID (+) " . "AND PATRON.PATRON_ID = :id";
     try {
         $sqlStmt = $this->executeSQL($sql, [':id' => $patron['id']]);
         $patron = [];
         while ($row = $sqlStmt->fetch(PDO::FETCH_ASSOC)) {
             if (!empty($row['FIRST_NAME'])) {
                 $patron['firstname'] = utf8_encode($row['FIRST_NAME']);
             }
             if (!empty($row['LAST_NAME'])) {
                 $patron['lastname'] = utf8_encode($row['LAST_NAME']);
             }
             if (!empty($row['PHONE_NUMBER'])) {
                 $patron['phone'] = utf8_encode($row['PHONE_NUMBER']);
             }
             if (!empty($row['PATRON_GROUP_NAME'])) {
                 $patron['group'] = utf8_encode($row['PATRON_GROUP_NAME']);
             }
             $validator = new EmailAddressValidator();
             $addr1 = utf8_encode($row['ADDRESS_LINE1']);
             if ($validator->isValid($addr1)) {
                 $patron['email'] = $addr1;
             } else {
                 if (!isset($patron['address1'])) {
                     if (!empty($addr1)) {
                         $patron['address1'] = $addr1;
                     }
                     if (!empty($row['ADDRESS_LINE2'])) {
                         $patron['address2'] = utf8_encode($row['ADDRESS_LINE2']);
                     }
                     if (!empty($row['ZIP_POSTAL'])) {
                         $patron['zip'] = utf8_encode($row['ZIP_POSTAL']);
                     }
                     if (!empty($row['CITY'])) {
                         $patron['city'] = utf8_encode($row['CITY']);
                     }
                     if (!empty($row['COUNTRY'])) {
                         $patron['country'] = utf8_encode($row['COUNTRY']);
                     }
                 }
             }
         }
         return empty($patron) ? null : $patron;
     } catch (PDOException $e) {
         throw new ILSException($e->getMessage());
     }
 }
示例#27
0
    /**
     * Testing initializing with several options
     */
    public function testInstanceWithOldOptions()
    {
        $handler = set_error_handler(array($this, 'errorHandler'), E_USER_NOTICE);
        $validator = new Validator\EmailAddress();
        $options   = $validator->getOptions();

        $this->assertEquals(Hostname::ALLOW_DNS, $options['allow']);
        $this->assertFalse($options['mx']);

        try {
            $validator = new Validator\EmailAddress(Hostname::ALLOW_ALL, true, new Hostname(Hostname::ALLOW_ALL));
            $options   = $validator->getOptions();

            $this->assertEquals(Hostname::ALLOW_ALL, $options['allow']);
            $this->assertTrue($options['mx']);
            set_error_handler($handler);
        } catch (\Zend\Exception $e) {
            $this->markTestSkipped('MX not available on this system');
        }
    }
示例#28
0
文件: Model.php 项目: gotcms/gotcms
 /**
  * Set User email
  *
  * @param string $userEmail Email address
  *
  * @return boolean
  */
 public function setEmail($userEmail)
 {
     $userEmail = trim($userEmail);
     $validator = new EmailAddress();
     if ($validator->isValid($userEmail)) {
         $userId = $this->getId();
         $select = $this->select(function (Select $select) use($userEmail, $userId) {
             $select->where->equalTo('email', $userEmail);
             if ($userId !== null) {
                 $select->where->notEqualTo('id', $userId);
             }
         });
         $row = $this->fetchRow($select);
         if (empty($row)) {
             $this->setData('email', $userEmail);
             return true;
         }
     }
     return false;
 }
示例#29
0
 /**
  * Validate a URI using the tag scheme (RFC 4151)
  *
  * @param string $id
  * @return bool
  */
 protected function _validateTagUri($id)
 {
     if (preg_match('/^tag:(?P<name>.*),(?P<date>\\d{4}-?\\d{0,2}-?\\d{0,2}):(?P<specific>.*)(.*:)*$/', $id, $matches)) {
         $dvalid = false;
         $nvalid = false;
         $date = $matches['date'];
         $d6 = strtotime($date);
         if (strlen($date) == 4 && $date <= date('Y')) {
             $dvalid = true;
         } elseif (strlen($date) == 7 && $d6 < strtotime("now")) {
             $dvalid = true;
         } elseif (strlen($date) == 10 && $d6 < strtotime("now")) {
             $dvalid = true;
         }
         $validator = new Validator\EmailAddress();
         if ($validator->isValid($matches['name'])) {
             $nvalid = true;
         } else {
             $nvalid = $validator->isValid('info@' . $matches['name']);
         }
         return $dvalid && $nvalid;
     }
     return false;
 }
示例#30
0
 /**
  * @param $data
  * @param bool $reservationId
  * @return array
  */
 public function validateAndCheckDiscountData($data, $reservationId = false)
 {
     $result = ['valid' => false, 'message' => ''];
     try {
         if ($reservationId) {
             /**
              * @var \DDD\Dao\Booking\Booking $reservationDao
              */
             $reservationDao = $this->getServiceLocator()->get('dao_booking_booking');
             $reservationData = $reservationDao->getDataForDiscountValidationById($reservationId);
             $data = ['email' => $reservationData->getGuestEmail(), 'aff_id' => $reservationData->getPartnerId()];
         }
         $visitor = new Container('visitor');
         if (!isset($data['aff_id']) && !is_null($visitor->partnerId) && (int) $visitor->partnerId) {
             $data['aff_id'] = (int) $visitor->partnerId;
         }
         $emailValidator = new EmailAddress();
         $emailValidator->setOptions(['domain' => true]);
         // validate Email for ginosiks
         if (isset($data['aff_id']) && $data['aff_id'] == self::SECRET_DISCOUNT_AFFILIATE_ID) {
             if (!isset($data['email']) || empty($data['email'])) {
                 $result['message'] .= "Email field is not submitted.\n";
             } elseif (!$emailValidator->isValid($data['email'])) {
                 $result['message'] .= "Email not valid.\n";
             } else {
                 /**
                  * @var UserManager $userManager
                  */
                 $userManager = $this->getServiceLocator()->get('dao_user_user_manager');
                 $userRow = $userManager->getUserIdByEmailAddress($data['email']);
                 // validate User
                 if (!$userRow['id']) {
                     $result['message'] .= "Email does not match the Ginosi User.\n";
                 } elseif ($userRow['system'] != 0 || $userRow['disabled'] != 0) {
                     $result['message'] .= "User disabled or system.\n";
                 } else {
                     $result['email'] = strtolower($data['email']);
                 }
             }
         }
         // validate Affiliate Id
         if (!isset($data['aff_id']) || !is_numeric($data['aff_id'])) {
             $result['message'] .= "Affiliate Id field is not submitted.\n";
         } else {
             $result['aff_id'] = (int) $data['aff_id'];
         }
         // get Affiliate Discount Value
         if (isset($result['aff_id'])) {
             /**
              * @var PartnersDAO $partnerDao
              */
             $partnerDao = $this->getServiceLocator()->get('dao_partners_partners');
             $partnerData = $partnerDao->getPartnerNameAndDiscountById($result['aff_id']);
             // check Affiliate Discount Value
             if (empty($partnerData['discount']) && $partnerData['discount'] <= 0) {
                 $result['message'] .= "Affiliate does not have discounts.\n";
             } else {
                 $result['discount_value'] = $partnerData['discount'];
                 $result['partner_name'] = $partnerData['partner_name'];
             }
         }
         // final judgment
         if (empty($result['message'])) {
             $result['valid'] = true;
             unset($result['message']);
         }
     } catch (\Exception $e) {
         $this->gr2logException($e, 'Cannot validate and check reservation discount data', $data);
     }
     return $result;
 }