mail.inc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. <?php
  2. /**
  3. * @file
  4. * API functions for processing and sending e-mail.
  5. */
  6. /**
  7. * Auto-detect appropriate line endings for e-mails.
  8. *
  9. * $conf['mail_line_endings'] will override this setting.
  10. */
  11. define('MAIL_LINE_ENDINGS', isset($_SERVER['WINDIR']) || (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Win32') !== FALSE) ? "\r\n" : "\n");
  12. /**
  13. * Special characters, defined in RFC_2822.
  14. */
  15. define('MAIL_RFC_2822_SPECIALS', '()<>[]:;@\,."');
  16. /**
  17. * Composes and optionally sends an e-mail message.
  18. *
  19. * Sending an e-mail works with defining an e-mail template (subject, text
  20. * and possibly e-mail headers) and the replacement values to use in the
  21. * appropriate places in the template. Processed e-mail templates are
  22. * requested from hook_mail() from the module sending the e-mail. Any module
  23. * can modify the composed e-mail message array using hook_mail_alter().
  24. * Finally drupal_mail_system()->mail() sends the e-mail, which can
  25. * be reused if the exact same composed e-mail is to be sent to multiple
  26. * recipients.
  27. *
  28. * Finding out what language to send the e-mail with needs some consideration.
  29. * If you send e-mail to a user, her preferred language should be fine, so
  30. * use user_preferred_language(). If you send email based on form values
  31. * filled on the page, there are two additional choices if you are not
  32. * sending the e-mail to a user on the site. You can either use the language
  33. * used to generate the page ($language global variable) or the site default
  34. * language. See language_default(). The former is good if sending e-mail to
  35. * the person filling the form, the later is good if you send e-mail to an
  36. * address previously set up (like contact addresses in a contact form).
  37. *
  38. * Taking care of always using the proper language is even more important
  39. * when sending e-mails in a row to multiple users. Hook_mail() abstracts
  40. * whether the mail text comes from an administrator setting or is
  41. * static in the source code. It should also deal with common mail tokens,
  42. * only receiving $params which are unique to the actual e-mail at hand.
  43. *
  44. * An example:
  45. *
  46. * @code
  47. * function example_notify($accounts) {
  48. * foreach ($accounts as $account) {
  49. * $params['account'] = $account;
  50. * // example_mail() will be called based on the first drupal_mail() parameter.
  51. * drupal_mail('example', 'notice', $account->mail, user_preferred_language($account), $params);
  52. * }
  53. * }
  54. *
  55. * function example_mail($key, &$message, $params) {
  56. * $data['user'] = $params['account'];
  57. * $options['language'] = $message['language'];
  58. * user_mail_tokens($variables, $data, $options);
  59. * switch($key) {
  60. * case 'notice':
  61. * // If the recipient can receive such notices by instant-message, do
  62. * // not send by email.
  63. * if (example_im_send($key, $message, $params)) {
  64. * $message['send'] = FALSE;
  65. * break;
  66. * }
  67. * $langcode = $message['language']->language;
  68. * $message['subject'] = t('Notification from !site', $variables, array('langcode' => $langcode));
  69. * $message['body'][] = t("Dear !username\n\nThere is new content available on the site.", $variables, array('langcode' => $langcode));
  70. * break;
  71. * }
  72. * }
  73. * @endcode
  74. *
  75. * Another example, which uses drupal_mail() to format a message for sending
  76. * later:
  77. *
  78. * @code
  79. * $params = array('current_conditions' => $data);
  80. * $to = 'user@example.com';
  81. * $message = drupal_mail('example', 'notice', $to, $language, $params, FALSE);
  82. * // Only add to the spool if sending was not canceled.
  83. * if ($message['send']) {
  84. * example_spool_message($message);
  85. * }
  86. * @endcode
  87. *
  88. * @param $module
  89. * A module name to invoke hook_mail() on. The {$module}_mail() hook will be
  90. * called to complete the $message structure which will already contain common
  91. * defaults.
  92. * @param $key
  93. * A key to identify the e-mail sent. The final e-mail id for e-mail altering
  94. * will be {$module}_{$key}.
  95. * @param $to
  96. * The e-mail address or addresses where the message will be sent to. The
  97. * formatting of this string will be validated with the
  98. * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
  99. * Some examples are:
  100. * - user@example.com
  101. * - user@example.com, anotheruser@example.com
  102. * - User <user@example.com>
  103. * - User <user@example.com>, Another User <anotheruser@example.com>
  104. * @param $language
  105. * Language object to use to compose the e-mail.
  106. * @param $params
  107. * Optional parameters to build the e-mail.
  108. * @param $from
  109. * Sets From to this value, if given.
  110. * @param $send
  111. * If TRUE, drupal_mail() will call drupal_mail_system()->mail() to deliver
  112. * the message, and store the result in $message['result']. Modules
  113. * implementing hook_mail_alter() may cancel sending by setting
  114. * $message['send'] to FALSE.
  115. *
  116. * @return
  117. * The $message array structure containing all details of the
  118. * message. If already sent ($send = TRUE), then the 'result' element
  119. * will contain the success indicator of the e-mail, failure being already
  120. * written to the watchdog. (Success means nothing more than the message being
  121. * accepted at php-level, which still doesn't guarantee it to be delivered.)
  122. */
  123. function drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) {
  124. $default_from = variable_get('site_mail', ini_get('sendmail_from'));
  125. // Bundle up the variables into a structured array for altering.
  126. $message = array(
  127. 'id' => $module . '_' . $key,
  128. 'module' => $module,
  129. 'key' => $key,
  130. 'to' => $to,
  131. 'from' => isset($from) ? $from : $default_from,
  132. 'language' => $language,
  133. 'params' => $params,
  134. 'send' => TRUE,
  135. 'subject' => '',
  136. 'body' => array()
  137. );
  138. // Build the default headers
  139. $headers = array(
  140. 'MIME-Version' => '1.0',
  141. 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
  142. 'Content-Transfer-Encoding' => '8Bit',
  143. 'X-Mailer' => 'Drupal'
  144. );
  145. if ($default_from) {
  146. // To prevent e-mail from looking like spam, the addresses in the Sender and
  147. // Return-Path headers should have a domain authorized to use the originating
  148. // SMTP server.
  149. $headers['From'] = $headers['Sender'] = $headers['Return-Path'] = $default_from;
  150. if (variable_get('mail_display_name_site_name', FALSE)) {
  151. $display_name = variable_get('site_name', 'Drupal');
  152. $headers['From'] = drupal_mail_format_display_name($display_name) . ' <' . $default_from . '>';
  153. }
  154. }
  155. if ($from && $from != $default_from) {
  156. $headers['From'] = $from;
  157. }
  158. $message['headers'] = $headers;
  159. // Build the e-mail (get subject and body, allow additional headers) by
  160. // invoking hook_mail() on this module. We cannot use module_invoke() as
  161. // we need to have $message by reference in hook_mail().
  162. if (function_exists($function = $module . '_mail')) {
  163. $function($key, $message, $params);
  164. }
  165. // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
  166. drupal_alter('mail', $message);
  167. // Retrieve the responsible implementation for this message.
  168. $system = drupal_mail_system($module, $key);
  169. // Format the message body.
  170. $message = $system->format($message);
  171. // Optionally send e-mail.
  172. if ($send) {
  173. // The original caller requested sending. Sending was canceled by one or
  174. // more hook_mail_alter() implementations. We set 'result' to NULL, because
  175. // FALSE indicates an error in sending.
  176. if (empty($message['send'])) {
  177. $message['result'] = NULL;
  178. }
  179. // Sending was originally requested and was not canceled.
  180. else {
  181. $message['result'] = $system->mail($message);
  182. // Log errors.
  183. if (!$message['result']) {
  184. watchdog('mail', 'Error sending e-mail (from %from to %to).', array('%from' => $message['from'], '%to' => $message['to']), WATCHDOG_ERROR);
  185. drupal_set_message(t('Unable to send e-mail. Contact the site administrator if the problem persists.'), 'error');
  186. }
  187. }
  188. }
  189. return $message;
  190. }
  191. /**
  192. * Returns an object that implements the MailSystemInterface interface.
  193. *
  194. * Allows for one or more custom mail backends to format and send mail messages
  195. * composed using drupal_mail().
  196. *
  197. * An implementation needs to implement the following methods:
  198. * - format: Allows to preprocess, format, and postprocess a mail
  199. * message before it is passed to the sending system. By default, all messages
  200. * may contain HTML and are converted to plain-text by the DefaultMailSystem
  201. * implementation. For example, an alternative implementation could override
  202. * the default implementation and additionally sanitize the HTML for usage in
  203. * a MIME-encoded e-mail, but still invoking the DefaultMailSystem
  204. * implementation to generate an alternate plain-text version for sending.
  205. * - mail: Sends a message through a custom mail sending engine.
  206. * By default, all messages are sent via PHP's mail() function by the
  207. * DefaultMailSystem implementation.
  208. *
  209. * The selection of a particular implementation is controlled via the variable
  210. * 'mail_system', which is a keyed array. The default implementation
  211. * is the class whose name is the value of 'default-system' key. A more specific
  212. * match first to key and then to module will be used in preference to the
  213. * default. To specify a different class for all mail sent by one module, set
  214. * the class name as the value for the key corresponding to the module name. To
  215. * specify a class for a particular message sent by one module, set the class
  216. * name as the value for the array key that is the message id, which is
  217. * "${module}_${key}".
  218. *
  219. * For example to debug all mail sent by the user module by logging it to a
  220. * file, you might set the variable as something like:
  221. *
  222. * @code
  223. * array(
  224. * 'default-system' => 'DefaultMailSystem',
  225. * 'user' => 'DevelMailLog',
  226. * );
  227. * @endcode
  228. *
  229. * Finally, a different system can be specified for a specific e-mail ID (see
  230. * the $key param), such as one of the keys used by the contact module:
  231. *
  232. * @code
  233. * array(
  234. * 'default-system' => 'DefaultMailSystem',
  235. * 'user' => 'DevelMailLog',
  236. * 'contact_page_autoreply' => 'DrupalDevNullMailSend',
  237. * );
  238. * @endcode
  239. *
  240. * Other possible uses for system include a mail-sending class that actually
  241. * sends (or duplicates) each message to SMS, Twitter, instant message, etc, or
  242. * a class that queues up a large number of messages for more efficient bulk
  243. * sending or for sending via a remote gateway so as to reduce the load
  244. * on the local server.
  245. *
  246. * @param $module
  247. * The module name which was used by drupal_mail() to invoke hook_mail().
  248. * @param $key
  249. * A key to identify the e-mail sent. The final e-mail ID for the e-mail
  250. * alter hook in drupal_mail() would have been {$module}_{$key}.
  251. *
  252. * @return MailSystemInterface
  253. */
  254. function drupal_mail_system($module, $key) {
  255. $instances = &drupal_static(__FUNCTION__, array());
  256. $id = $module . '_' . $key;
  257. $configuration = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  258. // Look for overrides for the default class, starting from the most specific
  259. // id, and falling back to the module name.
  260. if (isset($configuration[$id])) {
  261. $class = $configuration[$id];
  262. }
  263. elseif (isset($configuration[$module])) {
  264. $class = $configuration[$module];
  265. }
  266. else {
  267. $class = $configuration['default-system'];
  268. }
  269. if (empty($instances[$class])) {
  270. $interfaces = class_implements($class);
  271. if (isset($interfaces['MailSystemInterface'])) {
  272. $instances[$class] = new $class();
  273. }
  274. else {
  275. throw new Exception(t('Class %class does not implement interface %interface', array('%class' => $class, '%interface' => 'MailSystemInterface')));
  276. }
  277. }
  278. return $instances[$class];
  279. }
  280. /**
  281. * An interface for pluggable mail back-ends.
  282. */
  283. interface MailSystemInterface {
  284. /**
  285. * Format a message composed by drupal_mail() prior sending.
  286. *
  287. * @param $message
  288. * A message array, as described in hook_mail_alter().
  289. *
  290. * @return
  291. * The formatted $message.
  292. */
  293. public function format(array $message);
  294. /**
  295. * Send a message composed by drupal_mail().
  296. *
  297. * @param $message
  298. * Message array with at least the following elements:
  299. * - id: A unique identifier of the e-mail type. Examples: 'contact_user_copy',
  300. * 'user_password_reset'.
  301. * - to: The mail address or addresses where the message will be sent to.
  302. * The formatting of this string will be validated with the
  303. * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
  304. * Some examples are:
  305. * - user@example.com
  306. * - user@example.com, anotheruser@example.com
  307. * - User <user@example.com>
  308. * - User <user@example.com>, Another User <anotheruser@example.com>
  309. * - subject: Subject of the e-mail to be sent. This must not contain any
  310. * newline characters, or the mail may not be sent properly.
  311. * - body: Message to be sent. Accepts both CRLF and LF line-endings.
  312. * E-mail bodies must be wrapped. You can use drupal_wrap_mail() for
  313. * smart plain text wrapping.
  314. * - headers: Associative array containing all additional mail headers not
  315. * defined by one of the other parameters. PHP's mail() looks for Cc and
  316. * Bcc headers and sends the mail to addresses in these headers too.
  317. *
  318. * @return
  319. * TRUE if the mail was successfully accepted for delivery, otherwise FALSE.
  320. */
  321. public function mail(array $message);
  322. }
  323. /**
  324. * Performs format=flowed soft wrapping for mail (RFC 3676).
  325. *
  326. * We use delsp=yes wrapping, but only break non-spaced languages when
  327. * absolutely necessary to avoid compatibility issues.
  328. *
  329. * We deliberately use LF rather than CRLF, see drupal_mail().
  330. *
  331. * @param string $text
  332. * The plain text to process.
  333. * @param string $indent (optional)
  334. * A string to indent the text with. Only '>' characters are repeated on
  335. * subsequent wrapped lines. Others are replaced by spaces.
  336. *
  337. * @return string
  338. * The content of the email as a string with formatting applied.
  339. */
  340. function drupal_wrap_mail($text, $indent = '') {
  341. // Convert CRLF into LF.
  342. $text = str_replace("\r", '', $text);
  343. // See if soft-wrapping is allowed.
  344. $clean_indent = _drupal_html_to_text_clean($indent);
  345. $soft = strpos($clean_indent, ' ') === FALSE;
  346. // Check if the string has line breaks.
  347. if (strpos($text, "\n") !== FALSE) {
  348. // Remove trailing spaces to make existing breaks hard, but leave signature
  349. // marker untouched (RFC 3676, Section 4.3).
  350. $text = preg_replace('/(?(?<!^--) +\n| +\n)/m', "\n", $text);
  351. // Wrap each line at the needed width.
  352. $lines = explode("\n", $text);
  353. array_walk($lines, '_drupal_wrap_mail_line', array('soft' => $soft, 'length' => strlen($indent)));
  354. $text = implode("\n", $lines);
  355. }
  356. else {
  357. // Wrap this line.
  358. _drupal_wrap_mail_line($text, 0, array('soft' => $soft, 'length' => strlen($indent)));
  359. }
  360. // Empty lines with nothing but spaces.
  361. $text = preg_replace('/^ +\n/m', "\n", $text);
  362. // Space-stuff special lines.
  363. $text = preg_replace('/^(>| |From)/m', ' $1', $text);
  364. // Apply indentation. We only include non-'>' indentation on the first line.
  365. $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
  366. return $text;
  367. }
  368. /**
  369. * Transforms an HTML string into plain text, preserving its structure.
  370. *
  371. * The output will be suitable for use as 'format=flowed; delsp=yes' text
  372. * (RFC 3676) and can be passed directly to drupal_mail() for sending.
  373. *
  374. * We deliberately use LF rather than CRLF, see drupal_mail().
  375. *
  376. * This function provides suitable alternatives for the following tags:
  377. * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
  378. * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
  379. *
  380. * @param $string
  381. * The string to be transformed.
  382. * @param $allowed_tags (optional)
  383. * If supplied, a list of tags that will be transformed. If omitted, all
  384. * all supported tags are transformed.
  385. *
  386. * @return
  387. * The transformed string.
  388. */
  389. function drupal_html_to_text($string, $allowed_tags = NULL) {
  390. // Cache list of supported tags.
  391. static $supported_tags;
  392. if (empty($supported_tags)) {
  393. $supported_tags = array('a', 'em', 'i', 'strong', 'b', 'br', 'p', 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr');
  394. }
  395. // Make sure only supported tags are kept.
  396. $allowed_tags = isset($allowed_tags) ? array_intersect($supported_tags, $allowed_tags) : $supported_tags;
  397. // Make sure tags, entities and attributes are well-formed and properly nested.
  398. $string = _filter_htmlcorrector(filter_xss($string, $allowed_tags));
  399. // Apply inline styles.
  400. $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
  401. $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
  402. // Replace inline <a> tags with the text of link and a footnote.
  403. // 'See <a href="http://drupal.org">the Drupal site</a>' becomes
  404. // 'See the Drupal site [1]' with the URL included as a footnote.
  405. _drupal_html_to_mail_urls(NULL, TRUE);
  406. $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
  407. $string = preg_replace_callback($pattern, '_drupal_html_to_mail_urls', $string);
  408. $urls = _drupal_html_to_mail_urls();
  409. $footnotes = '';
  410. if (count($urls)) {
  411. $footnotes .= "\n";
  412. for ($i = 0, $max = count($urls); $i < $max; $i++) {
  413. $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
  414. }
  415. }
  416. // Split tags from text.
  417. $split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  418. // Note: PHP ensures the array consists of alternating delimiters and literals
  419. // and begins and ends with a literal (inserting $null as required).
  420. $tag = FALSE; // Odd/even counter (tag or no tag)
  421. $casing = NULL; // Case conversion function
  422. $output = '';
  423. $indent = array(); // All current indentation string chunks
  424. $lists = array(); // Array of counters for opened lists
  425. foreach ($split as $value) {
  426. $chunk = NULL; // Holds a string ready to be formatted and output.
  427. // Process HTML tags (but don't output any literally).
  428. if ($tag) {
  429. list($tagname) = explode(' ', strtolower($value), 2);
  430. switch ($tagname) {
  431. // List counters
  432. case 'ul':
  433. array_unshift($lists, '*');
  434. break;
  435. case 'ol':
  436. array_unshift($lists, 1);
  437. break;
  438. case '/ul':
  439. case '/ol':
  440. array_shift($lists);
  441. $chunk = ''; // Ensure blank new-line.
  442. break;
  443. // Quotation/list markers, non-fancy headers
  444. case 'blockquote':
  445. // Format=flowed indentation cannot be mixed with lists.
  446. $indent[] = count($lists) ? ' "' : '>';
  447. break;
  448. case 'li':
  449. $indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
  450. break;
  451. case 'dd':
  452. $indent[] = ' ';
  453. break;
  454. case 'h3':
  455. $indent[] = '.... ';
  456. break;
  457. case 'h4':
  458. $indent[] = '.. ';
  459. break;
  460. case '/blockquote':
  461. if (count($lists)) {
  462. // Append closing quote for inline quotes (immediately).
  463. $output = rtrim($output, "> \n") . "\"\n";
  464. $chunk = ''; // Ensure blank new-line.
  465. }
  466. // Fall-through
  467. case '/li':
  468. case '/dd':
  469. array_pop($indent);
  470. break;
  471. case '/h3':
  472. case '/h4':
  473. array_pop($indent);
  474. case '/h5':
  475. case '/h6':
  476. $chunk = ''; // Ensure blank new-line.
  477. break;
  478. // Fancy headers
  479. case 'h1':
  480. $indent[] = '======== ';
  481. $casing = 'drupal_strtoupper';
  482. break;
  483. case 'h2':
  484. $indent[] = '-------- ';
  485. $casing = 'drupal_strtoupper';
  486. break;
  487. case '/h1':
  488. case '/h2':
  489. $casing = NULL;
  490. // Pad the line with dashes.
  491. $output = _drupal_html_to_text_pad($output, ($tagname == '/h1') ? '=' : '-', ' ');
  492. array_pop($indent);
  493. $chunk = ''; // Ensure blank new-line.
  494. break;
  495. // Horizontal rulers
  496. case 'hr':
  497. // Insert immediately.
  498. $output .= drupal_wrap_mail('', implode('', $indent)) . "\n";
  499. $output = _drupal_html_to_text_pad($output, '-');
  500. break;
  501. // Paragraphs and definition lists
  502. case '/p':
  503. case '/dl':
  504. $chunk = ''; // Ensure blank new-line.
  505. break;
  506. }
  507. }
  508. // Process blocks of text.
  509. else {
  510. // Convert inline HTML text to plain text; not removing line-breaks or
  511. // white-space, since that breaks newlines when sanitizing plain-text.
  512. $value = trim(decode_entities($value));
  513. if (drupal_strlen($value)) {
  514. $chunk = $value;
  515. }
  516. }
  517. // See if there is something waiting to be output.
  518. if (isset($chunk)) {
  519. // Apply any necessary case conversion.
  520. if (isset($casing)) {
  521. $chunk = $casing($chunk);
  522. }
  523. // Format it and apply the current indentation.
  524. $output .= drupal_wrap_mail($chunk, implode('', $indent)) . MAIL_LINE_ENDINGS;
  525. // Remove non-quotation markers from indentation.
  526. $indent = array_map('_drupal_html_to_text_clean', $indent);
  527. }
  528. $tag = !$tag;
  529. }
  530. return $output . $footnotes;
  531. }
  532. /**
  533. * Return a RFC-2822 compliant "display-name" component.
  534. *
  535. * The "display-name" component is used in mail header "Originator" fields
  536. * (From, Sender, Reply-to) to give a human-friendly description of the
  537. * address, i.e. From: My Display Name <xyz@example.org>. RFC-822 and
  538. * RFC-2822 define its syntax and rules. This method gets as input a string
  539. * to be used as "display-name" and formats it to be RFC compliant.
  540. *
  541. * @param string $string
  542. * A string to be used as "display-name".
  543. *
  544. * @return string
  545. * A RFC compliant version of the string, ready to be used as
  546. * "display-name" in mail originator header fields.
  547. */
  548. function drupal_mail_format_display_name($string) {
  549. // Make sure we don't process html-encoded characters. They may create
  550. // unneeded trouble if left encoded, besides they will be correctly
  551. // processed if decoded.
  552. $string = decode_entities($string);
  553. // If string contains non-ASCII characters it must be (short) encoded
  554. // according to RFC-2047. The output of a "B" (Base64) encoded-word is
  555. // always safe to be used as display-name.
  556. $safe_display_name = mime_header_encode($string, TRUE);
  557. // Encoded-words are always safe to be used as display-name because don't
  558. // contain any RFC 2822 "specials" characters. However
  559. // mimeHeaderEncode() encodes a string only if it contains any
  560. // non-ASCII characters, and leaves its value untouched (un-encoded) if
  561. // ASCII only. For this reason in order to produce a valid display-name we
  562. // still need to make sure there are no "specials" characters left.
  563. if (preg_match('/[' . preg_quote(MAIL_RFC_2822_SPECIALS) . ']/', $safe_display_name)) {
  564. // If string is already quoted, it may or may not be escaped properly, so
  565. // don't trust it and reset.
  566. if (preg_match('/^"(.+)"$/', $safe_display_name, $matches)) {
  567. $safe_display_name = str_replace(array('\\\\', '\\"'), array('\\', '"'), $matches[1]);
  568. }
  569. // Transform the string in a RFC-2822 "quoted-string" by wrapping it in
  570. // double-quotes. Also make sure '"' and '\' occurrences are escaped.
  571. $safe_display_name = '"' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $safe_display_name) . '"';
  572. }
  573. return $safe_display_name;
  574. }
  575. /**
  576. * Wraps words on a single line.
  577. *
  578. * Callback for array_walk() within drupal_wrap_mail().
  579. */
  580. function _drupal_wrap_mail_line(&$line, $key, $values) {
  581. // Use soft-breaks only for purely quoted or unindented text.
  582. $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n");
  583. // Break really long words at the maximum width allowed.
  584. $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n", TRUE);
  585. }
  586. /**
  587. * Keeps track of URLs and replaces them with placeholder tokens.
  588. *
  589. * Callback for preg_replace_callback() within drupal_html_to_text().
  590. */
  591. function _drupal_html_to_mail_urls($match = NULL, $reset = FALSE) {
  592. global $base_url, $base_path;
  593. static $urls = array(), $regexp;
  594. if ($reset) {
  595. // Reset internal URL list.
  596. $urls = array();
  597. }
  598. else {
  599. if (empty($regexp)) {
  600. $regexp = '@^' . preg_quote($base_path, '@') . '@';
  601. }
  602. if ($match) {
  603. list(, , $url, $label) = $match;
  604. // Ensure all URLs are absolute.
  605. $urls[] = strpos($url, '://') ? $url : preg_replace($regexp, $base_url . '/', $url);
  606. return $label . ' [' . count($urls) . ']';
  607. }
  608. }
  609. return $urls;
  610. }
  611. /**
  612. * Replaces non-quotation markers from a given piece of indentation with spaces.
  613. *
  614. * Callback for array_map() within drupal_html_to_text().
  615. */
  616. function _drupal_html_to_text_clean($indent) {
  617. return preg_replace('/[^>]/', ' ', $indent);
  618. }
  619. /**
  620. * Pads the last line with the given character.
  621. *
  622. * @see drupal_html_to_text()
  623. */
  624. function _drupal_html_to_text_pad($text, $pad, $prefix = '') {
  625. // Remove last line break.
  626. $text = substr($text, 0, -1);
  627. // Calculate needed padding space and add it.
  628. if (($p = strrpos($text, "\n")) === FALSE) {
  629. $p = -1;
  630. }
  631. $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
  632. // Add prefix and padding, and restore linebreak.
  633. return $text . $prefix . str_repeat($pad, $n) . "\n";
  634. }