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 
72  private static function arrayToHeaderString( $headers, $endl = PHP_EOL ) {
73  $strings = [];
74  foreach ( $headers as $name => $value ) {
75  // Prevent header injection by stripping newlines from value
76  $value = self::sanitizeHeaderValue( $value );
77  $strings[] = "$name: $value";
78  }
79  return implode( $endl, $strings );
80  }
81 
87  private static function makeMsgId() {
88  $smtp = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SMTP );
89  $server = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Server );
90  $domainId = WikiMap::getCurrentWikiDbDomain()->getId();
91  $msgid = uniqid( $domainId . ".", true );
92  if ( is_array( $smtp ) && isset( $smtp['IDHost'] ) && $smtp['IDHost'] ) {
93  $domain = $smtp['IDHost'];
94  } else {
95  $url = wfParseUrl( $server );
96  $domain = $url['host'];
97  }
98  return "<$msgid@$domain>";
99  }
100 
120  public static function send( $to, $from, $subject, $body, $options = [] ) {
121  $allowHTMLEmail = MediaWikiServices::getInstance()->getMainConfig()->get(
122  MainConfigNames::AllowHTMLEmail );
123 
124  if ( !isset( $options['contentType'] ) ) {
125  $options['contentType'] = 'text/plain; charset=UTF-8';
126  }
127 
128  if ( !is_array( $to ) ) {
129  $to = [ $to ];
130  }
131 
132  // mail body must have some content
133  $minBodyLen = 10;
134  // arbitrary but longer than Array or Object to detect casting error
135 
136  // body must either be a string or an array with text and body
137  if (
138  !(
139  !is_array( $body ) &&
140  strlen( $body ) >= $minBodyLen
141  )
142  &&
143  !(
144  is_array( $body ) &&
145  isset( $body['text'] ) &&
146  isset( $body['html'] ) &&
147  strlen( $body['text'] ) >= $minBodyLen &&
148  strlen( $body['html'] ) >= $minBodyLen
149  )
150  ) {
151  // if it is neither we have a problem
152  return Status::newFatal( 'user-mail-no-body' );
153  }
154 
155  if ( !$allowHTMLEmail && is_array( $body ) ) {
156  // HTML not wanted. Dump it.
157  $body = $body['text'];
158  }
159 
160  wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) );
161 
162  // Make sure we have at least one address
163  $has_address = false;
164  foreach ( $to as $u ) {
165  if ( $u->address ) {
166  $has_address = true;
167  break;
168  }
169  }
170  if ( !$has_address ) {
171  return Status::newFatal( 'user-mail-no-addy' );
172  }
173 
174  // give a chance to UserMailerTransformContents subscribers who need to deal with each
175  // target differently to split up the address list
176  if ( count( $to ) > 1 ) {
177  $oldTo = $to;
178  Hooks::runner()->onUserMailerSplitTo( $to );
179  if ( $oldTo != $to ) {
180  $splitTo = array_diff( $oldTo, $to );
181  $to = array_diff( $oldTo, $splitTo ); // ignore new addresses added in the hook
182  // first send to non-split address list, then to split addresses one by one
183  $status = Status::newGood();
184  if ( $to ) {
185  $status->merge( self::sendInternal(
186  $to, $from, $subject, $body, $options ) );
187  }
188  foreach ( $splitTo as $newTo ) {
189  $status->merge( self::sendInternal(
190  [ $newTo ], $from, $subject, $body, $options ) );
191  }
192  return $status;
193  }
194  }
195 
196  return self::sendInternal( $to, $from, $subject, $body, $options );
197  }
198 
205  private static function isMailMimeUsable() {
206  static $usable = null;
207  if ( $usable === null ) {
208  $usable = class_exists( Mail_mime::class );
209  }
210  return $usable;
211  }
212 
219  private static function isMailUsable() {
220  static $usable = null;
221  if ( $usable === null ) {
222  $usable = class_exists( Mail::class );
223  }
224 
225  return $usable;
226  }
227 
244  protected static function sendInternal(
245  array $to,
246  MailAddress $from,
247  $subject,
248  $body,
249  $options = []
250  ) {
251  $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
252  $smtp = $mainConfig->get( MainConfigNames::SMTP );
253  $enotifMaxRecips = $mainConfig->get( MainConfigNames::EnotifMaxRecips );
254  $additionalMailParams = $mainConfig->get( MainConfigNames::AdditionalMailParams );
255  $mime = null;
256 
257  $replyto = $options['replyTo'] ?? null;
258  $contentType = $options['contentType'] ?? 'text/plain; charset=UTF-8';
259  $headers = $options['headers'] ?? [];
260 
261  // Allow transformation of content, such as encrypting/signing
262  $error = false;
263  // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
264  if ( !Hooks::runner()->onUserMailerTransformContent( $to, $from, $body, $error ) ) {
265  if ( $error ) {
266  return Status::newFatal( 'php-mail-error', $error );
267  } else {
268  return Status::newFatal( 'php-mail-error-unknown' );
269  }
270  }
271 
301  $headers['From'] = $from->toString();
302  $returnPath = $from->address;
303  $extraParams = $additionalMailParams;
304 
305  // Hook to generate custom VERP address for 'Return-Path'
306  Hooks::runner()->onUserMailerChangeReturnPath( $to, $returnPath );
307  // Add the envelope sender address using the -f command line option when PHP mail() is used.
308  // Will default to the $from->address when the UserMailerChangeReturnPath hook fails and the
309  // generated VERP address when the hook runs effectively.
310 
311  // PHP runs this through escapeshellcmd(). However that's not sufficient
312  // escaping (e.g. due to spaces). MediaWiki's email sanitizer should generally
313  // be good enough, but just in case, put in double quotes, and remove any
314  // double quotes present (" is not allowed in emails, so should have no
315  // effect, although this might cause apostrophes to be double escaped)
316  $returnPathCLI = '"' . str_replace( '"', '', $returnPath ) . '"';
317  $extraParams .= ' -f ' . $returnPathCLI;
318 
319  $headers['Return-Path'] = $returnPath;
320 
321  if ( $replyto ) {
322  $headers['Reply-To'] = $replyto->toString();
323  }
324 
325  $headers['Date'] = MWTimestamp::getLocalInstance()->format( 'r' );
326  $headers['Message-ID'] = self::makeMsgId();
327  $headers['X-Mailer'] = 'MediaWiki mailer';
328  $headers['List-Unsubscribe'] = '<' . SpecialPage::getTitleFor( 'Preferences' )
329  ->getFullURL( '', false, PROTO_CANONICAL ) . '>';
330 
331  // Line endings need to be different on Unix and Windows due to
332  // the bug described at https://core.trac.wordpress.org/ticket/2603
333  $endl = PHP_EOL;
334 
335  if ( is_array( $body ) ) {
336  // we are sending a multipart message
337  wfDebug( "Assembling multipart mime email" );
338  if ( !self::isMailMimeUsable() ) {
339  wfDebug( "PEAR Mail_Mime package is not installed. Falling back to text email." );
340  // remove the html body for text email fall back
341  $body = $body['text'];
342  } else {
343  // pear/mail_mime is already loaded by this point
344  if ( wfIsWindows() ) {
345  $body['text'] = str_replace( "\n", "\r\n", $body['text'] );
346  $body['html'] = str_replace( "\n", "\r\n", $body['html'] );
347  }
348  $mime = new Mail_mime( [
349  'eol' => $endl,
350  'text_charset' => 'UTF-8',
351  'html_charset' => 'UTF-8'
352  ] );
353  $mime->setTXTBody( $body['text'] );
354  $mime->setHTMLBody( $body['html'] );
355  $body = $mime->get(); // must call get() before headers()
356  $headers = $mime->headers( $headers );
357  }
358  }
359  if ( $mime === null ) {
360  // sending text only, either deliberately or as a fallback
361  if ( wfIsWindows() ) {
362  $body = str_replace( "\n", "\r\n", $body );
363  }
364  $headers['MIME-Version'] = '1.0';
365  $headers['Content-type'] = $contentType;
366  $headers['Content-transfer-encoding'] = '8bit';
367  }
368 
369  // allow transformation of MIME-encoded message
370  if ( !Hooks::runner()->onUserMailerTransformMessage(
371  $to, $from, $subject, $headers, $body, $error )
372  ) {
373  if ( $error ) {
374  return Status::newFatal( 'php-mail-error', $error );
375  } else {
376  return Status::newFatal( 'php-mail-error-unknown' );
377  }
378  }
379 
380  $ret = Hooks::runner()->onAlternateUserMailer( $headers, $to, $from, $subject, $body );
381  if ( $ret === false ) {
382  // the hook implementation will return false to skip regular mail sending
383  return Status::newGood();
384  } elseif ( $ret !== true ) {
385  // the hook implementation will return a string to pass an error message
386  return Status::newFatal( 'php-mail-error', $ret );
387  }
388 
389  if ( is_array( $smtp ) ) {
390  // Check if pear/mail is already loaded (via composer)
391  if ( !self::isMailUsable() ) {
392  throw new MWException( 'PEAR mail package is not installed' );
393  }
394 
395  $recips = array_map( 'strval', $to );
396 
397  AtEase::suppressWarnings();
398 
399  // Create the mail object using the Mail::factory method
400  $mail_object = Mail::factory( 'smtp', $smtp );
401  if ( PEAR::isError( $mail_object ) ) {
402  wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() );
403  AtEase::restoreWarnings();
404  return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
405  }
406  '@phan-var Mail_smtp $mail_object';
407 
408  wfDebug( "Sending mail via PEAR::Mail" );
409 
410  $headers['Subject'] = self::quotedPrintable( $subject );
411 
412  // When sending only to one recipient, shows it its email using To:
413  if ( count( $recips ) == 1 ) {
414  $headers['To'] = $recips[0];
415  }
416 
417  // Split jobs since SMTP servers tends to limit the maximum
418  // number of possible recipients.
419  $chunks = array_chunk( $recips, $enotifMaxRecips );
420  foreach ( $chunks as $chunk ) {
421  $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
422  // FIXME : some chunks might be sent while others are not!
423  if ( !$status->isOK() ) {
424  AtEase::restoreWarnings();
425  return $status;
426  }
427  }
428  AtEase::restoreWarnings();
429  return Status::newGood();
430  } else {
431  // PHP mail()
432  if ( count( $to ) > 1 ) {
433  $headers['To'] = 'undisclosed-recipients:;';
434  }
435  $headers = self::arrayToHeaderString( $headers, $endl );
436 
437  wfDebug( "Sending mail via internal mail() function" );
438 
439  self::$mErrorString = '';
440  $html_errors = ini_get( 'html_errors' );
441  ini_set( 'html_errors', '0' );
442  set_error_handler( 'UserMailer::errorHandler' );
443 
444  try {
445  foreach ( $to as $recip ) {
446  $sent = mail(
447  $recip->toString(),
448  self::quotedPrintable( $subject ),
449  $body,
450  $headers,
451  $extraParams
452  );
453  }
454  } catch ( Exception $e ) {
455  restore_error_handler();
456  throw $e;
457  }
458 
459  restore_error_handler();
460  ini_set( 'html_errors', $html_errors );
461 
462  if ( self::$mErrorString ) {
463  wfDebug( "Error sending mail: " . self::$mErrorString );
464  return Status::newFatal( 'php-mail-error', self::$mErrorString );
465  } elseif ( !$sent ) {
466  // @phan-suppress-previous-line PhanPossiblyUndeclaredVariable sent set on success
467  // mail function only tells if there's an error
468  wfDebug( "Unknown error sending mail" );
469  return Status::newFatal( 'php-mail-error-unknown' );
470  } else {
471  return Status::newGood();
472  }
473  }
474  }
475 
482  private static function errorHandler( $code, $string ) {
483  self::$mErrorString = preg_replace( '/^mail\‍(\‍)(\s*\[.*?\])?: /', '', $string );
484  }
485 
491  public static function sanitizeHeaderValue( $val ) {
492  return strtr( $val, [ "\r" => '', "\n" => '' ] );
493  }
494 
500  public static function rfc822Phrase( $phrase ) {
501  // Remove line breaks
502  $phrase = self::sanitizeHeaderValue( $phrase );
503  // Remove quotes
504  $phrase = str_replace( '"', '', $phrase );
505  return '"' . $phrase . '"';
506  }
507 
521  public static function quotedPrintable( $string, $charset = '' ) {
522  // Probably incomplete; see RFC 2045
523  if ( empty( $charset ) ) {
524  $charset = 'UTF-8';
525  }
526  $charset = strtoupper( $charset );
527  $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
528 
529  $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
530  $replace = $illegal . '\t ?_';
531  if ( !preg_match( "/[$illegal]/", $string ) ) {
532  return $string;
533  }
534  $out = "=?$charset?Q?";
535  $out .= preg_replace_callback( "/([$replace])/",
536  static function ( $matches ) {
537  return sprintf( "=%02X", ord( $matches[1] ) );
538  },
539  $string
540  );
541  $out .= '?=';
542  return $out;
543  }
544 }
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
MediaWiki exception.
Definition: MWException.php:29
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:70
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
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:500
static sanitizeHeaderValue( $val)
Strips bad characters from a header value to prevent PHP mail header injection attacks.
Definition: UserMailer.php:491
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:120
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:521
static sendInternal(array $to, MailAddress $from, $subject, $body, $options=[])
Helper function fo UserMailer::send() which does the actual sending.
Definition: UserMailer.php:244
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
$mime
Definition: router.php:60