src/OceanExpertBundle/Controller/MailsController.php line 285

Open in your IDE?
  1. <?php
  2. namespace OceanExpertBundle\Controller;
  3. use DateTime;
  4. use Doctrine\ORM\AbstractQuery;
  5. use Doctrine\ORM\Query;
  6. use Exception;
  7. use OceanExpertBundle\Entity\MailQueueFiles;
  8. use OceanExpertBundle\Entity\Mails;
  9. use OceanExpertBundle\Entity\Messages;
  10. use Psr\Log\LoggerInterface;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. class MailsController extends AbstractController
  16. {
  17.     public function indexAction()
  18.     {
  19.         return $this->render('Mails/index.html.twig', array());
  20.     }
  21.     public function uploadEmailAttachmentsAction(Request $request): Response
  22.     {
  23.         if (null !== $request->files) {
  24.             foreach ($request->files as $uploadedFile) {
  25.                 $fileName time() . '_' $uploadedFile->getClientOriginalName();
  26.                 $directory "uploads/emails/attachments/";
  27.                 $uploadedFile->move($directory$fileName);
  28.             }
  29.         }
  30.         return new Response($fileName);
  31.     }
  32.     public function removeEmailAttachmentAction(Request $request): Response
  33.     {
  34.         $fileName $request->query->get('filename');
  35.         if ($fileName) {
  36.             $file "uploads/emails/attachments/" $fileName;
  37.             if (file_exists($file)) {
  38.                 unlink($file);
  39.             }
  40.         }
  41.         return new Response($fileName);
  42.     }
  43.     /**
  44.      * make a file that contains the queue for the mails
  45.      *
  46.      * @param Request $request
  47.      *
  48.      * @return JsonResponse
  49.      *
  50.      * @throws Exception
  51.      */
  52.     public function emailQueueAction(Request $request): JsonResponse
  53.     {
  54.         //check if the event is already active
  55.         $em $this->getDoctrine()->getManager();
  56.         //if this is an email for an event, check the event is active
  57.         if ($request->request->get('eventid')) {
  58.             $event $em->getRepository('OceanExpertBundle:Events')
  59.                 ->findOneBy(
  60.                     array(
  61.                         'idEvent' => $request->request->get('eventid'),
  62.                         'status' => 1
  63.                     )
  64.                 );
  65.             if (!$event) {
  66.                 return new JsonResponse(
  67.                     array(
  68.                         'status' => 4,
  69.                         'error' => 'event not found or not active yet',
  70.                         'returnMessage' => 'no return message'
  71.                     )
  72.                 );
  73.             }
  74.         }
  75.         //what is our environment?
  76.         $env $this->container->get('kernel')->getEnvironment();
  77.         //for testing purposes
  78.         //$data['status'] = 3;
  79.         //$data['error'] = 'arno error';
  80.         //$data['returnMessage'] = 'arno return message';
  81.         //return new JsonResponse($data);
  82.         $data $request->request->all();
  83.         if (isset($data['subject'])
  84.             && trim($data['subject']) != ''
  85.             && trim($data['message'])
  86.         ) {
  87.             $returnMessage '';
  88.             $em $this->getDoctrine()->getManager();
  89.             $dirName '/tmp/emailqueue';
  90.             if ($env !== 'prod') {
  91.                 $dirName .= "_$env";
  92.             }
  93.             $fileName uniqid() . '.json';
  94.             $fullFileName $dirName '/' $fileName;
  95.             $returnMessage .= "dirname: $dirName, filename: $fileName, fullfilename: $fullFileName;";
  96.             clearstatcache();
  97.             if (!file_exists($dirName .'/')) {
  98.                 $returnMessage .= $dirName ' does not exist, trying to make it;';
  99.                 $dirMade mkdir(
  100.                     $dirName '/',
  101.                     0777,
  102.                     true
  103.                 );
  104.                 $returnMessage .= "dir made?: $dirMade;";
  105.             }
  106.             if ($fp fopen($fullFileName'w')) {
  107.                 $returnMessage .= "$fullFileName opened;";
  108.                 if (fwrite($fpjson_encode($data))) {
  109.                     fclose($fp);
  110.                     $returnMessage .= "$fullFileName closed;";
  111.                     $mailQueue = new MailQueueFiles();
  112.                     $mailQueue->setIdInd($data['userid']);
  113.                     $mailQueue->setFileName($fileName);
  114.                     $mailQueue->setCreatedAt(new DateTime("now"));
  115.                     $mailQueue->setProcessedAt(null);
  116.                     $mailQueue->setProcessed(0);
  117.                     $mailQueue->setApproved(1);
  118.                     $em->persist($mailQueue);
  119.                     $em->flush();
  120.                     $data['status'] = 0;
  121.                     $data['returnMessage'] = '0 means no errors; ' $returnMessage;
  122.                 } else {
  123.                     //not good
  124.                     $data['status'] = 1;
  125.                     $data['error'] = 'unable to write file, no mail will be sent';
  126.                     $data['returnMessage'] = 'for reference: ' $returnMessage;
  127.                 }
  128.             } else {
  129.                 //not good
  130.                 $data['status'] = 2;
  131.                 $data['error'] = 'unable to open file, no mail will be sent';
  132.                 $data['returnMessage'] = 'for reference: ' $returnMessage;
  133.             }
  134.         } else {
  135.             //not good
  136.             $data['status'] = 3;
  137.             $data['error'] = 'missing either subject or message to send';
  138.             $data['returnMessage'] = 'for reference: no return message';
  139.         }
  140.         return new JsonResponse($data);
  141.     }
  142.     /*
  143.     public function getUnsubscribeLink($idUser)
  144.     {
  145.         $request = $this->get('request_stack')->getCurrentRequest();
  146.         $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
  147.         $baseurl .= $this->generateUrl(
  148.             'email_unsubscribe',
  149.             array(
  150.                 'token' => $this->encrypt_decrypt(
  151.                     'encrypt',
  152.                     $idUser
  153.                 )
  154.             )
  155.         );
  156.         return $baseurl;
  157.     }
  158.     */
  159.     /**
  160.      * @param $action - encrypt | decrypt
  161.      * @param $string - String code
  162.      *
  163.      * @return bool|string - encrypted or decrypted string.
  164.      */
  165.     public static function encrypt_decrypt($action$string)
  166.     {
  167.         $output false;
  168.         $encrypt_method "AES-256-CBC";
  169.         $secret_key 'aAqyTksTjbW6BN8fnbLaY6qHYNFNQMnR';
  170.         $secret_iv 'KDAGPYqwgJGwpySZShr4b2pmTQTC2BLf';
  171.         // hash
  172.         $key hash('sha256'$secret_key);
  173.         $iv substr(
  174.             hash(
  175.                 'sha256',
  176.                 $secret_iv),
  177.             0,
  178.             16
  179.         );
  180.         if ($action == 'encrypt') {
  181.             $output openssl_encrypt
  182.             ($string,
  183.                 $encrypt_method,
  184.                 $key,
  185.                 0$iv);
  186.             $output base64_encode($output);
  187.         } elseif ($action == 'decrypt') {
  188.             $output openssl_decrypt(
  189.                 base64_decode($string),
  190.                 $encrypt_method,
  191.                 $key,
  192.                 0,
  193.                 $iv
  194.             );
  195.         }
  196.         return $output;
  197.     }
  198.     /**
  199.      * @param $token
  200.      *
  201.      * @return Response
  202.      *
  203.      * @throws Exception
  204.      */
  205.     public function unsubscribeAction($token): Response
  206.     {
  207.         $idUser $this->encrypt_decrypt('decrypt'$token);
  208.         $data = array();
  209.         if ($idUser != '') {
  210.             $em $this->getDoctrine()->getManager();
  211.             $user $em->getRepository('OceanExpertBundle:Indiv')->findOneBy(array('idInd' => $idUser));
  212.             if ($user) {
  213.                 $email $user->getEmail2() != '' $user->getEmail2() : $user->getEmail1();
  214.                 $data = array(
  215.                     'fname' => $user->getFname(),
  216.                     'sname' => $user->getSname(),
  217.                     'email' => $email,
  218.                     'subscribed' => $user->getDoNotInvite()
  219.                 );
  220.                 $request $this->container->get('request_stack')->getCurrentRequest();
  221.                 if ($request->isMethod('POST')) {
  222.                     $status $request->request->get('status'0);
  223.                     $user->setDoNotInvite($status);
  224.                     $user->setDoNoInviteOn(new DateTime());
  225.                     $user->setDoNoInviteBy($user->getIdInd());
  226.                     $em->persist($user);
  227.                     $em->flush();
  228.                     if ($user->getDoNotInvite() == 1) {
  229.                         $data['success'] = 'Thank you. you have been successfully unsubscribed.';
  230.                     } else {
  231.                         $data['success'] = 'Thank you. You are subscribed to OceanExpert emails.';
  232.                     }
  233.                 }
  234.             } else {
  235.                 $data['error'] = 'Invalid token or token id does not exists. Please check the unsubscribe link.';
  236.             }
  237.         } else {
  238.             $data['error'] = 'Invalid token or token id does not exists. Please check the unsubscribe link.';
  239.         }
  240.         return $this->render('Mails/unsubscribe.html.twig'$data);
  241.     }
  242.     /**
  243.      * this will be called by Mandrill when a mail triggers
  244.      *      send
  245.      *      deferral
  246.      *      hard_bounce
  247.      *      soft_bounce
  248.      *      open
  249.      *      click
  250.      *      spam
  251.      *      unsub
  252.      *      reject
  253.      *      denylist
  254.      *      allowlist
  255.      * for some dark reason this was handled by the IODE site ....
  256.      *
  257.      * @todo : check if we still need this, we already have an active check for mandrill in CheckMandrillForWebhooks
  258.      *
  259.      * @param LoggerInterface $logger
  260.      * @param Request         $request
  261.      *
  262.      * @return void
  263.      */
  264.     public function mandrillWebhookAction(LoggerInterface $loggerRequest $request) {
  265.         define('DEBUG'2);
  266.         $logMessage date('d/m/Y H:i:s') . ' start';
  267.         $logger->info('MANDRILLWEBHOOK: ' $logMessage);
  268.         $data $request->request->get('mandrill_events');
  269.         $logMessage "post data from Mandrill : $data";
  270.         $logger->info('MANDRILLWEBHOOK: ' $logMessage);
  271.         $data json_decode($datatrue);
  272.         //$logMessage = 'json data from Mandrill : ' . var_dump($data);
  273.         $logMessage 'json data from Mandrill';
  274.         $logger->info('MANDRILLWEBHOOK: ' $logMessage);
  275.         $em $this->getDoctrine()->getManager();
  276.         foreach ($data as $event) {
  277.             /*
  278.             //for the time being it's very hard to understand the relation between what mandrill sends and OE db
  279.             if (isset($event->msg)
  280.                 && isset($event->msg->metadata)
  281.                 && isset($event->msg->metadata->id)
  282.             ) {
  283.                 $id = $event->msg->metadata->id;
  284.                 $mail = $em->getRepository('OceanExpertBundle:Mails')
  285.                     ->findOneBy(
  286.                         array(
  287.                             'id' => $id
  288.                         )
  289.                     );
  290.                 if ($mail) {
  291.                     switch ($event->event) {
  292.                         case 'send':
  293.                             if (DEBUG > 1) {
  294.                                 $logMessage = "deleted id $id from table mails";
  295.                                 $logger->info('MANDRILLWEBHOOK: ' . $logMessage);
  296.                             }
  297.                             $em->remove($mail);
  298.                             $em->flush();
  299.                             break;
  300.                         case 'hard_bounce':
  301.                             if (DEBUG > 1) {
  302.                                 $logMessage = "set id $id as bounced in table mails";
  303.                                 $logger->info('MANDRILLWEBHOOK: ' . $logMessage);
  304.                             }
  305.                             $mail->setMandrillStatus('hard_bounce');
  306.                             $em->persist($mail);
  307.                             $em->flush();
  308.                             break;
  309.                         case 'soft_bounce':
  310.                             //$stmt = $pdo->prepare("UPDATE mails set try_sent = try_sent + 1, sent_time = now(), mandril_status = 'soft_bounce', sent_mandril = null WHERE id = :id");
  311.                             $mail->setMandrilStatus('soft_bounce');
  312.                             $mail->setSentMandril(null);
  313.                             $mail->setTrySent($mail->getTrySent() + 1);
  314.                             if (DEBUG > 1) {
  315.                                 $logMessage = "update id $id in table mails";
  316.                                 $logger->info('MANDRILLWEBHOOK: ' . $logMessage);
  317.                             }
  318.                             $em->persist($mail);
  319.                             $em->flush();
  320.                             break;
  321.                         default:
  322.                             if (DEBUG > 1) {
  323.                                 $logMessage = 'nothing to do for event ' . $event->event;
  324.                                 $logger->info('MANDRILLWEBHOOK: ' . $logMessage);
  325.                             }
  326.                     }
  327.                     dump($logMessage);
  328.                 } else {
  329.                     dump('NOT found mail with id "' . $id . '"');
  330.                     $record = array(
  331.                         'recipient' => 'recipient not found',
  332.                         'sender' => 'sender not found'
  333.                     );
  334.                 }
  335.             } else {
  336.                 $id = 'unknown id';
  337.                 $record = array(
  338.                     'recipient' => 'unknown recipient',
  339.                     'sender' => 'unknown sender'
  340.                 );
  341.             }
  342.             if (DEBUG > 1) {
  343.                 if (is_object($event)) {
  344.                     $event = $event->event;
  345.                 } else {
  346.                     $event = 'unknown event';
  347.                 }
  348.                 $logMessage = "info we need: $id;" . $event . ';' . $record['recipient'] . ';' . $record['sender'];
  349.                 $logger->info('MANDRILLWEBHOOK: ' . $logMessage);
  350.                 dump($logMessage);
  351.             }
  352.             */
  353.             $logger->info('MANDRILLWEBHOOK: ' json_encode($event));
  354.         }
  355.         $logMessage date('d/m/Y H:i:s') . ' end';
  356.         $logger->info('MANDRILLWEBHOOK: ' $logMessage);
  357.         return new Response('1');
  358.     }
  359. }