public function testEnsureEmailBodyCachedForAlreadyCached()
 {
     $email = new Email();
     $email->setEmailBody(new EmailBody());
     $this->emailBodySynchronizer->expects($this->never())->method('syncOneEmailBody');
     $this->manager->ensureEmailBodyCached($email);
 }
 /**
  * @dataProvider replaceDataProvider
  * @param       $bodyTemplate
  * @param array $attachments
  */
 public function testReplace($bodyTemplate, array $attachments)
 {
     $email = new Email();
     $emailBody = new EmailBody();
     $replacements = [];
     $contentIds = [];
     foreach ($attachments as $attachmentData) {
         $attachment = new EmailAttachment();
         $emailAttachmentContent = new EmailAttachmentContent();
         $emailAttachmentContent->setContent($attachmentData['content'])->setContentTransferEncoding($attachmentData['transfer_encoding']);
         $attachment->setEmbeddedContentId($attachmentData['content_id'])->setContentType($attachmentData['type'])->setContent($emailAttachmentContent);
         $emailBody->addAttachment($attachment);
         $cid = 'cid:' . $attachmentData['content_id'];
         $contentIds[] = $cid;
         if ($attachmentData['replace']) {
             $replacements[] = sprintf('data:%s;base64,%s', $attachmentData['type'], $attachmentData['content']);
         } else {
             $replacements[] = $cid;
         }
     }
     $emailBody->setBodyContent(vsprintf($bodyTemplate, $contentIds));
     $email->setEmailBody($emailBody);
     $event = new EmailBodyLoaded($email);
     $this->listener->replace($event);
     $this->assertEquals($email, $event->getEmail());
     $this->assertEquals(vsprintf($bodyTemplate, $replacements), $event->getEmail()->getEmailBody()->getBodyContent());
 }
 /**
  * Check that email body is cached.
  * If do not, load it using appropriate email extension add it to a cache.
  *
  * @param Email $email
  *
  * @throws LoadEmailBodyException if a body of the given email cannot be loaded
  */
 public function ensureEmailBodyCached(Email $email)
 {
     if ($email->getEmailBody() === null) {
         // body loader can load email from any folder
         // todo: refactor to use correct emailuser and origin
         // to use active origin and get correct folder from this origin
         $emailUser = $email->getEmailUsers()->first();
         $folder = $emailUser->getFolders()->first();
         $origin = $emailUser->getOrigin();
         if (!$origin) {
             throw new LoadEmailBodyFailedException($email);
         }
         $loader = $this->selector->select($origin);
         try {
             $emailBody = $loader->loadEmailBody($folder, $email, $this->em);
         } catch (LoadEmailBodyException $loadEx) {
             $this->logger->notice(sprintf('Load email body failed. Email id: %d. Error: %s', $email->getId(), $loadEx->getMessage()), ['exception' => $loadEx]);
             throw $loadEx;
         } catch (\Exception $ex) {
             $this->logger->warning(sprintf('Load email body failed. Email id: %d. Error: %s.', $email->getId(), $ex->getMessage()), ['exception' => $ex]);
             throw new LoadEmailBodyFailedException($email, $ex);
         }
         $email->setEmailBody($emailBody);
         $this->em->persist($email);
         $this->em->flush();
         $event = new EmailBodyAdded($email);
         $this->eventDispatcher->dispatch(EmailBodyAdded::NAME, $event);
     }
     $this->eventDispatcher->dispatch(EmailBodyLoaded::NAME, new EmailBodyLoaded($email));
 }
 /**
  * Returns the context for the given email
  *
  * @param Email $email
  *
  * @return array
  */
 public function getEmailContext(Email $email)
 {
     $criteria = Criteria::create();
     $criteria->andWhere(Criteria::expr()->eq('id', $email->getId()));
     $qb = $this->activityManager->getActivityTargetsQueryBuilder($this->class, $criteria);
     if (null === $qb) {
         return [];
     }
     $result = $qb->getQuery()->getResult();
     if (empty($result)) {
         return $result;
     }
     $currentUser = $this->securityFacade->getLoggedUser();
     $currentUserClass = ClassUtils::getClass($currentUser);
     $currentUserId = $currentUser->getId();
     $result = array_values(array_filter($result, function ($item) use($currentUserClass, $currentUserId) {
         return !($item['entity'] === $currentUserClass && $item['id'] == $currentUserId);
     }));
     foreach ($result as &$item) {
         $route = $this->configManager->getEntityMetadata($item['entity'])->getRoute();
         $item['entityId'] = $email->getId();
         $item['targetId'] = $item['id'];
         $item['targetClassName'] = $this->entityClassNameHelper->getUrlSafeClassName($item['entity']);
         $item['icon'] = $this->configManager->getProvider('entity')->getConfig($item['entity'])->get('icon');
         $item['link'] = $route ? $this->router->generate($route, ['id' => $item['id']]) : null;
         unset($item['id'], $item['entity']);
     }
     return $result;
 }
 /**
  * (@inherit)
  */
 public function setFlags(EmailFolder $folder, Email $email, $flags)
 {
     $repoImapEmail = $this->em->getRepository('OroImapBundle:ImapEmail');
     $uid = $repoImapEmail->getUid($folder->getId(), $email->getId());
     $this->connector->selectFolder($folder->getFullName());
     $this->connector->setFlags($uid, $flags);
 }
 /**
  * Check that email body is cached.
  * If do not, load it using appropriate email extension add it to a cache.
  *
  * @param Email $email
  *
  * @throws LoadEmailBodyException if a body of the given email cannot be loaded
  */
 public function ensureEmailBodyCached(Email $email)
 {
     if ($email->getEmailBody() !== null) {
         // The email body is already cached
         return;
     }
     // body loader can load email from any folder
     $folder = $email->getEmailUsers()->first()->getFolder();
     $origin = $folder->getOrigin();
     $loader = $this->selector->select($origin);
     try {
         $emailBody = $loader->loadEmailBody($folder, $email, $this->em);
     } catch (LoadEmailBodyException $loadEx) {
         $this->logger->notice(sprintf('Load email body failed. Email id: %d. Error: %s', $email->getId(), $loadEx->getMessage()), ['exception' => $loadEx]);
         throw $loadEx;
     } catch (\Exception $ex) {
         $this->logger->warning(sprintf('Load email body failed. Email id: %d. Error: %s.', $email->getId(), $ex->getMessage()), ['exception' => $ex]);
         throw new LoadEmailBodyFailedException($email, $ex);
     }
     $email->setEmailBody($emailBody);
     $this->em->persist($email);
     $this->em->flush();
     $event = new EmailBodyAdded($email);
     $this->eventDispatcher->dispatch(EmailBodyAdded::NAME, $event);
 }
 public function testGetDate()
 {
     $email = new Email();
     $date = new \DateTime('now', new \DateTimeZone('UTC'));
     $email->setSentAt($date);
     $this->assertSame($date, $this->provider->getDate($email));
 }
 /**
  * Check that email body is cached.
  * If do not, load it using appropriate email extension add it to a cache.
  *
  * @param Email $email
  */
 public function ensureEmailBodyCached(Email $email)
 {
     if ($email->getEmailBody() === null) {
         $this->emailBodySynchronizer->syncOneEmailBody($email);
         $this->em->flush();
     }
     $this->eventDispatcher->dispatch(EmailBodyLoaded::NAME, new EmailBodyLoaded($email));
 }
Exemple #9
0
 public function testBeforeSave()
 {
     $entity = new Email();
     $entity->beforeSave();
     $createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
     $this->assertEquals(Email::NORMAL_IMPORTANCE, $entity->getImportance());
     $this->assertGreaterThanOrEqual($createdAt, $entity->getCreated());
 }
 /**
  * @param Email  $email
  * @param \Exception $previous
  */
 public function __construct(Email $email, \Exception $previous = null)
 {
     $message = sprintf('Cannot load a body for "%s" email.', $email->getSubject());
     if ($previous) {
         $message .= sprintf(' Reason: %s.', $previous->getMessage());
     }
     parent::__construct($message, 0, $previous);
 }
 /**
  * @param array $targets
  * @param Email $email
  */
 protected function addRecipientOwners(&$targets, Email $email)
 {
     $recipients = $email->getRecipients();
     foreach ($recipients as $recipient) {
         $owner = $recipient->getEmailAddress()->getOwner();
         if ($owner) {
             $this->addTarget($targets, $owner);
         }
     }
 }
 /**
  * @param Email $email
  *
  * @return bool|string
  */
 protected function getFromNameLink(Email $email)
 {
     $path = false;
     if ($email->getFromEmailAddress() && $email->getFromEmailAddress()->getOwner()) {
         $className = $email->getFromEmailAddress()->getOwner()->getClass();
         $routeName = $this->configManager->getEntityMetadata($className)->getRoute('view', false);
         $path = $this->router->generate($routeName, ['id' => $email->getFromEmailAddress()->getOwner()->getId()]);
     }
     return $path;
 }
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $fromEmail = new EmailAddressProxy();
     $fromEmail->setEmail(uniqid() . '@gmail.com');
     $email = new Email();
     $email->setSubject(uniqid())->setFromName(uniqid())->setReceivedAt(new \DateTime())->setSentAt(new \DateTime())->setInternalDate(new \DateTime())->setFromEmailAddress($fromEmail)->setMessageId(uniqid());
     $manager->persist($fromEmail);
     $manager->persist($email);
     $manager->flush();
 }
 /**
  * Check that email body is cached.
  * If do not, load it using appropriate email extension add it to a cache.
  *
  * @param Email $email
  */
 public function ensureEmailBodyCached(Email $email)
 {
     if ($email->getEmailBody() !== null) {
         // The email body is already cached
         return;
     }
     $emailBody = $this->selector->select($email->getFolder()->getOrigin())->loadEmailBody($email, $this->em);
     $email->setEmailBody($emailBody);
     $this->em->persist($email);
     $this->em->flush();
 }
 /**
  * Add recipients to the specified Email object
  *
  * @param Email $obj The Email object recipients is added to
  * @param string $type The recipient type. Can be to, cc or bcc
  * @param string $email The email address, for example: john@example.com or "John Smith" <*****@*****.**>
  */
 protected function addRecipients(Email $obj, $type, $email)
 {
     if (!empty($email)) {
         if (is_string($email)) {
             $obj->addRecipient($this->recipient($type, $email));
         } elseif (is_array($email) || $email instanceof \Traversable) {
             foreach ($email as $e) {
                 $obj->addRecipient($this->recipient($type, $e));
             }
         }
     }
 }
 /**
  * Updates email references' threadId
  *
  * @param EntityManager $entityManager
  * @param Email $entity
  */
 protected function updateRefs(EntityManager $entityManager, Email $entity)
 {
     if ($entity->getThread()) {
         /** @var Email $email */
         foreach ($this->emailThreadProvider->getEmailReferences($this->em, $entity) as $email) {
             if (!$email->getThread()) {
                 $email->setThread($entity->getThread());
                 $entityManager->persist($email);
             }
         }
     }
 }
 /**
  * Check that email body is cached.
  * If do not, load it using appropriate email extension add it to a cache.
  *
  * @param Email $email
  */
 public function ensureEmailBodyCached(Email $email)
 {
     if ($email->getEmailBody() !== null) {
         // The email body is already cached
         return;
     }
     // body loader can load email from any folder
     $folder = $email->getFolders()->first();
     $origin = $folder->getOrigin();
     $emailBody = $this->selector->select($origin)->loadEmailBody($folder, $email, $this->em);
     $email->setEmailBody($emailBody);
     $this->em->persist($email);
     $this->em->flush();
 }
 /**
  * @param object $getOwnerResult
  * @param object $getUserResult
  * @param int    $getToCalls
  *
  * @dataProvider createReplyEmailModelProvider
  */
 public function testCreateReplyAllEmailModel($getOwnerResult, $getUserResult, $getToCalls)
 {
     $this->fromEmailAddress = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailAddress');
     $this->fromCcEmailAddress = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailAddress');
     $this->fromEmailAddress->expects($this->once())->method('getOwner')->willReturn($getOwnerResult);
     $this->helper->expects($this->any())->method('getUser')->willReturn($getUserResult);
     $getUserResult->expects($this->any())->method('getEmails')->willReturn([]);
     $this->email->expects($this->once())->method('getFromEmailAddress')->willReturn($this->fromEmailAddress);
     $this->email->expects($this->any())->method('getId');
     $emailAddress = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailAddress');
     $emailAddress->expects($this->exactly($getToCalls))->method('getEmail')->willReturn(null);
     $emailRecipient = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailRecipient');
     $emailRecipient->expects($this->exactly($getToCalls))->method('getEmailAddress')->willReturn($emailAddress);
     $to = new ArrayCollection();
     $to->add($emailRecipient);
     $this->email->expects($this->exactly($getToCalls))->method('getTo')->willReturn($to);
     $emailCcRecipient = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailRecipient');
     $emailCcRecipient->expects($this->once())->method('getEmailAddress')->willReturn($this->fromCcEmailAddress);
     $cc = new ArrayCollection();
     $cc->add($emailCcRecipient);
     $this->email->expects($this->exactly($getToCalls))->method('getCc')->willReturn($cc);
     $this->helper->expects($this->once())->method('prependWith');
     $this->helper->expects($this->once())->method('getEmailBody');
     $this->activityListProvider->expects($this->once())->method('getTargetEntities')->willReturn([]);
     $result = $this->emailModelBuilder->createReplyAllEmailModel($this->email);
     $this->assertInstanceOf('Oro\\Bundle\\EmailBundle\\Form\\Model\\Email', $result);
 }
 /**
  * @param Email       $email
  * @param object|null $owner
  */
 protected function addEmailRecipient(Email $email, $owner = null)
 {
     $emailAddr = new EmailAddress();
     $emailAddr->setOwner($owner);
     $recipient = new EmailRecipient();
     $recipient->setEmailAddress($emailAddr);
     $email->addRecipient($recipient);
 }
Exemple #20
0
 /**
  * @param boolean $atLeastOneGranted
  * @dataProvider voteProvider
  */
 public function testVote($atLeastOneGranted)
 {
     $token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface');
     $email = new Email();
     $emailUser1 = new EmailUser();
     $emailUser2 = new EmailUser();
     $emailUser3 = new EmailUser();
     $email->addEmailUser($emailUser1);
     $email->addEmailUser($emailUser2);
     $email->addEmailUser($emailUser3);
     $attributes = ['VIEW'];
     if ($atLeastOneGranted) {
         $this->securityFacade->expects($this->once())->method('isGranted')->with('VIEW', ${'emailUser' . mt_rand(1, 3)})->willReturn(true);
     }
     $result = $atLeastOneGranted ? EmailVoter::ACCESS_GRANTED : EmailVoter::ACCESS_DENIED;
     $this->assertEquals($result, $this->emailVoter->vote($token, $email, $attributes));
 }
 public function testCreateForwardEmailModel()
 {
     $this->helper->expects($this->once())->method('prependWith');
     $emailBody = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailBody');
     $emailBody->expects($this->exactly(1))->method('getAttachments')->willReturn([]);
     $this->email->expects($this->once())->method('getEmailBody')->willReturn($emailBody);
     $result = $this->emailModelBuilder->createForwardEmailModel($this->email);
     $this->assertInstanceOf('Oro\\Bundle\\EmailBundle\\Form\\Model\\Email', $result);
 }
 public function inapplicableEmailsProvider()
 {
     $date = new \DateTime('now', new \DateTimeZone('UTC'));
     $oldEmailDate = new \DateTime('now', new \DateTimeZone('UTC'));
     $oldEmailDate->sub(\DateInterval::createFromDateString('2 day'));
     $applicableSubjectsAndBodies = [['not empty subject', 'This is email body with offer, sale and won words.', $date], [null, 'This email has nothing.', $date], [null, 'This is email body with sale and won words.', $oldEmailDate]];
     $data = array_map(function ($subjectAndBody) {
         list($subject, $bodyContent, $sentAt) = $subjectAndBody;
         $body = new EmailBody();
         $body->setBodyContent($bodyContent);
         $email = new Email();
         $email->setSubject($subject);
         $email->setEmailBody($body);
         $email->setSentAt($sentAt);
         return [$email];
     }, $applicableSubjectsAndBodies);
     return $data;
 }
 public function getTestData()
 {
     $badEmail = new Email();
     $badEmailAddress = new EmailAddress();
     $badEmailOwner = new TestEmailOwner();
     $badEmailAddress->setOwner($badEmailOwner);
     $badRecipient = new EmailRecipient();
     $badRecipient->setEmailAddress($badEmailAddress);
     $badEmail->addRecipient($badRecipient);
     $email = new Email();
     $emailAddress = new EmailAddress();
     $organization = new TestOrganization(3);
     $emailOwner = new TestUser(null, null, null, $organization);
     $emailAddress->setOwner($emailOwner);
     $recipient = new EmailRecipient();
     $recipient->setEmailAddress($emailAddress);
     $email->addRecipient($recipient);
     return ['wrong class' => [new \stdClass(), ['integer' => ['organization' => null]]], 'email without correct user organization' => [$badEmail, ['integer' => ['organization' => 0]]], 'correct email' => [$email, ['integer' => ['organization' => [3]]]]];
 }
 public function testEnsureEmailBodyCached()
 {
     $email = new Email();
     $emailBody = new EmailBody();
     $emailUser = new EmailUser();
     $origin = new TestEmailOrigin();
     $folder = new EmailFolder();
     $folder->setOrigin($origin);
     $emailUser->setFolder($folder);
     $email->addEmailUser($emailUser);
     $loader = $this->getMock('Oro\\Bundle\\EmailBundle\\Provider\\EmailBodyLoaderInterface');
     $this->selector->expects($this->once())->method('select')->with($this->identicalTo($origin))->will($this->returnValue($loader));
     $loader->expects($this->once())->method('loadEmailBody')->with($this->identicalTo($folder), $this->identicalTo($email), $this->identicalTo($this->em))->will($this->returnValue($emailBody));
     $this->em->expects($this->once())->method('persist')->with($this->identicalTo($email));
     $this->em->expects($this->once())->method('flush');
     $this->logger->expects($this->never())->method('notice');
     $this->logger->expects($this->never())->method('warning');
     $this->manager->ensureEmailBodyCached($email);
     $this->assertSame($emailBody, $email->getEmailBody());
 }
 /**
  * {@inheritdoc}
  */
 public function loadEmailBody(Email $email, EntityManager $em)
 {
     /** @var ImapEmailOrigin $origin */
     $origin = $email->getFolder()->getOrigin();
     $config = new ImapConfig($origin->getHost(), $origin->getPort(), $origin->getSsl(), $origin->getUser(), $this->encryptor->decryptData($origin->getPassword()));
     $manager = new ImapEmailManager($this->connectorFactory->createImapConnector($config));
     $manager->selectFolder($email->getFolder()->getFullName());
     $repo = $em->getRepository('OroImapBundle:ImapEmail');
     $query = $repo->createQueryBuilder('e')->select('e.uid')->where('e.email = ?1')->setParameter(1, $email)->getQuery();
     /** @var ImapEmail $imapEmail */
     $imapEmail = $query->getSingleResult();
     $loadedEmail = $manager->findEmail($imapEmail['uid']);
     if ($loadedEmail === null) {
         throw new \RuntimeException(sprintf('Cannot find a body for "%s" email.', $email->getSubject()));
     }
     $builder = new EmailBodyBuilder();
     $builder->setEmailBody($loadedEmail->getBody()->getContent(), $loadedEmail->getBody()->getBodyIsText());
     foreach ($loadedEmail->getAttachments() as $attachment) {
         $builder->addEmailAttachment($attachment->getFileName(), $attachment->getContent(), $attachment->getContentType(), $attachment->getContentTransferEncoding());
     }
     return $builder->getEmailBody();
 }
 /**
  * @param Email $email
  * @param $data
  *
  * @return mixed
  */
 protected function setReplaedEmailId($email, $data)
 {
     if ($email->getThread()) {
         $emails = $email->getThread()->getEmails();
         // if there are just two email - add replayedEmailId to use on client side
         if (count($emails) === 2) {
             $data['replayedEmailId'] = $emails[0]->getId();
         }
     }
     return $data;
 }
 /**
  * @param Email $email
  */
 public function __construct(Email $email)
 {
     parent::__construct(sprintf('Cannot find a body for "%s" email.', $email->getSubject()));
 }
Exemple #28
0
 /**
  * Prepare emails to set status. If need get all from thread
  *
  * @param Email $entity
  * @param bool $checkThread Get threaded emails
  *
  * @return Email[]
  */
 protected function prepareFlaggedEmailEntities(Email $entity, $checkThread)
 {
     $thread = $entity->getThread();
     $emails = [$entity];
     if ($checkThread && $thread) {
         $emails = $thread->getEmails();
         return $emails->toArray();
     }
     return $emails;
 }
 /**
  * Gets array of EmailUser's by Email or EmailThread of this email depends on $checkThread flag
  * for current user and organization or which have mailbox owner.
  *
  * @param Email        $email
  * @param User         $user
  * @param Organization $organization
  * @param bool|false   $checkThread
  *
  * @return EmailUser[]
  */
 public function getAllEmailUsersByEmail(Email $email, User $user, Organization $organization, $checkThread = false)
 {
     $parameters = [];
     $queryBuilder = $this->createQueryBuilder('eu')->join('eu.email', 'e');
     if ($checkThread && ($thread = $email->getThread())) {
         $queryBuilder->andWhere('e.thread = :thread');
         $parameters['thread'] = $thread;
     } else {
         $queryBuilder->andWhere('eu.email = :email');
         $parameters['email'] = $email;
     }
     $orx = $queryBuilder->expr()->orX();
     $orx->add('eu.mailboxOwner IS NOT NULL')->add('eu.owner = :owner AND eu.organization = :organization');
     return $queryBuilder->andWhere($orx)->setParameters(array_merge($parameters, ['owner' => $user, 'organization' => $organization]))->getQuery()->getResult();
 }
 /**
  * Determines whether two emails are the same email message
  *
  * @param Email $email1
  * @param Email $email2
  * @return bool
  */
 protected function areEmailsEqual(Email $email1, Email $email2)
 {
     return $email1->getMessageId() === $email2->getMessageId();
 }