Use JobQueueGroup::singleton()
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /**
3 * Classes used to send e-mails
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
24 */
25
26
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.
31 */
32 class MailAddress {
33 /**
34 * @param $address string|User string with an email address, or a User object
35 * @param $name String: human-readable name if a string address is given
36 * @param $realName String: human-readable real name if a string address is given
37 */
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 );
47 }
48 }
49
50 /**
51 * Return formatted and quoted address to insert into SMTP headers
52 * @return string
53 */
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 . '"';
65 }
66 return "$quoted <{$this->address}>";
67 } else {
68 return $this->address;
69 }
70 } else {
71 return "";
72 }
73 }
74
75 function __toString() {
76 return $this->toString();
77 }
78 }
79
80
81 /**
82 * Collection of static functions for sending mail
83 */
84 class UserMailer {
85 static $mErrorString;
86
87 /**
88 * Send mail using a PEAR mailer
89 *
90 * @param $mailer
91 * @param $dest
92 * @param $headers
93 * @param $body
94 *
95 * @return Status
96 */
97 protected static function sendWithPear( $mailer, $dest, $headers, $body ) {
98 $mailResult = $mailer->send( $dest, $headers, $body );
99
100 # Based on the result return an error string,
101 if ( PEAR::isError( $mailResult ) ) {
102 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
103 return Status::newFatal( 'pear-mail-error', $mailResult->getMessage() );
104 } else {
105 return Status::newGood();
106 }
107 }
108
109 /**
110 * Creates a single string from an associative array
111 *
112 * @param $headers array Associative Array: keys are header field names,
113 * values are ... values.
114 * @param $endl String: The end of line character. Defaults to "\n"
115 * @return String
116 */
117 static function arrayToHeaderString( $headers, $endl = "\n" ) {
118 $strings = array();
119 foreach( $headers as $name => $value ) {
120 $strings[] = "$name: $value";
121 }
122 return implode( $endl, $strings );
123 }
124
125 /**
126 * Create a value suitable for the MessageId Header
127 *
128 * @return String
129 */
130 static function makeMsgId() {
131 global $wgSMTP, $wgServer;
132
133 $msgid = uniqid( wfWikiID() . ".", true ); /* true required for cygwin */
134 if ( is_array($wgSMTP) && isset($wgSMTP['IDHost']) && $wgSMTP['IDHost'] ) {
135 $domain = $wgSMTP['IDHost'];
136 } else {
137 $url = wfParseUrl($wgServer);
138 $domain = $url['host'];
139 }
140 return "<$msgid@$domain>";
141 }
142
143 /**
144 * This function will perform a direct (authenticated) login to
145 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
146 * array of parameters. It requires PEAR:Mail to do that.
147 * Otherwise it just uses the standard PHP 'mail' function.
148 *
149 * @param $to MailAddress: recipient's email (or an array of them)
150 * @param $from MailAddress: sender's email
151 * @param $subject String: email's subject.
152 * @param $body String: email's text.
153 * @param $replyto MailAddress: optional reply-to email (default: null).
154 * @param $contentType String: optional custom Content-Type (default: text/plain; charset=UTF-8)
155 * @throws MWException
156 * @return Status object
157 */
158 public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8' ) {
159 global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams;
160
161 if ( !is_array( $to ) ) {
162 $to = array( $to );
163 }
164
165 wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) . "\n" );
166
167 # Make sure we have at least one address
168 $has_address = false;
169 foreach ( $to as $u ) {
170 if ( $u->address ) {
171 $has_address = true;
172 break;
173 }
174 }
175 if ( !$has_address ) {
176 return Status::newFatal( 'user-mail-no-addy' );
177 }
178
179 # Forge email headers
180 # -------------------
181 #
182 # WARNING
183 #
184 # DO NOT add To: or Subject: headers at this step. They need to be
185 # handled differently depending upon the mailer we are going to use.
186 #
187 # To:
188 # PHP mail() first argument is the mail receiver. The argument is
189 # used as a recipient destination and as a To header.
190 #
191 # PEAR mailer has a recipient argument which is only used to
192 # send the mail. If no To header is given, PEAR will set it to
193 # to 'undisclosed-recipients:'.
194 #
195 # NOTE: To: is for presentation, the actual recipient is specified
196 # by the mailer using the Rcpt-To: header.
197 #
198 # Subject:
199 # PHP mail() second argument to pass the subject, passing a Subject
200 # as an additional header will result in a duplicate header.
201 #
202 # PEAR mailer should be passed a Subject header.
203 #
204 # -- hashar 20120218
205
206 $headers['From'] = $from->toString();
207 $headers['Return-Path'] = $from->address;
208
209 if ( $replyto ) {
210 $headers['Reply-To'] = $replyto->toString();
211 }
212
213 $headers['Date'] = date( 'r' );
214 $headers['MIME-Version'] = '1.0';
215 $headers['Content-type'] = ( is_null( $contentType ) ?
216 'text/plain; charset=UTF-8' : $contentType );
217 $headers['Content-transfer-encoding'] = '8bit';
218
219 $headers['Message-ID'] = self::makeMsgId();
220 $headers['X-Mailer'] = 'MediaWiki mailer';
221
222 $ret = wfRunHooks( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) );
223 if ( $ret === false ) {
224 return Status::newGood();
225 } elseif ( $ret !== true ) {
226 return Status::newFatal( 'php-mail-error', $ret );
227 }
228
229 if ( is_array( $wgSMTP ) ) {
230 #
231 # PEAR MAILER
232 #
233
234 if ( function_exists( 'stream_resolve_include_path' ) ) {
235 $found = stream_resolve_include_path( 'Mail.php' );
236 } else {
237 $found = Fallback::stream_resolve_include_path( 'Mail.php' );
238 }
239 if ( !$found ) {
240 throw new MWException( 'PEAR mail package is not installed' );
241 }
242 require_once( 'Mail.php' );
243
244 wfSuppressWarnings();
245
246 // Create the mail object using the Mail::factory method
247 $mail_object =& Mail::factory( 'smtp', $wgSMTP );
248 if ( PEAR::isError( $mail_object ) ) {
249 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
250 wfRestoreWarnings();
251 return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
252 }
253
254 wfDebug( "Sending mail via PEAR::Mail\n" );
255
256 $headers['Subject'] = self::quotedPrintable( $subject );
257
258 # When sending only to one recipient, shows it its email using To:
259 if ( count( $to ) == 1 ) {
260 $headers['To'] = $to[0]->toString();
261 }
262
263 # Split jobs since SMTP servers tends to limit the maximum
264 # number of possible recipients.
265 $chunks = array_chunk( $to, $wgEnotifMaxRecips );
266 foreach ( $chunks as $chunk ) {
267 $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
268 # FIXME : some chunks might be sent while others are not!
269 if ( !$status->isOK() ) {
270 wfRestoreWarnings();
271 return $status;
272 }
273 }
274 wfRestoreWarnings();
275 return Status::newGood();
276 } else {
277 #
278 # PHP mail()
279 #
280
281 # Line endings need to be different on Unix and Windows due to
282 # the bug described at http://trac.wordpress.org/ticket/2603
283 if ( wfIsWindows() ) {
284 $body = str_replace( "\n", "\r\n", $body );
285 $endl = "\r\n";
286 } else {
287 $endl = "\n";
288 }
289
290 if( count($to) > 1 ) {
291 $headers['To'] = 'undisclosed-recipients:;';
292 }
293 $headers = self::arrayToHeaderString( $headers, $endl );
294
295 wfDebug( "Sending mail via internal mail() function\n" );
296
297 self::$mErrorString = '';
298 $html_errors = ini_get( 'html_errors' );
299 ini_set( 'html_errors', '0' );
300 set_error_handler( 'UserMailer::errorHandler' );
301
302 $safeMode = wfIniGetBool( 'safe_mode' );
303 foreach ( $to as $recip ) {
304 if ( $safeMode ) {
305 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers );
306 } else {
307 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
308 }
309 }
310
311 restore_error_handler();
312 ini_set( 'html_errors', $html_errors );
313
314 if ( self::$mErrorString ) {
315 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
316 return Status::newFatal( 'php-mail-error', self::$mErrorString );
317 } elseif ( ! $sent ) {
318 // mail function only tells if there's an error
319 wfDebug( "Unknown error sending mail\n" );
320 return Status::newFatal( 'php-mail-error-unknown' );
321 } else {
322 return Status::newGood();
323 }
324 }
325 }
326
327 /**
328 * Set the mail error message in self::$mErrorString
329 *
330 * @param $code Integer: error number
331 * @param $string String: error message
332 */
333 static function errorHandler( $code, $string ) {
334 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
335 }
336
337 /**
338 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
339 * @param $phrase string
340 * @return string
341 */
342 public static function rfc822Phrase( $phrase ) {
343 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
344 return '"' . $phrase . '"';
345 }
346
347 /**
348 * Converts a string into quoted-printable format
349 * @since 1.17
350 * @return string
351 */
352 public static function quotedPrintable( $string, $charset = '' ) {
353 # Probably incomplete; see RFC 2045
354 if( empty( $charset ) ) {
355 $charset = 'UTF-8';
356 }
357 $charset = strtoupper( $charset );
358 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
359
360 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
361 $replace = $illegal . '\t ?_';
362 if( !preg_match( "/[$illegal]/", $string ) ) {
363 return $string;
364 }
365 $out = "=?$charset?Q?";
366 $out .= preg_replace_callback( "/([$replace])/",
367 array( __CLASS__, 'quotedPrintableCallback' ), $string );
368 $out .= '?=';
369 return $out;
370 }
371
372 protected static function quotedPrintableCallback( $matches ) {
373 return sprintf( "=%02X", ord( $matches[1] ) );
374 }
375 }
376
377 /**
378 * This module processes the email notifications when the current page is
379 * changed. It looks up the table watchlist to find out which users are watching
380 * that page.
381 *
382 * The current implementation sends independent emails to each watching user for
383 * the following reason:
384 *
385 * - Each watching user will be notified about the page edit time expressed in
386 * his/her local time (UTC is shown additionally). To achieve this, we need to
387 * find the individual timeoffset of each watching user from the preferences..
388 *
389 * Suggested improvement to slack down the number of sent emails: We could think
390 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
391 * same timeoffset in their preferences.
392 *
393 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
394 *
395 *
396 */
397 class EmailNotification {
398 protected $subject, $body, $replyto, $from;
399 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
400 protected $mailTargets = array();
401
402 /**
403 * @var Title
404 */
405 protected $title;
406
407 /**
408 * @var User
409 */
410 protected $editor;
411
412 /**
413 * Send emails corresponding to the user $editor editing the page $title.
414 * Also updates wl_notificationtimestamp.
415 *
416 * May be deferred via the job queue.
417 *
418 * @param $editor User object
419 * @param $title Title object
420 * @param $timestamp
421 * @param $summary
422 * @param $minorEdit
423 * @param $oldid (default: false)
424 * @param $pageStatus (default: 'changed')
425 */
426 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false, $pageStatus = 'changed' ) {
427 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
428 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
429
430 if ( $title->getNamespace() < 0 ) {
431 return;
432 }
433
434 // Build a list of users to notfiy
435 $watchers = array();
436 if ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) {
437 $dbw = wfGetDB( DB_MASTER );
438 $res = $dbw->select( array( 'watchlist' ),
439 array( 'wl_user' ),
440 array(
441 'wl_user != ' . intval( $editor->getID() ),
442 'wl_namespace' => $title->getNamespace(),
443 'wl_title' => $title->getDBkey(),
444 'wl_notificationtimestamp IS NULL',
445 ), __METHOD__
446 );
447 foreach ( $res as $row ) {
448 $watchers[] = intval( $row->wl_user );
449 }
450 if ( $watchers ) {
451 // Update wl_notificationtimestamp for all watching users except the editor
452 $fname = __METHOD__;
453 $dbw->onTransactionIdle(
454 function() use ( $dbw, $timestamp, $watchers, $title, $fname ) {
455 $dbw->begin( $fname );
456 $dbw->update( 'watchlist',
457 array( /* SET */
458 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
459 ), array( /* WHERE */
460 'wl_user' => $watchers,
461 'wl_namespace' => $title->getNamespace(),
462 'wl_title' => $title->getDBkey(),
463 ), $fname
464 );
465 $dbw->commit( $fname );
466 }
467 );
468 }
469 }
470
471 $sendEmail = true;
472 // If nobody is watching the page, and there are no users notified on all changes
473 // don't bother creating a job/trying to send emails
474 // $watchers deals with $wgEnotifWatchlist
475 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
476 $sendEmail = false;
477 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
478 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
479 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
480 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
481 $sendEmail = true;
482 }
483 }
484 }
485
486 if ( !$sendEmail ) {
487 return;
488 }
489 if ( $wgEnotifUseJobQ ) {
490 $params = array(
491 'editor' => $editor->getName(),
492 'editorID' => $editor->getID(),
493 'timestamp' => $timestamp,
494 'summary' => $summary,
495 'minorEdit' => $minorEdit,
496 'oldid' => $oldid,
497 'watchers' => $watchers,
498 'pageStatus' => $pageStatus
499 );
500 $job = new EnotifNotifyJob( $title, $params );
501 JobQueueGroup::singleton()->push( $job );
502 } else {
503 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers, $pageStatus );
504 }
505 }
506
507 /**
508 * Immediate version of notifyOnPageChange().
509 *
510 * Send emails corresponding to the user $editor editing the page $title.
511 * Also updates wl_notificationtimestamp.
512 *
513 * @param $editor User object
514 * @param $title Title object
515 * @param $timestamp string Edit timestamp
516 * @param $summary string Edit summary
517 * @param $minorEdit bool
518 * @param $oldid int Revision ID
519 * @param $watchers array of user IDs
520 */
521 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
522 $oldid, $watchers, $pageStatus = 'changed' ) {
523 # we use $wgPasswordSender as sender's address
524 global $wgEnotifWatchlist;
525 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
526
527 wfProfileIn( __METHOD__ );
528
529 # The following code is only run, if several conditions are met:
530 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
531 # 2. minor edits (changes) are only regarded if the global flag indicates so
532
533 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
534
535 $this->title = $title;
536 $this->timestamp = $timestamp;
537 $this->summary = $summary;
538 $this->minorEdit = $minorEdit;
539 $this->oldid = $oldid;
540 $this->editor = $editor;
541 $this->composed_common = false;
542 $this->pageStatus = $pageStatus;
543
544 $formattedPageStatus = array( 'deleted', 'created', 'moved', 'restored', 'changed' );
545
546 wfRunHooks( 'UpdateUserMailerFormattedPageStatus', array( &$formattedPageStatus ) );
547 if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
548 throw new MWException( 'Not a valid page status!' );
549 }
550
551 $userTalkId = false;
552
553 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
554
555 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
556 $targetUser = User::newFromName( $title->getText() );
557 $this->compose( $targetUser );
558 $userTalkId = $targetUser->getId();
559 }
560
561 if ( $wgEnotifWatchlist ) {
562 // Send updates to watchers other than the current editor
563 $userArray = UserArray::newFromIDs( $watchers );
564 foreach ( $userArray as $watchingUser ) {
565 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
566 ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) ) &&
567 $watchingUser->isEmailConfirmed() &&
568 $watchingUser->getID() != $userTalkId )
569 {
570 $this->compose( $watchingUser );
571 }
572 }
573 }
574 }
575
576 global $wgUsersNotifiedOnAllChanges;
577 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
578 if ( $editor->getName() == $name ) {
579 // No point notifying the user that actually made the change!
580 continue;
581 }
582 $user = User::newFromName( $name );
583 $this->compose( $user );
584 }
585
586 $this->sendMails();
587 wfProfileOut( __METHOD__ );
588 }
589
590 /**
591 * @param $editor User
592 * @param $title Title bool
593 * @param $minorEdit
594 * @return bool
595 */
596 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
597 global $wgEnotifUserTalk;
598 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
599
600 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
601 $targetUser = User::newFromName( $title->getText() );
602
603 if ( !$targetUser || $targetUser->isAnon() ) {
604 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
605 } elseif ( $targetUser->getId() == $editor->getId() ) {
606 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
607 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) &&
608 ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) ) )
609 {
610 if ( $targetUser->isEmailConfirmed() ) {
611 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
612 return true;
613 } else {
614 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
615 }
616 } else {
617 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
618 }
619 }
620 return false;
621 }
622
623 /**
624 * Generate the generic "this page has been changed" e-mail text.
625 */
626 private function composeCommonMailtext() {
627 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
628 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
629 global $wgEnotifImpersonal, $wgEnotifUseRealName;
630
631 $this->composed_common = true;
632
633 # You as the WikiAdmin and Sysops can make use of plenty of
634 # named variables when composing your notification emails while
635 # simply editing the Meta pages
636
637 $keys = array();
638 $postTransformKeys = array();
639 $pageTitleUrl = $this->title->getCanonicalUrl();
640 $pageTitle = $this->title->getPrefixedText();
641
642 if ( $this->oldid ) {
643 // Always show a link to the diff which triggered the mail. See bug 32210.
644 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
645 $this->title->getCanonicalUrl( 'diff=next&oldid=' . $this->oldid ) )
646 ->inContentLanguage()->text();
647
648 if ( !$wgEnotifImpersonal ) {
649 // For personal mail, also show a link to the diff of all changes
650 // since last visited.
651 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
652 $this->title->getCanonicalUrl( 'diff=0&oldid=' . $this->oldid ) )
653 ->inContentLanguage()->text();
654 }
655 $keys['$OLDID'] = $this->oldid;
656 } else {
657 # clear $OLDID placeholder in the message template
658 $keys['$OLDID'] = '';
659 $keys['$NEWPAGE'] = '';
660 }
661
662 $keys['$PAGETITLE'] = $this->title->getPrefixedText();
663 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalUrl();
664 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
665 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
666 $keys['$UNWATCHURL'] = $this->title->getCanonicalUrl( 'action=unwatch' );
667
668 if ( $this->editor->isAnon() ) {
669 # real anon (user:xxx.xxx.xxx.xxx)
670 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
671 ->inContentLanguage()->text();
672 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
673
674 } else {
675 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName ? $this->editor->getRealName() : $this->editor->getName();
676 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
677 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalUrl();
678 }
679
680 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalUrl();
681
682 # Replace this after transforming the message, bug 35019
683 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
684
685 # Now build message's subject and body
686 $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
687 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->escaped();
688
689 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
690 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
691 ->escaped();
692
693 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
694 $body = strtr( $body, $keys );
695 $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
696 $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
697
698 # Reveal the page editor's address as REPLY-TO address only if
699 # the user has not opted-out and the option is enabled at the
700 # global configuration level.
701 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
702 if ( $wgEnotifRevealEditorAddress
703 && ( $this->editor->getEmail() != '' )
704 && $this->editor->getOption( 'enotifrevealaddr' ) )
705 {
706 $editorAddress = new MailAddress( $this->editor );
707 if ( $wgEnotifFromEditor ) {
708 $this->from = $editorAddress;
709 } else {
710 $this->from = $adminAddress;
711 $this->replyto = $editorAddress;
712 }
713 } else {
714 $this->from = $adminAddress;
715 $this->replyto = new MailAddress( $wgNoReplyAddress );
716 }
717 }
718
719 /**
720 * Compose a mail to a given user and either queue it for sending, or send it now,
721 * depending on settings.
722 *
723 * Call sendMails() to send any mails that were queued.
724 * @param $user User
725 */
726 function compose( $user ) {
727 global $wgEnotifImpersonal;
728
729 if ( !$this->composed_common )
730 $this->composeCommonMailtext();
731
732 if ( $wgEnotifImpersonal ) {
733 $this->mailTargets[] = new MailAddress( $user );
734 } else {
735 $this->sendPersonalised( $user );
736 }
737 }
738
739 /**
740 * Send any queued mails
741 */
742 function sendMails() {
743 global $wgEnotifImpersonal;
744 if ( $wgEnotifImpersonal ) {
745 $this->sendImpersonal( $this->mailTargets );
746 }
747 }
748
749 /**
750 * Does the per-user customizations to a notification e-mail (name,
751 * timestamp in proper timezone, etc) and sends it out.
752 * Returns true if the mail was sent successfully.
753 *
754 * @param $watchingUser User object
755 * @return Boolean
756 * @private
757 */
758 function sendPersonalised( $watchingUser ) {
759 global $wgContLang, $wgEnotifUseRealName;
760 // From the PHP manual:
761 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
762 // The mail command will not parse this properly while talking with the MTA.
763 $to = new MailAddress( $watchingUser );
764
765 # $PAGEEDITDATE is the time and date of the page change
766 # expressed in terms of individual local time of the notification
767 # recipient, i.e. watching user
768 $body = str_replace(
769 array( '$WATCHINGUSERNAME',
770 '$PAGEEDITDATE',
771 '$PAGEEDITTIME' ),
772 array( $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName(),
773 $wgContLang->userDate( $this->timestamp, $watchingUser ),
774 $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
775 $this->body );
776
777 return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
778 }
779
780 /**
781 * Same as sendPersonalised but does impersonal mail suitable for bulk
782 * mailing. Takes an array of MailAddress objects.
783 * @return Status
784 */
785 function sendImpersonal( $addresses ) {
786 global $wgContLang;
787
788 if ( empty( $addresses ) )
789 return;
790
791 $body = str_replace(
792 array( '$WATCHINGUSERNAME',
793 '$PAGEEDITDATE',
794 '$PAGEEDITTIME' ),
795 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
796 $wgContLang->date( $this->timestamp, false, false ),
797 $wgContLang->time( $this->timestamp, false, false ) ),
798 $this->body );
799
800 return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
801 }
802
803 } # end of class EmailNotification