htmlmail.mail.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. <?php
  2. /**
  3. * @file
  4. * Formats and sends mail using the MailMIME class.
  5. *
  6. * @see http://drupal.org/node/900794
  7. * @see http://api.drupal.org/api/drupal/includes--mail.inc/interface/MailSystemInterface/7
  8. * @see http://drupal.org/project/mailmime
  9. */
  10. /**
  11. * Implements MailSystemInterface.
  12. */
  13. class HTMLMailSystem implements MailSystemInterface {
  14. /**
  15. * Format emails according to module settings.
  16. *
  17. * Parses the message headers and body into a MailMIME object. If another module
  18. * subsequently modifies the body, then format() should be called again before
  19. * sending. This is safe because the $message['body'] is not modified.
  20. *
  21. * @param $message
  22. * An associative array with at least the following parts:
  23. * - headers: An array of (name => value) email headers.
  24. * - body: The text/plain or text/html message part.
  25. *
  26. * @return
  27. * The formatted $message, ready for sending.
  28. */
  29. public function format(array $message) {
  30. $eol = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
  31. // @todo Remove this when issue #209672 gets resolved.
  32. $default_from = variable_get('site_mail', ini_get('sendmail_from'));
  33. if ( !empty($message['headers']['From'])
  34. && $message['headers']['From'] == $default_from
  35. && valid_email_address($default_from)
  36. ) {
  37. $message['headers']['From'] = '"'
  38. . str_replace('"', '', variable_get('site_name', 'Drupal'))
  39. . '" <' . $default_from . '>';
  40. }
  41. // Collapse the message body array.
  42. if (module_exists('mailmime')) {
  43. $body = $this->formatMailMIME($message);
  44. $plain = $message['MailMIME']->getTXTBody();
  45. }
  46. else {
  47. if (is_array($message['body'])) {
  48. $message['body'] = implode("<br />$eol<br />$eol", $message['body']);
  49. }
  50. $body = theme('htmlmail', $message);
  51. if ($message['body'] && !$body) {
  52. watchdog(
  53. 'htmlmail',
  54. 'The %theme function did not return any text. Please check your template file for errors.',
  55. array('%theme' => "theme('htmlmail', \$message)"),
  56. WATCHDOG_WARNING
  57. );
  58. $body = $message['body'];
  59. }
  60. // @todo Change to drupal_html_to_text when issue #299138 gets resolved.
  61. $plain = mailsystem_html_to_text($body);
  62. if ($body && !$plain) {
  63. watchdog(
  64. 'htmlmail',
  65. 'The %convert function did not return any text. Please report this error to the %mailsystem issue queue.',
  66. array('%convert' => 'mailsystem_html_to_text()', '%mailsystem' => 'Mail system'),
  67. WATCHDOG_WARNING,
  68. 'http://drupal.org/node/add/project-issue/mailsystem'
  69. );
  70. }
  71. }
  72. // Check to see whether recipient allows non-plaintext.
  73. if ($body && htmlmail_is_allowed($message['to'])) {
  74. // Optionally apply the selected web theme.
  75. if (module_exists('echo') && $theme = htmlmail_get_selected_theme($message)) {
  76. $themed_body = echo_themed_page($message['subject'], $body, $theme);
  77. if ($themed_body) {
  78. $body = $themed_body;
  79. }
  80. else {
  81. watchdog(
  82. 'htmlmail',
  83. 'The %echo function did not return any text. Please check the page template of your %theme theme for errors.',
  84. array('%echo' => 'echo_themed_page()', '%theme' => $theme),
  85. WATCHDOG_WARNING
  86. );
  87. }
  88. }
  89. // Optionally apply the selected output filter.
  90. if ($filter = variable_get('htmlmail_postfilter')) {
  91. $filtered_body = check_markup($body, $filter);
  92. if ($filtered_body) {
  93. $body = $filtered_body;
  94. }
  95. else {
  96. watchdog(
  97. 'htmlmail',
  98. 'The %check function did not return any text. Please check your %filter output filter for errors.',
  99. array('%check' => 'check_markup()', '%filter' => $filter),
  100. WATCHDOG_WARNING
  101. );
  102. }
  103. }
  104. // Store the fully-themed HTML body.
  105. if (isset($message['MailMIME'])) {
  106. $mime = &$message['MailMIME'];
  107. $mime->setHTMLBody($body);
  108. list($message['headers'], $message['body']) = $mime->toEmail($message['headers']);
  109. if (!$message['body']) {
  110. watchdog(
  111. 'htmlmail',
  112. 'The %toemail function did not return any text. Please report this errot to the %mailmime issue queue.',
  113. array('%toemail' => 'MailMIME::toEmail()', '%mailmime' => 'Mail MIME'),
  114. WATCHDOG_WARNING,
  115. 'http://drupal.org/node/add/project-issue/mailmime'
  116. );
  117. }
  118. }
  119. else {
  120. $message['headers']['Content-Type'] = 'text/html; charset=utf-8';
  121. $message['body'] = $body;
  122. }
  123. }
  124. else {
  125. if (isset($message['MailMIME'])) {
  126. $mime = &$message['MailMIME'];
  127. $mime->setHTMLBody('');
  128. $mime->setContentType('text/plain', array('charset' => 'utf-8'));
  129. list($message['headers'], $message['body']) = $mime->toEmail($message['headers']);
  130. if (!$message['body']) {
  131. watchdog(
  132. 'htmlmail',
  133. 'The %toemail function did not return any text. Please report this errot to the %mailmime issue queue.',
  134. array('%toemail' => 'MailMIME::toEmail()', '%mailmime' => 'Mail MIME'),
  135. WATCHDOG_WARNING,
  136. 'http://drupal.org/node/add/project-issue/mailmime'
  137. );
  138. }
  139. }
  140. else {
  141. $message['body'] = $plain;
  142. $message['headers']['Content-Type'] = 'text/plain; charset=utf-8';
  143. }
  144. }
  145. return $message;
  146. }
  147. /**
  148. * Use the MailMime class to format the message body.
  149. *
  150. * @see http://drupal.org/project/mailmime
  151. */
  152. public function formatMailMIME(array &$message) {
  153. $eol = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
  154. $message['body'] = MailMIME::concat($message['body']);
  155. // Build a full email message string.
  156. $email = MailMIME::encodeEmail($message['headers'], $message['body']);
  157. // Parse it into MIME parts.
  158. if (!($mime = MailMIME::parse($email))) {
  159. watchdog(
  160. 'HTMLMailSystem',
  161. 'Could not parse email message.',
  162. array(),
  163. WATCHDOG_ERROR
  164. );
  165. return $message;
  166. }
  167. // Work on a copy so that the original $message['body'] remains unchanged.
  168. $email = $message;
  169. if ( !($email['body'] = $mime->getHTMLBody())
  170. && !($email['body'] = $mime->getTXTBody())
  171. ) {
  172. $email['body'] = '';
  173. }
  174. else {
  175. // Wrap formatted plaintext in <pre> tags.
  176. if ( $email['body'] === strip_tags($email['body']) // No html tags.
  177. && preg_match('/.' . $eol . './', $email['body']) // At least one embedded newline.
  178. ) {
  179. $email['body'] = '<pre>' . $email['body'] . '</pre>';
  180. }
  181. }
  182. // Theme with htmlmail.tpl.php.
  183. $body = theme('htmlmail', $email);
  184. $mime->setHTMLBody($body);
  185. // @todo Change to drupal_html_to_text when issue #299138 gets resolved.
  186. $mime->setTXTBody(mailsystem_html_to_text($body));
  187. $message['MailMIME'] = &$mime;
  188. return $body;
  189. }
  190. /**
  191. * Send an email message.
  192. *
  193. * @param $message
  194. * An associative array containing at least:
  195. * - headers: An associative array of (name => value) email headers.
  196. * - body: The text/plain or text/html message body.
  197. * - MailMIME: The message, parsed into a MailMIME object.
  198. */
  199. public function mail(array $message) {
  200. $eol = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
  201. // Ensure that subject is non-null.
  202. $message += array('subject' => t('(No subject)'));
  203. // Check for empty recipient.
  204. if (empty($message['to'])) {
  205. if (empty($message['headers']['To'])) {
  206. watchdog(
  207. 'HTMLMailSystem',
  208. 'Cannot send email about %subject without a recipient.',
  209. array('subject' => $message['subject']),
  210. WATCHDOG_ERROR
  211. );
  212. return FALSE;
  213. }
  214. $message['to'] = $message['headers']['To'];
  215. }
  216. if (class_exists('MailMIME')) {
  217. $mime = new MailMIME();
  218. $to = $mime->encodeHeader('to', $message['to']);
  219. $subject = $mime->encodeHeader('subject', $message['subject']);
  220. $txt_headers = $mime->txtHeaders($message['headers']);
  221. }
  222. else {
  223. $to = mime_header_encode($message['to']);
  224. $subject = mime_header_encode($message['subject']);
  225. $txt_headers = $this->txtHeaders($message['headers']);
  226. }
  227. $body = preg_replace('#(\r\n|\r|\n)#s', $eol, $message['body']);
  228. // Check for empty body.
  229. if (empty($body)) {
  230. watchdog(
  231. 'HTMLMailSystem',
  232. 'Refusing to send a blank email to %recipient about %subject.',
  233. array('%recipient' => $message['to'], '%subject' => $message['subject']),
  234. WATCHDOG_WARNING
  235. );
  236. return FALSE;
  237. }
  238. if (variable_get('htmlmail_debug', 0)) {
  239. $params = array(
  240. $to,
  241. $subject,
  242. drupal_substr($body, 0, min(80, strpos("\n", $body))) . '...',
  243. $txt_headers
  244. );
  245. }
  246. if (isset($message['headers']['Return-Path'])) {
  247. // A return-path was set.
  248. if (isset($_SERVER['WINDIR']) || strpos($_SERVER['SERVER_SOFTWARE'], 'Win32') !== FALSE) {
  249. // On Windows, PHP will use the value of sendmail_from for the
  250. // Return-Path header.
  251. $old_from = ini_get('sendmail_from');
  252. ini_set('sendmail_from', $message['headers']['Return-Path']);
  253. $result = @mail($to, $subject, $body, $txt_headers);
  254. ini_set('sendmail_from', $old_from);
  255. }
  256. elseif (ini_get('safe_mode')) {
  257. // If safe mode is in effect, passing the fifth parameter to @mail
  258. // will cause it to return FALSE and generate a PHP warning, even
  259. // if the parameter is NULL.
  260. $result = @mail($to, $subject, $body, $txt_headers);
  261. }
  262. else {
  263. // On most non-Windows systems, the "-f" option to the sendmail command
  264. // is used to set the Return-Path.
  265. $extra = '-f' . $message['headers']['Return-Path'];
  266. $result = @mail($to, $subject, $body, $txt_headers, $extra);
  267. if (variable_get('htmlmail_debug', 0)) {
  268. $params[] = $extra;
  269. }
  270. }
  271. }
  272. else {
  273. // No return-path was set.
  274. $result = @mail($to, $subject, $body, $txt_headers);
  275. }
  276. if (!$result && variable_get('htmlmail_debug', 0)) {
  277. $call = '@mail(' . implode(', ', $params) . ')';
  278. foreach ($params as $i => $value) {
  279. $params[$i] = var_export($value, 1);
  280. }
  281. if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) {
  282. $trace = print_r(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 1);
  283. }
  284. else {
  285. $trace = debug_backtrace(0);
  286. for ($i = count($trace) - 1; $i >= 0; $i--) {
  287. unset($trace[$i]['args']);
  288. }
  289. $trace = print_r($trace);
  290. }
  291. watchdog('htmlmail', 'Mail sending failed because:<br /><pre>@call</pre><br />returned FALSE.<br /><pre>@trace</pre>', array('@call' => $call, '@trace' => $trace));
  292. }
  293. return $result;
  294. }
  295. /**
  296. * Converts an array of email headers to a text string.
  297. *
  298. * @param $headers
  299. * An associative array of ('HeaderName' => 'header value') pairs.
  300. *
  301. * @return
  302. * The concatenated headers as a single string.
  303. */
  304. public function txtHeaders(array $headers) {
  305. $output = array();
  306. foreach ($headers as $name => $value) {
  307. if (is_array($value)) {
  308. foreach ($value as $val) {
  309. $output[] = "$name: $val";
  310. }
  311. }
  312. else {
  313. $output[] = "$name: $value";
  314. }
  315. }
  316. return implode("\n", $output);
  317. }
  318. }