MediaWiki  master
UserMailer.php
Go to the documentation of this file.
1 <?php
2 
30 use Wikimedia\AtEase\AtEase;
31 
35 class UserMailer {
36  private static $mErrorString;
37 
48  protected static function sendWithPear( $mailer, $dest, $headers, $body ) {
49  $mailResult = $mailer->send( $dest, $headers, $body );
50 
51  // Based on the result return an error string,
52  if ( PEAR::isError( $mailResult ) ) {
53  wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() );
54  return Status::newFatal( 'pear-mail-error', $mailResult->getMessage() );
55  } else {
56  return Status::newGood();
57  }
58  }
59 
65  private static function makeMsgId() {
66  $smtp = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SMTP );
67  $server = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Server );
68  $domainId = WikiMap::getCurrentWikiDbDomain()->getId();
69  $msgid = uniqid( $domainId . ".", true );
70  if ( is_array( $smtp ) && isset( $smtp['IDHost'] ) && $smtp['IDHost'] ) {
71  $domain = $smtp['IDHost'];
72  } else {
73  $url = wfParseUrl( $server );
74  $domain = $url['host'];
75  }
76  return "<$msgid@$domain>";
77  }
78 
98  public static function send( $to, $from, $subject, $body, $options = [] ) {
99  $allowHTMLEmail = MediaWikiServices::getInstance()->getMainConfig()->get(
100  MainConfigNames::AllowHTMLEmail );
101 
102  if ( !isset( $options['contentType'] ) ) {
103  $options['contentType'] = 'text/plain; charset=UTF-8';
104  }
105 
106  if ( !is_array( $to ) ) {
107  $to = [ $to ];
108  }
109 
110  // mail body must have some content
111  $minBodyLen = 10;
112  // arbitrary but longer than Array or Object to detect casting error
113 
114  // body must either be a string or an array with text and body
115  if (
116  !(
117  !is_array( $body ) &&
118  strlen( $body ) >= $minBodyLen
119  )
120  &&
121  !(
122  is_array( $body ) &&
123  isset( $body['text'] ) &&
124  isset( $body['html'] ) &&
125  strlen( $body['text'] ) >= $minBodyLen &&
126  strlen( $body['html'] ) >= $minBodyLen
127  )
128  ) {
129  // if it is neither we have a problem
130  return Status::newFatal( 'user-mail-no-body' );
131  }
132 
133  if ( !$allowHTMLEmail && is_array( $body ) ) {
134  // HTML not wanted. Dump it.
135  $body = $body['text'];
136  }
137 
138  wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) );
139 
140  // Make sure we have at least one address
141  $has_address = false;
142  foreach ( $to as $u ) {
143  if ( $u->address ) {
144  $has_address = true;
145  break;
146  }
147  }
148  if ( !$has_address ) {
149  return Status::newFatal( 'user-mail-no-addy' );
150  }
151 
152  // give a chance to UserMailerTransformContents subscribers who need to deal with each
153  // target differently to split up the address list
154  if ( count( $to ) > 1 ) {
155  $oldTo = $to;
156  Hooks::runner()->onUserMailerSplitTo( $to );
157  if ( $oldTo != $to ) {
158  $splitTo = array_diff( $oldTo, $to );
159  $to = array_diff( $oldTo, $splitTo ); // ignore new addresses added in the hook
160  // first send to non-split address list, then to split addresses one by one
161  $status = Status::newGood();
162  if ( $to ) {
163  $status->merge( self::sendInternal(
164  $to, $from, $subject, $body, $options ) );
165  }
166  foreach ( $splitTo as $newTo ) {
167  $status->merge( self::sendInternal(
168  [ $newTo ], $from, $subject, $body, $options ) );
169  }
170  return $status;
171  }
172  }
173 
174  return self::sendInternal( $to, $from, $subject, $body, $options );
175  }
176 
193  protected static function sendInternal(
194  array $to,
195  MailAddress $from,
196  $subject,
197  $body,
198  $options = []
199  ) {
200  $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
201  $smtp = $mainConfig->get( MainConfigNames::SMTP );
202  $enotifMaxRecips = $mainConfig->get( MainConfigNames::EnotifMaxRecips );
203  $additionalMailParams = $mainConfig->get( MainConfigNames::AdditionalMailParams );
204 
205  $replyto = $options['replyTo'] ?? null;
206  $contentType = $options['contentType'] ?? 'text/plain; charset=UTF-8';
207  $headers = $options['headers'] ?? [];
208 
209  // Allow transformation of content, such as encrypting/signing
210  $error = false;
211  // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
212  if ( !Hooks::runner()->onUserMailerTransformContent( $to, $from, $body, $error ) ) {
213  if ( $error ) {
214  return Status::newFatal( 'php-mail-error', $error );
215  } else {
216  return Status::newFatal( 'php-mail-error-unknown' );
217  }
218  }
219 
249  $headers['From'] = $from->toString();
250  $returnPath = $from->address;
251  $extraParams = $additionalMailParams;
252 
253  // Hook to generate custom VERP address for 'Return-Path'
254  Hooks::runner()->onUserMailerChangeReturnPath( $to, $returnPath );
255  // Add the envelope sender address using the -f command line option when PHP mail() is used.
256  // Will default to the $from->address when the UserMailerChangeReturnPath hook fails and the
257  // generated VERP address when the hook runs effectively.
258 
259  // PHP runs this through escapeshellcmd(). However that's not sufficient
260  // escaping (e.g. due to spaces). MediaWiki's email sanitizer should generally
261  // be good enough, but just in case, put in double quotes, and remove any
262  // double quotes present (" is not allowed in emails, so should have no
263  // effect, although this might cause apostrophes to be double escaped)
264  $returnPathCLI = '"' . str_replace( '"', '', $returnPath ) . '"';
265  $extraParams .= ' -f ' . $returnPathCLI;
266 
267  $headers['Return-Path'] = $returnPath;
268 
269  if ( $replyto ) {
270  $headers['Reply-To'] = $replyto->toString();
271  }
272 
273  $headers['Date'] = MWTimestamp::getLocalInstance()->format( 'r' );
274  $headers['Message-ID'] = self::makeMsgId();
275  $headers['X-Mailer'] = 'MediaWiki mailer';
276  $headers['List-Unsubscribe'] = '<' . SpecialPage::getTitleFor( 'Preferences' )
277  ->getFullURL( '', false, PROTO_CANONICAL ) . '>';
278 
279  // Line endings need to be different on Unix and Windows due to
280  // the bug described at https://core.trac.wordpress.org/ticket/2603
281  $endl = PHP_EOL;
282 
283  if ( is_array( $body ) ) {
284  // we are sending a multipart message
285  wfDebug( "Assembling multipart mime email" );
286  if ( wfIsWindows() ) {
287  $body['text'] = str_replace( "\n", "\r\n", $body['text'] );
288  $body['html'] = str_replace( "\n", "\r\n", $body['html'] );
289  }
290  $mime = new Mail_mime( [
291  'eol' => $endl,
292  'text_charset' => 'UTF-8',
293  'html_charset' => 'UTF-8'
294  ] );
295  $mime->setTXTBody( $body['text'] );
296  $mime->setHTMLBody( $body['html'] );
297  $body = $mime->get(); // must call get() before headers()
298  $headers = $mime->headers( $headers );
299  } else {
300  // sending text only
301  if ( wfIsWindows() ) {
302  $body = str_replace( "\n", "\r\n", $body );
303  }
304  $headers['MIME-Version'] = '1.0';
305  $headers['Content-type'] = $contentType;
306  $headers['Content-transfer-encoding'] = '8bit';
307  }
308 
309  // allow transformation of MIME-encoded message
310  if ( !Hooks::runner()->onUserMailerTransformMessage(
311  $to, $from, $subject, $headers, $body, $error )
312  ) {
313  if ( $error ) {
314  return Status::newFatal( 'php-mail-error', $error );
315  } else {
316  return Status::newFatal( 'php-mail-error-unknown' );
317  }
318  }
319 
320  $ret = Hooks::runner()->onAlternateUserMailer( $headers, $to, $from, $subject, $body );
321  if ( $ret === false ) {
322  // the hook implementation will return false to skip regular mail sending
323  return Status::newGood();
324  } elseif ( $ret !== true ) {
325  // the hook implementation will return a string to pass an error message
326  return Status::newFatal( 'php-mail-error', $ret );
327  }
328 
329  if ( is_array( $smtp ) ) {
330  $recips = array_map( 'strval', $to );
331 
332  AtEase::suppressWarnings();
333 
334  // Create the mail object using the Mail::factory method
335  $mail_object = Mail::factory( 'smtp', $smtp );
336  if ( PEAR::isError( $mail_object ) ) {
337  wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() );
338  AtEase::restoreWarnings();
339  return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
340  }
341  '@phan-var Mail_smtp $mail_object';
342 
343  wfDebug( "Sending mail via PEAR::Mail" );
344 
345  $headers['Subject'] = self::quotedPrintable( $subject );
346 
347  // When sending only to one recipient, shows it its email using To:
348  if ( count( $recips ) == 1 ) {
349  $headers['To'] = $recips[0];
350  }
351 
352  // Split jobs since SMTP servers tends to limit the maximum
353  // number of possible recipients.
354  $chunks = array_chunk( $recips, $enotifMaxRecips );
355  foreach ( $chunks as $chunk ) {
356  $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
357  // FIXME : some chunks might be sent while others are not!
358  if ( !$status->isOK() ) {
359  AtEase::restoreWarnings();
360  return $status;
361  }
362  }
363  AtEase::restoreWarnings();
364  return Status::newGood();
365  } else {
366  // PHP mail()
367  if ( count( $to ) > 1 ) {
368  $headers['To'] = 'undisclosed-recipients:;';
369  }
370 
371  wfDebug( "Sending mail via internal mail() function" );
372 
373  self::$mErrorString = '';
374  $html_errors = ini_get( 'html_errors' );
375  ini_set( 'html_errors', '0' );
376  set_error_handler( 'UserMailer::errorHandler' );
377 
378  try {
379  foreach ( $to as $recip ) {
380  $sent = mail(
381  $recip->toString(),
382  self::quotedPrintable( $subject ),
383  $body,
384  $headers,
385  $extraParams
386  );
387  }
388  } catch ( Exception $e ) {
389  restore_error_handler();
390  throw $e;
391  }
392 
393  restore_error_handler();
394  ini_set( 'html_errors', $html_errors );
395 
396  if ( self::$mErrorString ) {
397  wfDebug( "Error sending mail: " . self::$mErrorString );
398  return Status::newFatal( 'php-mail-error', self::$mErrorString );
399  } elseif ( !$sent ) {
400  // @phan-suppress-previous-line PhanPossiblyUndeclaredVariable sent set on success
401  // mail function only tells if there's an error
402  wfDebug( "Unknown error sending mail" );
403  return Status::newFatal( 'php-mail-error-unknown' );
404  } else {
405  return Status::newGood();
406  }
407  }
408  }
409 
416  private static function errorHandler( $code, $string ) {
417  self::$mErrorString = preg_replace( '/^mail\‍(\‍)(\s*\[.*?\])?: /', '', $string );
418  }
419 
425  public static function sanitizeHeaderValue( $val ) {
426  return strtr( $val, [ "\r" => '', "\n" => '' ] );
427  }
428 
434  public static function rfc822Phrase( $phrase ) {
435  // Remove line breaks
436  $phrase = self::sanitizeHeaderValue( $phrase );
437  // Remove quotes
438  $phrase = str_replace( '"', '', $phrase );
439  return '"' . $phrase . '"';
440  }
441 
455  public static function quotedPrintable( $string, $charset = '' ) {
456  // Probably incomplete; see RFC 2045
457  if ( empty( $charset ) ) {
458  $charset = 'UTF-8';
459  }
460  $charset = strtoupper( $charset );
461  $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
462 
463  $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
464  $replace = $illegal . '\t ?_';
465  if ( !preg_match( "/[$illegal]/", $string ) ) {
466  return $string;
467  }
468  $out = "=?$charset?Q?";
469  $out .= preg_replace_callback( "/([$replace])/",
470  static function ( $matches ) {
471  return sprintf( "=%02X", ord( $matches[1] ) );
472  },
473  $string
474  );
475  $out .= '?=';
476  return $out;
477  }
478 }
const PROTO_CANONICAL
Definition: Defines.php:199
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfIsWindows()
Check if the operating system is Windows.
$matches
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:173
static getLocalInstance( $ts=false)
Get a timestamp instance in the server local timezone ($wgLocaltimezone)
Stores a single person's name and email address.
Definition: MailAddress.php:36
toString()
Return formatted and quoted address to insert into SMTP headers.
Definition: MailAddress.php:80
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:73
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:85
Collection of static functions for sending mail.
Definition: UserMailer.php:35
static rfc822Phrase( $phrase)
Converts a string into a valid RFC 822 "phrase", such as is used for the sender name.
Definition: UserMailer.php:434
static sanitizeHeaderValue( $val)
Strips bad characters from a header value to prevent PHP mail header injection attacks.
Definition: UserMailer.php:425
static send( $to, $from, $subject, $body, $options=[])
This function will perform a direct (authenticated) login to a SMTP Server to use for mail relaying i...
Definition: UserMailer.php:98
static sendWithPear( $mailer, $dest, $headers, $body)
Send mail using a PEAR mailer.
Definition: UserMailer.php:48
static quotedPrintable( $string, $charset='')
Converts a string into quoted-printable format.
Definition: UserMailer.php:455
static sendInternal(array $to, MailAddress $from, $subject, $body, $options=[])
Helper function fo UserMailer::send() which does the actual sending.
Definition: UserMailer.php:193
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
$mime
Definition: router.php:60