EmailAction.php 6.24 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\action\Plugin\Action\EmailAction.
 */

namespace Drupal\action\Plugin\Action;

10
use Drupal\Core\Access\AccessResult;
11
use Drupal\Core\Action\ConfigurableActionBase;
12
use Drupal\Core\Entity\EntityManagerInterface;
13
use Drupal\Core\Form\FormStateInterface;
14
use Drupal\Core\Mail\MailManagerInterface;
15
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
16
use Drupal\Core\Session\AccountInterface;
17
use Drupal\Core\Utility\Token;
18
use Psr\Log\LoggerInterface;
19 20 21
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
22
 * Sends an email message.
23 24 25
 *
 * @Action(
 *   id = "action_send_email_action",
26
 *   label = @Translation("Send email"),
27 28 29
 *   type = "system"
 * )
 */
30
class EmailAction extends ConfigurableActionBase implements ContainerFactoryPluginInterface {
31 32 33 34 35 36 37 38 39

  /**
   * The token service.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

  /**
40
   * The user storage.
41
   *
42
   * @var \Drupal\Core\Entity\EntityStorageInterface
43
   */
44
  protected $storage;
45

46 47 48 49 50 51 52
  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

53 54 55 56 57 58 59
  /**
   * The mail manager
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected $mailManager;

60 61 62 63 64 65 66
  /**
   * Constructs a EmailAction object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
67
   * @param mixed $plugin_definition
68 69 70
   *   The plugin implementation definition.
   * @param \Drupal\Core\Utility\Token $token
   *   The token service.
71
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
72
   *   The entity manager.
73 74
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
75 76
   * @param \Drupal\Core\Mail\MailManagerInterface
   *   The mail manager.
77
   */
78
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Token $token, EntityManagerInterface $entity_manager, LoggerInterface $logger, MailManagerInterface $mail_manager) {
79 80 81
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->token = $token;
82
    $this->storage = $entity_manager->getStorage('user');
83
    $this->logger = $logger;
84
    $this->mailManager = $mail_manager;
85 86 87 88 89
  }

  /**
   * {@inheritdoc}
   */
90
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
91 92
    return new static($configuration, $plugin_id, $plugin_definition,
      $container->get('token'),
93
      $container->get('entity.manager'),
94 95
      $container->get('logger.factory')->get('action'),
      $container->get('plugin.manager.mail')
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    );
  }

  /**
   * {@inheritdoc}
   */
  public function execute($entity = NULL) {
    if (empty($this->configuration['node'])) {
      $this->configuration['node'] = $entity;
    }

    $recipient = $this->token->replace($this->configuration['recipient'], $this->configuration);

    // If the recipient is a registered user with a language preference, use
    // the recipient's preferred language. Otherwise, use the system default
    // language.
112
    $recipient_accounts = $this->storage->loadByProperties(array('mail' => $recipient));
113 114
    $recipient_account = reset($recipient_accounts);
    if ($recipient_account) {
115
      $langcode = $recipient_account->getPreferredLangcode();
116 117
    }
    else {
118
      $langcode = language_default()->getId();
119 120 121
    }
    $params = array('context' => $this->configuration);

122
    if ($this->mailManager->mail('system', 'action_send_email', $recipient, $langcode, $params)) {
123
      $this->logger->notice('Sent email to %recipient', array('%recipient' => $recipient));
124 125
    }
    else {
126
      $this->logger->error('Unable to send email to %recipient', array('%recipient' => $recipient));
127 128 129 130 131 132
    }
  }

  /**
   * {@inheritdoc}
   */
133
  public function defaultConfiguration() {
134 135 136 137 138 139 140 141 142 143
    return array(
      'recipient' => '',
      'subject' => '',
      'message' => '',
    );
  }

  /**
   * {@inheritdoc}
   */
144
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
145 146 147 148 149
    $form['recipient'] = array(
      '#type' => 'textfield',
      '#title' => t('Recipient'),
      '#default_value' => $this->configuration['recipient'],
      '#maxlength' => '254',
150
      '#description' => t('The email address to which the message should be sent OR enter [node:author:mail], [comment:author:mail], etc. if you would like to send an email to the author of the original post.'),
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    );
    $form['subject'] = array(
      '#type' => 'textfield',
      '#title' => t('Subject'),
      '#default_value' => $this->configuration['subject'],
      '#maxlength' => '254',
      '#description' => t('The subject of the message.'),
    );
    $form['message'] = array(
      '#type' => 'textarea',
      '#title' => t('Message'),
      '#default_value' => $this->configuration['message'],
      '#cols' => '80',
      '#rows' => '20',
      '#description' => t('The message that should be sent. You may include placeholders like [node:title], [user:name], and [comment:body] to represent data that will be different each time message is sent. Not all placeholders will be available in all contexts.'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
173
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
174
    if (!valid_email_address($form_state->getValue('recipient')) && strpos($form_state->getValue('recipient'), ':mail') === FALSE) {
175
      // We want the literal %author placeholder to be emphasized in the error message.
176
      $form_state->setErrorByName('recipient', t('Enter a valid email address or use a token email address such as %author.', array('%author' => '[node:author:mail]')));
177 178 179 180 181 182
    }
  }

  /**
   * {@inheritdoc}
   */
183
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
184 185 186
    $this->configuration['recipient'] = $form_state->getValue('recipient');
    $this->configuration['subject'] = $form_state->getValue('subject');
    $this->configuration['message'] = $form_state->getValue('message');
187 188
  }

189 190 191 192 193 194 195 196
  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    $result = AccessResult::allowed();
    return $return_as_object ? $result : $result->isAllowed();
  }

197
}