Merge "[JobQueue] Added support for approximate FIFO job queues."
[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;
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 */
425 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
426 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
427 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
428
429 if ( $title->getNamespace() < 0 ) {
430 return;
431 }
432
433 // Build a list of users to notfiy
434 $watchers = array();
435 if ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) {
436 $dbw = wfGetDB( DB_MASTER );
437 $res = $dbw->select( array( 'watchlist' ),
438 array( 'wl_user' ),
439 array(
440 'wl_user != ' . intval( $editor->getID() ),
441 'wl_namespace' => $title->getNamespace(),
442 'wl_title' => $title->getDBkey(),
443 'wl_notificationtimestamp IS NULL',
444 ), __METHOD__
445 );
446 foreach ( $res as $row ) {
447 $watchers[] = intval( $row->wl_user );
448 }
449 if ( $watchers ) {
450 // Update wl_notificationtimestamp for all watching users except the editor
451 $fname = __METHOD__;
452 $dbw->onTransactionIdle(
453 function() use ( $dbw, $timestamp, $watchers, $title, $fname ) {
454 $dbw->begin( $fname );
455 $dbw->update( 'watchlist',
456 array( /* SET */
457 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
458 ), array( /* WHERE */
459 'wl_user' => $watchers,
460 'wl_namespace' => $title->getNamespace(),
461 'wl_title' => $title->getDBkey(),
462 ), $fname
463 );
464 $dbw->commit( $fname );
465 }
466 );
467 }
468 }
469
470 $sendEmail = true;
471 // If nobody is watching the page, and there are no users notified on all changes
472 // don't bother creating a job/trying to send emails
473 // $watchers deals with $wgEnotifWatchlist
474 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
475 $sendEmail = false;
476 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
477 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
478 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
479 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
480 $sendEmail = true;
481 }
482 }
483 }
484
485 if ( !$sendEmail ) {
486 return;
487 }
488 if ( $wgEnotifUseJobQ ) {
489 $params = array(
490 'editor' => $editor->getName(),
491 'editorID' => $editor->getID(),
492 'timestamp' => $timestamp,
493 'summary' => $summary,
494 'minorEdit' => $minorEdit,
495 'oldid' => $oldid,
496 'watchers' => $watchers
497 );
498 $job = new EnotifNotifyJob( $title, $params );
499 $job->insert();
500 } else {
501 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
502 }
503 }
504
505 /**
506 * Immediate version of notifyOnPageChange().
507 *
508 * Send emails corresponding to the user $editor editing the page $title.
509 * Also updates wl_notificationtimestamp.
510 *
511 * @param $editor User object
512 * @param $title Title object
513 * @param $timestamp string Edit timestamp
514 * @param $summary string Edit summary
515 * @param $minorEdit bool
516 * @param $oldid int Revision ID
517 * @param $watchers array of user IDs
518 */
519 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
520 # we use $wgPasswordSender as sender's address
521 global $wgEnotifWatchlist;
522 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
523
524 wfProfileIn( __METHOD__ );
525
526 # The following code is only run, if several conditions are met:
527 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
528 # 2. minor edits (changes) are only regarded if the global flag indicates so
529
530 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
531
532 $this->title = $title;
533 $this->timestamp = $timestamp;
534 $this->summary = $summary;
535 $this->minorEdit = $minorEdit;
536 $this->oldid = $oldid;
537 $this->editor = $editor;
538 $this->composed_common = false;
539
540 $userTalkId = false;
541
542 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
543
544 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
545 $targetUser = User::newFromName( $title->getText() );
546 $this->compose( $targetUser );
547 $userTalkId = $targetUser->getId();
548 }
549
550 if ( $wgEnotifWatchlist ) {
551 // Send updates to watchers other than the current editor
552 $userArray = UserArray::newFromIDs( $watchers );
553 foreach ( $userArray as $watchingUser ) {
554 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
555 ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) ) &&
556 $watchingUser->isEmailConfirmed() &&
557 $watchingUser->getID() != $userTalkId )
558 {
559 $this->compose( $watchingUser );
560 }
561 }
562 }
563 }
564
565 global $wgUsersNotifiedOnAllChanges;
566 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
567 if ( $editor->getName() == $name ) {
568 // No point notifying the user that actually made the change!
569 continue;
570 }
571 $user = User::newFromName( $name );
572 $this->compose( $user );
573 }
574
575 $this->sendMails();
576 wfProfileOut( __METHOD__ );
577 }
578
579 /**
580 * @param $editor User
581 * @param $title Title bool
582 * @param $minorEdit
583 * @return bool
584 */
585 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
586 global $wgEnotifUserTalk;
587 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
588
589 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
590 $targetUser = User::newFromName( $title->getText() );
591
592 if ( !$targetUser || $targetUser->isAnon() ) {
593 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
594 } elseif ( $targetUser->getId() == $editor->getId() ) {
595 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
596 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) &&
597 ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) ) )
598 {
599 if ( $targetUser->isEmailConfirmed() ) {
600 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
601 return true;
602 } else {
603 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
604 }
605 } else {
606 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
607 }
608 }
609 return false;
610 }
611
612 /**
613 * Generate the generic "this page has been changed" e-mail text.
614 */
615 private function composeCommonMailtext() {
616 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
617 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
618 global $wgEnotifImpersonal, $wgEnotifUseRealName;
619
620 $this->composed_common = true;
621
622 # You as the WikiAdmin and Sysops can make use of plenty of
623 # named variables when composing your notification emails while
624 # simply editing the Meta pages
625
626 $keys = array();
627 $postTransformKeys = array();
628
629 if ( $this->oldid ) {
630 // Always show a link to the diff which triggered the mail. See bug 32210.
631 $keys['$NEWPAGE'] = wfMessage( 'enotif_lastdiff',
632 $this->title->getCanonicalUrl( 'diff=next&oldid=' . $this->oldid ) )
633 ->inContentLanguage()->text();
634 if ( !$wgEnotifImpersonal ) {
635 // For personal mail, also show a link to the diff of all changes
636 // since last visited.
637 $keys['$NEWPAGE'] .= " \n" . wfMessage( 'enotif_lastvisited',
638 $this->title->getCanonicalUrl( 'diff=0&oldid=' . $this->oldid ) )
639 ->inContentLanguage()->text();
640 }
641 $keys['$OLDID'] = $this->oldid;
642 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
643 } else {
644 $keys['$NEWPAGE'] = wfMessage( 'enotif_newpagetext' )->inContentLanguage()->text();
645 # clear $OLDID placeholder in the message template
646 $keys['$OLDID'] = '';
647 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
648 }
649
650 $keys['$PAGETITLE'] = $this->title->getPrefixedText();
651 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalUrl();
652 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
653 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
654 $keys['$UNWATCHURL'] = $this->title->getCanonicalUrl( 'action=unwatch' );
655
656 if ( $this->editor->isAnon() ) {
657 # real anon (user:xxx.xxx.xxx.xxx)
658 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
659 ->inContentLanguage()->text();
660 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
661 } else {
662 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName ? $this->editor->getRealName() : $this->editor->getName();
663 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
664 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalUrl();
665 }
666
667 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalUrl();
668
669 # Replace this after transforming the message, bug 35019
670 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
671
672 # Now build message's subject and body
673
674 $subject = wfMessage( 'enotif_subject' )->inContentLanguage()->plain();
675 $subject = strtr( $subject, $keys );
676 $subject = MessageCache::singleton()->transform( $subject, false, null, $this->title );
677 $this->subject = strtr( $subject, $postTransformKeys );
678
679 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
680 $body = strtr( $body, $keys );
681 $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
682 $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
683
684 # Reveal the page editor's address as REPLY-TO address only if
685 # the user has not opted-out and the option is enabled at the
686 # global configuration level.
687 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
688 if ( $wgEnotifRevealEditorAddress
689 && ( $this->editor->getEmail() != '' )
690 && $this->editor->getOption( 'enotifrevealaddr' ) )
691 {
692 $editorAddress = new MailAddress( $this->editor );
693 if ( $wgEnotifFromEditor ) {
694 $this->from = $editorAddress;
695 } else {
696 $this->from = $adminAddress;
697 $this->replyto = $editorAddress;
698 }
699 } else {
700 $this->from = $adminAddress;
701 $this->replyto = new MailAddress( $wgNoReplyAddress );
702 }
703 }
704
705 /**
706 * Compose a mail to a given user and either queue it for sending, or send it now,
707 * depending on settings.
708 *
709 * Call sendMails() to send any mails that were queued.
710 * @param $user User
711 */
712 function compose( $user ) {
713 global $wgEnotifImpersonal;
714
715 if ( !$this->composed_common )
716 $this->composeCommonMailtext();
717
718 if ( $wgEnotifImpersonal ) {
719 $this->mailTargets[] = new MailAddress( $user );
720 } else {
721 $this->sendPersonalised( $user );
722 }
723 }
724
725 /**
726 * Send any queued mails
727 */
728 function sendMails() {
729 global $wgEnotifImpersonal;
730 if ( $wgEnotifImpersonal ) {
731 $this->sendImpersonal( $this->mailTargets );
732 }
733 }
734
735 /**
736 * Does the per-user customizations to a notification e-mail (name,
737 * timestamp in proper timezone, etc) and sends it out.
738 * Returns true if the mail was sent successfully.
739 *
740 * @param $watchingUser User object
741 * @return Boolean
742 * @private
743 */
744 function sendPersonalised( $watchingUser ) {
745 global $wgContLang, $wgEnotifUseRealName;
746 // From the PHP manual:
747 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
748 // The mail command will not parse this properly while talking with the MTA.
749 $to = new MailAddress( $watchingUser );
750
751 # $PAGEEDITDATE is the time and date of the page change
752 # expressed in terms of individual local time of the notification
753 # recipient, i.e. watching user
754 $body = str_replace(
755 array( '$WATCHINGUSERNAME',
756 '$PAGEEDITDATE',
757 '$PAGEEDITTIME' ),
758 array( $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName(),
759 $wgContLang->userDate( $this->timestamp, $watchingUser ),
760 $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
761 $this->body );
762
763 return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
764 }
765
766 /**
767 * Same as sendPersonalised but does impersonal mail suitable for bulk
768 * mailing. Takes an array of MailAddress objects.
769 * @return Status
770 */
771 function sendImpersonal( $addresses ) {
772 global $wgContLang;
773
774 if ( empty( $addresses ) )
775 return;
776
777 $body = str_replace(
778 array( '$WATCHINGUSERNAME',
779 '$PAGEEDITDATE',
780 '$PAGEEDITTIME' ),
781 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
782 $wgContLang->date( $this->timestamp, false, false ),
783 $wgContLang->time( $this->timestamp, false, false ) ),
784 $this->body );
785
786 return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
787 }
788
789 } # end of class EmailNotification