Exemplo n.º 1
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;
 }
Exemplo n.º 2
0
 /**
  *
  * @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;
     }
 }
Exemplo n.º 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);
 }
Exemplo n.º 5
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;
 }
Exemplo n.º 6
0
 /**
  * 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!");
     }
 }
Exemplo n.º 7
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;
 }
Exemplo n.º 8
0
 function setEmail($email)
 {
     $validador = new EmailAddress();
     if (!$validador->isValid($email)) {
         throw new Exception("E-mail não e valido");
     }
     $this->email = $email;
 }
Exemplo n.º 9
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);
 }
Exemplo n.º 10
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');
 }
Exemplo n.º 11
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]);
 }
Exemplo n.º 12
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.');
     }
 }
Exemplo n.º 13
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]);
 }
Exemplo n.º 14
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;
 }
Exemplo n.º 15
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) {
     }
 }
Exemplo n.º 16
0
 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;
     }
 }
Exemplo n.º 17
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;
 }
Exemplo n.º 18
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');
     }
 }
Exemplo n.º 19
0
   /**
     * Test changing hostname settings via EmailAddress object
     *
     * @return void
     */
    public function testHostnameSettings()
    {
        $validator = new Validator\EmailAddress();

        // Check no IDN matching
        $validator->getHostnameValidator()->setValidateIdn(false);
        $valuesExpected = array(
            array(false, array('name@b�rger.de', 'name@h�llo.de', 'name@h�llo.se'))
            );
        foreach ($valuesExpected as $element) {
            foreach ($element[1] as $input) {
                $this->assertEquals($element[0], $validator->isValid($input), implode("\n", $validator->getMessages()));
            }
        }

        // Check no TLD matching
        $validator->getHostnameValidator()->setValidateTld(false);
        $valuesExpected = array(
            array(true, array('*****@*****.**', '*****@*****.**', '*****@*****.**'))
            );
        foreach ($valuesExpected as $element) {
            foreach ($element[1] as $input) {
                $this->assertEquals($element[0], $validator->isValid($input), implode("\n", $validator->getMessages()));
            }
        }
    }
Exemplo n.º 20
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.'));
 }
Exemplo n.º 21
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));
 }
Exemplo n.º 22
0
 protected function assertValidEntry($entry, $isUpdate = false)
 {
     $domainDn = null;
     $errors = array();
     /*
      * employeeNumber
      */
     if (!preg_match('#^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$#', $entry['employeeNumber'])) {
         // This is fatal
         if ($isUpdate !== true) {
             throw new UserFriendlyException(500, 'Server error', 'The server is unable to generate a valid ID for this account. Please contact a technician.');
         } else {
             throw new UserFriendlyException(400, 'Incorrect request', 'The account ID provided with this request is incorrect.');
         }
     }
     /*
      * cn
      */
     if (!isset($entry['cn']) || empty($entry['cn'])) {
         $errors['cn'] = 'Display name is required.';
     }
     /*
      * givenName
      */
     // Nop
     /* 
      * sn
      */
     if (!isset($entry['sn']) || empty($entry['sn'])) {
         $errors['sn'] = 'Last name is required.';
     }
     /*
      * mail
      */
     // Validate mail format
     $emailValidator = new EmailAddress();
     if (!isset($entry['mail']) || empty($entry['mail'])) {
         $errors['mail'] = 'Email is required.';
     } else {
         if (!$emailValidator->isValid($entry['mail'])) {
             $errors['mail'] = 'The email provided is not correctly formated.';
         } else {
             // Validate mail domain-part is an allowed domain
             $result = $this->ldap->search(array('filter' => '(|(dc=' . Filter::escapeValue($emailValidator->hostname) . ')(associatedDomain=' . Filter::escapeValue($emailValidator->hostname) . '))', 'basedn' => $this->userBaseDn, 'attributes' => array('dc'), 'sizelimit' => 2));
             if ($result->count() < 1) {
                 $errors['mail'] = array('You are not allowed to create an account for the domain \'%@1\'.', $emailValidator->hostname);
             } else {
                 if ($result->count() > 1) {
                     // This is fatal
                     throw new UserFriendlyException(500, 'Server error', 'An inconsistency has been detected in the data. Please contact a technician.');
                 } else {
                     $domainEntry = $result->getFirst();
                     if ($domainEntry['dc'][0] !== $emailValidator->hostname) {
                         $errors['mail'] = array('\'%@1\' is a domain alias. Please use the primary domain.', $emailValidator->hostname);
                     } else {
                         $domainDn = $result->dn();
                         // Validate mail unicity
                         $result = $this->ldap->search(array('filter' => '(|(mail=' . Filter::escapeValue($entry['mail']) . ')(mailAlias=' . Filter::escapeValue($entry['mail']) . '))', 'basedn' => $domainDn, 'attributes' => array('employeeNumber'), 'sizelimit' => 2));
                         $result->getInnerIterator()->setAttributeNameTreatment(DefaultIterator::ATTRIBUTE_NATIVE);
                         if ($result->count() === 1) {
                             $duplicateEntry = $result->getFirst();
                             if ($isUpdate === false || $entry['employeeNumber'] !== $duplicateEntry['employeeNumber'][0]) {
                                 $errors['mail'] = 'This email address already exists on an other account.';
                             }
                         } else {
                             if ($result->count() > 1) {
                                 // This is fatal
                                 throw new UserFriendlyException(500, 'Server error', 'An inconsistency has been detected in the data. Please contact a technician.');
                             }
                         }
                     }
                 }
             }
         }
     }
     /*
      * mailAlias
      */
     // Validate each mail aliases
     if (!empty($entry['mailAlias']) && !is_array($entry['mailAlias'])) {
         $errors['mailAlias'] = 'The data for email aliases are not consistent.';
     } else {
         if (!empty($entry['mailAlias'])) {
             $errors['mailAlias'] = array();
             $aliasValidator = new EmailAddress();
             foreach ($entry['mailAlias'] as $alias) {
                 if (!$aliasValidator->isValid($alias)) {
                     // Validate alias format
                     $errors['mailAlias'][$alias] = 'The email alias provided is not correctly formated.';
                 } else {
                     if ($emailValidator->hostname !== $aliasValidator->hostname) {
                         // Validate alias domain-part is the same as mail domain-part
                         $errors['mailAlias'][$alias] = 'The email alias must use the same domain as the email.';
                     } else {
                         if ($alias === $entry['mail']) {
                             // Validate alias unicity with mail
                             $errors['mailAlias'][$alias] = 'The email alias address cannot be the same as the alias must use the same domain as the email.';
                         } else {
                             // Validate alias unicity with other entries (including mail)
                         }
                     }
                 }
             }
             if (count($errors['mailAlias']) < 1) {
                 unset($errors['mailAlias']);
             }
         }
     }
     /*
      * password / passwordConfirmation
      */
     if (isset($entry['userPassword']) && strlen($entry['userPassword']) < 6) {
         $errors['password'] = '******';
     } else {
         if (isset($entry['userPassword']) && isset($entry['userPassword']) !== isset($entry['passwordConfirmation'])) {
             $errors['passwordConfirmation'] = 'Please re-enter the password to confirm it.';
         } else {
             if (isset($entry['userPassword']) && $entry['userPassword'] !== $entry['passwordConfirmation']) {
                 $errors['passwordConfirmation'] = 'The confirmation does not match. Please check both password and its confirmation.';
             }
         }
     }
     //
     if (empty($errors)) {
         return sprintf('employeeNumber=%s,ou=Mailboxes,%s', $entry['employeeNumber'], $domainDn);
     } else {
         $description = count($errors) === 1 ? 'There were an error processing your request. Please review the field marked in red.' : 'There were errors processing your request. Please review the fields marked in red.';
         throw new UserFriendlyException(400, 'Provided data are incorrect', $description, $errors);
     }
 }
Exemplo n.º 23
0
 /**
  * @param         $emailAddress
  *
  * @return Entity\Organisation[]|null
  */
 public function findOrganisationByEmailAddress($emailAddress)
 {
     $qb = $this->_em->createQueryBuilder();
     $qb->select('o');
     $qb->distinct('o.id');
     $qb->from('Organisation\\Entity\\Organisation', 'o');
     $qb->join('o.country', 'c');
     //Inner join on contact_organisations to only have active organisations
     $qb->join('o.contactOrganisation', 'co');
     $subSelect = $this->_em->createQueryBuilder();
     $subSelect->select('wo');
     $subSelect->from('Organisation\\Entity\\Web', 'w');
     $subSelect->join('w.organisation', 'wo');
     $subSelect->andWhere('w.web LIKE :domain');
     $subSelect->andWhere($qb->expr()->notIn('w.web', ['gmail.com', 'hotmail.com', 'yahoo.com']));
     /**
      * Use the ZF2 EmailAddress validator to strip the hostname out of the EmailAddress
      */
     $validateEmail = new EmailAddress();
     $validateEmail->isValid($emailAddress);
     $qb->setParameter('domain', "%" . $validateEmail->hostname . "%");
     //We want a match on the email address
     $qb->andWhere($qb->expr()->in('o.id', $subSelect->getDQL()));
     $qb->addOrderBy('c.country', 'ASC');
     $qb->addOrderBy('o.organisation', 'ASC');
     return $qb->getQuery()->getResult();
 }
Exemplo n.º 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);
        }
    }
Exemplo n.º 25
0
 /**
  * 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;
 }
Exemplo n.º 26
0
 /**
  * We use this function to update the contactOrganisation of a user.
  * As input we use the corresponding contact entity and the array containing the
  * contactOrganisation information.
  *
  * $contactOrganisation['organisation_id'] > id of the chosen organisation
  * $contactOrganisation['branch'] > value of the branch (if an organisation_id is chosen)
  * $contactOrganisation['organisation'] > Name of the organisation
  * $contactOrganisation['country'] > CountryId
  *
  * @param Contact $contact
  * @param array   $contactOrganisation
  */
 public function updateContactOrganisation(Contact $contact, array $contactOrganisation)
 {
     /**
      * Find the current contactOrganisation, or create a new one if this empty (in case of a new contact)
      */
     $currentContactOrganisation = $contact->getContactOrganisation();
     if (is_null($currentContactOrganisation)) {
         $currentContactOrganisation = new ContactOrganisation();
         $currentContactOrganisation->setContact($contact);
     }
     /**
      * The trigger for this update is the presence of a $contactOrganisation['organisation_id'].
      * If this value != 0, a choice has been made from the dropdown and we will then take the branch as default
      */
     if (isset($contactOrganisation['organisation_id']) && $contactOrganisation['organisation_id'] != '0') {
         $organisation = $this->getOrganisationService()->findEntityById('organisation', (int) $contactOrganisation['organisation_id']);
         $currentContactOrganisation->setOrganisation($organisation);
         //Take te branch form the form element ($contactOrganisation['branch'])
         if (!empty($contactOrganisation['branch'])) {
             $currentContactOrganisation->setBranch($contactOrganisation['branch']);
         } else {
             $currentContactOrganisation->setBranch(null);
         }
     } else {
         /**
          * No organisation is chosen (the option 'none of the above' was taken, so create the organisation
          */
         /**
          * Don't do anything when the organisationName = empty
          */
         if (empty($contactOrganisation['organisation'])) {
             return;
         }
         $country = $this->getGeneralService()->findEntityById('country', (int) $contactOrganisation['country']);
         /*
          * Look for the organisation based on the name (without branch) and country + email
          */
         $organisation = $this->getOrganisationService()->findOrganisationByNameCountryAndEmailAddress($contactOrganisation['organisation'], $country, $contact->getEmail());
         $organisationFound = false;
         /*
          * We did not find an organisation, so we need to create it
          */
         if (sizeof($organisation) === 0) {
             $organisation = new Organisation();
             $organisation->setOrganisation($contactOrganisation['organisation']);
             $organisation->setCountry($country);
             $organisation->setType($this->organisationService->findEntityById('Type', 0));
             //Unknown
             /*
              * Add the domain in the saved domains for this new company
              * Use the ZF2 EmailAddress validator to strip the hostname out of the EmailAddress
              */
             $validateEmail = new EmailAddress();
             $validateEmail->isValid($contact->getEmail());
             $organisationWeb = new Web();
             $organisationWeb->setOrganisation($organisation);
             $organisationWeb->setWeb($validateEmail->hostname);
             $organisationWeb->setMain(Web::MAIN);
             //Skip hostnames like yahoo, gmail and hotmail, outlook
             if (!in_array($organisation->getWeb(), ['gmail.com', 'hotmail.com', 'outlook.com', 'yahoo.com'])) {
                 $this->getOrganisationService()->newEntity($organisationWeb);
             }
             $currentContactOrganisation->setOrganisation($organisation);
         } else {
             $foundOrganisation = null;
             /*
              * Go over the found organisation to match the branching
              */
             foreach ($organisation as $foundOrganisation) {
                 /*
                  * Stop when we have found an exact match and reset the branch if set
                  */
                 if ($foundOrganisation->getOrganisation() === $contactOrganisation['organisation'] && $country->getId() === $foundOrganisation->getCountry()->getId()) {
                     $currentContactOrganisation->setOrganisation($foundOrganisation);
                     $currentContactOrganisation->setBranch(null);
                     break;
                 }
                 if (!$organisationFound) {
                     //Create only a branch when the name is found and the given names do not match in length
                     if (strlen($foundOrganisation->getOrganisation()) < strlen($contactOrganisation['organisation']) - strlen($currentContactOrganisation->getBranch())) {
                         $currentContactOrganisation->setBranch(str_replace($contactOrganisation['organisation'], '~', $foundOrganisation->getOrganisation()));
                     } else {
                         //Reset the branch otherwise
                         $currentContactOrganisation->setBranch(null);
                     }
                     /*
                      * We have found a match of the organisation in the string and
                      */
                     $organisationFound = true;
                 }
             }
             $currentContactOrganisation->setOrganisation($foundOrganisation);
         }
     }
     $this->updateEntity($currentContactOrganisation);
 }
Exemplo n.º 27
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;
 }
Exemplo n.º 28
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());
     }
 }
Exemplo n.º 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;
 }
Exemplo n.º 30
0
 /**
  * With this function we will do some basic testing to see if the least amount of information is available.
  */
 protected function validateData()
 {
     $minimalRequiredElements = ['email', 'firstname', 'lastname'];
     /*
      * Go over all elements and check if the required elements are present
      */
     foreach ($minimalRequiredElements as $element) {
         if (!in_array($element, $this->header)) {
             $this->errors[] = sprintf("Element %s is missing in the file", $element);
         }
     }
     /*
      * Create the lookup-table
      */
     $this->headerKeys = array_flip($this->header);
     /*
      * Validate the elements.
      */
     $counter = 2;
     foreach ($this->content as $content) {
         /**
          * Validate the email addresses
          */
         $validate = new EmailAddress();
         if (!$validate->isValid($content[$this->headerKeys['email']])) {
             $this->errors[] = sprintf("EmailAddress (%s) in row %s is invalid", $content[$this->headerKeys['email']], $counter);
         }
         /**
          * Validate the organisation_id
          */
         if (!empty($this->headerKeys['organisation_id'])) {
             $organisationService = $this->getOrganisationService()->setOrganisationId($this->headerKeys['organisation_id']);
             if ($organisationService->isEmpty()) {
                 $this->errors[] = sprintf("Organisation with ID (%s) in row %s is cannot be found", $content[$this->headerKeys['organisation_id']], $counter);
             }
         }
         /**
          * Validate the country
          */
         if (!empty($this->headerKeys['country'])) {
             $country = $this->getGeneralService()->findCountryByName($content[$this->headerKeys['country']]);
             if (is_null($country)) {
                 $this->warnings[] = sprintf("Country (%s) in row %s is cannot be found", $content[$this->headerKeys['country']], $counter);
             }
         }
         $counter++;
     }
 }