email.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\Plugin;
  4. use Grav\Common\Twig;
  5. use RocketTheme\Toolbox\Event\Event;
  6. class EmailPlugin extends Plugin
  7. {
  8. /**
  9. * @var Email
  10. */
  11. protected $email;
  12. /**
  13. * @return array
  14. */
  15. public static function getSubscribedEvents()
  16. {
  17. return [
  18. 'onPluginsInitialized' => ['onPluginsInitialized', 0],
  19. 'onFormProcessed' => ['onFormProcessed', 0]
  20. ];
  21. }
  22. /**
  23. * Initialize emailing.
  24. */
  25. public function onPluginsInitialized()
  26. {
  27. require_once __DIR__ . '/classes/email.php';
  28. require_once __DIR__ . '/vendor/autoload.php';
  29. $this->email = new Email();
  30. if ($this->email->enabled()) {
  31. $this->grav['Email'] = $this->email;
  32. }
  33. }
  34. /**
  35. * Send email when processing the form data.
  36. *
  37. * @param Event $event
  38. */
  39. public function onFormProcessed(Event $event)
  40. {
  41. $form = $event['form'];
  42. $action = $event['action'];
  43. $params = $event['params'];
  44. if (!$this->email->enabled()) {
  45. return;
  46. }
  47. switch ($action) {
  48. case 'email':
  49. /** @var Twig $twig */
  50. $twig = $this->grav['twig'];
  51. $vars = array(
  52. 'form' => $form
  53. );
  54. if (!empty($params['from'])) {
  55. $from = $twig->processString($params['from'], $vars);
  56. } else {
  57. $from = $this->config->get('plugins.email.from');
  58. }
  59. if (!empty($params['to'])) {
  60. $to = (array) $params['to'];
  61. foreach ($to as &$address) {
  62. $address = $twig->processString($address, $vars);
  63. }
  64. } else {
  65. $to = (array) $this->config->get('plugins.email.to');
  66. }
  67. $subject = !empty($params['subject']) ?
  68. $twig->processString($params['subject'], $vars) : $form->page()->title();
  69. $body = !empty($params['body']) ?
  70. $twig->processString($params['body'], $vars) : '{% include "forms/data.html.twig" %}';
  71. $message = $this->email->message($subject, $body)
  72. ->setFrom($from)
  73. ->setTo($to);
  74. $this->email->send($message);
  75. break;
  76. }
  77. }
  78. }