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