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