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