comparison core/lib/Drupal/Core/Mail/MailManager.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 7a779792577d
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Core\Mail;
4
5 use Drupal\Component\Render\PlainTextOutput;
6 use Drupal\Core\Logger\LoggerChannelFactoryInterface;
7 use Drupal\Core\Plugin\DefaultPluginManager;
8 use Drupal\Core\Cache\CacheBackendInterface;
9 use Drupal\Core\Extension\ModuleHandlerInterface;
10 use Drupal\Core\Config\ConfigFactoryInterface;
11 use Drupal\Core\Render\RenderContext;
12 use Drupal\Core\Render\RendererInterface;
13 use Drupal\Core\StringTranslation\StringTranslationTrait;
14 use Drupal\Core\StringTranslation\TranslationInterface;
15
16 /**
17 * Provides a Mail plugin manager.
18 *
19 * @see \Drupal\Core\Annotation\Mail
20 * @see \Drupal\Core\Mail\MailInterface
21 * @see plugin_api
22 */
23 class MailManager extends DefaultPluginManager implements MailManagerInterface {
24
25 use StringTranslationTrait;
26
27 /**
28 * The config factory.
29 *
30 * @var \Drupal\Core\Config\ConfigFactoryInterface
31 */
32 protected $configFactory;
33
34 /**
35 * The logger factory.
36 *
37 * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
38 */
39 protected $loggerFactory;
40
41 /**
42 * The renderer.
43 *
44 * @var \Drupal\Core\Render\RendererInterface
45 */
46 protected $renderer;
47
48 /**
49 * List of already instantiated mail plugins.
50 *
51 * @var array
52 */
53 protected $instances = [];
54
55 /**
56 * Constructs the MailManager object.
57 *
58 * @param \Traversable $namespaces
59 * An object that implements \Traversable which contains the root paths
60 * keyed by the corresponding namespace to look for plugin implementations.
61 * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
62 * Cache backend instance to use.
63 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
64 * The module handler to invoke the alter hook with.
65 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
66 * The configuration factory.
67 * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
68 * The logger channel factory.
69 * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
70 * The string translation service.
71 * @param \Drupal\Core\Render\RendererInterface $renderer
72 * The renderer.
73 */
74 public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory, TranslationInterface $string_translation, RendererInterface $renderer) {
75 parent::__construct('Plugin/Mail', $namespaces, $module_handler, 'Drupal\Core\Mail\MailInterface', 'Drupal\Core\Annotation\Mail');
76 $this->alterInfo('mail_backend_info');
77 $this->setCacheBackend($cache_backend, 'mail_backend_plugins');
78 $this->configFactory = $config_factory;
79 $this->loggerFactory = $logger_factory;
80 $this->stringTranslation = $string_translation;
81 $this->renderer = $renderer;
82 }
83
84 /**
85 * Overrides PluginManagerBase::getInstance().
86 *
87 * Returns an instance of the mail plugin to use for a given message ID.
88 *
89 * The selection of a particular implementation is controlled via the config
90 * 'system.mail.interface', which is a keyed array. The default
91 * implementation is the mail plugin whose ID is the value of 'default' key. A
92 * more specific match first to key and then to module will be used in
93 * preference to the default. To specify a different plugin for all mail sent
94 * by one module, set the plugin ID as the value for the key corresponding to
95 * the module name. To specify a plugin for a particular message sent by one
96 * module, set the plugin ID as the value for the array key that is the
97 * message ID, which is "${module}_${key}".
98 *
99 * For example to debug all mail sent by the user module by logging it to a
100 * file, you might set the variable as something like:
101 *
102 * @code
103 * array(
104 * 'default' => 'php_mail',
105 * 'user' => 'devel_mail_log',
106 * );
107 * @endcode
108 *
109 * Finally, a different system can be specified for a specific message ID (see
110 * the $key param), such as one of the keys used by the contact module:
111 *
112 * @code
113 * array(
114 * 'default' => 'php_mail',
115 * 'user' => 'devel_mail_log',
116 * 'contact_page_autoreply' => 'null_mail',
117 * );
118 * @endcode
119 *
120 * Other possible uses for system include a mail-sending plugin that actually
121 * sends (or duplicates) each message to SMS, Twitter, instant message, etc,
122 * or a plugin that queues up a large number of messages for more efficient
123 * bulk sending or for sending via a remote gateway so as to reduce the load
124 * on the local server.
125 *
126 * @param array $options
127 * An array with the following key/value pairs:
128 * - module: (string) The module name which was used by
129 * \Drupal\Core\Mail\MailManagerInterface->mail() to invoke hook_mail().
130 * - key: (string) A key to identify the email sent. The final message ID
131 * is a string represented as {$module}_{$key}.
132 *
133 * @return \Drupal\Core\Mail\MailInterface
134 * A mail plugin instance.
135 *
136 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
137 */
138 public function getInstance(array $options) {
139 $module = $options['module'];
140 $key = $options['key'];
141 $message_id = $module . '_' . $key;
142
143 $configuration = $this->configFactory->get('system.mail')->get('interface');
144
145 // Look for overrides for the default mail plugin, starting from the most
146 // specific message_id, and falling back to the module name.
147 if (isset($configuration[$message_id])) {
148 $plugin_id = $configuration[$message_id];
149 }
150 elseif (isset($configuration[$module])) {
151 $plugin_id = $configuration[$module];
152 }
153 else {
154 $plugin_id = $configuration['default'];
155 }
156
157 if (empty($this->instances[$plugin_id])) {
158 $this->instances[$plugin_id] = $this->createInstance($plugin_id);
159 }
160 return $this->instances[$plugin_id];
161 }
162
163 /**
164 * {@inheritdoc}
165 */
166 public function mail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE) {
167 // Mailing can invoke rendering (e.g., generating URLs, replacing tokens),
168 // but e-mails are not HTTP responses: they're not cached, they don't have
169 // attachments. Therefore we perform mailing inside its own render context,
170 // to ensure it doesn't leak into the render context for the HTTP response
171 // to the current request.
172 return $this->renderer->executeInRenderContext(new RenderContext(), function () use ($module, $key, $to, $langcode, $params, $reply, $send) {
173 return $this->doMail($module, $key, $to, $langcode, $params, $reply, $send);
174 });
175 }
176
177 /**
178 * Composes and optionally sends an email message.
179 *
180 * @param string $module
181 * A module name to invoke hook_mail() on. The {$module}_mail() hook will be
182 * called to complete the $message structure which will already contain
183 * common defaults.
184 * @param string $key
185 * A key to identify the email sent. The final message ID for email altering
186 * will be {$module}_{$key}.
187 * @param string $to
188 * The email address or addresses where the message will be sent to. The
189 * formatting of this string will be validated with the
190 * @link http://php.net/manual/filter.filters.validate.php PHP email validation filter. @endlink
191 * Some examples are:
192 * - user@example.com
193 * - user@example.com, anotheruser@example.com
194 * - User <user@example.com>
195 * - User <user@example.com>, Another User <anotheruser@example.com>
196 * @param string $langcode
197 * Language code to use to compose the email.
198 * @param array $params
199 * (optional) Parameters to build the email.
200 * @param string|null $reply
201 * Optional email address to be used to answer.
202 * @param bool $send
203 * If TRUE, call an implementation of
204 * \Drupal\Core\Mail\MailInterface->mail() to deliver the message, and
205 * store the result in $message['result']. Modules implementing
206 * hook_mail_alter() may cancel sending by setting $message['send'] to
207 * FALSE.
208 *
209 * @return array
210 * The $message array structure containing all details of the message. If
211 * already sent ($send = TRUE), then the 'result' element will contain the
212 * success indicator of the email, failure being already written to the
213 * watchdog. (Success means nothing more than the message being accepted at
214 * php-level, which still doesn't guarantee it to be delivered.)
215 *
216 * @see \Drupal\Core\Mail\MailManagerInterface::mail()
217 */
218 public function doMail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE) {
219 $site_config = $this->configFactory->get('system.site');
220 $site_mail = $site_config->get('mail');
221 if (empty($site_mail)) {
222 $site_mail = ini_get('sendmail_from');
223 }
224
225 // Bundle up the variables into a structured array for altering.
226 $message = [
227 'id' => $module . '_' . $key,
228 'module' => $module,
229 'key' => $key,
230 'to' => $to,
231 'from' => $site_mail,
232 'reply-to' => $reply,
233 'langcode' => $langcode,
234 'params' => $params,
235 'send' => TRUE,
236 'subject' => '',
237 'body' => [],
238 ];
239
240 // Build the default headers.
241 $headers = [
242 'MIME-Version' => '1.0',
243 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
244 'Content-Transfer-Encoding' => '8Bit',
245 'X-Mailer' => 'Drupal',
246 ];
247 // To prevent email from looking like spam, the addresses in the Sender and
248 // Return-Path headers should have a domain authorized to use the
249 // originating SMTP server.
250 $headers['Sender'] = $headers['Return-Path'] = $site_mail;
251 $headers['From'] = $site_config->get('name') . ' <' . $site_mail . '>';
252 if ($reply) {
253 $headers['Reply-to'] = $reply;
254 }
255 $message['headers'] = $headers;
256
257 // Build the email (get subject and body, allow additional headers) by
258 // invoking hook_mail() on this module. We cannot use
259 // moduleHandler()->invoke() as we need to have $message by reference in
260 // hook_mail().
261 if (function_exists($function = $module . '_mail')) {
262 $function($key, $message, $params);
263 }
264
265 // Invoke hook_mail_alter() to allow all modules to alter the resulting
266 // email.
267 $this->moduleHandler->alter('mail', $message);
268
269 // Retrieve the responsible implementation for this message.
270 $system = $this->getInstance(['module' => $module, 'key' => $key]);
271
272 // Format the message body.
273 $message = $system->format($message);
274
275 // Optionally send email.
276 if ($send) {
277 // The original caller requested sending. Sending was canceled by one or
278 // more hook_mail_alter() implementations. We set 'result' to NULL,
279 // because FALSE indicates an error in sending.
280 if (empty($message['send'])) {
281 $message['result'] = NULL;
282 }
283 // Sending was originally requested and was not canceled.
284 else {
285 // Ensure that subject is plain text. By default translated and
286 // formatted strings are prepared for the HTML context and email
287 // subjects are plain strings.
288 if ($message['subject']) {
289 $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
290 }
291 $message['result'] = $system->mail($message);
292 // Log errors.
293 if (!$message['result']) {
294 $this->loggerFactory->get('mail')
295 ->error('Error sending email (from %from to %to with reply-to %reply).', [
296 '%from' => $message['from'],
297 '%to' => $message['to'],
298 '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
299 ]);
300 drupal_set_message($this->t('Unable to send email. Contact the site administrator if the problem persists.'), 'error');
301 }
302 }
303 }
304
305 return $message;
306 }
307
308 }