Merge "resourceloader: Condition-wrap the HTML tag instead of JS response"
[mediawiki.git] / includes / UserMailer.php
blob0ce9b5aaa5c1750bbec0f3bb452f6475a64e2112
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 private static $mErrorString;
86 /**
87 * Send mail using a PEAR mailer
89 * @param UserMailer $mailer
90 * @param string $dest
91 * @param string $headers
92 * @param string $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 // Prevent header injection by stripping newlines from value
124 $value = self::sanitizeHeaderValue( $value );
125 $strings[] = "$name: $value";
127 return implode( $endl, $strings );
131 * Create a value suitable for the MessageId Header
133 * @return string
135 static function makeMsgId() {
136 global $wgSMTP, $wgServer;
138 $msgid = uniqid( wfWikiID() . ".", true ); /* true required for cygwin */
139 if ( is_array( $wgSMTP ) && isset( $wgSMTP['IDHost'] ) && $wgSMTP['IDHost'] ) {
140 $domain = $wgSMTP['IDHost'];
141 } else {
142 $url = wfParseUrl( $wgServer );
143 $domain = $url['host'];
145 return "<$msgid@$domain>";
149 * This function will perform a direct (authenticated) login to
150 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
151 * array of parameters. It requires PEAR:Mail to do that.
152 * Otherwise it just uses the standard PHP 'mail' function.
154 * @param MailAddress|MailAddress[] $to Recipient's email (or an array of them)
155 * @param MailAddress $from Sender's email
156 * @param string $subject Email's subject.
157 * @param string $body Email's text or Array of two strings to be the text and html bodies
158 * @param MailAddress $replyto Optional reply-to email (default: null).
159 * @param string $contentType Optional custom Content-Type (default: text/plain; charset=UTF-8)
160 * @throws MWException
161 * @throws Exception
162 * @return Status
164 public static function send( $to, $from, $subject, $body, $replyto = null,
165 $contentType = 'text/plain; charset=UTF-8'
167 global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams, $wgAllowHTMLEmail;
168 $mime = null;
169 if ( !is_array( $to ) ) {
170 $to = array( $to );
173 // mail body must have some content
174 $minBodyLen = 10;
175 // arbitrary but longer than Array or Object to detect casting error
177 // body must either be a string or an array with text and body
178 if (
180 !is_array( $body ) &&
181 strlen( $body ) >= $minBodyLen
185 is_array( $body ) &&
186 isset( $body['text'] ) &&
187 isset( $body['html'] ) &&
188 strlen( $body['text'] ) >= $minBodyLen &&
189 strlen( $body['html'] ) >= $minBodyLen
192 // if it is neither we have a problem
193 return Status::newFatal( 'user-mail-no-body' );
196 if ( !$wgAllowHTMLEmail && is_array( $body ) ) {
197 // HTML not wanted. Dump it.
198 $body = $body['text'];
201 wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) . "\n" );
203 # Make sure we have at least one address
204 $has_address = false;
205 foreach ( $to as $u ) {
206 if ( $u->address ) {
207 $has_address = true;
208 break;
211 if ( !$has_address ) {
212 return Status::newFatal( 'user-mail-no-addy' );
215 # Forge email headers
216 # -------------------
218 # WARNING
220 # DO NOT add To: or Subject: headers at this step. They need to be
221 # handled differently depending upon the mailer we are going to use.
223 # To:
224 # PHP mail() first argument is the mail receiver. The argument is
225 # used as a recipient destination and as a To header.
227 # PEAR mailer has a recipient argument which is only used to
228 # send the mail. If no To header is given, PEAR will set it to
229 # to 'undisclosed-recipients:'.
231 # NOTE: To: is for presentation, the actual recipient is specified
232 # by the mailer using the Rcpt-To: header.
234 # Subject:
235 # PHP mail() second argument to pass the subject, passing a Subject
236 # as an additional header will result in a duplicate header.
238 # PEAR mailer should be passed a Subject header.
240 # -- hashar 20120218
242 $headers['From'] = $from->toString();
243 $returnPath = $from->address;
244 $extraParams = $wgAdditionalMailParams;
246 // Hook to generate custom VERP address for 'Return-Path'
247 wfRunHooks( 'UserMailerChangeReturnPath', array( $to, &$returnPath ) );
248 # Add the envelope sender address using the -f command line option when PHP mail() is used.
249 # Will default to the $from->address when the UserMailerChangeReturnPath hook fails and the
250 # generated VERP address when the hook runs effectively.
251 $extraParams .= ' -f ' . $returnPath;
253 $headers['Return-Path'] = $returnPath;
255 if ( $replyto ) {
256 $headers['Reply-To'] = $replyto->toString();
259 $headers['Date'] = MWTimestamp::getLocalInstance()->format( 'r' );
260 $headers['Message-ID'] = self::makeMsgId();
261 $headers['X-Mailer'] = 'MediaWiki mailer';
263 # Line endings need to be different on Unix and Windows due to
264 # the bug described at http://trac.wordpress.org/ticket/2603
265 if ( wfIsWindows() ) {
266 $endl = "\r\n";
267 } else {
268 $endl = "\n";
271 if ( is_array( $body ) ) {
272 // we are sending a multipart message
273 wfDebug( "Assembling multipart mime email\n" );
274 if ( !stream_resolve_include_path( 'Mail/mime.php' ) ) {
275 wfDebug( "PEAR Mail_Mime package is not installed. Falling back to text email.\n" );
276 // remove the html body for text email fall back
277 $body = $body['text'];
278 } else {
279 require_once 'Mail/mime.php';
280 if ( wfIsWindows() ) {
281 $body['text'] = str_replace( "\n", "\r\n", $body['text'] );
282 $body['html'] = str_replace( "\n", "\r\n", $body['html'] );
284 $mime = new Mail_mime( array(
285 'eol' => $endl,
286 'text_charset' => 'UTF-8',
287 'html_charset' => 'UTF-8'
288 ) );
289 $mime->setTXTBody( $body['text'] );
290 $mime->setHTMLBody( $body['html'] );
291 $body = $mime->get(); // must call get() before headers()
292 $headers = $mime->headers( $headers );
295 if ( $mime === null ) {
296 // sending text only, either deliberately or as a fallback
297 if ( wfIsWindows() ) {
298 $body = str_replace( "\n", "\r\n", $body );
300 $headers['MIME-Version'] = '1.0';
301 $headers['Content-type'] = ( is_null( $contentType ) ?
302 'text/plain; charset=UTF-8' : $contentType );
303 $headers['Content-transfer-encoding'] = '8bit';
306 $ret = wfRunHooks( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) );
307 if ( $ret === false ) {
308 // the hook implementation will return false to skip regular mail sending
309 return Status::newGood();
310 } elseif ( $ret !== true ) {
311 // the hook implementation will return a string to pass an error message
312 return Status::newFatal( 'php-mail-error', $ret );
315 if ( is_array( $wgSMTP ) ) {
317 # PEAR MAILER
320 if ( !stream_resolve_include_path( 'Mail.php' ) ) {
321 throw new MWException( 'PEAR mail package is not installed' );
323 require_once 'Mail.php';
325 wfSuppressWarnings();
327 // Create the mail object using the Mail::factory method
328 $mail_object =& Mail::factory( 'smtp', $wgSMTP );
329 if ( PEAR::isError( $mail_object ) ) {
330 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
331 wfRestoreWarnings();
332 return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
335 wfDebug( "Sending mail via PEAR::Mail\n" );
337 $headers['Subject'] = self::quotedPrintable( $subject );
339 # When sending only to one recipient, shows it its email using To:
340 if ( count( $to ) == 1 ) {
341 $headers['To'] = $to[0]->toString();
344 # Split jobs since SMTP servers tends to limit the maximum
345 # number of possible recipients.
346 $chunks = array_chunk( $to, $wgEnotifMaxRecips );
347 foreach ( $chunks as $chunk ) {
348 $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
349 # FIXME : some chunks might be sent while others are not!
350 if ( !$status->isOK() ) {
351 wfRestoreWarnings();
352 return $status;
355 wfRestoreWarnings();
356 return Status::newGood();
357 } else {
359 # PHP mail()
361 if ( count( $to ) > 1 ) {
362 $headers['To'] = 'undisclosed-recipients:;';
364 $headers = self::arrayToHeaderString( $headers, $endl );
366 wfDebug( "Sending mail via internal mail() function\n" );
368 self::$mErrorString = '';
369 $html_errors = ini_get( 'html_errors' );
370 ini_set( 'html_errors', '0' );
371 set_error_handler( 'UserMailer::errorHandler' );
373 try {
374 $safeMode = wfIniGetBool( 'safe_mode' );
376 foreach ( $to as $recip ) {
377 if ( $safeMode ) {
378 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers );
379 } else {
380 $sent = mail(
381 $recip,
382 self::quotedPrintable( $subject ),
383 $body,
384 $headers,
385 $extraParams
389 } catch ( Exception $e ) {
390 restore_error_handler();
391 throw $e;
394 restore_error_handler();
395 ini_set( 'html_errors', $html_errors );
397 if ( self::$mErrorString ) {
398 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
399 return Status::newFatal( 'php-mail-error', self::$mErrorString );
400 } elseif ( !$sent ) {
401 // mail function only tells if there's an error
402 wfDebug( "Unknown error sending mail\n" );
403 return Status::newFatal( 'php-mail-error-unknown' );
404 } else {
405 return Status::newGood();
411 * Set the mail error message in self::$mErrorString
413 * @param int $code Error number
414 * @param string $string Error message
416 static function errorHandler( $code, $string ) {
417 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
421 * Strips bad characters from a header value to prevent PHP mail header injection attacks
422 * @param string $val String to be santizied
423 * @return string
425 public static function sanitizeHeaderValue( $val ) {
426 return strtr( $val, array( "\r" => '', "\n" => '' ) );
430 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
431 * @param string $phrase
432 * @return string
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 . '"';
443 * Converts a string into quoted-printable format
444 * @since 1.17
446 * From PHP5.3 there is a built in function quoted_printable_encode()
447 * This method does not duplicate that.
448 * This method is doing Q encoding inside encoded-words as defined by RFC 2047
449 * This is for email headers.
450 * The built in quoted_printable_encode() is for email bodies
451 * @param string $string
452 * @param string $charset
453 * @return string
455 public static function quotedPrintable( $string, $charset = '' ) {
456 # Probably incomplete; see RFC 2045
457 if ( empty( $charset ) ) {
458 $charset = 'UTF-8';
460 $charset = strtoupper( $charset );
461 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
463 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
464 $replace = $illegal . '\t ?_';
465 if ( !preg_match( "/[$illegal]/", $string ) ) {
466 return $string;
468 $out = "=?$charset?Q?";
469 $out .= preg_replace_callback( "/([$replace])/",
470 array( __CLASS__, 'quotedPrintableCallback' ), $string );
471 $out .= '?=';
472 return $out;
475 protected static function quotedPrintableCallback( $matches ) {
476 return sprintf( "=%02X", ord( $matches[1] ) );
481 * This module processes the email notifications when the current page is
482 * changed. It looks up the table watchlist to find out which users are watching
483 * that page.
485 * The current implementation sends independent emails to each watching user for
486 * the following reason:
488 * - Each watching user will be notified about the page edit time expressed in
489 * his/her local time (UTC is shown additionally). To achieve this, we need to
490 * find the individual timeoffset of each watching user from the preferences..
492 * Suggested improvement to slack down the number of sent emails: We could think
493 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
494 * same timeoffset in their preferences.
496 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
500 class EmailNotification {
501 protected $subject, $body, $replyto, $from;
502 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
503 protected $mailTargets = array();
506 * @var Title
508 protected $title;
511 * @var User
513 protected $editor;
516 * Send emails corresponding to the user $editor editing the page $title.
517 * Also updates wl_notificationtimestamp.
519 * May be deferred via the job queue.
521 * @param User $editor
522 * @param Title $title
523 * @param string $timestamp
524 * @param string $summary
525 * @param bool $minorEdit
526 * @param bool $oldid (default: false)
527 * @param string $pageStatus (default: 'changed')
529 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
530 $minorEdit, $oldid = false, $pageStatus = 'changed'
532 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
533 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
535 if ( $title->getNamespace() < 0 ) {
536 return;
539 // Build a list of users to notify
540 $watchers = array();
541 if ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) {
542 $dbw = wfGetDB( DB_MASTER );
543 $res = $dbw->select( array( 'watchlist' ),
544 array( 'wl_user' ),
545 array(
546 'wl_user != ' . intval( $editor->getID() ),
547 'wl_namespace' => $title->getNamespace(),
548 'wl_title' => $title->getDBkey(),
549 'wl_notificationtimestamp IS NULL',
550 ), __METHOD__
552 foreach ( $res as $row ) {
553 $watchers[] = intval( $row->wl_user );
555 if ( $watchers ) {
556 // Update wl_notificationtimestamp for all watching users except the editor
557 $fname = __METHOD__;
558 $dbw->onTransactionIdle(
559 function () use ( $dbw, $timestamp, $watchers, $title, $fname ) {
560 $dbw->update( 'watchlist',
561 array( /* SET */
562 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
563 ), array( /* WHERE */
564 'wl_user' => $watchers,
565 'wl_namespace' => $title->getNamespace(),
566 'wl_title' => $title->getDBkey(),
567 ), $fname
574 $sendEmail = true;
575 // If nobody is watching the page, and there are no users notified on all changes
576 // don't bother creating a job/trying to send emails
577 // $watchers deals with $wgEnotifWatchlist
578 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
579 $sendEmail = false;
580 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
581 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
582 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
583 if ( $wgEnotifUserTalk
584 && $isUserTalkPage
585 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
587 $sendEmail = true;
592 if ( !$sendEmail ) {
593 return;
596 if ( $wgEnotifUseJobQ ) {
597 $params = array(
598 'editor' => $editor->getName(),
599 'editorID' => $editor->getID(),
600 'timestamp' => $timestamp,
601 'summary' => $summary,
602 'minorEdit' => $minorEdit,
603 'oldid' => $oldid,
604 'watchers' => $watchers,
605 'pageStatus' => $pageStatus
607 $job = new EnotifNotifyJob( $title, $params );
608 JobQueueGroup::singleton()->push( $job );
609 } else {
610 $this->actuallyNotifyOnPageChange(
611 $editor,
612 $title,
613 $timestamp,
614 $summary,
615 $minorEdit,
616 $oldid,
617 $watchers,
618 $pageStatus
624 * Immediate version of notifyOnPageChange().
626 * Send emails corresponding to the user $editor editing the page $title.
627 * Also updates wl_notificationtimestamp.
629 * @param User $editor
630 * @param Title $title
631 * @param string $timestamp Edit timestamp
632 * @param string $summary Edit summary
633 * @param bool $minorEdit
634 * @param int $oldid Revision ID
635 * @param array $watchers Array of user IDs
636 * @param string $pageStatus
637 * @throws MWException
639 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
640 $oldid, $watchers, $pageStatus = 'changed' ) {
641 # we use $wgPasswordSender as sender's address
642 global $wgEnotifWatchlist;
643 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
645 wfProfileIn( __METHOD__ );
647 # The following code is only run, if several conditions are met:
648 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
649 # 2. minor edits (changes) are only regarded if the global flag indicates so
651 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
653 $this->title = $title;
654 $this->timestamp = $timestamp;
655 $this->summary = $summary;
656 $this->minorEdit = $minorEdit;
657 $this->oldid = $oldid;
658 $this->editor = $editor;
659 $this->composed_common = false;
660 $this->pageStatus = $pageStatus;
662 $formattedPageStatus = array( 'deleted', 'created', 'moved', 'restored', 'changed' );
664 wfRunHooks( 'UpdateUserMailerFormattedPageStatus', array( &$formattedPageStatus ) );
665 if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
666 wfProfileOut( __METHOD__ );
667 throw new MWException( 'Not a valid page status!' );
670 $userTalkId = false;
672 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
673 if ( $wgEnotifUserTalk
674 && $isUserTalkPage
675 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
677 $targetUser = User::newFromName( $title->getText() );
678 $this->compose( $targetUser );
679 $userTalkId = $targetUser->getId();
682 if ( $wgEnotifWatchlist ) {
683 // Send updates to watchers other than the current editor
684 $userArray = UserArray::newFromIDs( $watchers );
685 foreach ( $userArray as $watchingUser ) {
686 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
687 && ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) )
688 && $watchingUser->isEmailConfirmed()
689 && $watchingUser->getID() != $userTalkId
691 if ( wfRunHooks( 'SendWatchlistEmailNotification', array( $watchingUser, $title, $this ) ) ) {
692 $this->compose( $watchingUser );
699 global $wgUsersNotifiedOnAllChanges;
700 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
701 if ( $editor->getName() == $name ) {
702 // No point notifying the user that actually made the change!
703 continue;
705 $user = User::newFromName( $name );
706 $this->compose( $user );
709 $this->sendMails();
710 wfProfileOut( __METHOD__ );
714 * @param User $editor
715 * @param Title $title
716 * @param bool $minorEdit
717 * @return bool
719 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
720 global $wgEnotifUserTalk;
721 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
723 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
724 $targetUser = User::newFromName( $title->getText() );
726 if ( !$targetUser || $targetUser->isAnon() ) {
727 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
728 } elseif ( $targetUser->getId() == $editor->getId() ) {
729 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
730 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
731 && ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) )
733 if ( !$targetUser->isEmailConfirmed() ) {
734 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
735 } elseif ( !wfRunHooks( 'AbortTalkPageEmailNotification', array( $targetUser, $title ) ) ) {
736 wfDebug( __METHOD__ . ": talk page update notification is aborted for this user\n" );
737 } else {
738 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
739 return true;
741 } else {
742 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
745 return false;
749 * Generate the generic "this page has been changed" e-mail text.
751 private function composeCommonMailtext() {
752 global $wgPasswordSender, $wgNoReplyAddress;
753 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
754 global $wgEnotifImpersonal, $wgEnotifUseRealName;
756 $this->composed_common = true;
758 # You as the WikiAdmin and Sysops can make use of plenty of
759 # named variables when composing your notification emails while
760 # simply editing the Meta pages
762 $keys = array();
763 $postTransformKeys = array();
764 $pageTitleUrl = $this->title->getCanonicalURL();
765 $pageTitle = $this->title->getPrefixedText();
767 if ( $this->oldid ) {
768 // Always show a link to the diff which triggered the mail. See bug 32210.
769 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
770 $this->title->getCanonicalURL( array( 'diff' => 'next', 'oldid' => $this->oldid ) ) )
771 ->inContentLanguage()->text();
773 if ( !$wgEnotifImpersonal ) {
774 // For personal mail, also show a link to the diff of all changes
775 // since last visited.
776 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
777 $this->title->getCanonicalURL( array( 'diff' => '0', 'oldid' => $this->oldid ) ) )
778 ->inContentLanguage()->text();
780 $keys['$OLDID'] = $this->oldid;
781 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
782 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
783 } else {
784 # clear $OLDID placeholder in the message template
785 $keys['$OLDID'] = '';
786 $keys['$NEWPAGE'] = '';
787 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
788 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
791 $keys['$PAGETITLE'] = $this->title->getPrefixedText();
792 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalURL();
793 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
794 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
795 $keys['$UNWATCHURL'] = $this->title->getCanonicalURL( 'action=unwatch' );
797 if ( $this->editor->isAnon() ) {
798 # real anon (user:xxx.xxx.xxx.xxx)
799 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
800 ->inContentLanguage()->text();
801 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
803 } else {
804 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor->getRealName() !== ''
805 ? $this->editor->getRealName() : $this->editor->getName();
806 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
807 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
810 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
811 $keys['$HELPPAGE'] = wfExpandUrl(
812 Skin::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
815 # Replace this after transforming the message, bug 35019
816 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
818 // Now build message's subject and body
820 // Messages:
821 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
822 // enotif_subject_restored, enotif_subject_changed
823 $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
824 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
826 // Messages:
827 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
828 // enotif_body_intro_restored, enotif_body_intro_changed
829 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
830 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
831 ->text();
833 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
834 $body = strtr( $body, $keys );
835 $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
836 $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
838 # Reveal the page editor's address as REPLY-TO address only if
839 # the user has not opted-out and the option is enabled at the
840 # global configuration level.
841 $adminAddress = new MailAddress( $wgPasswordSender,
842 wfMessage( 'emailsender' )->inContentLanguage()->text() );
843 if ( $wgEnotifRevealEditorAddress
844 && ( $this->editor->getEmail() != '' )
845 && $this->editor->getOption( 'enotifrevealaddr' )
847 $editorAddress = new MailAddress( $this->editor );
848 if ( $wgEnotifFromEditor ) {
849 $this->from = $editorAddress;
850 } else {
851 $this->from = $adminAddress;
852 $this->replyto = $editorAddress;
854 } else {
855 $this->from = $adminAddress;
856 $this->replyto = new MailAddress( $wgNoReplyAddress );
861 * Compose a mail to a given user and either queue it for sending, or send it now,
862 * depending on settings.
864 * Call sendMails() to send any mails that were queued.
865 * @param User $user
867 function compose( $user ) {
868 global $wgEnotifImpersonal;
870 if ( !$this->composed_common ) {
871 $this->composeCommonMailtext();
874 if ( $wgEnotifImpersonal ) {
875 $this->mailTargets[] = new MailAddress( $user );
876 } else {
877 $this->sendPersonalised( $user );
882 * Send any queued mails
884 function sendMails() {
885 global $wgEnotifImpersonal;
886 if ( $wgEnotifImpersonal ) {
887 $this->sendImpersonal( $this->mailTargets );
892 * Does the per-user customizations to a notification e-mail (name,
893 * timestamp in proper timezone, etc) and sends it out.
894 * Returns true if the mail was sent successfully.
896 * @param User $watchingUser
897 * @return bool
898 * @private
900 function sendPersonalised( $watchingUser ) {
901 global $wgContLang, $wgEnotifUseRealName;
902 // From the PHP manual:
903 // Note: The to parameter cannot be an address in the form of
904 // "Something <someone@example.com>". The mail command will not parse
905 // this properly while talking with the MTA.
906 $to = new MailAddress( $watchingUser );
908 # $PAGEEDITDATE is the time and date of the page change
909 # expressed in terms of individual local time of the notification
910 # recipient, i.e. watching user
911 $body = str_replace(
912 array( '$WATCHINGUSERNAME',
913 '$PAGEEDITDATE',
914 '$PAGEEDITTIME' ),
915 array( $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
916 ? $watchingUser->getRealName() : $watchingUser->getName(),
917 $wgContLang->userDate( $this->timestamp, $watchingUser ),
918 $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
919 $this->body );
921 return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
925 * Same as sendPersonalised but does impersonal mail suitable for bulk
926 * mailing. Takes an array of MailAddress objects.
927 * @param MailAddress[] $addresses
928 * @return Status|null
930 function sendImpersonal( $addresses ) {
931 global $wgContLang;
933 if ( empty( $addresses ) ) {
934 return null;
937 $body = str_replace(
938 array( '$WATCHINGUSERNAME',
939 '$PAGEEDITDATE',
940 '$PAGEEDITTIME' ),
941 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
942 $wgContLang->date( $this->timestamp, false, false ),
943 $wgContLang->time( $this->timestamp, false, false ) ),
944 $this->body );
946 return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
949 } # end of class EmailNotification