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