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