3 * Classes used to send e-mails
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.
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.
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
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
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.
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
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();
44 $this->address
= strval( $address );
45 $this->name
= strval( $name );
46 $this->realName
= strval( $realName );
51 * Return formatted and quoted address to insert into SMTP headers
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 . '"';
66 return "$quoted <{$this->address}>";
68 return $this->address
;
75 function __toString() {
76 return $this->toString();
82 * Collection of static functions for sending mail
88 * Send mail using a PEAR mailer
97 protected static function sendWithPear( $mailer, $dest, $headers, $body ) {
98 $mailResult = $mailer->send( $dest, $headers, $body );
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() );
105 return Status
::newGood();
110 * Creates a single string from an associative array
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"
117 static function arrayToHeaderString( $headers, $endl = "\n" ) {
118 foreach( $headers as $name => $value ) {
119 $string[] = "$name: $value";
121 return implode( $endl, $string );
125 * Create a value suitable for the MessageId Header
129 static function makeMsgId() {
132 $msgid = uniqid( "UserMailer", true ); /* true required for cygwin */
133 return "<$msgid@$wgServer>";
137 * This function will perform a direct (authenticated) login to
138 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
139 * array of parameters. It requires PEAR:Mail to do that.
140 * Otherwise it just uses the standard PHP 'mail' function.
142 * @param $to MailAddress: recipient's email (or an array of them)
143 * @param $from MailAddress: sender's email
144 * @param $subject String: email's subject.
145 * @param $body String: email's text.
146 * @param $replyto MailAddress: optional reply-to email (default: null).
147 * @param $contentType String: optional custom Content-Type (default: text/plain; charset=UTF-8)
148 * @return Status object
150 public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8' ) {
151 global $wgSMTP, $wgEnotifImpersonal;
152 global $wgEnotifMaxRecips, $wgAdditionalMailParams;
155 wfDebug( __METHOD__
. ': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
157 $headers['From'] = $from->toString();
158 $headers['Return-Path'] = $from->toString();
161 if ( is_array( $to ) ) {
162 foreach ( $to as $u ) {
164 $dest[] = $u->address
;
167 } else if( $to->address
) {
168 $dest[] = $to->address
;
170 if ( count( $dest ) == 0 ) {
171 return Status
::newFatal( 'user-mail-no-addy' );
174 if ( $wgEnotifImpersonal ) {
175 $headers['To'] = 'undisclosed-recipients:;';
178 $headers['To'] = implode( ", ", $dest );
182 $headers['Reply-To'] = $replyto->toString();
184 $headers['Subject'] = self
::quotedPrintable( $subject );
185 $headers['Date'] = date( 'r' );
186 $headers['MIME-Version'] = '1.0';
187 $headers['Content-type'] = ( is_null( $contentType ) ?
188 'text/plain; charset=UTF-8' : $contentType );
189 $headers['Content-transfer-encoding'] = '8bit';
191 $headers['Message-ID'] = self
::makeMsgId();
192 $headers['X-Mailer'] = 'MediaWiki mailer';
193 $headers['From'] = $from->toString();
195 $ret = wfRunHooks( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) );
196 if ( $ret === false ) {
197 return Status
::newGood();
198 } else if ( $ret !== true ) {
199 return Status
::newFatal( 'php-mail-error', $ret );
202 if ( is_array( $wgSMTP ) ) {
203 if ( function_exists( 'stream_resolve_include_path' ) ) {
204 $found = stream_resolve_include_path( 'Mail.php' );
206 $found = Fallback
::stream_resolve_include_path( 'Mail.php' );
209 throw new MWException( 'PEAR mail package is not installed' );
211 require_once( 'Mail.php' );
213 wfSuppressWarnings();
215 // Create the mail object using the Mail::factory method
216 $mail_object =& Mail
::factory( 'smtp', $wgSMTP );
217 if ( PEAR
::isError( $mail_object ) ) {
218 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
220 return Status
::newFatal( 'pear-mail-error', $mail_object->getMessage() );
223 wfDebug( "Sending mail via PEAR::Mail\n" );
224 $chunks = array_chunk( $dest, $wgEnotifMaxRecips );
225 foreach ( $chunks as $chunk ) {
226 $status = self
::sendWithPear( $mail_object, $chunk, $headers, $body );
227 if ( !$status->isOK() ) {
233 return Status
::newGood();
235 # Line endings need to be different on Unix and Windows due to
236 # the bug described at http://trac.wordpress.org/ticket/2603
237 if ( wfIsWindows() ) {
238 $body = str_replace( "\n", "\r\n", $body );
244 $headers = self
::arrayToHeaderString( $headers, $endl );
246 wfDebug( "Sending mail via internal mail() function\n" );
248 self
::$mErrorString = '';
249 $html_errors = ini_get( 'html_errors' );
250 ini_set( 'html_errors', '0' );
251 set_error_handler( 'UserMailer::errorHandler' );
253 foreach ( $dest as $recip ) {
254 $sent = mail( $recip, self
::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
257 restore_error_handler();
258 ini_set( 'html_errors', $html_errors );
260 if ( self
::$mErrorString ) {
261 wfDebug( "Error sending mail: " . self
::$mErrorString . "\n" );
262 return Status
::newFatal( 'php-mail-error', self
::$mErrorString );
263 } elseif ( ! $sent ) {
264 // mail function only tells if there's an error
265 wfDebug( "Unknown error sending mail\n" );
266 return Status
::newFatal( 'php-mail-error-unknown' );
268 return Status
::newGood();
274 * Set the mail error message in self::$mErrorString
276 * @param $code Integer: error number
277 * @param $string String: error message
279 static function errorHandler( $code, $string ) {
280 self
::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
284 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
285 * @param $phrase string
288 public static function rfc822Phrase( $phrase ) {
289 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
290 return '"' . $phrase . '"';
294 * Converts a string into quoted-printable format
297 public static function quotedPrintable( $string, $charset = '' ) {
298 # Probably incomplete; see RFC 2045
299 if( empty( $charset ) ) {
302 $charset = strtoupper( $charset );
303 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
305 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
306 $replace = $illegal . '\t ?_';
307 if( !preg_match( "/[$illegal]/", $string ) ) {
310 $out = "=?$charset?Q?";
311 $out .= preg_replace_callback( "/([$replace])/",
312 array( __CLASS__
, 'quotedPrintableCallback' ), $string );
317 protected static function quotedPrintableCallback( $matches ) {
318 return sprintf( "=%02X", ord( $matches[1] ) );
323 * This module processes the email notifications when the current page is
324 * changed. It looks up the table watchlist to find out which users are watching
327 * The current implementation sends independent emails to each watching user for
328 * the following reason:
330 * - Each watching user will be notified about the page edit time expressed in
331 * his/her local time (UTC is shown additionally). To achieve this, we need to
332 * find the individual timeoffset of each watching user from the preferences..
334 * Suggested improvement to slack down the number of sent emails: We could think
335 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
336 * same timeoffset in their preferences.
338 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
342 class EmailNotification
{
343 protected $to, $subject, $body, $replyto, $from;
344 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
345 protected $mailTargets = array();
348 * Send emails corresponding to the user $editor editing the page $title.
349 * Also updates wl_notificationtimestamp.
351 * May be deferred via the job queue.
353 * @param $editor User object
354 * @param $title Title object
358 * @param $oldid (default: false)
360 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
361 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
363 if ( $title->getNamespace() < 0 ) {
367 // Build a list of users to notfiy
369 if ( $wgEnotifWatchlist ||
$wgShowUpdatedMarker ) {
370 $dbw = wfGetDB( DB_MASTER
);
371 $res = $dbw->select( array( 'watchlist' ),
374 'wl_title' => $title->getDBkey(),
375 'wl_namespace' => $title->getNamespace(),
376 'wl_user != ' . intval( $editor->getID() ),
377 'wl_notificationtimestamp IS NULL',
380 foreach ( $res as $row ) {
381 $watchers[] = intval( $row->wl_user
);
384 // Update wl_notificationtimestamp for all watching users except
387 $dbw->update( 'watchlist',
389 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
390 ), array( /* WHERE */
391 'wl_title' => $title->getDBkey(),
392 'wl_namespace' => $title->getNamespace(),
393 'wl_user' => $watchers
400 if ( $wgEnotifUseJobQ ) {
402 'editor' => $editor->getName(),
403 'editorID' => $editor->getID(),
404 'timestamp' => $timestamp,
405 'summary' => $summary,
406 'minorEdit' => $minorEdit,
408 'watchers' => $watchers
410 $job = new EnotifNotifyJob( $title, $params );
413 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
419 * Immediate version of notifyOnPageChange().
421 * Send emails corresponding to the user $editor editing the page $title.
422 * Also updates wl_notificationtimestamp.
424 * @param $editor User object
425 * @param $title Title object
426 * @param $timestamp string Edit timestamp
427 * @param $summary string Edit summary
428 * @param $minorEdit bool
429 * @param $oldid int Revision ID
430 * @param $watchers array of user IDs
432 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
433 # we use $wgPasswordSender as sender's address
434 global $wgEnotifWatchlist;
435 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
437 wfProfileIn( __METHOD__
);
439 # The following code is only run, if several conditions are met:
440 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
441 # 2. minor edits (changes) are only regarded if the global flag indicates so
443 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
445 $this->title
= $title;
446 $this->timestamp
= $timestamp;
447 $this->summary
= $summary;
448 $this->minorEdit
= $minorEdit;
449 $this->oldid
= $oldid;
450 $this->editor
= $editor;
451 $this->composed_common
= false;
455 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
456 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
457 $targetUser = User
::newFromName( $title->getText() );
458 if ( !$targetUser ||
$targetUser->isAnon() ) {
459 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
460 } elseif ( $targetUser->getId() == $editor->getId() ) {
461 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
462 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) &&
463 ( !$minorEdit ||
$targetUser->getOption( 'enotifminoredits' ) ) )
465 if ( $targetUser->isEmailConfirmed() ) {
466 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
467 $this->compose( $targetUser );
468 $userTalkId = $targetUser->getId();
470 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
473 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
477 if ( $wgEnotifWatchlist ) {
478 // Send updates to watchers other than the current editor
479 $userArray = UserArray
::newFromIDs( $watchers );
480 foreach ( $userArray as $watchingUser ) {
481 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
482 ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) ) &&
483 $watchingUser->isEmailConfirmed() &&
484 $watchingUser->getID() != $userTalkId )
486 $this->compose( $watchingUser );
492 global $wgUsersNotifiedOnAllChanges;
493 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
494 $user = User
::newFromName( $name );
495 $this->compose( $user );
499 wfProfileOut( __METHOD__
);
503 * Generate the generic "this page has been changed" e-mail text.
505 private function composeCommonMailtext() {
506 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
507 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
508 global $wgEnotifImpersonal, $wgEnotifUseRealName;
510 $this->composed_common
= true;
512 $summary = ( $this->summary
== '' ) ?
' - ' : $this->summary
;
513 $medit = ( $this->minorEdit
) ?
wfMsgForContent( 'minoredit' ) : '';
515 # You as the WikiAdmin and Sysops can make use of plenty of
516 # named variables when composing your notification emails while
517 # simply editing the Meta pages
519 $subject = wfMsgForContent( 'enotif_subject' );
520 $body = wfMsgForContent( 'enotif_body' );
521 $from = ''; /* fail safe */
522 $replyto = ''; /* fail safe */
525 if ( $this->oldid
) {
526 $difflink = wfExpandUrl( $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
), PROTO_HTTP
);
527 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
528 $keys['$OLDID'] = $this->oldid
;
529 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
531 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
532 # clear $OLDID placeholder in the message template
533 $keys['$OLDID'] = '';
534 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
537 if ( $wgEnotifImpersonal && $this->oldid
) {
539 * For impersonal mail, show a diff link to the last
542 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
543 wfExpandUrl( $this->title
->getFullURL( "oldid={$this->oldid}&diff=next" ), PROTO_HTTP
) );
546 $body = strtr( $body, $keys );
547 $pagetitle = $this->title
->getPrefixedText();
548 $keys['$PAGETITLE'] = $pagetitle;
549 $keys['$PAGETITLE_URL'] = wfExpandUrl( $this->title
->getFullUrl(), PROTO_HTTP
);
551 $keys['$PAGEMINOREDIT'] = $medit;
552 $keys['$PAGESUMMARY'] = $summary;
553 $keys['$UNWATCHURL'] = wfExpandUrl( $this->title
->getFullUrl( 'action=unwatch' ), PROTO_HTTP
);
555 $subject = strtr( $subject, $keys );
557 # Reveal the page editor's address as REPLY-TO address only if
558 # the user has not opted-out and the option is enabled at the
559 # global configuration level.
560 $editor = $this->editor
;
561 $name = $wgEnotifUseRealName ?
$editor->getRealName() : $editor->getName();
562 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
563 $editorAddress = new MailAddress( $editor );
564 if ( $wgEnotifRevealEditorAddress
565 && ( $editor->getEmail() != '' )
566 && $editor->getOption( 'enotifrevealaddr' ) ) {
567 if ( $wgEnotifFromEditor ) {
568 $from = $editorAddress;
570 $from = $adminAddress;
571 $replyto = $editorAddress;
574 $from = $adminAddress;
575 $replyto = new MailAddress( $wgNoReplyAddress );
578 if ( $editor->isAnon() ) {
579 # real anon (user:xxx.xxx.xxx.xxx)
580 $utext = wfMsgForContent( 'enotif_anon_editor', $name );
581 $subject = str_replace( '$PAGEEDITOR', $utext, $subject );
582 $keys['$PAGEEDITOR'] = $utext;
583 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
585 $subject = str_replace( '$PAGEEDITOR', $name, $subject );
586 $keys['$PAGEEDITOR'] = $name;
587 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
588 $keys['$PAGEEDITOR_EMAIL'] = wfExpandUrl( $emailPage->getFullUrl(), PROTO_HTTP
);
590 $userPage = $editor->getUserPage();
591 $keys['$PAGEEDITOR_WIKI'] = wfExpandUrl( $userPage->getFullUrl(), PROTO_HTTP
);
592 $body = strtr( $body, $keys );
593 $body = wordwrap( $body, 72 );
595 # now save this as the constant user-independent part of the message
597 $this->replyto
= $replyto;
598 $this->subject
= $subject;
603 * Compose a mail to a given user and either queue it for sending, or send it now,
604 * depending on settings.
606 * Call sendMails() to send any mails that were queued.
608 function compose( $user ) {
609 global $wgEnotifImpersonal;
611 if ( !$this->composed_common
)
612 $this->composeCommonMailtext();
614 if ( $wgEnotifImpersonal ) {
615 $this->mailTargets
[] = new MailAddress( $user );
617 $this->sendPersonalised( $user );
622 * Send any queued mails
624 function sendMails() {
625 global $wgEnotifImpersonal;
626 if ( $wgEnotifImpersonal ) {
627 $this->sendImpersonal( $this->mailTargets
);
632 * Does the per-user customizations to a notification e-mail (name,
633 * timestamp in proper timezone, etc) and sends it out.
634 * Returns true if the mail was sent successfully.
636 * @param $watchingUser User object
640 function sendPersonalised( $watchingUser ) {
641 global $wgContLang, $wgEnotifUseRealName;
642 // From the PHP manual:
643 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
644 // The mail command will not parse this properly while talking with the MTA.
645 $to = new MailAddress( $watchingUser );
646 $name = $wgEnotifUseRealName ?
$watchingUser->getRealName() : $watchingUser->getName();
647 $body = str_replace( '$WATCHINGUSERNAME', $name, $this->body
);
649 $timecorrection = $watchingUser->getOption( 'timecorrection' );
651 # $PAGEEDITDATE is the time and date of the page change
652 # expressed in terms of individual local time of the notification
653 # recipient, i.e. watching user
655 array( '$PAGEEDITDATEANDTIME',
658 array( $wgContLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
659 $wgContLang->date( $this->timestamp
, true, false, $timecorrection ),
660 $wgContLang->time( $this->timestamp
, true, false, $timecorrection ) ),
663 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, $this->replyto
);
667 * Same as sendPersonalised but does impersonal mail suitable for bulk
668 * mailing. Takes an array of MailAddress objects.
670 function sendImpersonal( $addresses ) {
673 if ( empty( $addresses ) )
677 array( '$WATCHINGUSERNAME',
680 array( wfMsgForContent( 'enotif_impersonal_salutation' ),
681 $wgContLang->date( $this->timestamp
, true, false, false ),
682 $wgContLang->time( $this->timestamp
, true, false, false ) ),
685 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, $this->replyto
);
688 } # end of class EmailNotification