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 $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"
117 static function arrayToHeaderString( $headers, $endl = "\n" ) {
119 foreach( $headers as $name => $value ) {
120 $strings[] = "$name: $value";
122 return implode( $endl, $strings );
126 * Create a value suitable for the MessageId Header
130 static function makeMsgId() {
131 global $wgSMTP, $wgServer;
133 $msgid = uniqid( wfWikiID() . ".", true ); /* true required for cygwin */
134 if ( is_array($wgSMTP) && isset($wgSMTP['IDHost']) && $wgSMTP['IDHost'] ) {
135 $domain = $wgSMTP['IDHost'];
137 $url = wfParseUrl($wgServer);
138 $domain = $url['host'];
140 return "<$msgid@$domain>";
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.
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
157 public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8' ) {
158 global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams;
160 if ( !is_array( $to ) ) {
164 wfDebug( __METHOD__
. ': sending mail to ' . implode( ', ', $to ) . "\n" );
167 foreach ( $to as $u ) {
169 $dest[] = $u->address
;
172 if ( count( $dest ) == 0 ) {
173 return Status
::newFatal( 'user-mail-no-addy' );
176 $headers['From'] = $from->toString();
177 $headers['Return-Path'] = $from->address
;
178 if ( count( $to ) == 1 ) {
179 $headers['To'] = $to[0]->toString();
181 $headers['To'] = 'undisclosed-recipients:;';
185 $headers['Reply-To'] = $replyto->toString();
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';
195 $headers['Message-ID'] = self
::makeMsgId();
196 $headers['X-Mailer'] = 'MediaWiki mailer';
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 );
205 if ( is_array( $wgSMTP ) ) {
206 if ( function_exists( 'stream_resolve_include_path' ) ) {
207 $found = stream_resolve_include_path( 'Mail.php' );
209 $found = Fallback
::stream_resolve_include_path( 'Mail.php' );
212 throw new MWException( 'PEAR mail package is not installed' );
214 require_once( 'Mail.php' );
216 wfSuppressWarnings();
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" );
223 return Status
::newFatal( 'pear-mail-error', $mail_object->getMessage() );
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() ) {
236 return Status
::newGood();
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 );
247 # Subject header is unneeded since it an argument of mail()
248 unset( $headers['Subject'] );
249 $headers = self
::arrayToHeaderString( $headers, $endl );
251 wfDebug( "Sending mail via internal mail() function\n" );
253 self
::$mErrorString = '';
254 $html_errors = ini_get( 'html_errors' );
255 ini_set( 'html_errors', '0' );
256 set_error_handler( 'UserMailer::errorHandler' );
258 $safeMode = wfIniGetBool( 'safe_mode' );
259 foreach ( $dest as $recip ) {
261 $sent = mail( $recip, self
::quotedPrintable( $subject ), $body, $headers );
263 $sent = mail( $recip, self
::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
267 restore_error_handler();
268 ini_set( 'html_errors', $html_errors );
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' );
278 return Status
::newGood();
284 * Set the mail error message in self::$mErrorString
286 * @param $code Integer: error number
287 * @param $string String: error message
289 static function errorHandler( $code, $string ) {
290 self
::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
294 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
295 * @param $phrase string
298 public static function rfc822Phrase( $phrase ) {
299 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
300 return '"' . $phrase . '"';
304 * Converts a string into quoted-printable format
308 public static function quotedPrintable( $string, $charset = '' ) {
309 # Probably incomplete; see RFC 2045
310 if( empty( $charset ) ) {
313 $charset = strtoupper( $charset );
314 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
316 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
317 $replace = $illegal . '\t ?_';
318 if( !preg_match( "/[$illegal]/", $string ) ) {
321 $out = "=?$charset?Q?";
322 $out .= preg_replace_callback( "/([$replace])/",
323 array( __CLASS__
, 'quotedPrintableCallback' ), $string );
328 protected static function quotedPrintableCallback( $matches ) {
329 return sprintf( "=%02X", ord( $matches[1] ) );
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
338 * The current implementation sends independent emails to each watching user for
339 * the following reason:
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..
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.
349 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
353 class EmailNotification
{
354 protected $subject, $body, $replyto, $from;
355 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common;
356 protected $mailTargets = array();
369 * Send emails corresponding to the user $editor editing the page $title.
370 * Also updates wl_notificationtimestamp.
372 * May be deferred via the job queue.
374 * @param $editor User object
375 * @param $title Title object
379 * @param $oldid (default: false)
381 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
382 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
383 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
385 if ( $title->getNamespace() < 0 ) {
389 // Build a list of users to notfiy
391 if ( $wgEnotifWatchlist ||
$wgShowUpdatedMarker ) {
392 $dbw = wfGetDB( DB_MASTER
);
393 $res = $dbw->select( array( 'watchlist' ),
396 'wl_title' => $title->getDBkey(),
397 'wl_namespace' => $title->getNamespace(),
398 'wl_user != ' . intval( $editor->getID() ),
399 'wl_notificationtimestamp IS NULL',
402 foreach ( $res as $row ) {
403 $watchers[] = intval( $row->wl_user
);
406 // Update wl_notificationtimestamp for all watching users except
409 $dbw->update( 'watchlist',
411 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
412 ), array( /* WHERE */
413 'wl_title' => $title->getDBkey(),
414 'wl_namespace' => $title->getNamespace(),
415 'wl_user' => $watchers
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 ) ) {
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 ) ) {
440 if ( $wgEnotifUseJobQ ) {
442 'editor' => $editor->getName(),
443 'editorID' => $editor->getID(),
444 'timestamp' => $timestamp,
445 'summary' => $summary,
446 'minorEdit' => $minorEdit,
448 'watchers' => $watchers
450 $job = new EnotifNotifyJob( $title, $params );
453 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
458 * Immediate version of notifyOnPageChange().
460 * Send emails corresponding to the user $editor editing the page $title.
461 * Also updates wl_notificationtimestamp.
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
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;
476 wfProfileIn( __METHOD__
);
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
482 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
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;
494 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
496 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
497 $targetUser = User
::newFromName( $title->getText() );
498 $this->compose( $targetUser );
499 $userTalkId = $targetUser->getId();
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 )
511 $this->compose( $watchingUser );
517 global $wgUsersNotifiedOnAllChanges;
518 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
519 if ( $editor->getName() == $name ) {
520 // No point notifying the user that actually made the change!
523 $user = User
::newFromName( $name );
524 $this->compose( $user );
528 wfProfileOut( __METHOD__
);
532 * @param $editor User
533 * @param $title Title bool
537 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
538 global $wgEnotifUserTalk;
539 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
541 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
542 $targetUser = User
::newFromName( $title->getText() );
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' ) ) )
551 if ( $targetUser->isEmailConfirmed() ) {
552 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
555 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
558 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
565 * Generate the generic "this page has been changed" e-mail text.
567 private function composeCommonMailtext() {
568 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
569 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
570 global $wgEnotifImpersonal, $wgEnotifUseRealName;
572 $this->composed_common
= true;
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
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
) );
590 $keys['$OLDID'] = $this->oldid
;
591 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
593 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
594 # clear $OLDID placeholder in the message template
595 $keys['$OLDID'] = '';
596 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
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' );
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' );
610 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName ?
$this->editor
->getRealName() : $this->editor
->getName();
611 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $this->editor
->getName() );
612 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalUrl();
615 $keys['$PAGEEDITOR_WIKI'] = $this->editor
->getUserPage()->getCanonicalUrl();
617 # Now build message's subject and body
619 $subject = wfMsgExt( 'enotif_subject', 'content' );
620 $subject = strtr( $subject, $keys );
621 $this->subject
= MessageCache
::singleton()->transform( $subject, false, null, $this->title
);
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 );
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' ) )
636 $editorAddress = new MailAddress( $this->editor
);
637 if ( $wgEnotifFromEditor ) {
638 $this->from
= $editorAddress;
640 $this->from
= $adminAddress;
641 $this->replyto
= $editorAddress;
644 $this->from
= $adminAddress;
645 $this->replyto
= new MailAddress( $wgNoReplyAddress );
650 * Compose a mail to a given user and either queue it for sending, or send it now,
651 * depending on settings.
653 * Call sendMails() to send any mails that were queued.
656 function compose( $user ) {
657 global $wgEnotifImpersonal;
659 if ( !$this->composed_common
)
660 $this->composeCommonMailtext();
662 if ( $wgEnotifImpersonal ) {
663 $this->mailTargets
[] = new MailAddress( $user );
665 $this->sendPersonalised( $user );
670 * Send any queued mails
672 function sendMails() {
673 global $wgEnotifImpersonal;
674 if ( $wgEnotifImpersonal ) {
675 $this->sendImpersonal( $this->mailTargets
);
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.
684 * @param $watchingUser User object
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 );
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
699 array( '$WATCHINGUSERNAME',
702 array( $wgEnotifUseRealName ?
$watchingUser->getRealName() : $watchingUser->getName(),
703 $wgContLang->userDate( $this->timestamp
, $watchingUser ),
704 $wgContLang->userTime( $this->timestamp
, $watchingUser ) ),
707 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, $this->replyto
);
711 * Same as sendPersonalised but does impersonal mail suitable for bulk
712 * mailing. Takes an array of MailAddress objects.
715 function sendImpersonal( $addresses ) {
718 if ( empty( $addresses ) )
722 array( '$WATCHINGUSERNAME',
725 array( wfMsgForContent( 'enotif_impersonal_salutation' ),
726 $wgContLang->date( $this->timestamp
, false, false ),
727 $wgContLang->time( $this->timestamp
, false, false ) ),
730 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, $this->replyto
);
733 } # end of class EmailNotification