1 | <?php |
---|
2 | |
---|
3 | /** |
---|
4 | * Compose and optionally send an e-mail message. |
---|
5 | * |
---|
6 | * Sending an e-mail works with defining an e-mail template (subject, text |
---|
7 | * and possibly e-mail headers) and the replacement values to use in the |
---|
8 | * appropriate places in the template. Processed e-mail templates are |
---|
9 | * requested from hook_mail() from the module sending the e-mail. Any module |
---|
10 | * can modify the composed e-mail message array using hook_mail_alter(). |
---|
11 | * Finally drupal_mail_send() sends the e-mail, which can be reused |
---|
12 | * if the exact same composed e-mail is to be sent to multiple recipients. |
---|
13 | * |
---|
14 | * Finding out what language to send the e-mail with needs some consideration. |
---|
15 | * If you send e-mail to a user, her preferred language should be fine, so |
---|
16 | * use user_preferred_language(). If you send email based on form values |
---|
17 | * filled on the page, there are two additional choices if you are not |
---|
18 | * sending the e-mail to a user on the site. You can either use the language |
---|
19 | * used to generate the page ($language global variable) or the site default |
---|
20 | * language. See language_default(). The former is good if sending e-mail to |
---|
21 | * the person filling the form, the later is good if you send e-mail to an |
---|
22 | * address previously set up (like contact addresses in a contact form). |
---|
23 | * |
---|
24 | * Taking care of always using the proper language is even more important |
---|
25 | * when sending e-mails in a row to multiple users. Hook_mail() abstracts |
---|
26 | * whether the mail text comes from an administrator setting or is |
---|
27 | * static in the source code. It should also deal with common mail tokens, |
---|
28 | * only receiving $params which are unique to the actual e-mail at hand. |
---|
29 | * |
---|
30 | * An example: |
---|
31 | * |
---|
32 | * @code |
---|
33 | * function example_notify($accounts) { |
---|
34 | * foreach ($accounts as $account) { |
---|
35 | * $params['account'] = $account; |
---|
36 | * // example_mail() will be called based on the first drupal_mail() parameter. |
---|
37 | * drupal_mail('example', 'notice', $account->mail, user_preferred_language($account), $params); |
---|
38 | * } |
---|
39 | * } |
---|
40 | * |
---|
41 | * function example_mail($key, &$message, $params) { |
---|
42 | * $language = $message['language']; |
---|
43 | * $variables = user_mail_tokens($params['account'], $language); |
---|
44 | * switch($key) { |
---|
45 | * case 'notice': |
---|
46 | * $message['subject'] = t('Notification from !site', $variables, $language->language); |
---|
47 | * $message['body'][] = t("Dear !username\n\nThere is new content available on the site.", $variables, $language->language); |
---|
48 | * break; |
---|
49 | * } |
---|
50 | * } |
---|
51 | * @endcode |
---|
52 | * |
---|
53 | * @param $module |
---|
54 | * A module name to invoke hook_mail() on. The {$module}_mail() hook will be |
---|
55 | * called to complete the $message structure which will already contain common |
---|
56 | * defaults. |
---|
57 | * @param $key |
---|
58 | * A key to identify the e-mail sent. The final e-mail id for e-mail altering |
---|
59 | * will be {$module}_{$key}. |
---|
60 | * @param $to |
---|
61 | * The e-mail address or addresses where the message will be sent to. The |
---|
62 | * formatting of this string must comply with |
---|
63 | * @link http://tools.ietf.org/html/rfc5322 RFC 5322 @endlink. |
---|
64 | * Some examples are: |
---|
65 | * - user@example.com |
---|
66 | * - user@example.com, anotheruser@example.com |
---|
67 | * - User <user@example.com> |
---|
68 | * - User <user@example.com>, Another User <anotheruser@example.com> |
---|
69 | * @param $language |
---|
70 | * Language object to use to compose the e-mail. |
---|
71 | * @param $params |
---|
72 | * Optional parameters to build the e-mail. |
---|
73 | * @param $from |
---|
74 | * Sets From to this value, if given. |
---|
75 | * @param $send |
---|
76 | * Send the message directly, without calling drupal_mail_send() manually. |
---|
77 | * |
---|
78 | * @return |
---|
79 | * The $message array structure containing all details of the |
---|
80 | * message. If already sent ($send = TRUE), then the 'result' element |
---|
81 | * will contain the success indicator of the e-mail, failure being already |
---|
82 | * written to the watchdog. (Success means nothing more than the message being |
---|
83 | * accepted at php-level, which still doesn't guarantee it to be delivered.) |
---|
84 | */ |
---|
85 | function drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) { |
---|
86 | $default_from = variable_get('site_mail', ini_get('sendmail_from')); |
---|
87 | |
---|
88 | // Bundle up the variables into a structured array for altering. |
---|
89 | $message = array( |
---|
90 | 'id' => $module .'_'. $key, |
---|
91 | 'to' => $to, |
---|
92 | 'from' => isset($from) ? $from : $default_from, |
---|
93 | 'language' => $language, |
---|
94 | 'params' => $params, |
---|
95 | 'subject' => '', |
---|
96 | 'body' => array() |
---|
97 | ); |
---|
98 | |
---|
99 | // Build the default headers |
---|
100 | $headers = array( |
---|
101 | 'MIME-Version' => '1.0', |
---|
102 | 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', |
---|
103 | 'Content-Transfer-Encoding' => '8Bit', |
---|
104 | 'X-Mailer' => 'Drupal' |
---|
105 | ); |
---|
106 | if ($default_from) { |
---|
107 | // To prevent e-mail from looking like spam, the addresses in the Sender and |
---|
108 | // Return-Path headers should have a domain authorized to use the originating |
---|
109 | // SMTP server. Errors-To is redundant, but shouldn't hurt. |
---|
110 | $headers['From'] = $headers['Sender'] = $headers['Return-Path'] = $headers['Errors-To'] = $default_from; |
---|
111 | } |
---|
112 | if ($from) { |
---|
113 | $headers['From'] = $from; |
---|
114 | } |
---|
115 | $message['headers'] = $headers; |
---|
116 | |
---|
117 | // Build the e-mail (get subject and body, allow additional headers) by |
---|
118 | // invoking hook_mail() on this module. We cannot use module_invoke() as |
---|
119 | // we need to have $message by reference in hook_mail(). |
---|
120 | if (function_exists($function = $module .'_mail')) { |
---|
121 | $function($key, $message, $params); |
---|
122 | } |
---|
123 | |
---|
124 | // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail. |
---|
125 | drupal_alter('mail', $message); |
---|
126 | |
---|
127 | // Concatenate and wrap the e-mail body. |
---|
128 | $message['body'] = is_array($message['body']) ? drupal_wrap_mail(implode("\n\n", $message['body'])) : drupal_wrap_mail($message['body']); |
---|
129 | |
---|
130 | // Optionally send e-mail. |
---|
131 | if ($send) { |
---|
132 | $message['result'] = drupal_mail_send($message); |
---|
133 | |
---|
134 | // Log errors |
---|
135 | if (!$message['result']) { |
---|
136 | watchdog('mail', 'Error sending e-mail (from %from to %to).', array('%from' => $message['from'], '%to' => $message['to']), WATCHDOG_ERROR); |
---|
137 | drupal_set_message(t('Unable to send e-mail. Please contact the site administrator if the problem persists.'), 'error'); |
---|
138 | } |
---|
139 | } |
---|
140 | |
---|
141 | return $message; |
---|
142 | } |
---|
143 | |
---|
144 | /** |
---|
145 | * Send an e-mail message, using Drupal variables and default settings. |
---|
146 | * More information in the <a href="http://php.net/manual/en/function.mail.php"> |
---|
147 | * PHP function reference for mail()</a>. See drupal_mail() for information on |
---|
148 | * how $message is composed. |
---|
149 | * |
---|
150 | * @param $message |
---|
151 | * Message array with at least the following elements: |
---|
152 | * - id: A unique identifier of the e-mail type. Examples: |
---|
153 | * 'contact_user_copy', 'user_password_reset'. |
---|
154 | * - to: The mail address or addresses where the message will be sent to. The |
---|
155 | * formatting of this string must comply with |
---|
156 | * @link http://tools.ietf.org/html/rfc5322 RFC 5322 @endlink. |
---|
157 | * Some examples are: |
---|
158 | * - user@example.com |
---|
159 | * - user@example.com, anotheruser@example.com |
---|
160 | * - User <user@example.com> |
---|
161 | * - User <user@example.com>, Another User <anotheruser@example.com> |
---|
162 | * - subject: Subject of the e-mail to be sent. This must not contain any |
---|
163 | * newline characters, or the mail may not be sent properly. |
---|
164 | * - body: Message to be sent. Accepts both CRLF and LF line-endings. |
---|
165 | * E-mail bodies must be wrapped. You can use drupal_wrap_mail() for |
---|
166 | * smart plain text wrapping. |
---|
167 | * - headers: Associative array containing all mail headers. |
---|
168 | * |
---|
169 | * @return |
---|
170 | * Returns TRUE if the mail was successfully accepted for delivery, |
---|
171 | * FALSE otherwise. |
---|
172 | */ |
---|
173 | function drupal_mail_send($message) { |
---|
174 | // Allow for a custom mail backend. |
---|
175 | if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) { |
---|
176 | include_once './'. variable_get('smtp_library', ''); |
---|
177 | return drupal_mail_wrapper($message); |
---|
178 | } |
---|
179 | else { |
---|
180 | $mimeheaders = array(); |
---|
181 | foreach ($message['headers'] as $name => $value) { |
---|
182 | $mimeheaders[] = $name .': '. mime_header_encode($value); |
---|
183 | } |
---|
184 | return mail( |
---|
185 | $message['to'], |
---|
186 | mime_header_encode($message['subject']), |
---|
187 | // Note: e-mail uses CRLF for line-endings, but PHP's API requires LF. |
---|
188 | // They will appear correctly in the actual e-mail that is sent. |
---|
189 | str_replace("\r", '', $message['body']), |
---|
190 | // For headers, PHP's API suggests that we use CRLF normally, |
---|
191 | // but some MTAs incorrecly replace LF with CRLF. See #234403. |
---|
192 | join("\n", $mimeheaders) |
---|
193 | ); |
---|
194 | } |
---|
195 | } |
---|
196 | |
---|
197 | /** |
---|
198 | * Perform format=flowed soft wrapping for mail (RFC 3676). |
---|
199 | * |
---|
200 | * We use delsp=yes wrapping, but only break non-spaced languages when |
---|
201 | * absolutely necessary to avoid compatibility issues. |
---|
202 | * |
---|
203 | * We deliberately use LF rather than CRLF, see drupal_mail(). |
---|
204 | * |
---|
205 | * @param $text |
---|
206 | * The plain text to process. |
---|
207 | * @param $indent (optional) |
---|
208 | * A string to indent the text with. Only '>' characters are repeated on |
---|
209 | * subsequent wrapped lines. Others are replaced by spaces. |
---|
210 | */ |
---|
211 | function drupal_wrap_mail($text, $indent = '') { |
---|
212 | // Convert CRLF into LF. |
---|
213 | $text = str_replace("\r", '', $text); |
---|
214 | // See if soft-wrapping is allowed. |
---|
215 | $clean_indent = _drupal_html_to_text_clean($indent); |
---|
216 | $soft = strpos($clean_indent, ' ') === FALSE; |
---|
217 | // Check if the string has line breaks. |
---|
218 | if (strpos($text, "\n") !== FALSE) { |
---|
219 | // Remove trailing spaces to make existing breaks hard. |
---|
220 | $text = preg_replace('/ +\n/m', "\n", $text); |
---|
221 | // Wrap each line at the needed width. |
---|
222 | $lines = explode("\n", $text); |
---|
223 | array_walk($lines, '_drupal_wrap_mail_line', array('soft' => $soft, 'length' => strlen($indent))); |
---|
224 | $text = implode("\n", $lines); |
---|
225 | } |
---|
226 | else { |
---|
227 | // Wrap this line. |
---|
228 | _drupal_wrap_mail_line($text, 0, array('soft' => $soft, 'length' => strlen($indent))); |
---|
229 | } |
---|
230 | // Empty lines with nothing but spaces. |
---|
231 | $text = preg_replace('/^ +\n/m', "\n", $text); |
---|
232 | // Space-stuff special lines. |
---|
233 | $text = preg_replace('/^(>| |From)/m', ' $1', $text); |
---|
234 | // Apply indentation. We only include non-'>' indentation on the first line. |
---|
235 | $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent)); |
---|
236 | |
---|
237 | return $text; |
---|
238 | } |
---|
239 | |
---|
240 | /** |
---|
241 | * Transform an HTML string into plain text, preserving the structure of the |
---|
242 | * markup. Useful for preparing the body of a node to be sent by e-mail. |
---|
243 | * |
---|
244 | * The output will be suitable for use as 'format=flowed; delsp=yes' text |
---|
245 | * (RFC 3676) and can be passed directly to drupal_mail() for sending. |
---|
246 | * |
---|
247 | * We deliberately use LF rather than CRLF, see drupal_mail(). |
---|
248 | * |
---|
249 | * This function provides suitable alternatives for the following tags: |
---|
250 | * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt> |
---|
251 | * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr> |
---|
252 | * |
---|
253 | * @param $string |
---|
254 | * The string to be transformed. |
---|
255 | * @param $allowed_tags (optional) |
---|
256 | * If supplied, a list of tags that will be transformed. If omitted, all |
---|
257 | * all supported tags are transformed. |
---|
258 | * |
---|
259 | * @return |
---|
260 | * The transformed string. |
---|
261 | */ |
---|
262 | function drupal_html_to_text($string, $allowed_tags = NULL) { |
---|
263 | // Cache list of supported tags. |
---|
264 | static $supported_tags; |
---|
265 | if (empty($supported_tags)) { |
---|
266 | $supported_tags = array('a', 'em', 'i', 'strong', 'b', 'br', 'p', 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr'); |
---|
267 | } |
---|
268 | |
---|
269 | // Make sure only supported tags are kept. |
---|
270 | $allowed_tags = isset($allowed_tags) ? array_intersect($supported_tags, $allowed_tags) : $supported_tags; |
---|
271 | |
---|
272 | // Make sure tags, entities and attributes are well-formed and properly nested. |
---|
273 | $string = _filter_htmlcorrector(filter_xss($string, $allowed_tags)); |
---|
274 | |
---|
275 | // Apply inline styles. |
---|
276 | $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string); |
---|
277 | $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string); |
---|
278 | |
---|
279 | // Replace inline <a> tags with the text of link and a footnote. |
---|
280 | // 'See <a href="http://drupal.org">the Drupal site</a>' becomes |
---|
281 | // 'See the Drupal site [1]' with the URL included as a footnote. |
---|
282 | _drupal_html_to_mail_urls(NULL, TRUE); |
---|
283 | $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i'; |
---|
284 | $string = preg_replace_callback($pattern, '_drupal_html_to_mail_urls', $string); |
---|
285 | $urls = _drupal_html_to_mail_urls(); |
---|
286 | $footnotes = ''; |
---|
287 | if (count($urls)) { |
---|
288 | $footnotes .= "\n"; |
---|
289 | for ($i = 0, $max = count($urls); $i < $max; $i++) { |
---|
290 | $footnotes .= '['. ($i + 1) .'] '. $urls[$i] ."\n"; |
---|
291 | } |
---|
292 | } |
---|
293 | |
---|
294 | // Split tags from text. |
---|
295 | $split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE); |
---|
296 | // Note: PHP ensures the array consists of alternating delimiters and literals |
---|
297 | // and begins and ends with a literal (inserting $null as required). |
---|
298 | |
---|
299 | $tag = FALSE; // Odd/even counter (tag or no tag) |
---|
300 | $casing = NULL; // Case conversion function |
---|
301 | $output = ''; |
---|
302 | $indent = array(); // All current indentation string chunks |
---|
303 | $lists = array(); // Array of counters for opened lists |
---|
304 | foreach ($split as $value) { |
---|
305 | $chunk = NULL; // Holds a string ready to be formatted and output. |
---|
306 | |
---|
307 | // Process HTML tags (but don't output any literally). |
---|
308 | if ($tag) { |
---|
309 | list($tagname) = explode(' ', strtolower($value), 2); |
---|
310 | switch ($tagname) { |
---|
311 | // List counters |
---|
312 | case 'ul': |
---|
313 | array_unshift($lists, '*'); |
---|
314 | break; |
---|
315 | case 'ol': |
---|
316 | array_unshift($lists, 1); |
---|
317 | break; |
---|
318 | case '/ul': |
---|
319 | case '/ol': |
---|
320 | array_shift($lists); |
---|
321 | $chunk = ''; // Ensure blank new-line. |
---|
322 | break; |
---|
323 | |
---|
324 | // Quotation/list markers, non-fancy headers |
---|
325 | case 'blockquote': |
---|
326 | // Format=flowed indentation cannot be mixed with lists. |
---|
327 | $indent[] = count($lists) ? ' "' : '>'; |
---|
328 | break; |
---|
329 | case 'li': |
---|
330 | $indent[] = is_numeric($lists[0]) ? ' '. $lists[0]++ .') ' : ' * '; |
---|
331 | break; |
---|
332 | case 'dd': |
---|
333 | $indent[] = ' '; |
---|
334 | break; |
---|
335 | case 'h3': |
---|
336 | $indent[] = '.... '; |
---|
337 | break; |
---|
338 | case 'h4': |
---|
339 | $indent[] = '.. '; |
---|
340 | break; |
---|
341 | case '/blockquote': |
---|
342 | if (count($lists)) { |
---|
343 | // Append closing quote for inline quotes (immediately). |
---|
344 | $output = rtrim($output, "> \n") ."\"\n"; |
---|
345 | $chunk = ''; // Ensure blank new-line. |
---|
346 | } |
---|
347 | // Fall-through |
---|
348 | case '/li': |
---|
349 | case '/dd': |
---|
350 | array_pop($indent); |
---|
351 | break; |
---|
352 | case '/h3': |
---|
353 | case '/h4': |
---|
354 | array_pop($indent); |
---|
355 | case '/h5': |
---|
356 | case '/h6': |
---|
357 | $chunk = ''; // Ensure blank new-line. |
---|
358 | break; |
---|
359 | |
---|
360 | // Fancy headers |
---|
361 | case 'h1': |
---|
362 | $indent[] = '======== '; |
---|
363 | $casing = 'drupal_strtoupper'; |
---|
364 | break; |
---|
365 | case 'h2': |
---|
366 | $indent[] = '-------- '; |
---|
367 | $casing = 'drupal_strtoupper'; |
---|
368 | break; |
---|
369 | case '/h1': |
---|
370 | case '/h2': |
---|
371 | $casing = NULL; |
---|
372 | // Pad the line with dashes. |
---|
373 | $output = _drupal_html_to_text_pad($output, ($tagname == '/h1') ? '=' : '-', ' '); |
---|
374 | array_pop($indent); |
---|
375 | $chunk = ''; // Ensure blank new-line. |
---|
376 | break; |
---|
377 | |
---|
378 | // Horizontal rulers |
---|
379 | case 'hr': |
---|
380 | // Insert immediately. |
---|
381 | $output .= drupal_wrap_mail('', implode('', $indent)) ."\n"; |
---|
382 | $output = _drupal_html_to_text_pad($output, '-'); |
---|
383 | break; |
---|
384 | |
---|
385 | // Paragraphs and definition lists |
---|
386 | case '/p': |
---|
387 | case '/dl': |
---|
388 | $chunk = ''; // Ensure blank new-line. |
---|
389 | break; |
---|
390 | } |
---|
391 | } |
---|
392 | // Process blocks of text. |
---|
393 | else { |
---|
394 | // Convert inline HTML text to plain text. |
---|
395 | $value = trim(preg_replace('/\s+/', ' ', decode_entities($value))); |
---|
396 | if (strlen($value)) { |
---|
397 | $chunk = $value; |
---|
398 | } |
---|
399 | } |
---|
400 | |
---|
401 | // See if there is something waiting to be output. |
---|
402 | if (isset($chunk)) { |
---|
403 | // Apply any necessary case conversion. |
---|
404 | if (isset($casing)) { |
---|
405 | $chunk = $casing($chunk); |
---|
406 | } |
---|
407 | // Format it and apply the current indentation. |
---|
408 | $output .= drupal_wrap_mail($chunk, implode('', $indent)) ."\n"; |
---|
409 | // Remove non-quotation markers from indentation. |
---|
410 | $indent = array_map('_drupal_html_to_text_clean', $indent); |
---|
411 | } |
---|
412 | |
---|
413 | $tag = !$tag; |
---|
414 | } |
---|
415 | |
---|
416 | return $output . $footnotes; |
---|
417 | } |
---|
418 | |
---|
419 | /** |
---|
420 | * Helper function for array_walk in drupal_wrap_mail(). |
---|
421 | * |
---|
422 | * Wraps words on a single line. |
---|
423 | */ |
---|
424 | function _drupal_wrap_mail_line(&$line, $key, $values) { |
---|
425 | // Use soft-breaks only for purely quoted or unindented text. |
---|
426 | $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n"); |
---|
427 | // Break really long words at the maximum width allowed. |
---|
428 | $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n"); |
---|
429 | } |
---|
430 | |
---|
431 | /** |
---|
432 | * Helper function for drupal_html_to_text(). |
---|
433 | * |
---|
434 | * Keeps track of URLs and replaces them with placeholder tokens. |
---|
435 | */ |
---|
436 | function _drupal_html_to_mail_urls($match = NULL, $reset = FALSE) { |
---|
437 | global $base_url, $base_path; |
---|
438 | static $urls = array(), $regexp; |
---|
439 | |
---|
440 | if ($reset) { |
---|
441 | // Reset internal URL list. |
---|
442 | $urls = array(); |
---|
443 | } |
---|
444 | else { |
---|
445 | if (empty($regexp)) { |
---|
446 | $regexp = '@^'. preg_quote($base_path, '@') .'@'; |
---|
447 | } |
---|
448 | if ($match) { |
---|
449 | list(, , $url, $label) = $match; |
---|
450 | // Ensure all URLs are absolute. |
---|
451 | $urls[] = strpos($url, '://') ? $url : preg_replace($regexp, $base_url .'/', $url); |
---|
452 | return $label .' ['. count($urls) .']'; |
---|
453 | } |
---|
454 | } |
---|
455 | return $urls; |
---|
456 | } |
---|
457 | |
---|
458 | /** |
---|
459 | * Helper function for drupal_wrap_mail() and drupal_html_to_text(). |
---|
460 | * |
---|
461 | * Replace all non-quotation markers from a given piece of indentation with spaces. |
---|
462 | */ |
---|
463 | function _drupal_html_to_text_clean($indent) { |
---|
464 | return preg_replace('/[^>]/', ' ', $indent); |
---|
465 | } |
---|
466 | |
---|
467 | /** |
---|
468 | * Helper function for drupal_html_to_text(). |
---|
469 | * |
---|
470 | * Pad the last line with the given character. |
---|
471 | */ |
---|
472 | function _drupal_html_to_text_pad($text, $pad, $prefix = '') { |
---|
473 | // Remove last line break. |
---|
474 | $text = substr($text, 0, -1); |
---|
475 | // Calculate needed padding space and add it. |
---|
476 | if (($p = strrpos($text, "\n")) === FALSE) { |
---|
477 | $p = -1; |
---|
478 | } |
---|
479 | $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix)); |
---|
480 | // Add prefix and padding, and restore linebreak. |
---|
481 | return $text . $prefix . str_repeat($pad, $n) ."\n"; |
---|
482 | } |
---|