Commit cc9f167e authored by Gábor Hojtsy's avatar Gábor Hojtsy

#154218 by Steven: HTML to text email converter, centralizing email wrapping...

#154218 by Steven: HTML to text email converter, centralizing email wrapping in Drupal core and providing a solid conversion function for contributed modules
parent a9749f8b
......@@ -2253,6 +2253,7 @@ function _drupal_bootstrap_full() {
require_once './includes/unicode.inc';
require_once './includes/image.inc';
require_once './includes/form.inc';
require_once './includes/mail.inc';
// Set the Drupal custom error handler.
set_error_handler('drupal_error_handler');
// Emit the correct charset HTTP header.
......@@ -2308,99 +2309,6 @@ function page_set_cache() {
}
}
/**
* Send an e-mail message, using Drupal variables and default settings.
* More information in the <a href="http://php.net/manual/en/function.mail.php">
* PHP function reference for mail()</a>
* @param $mailkey
* A key to identify the mail sent, for altering.
* @param $to
* The mail address or addresses where the message will be send to. The
* formatting of this string must comply with RFC 2822. 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 $subject
* Subject of the e-mail to be sent. This must not contain any newline
* characters, or the mail may not be sent properly.
* @param $body
* Message to be sent. Drupal will format the correct line endings for you.
* @param $from
* Sets From, Reply-To, Return-Path and Error-To to this value, if given.
* @param $headers
* Associative array containing the headers to add. This is typically
* used to add extra headers (From, Cc, and Bcc).
* <em>When sending mail, the mail must contain a From header.</em>
* @return Returns TRUE if the mail was successfully accepted for delivery,
* FALSE otherwise.
*/
function drupal_mail($mailkey, $to, $subject, $body, $from = NULL, $headers = array()) {
$defaults = array(
'MIME-Version' => '1.0',
'Content-Type' => 'text/plain; charset=UTF-8; format=flowed',
'Content-Transfer-Encoding' => '8Bit',
'X-Mailer' => 'Drupal'
);
// To prevent e-mail from looking like spam, the addresses in the Sender and
// Return-Path headers should have a domain authorized to use the originating
// SMTP server. Errors-To is redundant, but shouldn't hurt.
$default_from = variable_get('site_mail', ini_get('sendmail_from'));
if ($default_from) {
$defaults['From'] = $defaults['Reply-To'] = $defaults['Sender'] = $defaults['Return-Path'] = $defaults['Errors-To'] = $default_from;
}
if ($from) {
$defaults['From'] = $defaults['Reply-To'] = $from;
}
$headers = array_merge($defaults, $headers);
// Bundle up the variables into a structured array for altering.
$message = array('#mail_id' => $mailkey, '#to' => $to, '#subject' => $subject, '#body' => $body, '#from' => $from, '#headers' => $headers);
drupal_alter('mail', $message);
$mailkey = $message['#mail_id'];
$to = $message['#to'];
$subject = $message['#subject'];
$body = $message['#body'];
$from = $message['#from'];
$headers = $message['#headers'];
// Allow for custom mail backend
if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
include_once './' . variable_get('smtp_library', '');
return drupal_mail_wrapper($mailkey, $to, $subject, $body, $from, $headers);
}
else {
// Note: if you are having problems with sending mail, or mails look wrong
// when they are received you may have to modify the str_replace to suit
// your systems.
// - \r\n will work under dos and windows.
// - \n will work for linux, unix and BSDs.
// - \r will work for macs.
//
// According to RFC 2646, it's quite rude to not wrap your e-mails:
//
// "The Text/Plain media type is the lowest common denominator of
// Internet e-mail, with lines of no more than 997 characters (by
// convention usually no more than 80), and where the CRLF sequence
// represents a line break [MIME-IMT]."
//
// CRLF === \r\n
//
// http://www.rfc-editor.org/rfc/rfc2646.txt
$mimeheaders = array();
foreach ($headers as $name => $value) {
$mimeheaders[] = $name .': '. mime_header_encode($value);
}
return mail(
$to,
mime_header_encode($subject),
str_replace("\r", '', $body),
join("\n", $mimeheaders)
);
}
}
/**
* Executes a cron run when called
* @return
......
<?php
// $Id$
/**
* Send an e-mail message, using Drupal variables and default settings.
* More information in the <a href="http://php.net/manual/en/function.mail.php">
* PHP function reference for mail()</a>
*
* @param $mailkey
* A key to identify the mail sent, for altering.
* @param $to
* The mail address or addresses where the message will be send to. The
* formatting of this string must comply with RFC 2822. 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 $subject
* Subject of the e-mail to be sent. This must not contain any newline
* characters, or the mail may not be sent properly.
* @param $body
* Message to be sent. Accepts both CRLF and LF line-endings.
* E-mail bodies must be wrapped. You can use drupal_wrap_mail() for
* smart plain text wrapping.
* @param $from
* Sets From, Reply-To, Return-Path and Error-To to this value, if given.
* @param $headers
* Associative array containing the headers to add. This is typically
* used to add extra headers (From, Cc, and Bcc).
* <em>When sending mail, the mail must contain a From header.</em>
* @return Returns TRUE if the mail was successfully accepted for delivery,
* FALSE otherwise.
*/
function drupal_mail($mailkey, $to, $subject, $body, $from = NULL, $headers = array()) {
$defaults = 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 e-mail from looking like spam, the addresses in the Sender and
// Return-Path headers should have a domain authorized to use the originating
// SMTP server. Errors-To is redundant, but shouldn't hurt.
$default_from = variable_get('site_mail', ini_get('sendmail_from'));
if ($default_from) {
$defaults['From'] = $defaults['Reply-To'] = $defaults['Sender'] = $defaults['Return-Path'] = $defaults['Errors-To'] = $default_from;
}
if ($from) {
$defaults['From'] = $defaults['Reply-To'] = $from;
}
$headers = array_merge($defaults, $headers);
// Bundle up the variables into a structured array for altering.
$message = array('#mail_id' => $mailkey, '#to' => $to, '#subject' => $subject, '#body' => $body, '#from' => $from, '#headers' => $headers);
drupal_alter('mail', $message);
$mailkey = $message['#mail_id'];
$to = $message['#to'];
$subject = $message['#subject'];
$body = $message['#body'];
$from = $message['#from'];
$headers = $message['#headers'];
// Allow for custom mail backend
if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
include_once './' . variable_get('smtp_library', '');
return drupal_mail_wrapper($mailkey, $to, $subject, $body, $from, $headers);
}
else {
// Note: e-mail uses CRLF for line-endings, but PHP's API requires LF.
// They will appear correctly in the actual e-mail that is sent.
$mimeheaders = array();
foreach ($headers as $name => $value) {
$mimeheaders[] = $name .': '. mime_header_encode($value);
}
return mail(
$to,
mime_header_encode($subject),
str_replace("\r", '', $body),
join("\n", $mimeheaders)
);
}
}
/**
* Perform 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 drupal_mail().
*
* @param $text
* The plain text to process.
* @param $indent (optional)
* A string to indent the text with. Only '>' characters are repeated on
* subsequent wrapped lines. Others are replaced by spaces.
*/
function drupal_wrap_mail($text, $indent = '') {
// Convert CRLF into LF.
$text = str_replace("\r", '', $text);
// See if soft-wrapping is allowed.
$clean_indent = _drupal_html_to_text_clean($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.
$text = preg_replace('/ +\n/m', "\n", $text);
// Wrap each line at the needed width.
$lines = explode("\n", $text);
array_walk($lines, '_drupal_wrap_mail_line', array('soft' => $soft, 'length' => strlen($indent)));
$text = implode("\n", $lines);
}
else {
// Wrap this line.
_drupal_wrap_mail_line($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;
}
/**
* Transform an HTML string into plain text, preserving the structure of the
* markup. Useful for preparing the body of a node to be sent by email.
*
* The output will be suitable for use as 'format=flowed; delsp=yes' text
* (RFC 3676) and can be passed directly to drupal_mail() for sending.
*
* We deliberately use LF rather than CRLF, see drupal_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
* The string to be transformed.
* @param $allowed_tags (optional)
* If supplied, a list of tags that will be transformed. If omitted, all
* all supported tags are transformed.
* @return
* The transformed string.
*/
function drupal_html_to_text($string, $allowed_tags = NULL) {
// Cache list of supported tags.
static $supported_tags;
if (empty($supported_tags)) {
$supported_tags = 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($supported_tags, $allowed_tags) : $supported_tags;
// Make sure tags, entities and attributes are well-formed and properly nested.
$string = _filter_htmlcorrector(filter_xss($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="http://drupal.org">the Drupal site</a>' becomes
// 'See the Drupal site [1]' with the URL included as a footnote.
$pattern = '@(<a[^>]+?href="([^"]*)">(.+?)</a>)@i';
$string = preg_replace_callback($pattern, '_drupal_html_to_mail_urls', $string);
$urls = _drupal_html_to_mail_urls();
$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).
$tag = FALSE; // Odd/even counter (tag or no tag)
$casing = NULL; // Case conversion function
$output = '';
$indent = array(); // All current indentation string chunks
$lists = array(); // Array of counters for opened lists
foreach ($split as $value) {
$chunk = NULL; // Holds a string ready to be formatted and output.
// 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);
$chunk = ''; // Ensure blank new-line.
break;
// Quotation/list markers, non-fancy headers
case 'blockquote':
// Format=flowed indentation cannot be mixed with lists.
$indent[] = count($lists) ? ' "' : '>';
break;
case 'li':
$indent[] = 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";
$chunk = ''; // Ensure blank new-line.
}
// Fall-through
case '/li':
case '/dd':
array_pop($indent);
break;
case '/h3':
case '/h4':
array_pop($indent);
case '/h5':
case '/h6':
$chunk = ''; // Ensure blank new-line.
break;
// Fancy headers
case 'h1':
$indent[] = '======== ';
$casing = 'drupal_strtoupper';
break;
case 'h2':
$indent[] = '-------- ';
$casing = 'drupal_strtoupper';
break;
case '/h1':
case '/h2':
$casing = NULL;
// Pad the line with dashes.
$output = _drupal_html_to_text_pad($output, ($tagname == '/h1') ? '=' : '-', ' ');
array_pop($indent);
$chunk = ''; // Ensure blank new-line.
break;
// Horizontal rulers
case 'hr':
// Insert immediately.
$output .= drupal_wrap_mail('', implode('', $indent)) ."\n";
$output = _drupal_html_to_text_pad($output, '-');
break;
// Paragraphs and definition lists
case '/p':
case '/dl':
$chunk = ''; // Ensure blank new-line.
break;
}
}
// Process blocks of text.
else {
// Convert inline HTML text to plain text.
$value = trim(preg_replace('/\s+/', ' ', decode_entities($value)));
if (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 = $casing($chunk);
}
// Format it and apply the current indentation.
$output .= drupal_wrap_mail($chunk, implode('', $indent)) ."\n";
// Remove non-quotation markers from indentation.
$indent = array_map('_drupal_html_to_text_clean', $indent);
}
$tag = !$tag;
}
return $output . $footnotes;
}
/**
* Helper function for array_walk in drupal_wrap_mail().
*
* Wraps words on a single line.
*/
function _drupal_wrap_mail_line(&$line, $key, $values) {
// 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");
}
/**
* Helper function for drupal_html_to_text().
*
* Keeps track of URLs and replaces them with placeholder tokens.
*/
function _drupal_html_to_mail_urls($match = NULL) {
global $base_url, $base_path;
static $urls = array(), $regexp;
if (empty($regexp)) {
$regexp = '@^'. preg_quote($base_path, '@') .'@';
}
if ($match) {
list(,, $url, $label) = $match;
// Ensure all URLs are absolute.
$urls[] = strpos($url, '://') ? $url : preg_replace($regexp, $base_url .'/', $url);
return $label .' ['. count($urls) .']';
}
return $urls;
}
/**
* Helper function for drupal_wrap_mail() and drupal_html_to_text().
*
* Replace all non-quotation markers from a given piece of indentation with spaces.
*/
function _drupal_html_to_text_clean($indent) {
return preg_replace('/[^>]/', ' ', $indent);
}
/**
* Helper function for drupal_html_to_text().
*
* Pad the last line with the given character.
*/
function _drupal_html_to_text_pad($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));
// Add prefix and padding, and restore linebreak.
return $text . $prefix . str_repeat($pad, $n - strlen($prefix)) ."\n";
}
......@@ -370,11 +370,6 @@ function contact_mail_user_submit($form, &$form_state) {
$message[] = t('Message:');
$message[] = $form_state['values']['message'];
// Tidy up the body:
foreach ($message as $key => $value) {
$message[$key] = wordwrap($value);
}
// Prepare all fields:
$to = $account->mail;
$from = $user->mail;
......@@ -383,7 +378,7 @@ function contact_mail_user_submit($form, &$form_state) {
$subject = '['. variable_get('site_name', 'Drupal') .'] '. $form_state['values']['subject'];
// Prepare the body:
$body = implode("\n\n", $message);
$body = drupal_wrap_mail(implode("\n\n", $message));
// Send the e-mail:
drupal_mail('contact-user-mail', $to, $subject, $body, $from);
......@@ -518,11 +513,6 @@ function contact_mail_page_submit($form, &$form_state) {
$message[] = t("!name sent a message using the contact form at !form.", array('!name' => $form_state['values']['name'], '!form' => url($_GET['q'], array('absolute' => TRUE))));
$message[] = $form_state['values']['message'];
// Tidy up the body:
foreach ($message as $key => $value) {
$message[$key] = wordwrap($value);
}
// Load the category information:
$contact = db_fetch_object(db_query("SELECT * FROM {contact} WHERE cid = %d", $form_state['values']['cid']));
......@@ -530,7 +520,7 @@ function contact_mail_page_submit($form, &$form_state) {
$subject = t('[!category] !subject', array('!category' => $contact->category, '!subject' => $form_state['values']['subject']));
// Prepare the body:
$body = implode("\n\n", $message);
$body = drupal_wrap_mail(implode("\n\n", $message));
// Send the e-mail to the recipients:
drupal_mail('contact-page-mail', $contact->recipients, $subject, $body, $from);
......@@ -542,7 +532,7 @@ function contact_mail_page_submit($form, &$form_state) {
// Send an auto-reply if necessary:
if ($contact->reply) {
drupal_mail('contact-page-autoreply', $from, $subject, wordwrap($contact->reply), $contact->recipients);
drupal_mail('contact-page-autoreply', $from, $subject, drupal_wrap_mail($contact->reply), $contact->recipients);
}
// Log the operation:
......
......@@ -3157,7 +3157,7 @@ function _user_mail_notify($op, $account, $password = NULL) {
$from = variable_get('site_mail', ini_get('sendmail_from'));
$variables = user_mail_tokens($account, $password);
$subject = _user_mail_text($op .'_subject', $variables);
$body = _user_mail_text($op .'_body', $variables);
$body = drupal_wrap_mail(_user_mail_text($op .'_body', $variables));
$result = drupal_mail($mail_id, $account->mail, $subject, $body, $from);
if ($op == 'register_pending_approval') {
// If a user registered requiring admin approval, notify the admin, too.
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment