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