Exemplo n.º 1
0
 public function testGetNewToken()
 {
     $tockens = array();
     while (sizeof($tockens) < 100) {
         $newToken = SentEmail::getNewToken();
         $this->assertNotContains($newToken, $tockens);
         $tockens[] = $newToken;
     }
 }
 public function testWebViewAction_Admin_with_CampaignParams()
 {
     $token = "fdasdfasfafsadf";
     $twigMock = $this->getMockBuilder("Symfony\\Bundle\\TwigBundle\\TwigEngine")->disableOriginalConstructor()->getMock();
     $twigMock->expects($this->once())->method("renderResponse")->will($this->returnCallback(array($this, 'renderResponseCallback')));
     $userMock = $this->getMockBuilder('FOS\\UserBundle\\Model\\User')->getMock();
     $userMock->expects($this->once())->method("getEmail")->will($this->returnValue("*****@*****.**"));
     $userMock->expects($this->once())->method("hasRole")->with("ROLE_ADMIN")->will($this->returnValue(true));
     $sentEmail = new SentEmail();
     $sentEmail->setRecipients(array("*****@*****.**"));
     $sentEmail->setSent(new \DateTime("2 weeks ago"));
     $sentEmail->setTemplate(AzineTemplateProvider::NEWSLETTER_TEMPLATE);
     $sentEmail->setVariables(array());
     $sentEmail->setToken($token);
     $repositoryMock = $this->getMockBuilder("Azine\\EmailBundle\\Entity\\Repositories\\SentEmailRepository")->disableOriginalConstructor()->setMethods(array('findOneByToken'))->getMock();
     $repositoryMock->expects($this->once())->method("findOneByToken")->will($this->returnValue($sentEmail));
     $doctrineManagerMock = $this->getMockBuilder("Doctrine\\ORM\\EntityManager")->disableOriginalConstructor()->getMock();
     $doctrineManagerRegistryMock = $this->getMockBuilder("Doctrine\\Common\\Persistence\\ManagerRegistry")->disableOriginalConstructor()->getMock();
     $doctrineManagerRegistryMock->expects($this->once())->method('getRepository')->with('AzineEmailBundle:SentEmail')->will($this->returnValue($repositoryMock));
     $doctrineManagerRegistryMock->expects($this->once())->method('getManager')->will($this->returnValue($this->returnValue($doctrineManagerMock)));
     $securityTokenMock = $this->getMockBuilder("Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface")->disableOriginalConstructor()->getMock();
     $securityTokenMock->expects($this->exactly(2))->method('getUser')->will($this->returnValue($userMock));
     $securityContextMock = $this->getMockBuilder("Symfony\\Component\\Security\\Core\\SecurityContext")->disableOriginalConstructor()->getMock();
     $securityContextMock->expects($this->once())->method('getToken')->will($this->returnValue($securityTokenMock));
     $templateProviderMock = $this->getMockBuilder("Azine\\EmailBundle\\Services\\AzineTemplateProvider")->disableOriginalConstructor()->getMock();
     $templateProviderMock->expects($this->once())->method('getWebViewTokenId')->will($this->returnValue("tokenId"));
     $templateProviderMock->expects($this->once())->method('getCampaignParamsFor')->will($this->returnValue(array("campaign" => "newsletter", "keyword" => "2013-11-19")));
     $containerMock = $this->getMockBuilder("Symfony\\Component\\DependencyInjection\\ContainerInterface")->disableOriginalConstructor()->getMock();
     $containerMock->expects($this->exactly(5))->method("get")->will($this->returnValueMap(array(array('azine_email_template_provider', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $templateProviderMock), array('templating', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $twigMock), array('doctrine', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $doctrineManagerRegistryMock), array('security.context', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $securityContextMock))));
     $containerMock->expects($this->once())->method("has")->with('security.context')->will($this->returnValue(true));
     $controller = new AzineEmailTemplateController();
     $controller->setContainer($containerMock);
     $response = $controller->webViewAction($token);
     $this->assertContains("http://testurl.com/?campaign=newsletter&keyword=2013-11-19", $response->getContent());
     $this->assertContains('http://testurl.com/with/?param=1&campaign=newsletter&keyword=2013-11-19', $response->getContent());
 }
 /**
  * Check if the user is allowed to see the email.
  * => the mail is public or the user is among the recipients or the user is an admin.
  *
  * @param  SentEmail $mail
  * @return boolean
  */
 private function userIsAllowedToSeeThisMail(SentEmail $mail)
 {
     $recipients = $mail->getRecipients();
     // it is a public email
     if ($recipients == null) {
         return true;
     }
     // get the current user
     $currentUser = null;
     if (!$this->container->has('security.context')) {
         // @codeCoverageIgnoreStart
         throw new \LogicException('The SecurityBundle is not registered in your application.');
         // @codeCoverageIgnoreEnd
     } else {
         $token = $this->container->get('security.context')->getToken();
         // check if the token is not null and the user in the token an object
         if ($token instanceof TokenInterface && is_object($token->getUser())) {
             $currentUser = $token->getUser();
         }
     }
     // it is not a public email, and a user is logged in
     if ($currentUser != null) {
         // the user is among the recipients
         if (array_search($currentUser->getEmail(), $recipients) !== false) {
             return true;
         }
         // the user is admin
         if ($currentUser->hasRole("ROLE_ADMIN")) {
             return true;
         }
     }
     // not public email, but
     // 		- there is no user, or
     //		- the user is not among the recipients and
     //		- the user not an admin-user either
     return false;
 }
Exemplo n.º 4
0
 /**
  * (non-PHPdoc)
  * @see Azine\EmailBundle\Services.TemplateTwigSwiftMailerInterface::sendEmail()
  * @param array $failedRecipients
  * @param string $subject
  * @param String $from
  * @param String $fromName
  * @param array|String $to
  * @param String $toName
  * @param array|String $cc
  * @param String $ccName
  * @param array|String $bcc
  * @param String $bccName
  * @param $replyTo
  * @param $replyToName
  * @param array $params
  * @param $template
  * @param array $attachments
  * @param null $emailLocale
  * @param \Swift_Message $message
  * @return int
  */
 public function sendEmail(&$failedRecipients, $subject, $from, $fromName, $to, $toName, $cc, $ccName, $bcc, $bccName, $replyTo, $replyToName, array $params, $template, $attachments = array(), $emailLocale = null, \Swift_Message &$message = null)
 {
     // create the message
     if ($message == null) {
         $message = \Swift_Message::newInstance();
     }
     $message->setSubject($subject);
     // set the from-Name & -Emali to the default ones if not given
     if ($from == null) {
         $from = $this->noReplyEmail;
     }
     if ($fromName == null) {
         $fromName = $this->noReplyName;
     }
     // add the from-email for the footer-text
     if (!array_key_exists('fromEmail', $params)) {
         $params['sendMailAccountName'] = $this->noReplyName;
         $params['sendMailAccountAddress'] = $this->noReplyEmail;
     }
     // get the baseTemplate. => templateId without the ending.
     $templateBaseId = substr($template, 0, strrpos($template, ".", -6));
     // check if this email should be stored for web-view
     if ($this->templateProvider->saveWebViewFor($templateBaseId)) {
         // keep a copy of the vars for the web-view
         $webViewParams = $params;
         // add the web-view token
         $params[$this->templateProvider->getWebViewTokenId()] = SentEmail::getNewToken();
     } else {
         $webViewParams = array();
     }
     // recursively add all template-variables for the wrapper-templates and contentItems
     $params = $this->templateProvider->addTemplateVariablesFor($templateBaseId, $params);
     // recursively attach all messages in the array
     $this->embedImages($message, $params);
     // change the locale for the email-recipients
     if ($emailLocale !== null && strlen($emailLocale) > 0) {
         $currentUserLocale = $this->translator->getLocale();
         // change the router-context locale
         $this->routerContext->setParameter("_locale", $emailLocale);
         // change the translator locale
         $this->translator->setLocale($emailLocale);
     } else {
         $emailLocale = $this->translator->getLocale();
     }
     // recursively add snippets for the wrapper-templates and contentItems
     $params = $this->templateProvider->addTemplateSnippetsWithImagesFor($templateBaseId, $params, $emailLocale);
     // add the emailLocale (used for web-view)
     $params['emailLocale'] = $emailLocale;
     // render the email parts
     $twigTemplate = $this->loadTemplate($template);
     $textBody = $twigTemplate->renderBlock('body_text', $params);
     $message->addPart($textBody, 'text/plain');
     $htmlBody = $twigTemplate->renderBlock('body_html', $params);
     $campaignParams = $this->templateProvider->getCampaignParamsFor($templateBaseId, $params);
     if (sizeof($campaignParams) > 0) {
         $htmlBody = $this->emailTwigExtension->addCampaignParamsToAllUrls($htmlBody, $campaignParams);
     }
     // if email-tracking is enabled
     if ($this->emailOpenTrackingCodeBuilder) {
         // add an image at the end of the html tag with the tracking-params to track email-opens
         $imgTrackingCode = $this->emailOpenTrackingCodeBuilder->getTrackingImgCode($templateBaseId, $campaignParams, $params, $message->getId(), $to, $cc, $bcc);
         if ($imgTrackingCode && strlen($imgTrackingCode) > 0) {
             $htmlCloseTagPosition = strpos($htmlBody, "</body>");
             $htmlBody = substr_replace($htmlBody, $imgTrackingCode, $htmlCloseTagPosition, 0);
         }
     }
     $message->setBody($htmlBody, 'text/html');
     // remove unused/unreferenced embeded items from the message
     $message = $this->removeUnreferecedEmbededItemsFromMessage($message, $params, $htmlBody);
     // change the locale back to the users locale
     if (isset($currentUserLocale) && $currentUserLocale != null) {
         $this->routerContext->setParameter("_locale", $currentUserLocale);
         $this->translator->setLocale($currentUserLocale);
     }
     // add attachments
     foreach ($attachments as $fileName => $file) {
         // add attachment from existing file
         if (is_string($file)) {
             // check that the file really exists!
             if (file_exists($file)) {
                 $attachment = \Swift_Attachment::fromPath($file);
                 if (strlen($fileName) >= 5) {
                     $attachment->setFilename($fileName);
                 }
             } else {
                 throw new FileException("File not found: " . $file);
             }
             // add attachment from generated data
         } else {
             $attachment = \Swift_Attachment::newInstance($file, $fileName);
         }
         $message->attach($attachment);
     }
     // set the addresses
     if ($from) {
         $message->setFrom($from, $fromName);
     }
     if ($replyTo) {
         $message->setReplyTo($replyTo, $replyToName);
     } elseif ($from) {
         $message->setReplyTo($from, $fromName);
     }
     if ($to) {
         $message->setTo($to, $toName);
     }
     if ($cc) {
         $message->setCc($cc, $ccName);
     }
     if ($bcc) {
         $message->setBcc($bcc, $bccName);
     }
     // add custom headers
     $this->templateProvider->addCustomHeaders($templateBaseId, $message, $params);
     // send the message
     $mailer = $this->getMailer($params);
     $messagesSent = $mailer->send($message, $failedRecipients);
     // if the message was successfully sent,
     // and it should be made available in web-view
     if ($messagesSent && array_key_exists($this->templateProvider->getWebViewTokenId(), $params)) {
         // store the email
         $sentEmail = new SentEmail();
         $sentEmail->setToken($params[$this->templateProvider->getWebViewTokenId()]);
         $sentEmail->setTemplate($templateBaseId);
         $sentEmail->setSent(new \DateTime());
         // recursively add all template-variables for the wrapper-templates and contentItems
         $webViewParams = $this->templateProvider->addTemplateVariablesFor($template, $webViewParams);
         // replace absolute image-paths with relative ones.
         $webViewParams = $this->templateProvider->makeImagePathsWebRelative($webViewParams, $emailLocale);
         // recursively add snippets for the wrapper-templates and contentItems
         $webViewParams = $this->templateProvider->addTemplateSnippetsWithImagesFor($template, $webViewParams, $emailLocale, true);
         $sentEmail->setVariables($webViewParams);
         // save only successfull recipients
         if (!is_array($to)) {
             $to = array($to);
         }
         $successfulRecipients = array_diff($to, $failedRecipients);
         $sentEmail->setRecipients($successfulRecipients);
         // write to db
         $em = $this->managerRegistry->getManager();
         $em->persist($sentEmail);
         $em->flush($sentEmail);
         $em->clear();
         gc_collect_cycles();
     }
     return $messagesSent;
 }