Esempio n. 1
0
 /**
  * (@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);
 }
 /**
  * {@inheritdoc}
  */
 public function select(EmailFolder $folder, OroEntityManager $em)
 {
     /** @var UserEmailOrigin $origin */
     $origin = $folder->getOrigin();
     $config = new ImapConfig($origin->getImapHost(), $origin->getImapPort(), $origin->getImapEncryption(), $origin->getUser(), $this->encryptor->decryptData($origin->getPassword()), $this->imapEmailGoogleOauth2Manager->getAccessTokenWithCheckingExpiration($origin));
     return new ImapEmailFlagManager($this->connectorFactory->createImapConnector($config), $em);
 }
 /**
  * {@inheritdoc}
  */
 public function select(EmailFolder $folder, OroEntityManager $em)
 {
     /** @var ImapEmailOrigin $origin */
     $origin = $folder->getOrigin();
     $config = new ImapConfig($origin->getHost(), $origin->getPort(), $origin->getSsl(), $origin->getUser(), $this->encryptor->decryptData($origin->getPassword()));
     return new ImapEmailFlagManager($this->connectorFactory->createImapConnector($config), $em);
 }
Esempio n. 4
0
 /**
  * @param EmailFolder $emailFolder
  *
  * @return $this
  */
 public function setEmailFolder($emailFolder)
 {
     $this->emailFolder = $emailFolder;
     if ($this->hasParentFolderModel()) {
         $this->emailFolder->setParentFolder($this->getParentFolderModel()->getEmailFolder());
     }
     return $this;
 }
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $outboxFolder = new EmailFolder();
     $outboxFolder->setType(EmailFolder::SENT)->setName(EmailFolder::SENT)->setFullName(EmailFolder::SENT);
     $origin = new InternalEmailOrigin();
     $origin->setName(InternalEmailOrigin::BAP)->addFolder($outboxFolder);
     $manager->persist($origin);
     $manager->flush();
 }
 public function testEmailGetterAndSetter()
 {
     $email = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\Email');
     $entity = new EmailFolder();
     $entity->addEmail($email);
     $emails = $entity->getEmails();
     $this->assertInstanceOf('Doctrine\\Common\\Collections\\ArrayCollection', $emails);
     $this->assertCount(1, $emails);
     $this->assertTrue($email === $emails[0]);
 }
Esempio n. 7
0
 public function testFolderGetterAndSetter()
 {
     $subFolder = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailFolder');
     $subFolder2 = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailFolder');
     $entity = new EmailFolder();
     $entity->addSubFolder($subFolder);
     $entity->addSubFolder($subFolder2);
     $subFolders = $entity->getSubFolders();
     $this->assertInstanceOf('Doctrine\\Common\\Collections\\ArrayCollection', $subFolders);
     $this->assertCount(2, $subFolders);
     $this->assertTrue($subFolder === $subFolders[0]);
     $this->assertTrue($subFolder2 === $subFolders[1]);
 }
Esempio n. 8
0
 /**
  * {@inheritdoc}
  */
 public function loadEmailBody(EmailFolder $folder, Email $email, EntityManager $em)
 {
     /** @var UserEmailOrigin $origin */
     $origin = $folder->getOrigin();
     $config = new ImapConfig($origin->getImapHost(), $origin->getImapPort(), $origin->getImapEncryption(), $origin->getUser(), $this->encryptor->decryptData($origin->getPassword()), $this->imapEmailGoogleOauth2Manager->getAccessTokenWithCheckingExpiration($origin));
     $manager = new ImapEmailManager($this->connectorFactory->createImapConnector($config));
     $manager->selectFolder($folder->getFullName());
     $repo = $em->getRepository('OroImapBundle:ImapEmail');
     $query = $repo->createQueryBuilder('e')->select('e.uid')->innerJoin('e.imapFolder', 'if')->where('e.email = ?1 AND if.folder = ?2')->setParameter(1, $email)->setParameter(2, $folder)->getQuery();
     $loadedEmail = $manager->findEmail($query->getSingleScalarResult());
     if (null === $loadedEmail) {
         throw new EmailBodyNotFoundException($email);
     }
     $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(), $attachment->getContentId());
     }
     return $builder->getEmailBody();
 }
Esempio n. 9
0
 public function testOutdatedAt()
 {
     $entity = new EmailFolder();
     $this->assertFalse($entity->isOutdated());
     $date = new \DateTime();
     $entity->setOutdatedAt($date);
     $this->assertEquals($date, $entity->getOutdatedAt());
     $this->assertTrue($entity->isOutdated());
     $entity->setOutdatedAt(null);
     $this->assertFalse($entity->isOutdated());
 }
Esempio n. 10
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     $userManager = $this->container->get('oro_user.manager');
     $organization = $manager->getRepository('OroOrganizationBundle:Organization')->getFirst();
     $role = $manager->getRepository('OroUserBundle:Role')->findOneBy(['role' => 'ROLE_ADMINISTRATOR']);
     $user = $userManager->createUser();
     $user->setUsername('simple_user')->setPlainPassword('simple_password')->setEmail('*****@*****.**')->setOrganization($organization)->addOrganization($organization)->setEnabled(true)->addRole($role);
     $folder = new EmailFolder();
     $folder->setName('sent');
     $folder->setFullName('sent');
     $folder->setType('sent');
     $origin = new InternalEmailOrigin();
     $origin->setName('simple_user_origin_name');
     $origin->setActive(true);
     $origin->addFolder($folder);
     $origin->setOwner($user);
     $origin->setOrganization($organization);
     $user->addEmailOrigin($origin);
     $userManager->updateUser($user);
     $user2 = $userManager->createUser();
     $user2->setUsername('simple_user2')->setPlainPassword('simple_password2')->setFirstName('Elley')->setLastName('Towards')->setEmail('*****@*****.**')->setOrganization($organization)->addOrganization($organization)->setEnabled(true);
     $folder2 = new EmailFolder();
     $folder2->setName('sent');
     $folder2->setFullName('sent');
     $folder2->setType('sent');
     $origin2 = new InternalEmailOrigin();
     $origin2->setName('simple_user_origin_name_2');
     $origin2->setActive(true);
     $origin2->addFolder($folder2);
     $origin2->setOwner($user2);
     $origin2->setOrganization($organization);
     $user2->addEmailOrigin($origin);
     $userManager->updateUser($user2);
     $this->setReference($user->getUsername(), $user);
     $this->setReference($user2->getUsername(), $user2);
 }
Esempio n. 11
0
 protected function getTestOrigin()
 {
     $outboxFolder = new EmailFolder();
     $outboxFolder->setType(FolderType::SENT)->setName(FolderType::SENT)->setFullName(FolderType::SENT);
     $origin = new InternalEmailOrigin();
     $origin->setName('BAP_User_1')->addFolder($outboxFolder)->setOwner($this->getTestUser())->setOrganization($this->getTestOrganization());
     return $origin;
 }
 /**
  * Cleans doctrine's UOF to prevent:
  *  - "eating" too much memory
  *  - storing too many object which cause slowness of sync process
  * Tracks time when last batch was saved.
  * Calculates time between batch saves.
  *
  * @param bool             $isFolderSyncComplete
  * @param null|EmailFolder $folder
  */
 protected function cleanUp($isFolderSyncComplete = false, $folder = null)
 {
     $this->emailEntityBuilder->getBatch()->clear();
     /**
      * Clear entity manager.
      */
     $map = $this->entitiesToClear();
     foreach ($map as $entityClass) {
         $this->em->clear($entityClass);
     }
     /**
      * In case folder sync completed and batch save time exceeded limit - throws exception.
      */
     if ($isFolderSyncComplete && $folder != null && $this->dbBatchSaveTime > 0 && $this->dbBatchSaveTime > self::DB_BATCH_TIME) {
         throw new SyncFolderTimeoutException($folder->getOrigin()->getId(), $folder->getFullName());
     } elseif ($isFolderSyncComplete) {
         /**
          * In case folder sync completed without batch save time exceed - reset dbBatchSaveTime.
          */
         $this->dbBatchSaveTime = -1;
     } else {
         /**
          * After batch save - calculate time difference between batches
          */
         if ($this->dbBatchSaveTimestamp !== 0) {
             $this->dbBatchSaveTime = time() - $this->dbBatchSaveTimestamp;
             $this->logger->info(sprintf('Batch save time: "%d" seconds.', $this->dbBatchSaveTime));
         }
     }
     $this->dbBatchSaveTimestamp = time();
 }
Esempio n. 13
0
 /**
  * Add folder
  *
  * @param  EmailFolder $folder
  *
  * @return EmailOrigin
  */
 public function addFolder(EmailFolder $folder)
 {
     $this->folders[] = $folder;
     $folder->setOrigin($this);
     return $this;
 }
 /**
  * Saves emails into the database
  *
  * @param Email[] $emails
  * @param EmailFolder $folder
  */
 protected function saveEmails(array $emails, EmailFolder $folder)
 {
     $this->emailEntityBuilder->removeEmails();
     $uids = array_map(function ($el) {
         /** @var Email $el */
         return $el->getId()->getUid();
     }, $emails);
     $repo = $this->em->getRepository('OroImapBundle:ImapEmail');
     $query = $repo->createQueryBuilder('e')->select('e.uid')->innerJoin('e.email', 'se')->innerJoin('se.folder', 'sf')->where('sf.id = :folderId AND e.uid IN (:uids)')->setParameter('folderId', $folder->getId())->setParameter('uids', $uids)->getQuery();
     $existingUids = array_map(function ($el) {
         return $el['uid'];
     }, $query->getResult());
     foreach ($emails as $src) {
         if (!in_array($src->getId()->getUid(), $existingUids)) {
             $this->log->notice(sprintf('Persisting "%s" email (UID: %d) ...', $src->getSubject(), $src->getId()->getUid()));
             $email = $this->emailEntityBuilder->email($src->getSubject(), $src->getFrom(), $src->getToRecipients(), $src->getSentAt(), $src->getReceivedAt(), $src->getInternalDate(), $src->getImportance(), $src->getCcRecipients(), $src->getBccRecipients());
             $email->setFolder($folder);
             $imapEmail = new ImapEmail();
             $imapEmail->setUid($src->getId()->getUid())->setEmail($email);
             $this->em->persist($imapEmail);
             $this->log->notice(sprintf('The "%s" email was persisted.', $src->getSubject()));
         } else {
             $this->log->notice(sprintf('Skip "%s" (UID: %d) email, because it is already synchronised.', $src->getSubject(), $src->getId()->getUid()));
         }
     }
     $this->emailEntityBuilder->getBatch()->persist($this->em);
     $this->em->flush();
 }
 /**
  * @expectedException \Oro\Bundle\EmailBundle\Exception\EmailBodyNotFoundException
  * @expectedExceptionMessage Cannot find a body for "test email" email.
  */
 public function testEnsureEmailBodyCachedNotFound()
 {
     $email = new Email();
     ReflectionUtil::setId($email, 123);
     $email->setSubject('test email');
     $emailBody = new EmailBody();
     $emailUser = new EmailUser();
     $origin = new TestEmailOrigin();
     $folder = new EmailFolder();
     $folder->setOrigin($origin);
     $emailUser->setFolder($folder);
     $email->addEmailUser($emailUser);
     $exception = new EmailBodyNotFoundException($email);
     $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')->will($this->throwException($exception));
     $this->em->expects($this->never())->method('persist');
     $this->em->expects($this->never())->method('flush');
     $this->logger->expects($this->once())->method('notice')->with('Load email body failed. Email id: 123. Error: Cannot find a body for "test email" email.', ['exception' => $exception]);
     $this->logger->expects($this->never())->method('warning');
     $this->manager->ensureEmailBodyCached($email);
     $this->assertSame($emailBody, $email->getEmailBody());
 }
 /**
  * Performs synchronization of folders
  *
  * @param EmailOrigin $origin
  *
  * @return ImapEmailFolder[] The list of folders for which emails need to be synchronized
  */
 protected function syncFolders(EmailOrigin $origin)
 {
     $folders = [];
     $existingImapFolders = $this->getExistingImapFolders($origin);
     $srcFolders = $this->getFolders();
     foreach ($srcFolders as $srcFolder) {
         $folderFullName = $srcFolder->getGlobalName();
         $uidValidity = $this->getUidValidity($srcFolder);
         // check if the current folder already exist and has no changes,
         // if so, remove it from the list of existing folders
         $imapFolder = null;
         foreach ($existingImapFolders as $key => $existingImapFolder) {
             if ($existingImapFolder->getUidValidity() === $uidValidity && $existingImapFolder->getFolder()->getFullName() === $folderFullName) {
                 $imapFolder = $existingImapFolder;
                 unset($existingImapFolders[$key]);
                 break;
             }
         }
         // check if new folder need to be created
         if (!$imapFolder) {
             $this->logger->notice(sprintf('Persisting "%s" folder ...', $folderFullName));
             $folder = new EmailFolder();
             $folder->setFullName($folderFullName)->setName($srcFolder->getLocalName())->setType($srcFolder->guessFolderType());
             $origin->addFolder($folder);
             $this->em->persist($folder);
             $imapFolder = new ImapEmailFolder();
             $imapFolder->setFolder($folder);
             $imapFolder->setUidValidity($uidValidity);
             $this->em->persist($imapFolder);
             $this->logger->notice(sprintf('The "%s" folder was persisted.', $folderFullName));
         }
         // save folder to the list of folders to be synchronized
         $folders[] = $imapFolder;
     }
     // mark the rest of existing folders as outdated
     foreach ($existingImapFolders as $imapFolder) {
         $this->logger->notice(sprintf('Mark "%s" folder as outdated.', $imapFolder->getFolder()->getFullName()));
         $imapFolder->getFolder()->setOutdatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
         $this->em->persist($imapFolder->getFolder());
     }
     $this->em->persist($origin);
     $this->em->flush();
     return $folders;
 }
 public function testSync()
 {
     $email = new Email();
     $email->setSubject('Test email');
     $emailBody = new EmailBody();
     $emailUser = new EmailUser();
     $origin = new TestEmailOrigin();
     $folder = new EmailFolder();
     $folder->setOrigin($origin);
     $emailUser->setOrigin($origin);
     $emailUser->addFolder($folder);
     $email->addEmailUser($emailUser);
     $repo = $this->getMockBuilder('Oro\\Bundle\\EmailBundle\\Entity\\Repository\\EmailRepository')->disableOriginalConstructor()->getMock();
     $this->doctrine->expects($this->once())->method('getRepository')->willReturn($repo);
     $runCount = 0;
     $repo->expects($this->exactly(2))->method('getEmailsWithoutBody')->willReturnCallback(function () use(&$runCount, $email) {
         $runCount++;
         return $runCount === 1 ? [$email] : [];
     });
     $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->em->expects($this->once())->method('clear');
     $this->logger->expects($this->exactly(2))->method('notice');
     $this->logger->expects($this->never())->method('warning');
     $this->synchronizer->sync();
     $this->assertSame($emailBody, $email->getEmailBody());
 }
 /**
  * @param EmailFolder $folder
  * @param Email $email
  * @param array $existingUids
  *
  * @return bool
  */
 protected function allowSaveEmail(EmailFolder $folder, Email $email, array $existingUids)
 {
     if ($folder->getSynchronizedAt() > $email->getSentAt()) {
         $this->logger->info(sprintf('Skip "%s" (UID: %d) email, because it was sent earlier than the last synchronization was done', $email->getSubject(), $email->getId()->getUid()));
         return false;
     }
     if (in_array($email->getId()->getUid(), $existingUids)) {
         $this->logger->info(sprintf('Skip "%s" (UID: %d) email, because it is already synchronised.', $email->getSubject(), $email->getId()->getUid()));
         return false;
     }
     return true;
 }
Esempio n. 19
0
 /**
  * @param EmailFolder $folder
  * @param array       $messages
  * @return EmailUser[]
  */
 public function getEmailUsersByFolderAndMessageIds(EmailFolder $folder, array $messages)
 {
     return $this->createQueryBuilder('eu')->leftJoin('eu.email', 'email')->andWhere('email.messageId IN (:messageIds)')->andWhere('eu.origin IN (:origin)')->setParameter('messageIds', $messages)->setParameter('origin', $folder->getOrigin())->getQuery()->getResult();
 }
Esempio n. 20
0
 /**
  * @param Folder $srcFolder
  *
  * @return EmailFolderModel
  */
 protected function createEmailFolderModel(Folder $srcFolder, $uidValidity)
 {
     $folder = new EmailFolder();
     $folder->setFullName($srcFolder->getGlobalName())->setName($srcFolder->getLocalName())->setType($srcFolder->guessFolderType())->setOrigin($this->origin);
     $emailFolderModel = new EmailFolderModel();
     $emailFolderModel->setUidValidity($uidValidity);
     $emailFolderModel->setEmailFolder($folder);
     return $emailFolderModel;
 }
Esempio n. 21
0
 public function __construct($id = null)
 {
     parent::__construct();
     $this->id = $id;
 }
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testPersist()
 {
     $origin = $this->getMockBuilder('Oro\\Bundle\\EmailBundle\\Entity\\EmailOrigin')->getMock();
     $origin->expects($this->any())->method('getId')->will($this->returnValue(1));
     $folder = new EmailFolder();
     $folder->setName('Exist');
     $folder->setFullName('Exist');
     $folder->setOrigin($origin);
     $this->batch->addFolder($folder);
     $newFolder = new EmailFolder();
     $newFolder->setName('New');
     $newFolder->setFullName('New');
     $newFolder->setOrigin($origin);
     $this->batch->addFolder($newFolder);
     $dbFolder = new EmailFolder();
     $dbFolder->setName('DbExist');
     $dbFolder->setFullName('DbExist');
     $dbFolder->setOrigin($origin);
     $addr = $this->addrManager->newEmailAddress()->setEmail('Exist');
     $this->batch->addAddress($addr);
     $newAddr = $this->addrManager->newEmailAddress()->setEmail('New');
     $this->batch->addAddress($newAddr);
     $dbAddr = $this->addrManager->newEmailAddress()->setEmail('DbExist');
     $email1 = new Email();
     $email1->setXMessageId('email1');
     $email1->setMessageId('email1');
     $email1->setFromEmailAddress($addr);
     $emailUser1 = new EmailUser();
     $emailUser1->addFolder($folder);
     $emailUser1->setOrigin($origin);
     $email1->addEmailUser($emailUser1);
     $this->addEmailRecipient($email1, $addr);
     $this->addEmailRecipient($email1, $newAddr);
     $this->batch->addEmailUser($emailUser1);
     $email2 = new Email();
     $email2->setXMessageId('email2');
     $email2->setMessageId('email2');
     $email2->setFromEmailAddress($newAddr);
     $emailUser2 = new EmailUser();
     $emailUser2->addFolder($newFolder);
     $emailUser2->setOrigin($origin);
     $email2->addEmailUser($emailUser2);
     $this->addEmailRecipient($email2, $addr);
     $this->addEmailRecipient($email2, $newAddr);
     $this->batch->addEmailUser($emailUser2);
     $email3 = new Email();
     $email3->setXMessageId('email3');
     $email3->setMessageId('some_email');
     $email3->setFromEmailAddress($newAddr);
     $emailUser3 = new EmailUser();
     $emailUser3->addFolder($folder);
     $email3->addEmailUser($emailUser3);
     $this->addEmailRecipient($email3, $addr);
     $this->addEmailRecipient($email3, $newAddr);
     $this->batch->addEmailUser($emailUser3);
     $email4 = new Email();
     $email4->setXMessageId('email4');
     $email4->setMessageId('some_email');
     $email4->setFromEmailAddress($newAddr);
     $emailUser4 = new EmailUser();
     $emailUser4->addFolder($folder);
     $email4->addEmailUser($emailUser4);
     $this->addEmailRecipient($email4, $addr);
     $this->addEmailRecipient($email4, $newAddr);
     $this->batch->addEmailUser($emailUser4);
     $existingEmail = new Email();
     $existingEmail->setXMessageId('existing_email');
     $existingEmail->setMessageId('some_email');
     $existingEmail->setFromEmailAddress($newAddr);
     $emailUser5 = new EmailUser();
     $emailUser5->addFolder($dbFolder);
     $existingEmail->addEmailUser($emailUser5);
     $this->addEmailRecipient($existingEmail, $addr);
     $this->addEmailRecipient($existingEmail, $newAddr);
     $em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     $folderRepo = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $addrRepo = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $emailRepo = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $em->expects($this->exactly(3))->method('getRepository')->will($this->returnValueMap(array(array('OroEmailBundle:EmailFolder', $folderRepo), array('Oro\\Bundle\\EmailBundle\\Tests\\Unit\\Entity\\TestFixtures\\TestEmailAddressProxy', $addrRepo), array('OroEmailBundle:Email', $emailRepo))));
     $folderRepo->expects($this->exactly(2))->method('findOneBy')->will($this->returnCallback(function ($c) use(&$dbFolder) {
         return $c['fullName'] === 'Exist' ? $dbFolder : null;
     }));
     $addrRepo->expects($this->exactly(2))->method('findOneBy')->will($this->returnCallback(function ($c) use(&$dbAddr) {
         return $c['email'] === 'Exist' ? $dbAddr : null;
     }));
     $emailRepo->expects($this->once())->method('findBy')->with(array('messageId' => array('email1', 'email2', 'some_email')))->will($this->returnValue([$existingEmail]));
     $owner = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailOwnerInterface');
     $this->ownerProvider->expects($this->any())->method('findEmailOwner')->will($this->returnValue($owner));
     $this->batch->persist($em);
     $this->assertCount(1, $email1->getEmailUsers());
     $this->assertCount(1, $email2->getEmailUsers());
     $this->assertTrue($origin === $emailUser1->getOrigin());
     $this->assertTrue($origin === $emailUser2->getOrigin());
     $this->assertSame($newFolder, $emailUser2->getFolders()->first());
     $this->assertSame($dbFolder, $emailUser1->getFolders()->first());
     $this->assertTrue($dbAddr === $email1->getFromEmailAddress());
     $this->assertNull($email1->getFromEmailAddress()->getOwner());
     $this->assertTrue($newAddr === $email2->getFromEmailAddress());
     $this->assertTrue($owner === $email2->getFromEmailAddress()->getOwner());
     $email1Recipients = $email1->getRecipients();
     $this->assertTrue($dbAddr === $email1Recipients[0]->getEmailAddress());
     $this->assertNull($email1Recipients[0]->getEmailAddress()->getOwner());
     $this->assertTrue($newAddr === $email1Recipients[1]->getEmailAddress());
     $this->assertTrue($owner === $email1Recipients[1]->getEmailAddress()->getOwner());
     $email2Recipients = $email2->getRecipients();
     $this->assertTrue($dbAddr === $email2Recipients[0]->getEmailAddress());
     $this->assertNull($email2Recipients[0]->getEmailAddress()->getOwner());
     $this->assertTrue($newAddr === $email2Recipients[1]->getEmailAddress());
     $this->assertTrue($owner === $email2Recipients[1]->getEmailAddress()->getOwner());
     $changes = $this->batch->getChanges();
     $this->assertCount(3, $changes);
     $this->assertSame($folder, $changes[0]['old']);
     $this->assertSame($dbFolder, $changes[0]['new']);
     $this->assertSame($email3, $changes[1]['old']);
     $this->assertSame($existingEmail, $changes[1]['new']);
     $this->assertSame($email4, $changes[2]['old']);
     $this->assertSame($existingEmail, $changes[2]['new']);
 }
 /**
  * Create EmailFolder entity object
  *
  * @param string $type The folder type. Can be inbox, sent, trash, drafts or other
  * @param string $fullName The full name of a folder
  * @param string $name The folder name
  * @return EmailFolder
  */
 protected function folder($type, $fullName, $name)
 {
     $result = $this->batch->getFolder($type, $fullName);
     if ($result === null) {
         $result = new EmailFolder();
         $result->setType($type)->setFullName($fullName)->setName($name);
         $this->batch->addFolder($result);
     }
     return $result;
 }
 /**
  * @dataProvider supportedMethods
  */
 public function testProcessValidData($method)
 {
     $this->request->setMethod($method);
     $this->model->setFrom('*****@*****.**')->setTo(array('*****@*****.**'))->setSubject('testSubject')->setBody('testBody');
     $this->form->expects($this->once())->method('setData')->with($this->model);
     $this->form->expects($this->once())->method('submit')->with($this->request);
     $this->form->expects($this->once())->method('isValid')->will($this->returnValue(true));
     $message = new \Swift_Message();
     $this->mailer->expects($this->once())->method('createMessage')->will($this->returnValue($message));
     $this->mailer->expects($this->once())->method('send')->will($this->returnValue(1));
     $origin = new InternalEmailOrigin();
     $folder = new EmailFolder();
     $folder->setType(EmailFolder::SENT);
     $origin->addFolder($folder);
     $emailOriginRepo = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $emailOriginRepo->expects($this->once())->method('findOneBy')->with(array('name' => InternalEmailOrigin::BAP))->will($this->returnValue($origin));
     $this->em->expects($this->once())->method('getRepository')->with('OroEmailBundle:InternalEmailOrigin')->will($this->returnValue($emailOriginRepo));
     $this->emailEntityBuilder->expects($this->once())->method('setOrigin')->with($this->identicalTo($origin));
     $email = new EmailEntity();
     $this->emailEntityBuilder->expects($this->once())->method('email')->with('testSubject', '*****@*****.**', array('*****@*****.**'))->will($this->returnValue($email));
     $body = new EmailBody();
     $this->emailEntityBuilder->expects($this->once())->method('body')->with('testBody', false, true)->will($this->returnValue($body));
     $batch = $this->getMock('Oro\\Bundle\\EmailBundle\\Builder\\EmailEntityBatchInterface');
     $this->emailEntityBuilder->expects($this->once())->method('getBatch')->will($this->returnValue($batch));
     $batch->expects($this->once())->method('persist')->with($this->identicalTo($this->em));
     $this->em->expects($this->once())->method('flush');
     $this->assertTrue($this->handler->process($this->model));
     $this->assertNotNull($message);
     $this->assertEquals(array('*****@*****.**' => null), $message->getFrom());
     $this->assertEquals(array('*****@*****.**' => null), $message->getTo());
     $this->assertEquals('testSubject', $message->getSubject());
     $this->assertEquals('testBody', $message->getBody());
     $this->assertTrue($folder === $email->getFolder());
     $this->assertTrue($body === $email->getEmailBody());
 }
 /**
  * @param string   $folderName
  * @param string   $folderFullName
  * @param int      $uidValidity
  * @param int|null $id
  *
  * @return ImapEmailFolder
  */
 protected function createImapFolder($folderName, $folderFullName, $uidValidity, $id = null)
 {
     $folder = new EmailFolder();
     $folder->setName($folderName)->setFullName($folderFullName);
     $imapFolder = new ImapEmailFolder();
     $imapFolder->setFolder($folder)->setUidValidity($uidValidity);
     if ($id !== null) {
         ReflectionUtil::setId($imapFolder, $id);
     }
     return $imapFolder;
 }
 /**
  * Register EmailFolder object
  *
  * @param EmailFolder $obj
  * @throws \LogicException
  */
 public function addFolder(EmailFolder $obj)
 {
     $key = strtolower(sprintf('%s_%s', $obj->getType(), $obj->getFullName()));
     if (isset($this->folders[$key])) {
         throw new \LogicException(sprintf('The folder "%s" (type: %s) already exists in the batch.', $obj->getFullName(), $obj->getType()));
     }
     $this->folders[$key] = $obj;
 }
 /**
  * Get email ids and create iterator
  *
  * @param EmailOrigin $origin
  * @param ImapEmailFolder $imapFolder
  * @param EmailFolder $folder
  *
  * @return ImapEmailIterator
  */
 protected function getEmailIterator(EmailOrigin $origin, ImapEmailFolder $imapFolder, EmailFolder $folder)
 {
     if ($origin->getMailbox()) {
         // build search query for emails sync
         $sqb = $this->manager->getSearchQueryBuilder();
         if ($origin->getSynchronizedAt() && $folder->getSynchronizedAt()) {
             if ($folder->getType() === FolderType::SENT) {
                 $sqb->sent($folder->getSynchronizedAt());
             } else {
                 $sqb->received($folder->getSynchronizedAt());
             }
         }
         $searchQuery = $sqb->get();
         $this->logger->info(sprintf('Loading emails from "%s" folder ...', $folder->getFullName()));
         $this->logger->info(sprintf('Query: "%s".', $searchQuery->convertToSearchString()));
         $emails = $this->manager->getEmails($searchQuery);
     } else {
         $lastUid = $this->em->getRepository('OroImapBundle:ImapEmail')->findLastUidByFolder($imapFolder);
         $this->logger->info(sprintf('Previous max email UID "%s"', $lastUid));
         $emails = $this->manager->getEmailsUidBased(sprintf('%s:*', ++$lastUid));
     }
     return $emails;
 }
Esempio n. 28
0
 /**
  * @param User                  $emailOwner
  * @param OrganizationInterface $organization
  *
  * @return InternalEmailOrigin
  */
 protected function createUserInternalOrigin(User $emailOwner, OrganizationInterface $organization = null)
 {
     $organization = $organization ? $organization : $emailOwner->getOrganization();
     $originName = InternalEmailOrigin::BAP . '_User_' . $emailOwner->getId();
     $outboxFolder = new EmailFolder();
     $outboxFolder->setType(FolderType::SENT)->setName(FolderType::SENT)->setFullName(FolderType::SENT);
     $origin = new InternalEmailOrigin();
     $origin->setName($originName)->addFolder($outboxFolder)->setOwner($emailOwner)->setOrganization($organization);
     $emailOwner->addEmailOrigin($origin);
     $this->getEntityManager()->persist($origin);
     $this->getEntityManager()->persist($emailOwner);
     return $origin;
 }
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testPersist()
 {
     $origin = $this->getMockBuilder('Oro\\Bundle\\EmailBundle\\Entity\\EmailOrigin')->getMock();
     $origin->expects($this->any())->method('getId')->will($this->returnValue(1));
     $this->batch->addOrigin($origin);
     $folder = new EmailFolder();
     $folder->setName('Exist');
     $folder->setFullName('Exist');
     $folder->setOrigin($origin);
     $this->batch->addFolder($folder);
     $newFolder = new EmailFolder();
     $newFolder->setName('New');
     $newFolder->setFullName('New');
     $newFolder->setOrigin($origin);
     $this->batch->addFolder($newFolder);
     $dbFolder = new EmailFolder();
     $dbFolder->setName('DbExist');
     $dbFolder->setFullName('DbExist');
     $dbFolder->setOrigin($origin);
     $addr = $this->addrManager->newEmailAddress()->setEmail('Exist');
     $this->batch->addAddress($addr);
     $newAddr = $this->addrManager->newEmailAddress()->setEmail('New');
     $this->batch->addAddress($newAddr);
     $dbAddr = $this->addrManager->newEmailAddress()->setEmail('DbExist');
     $email1 = new Email();
     $email1->setFolder($folder);
     $email1->setFromEmailAddress($addr);
     $email1Recip1 = new EmailRecipient();
     $email1Recip1->setEmailAddress($addr);
     $email1Recip2 = new EmailRecipient();
     $email1Recip2->setEmailAddress($newAddr);
     $email1->addRecipient($email1Recip1);
     $email1->addRecipient($email1Recip2);
     $this->batch->addEmail($email1);
     $email2 = new Email();
     $email2->setFolder($newFolder);
     $email2->setFromEmailAddress($newAddr);
     $email2Recip1 = new EmailRecipient();
     $email2Recip1->setEmailAddress($addr);
     $email2Recip2 = new EmailRecipient();
     $email2Recip2->setEmailAddress($newAddr);
     $email2->addRecipient($email2Recip1);
     $email2->addRecipient($email2Recip2);
     $this->batch->addEmail($email2);
     $em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     $folderRepo = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $addrRepo = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $em->expects($this->exactly(2))->method('getRepository')->will($this->returnValueMap(array(array('OroEmailBundle:EmailFolder', $folderRepo), array('Oro\\Bundle\\EmailBundle\\Tests\\Unit\\Entity\\TestFixtures\\TestEmailAddressProxy', $addrRepo))));
     $folderRepo->expects($this->exactly(2))->method('findOneBy')->will($this->returnCallback(function ($c) use(&$dbFolder) {
         return $c['fullName'] === 'Exist' ? $dbFolder : null;
     }));
     $addrRepo->expects($this->exactly(2))->method('findOneBy')->will($this->returnCallback(function ($c) use(&$dbAddr) {
         return $c['email'] === 'Exist' ? $dbAddr : null;
     }));
     $em->expects($this->exactly(4))->method('persist')->with($this->logicalOr($this->identicalTo($newFolder), $this->identicalTo($newAddr), $this->identicalTo($email1), $this->identicalTo($email2)));
     $owner = $this->getMock('Oro\\Bundle\\EmailBundle\\Entity\\EmailOwnerInterface');
     $this->ownerProvider->expects($this->any())->method('findEmailOwner')->will($this->returnValue($owner));
     $this->batch->persist($em);
     $this->assertTrue($origin === $email1->getFolder()->getOrigin());
     $this->assertTrue($origin === $email2->getFolder()->getOrigin());
     $this->assertTrue($dbFolder === $email1->getFolder());
     $this->assertTrue($newFolder === $email2->getFolder());
     $this->assertTrue($dbAddr === $email1->getFromEmailAddress());
     $this->assertNull($email1->getFromEmailAddress()->getOwner());
     $this->assertTrue($newAddr === $email2->getFromEmailAddress());
     $this->assertTrue($owner === $email2->getFromEmailAddress()->getOwner());
     $email1Recipients = $email1->getRecipients();
     $this->assertTrue($dbAddr === $email1Recipients[0]->getEmailAddress());
     $this->assertNull($email1Recipients[0]->getEmailAddress()->getOwner());
     $this->assertTrue($newAddr === $email1Recipients[1]->getEmailAddress());
     $this->assertTrue($owner === $email1Recipients[1]->getEmailAddress()->getOwner());
     $email2Recipients = $email2->getRecipients();
     $this->assertTrue($dbAddr === $email2Recipients[0]->getEmailAddress());
     $this->assertNull($email2Recipients[0]->getEmailAddress()->getOwner());
     $this->assertTrue($newAddr === $email2Recipients[1]->getEmailAddress());
     $this->assertTrue($owner === $email2Recipients[1]->getEmailAddress()->getOwner());
 }