UserMailer.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <?php
  2. /**
  3. * Classes used to send e-mails
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @author <brion@pobox.com>
  22. * @author <mail@tgries.de>
  23. * @author Tim Starling
  24. * @author Luke Welling lwelling@wikimedia.org
  25. */
  26. /**
  27. * Collection of static functions for sending mail
  28. */
  29. class UserMailer {
  30. private static $mErrorString;
  31. /**
  32. * Send mail using a PEAR mailer
  33. *
  34. * @param Mail_smtp $mailer
  35. * @param string[]|string $dest
  36. * @param array $headers
  37. * @param string $body
  38. *
  39. * @return Status
  40. */
  41. protected static function sendWithPear( $mailer, $dest, $headers, $body ) {
  42. $mailResult = $mailer->send( $dest, $headers, $body );
  43. // Based on the result return an error string,
  44. if ( PEAR::isError( $mailResult ) ) {
  45. wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
  46. return Status::newFatal( 'pear-mail-error', $mailResult->getMessage() );
  47. } else {
  48. return Status::newGood();
  49. }
  50. }
  51. /**
  52. * Creates a single string from an associative array
  53. *
  54. * @param array $headers Associative Array: keys are header field names,
  55. * values are ... values.
  56. * @param string $endl The end of line character. Defaults to "\n"
  57. *
  58. * Note RFC2822 says newlines must be CRLF (\r\n)
  59. * but php mail naively "corrects" it and requires \n for the "correction" to work
  60. *
  61. * @return string
  62. */
  63. private static function arrayToHeaderString( $headers, $endl = PHP_EOL ) {
  64. $strings = [];
  65. foreach ( $headers as $name => $value ) {
  66. // Prevent header injection by stripping newlines from value
  67. $value = self::sanitizeHeaderValue( $value );
  68. $strings[] = "$name: $value";
  69. }
  70. return implode( $endl, $strings );
  71. }
  72. /**
  73. * Create a value suitable for the MessageId Header
  74. *
  75. * @return string
  76. */
  77. private static function makeMsgId() {
  78. global $wgSMTP, $wgServer;
  79. $domainId = WikiMap::getCurrentWikiDbDomain()->getId();
  80. $msgid = uniqid( $domainId . ".", true /** for cygwin */ );
  81. if ( is_array( $wgSMTP ) && isset( $wgSMTP['IDHost'] ) && $wgSMTP['IDHost'] ) {
  82. $domain = $wgSMTP['IDHost'];
  83. } else {
  84. $url = wfParseUrl( $wgServer );
  85. $domain = $url['host'];
  86. }
  87. return "<$msgid@$domain>";
  88. }
  89. /**
  90. * This function will perform a direct (authenticated) login to
  91. * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
  92. * array of parameters. It requires PEAR:Mail to do that.
  93. * Otherwise it just uses the standard PHP 'mail' function.
  94. *
  95. * @param MailAddress|MailAddress[] $to Recipient's email (or an array of them)
  96. * @param MailAddress $from Sender's email
  97. * @param string $subject Email's subject.
  98. * @param string|string[] $body Email's text or Array of two strings to be the text and html bodies
  99. * @param array $options Keys:
  100. * 'replyTo' MailAddress
  101. * 'contentType' string default 'text/plain; charset=UTF-8'
  102. * 'headers' array Extra headers to set
  103. *
  104. * @throws MWException
  105. * @throws Exception
  106. * @return Status
  107. */
  108. public static function send( $to, $from, $subject, $body, $options = [] ) {
  109. global $wgAllowHTMLEmail;
  110. if ( !isset( $options['contentType'] ) ) {
  111. $options['contentType'] = 'text/plain; charset=UTF-8';
  112. }
  113. if ( !is_array( $to ) ) {
  114. $to = [ $to ];
  115. }
  116. // mail body must have some content
  117. $minBodyLen = 10;
  118. // arbitrary but longer than Array or Object to detect casting error
  119. // body must either be a string or an array with text and body
  120. if (
  121. !(
  122. !is_array( $body ) &&
  123. strlen( $body ) >= $minBodyLen
  124. )
  125. &&
  126. !(
  127. is_array( $body ) &&
  128. isset( $body['text'] ) &&
  129. isset( $body['html'] ) &&
  130. strlen( $body['text'] ) >= $minBodyLen &&
  131. strlen( $body['html'] ) >= $minBodyLen
  132. )
  133. ) {
  134. // if it is neither we have a problem
  135. return Status::newFatal( 'user-mail-no-body' );
  136. }
  137. if ( !$wgAllowHTMLEmail && is_array( $body ) ) {
  138. // HTML not wanted. Dump it.
  139. $body = $body['text'];
  140. }
  141. wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) . "\n" );
  142. // Make sure we have at least one address
  143. $has_address = false;
  144. foreach ( $to as $u ) {
  145. if ( $u->address ) {
  146. $has_address = true;
  147. break;
  148. }
  149. }
  150. if ( !$has_address ) {
  151. return Status::newFatal( 'user-mail-no-addy' );
  152. }
  153. // give a chance to UserMailerTransformContents subscribers who need to deal with each
  154. // target differently to split up the address list
  155. if ( count( $to ) > 1 ) {
  156. $oldTo = $to;
  157. Hooks::run( 'UserMailerSplitTo', [ &$to ] );
  158. if ( $oldTo != $to ) {
  159. $splitTo = array_diff( $oldTo, $to );
  160. $to = array_diff( $oldTo, $splitTo ); // ignore new addresses added in the hook
  161. // first send to non-split address list, then to split addresses one by one
  162. $status = Status::newGood();
  163. if ( $to ) {
  164. $status->merge( self::sendInternal(
  165. $to, $from, $subject, $body, $options ) );
  166. }
  167. foreach ( $splitTo as $newTo ) {
  168. $status->merge( self::sendInternal(
  169. [ $newTo ], $from, $subject, $body, $options ) );
  170. }
  171. return $status;
  172. }
  173. }
  174. return self::sendInternal( $to, $from, $subject, $body, $options );
  175. }
  176. /**
  177. * Whether the PEAR Mail_mime library is usable. This will
  178. * try and load it if it is not already.
  179. *
  180. * @return bool
  181. */
  182. private static function isMailMimeUsable() {
  183. static $usable = null;
  184. if ( $usable === null ) {
  185. $usable = class_exists( 'Mail_mime' );
  186. }
  187. return $usable;
  188. }
  189. /**
  190. * Whether the PEAR Mail library is usable. This will
  191. * try and load it if it is not already.
  192. *
  193. * @return bool
  194. */
  195. private static function isMailUsable() {
  196. static $usable = null;
  197. if ( $usable === null ) {
  198. $usable = class_exists( 'Mail' );
  199. }
  200. return $usable;
  201. }
  202. /**
  203. * Helper function fo UserMailer::send() which does the actual sending. It expects a $to
  204. * list which the UserMailerSplitTo hook would not split further.
  205. * @param MailAddress[] $to Array of recipients' email addresses
  206. * @param MailAddress $from Sender's email
  207. * @param string $subject Email's subject.
  208. * @param string|string[] $body Email's text or Array of two strings to be the text and html bodies
  209. * @param array $options Keys:
  210. * 'replyTo' MailAddress
  211. * 'contentType' string default 'text/plain; charset=UTF-8'
  212. * 'headers' array Extra headers to set
  213. *
  214. * @throws MWException
  215. * @throws Exception
  216. * @return Status
  217. */
  218. protected static function sendInternal(
  219. array $to,
  220. MailAddress $from,
  221. $subject,
  222. $body,
  223. $options = []
  224. ) {
  225. global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams;
  226. $mime = null;
  227. $replyto = $options['replyTo'] ?? null;
  228. $contentType = $options['contentType'] ?? 'text/plain; charset=UTF-8';
  229. $headers = $options['headers'] ?? [];
  230. // Allow transformation of content, such as encrypting/signing
  231. $error = false;
  232. if ( !Hooks::run( 'UserMailerTransformContent', [ $to, $from, &$body, &$error ] ) ) {
  233. if ( $error ) {
  234. return Status::newFatal( 'php-mail-error', $error );
  235. } else {
  236. return Status::newFatal( 'php-mail-error-unknown' );
  237. }
  238. }
  239. /**
  240. * Forge email headers
  241. * -------------------
  242. *
  243. * WARNING
  244. *
  245. * DO NOT add To: or Subject: headers at this step. They need to be
  246. * handled differently depending upon the mailer we are going to use.
  247. *
  248. * To:
  249. * PHP mail() first argument is the mail receiver. The argument is
  250. * used as a recipient destination and as a To header.
  251. *
  252. * PEAR mailer has a recipient argument which is only used to
  253. * send the mail. If no To header is given, PEAR will set it to
  254. * to 'undisclosed-recipients:'.
  255. *
  256. * NOTE: To: is for presentation, the actual recipient is specified
  257. * by the mailer using the Rcpt-To: header.
  258. *
  259. * Subject:
  260. * PHP mail() second argument to pass the subject, passing a Subject
  261. * as an additional header will result in a duplicate header.
  262. *
  263. * PEAR mailer should be passed a Subject header.
  264. *
  265. * -- hashar 20120218
  266. */
  267. $headers['From'] = $from->toString();
  268. $returnPath = $from->address;
  269. $extraParams = $wgAdditionalMailParams;
  270. // Hook to generate custom VERP address for 'Return-Path'
  271. Hooks::run( 'UserMailerChangeReturnPath', [ $to, &$returnPath ] );
  272. // Add the envelope sender address using the -f command line option when PHP mail() is used.
  273. // Will default to the $from->address when the UserMailerChangeReturnPath hook fails and the
  274. // generated VERP address when the hook runs effectively.
  275. // PHP runs this through escapeshellcmd(). However that's not sufficient
  276. // escaping (e.g. due to spaces). MediaWiki's email sanitizer should generally
  277. // be good enough, but just in case, put in double quotes, and remove any
  278. // double quotes present (" is not allowed in emails, so should have no
  279. // effect, although this might cause apostrophees to be double escaped)
  280. $returnPathCLI = '"' . str_replace( '"', '', $returnPath ) . '"';
  281. $extraParams .= ' -f ' . $returnPathCLI;
  282. $headers['Return-Path'] = $returnPath;
  283. if ( $replyto ) {
  284. $headers['Reply-To'] = $replyto->toString();
  285. }
  286. $headers['Date'] = MWTimestamp::getLocalInstance()->format( 'r' );
  287. $headers['Message-ID'] = self::makeMsgId();
  288. $headers['X-Mailer'] = 'MediaWiki mailer';
  289. $headers['List-Unsubscribe'] = '<' . SpecialPage::getTitleFor( 'Preferences' )
  290. ->getFullURL( '', false, PROTO_CANONICAL ) . '>';
  291. // Line endings need to be different on Unix and Windows due to
  292. // the bug described at https://core.trac.wordpress.org/ticket/2603
  293. $endl = PHP_EOL;
  294. if ( is_array( $body ) ) {
  295. // we are sending a multipart message
  296. wfDebug( "Assembling multipart mime email\n" );
  297. if ( !self::isMailMimeUsable() ) {
  298. wfDebug( "PEAR Mail_Mime package is not installed. Falling back to text email.\n" );
  299. // remove the html body for text email fall back
  300. $body = $body['text'];
  301. } else {
  302. // pear/mail_mime is already loaded by this point
  303. if ( wfIsWindows() ) {
  304. $body['text'] = str_replace( "\n", "\r\n", $body['text'] );
  305. $body['html'] = str_replace( "\n", "\r\n", $body['html'] );
  306. }
  307. $mime = new Mail_mime( [
  308. 'eol' => $endl,
  309. 'text_charset' => 'UTF-8',
  310. 'html_charset' => 'UTF-8'
  311. ] );
  312. $mime->setTXTBody( $body['text'] );
  313. $mime->setHTMLBody( $body['html'] );
  314. $body = $mime->get(); // must call get() before headers()
  315. $headers = $mime->headers( $headers );
  316. }
  317. }
  318. if ( $mime === null ) {
  319. // sending text only, either deliberately or as a fallback
  320. if ( wfIsWindows() ) {
  321. $body = str_replace( "\n", "\r\n", $body );
  322. }
  323. $headers['MIME-Version'] = '1.0';
  324. $headers['Content-type'] = $contentType;
  325. $headers['Content-transfer-encoding'] = '8bit';
  326. }
  327. // allow transformation of MIME-encoded message
  328. if ( !Hooks::run( 'UserMailerTransformMessage',
  329. [ $to, $from, &$subject, &$headers, &$body, &$error ] )
  330. ) {
  331. if ( $error ) {
  332. return Status::newFatal( 'php-mail-error', $error );
  333. } else {
  334. return Status::newFatal( 'php-mail-error-unknown' );
  335. }
  336. }
  337. $ret = Hooks::run( 'AlternateUserMailer', [ $headers, $to, $from, $subject, $body ] );
  338. if ( $ret === false ) {
  339. // the hook implementation will return false to skip regular mail sending
  340. return Status::newGood();
  341. } elseif ( $ret !== true ) {
  342. // the hook implementation will return a string to pass an error message
  343. return Status::newFatal( 'php-mail-error', $ret );
  344. }
  345. if ( is_array( $wgSMTP ) ) {
  346. // Check if pear/mail is already loaded (via composer)
  347. if ( !self::isMailUsable() ) {
  348. throw new MWException( 'PEAR mail package is not installed' );
  349. }
  350. $recips = array_map( 'strval', $to );
  351. Wikimedia\suppressWarnings();
  352. // Create the mail object using the Mail::factory method
  353. $mail_object = Mail::factory( 'smtp', $wgSMTP );
  354. if ( PEAR::isError( $mail_object ) ) {
  355. wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
  356. Wikimedia\restoreWarnings();
  357. return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
  358. }
  359. '@phan-var Mail_smtp $mail_object';
  360. wfDebug( "Sending mail via PEAR::Mail\n" );
  361. $headers['Subject'] = self::quotedPrintable( $subject );
  362. // When sending only to one recipient, shows it its email using To:
  363. if ( count( $recips ) == 1 ) {
  364. $headers['To'] = $recips[0];
  365. }
  366. // Split jobs since SMTP servers tends to limit the maximum
  367. // number of possible recipients.
  368. $chunks = array_chunk( $recips, $wgEnotifMaxRecips );
  369. foreach ( $chunks as $chunk ) {
  370. $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
  371. // FIXME : some chunks might be sent while others are not!
  372. if ( !$status->isOK() ) {
  373. Wikimedia\restoreWarnings();
  374. return $status;
  375. }
  376. }
  377. Wikimedia\restoreWarnings();
  378. return Status::newGood();
  379. } else {
  380. // PHP mail()
  381. if ( count( $to ) > 1 ) {
  382. $headers['To'] = 'undisclosed-recipients:;';
  383. }
  384. $headers = self::arrayToHeaderString( $headers, $endl );
  385. wfDebug( "Sending mail via internal mail() function\n" );
  386. self::$mErrorString = '';
  387. $html_errors = ini_get( 'html_errors' );
  388. ini_set( 'html_errors', '0' );
  389. set_error_handler( 'UserMailer::errorHandler' );
  390. try {
  391. foreach ( $to as $recip ) {
  392. $sent = mail(
  393. $recip->toString(),
  394. self::quotedPrintable( $subject ),
  395. $body,
  396. $headers,
  397. $extraParams
  398. );
  399. }
  400. } catch ( Exception $e ) {
  401. restore_error_handler();
  402. throw $e;
  403. }
  404. restore_error_handler();
  405. ini_set( 'html_errors', $html_errors );
  406. if ( self::$mErrorString ) {
  407. wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
  408. return Status::newFatal( 'php-mail-error', self::$mErrorString );
  409. } elseif ( !$sent ) {
  410. // mail function only tells if there's an error
  411. wfDebug( "Unknown error sending mail\n" );
  412. return Status::newFatal( 'php-mail-error-unknown' );
  413. } else {
  414. return Status::newGood();
  415. }
  416. }
  417. }
  418. /**
  419. * Set the mail error message in self::$mErrorString
  420. *
  421. * @param int $code Error number
  422. * @param string $string Error message
  423. */
  424. private static function errorHandler( $code, $string ) {
  425. self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
  426. }
  427. /**
  428. * Strips bad characters from a header value to prevent PHP mail header injection attacks
  429. * @param string $val String to be santizied
  430. * @return string
  431. */
  432. public static function sanitizeHeaderValue( $val ) {
  433. return strtr( $val, [ "\r" => '', "\n" => '' ] );
  434. }
  435. /**
  436. * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
  437. * @param string $phrase
  438. * @return string
  439. */
  440. public static function rfc822Phrase( $phrase ) {
  441. // Remove line breaks
  442. $phrase = self::sanitizeHeaderValue( $phrase );
  443. // Remove quotes
  444. $phrase = str_replace( '"', '', $phrase );
  445. return '"' . $phrase . '"';
  446. }
  447. /**
  448. * Converts a string into quoted-printable format
  449. * @since 1.17
  450. *
  451. * From PHP5.3 there is a built in function quoted_printable_encode()
  452. * This method does not duplicate that.
  453. * This method is doing Q encoding inside encoded-words as defined by RFC 2047
  454. * This is for email headers.
  455. * The built in quoted_printable_encode() is for email bodies
  456. * @param string $string
  457. * @param string $charset
  458. * @return string
  459. */
  460. public static function quotedPrintable( $string, $charset = '' ) {
  461. // Probably incomplete; see RFC 2045
  462. if ( empty( $charset ) ) {
  463. $charset = 'UTF-8';
  464. }
  465. $charset = strtoupper( $charset );
  466. $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
  467. $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
  468. $replace = $illegal . '\t ?_';
  469. if ( !preg_match( "/[$illegal]/", $string ) ) {
  470. return $string;
  471. }
  472. $out = "=?$charset?Q?";
  473. $out .= preg_replace_callback( "/([$replace])/",
  474. function ( $matches ) {
  475. return sprintf( "=%02X", ord( $matches[1] ) );
  476. },
  477. $string
  478. );
  479. $out .= '?=';
  480. return $out;
  481. }
  482. }