Drupal 8.0.0 beta 12. More info: https://www.drupal.org/node/2514176
This commit is contained in:
commit
9921556621
13277 changed files with 1459781 additions and 0 deletions
396
core/lib/Drupal/Core/Mail/MailFormatHelper.php
Normal file
396
core/lib/Drupal/Core/Mail/MailFormatHelper.php
Normal file
|
@ -0,0 +1,396 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Core\Mail\MailFormatHelper.
|
||||
*/
|
||||
|
||||
namespace Drupal\Core\Mail;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\Component\Utility\Xss;
|
||||
use Drupal\Core\Site\Settings;
|
||||
|
||||
/**
|
||||
* Defines a class containing utility methods for formatting mail messages.
|
||||
*/
|
||||
class MailFormatHelper {
|
||||
|
||||
/**
|
||||
* Internal array of urls replaced with tokens.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $urls = array();
|
||||
|
||||
/**
|
||||
* Quoted regex expression based on base path.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $regexp;
|
||||
|
||||
/**
|
||||
* Array of tags supported.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $supportedTags = array();
|
||||
|
||||
/**
|
||||
* Performs format=flowed soft wrapping for mail (RFC 3676).
|
||||
*
|
||||
* We use delsp=yes wrapping, but only break non-spaced languages when
|
||||
* absolutely necessary to avoid compatibility issues.
|
||||
*
|
||||
* We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
|
||||
*
|
||||
* @param string $text
|
||||
* The plain text to process.
|
||||
* @param string $indent
|
||||
* (optional) A string to indent the text with. Only '>' characters are
|
||||
* repeated on subsequent wrapped lines. Others are replaced by spaces.
|
||||
*
|
||||
* @return string
|
||||
* The content of the email as a string with formatting applied.
|
||||
*/
|
||||
public static function wrapMail($text, $indent = '') {
|
||||
// Convert CRLF into LF.
|
||||
$text = str_replace("\r", '', $text);
|
||||
// See if soft-wrapping is allowed.
|
||||
$clean_indent = static::htmlToTextClean($indent);
|
||||
$soft = strpos($clean_indent, ' ') === FALSE;
|
||||
// Check if the string has line breaks.
|
||||
if (strpos($text, "\n") !== FALSE) {
|
||||
// Remove trailing spaces to make existing breaks hard, but leave
|
||||
// signature marker untouched (RFC 3676, Section 4.3).
|
||||
$text = preg_replace('/(?(?<!^--) +\n| +\n)/m', "\n", $text);
|
||||
// Wrap each line at the needed width.
|
||||
$lines = explode("\n", $text);
|
||||
array_walk($lines, '\Drupal\Core\Mail\MailFormatHelper::wrapMailLine', array('soft' => $soft, 'length' => strlen($indent)));
|
||||
$text = implode("\n", $lines);
|
||||
}
|
||||
else {
|
||||
// Wrap this line.
|
||||
static::wrapMailLine($text, 0, array('soft' => $soft, 'length' => strlen($indent)));
|
||||
}
|
||||
// Empty lines with nothing but spaces.
|
||||
$text = preg_replace('/^ +\n/m', "\n", $text);
|
||||
// Space-stuff special lines.
|
||||
$text = preg_replace('/^(>| |From)/m', ' $1', $text);
|
||||
// Apply indentation. We only include non-'>' indentation on the first line.
|
||||
$text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms an HTML string into plain text, preserving its structure.
|
||||
*
|
||||
* The output will be suitable for use as 'format=flowed; delsp=yes' text
|
||||
* (RFC 3676) and can be passed directly to MailManagerInterface::mail() for sending.
|
||||
*
|
||||
* We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
|
||||
*
|
||||
* This function provides suitable alternatives for the following tags:
|
||||
* <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
|
||||
* <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
|
||||
*
|
||||
* @param string $string
|
||||
* The string to be transformed.
|
||||
* @param array $allowed_tags
|
||||
* (optional) If supplied, a list of tags that will be transformed. If
|
||||
* omitted, all supported tags are transformed.
|
||||
*
|
||||
* @return string
|
||||
* The transformed string.
|
||||
*/
|
||||
public static function htmlToText($string, $allowed_tags = NULL) {
|
||||
// Cache list of supported tags.
|
||||
if (empty(static::$supportedTags)) {
|
||||
static::$supportedTags = array('a', 'em', 'i', 'strong', 'b', 'br', 'p',
|
||||
'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3',
|
||||
'h4', 'h5', 'h6', 'hr');
|
||||
}
|
||||
|
||||
// Make sure only supported tags are kept.
|
||||
$allowed_tags = isset($allowed_tags) ? array_intersect(static::$supportedTags, $allowed_tags) : static::$supportedTags;
|
||||
|
||||
// Make sure tags, entities and attributes are well-formed and properly
|
||||
// nested.
|
||||
$string = Html::normalize(Xss::filter($string, $allowed_tags));
|
||||
|
||||
// Apply inline styles.
|
||||
$string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
|
||||
$string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
|
||||
|
||||
// Replace inline <a> tags with the text of link and a footnote.
|
||||
// 'See <a href="https://www.drupal.org">the Drupal site</a>' becomes
|
||||
// 'See the Drupal site [1]' with the URL included as a footnote.
|
||||
static::htmlToMailUrls(NULL, TRUE);
|
||||
$pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
|
||||
$string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
|
||||
$urls = static::htmlToMailUrls();
|
||||
$footnotes = '';
|
||||
if (count($urls)) {
|
||||
$footnotes .= "\n";
|
||||
for ($i = 0, $max = count($urls); $i < $max; $i++) {
|
||||
$footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Split tags from text.
|
||||
$split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
|
||||
// Note: PHP ensures the array consists of alternating delimiters and
|
||||
// literals and begins and ends with a literal (inserting $null as
|
||||
// required).
|
||||
// Odd/even counter (tag or no tag).
|
||||
$tag = FALSE;
|
||||
// Case conversion function.
|
||||
$casing = NULL;
|
||||
$output = '';
|
||||
// All current indentation string chunks.
|
||||
$indent = array();
|
||||
// Array of counters for opened lists.
|
||||
$lists = array();
|
||||
foreach ($split as $value) {
|
||||
// Holds a string ready to be formatted and output.
|
||||
$chunk = NULL;
|
||||
|
||||
// Process HTML tags (but don't output any literally).
|
||||
if ($tag) {
|
||||
list($tagname) = explode(' ', strtolower($value), 2);
|
||||
switch ($tagname) {
|
||||
// List counters.
|
||||
case 'ul':
|
||||
array_unshift($lists, '*');
|
||||
break;
|
||||
|
||||
case 'ol':
|
||||
array_unshift($lists, 1);
|
||||
break;
|
||||
|
||||
case '/ul':
|
||||
case '/ol':
|
||||
array_shift($lists);
|
||||
// Ensure blank new-line.
|
||||
$chunk = '';
|
||||
break;
|
||||
|
||||
// Quotation/list markers, non-fancy headers.
|
||||
case 'blockquote':
|
||||
// Format=flowed indentation cannot be mixed with lists.
|
||||
$indent[] = count($lists) ? ' "' : '>';
|
||||
break;
|
||||
|
||||
case 'li':
|
||||
$indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
|
||||
break;
|
||||
|
||||
case 'dd':
|
||||
$indent[] = ' ';
|
||||
break;
|
||||
|
||||
case 'h3':
|
||||
$indent[] = '.... ';
|
||||
break;
|
||||
|
||||
case 'h4':
|
||||
$indent[] = '.. ';
|
||||
break;
|
||||
|
||||
case '/blockquote':
|
||||
if (count($lists)) {
|
||||
// Append closing quote for inline quotes (immediately).
|
||||
$output = rtrim($output, "> \n") . "\"\n";
|
||||
// Ensure blank new-line.
|
||||
$chunk = '';
|
||||
}
|
||||
|
||||
// Fall-through.
|
||||
case '/li':
|
||||
case '/dd':
|
||||
array_pop($indent);
|
||||
break;
|
||||
|
||||
case '/h3':
|
||||
case '/h4':
|
||||
array_pop($indent);
|
||||
case '/h5':
|
||||
case '/h6':
|
||||
// Ensure blank new-line.
|
||||
$chunk = '';
|
||||
break;
|
||||
|
||||
// Fancy headers.
|
||||
case 'h1':
|
||||
$indent[] = '======== ';
|
||||
$casing = '\Drupal\Component\Utility\Unicode::strtoupper';
|
||||
break;
|
||||
|
||||
case 'h2':
|
||||
$indent[] = '-------- ';
|
||||
$casing = '\Drupal\Component\Utility\Unicode::strtoupper';
|
||||
break;
|
||||
|
||||
case '/h1':
|
||||
case '/h2':
|
||||
$casing = NULL;
|
||||
// Pad the line with dashes.
|
||||
$output = static::htmlToTextPad($output, ($tagname == '/h1') ? '=' : '-', ' ');
|
||||
array_pop($indent);
|
||||
// Ensure blank new-line.
|
||||
$chunk = '';
|
||||
break;
|
||||
|
||||
// Horizontal rulers.
|
||||
case 'hr':
|
||||
// Insert immediately.
|
||||
$output .= static::wrapMail('', implode('', $indent)) . "\n";
|
||||
$output = static::htmlToTextPad($output, '-');
|
||||
break;
|
||||
|
||||
// Paragraphs and definition lists.
|
||||
case '/p':
|
||||
case '/dl':
|
||||
// Ensure blank new-line.
|
||||
$chunk = '';
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Process blocks of text.
|
||||
else {
|
||||
// Convert inline HTML text to plain text; not removing line-breaks or
|
||||
// white-space, since that breaks newlines when sanitizing plain-text.
|
||||
$value = trim(Html::decodeEntities($value));
|
||||
if (Unicode::strlen($value)) {
|
||||
$chunk = $value;
|
||||
}
|
||||
}
|
||||
|
||||
// See if there is something waiting to be output.
|
||||
if (isset($chunk)) {
|
||||
// Apply any necessary case conversion.
|
||||
if (isset($casing)) {
|
||||
$chunk = call_user_func($casing, $chunk);
|
||||
}
|
||||
$line_endings = Settings::get('mail_line_endings', PHP_EOL);
|
||||
// Format it and apply the current indentation.
|
||||
$output .= static::wrapMail($chunk, implode('', $indent)) . $line_endings;
|
||||
// Remove non-quotation markers from indentation.
|
||||
$indent = array_map('\Drupal\Core\Mail\MailFormatHelper::htmlToTextClean', $indent);
|
||||
}
|
||||
|
||||
$tag = !$tag;
|
||||
}
|
||||
|
||||
return $output . $footnotes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps words on a single line.
|
||||
*
|
||||
* Callback for array_walk() within
|
||||
* \Drupal\Core\Mail\MailFormatHelper::wrapMail().
|
||||
*
|
||||
* Note that we are skipping MIME content header lines, because attached
|
||||
* files, especially applications, could have long MIME types or long
|
||||
* filenames which result in line length longer than the 77 characters limit
|
||||
* and wrapping that line will break the email format. E.g., the attached file
|
||||
* hello_drupal.docx will produce the following Content-Type:
|
||||
* @code
|
||||
* Content-Type:
|
||||
* application/vnd.openxmlformats-officedocument.wordprocessingml.document;
|
||||
* name="hello_drupal.docx"
|
||||
* @endcode
|
||||
*/
|
||||
protected static function wrapMailLine(&$line, $key, $values) {
|
||||
$line_is_mime_header = FALSE;
|
||||
$mime_headers = array(
|
||||
'Content-Type',
|
||||
'Content-Transfer-Encoding',
|
||||
'Content-Disposition',
|
||||
'Content-Description',
|
||||
);
|
||||
|
||||
// Do not break MIME headers which could be longer than 77 characters.
|
||||
foreach ($mime_headers as $header) {
|
||||
if (strpos($line, $header . ': ') === 0) {
|
||||
$line_is_mime_header = TRUE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!$line_is_mime_header) {
|
||||
// Use soft-breaks only for purely quoted or unindented text.
|
||||
$line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n");
|
||||
}
|
||||
// Break really long words at the maximum width allowed.
|
||||
$line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n", TRUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps track of URLs and replaces them with placeholder tokens.
|
||||
*
|
||||
* Callback for preg_replace_callback() within
|
||||
* \Drupal\Core\Mail\MailFormatHelper::htmlToText().
|
||||
*/
|
||||
protected static function htmlToMailUrls($match = NULL, $reset = FALSE) {
|
||||
// @todo Use request context instead.
|
||||
global $base_url, $base_path;
|
||||
|
||||
if ($reset) {
|
||||
// Reset internal URL list.
|
||||
static::$urls = array();
|
||||
}
|
||||
else {
|
||||
if (empty(static::$regexp)) {
|
||||
static::$regexp = '@^' . preg_quote($base_path, '@') . '@';
|
||||
}
|
||||
if ($match) {
|
||||
list(, , $url, $label) = $match;
|
||||
// Ensure all URLs are absolute.
|
||||
static::$urls[] = strpos($url, '://') ? $url : preg_replace(static::$regexp, $base_url . '/', $url);
|
||||
return $label . ' [' . count(static::$urls) . ']';
|
||||
}
|
||||
}
|
||||
return static::$urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces non-quotation markers from a piece of indentation with spaces.
|
||||
*
|
||||
* Callback for array_map() within
|
||||
* \Drupal\Core\Mail\MailFormatHelper::htmlToText().
|
||||
*/
|
||||
protected static function htmlToTextClean($indent) {
|
||||
return preg_replace('/[^>]/', ' ', $indent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pads the last line with the given character.
|
||||
*
|
||||
* @param string $text
|
||||
* The text to pad.
|
||||
* @param string $pad
|
||||
* The character to pad the end of the string with.
|
||||
* @param string $prefix
|
||||
* (optional) Prefix to add to the string.
|
||||
*
|
||||
* @return string
|
||||
* The padded string.
|
||||
*
|
||||
* @see \Drupal\Core\Mail\MailFormatHelper::htmlToText()
|
||||
*/
|
||||
protected static function htmlToTextPad($text, $pad, $prefix = '') {
|
||||
// Remove last line break.
|
||||
$text = substr($text, 0, -1);
|
||||
// Calculate needed padding space and add it.
|
||||
if (($p = strrpos($text, "\n")) === FALSE) {
|
||||
$p = -1;
|
||||
}
|
||||
$n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
|
||||
// Add prefix and padding, and restore linebreak.
|
||||
return $text . $prefix . str_repeat($pad, $n) . "\n";
|
||||
}
|
||||
}
|
68
core/lib/Drupal/Core/Mail/MailInterface.php
Normal file
68
core/lib/Drupal/Core/Mail/MailInterface.php
Normal file
|
@ -0,0 +1,68 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Core\Mail\MailInterface.
|
||||
*/
|
||||
|
||||
namespace Drupal\Core\Mail;
|
||||
|
||||
/**
|
||||
* Defines an interface for pluggable mail back-ends.
|
||||
*
|
||||
* @see \Drupal\Core\Annotation\Mail
|
||||
* @see \Drupal\Core\Mail\MailManager
|
||||
* @see plugin_api
|
||||
*/
|
||||
interface MailInterface {
|
||||
|
||||
/**
|
||||
* Formats a message prior to sending.
|
||||
*
|
||||
* Allows to preprocess, format, and postprocess a mail message before it is
|
||||
* passed to the sending system. By default, all messages may contain HTML and
|
||||
* are converted to plain-text by the Drupal\Core\Mail\Plugin\Mail\PhpMail
|
||||
* implementation. For example, an alternative implementation could override
|
||||
* the default implementation and also sanitize the HTML for usage in a MIME-
|
||||
* encoded email, but still invoking the Drupal\Core\Mail\Plugin\Mail\PhpMail
|
||||
* implementation to generate an alternate plain-text version for sending.
|
||||
*
|
||||
* @param array $message
|
||||
* A message array, as described in hook_mail_alter().
|
||||
*
|
||||
* @return array
|
||||
* The formatted $message.
|
||||
*
|
||||
* @see \Drupal\Core\Mail\MailManagerInterface
|
||||
*/
|
||||
public function format(array $message);
|
||||
|
||||
/**
|
||||
* Sends a message composed by \Drupal\Core\Mail\MailManagerInterface->mail().
|
||||
*
|
||||
* @param array $message
|
||||
* Message array with at least the following elements:
|
||||
* - id: A unique identifier of the email type. Examples: 'contact_user_copy',
|
||||
* 'user_password_reset'.
|
||||
* - to: The mail address or addresses where the message will be sent to.
|
||||
* The formatting of this string will be validated with the
|
||||
* @link http://php.net/manual/filter.filters.validate.php PHP email validation filter. @endlink
|
||||
* Some examples:
|
||||
* - user@example.com
|
||||
* - user@example.com, anotheruser@example.com
|
||||
* - User <user@example.com>
|
||||
* - User <user@example.com>, Another User <anotheruser@example.com>
|
||||
* - subject: Subject of the email to be sent. This must not contain any
|
||||
* newline characters, or the mail may not be sent properly.
|
||||
* - body: Message to be sent. Accepts both CRLF and LF line-endings.
|
||||
* Email bodies must be wrapped. For smart plain text wrapping you can use
|
||||
* \Drupal\Core\Mail\MailFormatHelper::wrapMail() .
|
||||
* - headers: Associative array containing all additional mail headers not
|
||||
* defined by one of the other parameters. PHP's mail() looks for Cc and
|
||||
* Bcc headers and sends the mail to addresses in these headers too.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if the mail was successfully accepted for delivery, otherwise FALSE.
|
||||
*/
|
||||
public function mail(array $message);
|
||||
}
|
242
core/lib/Drupal/Core/Mail/MailManager.php
Normal file
242
core/lib/Drupal/Core/Mail/MailManager.php
Normal file
|
@ -0,0 +1,242 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Core\Mail\MailManager.
|
||||
*/
|
||||
|
||||
namespace Drupal\Core\Mail;
|
||||
|
||||
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
|
||||
use Drupal\Core\Plugin\DefaultPluginManager;
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\StringTranslation\StringTranslationTrait;
|
||||
use Drupal\Core\StringTranslation\TranslationInterface;
|
||||
|
||||
/**
|
||||
* Provides a Mail plugin manager.
|
||||
*
|
||||
* @see \Drupal\Core\Annotation\Mail
|
||||
* @see \Drupal\Core\Mail\MailInterface
|
||||
* @see plugin_api
|
||||
*/
|
||||
class MailManager extends DefaultPluginManager implements MailManagerInterface {
|
||||
|
||||
use StringTranslationTrait;
|
||||
|
||||
/**
|
||||
* The config factory.
|
||||
*
|
||||
* @var \Drupal\Core\Config\ConfigFactoryInterface
|
||||
*/
|
||||
protected $configFactory;
|
||||
|
||||
/**
|
||||
* The logger factory.
|
||||
*
|
||||
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
|
||||
*/
|
||||
protected $loggerFactory;
|
||||
|
||||
/**
|
||||
* List of already instantiated mail plugins.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $instances = array();
|
||||
|
||||
/**
|
||||
* Constructs the MailManager object.
|
||||
*
|
||||
* @param \Traversable $namespaces
|
||||
* An object that implements \Traversable which contains the root paths
|
||||
* keyed by the corresponding namespace to look for plugin implementations.
|
||||
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
|
||||
* Cache backend instance to use.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler to invoke the alter hook with.
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The configuration factory.
|
||||
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
|
||||
* The logger channel factory.
|
||||
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
|
||||
* The string translation service.
|
||||
*/
|
||||
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory, TranslationInterface $string_translation) {
|
||||
parent::__construct('Plugin/Mail', $namespaces, $module_handler, 'Drupal\Core\Mail\MailInterface', 'Drupal\Core\Annotation\Mail');
|
||||
$this->alterInfo('mail_backend_info');
|
||||
$this->setCacheBackend($cache_backend, 'mail_backend_plugins');
|
||||
$this->configFactory = $config_factory;
|
||||
$this->loggerFactory = $logger_factory;
|
||||
$this->stringTranslation = $string_translation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides PluginManagerBase::getInstance().
|
||||
*
|
||||
* Returns an instance of the mail plugin to use for a given message ID.
|
||||
*
|
||||
* The selection of a particular implementation is controlled via the config
|
||||
* 'system.mail.interface', which is a keyed array. The default
|
||||
* implementation is the mail plugin whose ID is the value of 'default' key. A
|
||||
* more specific match first to key and then to module will be used in
|
||||
* preference to the default. To specify a different plugin for all mail sent
|
||||
* by one module, set the plugin ID as the value for the key corresponding to
|
||||
* the module name. To specify a plugin for a particular message sent by one
|
||||
* module, set the plugin ID as the value for the array key that is the
|
||||
* message ID, which is "${module}_${key}".
|
||||
*
|
||||
* For example to debug all mail sent by the user module by logging it to a
|
||||
* file, you might set the variable as something like:
|
||||
*
|
||||
* @code
|
||||
* array(
|
||||
* 'default' => 'php_mail',
|
||||
* 'user' => 'devel_mail_log',
|
||||
* );
|
||||
* @endcode
|
||||
*
|
||||
* Finally, a different system can be specified for a specific message ID (see
|
||||
* the $key param), such as one of the keys used by the contact module:
|
||||
*
|
||||
* @code
|
||||
* array(
|
||||
* 'default' => 'php_mail',
|
||||
* 'user' => 'devel_mail_log',
|
||||
* 'contact_page_autoreply' => 'null_mail',
|
||||
* );
|
||||
* @endcode
|
||||
*
|
||||
* Other possible uses for system include a mail-sending plugin that actually
|
||||
* sends (or duplicates) each message to SMS, Twitter, instant message, etc,
|
||||
* or a plugin that queues up a large number of messages for more efficient
|
||||
* bulk sending or for sending via a remote gateway so as to reduce the load
|
||||
* on the local server.
|
||||
*
|
||||
* @param array $options
|
||||
* An array with the following key/value pairs:
|
||||
* - module: (string) The module name which was used by
|
||||
* \Drupal\Core\Mail\MailManagerInterface->mail() to invoke hook_mail().
|
||||
* - key: (string) A key to identify the email sent. The final message ID
|
||||
* is a string represented as {$module}_{$key}.
|
||||
*
|
||||
* @return \Drupal\Core\Mail\MailInterface
|
||||
* A mail plugin instance.
|
||||
*
|
||||
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
|
||||
*/
|
||||
public function getInstance(array $options) {
|
||||
$module = $options['module'];
|
||||
$key = $options['key'];
|
||||
$message_id = $module . '_' . $key;
|
||||
|
||||
$configuration = $this->configFactory->get('system.mail')->get('interface');
|
||||
|
||||
// Look for overrides for the default mail plugin, starting from the most
|
||||
// specific message_id, and falling back to the module name.
|
||||
if (isset($configuration[$message_id])) {
|
||||
$plugin_id = $configuration[$message_id];
|
||||
}
|
||||
elseif (isset($configuration[$module])) {
|
||||
$plugin_id = $configuration[$module];
|
||||
}
|
||||
else {
|
||||
$plugin_id = $configuration['default'];
|
||||
}
|
||||
|
||||
if (empty($this->instances[$plugin_id])) {
|
||||
$this->instances[$plugin_id] = $this->createInstance($plugin_id);
|
||||
}
|
||||
return $this->instances[$plugin_id];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function mail($module, $key, $to, $langcode, $params = array(), $reply = NULL, $send = TRUE) {
|
||||
$site_config = $this->configFactory->get('system.site');
|
||||
$site_mail = $site_config->get('mail');
|
||||
if (empty($site_mail)) {
|
||||
$site_mail = ini_get('sendmail_from');
|
||||
}
|
||||
|
||||
// Bundle up the variables into a structured array for altering.
|
||||
$message = array(
|
||||
'id' => $module . '_' . $key,
|
||||
'module' => $module,
|
||||
'key' => $key,
|
||||
'to' => $to,
|
||||
'from' => $site_mail,
|
||||
'reply-to' => $reply,
|
||||
'langcode' => $langcode,
|
||||
'params' => $params,
|
||||
'send' => TRUE,
|
||||
'subject' => '',
|
||||
'body' => array(),
|
||||
);
|
||||
|
||||
// Build the default headers.
|
||||
$headers = array(
|
||||
'MIME-Version' => '1.0',
|
||||
'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
|
||||
'Content-Transfer-Encoding' => '8Bit',
|
||||
'X-Mailer' => 'Drupal',
|
||||
);
|
||||
// To prevent email from looking like spam, the addresses in the Sender and
|
||||
// Return-Path headers should have a domain authorized to use the
|
||||
// originating SMTP server.
|
||||
$headers['Sender'] = $headers['Return-Path'] = $site_mail;
|
||||
$headers['From'] = $site_config->get('name') . ' <' . $site_mail . '>';
|
||||
if ($reply) {
|
||||
$headers['Reply-to'] = $reply;
|
||||
}
|
||||
$message['headers'] = $headers;
|
||||
|
||||
// Build the email (get subject and body, allow additional headers) by
|
||||
// invoking hook_mail() on this module. We cannot use
|
||||
// moduleHandler()->invoke() as we need to have $message by reference in
|
||||
// hook_mail().
|
||||
if (function_exists($function = $module . '_mail')) {
|
||||
$function($key, $message, $params);
|
||||
}
|
||||
|
||||
// Invoke hook_mail_alter() to allow all modules to alter the resulting
|
||||
// email.
|
||||
$this->moduleHandler->alter('mail', $message);
|
||||
|
||||
// Retrieve the responsible implementation for this message.
|
||||
$system = $this->getInstance(array('module' => $module, 'key' => $key));
|
||||
|
||||
// Format the message body.
|
||||
$message = $system->format($message);
|
||||
|
||||
// Optionally send email.
|
||||
if ($send) {
|
||||
// The original caller requested sending. Sending was canceled by one or
|
||||
// more hook_mail_alter() implementations. We set 'result' to NULL,
|
||||
// because FALSE indicates an error in sending.
|
||||
if (empty($message['send'])) {
|
||||
$message['result'] = NULL;
|
||||
}
|
||||
// Sending was originally requested and was not canceled.
|
||||
else {
|
||||
$message['result'] = $system->mail($message);
|
||||
// Log errors.
|
||||
if (!$message['result']) {
|
||||
$this->loggerFactory->get('mail')
|
||||
->error('Error sending email (from %from to %to with reply-to %reply).', array(
|
||||
'%from' => $message['from'],
|
||||
'%to' => $message['to'],
|
||||
'%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
|
||||
));
|
||||
drupal_set_message($this->t('Unable to send email. Contact the site administrator if the problem persists.'), 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
}
|
128
core/lib/Drupal/Core/Mail/MailManagerInterface.php
Normal file
128
core/lib/Drupal/Core/Mail/MailManagerInterface.php
Normal file
|
@ -0,0 +1,128 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Core\Mail\MailManagerInterface.
|
||||
*/
|
||||
|
||||
namespace Drupal\Core\Mail;
|
||||
|
||||
use Drupal\Component\Plugin\PluginManagerInterface;
|
||||
|
||||
/**
|
||||
* Provides an interface for sending mail.
|
||||
*/
|
||||
interface MailManagerInterface extends PluginManagerInterface {
|
||||
|
||||
/**
|
||||
* Composes and optionally sends an email message.
|
||||
*
|
||||
* Sending an email works with defining an email template (subject, text and
|
||||
* possibly email headers) and the replacement values to use in the
|
||||
* appropriate places in the template. Processed email templates are requested
|
||||
* from hook_mail() from the module sending the email. Any module can modify
|
||||
* the composed email message array using hook_mail_alter(). Finally
|
||||
* \Drupal::service('plugin.manager.mail')->mail() sends the email, which can
|
||||
* be reused if the exact same composed email is to be sent to multiple
|
||||
* recipients.
|
||||
*
|
||||
* Finding out what language to send the email with needs some consideration.
|
||||
* If you send email to a user, her preferred language should be fine, so use
|
||||
* user_preferred_langcode(). If you send email based on form values filled on
|
||||
* the page, there are two additional choices if you are not sending the email
|
||||
* to a user on the site. You can either use the language used to generate the
|
||||
* page or the site default language. See
|
||||
* Drupal\Core\Language\LanguageManagerInterface::getDefaultLanguage(). The
|
||||
* former is good if sending email to the person filling the form, the later
|
||||
* is good if you send email to an address previously set up (like contact
|
||||
* addresses in a contact form).
|
||||
*
|
||||
* Taking care of always using the proper language is even more important when
|
||||
* sending emails in a row to multiple users. Hook_mail() abstracts whether
|
||||
* the mail text comes from an administrator setting or is static in the
|
||||
* source code. It should also deal with common mail tokens, only receiving
|
||||
* $params which are unique to the actual email at hand.
|
||||
*
|
||||
* An example:
|
||||
*
|
||||
* @code
|
||||
* function example_notify($accounts) {
|
||||
* foreach ($accounts as $account) {
|
||||
* $params['account'] = $account;
|
||||
* // example_mail() will be called based on the first
|
||||
* // MailManagerInterface->mail() parameter.
|
||||
* \Drupal::service('plugin.manager.mail')->mail('example', 'notice', $account->mail, user_preferred_langcode($account), $params);
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* function example_mail($key, &$message, $params) {
|
||||
* $data['user'] = $params['account'];
|
||||
* $options['langcode'] = $message['langcode'];
|
||||
* user_mail_tokens($variables, $data, $options);
|
||||
* switch($key) {
|
||||
* case 'notice':
|
||||
* // If the recipient can receive such notices by instant-message, do
|
||||
* // not send by email.
|
||||
* if (example_im_send($key, $message, $params)) {
|
||||
* $message['send'] = FALSE;
|
||||
* break;
|
||||
* }
|
||||
* $message['subject'] = t('Notification from !site', $variables, $options);
|
||||
* $message['body'][] = t("Dear !username\n\nThere is new content available on the site.", $variables, $options);
|
||||
* break;
|
||||
* }
|
||||
* }
|
||||
* @endcode
|
||||
*
|
||||
* Another example, which uses MailManagerInterface->mail() to format a
|
||||
* message for sending later:
|
||||
*
|
||||
* @code
|
||||
* $params = array('current_conditions' => $data);
|
||||
* $to = 'user@example.com';
|
||||
* $message = \Drupal::service('plugin.manager.mail')->mail('example', 'notice', $to, $langcode, $params, FALSE);
|
||||
* // Only add to the spool if sending was not canceled.
|
||||
* if ($message['send']) {
|
||||
* example_spool_message($message);
|
||||
* }
|
||||
* @endcode
|
||||
*
|
||||
* @param string $module
|
||||
* A module name to invoke hook_mail() on. The {$module}_mail() hook will be
|
||||
* called to complete the $message structure which will already contain
|
||||
* common defaults.
|
||||
* @param string $key
|
||||
* A key to identify the email sent. The final message ID for email altering
|
||||
* will be {$module}_{$key}.
|
||||
* @param string $to
|
||||
* The email address or addresses where the message will be sent to. The
|
||||
* formatting of this string will be validated with the
|
||||
* @link http://php.net/manual/filter.filters.validate.php PHP email validation filter. @endlink
|
||||
* Some examples are:
|
||||
* - user@example.com
|
||||
* - user@example.com, anotheruser@example.com
|
||||
* - User <user@example.com>
|
||||
* - User <user@example.com>, Another User <anotheruser@example.com>
|
||||
* @param string $langcode
|
||||
* Language code to use to compose the email.
|
||||
* @param array $params
|
||||
* (optional) Parameters to build the email.
|
||||
* @param string|null $reply
|
||||
* Optional email address to be used to answer.
|
||||
* @param bool $send
|
||||
* If TRUE, call an implementation of
|
||||
* \Drupal\Core\Mail\MailInterface->mail() to deliver the message, and
|
||||
* store the result in $message['result']. Modules implementing
|
||||
* hook_mail_alter() may cancel sending by setting $message['send'] to
|
||||
* FALSE.
|
||||
*
|
||||
* @return array
|
||||
* The $message array structure containing all details of the message. If
|
||||
* already sent ($send = TRUE), then the 'result' element will contain the
|
||||
* success indicator of the email, failure being already written to the
|
||||
* watchdog. (Success means nothing more than the message being accepted at
|
||||
* php-level, which still doesn't guarantee it to be delivered.)
|
||||
*/
|
||||
public function mail($module, $key, $to, $langcode, $params = array(), $reply = NULL, $send = TRUE);
|
||||
|
||||
}
|
118
core/lib/Drupal/Core/Mail/Plugin/Mail/PhpMail.php
Normal file
118
core/lib/Drupal/Core/Mail/Plugin/Mail/PhpMail.php
Normal file
|
@ -0,0 +1,118 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Core\Mail\Plugin\Mail\PhpMail.
|
||||
*/
|
||||
|
||||
namespace Drupal\Core\Mail\Plugin\Mail;
|
||||
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\Core\Mail\MailFormatHelper;
|
||||
use Drupal\Core\Mail\MailInterface;
|
||||
use Drupal\Core\Site\Settings;
|
||||
|
||||
/**
|
||||
* Defines the default Drupal mail backend, using PHP's native mail() function.
|
||||
*
|
||||
* @Mail(
|
||||
* id = "php_mail",
|
||||
* label = @Translation("Default PHP mailer"),
|
||||
* description = @Translation("Sends the message as plain text, using PHP's native mail() function.")
|
||||
* )
|
||||
*/
|
||||
class PhpMail implements MailInterface {
|
||||
|
||||
/**
|
||||
* Concatenates and wraps the email body for plain-text mails.
|
||||
*
|
||||
* @param array $message
|
||||
* A message array, as described in hook_mail_alter().
|
||||
*
|
||||
* @return array
|
||||
* The formatted $message.
|
||||
*/
|
||||
public function format(array $message) {
|
||||
// Join the body array into one string.
|
||||
$message['body'] = implode("\n\n", $message['body']);
|
||||
// Convert any HTML to plain-text.
|
||||
$message['body'] = MailFormatHelper::htmlToText($message['body']);
|
||||
// Wrap the mail body for sending.
|
||||
$message['body'] = MailFormatHelper::wrapMail($message['body']);
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an email message.
|
||||
*
|
||||
* @param array $message
|
||||
* A message array, as described in hook_mail_alter().
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if the mail was successfully accepted, otherwise FALSE.
|
||||
*
|
||||
* @see http://php.net/manual/en/function.mail.php
|
||||
* @see \Drupal\Core\Mail\MailManagerInterface::mail()
|
||||
*/
|
||||
public function mail(array $message) {
|
||||
// If 'Return-Path' isn't already set in php.ini, we pass it separately
|
||||
// as an additional parameter instead of in the header.
|
||||
if (isset($message['headers']['Return-Path'])) {
|
||||
$return_path_set = strpos(ini_get('sendmail_path'), ' -f');
|
||||
if (!$return_path_set) {
|
||||
$message['Return-Path'] = $message['headers']['Return-Path'];
|
||||
unset($message['headers']['Return-Path']);
|
||||
}
|
||||
}
|
||||
$mimeheaders = array();
|
||||
foreach ($message['headers'] as $name => $value) {
|
||||
$mimeheaders[] = $name . ': ' . Unicode::mimeHeaderEncode($value);
|
||||
}
|
||||
$line_endings = Settings::get('mail_line_endings', PHP_EOL);
|
||||
// Prepare mail commands.
|
||||
$mail_subject = Unicode::mimeHeaderEncode($message['subject']);
|
||||
// Note: email uses CRLF for line-endings. PHP's API requires LF
|
||||
// on Unix and CRLF on Windows. Drupal automatically guesses the
|
||||
// line-ending format appropriate for your system. If you need to
|
||||
// override this, adjust $settings['mail_line_endings'] in settings.php.
|
||||
$mail_body = preg_replace('@\r?\n@', $line_endings, $message['body']);
|
||||
// For headers, PHP's API suggests that we use CRLF normally,
|
||||
// but some MTAs incorrectly replace LF with CRLF. See #234403.
|
||||
$mail_headers = join("\n", $mimeheaders);
|
||||
|
||||
$request = \Drupal::request();
|
||||
|
||||
// We suppress warnings and notices from mail() because of issues on some
|
||||
// hosts. The return value of this method will still indicate whether mail
|
||||
// was sent successfully.
|
||||
if (!$request->server->has('WINDIR') && strpos($request->server->get('SERVER_SOFTWARE'), 'Win32') === FALSE) {
|
||||
// On most non-Windows systems, the "-f" option to the sendmail command
|
||||
// is used to set the Return-Path. There is no space between -f and
|
||||
// the value of the return path.
|
||||
$additional_headers = isset($message['Return-Path']) ? '-f' . $message['Return-Path'] : '';
|
||||
$mail_result = @mail(
|
||||
$message['to'],
|
||||
$mail_subject,
|
||||
$mail_body,
|
||||
$mail_headers,
|
||||
$additional_headers
|
||||
);
|
||||
}
|
||||
else {
|
||||
// On Windows, PHP will use the value of sendmail_from for the
|
||||
// Return-Path header.
|
||||
$old_from = ini_get('sendmail_from');
|
||||
ini_set('sendmail_from', $message['Return-Path']);
|
||||
$mail_result = @mail(
|
||||
$message['to'],
|
||||
$mail_subject,
|
||||
$mail_body,
|
||||
$mail_headers
|
||||
);
|
||||
ini_set('sendmail_from', $old_from);
|
||||
}
|
||||
|
||||
return $mail_result;
|
||||
}
|
||||
}
|
35
core/lib/Drupal/Core/Mail/Plugin/Mail/TestMailCollector.php
Normal file
35
core/lib/Drupal/Core/Mail/Plugin/Mail/TestMailCollector.php
Normal file
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Core\Mail\Plugin\Mail\TestMailCollector.
|
||||
*/
|
||||
|
||||
namespace Drupal\Core\Mail\Plugin\Mail;
|
||||
|
||||
use Drupal\Core\Mail\MailInterface;
|
||||
|
||||
/**
|
||||
* Defines a mail backend that captures sent messages in the state system.
|
||||
*
|
||||
* This class is for running tests or for development.
|
||||
*
|
||||
* @Mail(
|
||||
* id = "test_mail_collector",
|
||||
* label = @Translation("Mail collector"),
|
||||
* description = @Translation("Does not send the message, but stores it in Drupal within the state system. Used for testing.")
|
||||
* )
|
||||
*/
|
||||
class TestMailCollector extends PhpMail implements MailInterface {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function mail(array $message) {
|
||||
$captured_emails = \Drupal::state()->get('system.test_mail_collector') ?: array();
|
||||
$captured_emails[] = $message;
|
||||
\Drupal::state()->set('system.test_mail_collector', $captured_emails);
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
}
|
Reference in a new issue