Temporarily reverting r99863 to see if I can pin down test failures
[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, $wgEnotifImpersonal;
158 global $wgEnotifMaxRecips, $wgAdditionalMailParams;
159
160 $emails = '';
161 wfDebug( __METHOD__ . ': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
162
163 $headers['From'] = $from->toString();
164 $headers['Return-Path'] = $from->toString();
165
166 $dest = array();
167 if ( is_array( $to ) ) {
168 foreach ( $to as $u ) {
169 if ( $u->address ) {
170 $dest[] = $u->address;
171 }
172 }
173 } else if( $to->address ) {
174 $dest[] = $to->address;
175 }
176 if ( count( $dest ) == 0 ) {
177 return Status::newFatal( 'user-mail-no-addy' );
178 }
179
180 if ( $wgEnotifImpersonal ) {
181 $headers['To'] = 'undisclosed-recipients:;';
182 }
183 else {
184 $headers['To'] = implode( ", ", $dest );
185 }
186
187 if ( $replyto ) {
188 $headers['Reply-To'] = $replyto->toString();
189 }
190 $headers['Subject'] = self::quotedPrintable( $subject );
191 $headers['Date'] = date( 'r' );
192 $headers['MIME-Version'] = '1.0';
193 $headers['Content-type'] = ( is_null( $contentType ) ?
194 'text/plain; charset=UTF-8' : $contentType );
195 $headers['Content-transfer-encoding'] = '8bit';
196
197 $headers['Message-ID'] = self::makeMsgId();
198 $headers['X-Mailer'] = 'MediaWiki mailer';
199 $headers['From'] = $from->toString();
200
201 $ret = wfRunHooks( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) );
202 if ( $ret === false ) {
203 return Status::newGood();
204 } else if ( $ret !== true ) {
205 return Status::newFatal( 'php-mail-error', $ret );
206 }
207
208 if ( is_array( $wgSMTP ) ) {
209 if ( function_exists( 'stream_resolve_include_path' ) ) {
210 $found = stream_resolve_include_path( 'Mail.php' );
211 } else {
212 $found = Fallback::stream_resolve_include_path( 'Mail.php' );
213 }
214 if ( !$found ) {
215 throw new MWException( 'PEAR mail package is not installed' );
216 }
217 require_once( 'Mail.php' );
218
219 wfSuppressWarnings();
220
221 // Create the mail object using the Mail::factory method
222 $mail_object =& Mail::factory( 'smtp', $wgSMTP );
223 if ( PEAR::isError( $mail_object ) ) {
224 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
225 wfRestoreWarnings();
226 return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
227 }
228
229 wfDebug( "Sending mail via PEAR::Mail\n" );
230 $chunks = array_chunk( $dest, $wgEnotifMaxRecips );
231 foreach ( $chunks as $chunk ) {
232 $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
233 if ( !$status->isOK() ) {
234 wfRestoreWarnings();
235 return $status;
236 }
237 }
238 wfRestoreWarnings();
239 return Status::newGood();
240 } else {
241 # Line endings need to be different on Unix and Windows due to
242 # the bug described at http://trac.wordpress.org/ticket/2603
243 if ( wfIsWindows() ) {
244 $body = str_replace( "\n", "\r\n", $body );
245 $endl = "\r\n";
246 } else {
247 $endl = "\n";
248 }
249
250 $headers = self::arrayToHeaderString( $headers, $endl );
251
252 wfDebug( "Sending mail via internal mail() function\n" );
253
254 self::$mErrorString = '';
255 $html_errors = ini_get( 'html_errors' );
256 ini_set( 'html_errors', '0' );
257 set_error_handler( 'UserMailer::errorHandler' );
258
259 $safeMode = wfIniGetBool( 'safe_mode' );
260 foreach ( $dest as $recip ) {
261 if ( $safeMode ) {
262 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers );
263 } else {
264 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
265 }
266 }
267
268 restore_error_handler();
269 ini_set( 'html_errors', $html_errors );
270
271 if ( self::$mErrorString ) {
272 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
273 return Status::newFatal( 'php-mail-error', self::$mErrorString );
274 } elseif ( ! $sent ) {
275 // mail function only tells if there's an error
276 wfDebug( "Unknown error sending mail\n" );
277 return Status::newFatal( 'php-mail-error-unknown' );
278 } else {
279 return Status::newGood();
280 }
281 }
282 }
283
284 /**
285 * Set the mail error message in self::$mErrorString
286 *
287 * @param $code Integer: error number
288 * @param $string String: error message
289 */
290 static function errorHandler( $code, $string ) {
291 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
292 }
293
294 /**
295 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
296 * @param $phrase string
297 * @return string
298 */
299 public static function rfc822Phrase( $phrase ) {
300 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
301 return '"' . $phrase . '"';
302 }
303
304 /**
305 * Converts a string into quoted-printable format
306 * @since 1.17
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 $to, $subject, $body, $replyto, $from;
355 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
356 protected $mailTargets = array();
357
358 /**
359 * Send emails corresponding to the user $editor editing the page $title.
360 * Also updates wl_notificationtimestamp.
361 *
362 * May be deferred via the job queue.
363 *
364 * @param $editor User object
365 * @param $title Title object
366 * @param $timestamp
367 * @param $summary
368 * @param $minorEdit
369 * @param $oldid (default: false)
370 */
371 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
372 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
373 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
374
375 if ( $title->getNamespace() < 0 ) {
376 return;
377 }
378
379 // Build a list of users to notfiy
380 $watchers = array();
381 if ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) {
382 $dbw = wfGetDB( DB_MASTER );
383 $res = $dbw->select( array( 'watchlist' ),
384 array( 'wl_user' ),
385 array(
386 'wl_title' => $title->getDBkey(),
387 'wl_namespace' => $title->getNamespace(),
388 'wl_user != ' . intval( $editor->getID() ),
389 'wl_notificationtimestamp IS NULL',
390 ), __METHOD__
391 );
392 foreach ( $res as $row ) {
393 $watchers[] = intval( $row->wl_user );
394 }
395 if ( $watchers ) {
396 // Update wl_notificationtimestamp for all watching users except
397 // the editor
398 $dbw->begin();
399 $dbw->update( 'watchlist',
400 array( /* SET */
401 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
402 ), array( /* WHERE */
403 'wl_title' => $title->getDBkey(),
404 'wl_namespace' => $title->getNamespace(),
405 'wl_user' => $watchers
406 ), __METHOD__
407 );
408 $dbw->commit();
409 }
410 }
411
412 $sendEmail = true;
413 // If nobody is watching the page, and there are no users notified on all changes
414 // don't bother creating a job/trying to send emails
415 // $watchers deals with $wgEnotifWatchlist
416 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
417 $sendEmail = false;
418 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
419 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
420 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
421 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
422 $sendEmail = true;
423 }
424 }
425 }
426
427 if ( !$sendEmail ) {
428 return;
429 }
430 if ( $wgEnotifUseJobQ ) {
431 $params = array(
432 'editor' => $editor->getName(),
433 'editorID' => $editor->getID(),
434 'timestamp' => $timestamp,
435 'summary' => $summary,
436 'minorEdit' => $minorEdit,
437 'oldid' => $oldid,
438 'watchers' => $watchers
439 );
440 $job = new EnotifNotifyJob( $title, $params );
441 $job->insert();
442 } else {
443 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
444 }
445 }
446
447 /**
448 * Immediate version of notifyOnPageChange().
449 *
450 * Send emails corresponding to the user $editor editing the page $title.
451 * Also updates wl_notificationtimestamp.
452 *
453 * @param $editor User object
454 * @param $title Title object
455 * @param $timestamp string Edit timestamp
456 * @param $summary string Edit summary
457 * @param $minorEdit bool
458 * @param $oldid int Revision ID
459 * @param $watchers array of user IDs
460 */
461 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
462 # we use $wgPasswordSender as sender's address
463 global $wgEnotifWatchlist;
464 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
465
466 wfProfileIn( __METHOD__ );
467
468 # The following code is only run, if several conditions are met:
469 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
470 # 2. minor edits (changes) are only regarded if the global flag indicates so
471
472 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
473
474 $this->title = $title;
475 $this->timestamp = $timestamp;
476 $this->summary = $summary;
477 $this->minorEdit = $minorEdit;
478 $this->oldid = $oldid;
479 $this->editor = $editor;
480 $this->composed_common = false;
481
482 $userTalkId = false;
483
484 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
485
486 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
487 $targetUser = User::newFromName( $title->getText() );
488 $this->compose( $targetUser );
489 $userTalkId = $targetUser->getId();
490 }
491
492 if ( $wgEnotifWatchlist ) {
493 // Send updates to watchers other than the current editor
494 $userArray = UserArray::newFromIDs( $watchers );
495 foreach ( $userArray as $watchingUser ) {
496 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
497 ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) ) &&
498 $watchingUser->isEmailConfirmed() &&
499 $watchingUser->getID() != $userTalkId )
500 {
501 $this->compose( $watchingUser );
502 }
503 }
504 }
505 }
506
507 global $wgUsersNotifiedOnAllChanges;
508 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
509 $user = User::newFromName( $name );
510 $this->compose( $user );
511 }
512
513 $this->sendMails();
514 wfProfileOut( __METHOD__ );
515 }
516
517 /**
518 * @param $editor User
519 * @param $title Title bool
520 * @param $minorEdit
521 * @return bool
522 */
523 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
524 global $wgEnotifUserTalk;
525 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
526
527 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
528 $targetUser = User::newFromName( $title->getText() );
529
530 if ( !$targetUser || $targetUser->isAnon() ) {
531 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
532 } elseif ( $targetUser->getId() == $editor->getId() ) {
533 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
534 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) &&
535 ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) ) )
536 {
537 if ( $targetUser->isEmailConfirmed() ) {
538 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
539 return true;
540 } else {
541 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
542 }
543 } else {
544 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
545 }
546 }
547 return false;
548 }
549
550 /**
551 * Generate the generic "this page has been changed" e-mail text.
552 */
553 private function composeCommonMailtext() {
554 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
555 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
556 global $wgEnotifImpersonal, $wgEnotifUseRealName;
557
558 $this->composed_common = true;
559
560 $summary = ( $this->summary == '' ) ? ' - ' : $this->summary;
561 $medit = ( $this->minorEdit ) ? wfMsgForContent( 'minoredit' ) : '';
562
563 # You as the WikiAdmin and Sysops can make use of plenty of
564 # named variables when composing your notification emails while
565 # simply editing the Meta pages
566
567 $subject = wfMsgForContent( 'enotif_subject' );
568 $body = wfMsgForContent( 'enotif_body' );
569 $from = ''; /* fail safe */
570 $replyto = ''; /* fail safe */
571 $keys = array();
572
573 if ( $this->oldid ) {
574 $difflink = $this->title->getCanonicalUrl( 'diff=0&oldid=' . $this->oldid );
575 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
576 $keys['$OLDID'] = $this->oldid;
577 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
578 } else {
579 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
580 # clear $OLDID placeholder in the message template
581 $keys['$OLDID'] = '';
582 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
583 }
584
585 if ( $wgEnotifImpersonal && $this->oldid ) {
586 /**
587 * For impersonal mail, show a diff link to the last
588 * revision.
589 */
590 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
591 $this->title->getCanonicalUrl( "oldid={$this->oldid}&diff=next" ) );
592 }
593
594 $body = strtr( $body, $keys );
595 $pagetitle = $this->title->getPrefixedText();
596 $keys['$PAGETITLE'] = $pagetitle;
597 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalUrl();
598
599 $keys['$PAGEMINOREDIT'] = $medit;
600 $keys['$PAGESUMMARY'] = $summary;
601 $keys['$UNWATCHURL'] = $this->title->getCanonicalUrl( 'action=unwatch' );
602
603 $subject = strtr( $subject, $keys );
604
605 # Reveal the page editor's address as REPLY-TO address only if
606 # the user has not opted-out and the option is enabled at the
607 # global configuration level.
608 $editor = $this->editor;
609 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
610 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
611 $editorAddress = new MailAddress( $editor );
612 if ( $wgEnotifRevealEditorAddress
613 && ( $editor->getEmail() != '' )
614 && $editor->getOption( 'enotifrevealaddr' ) ) {
615 if ( $wgEnotifFromEditor ) {
616 $from = $editorAddress;
617 } else {
618 $from = $adminAddress;
619 $replyto = $editorAddress;
620 }
621 } else {
622 $from = $adminAddress;
623 $replyto = new MailAddress( $wgNoReplyAddress );
624 }
625
626 if ( $editor->isAnon() ) {
627 # real anon (user:xxx.xxx.xxx.xxx)
628 $utext = wfMsgForContent( 'enotif_anon_editor', $name );
629 $subject = str_replace( '$PAGEEDITOR', $utext, $subject );
630 $keys['$PAGEEDITOR'] = $utext;
631 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
632 } else {
633 $subject = str_replace( '$PAGEEDITOR', $name, $subject );
634 $keys['$PAGEEDITOR'] = $name;
635 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
636 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalUrl();
637 }
638 $userPage = $editor->getUserPage();
639 $keys['$PAGEEDITOR_WIKI'] = $userPage->getCanonicalUrl();
640 $body = strtr( $body, $keys );
641 $body = wordwrap( $body, 72 );
642
643 # now save this as the constant user-independent part of the message
644 $this->from = $from;
645 $this->replyto = $replyto;
646 $this->subject = $subject;
647 $this->body = $body;
648 }
649
650 /**
651 * Compose a mail to a given user and either queue it for sending, or send it now,
652 * depending on settings.
653 *
654 * Call sendMails() to send any mails that were queued.
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 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
695 $body = str_replace( '$WATCHINGUSERNAME', $name, $this->body );
696
697 $timecorrection = $watchingUser->getOption( 'timecorrection' );
698
699 # $PAGEEDITDATE is the time and date of the page change
700 # expressed in terms of individual local time of the notification
701 # recipient, i.e. watching user
702 $body = str_replace(
703 array( '$PAGEEDITDATEANDTIME',
704 '$PAGEEDITDATE',
705 '$PAGEEDITTIME' ),
706 array( $wgContLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
707 $wgContLang->date( $this->timestamp, true, false, $timecorrection ),
708 $wgContLang->time( $this->timestamp, true, false, $timecorrection ) ),
709 $body );
710
711 return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
712 }
713
714 /**
715 * Same as sendPersonalised but does impersonal mail suitable for bulk
716 * mailing. Takes an array of MailAddress objects.
717 */
718 function sendImpersonal( $addresses ) {
719 global $wgContLang;
720
721 if ( empty( $addresses ) )
722 return;
723
724 $body = str_replace(
725 array( '$WATCHINGUSERNAME',
726 '$PAGEEDITDATE',
727 '$PAGEEDITTIME' ),
728 array( wfMsgForContent( 'enotif_impersonal_salutation' ),
729 $wgContLang->date( $this->timestamp, true, false, false ),
730 $wgContLang->time( $this->timestamp, true, false, false ) ),
731 $this->body );
732
733 return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
734 }
735
736 } # end of class EmailNotification