Merge "Add ss_active_users in SiteStats::isSane"
[mediawiki.git] / includes / UserMailer.php
blobe48070aa04c6755d4e322bf8eeea1d6d8add0b05
1 <?php
2 /**
3 * Classes used to send e-mails
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.
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.
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
20 * @file
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
24 * @author Luke Welling lwelling@wikimedia.org
27 /**
28 * Stores a single person's name and email address.
29 * These are passed in via the constructor, and will be returned in SMTP
30 * header format when requested.
32 class MailAddress {
33 /**
34 * @param string|User $address string with an email address, or a User object
35 * @param string $name human-readable name if a string address is given
36 * @param string $realName human-readable real name if a string address is given
38 function __construct( $address, $name = null, $realName = null ) {
39 if ( is_object( $address ) && $address instanceof User ) {
40 $this->address = $address->getEmail();
41 $this->name = $address->getName();
42 $this->realName = $address->getRealName();
43 } else {
44 $this->address = strval( $address );
45 $this->name = strval( $name );
46 $this->realName = strval( $realName );
50 /**
51 * Return formatted and quoted address to insert into SMTP headers
52 * @return string
54 function toString() {
55 # PHP's mail() implementation under Windows is somewhat shite, and
56 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
57 # so don't bother generating them
58 if ( $this->address ) {
59 if ( $this->name != '' && !wfIsWindows() ) {
60 global $wgEnotifUseRealName;
61 $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
62 $quoted = UserMailer::quotedPrintable( $name );
63 if ( strpos( $quoted, '.' ) !== false || strpos( $quoted, ',' ) !== false ) {
64 $quoted = '"' . $quoted . '"';
66 return "$quoted <{$this->address}>";
67 } else {
68 return $this->address;
70 } else {
71 return "";
75 function __toString() {
76 return $this->toString();
80 /**
81 * Collection of static functions for sending mail
83 class UserMailer {
84 static $mErrorString;
86 /**
87 * Send mail using a PEAR mailer
89 * @param $mailer
90 * @param $dest
91 * @param $headers
92 * @param $body
94 * @return Status
96 protected static function sendWithPear( $mailer, $dest, $headers, $body ) {
97 $mailResult = $mailer->send( $dest, $headers, $body );
99 # Based on the result return an error string,
100 if ( PEAR::isError( $mailResult ) ) {
101 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
102 return Status::newFatal( 'pear-mail-error', $mailResult->getMessage() );
103 } else {
104 return Status::newGood();
109 * Creates a single string from an associative array
111 * @param array $headers Associative Array: keys are header field names,
112 * values are ... values.
113 * @param string $endl The end of line character. Defaults to "\n"
115 * Note RFC2822 says newlines must be CRLF (\r\n)
116 * but php mail naively "corrects" it and requires \n for the "correction" to work
118 * @return String
120 static function arrayToHeaderString( $headers, $endl = "\n" ) {
121 $strings = array();
122 foreach ( $headers as $name => $value ) {
123 $strings[] = "$name: $value";
125 return implode( $endl, $strings );
129 * Create a value suitable for the MessageId Header
131 * @return String
133 static function makeMsgId() {
134 global $wgSMTP, $wgServer;
136 $msgid = uniqid( wfWikiID() . ".", true ); /* true required for cygwin */
137 if ( is_array( $wgSMTP ) && isset( $wgSMTP['IDHost'] ) && $wgSMTP['IDHost'] ) {
138 $domain = $wgSMTP['IDHost'];
139 } else {
140 $url = wfParseUrl( $wgServer );
141 $domain = $url['host'];
143 return "<$msgid@$domain>";
147 * This function will perform a direct (authenticated) login to
148 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
149 * array of parameters. It requires PEAR:Mail to do that.
150 * Otherwise it just uses the standard PHP 'mail' function.
152 * @param $to MailAddress: recipient's email (or an array of them)
153 * @param $from MailAddress: sender's email
154 * @param string $subject email's subject.
155 * @param string $body email's text or Array of two strings to be the text and html bodies
156 * @param $replyto MailAddress: optional reply-to email (default: null).
157 * @param string $contentType optional custom Content-Type (default: text/plain; charset=UTF-8)
158 * @throws MWException
159 * @return Status object
161 public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8' ) {
162 global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams, $wgAllowHTMLEmail;
163 $mime = null;
164 if ( !is_array( $to ) ) {
165 $to = array( $to );
168 // mail body must have some content
169 $minBodyLen = 10;
170 // arbitrary but longer than Array or Object to detect casting error
172 // body must either be a string or an array with text and body
173 if (
175 !is_array( $body ) &&
176 strlen( $body ) >= $minBodyLen
180 is_array( $body ) &&
181 isset( $body['text'] ) &&
182 isset( $body['html'] ) &&
183 strlen( $body['text'] ) >= $minBodyLen &&
184 strlen( $body['html'] ) >= $minBodyLen
187 // if it is neither we have a problem
188 return Status::newFatal( 'user-mail-no-body' );
191 if ( !$wgAllowHTMLEmail && is_array( $body ) ) {
192 // HTML not wanted. Dump it.
193 $body = $body['text'];
196 wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) . "\n" );
198 # Make sure we have at least one address
199 $has_address = false;
200 foreach ( $to as $u ) {
201 if ( $u->address ) {
202 $has_address = true;
203 break;
206 if ( !$has_address ) {
207 return Status::newFatal( 'user-mail-no-addy' );
210 # Forge email headers
211 # -------------------
213 # WARNING
215 # DO NOT add To: or Subject: headers at this step. They need to be
216 # handled differently depending upon the mailer we are going to use.
218 # To:
219 # PHP mail() first argument is the mail receiver. The argument is
220 # used as a recipient destination and as a To header.
222 # PEAR mailer has a recipient argument which is only used to
223 # send the mail. If no To header is given, PEAR will set it to
224 # to 'undisclosed-recipients:'.
226 # NOTE: To: is for presentation, the actual recipient is specified
227 # by the mailer using the Rcpt-To: header.
229 # Subject:
230 # PHP mail() second argument to pass the subject, passing a Subject
231 # as an additional header will result in a duplicate header.
233 # PEAR mailer should be passed a Subject header.
235 # -- hashar 20120218
237 $headers['From'] = $from->toString();
238 $headers['Return-Path'] = $from->address;
240 if ( $replyto ) {
241 $headers['Reply-To'] = $replyto->toString();
244 $headers['Date'] = date( 'r' );
245 $headers['Message-ID'] = self::makeMsgId();
246 $headers['X-Mailer'] = 'MediaWiki mailer';
248 # Line endings need to be different on Unix and Windows due to
249 # the bug described at http://trac.wordpress.org/ticket/2603
250 if ( wfIsWindows() ) {
251 $endl = "\r\n";
252 } else {
253 $endl = "\n";
256 if ( is_array( $body ) ) {
257 // we are sending a multipart message
258 wfDebug( "Assembling multipart mime email\n" );
259 if ( !stream_resolve_include_path( 'Mail/mime.php' ) ) {
260 wfDebug( "PEAR Mail_Mime package is not installed. Falling back to text email.\n" );
262 else {
263 require_once 'Mail/mime.php';
264 if ( wfIsWindows() ) {
265 $body['text'] = str_replace( "\n", "\r\n", $body['text'] );
266 $body['html'] = str_replace( "\n", "\r\n", $body['html'] );
268 $mime = new Mail_mime( array( 'eol' => $endl ) );
269 $mime->setTXTBody( $body['text'] );
270 $mime->setHTMLBody( $body['html'] );
271 $body = $mime->get(); // must call get() before headers()
272 $headers = $mime->headers( $headers );
275 if ( !isset( $mime ) ) {
276 // sending text only, either deliberately or as a fallback
277 if ( wfIsWindows() ) {
278 $body = str_replace( "\n", "\r\n", $body );
280 $headers['MIME-Version'] = '1.0';
281 $headers['Content-type'] = ( is_null( $contentType ) ?
282 'text/plain; charset=UTF-8' : $contentType );
283 $headers['Content-transfer-encoding'] = '8bit';
286 $ret = wfRunHooks( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) );
287 if ( $ret === false ) {
288 // the hook implementation will return false to skip regular mail sending
289 return Status::newGood();
290 } elseif ( $ret !== true ) {
291 // the hook implementation will return a string to pass an error message
292 return Status::newFatal( 'php-mail-error', $ret );
295 if ( is_array( $wgSMTP ) ) {
297 # PEAR MAILER
300 if ( !stream_resolve_include_path( 'Mail.php' ) ) {
301 throw new MWException( 'PEAR mail package is not installed' );
303 require_once 'Mail.php';
305 wfSuppressWarnings();
307 // Create the mail object using the Mail::factory method
308 $mail_object =& Mail::factory( 'smtp', $wgSMTP );
309 if ( PEAR::isError( $mail_object ) ) {
310 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
311 wfRestoreWarnings();
312 return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
315 wfDebug( "Sending mail via PEAR::Mail\n" );
317 $headers['Subject'] = self::quotedPrintable( $subject );
319 # When sending only to one recipient, shows it its email using To:
320 if ( count( $to ) == 1 ) {
321 $headers['To'] = $to[0]->toString();
324 # Split jobs since SMTP servers tends to limit the maximum
325 # number of possible recipients.
326 $chunks = array_chunk( $to, $wgEnotifMaxRecips );
327 foreach ( $chunks as $chunk ) {
328 $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
329 # FIXME : some chunks might be sent while others are not!
330 if ( !$status->isOK() ) {
331 wfRestoreWarnings();
332 return $status;
335 wfRestoreWarnings();
336 return Status::newGood();
337 } else {
339 # PHP mail()
341 if ( count( $to ) > 1 ) {
342 $headers['To'] = 'undisclosed-recipients:;';
344 $headers = self::arrayToHeaderString( $headers, $endl );
346 wfDebug( "Sending mail via internal mail() function\n" );
348 self::$mErrorString = '';
349 $html_errors = ini_get( 'html_errors' );
350 ini_set( 'html_errors', '0' );
351 set_error_handler( 'UserMailer::errorHandler' );
353 $safeMode = wfIniGetBool( 'safe_mode' );
355 foreach ( $to as $recip ) {
356 if ( $safeMode ) {
357 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers );
358 } else {
359 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
363 restore_error_handler();
364 ini_set( 'html_errors', $html_errors );
366 if ( self::$mErrorString ) {
367 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
368 return Status::newFatal( 'php-mail-error', self::$mErrorString );
369 } elseif ( ! $sent ) {
370 // mail function only tells if there's an error
371 wfDebug( "Unknown error sending mail\n" );
372 return Status::newFatal( 'php-mail-error-unknown' );
373 } else {
374 return Status::newGood();
380 * Set the mail error message in self::$mErrorString
382 * @param $code Integer: error number
383 * @param string $string error message
385 static function errorHandler( $code, $string ) {
386 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
390 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
391 * @param $phrase string
392 * @return string
394 public static function rfc822Phrase( $phrase ) {
395 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
396 return '"' . $phrase . '"';
400 * Converts a string into quoted-printable format
401 * @since 1.17
403 * From PHP5.3 there is a built in function quoted_printable_encode()
404 * This method does not duplicate that.
405 * This method is doing Q encoding inside encoded-words as defined by RFC 2047
406 * This is for email headers.
407 * The built in quoted_printable_encode() is for email bodies
408 * @return string
410 public static function quotedPrintable( $string, $charset = '' ) {
411 # Probably incomplete; see RFC 2045
412 if ( empty( $charset ) ) {
413 $charset = 'UTF-8';
415 $charset = strtoupper( $charset );
416 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
418 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
419 $replace = $illegal . '\t ?_';
420 if ( !preg_match( "/[$illegal]/", $string ) ) {
421 return $string;
423 $out = "=?$charset?Q?";
424 $out .= preg_replace_callback( "/([$replace])/",
425 array( __CLASS__, 'quotedPrintableCallback' ), $string );
426 $out .= '?=';
427 return $out;
430 protected static function quotedPrintableCallback( $matches ) {
431 return sprintf( "=%02X", ord( $matches[1] ) );
436 * This module processes the email notifications when the current page is
437 * changed. It looks up the table watchlist to find out which users are watching
438 * that page.
440 * The current implementation sends independent emails to each watching user for
441 * the following reason:
443 * - Each watching user will be notified about the page edit time expressed in
444 * his/her local time (UTC is shown additionally). To achieve this, we need to
445 * find the individual timeoffset of each watching user from the preferences..
447 * Suggested improvement to slack down the number of sent emails: We could think
448 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
449 * same timeoffset in their preferences.
451 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
455 class EmailNotification {
456 protected $subject, $body, $replyto, $from;
457 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
458 protected $mailTargets = array();
461 * @var Title
463 protected $title;
466 * @var User
468 protected $editor;
471 * Send emails corresponding to the user $editor editing the page $title.
472 * Also updates wl_notificationtimestamp.
474 * May be deferred via the job queue.
476 * @param $editor User object
477 * @param $title Title object
478 * @param $timestamp
479 * @param $summary
480 * @param $minorEdit
481 * @param $oldid (default: false)
482 * @param $pageStatus (default: 'changed')
484 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false, $pageStatus = 'changed' ) {
485 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
486 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
488 if ( $title->getNamespace() < 0 ) {
489 return;
492 // Build a list of users to notify
493 $watchers = array();
494 if ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) {
495 $dbw = wfGetDB( DB_MASTER );
496 $res = $dbw->select( array( 'watchlist' ),
497 array( 'wl_user' ),
498 array(
499 'wl_user != ' . intval( $editor->getID() ),
500 'wl_namespace' => $title->getNamespace(),
501 'wl_title' => $title->getDBkey(),
502 'wl_notificationtimestamp IS NULL',
503 ), __METHOD__
505 foreach ( $res as $row ) {
506 $watchers[] = intval( $row->wl_user );
508 if ( $watchers ) {
509 // Update wl_notificationtimestamp for all watching users except the editor
510 $fname = __METHOD__;
511 $dbw->onTransactionIdle(
512 function() use ( $dbw, $timestamp, $watchers, $title, $fname ) {
513 $dbw->begin( $fname );
514 $dbw->update( 'watchlist',
515 array( /* SET */
516 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
517 ), array( /* WHERE */
518 'wl_user' => $watchers,
519 'wl_namespace' => $title->getNamespace(),
520 'wl_title' => $title->getDBkey(),
521 ), $fname
523 $dbw->commit( $fname );
529 $sendEmail = true;
530 // If nobody is watching the page, and there are no users notified on all changes
531 // don't bother creating a job/trying to send emails
532 // $watchers deals with $wgEnotifWatchlist
533 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
534 $sendEmail = false;
535 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
536 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
537 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
538 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
539 $sendEmail = true;
544 if ( !$sendEmail ) {
545 return;
547 if ( $wgEnotifUseJobQ ) {
548 $params = array(
549 'editor' => $editor->getName(),
550 'editorID' => $editor->getID(),
551 'timestamp' => $timestamp,
552 'summary' => $summary,
553 'minorEdit' => $minorEdit,
554 'oldid' => $oldid,
555 'watchers' => $watchers,
556 'pageStatus' => $pageStatus
558 $job = new EnotifNotifyJob( $title, $params );
559 JobQueueGroup::singleton()->push( $job );
560 } else {
561 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers, $pageStatus );
566 * Immediate version of notifyOnPageChange().
568 * Send emails corresponding to the user $editor editing the page $title.
569 * Also updates wl_notificationtimestamp.
571 * @param $editor User object
572 * @param $title Title object
573 * @param string $timestamp Edit timestamp
574 * @param string $summary Edit summary
575 * @param $minorEdit bool
576 * @param int $oldid Revision ID
577 * @param array $watchers of user IDs
578 * @param string $pageStatus
579 * @throws MWException
581 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
582 $oldid, $watchers, $pageStatus = 'changed' ) {
583 # we use $wgPasswordSender as sender's address
584 global $wgEnotifWatchlist;
585 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
587 wfProfileIn( __METHOD__ );
589 # The following code is only run, if several conditions are met:
590 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
591 # 2. minor edits (changes) are only regarded if the global flag indicates so
593 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
595 $this->title = $title;
596 $this->timestamp = $timestamp;
597 $this->summary = $summary;
598 $this->minorEdit = $minorEdit;
599 $this->oldid = $oldid;
600 $this->editor = $editor;
601 $this->composed_common = false;
602 $this->pageStatus = $pageStatus;
604 $formattedPageStatus = array( 'deleted', 'created', 'moved', 'restored', 'changed' );
606 wfRunHooks( 'UpdateUserMailerFormattedPageStatus', array( &$formattedPageStatus ) );
607 if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
608 wfProfileOut( __METHOD__ );
609 throw new MWException( 'Not a valid page status!' );
612 $userTalkId = false;
614 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
616 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
617 $targetUser = User::newFromName( $title->getText() );
618 $this->compose( $targetUser );
619 $userTalkId = $targetUser->getId();
622 if ( $wgEnotifWatchlist ) {
623 // Send updates to watchers other than the current editor
624 $userArray = UserArray::newFromIDs( $watchers );
625 foreach ( $userArray as $watchingUser ) {
626 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
627 ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) ) &&
628 $watchingUser->isEmailConfirmed() &&
629 $watchingUser->getID() != $userTalkId )
631 $this->compose( $watchingUser );
637 global $wgUsersNotifiedOnAllChanges;
638 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
639 if ( $editor->getName() == $name ) {
640 // No point notifying the user that actually made the change!
641 continue;
643 $user = User::newFromName( $name );
644 $this->compose( $user );
647 $this->sendMails();
648 wfProfileOut( __METHOD__ );
652 * @param $editor User
653 * @param $title Title bool
654 * @param $minorEdit
655 * @return bool
657 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
658 global $wgEnotifUserTalk;
659 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
661 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
662 $targetUser = User::newFromName( $title->getText() );
664 if ( !$targetUser || $targetUser->isAnon() ) {
665 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
666 } elseif ( $targetUser->getId() == $editor->getId() ) {
667 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
668 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) &&
669 ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) ) )
671 if ( $targetUser->isEmailConfirmed() ) {
672 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
673 return true;
674 } else {
675 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
677 } else {
678 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
681 return false;
685 * Generate the generic "this page has been changed" e-mail text.
687 private function composeCommonMailtext() {
688 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
689 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
690 global $wgEnotifImpersonal, $wgEnotifUseRealName;
692 $this->composed_common = true;
694 # You as the WikiAdmin and Sysops can make use of plenty of
695 # named variables when composing your notification emails while
696 # simply editing the Meta pages
698 $keys = array();
699 $postTransformKeys = array();
700 $pageTitleUrl = $this->title->getCanonicalURL();
701 $pageTitle = $this->title->getPrefixedText();
703 if ( $this->oldid ) {
704 // Always show a link to the diff which triggered the mail. See bug 32210.
705 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
706 $this->title->getCanonicalURL( array( 'diff' => 'next', 'oldid' => $this->oldid ) ) )
707 ->inContentLanguage()->text();
709 if ( !$wgEnotifImpersonal ) {
710 // For personal mail, also show a link to the diff of all changes
711 // since last visited.
712 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
713 $this->title->getCanonicalURL( array( 'diff' => '0', 'oldid' => $this->oldid ) ) )
714 ->inContentLanguage()->text();
716 $keys['$OLDID'] = $this->oldid;
717 // @deprecated Remove in MediaWiki 1.23.
718 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
719 } else {
720 # clear $OLDID placeholder in the message template
721 $keys['$OLDID'] = '';
722 $keys['$NEWPAGE'] = '';
723 // @deprecated Remove in MediaWiki 1.23.
724 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
727 $keys['$PAGETITLE'] = $this->title->getPrefixedText();
728 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalURL();
729 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
730 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
731 $keys['$UNWATCHURL'] = $this->title->getCanonicalURL( 'action=unwatch' );
733 if ( $this->editor->isAnon() ) {
734 # real anon (user:xxx.xxx.xxx.xxx)
735 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
736 ->inContentLanguage()->text();
737 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
739 } else {
740 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName ? $this->editor->getRealName() : $this->editor->getName();
741 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
742 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
745 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
747 # Replace this after transforming the message, bug 35019
748 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
750 # Now build message's subject and body
751 $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
752 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
754 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
755 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
756 ->text();
758 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
759 $body = strtr( $body, $keys );
760 $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
761 $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
763 # Reveal the page editor's address as REPLY-TO address only if
764 # the user has not opted-out and the option is enabled at the
765 # global configuration level.
766 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
767 if ( $wgEnotifRevealEditorAddress
768 && ( $this->editor->getEmail() != '' )
769 && $this->editor->getOption( 'enotifrevealaddr' ) )
771 $editorAddress = new MailAddress( $this->editor );
772 if ( $wgEnotifFromEditor ) {
773 $this->from = $editorAddress;
774 } else {
775 $this->from = $adminAddress;
776 $this->replyto = $editorAddress;
778 } else {
779 $this->from = $adminAddress;
780 $this->replyto = new MailAddress( $wgNoReplyAddress );
785 * Compose a mail to a given user and either queue it for sending, or send it now,
786 * depending on settings.
788 * Call sendMails() to send any mails that were queued.
789 * @param $user User
791 function compose( $user ) {
792 global $wgEnotifImpersonal;
794 if ( !$this->composed_common ) {
795 $this->composeCommonMailtext();
798 if ( $wgEnotifImpersonal ) {
799 $this->mailTargets[] = new MailAddress( $user );
800 } else {
801 $this->sendPersonalised( $user );
806 * Send any queued mails
808 function sendMails() {
809 global $wgEnotifImpersonal;
810 if ( $wgEnotifImpersonal ) {
811 $this->sendImpersonal( $this->mailTargets );
816 * Does the per-user customizations to a notification e-mail (name,
817 * timestamp in proper timezone, etc) and sends it out.
818 * Returns true if the mail was sent successfully.
820 * @param $watchingUser User object
821 * @return Boolean
822 * @private
824 function sendPersonalised( $watchingUser ) {
825 global $wgContLang, $wgEnotifUseRealName;
826 // From the PHP manual:
827 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
828 // The mail command will not parse this properly while talking with the MTA.
829 $to = new MailAddress( $watchingUser );
831 # $PAGEEDITDATE is the time and date of the page change
832 # expressed in terms of individual local time of the notification
833 # recipient, i.e. watching user
834 $body = str_replace(
835 array( '$WATCHINGUSERNAME',
836 '$PAGEEDITDATE',
837 '$PAGEEDITTIME' ),
838 array( $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName(),
839 $wgContLang->userDate( $this->timestamp, $watchingUser ),
840 $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
841 $this->body );
843 return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
847 * Same as sendPersonalised but does impersonal mail suitable for bulk
848 * mailing. Takes an array of MailAddress objects.
849 * @param $addresses array
850 * @return Status|null
852 function sendImpersonal( $addresses ) {
853 global $wgContLang;
855 if ( empty( $addresses ) ) {
856 return null;
859 $body = str_replace(
860 array( '$WATCHINGUSERNAME',
861 '$PAGEEDITDATE',
862 '$PAGEEDITTIME' ),
863 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
864 $wgContLang->date( $this->timestamp, false, false ),
865 $wgContLang->time( $this->timestamp, false, false ) ),
866 $this->body );
868 return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
871 } # end of class EmailNotification