MediaWiki  master
UserMailer.php
Go to the documentation of this file.
1 <?php
2 
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  // Create the mail object using the Mail::factory method
333  $mail_object = Mail::factory( 'smtp', $smtp );
334  if ( PEAR::isError( $mail_object ) ) {
335  wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() );
336  return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
337  }
338  '@phan-var Mail_smtp $mail_object';
339 
340  wfDebug( "Sending mail via PEAR::Mail" );
341 
342  $headers['Subject'] = self::quotedPrintable( $subject );
343 
344  // When sending only to one recipient, shows it its email using To:
345  if ( count( $recips ) == 1 ) {
346  $headers['To'] = $recips[0];
347  }
348 
349  // Split jobs since SMTP servers tends to limit the maximum
350  // number of possible recipients.
351  $chunks = array_chunk( $recips, $enotifMaxRecips );
352  foreach ( $chunks as $chunk ) {
353  $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
354  // FIXME : some chunks might be sent while others are not!
355  if ( !$status->isOK() ) {
356  return $status;
357  }
358  }
359  return Status::newGood();
360  } else {
361  // PHP mail()
362  if ( count( $to ) > 1 ) {
363  $headers['To'] = 'undisclosed-recipients:;';
364  }
365 
366  wfDebug( "Sending mail via internal mail() function" );
367 
368  self::$mErrorString = '';
369  $html_errors = ini_get( 'html_errors' );
370  ini_set( 'html_errors', '0' );
371  set_error_handler( 'UserMailer::errorHandler' );
372 
373  try {
374  foreach ( $to as $recip ) {
375  $sent = mail(
376  $recip->toString(),
377  self::quotedPrintable( $subject ),
378  $body,
379  $headers,
380  $extraParams
381  );
382  }
383  } catch ( Exception $e ) {
384  restore_error_handler();
385  throw $e;
386  }
387 
388  restore_error_handler();
389  ini_set( 'html_errors', $html_errors );
390 
391  if ( self::$mErrorString ) {
392  wfDebug( "Error sending mail: " . self::$mErrorString );
393  return Status::newFatal( 'php-mail-error', self::$mErrorString );
394  } elseif ( !$sent ) {
395  // @phan-suppress-previous-line PhanPossiblyUndeclaredVariable sent set on success
396  // mail function only tells if there's an error
397  wfDebug( "Unknown error sending mail" );
398  return Status::newFatal( 'php-mail-error-unknown' );
399  } else {
400  return Status::newGood();
401  }
402  }
403  }
404 
411  private static function errorHandler( $code, $string ) {
412  self::$mErrorString = preg_replace( '/^mail\‍(\‍)(\s*\[.*?\])?: /', '', $string );
413  }
414 
420  public static function sanitizeHeaderValue( $val ) {
421  return strtr( $val, [ "\r" => '', "\n" => '' ] );
422  }
423 
429  public static function rfc822Phrase( $phrase ) {
430  // Remove line breaks
431  $phrase = self::sanitizeHeaderValue( $phrase );
432  // Remove quotes
433  $phrase = str_replace( '"', '', $phrase );
434  return '"' . $phrase . '"';
435  }
436 
450  public static function quotedPrintable( $string, $charset = '' ) {
451  // Probably incomplete; see RFC 2045
452  if ( empty( $charset ) ) {
453  $charset = 'UTF-8';
454  }
455  $charset = strtoupper( $charset );
456  $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
457 
458  $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
459  $replace = $illegal . '\t ?_';
460  if ( !preg_match( "/[$illegal]/", $string ) ) {
461  return $string;
462  }
463  $out = "=?$charset?Q?";
464  $out .= preg_replace_callback( "/([$replace])/",
465  static function ( $matches ) {
466  return sprintf( "=%02X", ord( $matches[1] ) );
467  },
468  $string
469  );
470  $out .= '?=';
471  return $out;
472  }
473 }
wfIsWindows()
Check if the operating system is Windows.
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.
$matches
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
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.
Helper tools for dealing with other locally-hosted wikis.
Definition: WikiMap.php:33
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:429
static sanitizeHeaderValue( $val)
Strips bad characters from a header value to prevent PHP mail header injection attacks.
Definition: UserMailer.php:420
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:450
static sendInternal(array $to, MailAddress $from, $subject, $body, $options=[])
Helper function fo UserMailer::send() which does the actual sending.
Definition: UserMailer.php:193
$mime
Definition: router.php:60