mail.inc

  1. 7.x drupal-7.x/includes/mail.inc
  2. 6.x drupal-6.x/includes/mail.inc

File

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