PageRenderTime 42ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/produtechv2/includes/mail.inc

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