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