src/Biceps/CoreBundle/Model/EmailsManager.php line 662

Open in your IDE?
  1. <?php
  2. /**
  3.  * @copyright Copyright (c) 2016 biceps.ch
  4.  */
  5. namespace Biceps\CoreBundle\Model;
  6. use Biceps\CoreBundle\Entity\ContactPerson;
  7. use Biceps\CoreBundle\Entity\Email;
  8. use Biceps\CoreBundle\Entity\EmailRepository;
  9. use Biceps\CoreBundle\Entity\Invoice;
  10. use Biceps\CoreBundle\Entity\Licence;
  11. use Biceps\CoreBundle\Entity\ProfileRepository;
  12. use Biceps\CoreBundle\Entity\Registration;
  13. use Biceps\CoreBundle\Entity\SpamPrevent;
  14. use Biceps\CoreBundle\Entity\SpamPreventRepository;
  15. use Biceps\CoreBundle\Entity\Voucher;
  16. use Biceps\PaymentBundle\Entity\CamtFile;
  17. use Doctrine\ORM\EntityManager;
  18. use Doctrine\ORM\OptimisticLockException;
  19. use Doctrine\ORM\ORMException;
  20. use FOS\UserBundle\Util\TokenGenerator;
  21. use Swift_Attachment;
  22. use Swift_Mailer;
  23. use Swift_Message;
  24. use Swift_Mime_Attachment;
  25. use Swift_Transport_SpoolTransport;
  26. use Symfony\Bundle\FrameworkBundle\Routing\Router;
  27. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  28. use Symfony\Component\DependencyInjection\ContainerInterface;
  29. use Symfony\Component\Filesystem\Exception\IOException;
  30. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  31. use Symfony\Component\Templating\EngineInterface;
  32. use Biceps\CoreBundle\Entity\Profile;
  33. use Biceps\CoreBundle\Entity\User;
  34. use whatwedo\PostFinanceEPayment\Response\Response;
  35. class EmailsManager implements ContainerAwareInterface
  36. {
  37.     /** @var \Symfony\Bundle\FrameworkBundle\Templating\EngineInterface */
  38.     private $templating;
  39.     /** @var Swift_Mailer */
  40.     private $mailer;
  41.     /** @var ContainerInterface */
  42.     protected $container;
  43.     /** @var SpamPreventRepository */
  44.     protected $spamPreventRepository;
  45.     /** @var Router */
  46.     protected $router;
  47.     /** @var EntityManager */
  48.     protected $em;
  49.     /**
  50.      * @param Swift_Mailer $mailer
  51.      * @param EngineInterface $templating
  52.      */
  53.     public function __construct(Swift_Mailer $mailerEngineInterface $templating)
  54.     {
  55.         $this->templating $templating;
  56.         $this->mailer $mailer;
  57.     }
  58.     /**
  59.      * Send a message to $email to inform him/her of a $password change.
  60.      * @param string $email
  61.      * @param string $password
  62.      */
  63.     public function sendChangePasswordEmail($email$password)
  64.     {
  65.         $this->sendTemplateEmail(
  66.             $email,
  67.             $this->container->getParameter('biceps_core.emails.password_changed.subject'),
  68.             'BicepsCoreBundle:Emails:password_changed',
  69.             array('email' => $email'password' => $password)
  70.         );
  71.     }
  72.     /**
  73.      * Send a message to $email to inform him/her that a new account has been created.
  74.      * @param string $email
  75.      * @param string $password
  76.      */
  77.     public function sendCreateAccountEmail($email$password)
  78.     {
  79.         $this->sendTemplateEmail(
  80.             $email,
  81.             $this->container->getParameter('biceps_core.emails.new_account.subject'),
  82.             'BicepsCoreBundle:Emails:email_created',
  83.             array('email' => $email'password' => $password)
  84.         );
  85.     }
  86.     /**
  87.      * Send a message to $email to inform him/her that a new account has been created.
  88.      * @param string $email
  89.      * @param string $password
  90.      */
  91.     public function sendAddAccountEmail($email$password)
  92.     {
  93.         $this->sendTemplateEmail(
  94.             $email,
  95.             $this->container->getParameter('biceps_core.emails.new_account.subject'),
  96.             'BicepsCoreBundle:Emails:email_added',
  97.             array('email' => $email'password' => $password)
  98.         );
  99.     }
  100.     /**
  101.      * Send a message to $email to validate his email address using the given $token.
  102.      * @param string $email
  103.      * @param string $url
  104.      * @param string $removeUrl
  105.      * @param bool $isGift
  106.      */
  107.     public function sendAddressValidationEmail(string $emailstring $urlstring $removeUrl$isGift false)
  108.     {
  109.         $this->sendTemplateEmail(
  110.             $email,
  111.             $this->container->getParameter('biceps_core.emails.validate_email.subject'),
  112.             'BicepsCoreBundle:Emails:validate_email',
  113.             [
  114.                 'email' => $email,
  115.                 'url' => $url,
  116.                 'removeUrl' => $removeUrl,
  117.                 'isGift' => $isGift,
  118.             ]
  119.         );
  120.     }
  121.     /**
  122.      * Send a message to all the emails of $user to inform that a registration occurred with an email belonging to
  123.      * one of his profiles. The emails are not sent if the last notification was sent too recently.
  124.      *
  125.      * @param User $user
  126.      * @param Profile $profile
  127.      *
  128.      * @throws ORMException
  129.      * @throws OptimisticLockException
  130.      */
  131.     public function sendProfileRegistrationAttemptEmail(User $userProfile $profile)
  132.     {
  133.         foreach ($user->getEmails() as $email) {
  134.             if (!$this->spamPreventRepository->check('registration-attempt'$email->getAddress())) {
  135.                 // It's not long enough since we sent the same notification email, skip this address
  136.                 continue;
  137.             }
  138.             $this->sendTemplateEmail(
  139.                 $email->getAddress(),
  140.                 $this->container->getParameter('biceps_core.emails.profile-registration-attempt.subject'),
  141.                 'BicepsCoreBundle:Emails:profile-registration-attempt',
  142.                 array('email' => $profile->getEmail())
  143.             );
  144.         }
  145.     }
  146.     /**
  147.      * @param Email $email
  148.      * @param string $password
  149.      *
  150.      * @return bool
  151.      */
  152.     public function sendMigrationAccountInformation(Email $emailstring $password)
  153.     {
  154. //        $spamKey = sprintf('%s:%s', $email->getAddress(), $password);
  155. //        if (!$this->spamPreventRepository->check('migration-information', $spamKey)) {
  156. //            // It's not long enough since we sent the same notification email, skip this address
  157. //            return true;
  158. //        }
  159.         return $this->sendTemplateEmail(
  160.             $email->getAddress(),
  161.             $this->container->getParameter('biceps_core.emails.account-migration.subject'),
  162.             'BicepsCoreBundle:Emails:account_migration',
  163.             [
  164.                 'user' => $email->getUser(),
  165.                 'password' => $password,
  166.             ]
  167.         );
  168.     }
  169.     /**
  170.      * Send an email to all the emails of $user to inform that one of his licences has been activated.
  171.      *
  172.      * @param User $user
  173.      * @param Licence $licence
  174.      * @param bool $licenceRestarted
  175.      *
  176.      * @throws ORMException
  177.      * @throws OptimisticLockException
  178.      */
  179.     public function sendInformUserOfLicenceActivation(User $userLicence $licence$licenceRestarted false)
  180.     {
  181.         $email $user->getMainEmail();
  182.         if (!$this->spamPreventRepository->check('licence-activation-' $licence->getId(), $email->getAddress())) {
  183.             // It's not long enough since we sent the same notification email, skip this address
  184.             return;
  185.         }
  186.         if($licenceRestarted){
  187.             $this->sendTemplateEmail(
  188.                 $email->getAddress(),
  189.                 $this->container->getParameter('biceps_core.emails.licence-reactivation.subject'),
  190.                 'BicepsCoreBundle:Emails:licence-reactivation',
  191.                 array('licence' => $licence)
  192.             );
  193.         }else {
  194.             if($licence->isPending()){
  195.                 $subject $this->container->getParameter('biceps_core.emails.licence-renewing.subject');
  196.             }else{
  197.                 $subject $this->container->getParameter('biceps_core.emails.licence-activation.subject');
  198.             }
  199.             $this->sendTemplateEmail(
  200.                 $email->getAddress(),
  201.                 $subject,
  202.                 'BicepsCoreBundle:Emails:licence-activation',
  203.                 array('licence' => $licence)
  204.             );
  205.         }
  206.     }
  207.     /**
  208.      * Send an email to all the emails of $user to inform that one of his licences has been deactivated.
  209.      *
  210.      * @param User $user
  211.      * @param Licence $licence
  212.      *
  213.      * @throws ORMException
  214.      * @throws OptimisticLockException
  215.      */
  216.     public function sendInformUserOfLicenceDeactivation(User $userLicence $licence)
  217.     {
  218.         $email $user->getMainEmail();
  219.         if (!$this->spamPreventRepository->check('licence-deactivation-' $licence->getId(), $email->getAddress())) {
  220.             // It's not long enough since we sent the same notification email, skip this address
  221.             return;
  222.         }
  223.         $this->sendTemplateEmail(
  224.             $email->getAddress(),
  225.             $this->container->getParameter('biceps_core.emails.licence-deactivation.subject'),
  226.             'BicepsCoreBundle:Emails:licence-deactivation',
  227.             array('licence' => $licence)
  228.         );
  229.     }
  230.     /**
  231.      * Send an $invoice PDF as an email attachment.
  232.      *
  233.      * @param Invoice $invoice
  234.      *
  235.      * @return bool
  236.      *
  237.      * @throws ORMException
  238.      * @throws OptimisticLockException
  239.      */
  240.     public function sendInvoicePdf(Invoice $invoice)
  241.     {
  242.         if ($invoice->getOrder()->getUser()) {
  243.             $buyer $invoice->getOrder()->getUser();
  244.             $email $buyer->getMainEmail()->getAddress();
  245.         } else {
  246.             $buyer $invoice->getOrder()->getRegistration();
  247.             $email $buyer->getEmail();
  248.         }
  249.         $filename sprintf('%s-%s-%s'str_pad($invoice->getId(), 6'0'STR_PAD_LEFT), date('YmdHis'), 'invoice.pdf');
  250.         $path $this->container->getParameter('kernel.cache_dir') . '/' $filename;
  251.         /** @var InvoiceManager $invoiceManager */
  252.         $invoiceManager $this->container->get('biceps_core.invoice_manager');
  253.         $pdf $invoiceManager->printInvoice($invoicetrue);
  254.         if (!$pdf->saveAs($path)) {
  255.             throw new IOException(sprintf('Unable to save file "%s"'$pdf->getError()), 1545825136);
  256.         }
  257.         $sent $this->sendTemplateEmail(
  258.             $email,
  259.             $this->container->getParameter('biceps_core.emails.invoice-pdf.subject'),
  260.             'BicepsCoreBundle:Emails:invoice_pdf',
  261.             array('invoice' => $invoice'buyer' => $buyer),
  262.             Swift_Attachment::fromPath($path'application/pdf')
  263.         );
  264.         // Actually send the email *before* removing the attachment
  265.         $this->flushTransport();
  266.         if (file_exists($path)) {
  267.             unlink($path);
  268.         }
  269.         return $sent;
  270.     }
  271.     /**
  272.      * Send a voucher PDF as an email attachment.
  273.      * @param User|Registration|string $buyer
  274.      * @param Voucher $voucher
  275.      */
  276.     public function sendVoucherPdf($buyerVoucher $voucher)
  277.     {
  278.         $filename sprintf('%s-%s-%s'str_pad($voucher->getId(), 6'0'STR_PAD_LEFT), date('YmdHis'), 'bon-biceps.pdf');
  279.         $path $this->container->getParameter('kernel.cache_dir') . '/' $filename;
  280.         $this
  281.             ->container
  282.             ->get('biceps_core.pdf_helper')
  283.             ->generateVoucherPdf($voucher)
  284.             ->saveAs($path);
  285.         $this->sendTemplateEmail(
  286.             is_string($buyer) ? $buyer : ($buyer instanceof User $buyer->getMainEmail()->getAddress() : $buyer->getEmail()),
  287.             $this->container->getParameter('biceps_core.emails.voucher-pdf.subject'),
  288.             'BicepsCoreBundle:Emails:voucher_pdf',
  289.             ['voucher' => $voucher],
  290.             Swift_Attachment::fromPath($path'application/pdf')
  291.         );
  292.         // Actually send the email *before* removing the attachment
  293.         $this->flushTransport();
  294.         if (file_exists($path)) {
  295.             unlink($path);
  296.         }
  297.     }
  298.     /**
  299.      * Send a list of unsent invoices.
  300.      * @param array $invoices
  301.      */
  302.     public function sendUnsentInvoicesAlert(array $invoices)
  303.     {
  304.         if (!$this->spamPreventRepository->check('unsent-invoices-alert'""1)) {
  305.             // Prevent email to be sent too many time
  306.             return false;
  307.         }
  308.         return $this->sendTemplateEmail(
  309.             $this->container->getParameter('notification_admin_email'),
  310.             $this->container->getParameter('biceps_core.emails.unsent-invoices.subject'),
  311.             'BicepsCoreBundle:Emails:unsent-invoices',
  312.             array('invoices' => $invoices)
  313.         );
  314.     }
  315.     /**
  316.      * Send a notification to admin
  317.      * @param int $reference
  318.      * @param string $message
  319.      * @param array $data
  320.      *
  321.      * @return bool
  322.      */
  323.     public function sendOrderNotFoundNotification(int $referencestring $message, array $data) : bool
  324.     {
  325.         if (!$this->spamPreventRepository->check('order-not-found'$reference100)) {
  326.             // Prevent email to be sent too many time
  327.             return false;
  328.         }
  329.         return $this->sendTemplateEmail(
  330.             $this->container->getParameter('notification_admin_email'),
  331.             $this->container->getParameter('biceps_core.emails.order-not-found.subject'),
  332.             'BicepsCoreBundle:Emails:order-not-found',
  333.             [
  334.                 'message' => $message,
  335.                 'data' => $data
  336.             ]
  337.         );
  338.     }
  339.     /**
  340.      * Send a registration reminder to the given $registration if none was sent yet.
  341.      * Return true if the email was sent and false otherwise.
  342.      *
  343.      * @param Registration $registration
  344.      * @param int $spamDelay
  345.      *
  346.      * @return bool
  347.      *
  348.      * @throws ORMException
  349.      * @throws OptimisticLockException
  350.      */
  351.     public function sendRegistrationReminder(Registration $registration$spamDelay 1)
  352.     {
  353.         if (!$this->spamPreventRepository->check('registration-reminder'$registration->getId(), $spamDelay)) {
  354.             // A reminder has already been sent to this registration
  355.             return false;
  356.         }
  357.         /** @var TokenGenerator $tokenGenerator */
  358.         $tokenGenerator $this->container->get('fos_user.util.token_generator');
  359.         $registration->setRemoveToken($registration->getRemoveToken() ?: $tokenGenerator->generateToken());
  360.         $registration->setReminderCount($registration->getReminderCount() + 1);
  361.         if ($registration->getIsValidated()) {
  362.             $url $this->router->generate(
  363.                 'biceps_front_register_select_payment_method',
  364.                 ['registration' => $registration->getId()],
  365.                 UrlGeneratorInterface::ABSOLUTE_URL
  366.             );
  367.         } else {
  368.             $registration->setValidationToken($registration->getValidationToken() ?: $tokenGenerator->generateToken());
  369.             $url $this->router->generate(
  370.                 'biceps_front_register_validate_email',
  371.                 [
  372.                     'token' => $registration->getValidationToken(),
  373.                 ],
  374.                 UrlGeneratorInterface::ABSOLUTE_URL
  375.             );
  376.         }
  377.         $this->em->persist($registration);
  378.         $this->em->flush();
  379.         $removeUrl $this->router->generate(
  380.             'biceps_front_register_remove_registration',
  381.             [
  382.                 'token' => $registration->getRemoveToken(),
  383.             ],
  384.             UrlGeneratorInterface::ABSOLUTE_URL
  385.         );
  386.         $contactUrl $this->router->generate(
  387.             'biceps_front_contact_me',
  388.             ['reason' => 'account'],
  389.             UrlGeneratorInterface::ABSOLUTE_URL
  390.         );
  391.         $this->sendTemplateEmail(
  392.             $registration->getEmail(),
  393.             $this->container->getParameter('biceps_core.emails.registration_reminder.subject'),
  394.             'BicepsCoreBundle:Emails:registration_reminder',
  395.             array(
  396.                 'registration' => $registration,
  397.                 'url' => $url,
  398.                 'removeUrl' => $removeUrl,
  399.                 'contactUrl' => $contactUrl,
  400.             )
  401.         );
  402.         return true;
  403.     }
  404.     /**
  405.      * Send a renewal reminder to $email for the given $licence.
  406.      * Return true if the email was sent and false otherwise.
  407.      *
  408.      * @param Licence $licence
  409.      * @param Email $email
  410.      *
  411.      * @return bool
  412.      *
  413.      * @throws ORMException
  414.      * @throws OptimisticLockException
  415.      */
  416.     public function sendLicenceRenewalReminder(Licence $licenceEmail $email)
  417.     {
  418.         if (!$this->spamPreventRepository->check('licence-renewal-' $licence->getId(), $email->getAddress(), 2)) {
  419.             // A reminder has already been sent for this licence
  420.             return false;
  421.         }
  422.         $this->sendTemplateEmail(
  423.             $email->getAddress(),
  424.             $this->container->getParameter('biceps_core.emails.renewal_reminder.subject'),
  425.             'BicepsCoreBundle:Emails:renewal_reminder',
  426.             array(
  427.                 'licence' => $licence,
  428.                 'user' => $email->getUser(),
  429.                 'renewLink' => $this->router->generate(
  430.                     'biceps_front_create_order',
  431.                     array('id' => $licence->getId()),
  432.                     UrlGeneratorInterface::ABSOLUTE_URL
  433.                 ),
  434.             )
  435.         );
  436.         return true;
  437.     }
  438.     /**
  439.      * Send a expiration reminder to $email for the given $licence.
  440.      * Return true if the email was sent and false otherwise.
  441.      *
  442.      * @param Licence $licence
  443.      * @param Email $email
  444.      *
  445.      * @return bool
  446.      *
  447.      * @throws ORMException
  448.      * @throws OptimisticLockException
  449.      */
  450.     public function sendLicenceExpiredReminder(Licence $licenceEmail $email)
  451.     {
  452.         if (!$this->spamPreventRepository->check('licence-expired-' $licence->getId(), $email->getAddress(), 100)) {
  453.             // A reminder has already been sent for this licence
  454.             return false;
  455.         }
  456.         $this->sendTemplateEmail(
  457.             $email->getAddress(),
  458.             $this->container->getParameter('biceps_core.emails.expiration_reminder.subject'),
  459.             'BicepsCoreBundle:Emails:expiration_reminder',
  460.             array(
  461.                 'licence' => $licence,
  462.                 'user' => $email->getUser(),
  463.                 'renewLink' => $this->router->generate(
  464.                     'biceps_front_create_order',
  465.                     array('id' => $licence->getId()),
  466.                     UrlGeneratorInterface::ABSOLUTE_URL
  467.                 ),
  468.             )
  469.         );
  470.         return true;
  471.     }
  472.     /**
  473.      * Send an email to the admin to inform there are errors or warnings in the given CAMT $file.
  474.      *
  475.      * @param CamtFile $file
  476.      * @param array $errors
  477.      */
  478.     public function sendCamtErrorsNotifications(CamtFile $file, array $errors = [])
  479.     {
  480.         $email $this->container->getParameter('notification_admin_email');
  481.         $this->sendTemplateEmail(
  482.             $email,
  483.             $this->container->getParameter('biceps_core.emails.camt_warnings.subject'),
  484.             'BicepsCoreBundle:Emails:camt_warnings',
  485.             [
  486.                 'file' => $file,
  487.                 'errors' => $errors,
  488.             ]
  489.         );
  490.     }
  491.     /**
  492.      * Send a reminder for the given unpaid $invoice.
  493.      * The email template and subject are different depending on whether this is a new customer (registration) or
  494.      * an existing customer (user).
  495.      *
  496.      * @param Invoice $invoice
  497.      *
  498.      * @throws ORMException
  499.      * @throws OptimisticLockException
  500.      */
  501.     public function sendInvoiceFirstReminder(Invoice $invoice)
  502.     {
  503.         $order $invoice->getOrder();
  504.         $address null;
  505.         $subject null;
  506.         $template null;
  507.         $address $order->getEmail();
  508.         if ($address) {
  509.             $user $order->getUser();
  510.             if ($user && !$user->isNew()) {
  511.                 $subject $this->container->getParameter('biceps_core.emails.first_reminder_for_users.subject');
  512.                 $template 'invoice_first_reminder_for_users';
  513.             } else {
  514.                 $subject $this->container->getParameter('biceps_core.emails.first_reminder_for_registrations.subject');
  515.                 $template 'invoice_first_reminder_for_registrations';
  516.             }
  517.             $template 'BicepsCoreBundle:Emails:' $template;
  518.             $filename sprintf('%s-%s-%s'str_pad($invoice->getId(), 6'0'STR_PAD_LEFT), date('YmdHis'), 'invoice.pdf');
  519.             $path $this->container->getParameter('kernel.cache_dir') . '/' $filename;
  520.             /** @var InvoiceManager $invoiceManager */
  521.             $invoiceManager $this->container->get('biceps_core.invoice_manager');
  522.             $pdf $invoiceManager->printInvoice($invoicetrue);
  523.             $pdf->saveAs($path);
  524.             $this->sendTemplateEmail(
  525.                 $address,
  526.                 $subject,
  527.                 $template,
  528.                 array('order' => $order'invoice' => $invoice),
  529.                 Swift_Attachment::fromPath($path'application/pdf')
  530.             );
  531.             // Actually send the email *before* removing the attachment
  532.             $this->flushTransport();
  533.             if (file_exists($path)) {
  534.                 unlink($path);
  535.             }
  536.         }
  537.     }
  538.     /**
  539.      * Send an email to the user/registration with an unpaid invoice to inform the licence has been deactivated or the
  540.      * registration has been removed.
  541.      *
  542.      * @param Invoice $invoice
  543.      *
  544.      * @throws ORMException
  545.      * @throws OptimisticLockException
  546.      */
  547.     public function sendInvoiceSecondReminder(Invoice $invoice)
  548.     {
  549.         $order $invoice->getOrder();
  550.         $address null;
  551.         $subject null;
  552.         $template null;
  553.         $address $order->getEmail();
  554.         if ($address) {
  555.             $user $order->getUser();
  556.             if ($user && !$user->isNew()) {
  557.                 if ($order->getIsGift()) {
  558.                     $subject $this->container->getParameter('biceps_core.emails.second_reminder_for_users_for_gift.subject');
  559.                 } else {
  560.                     $subject $this->container->getParameter('biceps_core.emails.second_reminder_for_users.subject');
  561.                 }
  562.                 $template 'invoice_second_reminder_for_users';
  563.             } else {
  564.                 $subject $this->container->getParameter('biceps_core.emails.second_reminder_for_registrations.subject');
  565.                 $template 'invoice_second_reminder_for_registrations';
  566.             }
  567.             $template 'BicepsCoreBundle:Emails:' $template;
  568.             $filename sprintf('%s-%s-%s'str_pad($invoice->getId(), 6'0'STR_PAD_LEFT), date('YmdHis'), 'invoice.pdf');
  569.             $path $this->container->getParameter('kernel.cache_dir') . '/' $filename;
  570.             /** @var InvoiceManager $invoiceManager */
  571.             $invoiceManager $this->container->get('biceps_core.invoice_manager');
  572.             $pdf $invoiceManager->printInvoice($invoicetrue);
  573.             $pdf->saveAs($path);
  574.             $this->sendTemplateEmail(
  575.                 $address,
  576.                 $subject,
  577.                 $template,
  578.                 array('order' => $order'invoice' => $invoice),
  579.                 Swift_Attachment::fromPath($path'application/pdf')
  580.             );
  581.             // Actually send the email *before* removing the attachment
  582.             $this->flushTransport();
  583.             if (file_exists($path)) {
  584.                 unlink($path);
  585.             }
  586.         }
  587.     }
  588.     /** {@inheritdoc} */
  589.     public function setContainer(ContainerInterface $container null)
  590.     {
  591.         /** @var EntityManager $entityManager */
  592.         $this->em $container->get('doctrine.orm.entity_manager');
  593.         $this->container $container;
  594.         $this->spamPreventRepository $this->em->getRepository(SpamPrevent::class);
  595.         $this->router $container->get('router');
  596.     }
  597.     /**
  598.      * Send an email based on a twig template.
  599.      * Will use $template.html.twig for the HTML version and $template.txt.twig for the text version.
  600.      * @param string $recipient
  601.      * @param string $subject
  602.      * @param string $template
  603.      * @param array $params
  604.      * @param Swift_Mime_Attachment $attachment
  605.      * @param callable $beforeSend
  606.      *
  607.      * @return bool
  608.      */
  609.     protected function sendTemplateEmail(
  610.         $recipient,
  611.         $subject,
  612.         $template,
  613.         array $params = array(),
  614.         Swift_Mime_Attachment $attachment null,
  615.         $beforeSend null
  616.     )
  617.     {
  618.         $bodyHtml $this->templating->render(sprintf('%s.html.twig'$template), $params);
  619.         $bodyTxt $this->templating->render(sprintf('%s.txt.twig'$template), $params);
  620.         return $this->sendEmail($recipient$subject$bodyHtml$bodyTxt$attachment$beforeSend);
  621.     }
  622.     /**
  623.      * Send an email.
  624.      * @param string $recipient
  625.      * @param string $subject
  626.      * @param string $bodyHtml
  627.      * @param string $bodyTxt
  628.      * @param Swift_Mime_Attachment $attachment
  629.      * @param callable $beforeSend
  630.      *
  631.      * @return bool
  632.      */
  633.     protected function sendEmail(
  634.         $recipient,
  635.         $subject,
  636.         $bodyHtml,
  637.         $bodyTxt,
  638.         Swift_Mime_Attachment $attachment null,
  639.         $beforeSend null
  640.     )
  641.     {
  642.         /** @var Swift_Message $message */
  643.         $message = (new Swift_Message())
  644.             ->setSubject($subject)
  645.             ->setFrom($this->container->getParameter('mails_sender'))
  646.             ->setTo($recipient)
  647.             ->setBody($bodyHtml'text/html')
  648.             ->addPart($bodyTxt'text/plain');
  649.         $replyTo $this->container->getParameter('mails_reply_to');
  650.         if ($replyTo){
  651.             $message->setReplyTo($replyTo);
  652.         }
  653.         if ($attachment) {
  654.             $message->attach($attachment);
  655.         }
  656.         if ($beforeSend && is_callable($beforeSend)) {
  657.             call_user_func($beforeSend$message);
  658.         }
  659.         return $this->mailer->send($message) === 1;
  660.     }
  661.     /**
  662.      * Flush the transport so the messages are sent immediately.
  663.      * See http://stackoverflow.com/a/15643422
  664.      */
  665.     protected function flushTransport()
  666.     {
  667.         /** @var Swift_Transport_SpoolTransport $transport */
  668.         $transport $this->container->get('mailer')->getTransport();
  669.         /** @var Swift_Transport_SpoolTransport $transportReal */
  670.         $transportReal $this->container->get('swiftmailer.transport.real');
  671.         $spool $transport->getSpool();
  672.         $spool->flushQueue($transportReal);
  673.     }
  674.     /**
  675.      * @param ContactPerson $person
  676.      *
  677.      * @return bool
  678.      */
  679.     public function sendContactAdministratorEmail(ContactPerson $person)
  680.     {
  681.         /** @var EmailRepository $emailRepository */
  682.         $emailRepository $this->em->getRepository(Email::class);
  683.         $emailOrProfile $emailRepository->findOneByAddress($person->getEmail());
  684.         if (!$emailOrProfile) {
  685.             /** @var ProfileRepository $profileRepository */
  686.             $profileRepository $this->em->getRepository(Profile::class);
  687.             $emailOrProfile $profileRepository->findOneByEmail($person->getEmail());
  688.         }
  689.         return $this->sendTemplateEmail(
  690.             $this->container->getParameter('contact_admin_email'),
  691.             $this->container->getParameter('biceps_core.emails.contact-me.subject'),
  692.             'BicepsCoreBundle:Emails:contact_me',
  693.             [
  694.                 'data' => $person,
  695.                 'user' => $emailOrProfile $emailOrProfile->getUser() : null,
  696.             ],
  697.             null,
  698.             function (Swift_Message $message) use ($person) {
  699.                 $message->addReplyTo($person->getEmail(), $person->getFullName());
  700.             }
  701.         );
  702.     }
  703. }