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" ) {
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() {
130 global $wgSMTP, $wgServer;
132 $msgid = uniqid( wfWikiID() . ".", true ); /* true required for cygwin */
133 if ( is_array($wgSMTP) && isset($wgSMTP['IDHost']) && $wgSMTP['IDHost'] ) {
134 $domain = $wgSMTP['IDHost'];
136 $url = wfParseUrl($wgServer);
137 $domain = $url['host'];
139 return "<$msgid@$domain>";
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.
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
156 public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8' ) {
157 global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams;
159 if ( !is_array( $to ) ) {
163 wfDebug( __METHOD__
. ': sending mail to ' . implode( ', ', $to ) . "\n" );
166 foreach ( $to as $u ) {
168 $dest[] = $u->address
;
171 if ( count( $dest ) == 0 ) {
172 return Status
::newFatal( 'user-mail-no-addy' );
175 $headers['From'] = $from->toString();
176 $headers['Return-Path'] = $from->address
;
177 if ( count( $to ) == 1 ) {
178 $headers['To'] = $to[0]->toString();
180 $headers['To'] = 'undisclosed-recipients:;';
184 $headers['Reply-To'] = $replyto->toString();
187 $headers['Subject'] = self
::quotedPrintable( $subject );
188 $headers['Date'] = date( 'r' );
189 $headers['MIME-Version'] = '1.0';
190 $headers['Content-type'] = ( is_null( $contentType ) ?
191 'text/plain; charset=UTF-8' : $contentType );
192 $headers['Content-transfer-encoding'] = '8bit';
194 $headers['Message-ID'] = self
::makeMsgId();
195 $headers['X-Mailer'] = 'MediaWiki mailer';
197 $ret = wfRunHooks( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) );
198 if ( $ret === false ) {
199 return Status
::newGood();
200 } elseif ( $ret !== true ) {
201 return Status
::newFatal( 'php-mail-error', $ret );
204 if ( is_array( $wgSMTP ) ) {
205 if ( function_exists( 'stream_resolve_include_path' ) ) {
206 $found = stream_resolve_include_path( 'Mail.php' );
208 $found = Fallback
::stream_resolve_include_path( 'Mail.php' );
211 throw new MWException( 'PEAR mail package is not installed' );
213 require_once( 'Mail.php' );
215 wfSuppressWarnings();
217 // Create the mail object using the Mail::factory method
218 $mail_object =& Mail
::factory( 'smtp', $wgSMTP );
219 if ( PEAR
::isError( $mail_object ) ) {
220 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
222 return Status
::newFatal( 'pear-mail-error', $mail_object->getMessage() );
225 wfDebug( "Sending mail via PEAR::Mail\n" );
226 $chunks = array_chunk( $dest, $wgEnotifMaxRecips );
227 foreach ( $chunks as $chunk ) {
228 $status = self
::sendWithPear( $mail_object, $chunk, $headers, $body );
229 if ( !$status->isOK() ) {
235 return Status
::newGood();
237 # Line endings need to be different on Unix and Windows due to
238 # the bug described at http://trac.wordpress.org/ticket/2603
239 if ( wfIsWindows() ) {
240 $body = str_replace( "\n", "\r\n", $body );
246 $headers = self
::arrayToHeaderString( $headers, $endl );
248 wfDebug( "Sending mail via internal mail() function\n" );
250 self
::$mErrorString = '';
251 $html_errors = ini_get( 'html_errors' );
252 ini_set( 'html_errors', '0' );
253 set_error_handler( 'UserMailer::errorHandler' );
255 $safeMode = wfIniGetBool( 'safe_mode' );
256 foreach ( $dest as $recip ) {
258 $sent = mail( $recip, self
::quotedPrintable( $subject ), $body, $headers );
260 $sent = mail( $recip, self
::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
264 restore_error_handler();
265 ini_set( 'html_errors', $html_errors );
267 if ( self
::$mErrorString ) {
268 wfDebug( "Error sending mail: " . self
::$mErrorString . "\n" );
269 return Status
::newFatal( 'php-mail-error', self
::$mErrorString );
270 } elseif ( ! $sent ) {
271 // mail function only tells if there's an error
272 wfDebug( "Unknown error sending mail\n" );
273 return Status
::newFatal( 'php-mail-error-unknown' );
275 return Status
::newGood();
281 * Set the mail error message in self::$mErrorString
283 * @param $code Integer: error number
284 * @param $string String: error message
286 static function errorHandler( $code, $string ) {
287 self
::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
291 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
292 * @param $phrase string
295 public static function rfc822Phrase( $phrase ) {
296 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
297 return '"' . $phrase . '"';
301 * Converts a string into quoted-printable format
305 public static function quotedPrintable( $string, $charset = '' ) {
306 # Probably incomplete; see RFC 2045
307 if( empty( $charset ) ) {
310 $charset = strtoupper( $charset );
311 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
313 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
314 $replace = $illegal . '\t ?_';
315 if( !preg_match( "/[$illegal]/", $string ) ) {
318 $out = "=?$charset?Q?";
319 $out .= preg_replace_callback( "/([$replace])/",
320 array( __CLASS__
, 'quotedPrintableCallback' ), $string );
325 protected static function quotedPrintableCallback( $matches ) {
326 return sprintf( "=%02X", ord( $matches[1] ) );
331 * This module processes the email notifications when the current page is
332 * changed. It looks up the table watchlist to find out which users are watching
335 * The current implementation sends independent emails to each watching user for
336 * the following reason:
338 * - Each watching user will be notified about the page edit time expressed in
339 * his/her local time (UTC is shown additionally). To achieve this, we need to
340 * find the individual timeoffset of each watching user from the preferences..
342 * Suggested improvement to slack down the number of sent emails: We could think
343 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
344 * same timeoffset in their preferences.
346 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
350 class EmailNotification
{
351 protected $subject, $body, $replyto, $from;
352 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common;
353 protected $mailTargets = array();
366 * Send emails corresponding to the user $editor editing the page $title.
367 * Also updates wl_notificationtimestamp.
369 * May be deferred via the job queue.
371 * @param $editor User object
372 * @param $title Title object
376 * @param $oldid (default: false)
378 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
379 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
380 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
382 if ( $title->getNamespace() < 0 ) {
386 // Build a list of users to notfiy
388 if ( $wgEnotifWatchlist ||
$wgShowUpdatedMarker ) {
389 $dbw = wfGetDB( DB_MASTER
);
390 $res = $dbw->select( array( 'watchlist' ),
393 'wl_title' => $title->getDBkey(),
394 'wl_namespace' => $title->getNamespace(),
395 'wl_user != ' . intval( $editor->getID() ),
396 'wl_notificationtimestamp IS NULL',
399 foreach ( $res as $row ) {
400 $watchers[] = intval( $row->wl_user
);
403 // Update wl_notificationtimestamp for all watching users except
406 $dbw->update( 'watchlist',
408 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
409 ), array( /* WHERE */
410 'wl_title' => $title->getDBkey(),
411 'wl_namespace' => $title->getNamespace(),
412 'wl_user' => $watchers
420 // If nobody is watching the page, and there are no users notified on all changes
421 // don't bother creating a job/trying to send emails
422 // $watchers deals with $wgEnotifWatchlist
423 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
425 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
426 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
427 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
428 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
437 if ( $wgEnotifUseJobQ ) {
439 'editor' => $editor->getName(),
440 'editorID' => $editor->getID(),
441 'timestamp' => $timestamp,
442 'summary' => $summary,
443 'minorEdit' => $minorEdit,
445 'watchers' => $watchers
447 $job = new EnotifNotifyJob( $title, $params );
450 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
455 * Immediate version of notifyOnPageChange().
457 * Send emails corresponding to the user $editor editing the page $title.
458 * Also updates wl_notificationtimestamp.
460 * @param $editor User object
461 * @param $title Title object
462 * @param $timestamp string Edit timestamp
463 * @param $summary string Edit summary
464 * @param $minorEdit bool
465 * @param $oldid int Revision ID
466 * @param $watchers array of user IDs
468 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
469 # we use $wgPasswordSender as sender's address
470 global $wgEnotifWatchlist;
471 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
473 wfProfileIn( __METHOD__
);
475 # The following code is only run, if several conditions are met:
476 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
477 # 2. minor edits (changes) are only regarded if the global flag indicates so
479 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
481 $this->title
= $title;
482 $this->timestamp
= $timestamp;
483 $this->summary
= $summary;
484 $this->minorEdit
= $minorEdit;
485 $this->oldid
= $oldid;
486 $this->editor
= $editor;
487 $this->composed_common
= false;
491 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
493 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
494 $targetUser = User
::newFromName( $title->getText() );
495 $this->compose( $targetUser );
496 $userTalkId = $targetUser->getId();
499 if ( $wgEnotifWatchlist ) {
500 // Send updates to watchers other than the current editor
501 $userArray = UserArray
::newFromIDs( $watchers );
502 foreach ( $userArray as $watchingUser ) {
503 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
504 ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) ) &&
505 $watchingUser->isEmailConfirmed() &&
506 $watchingUser->getID() != $userTalkId )
508 $this->compose( $watchingUser );
514 global $wgUsersNotifiedOnAllChanges;
515 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
516 if ( $editor->getName() == $name ) {
517 // No point notifying the user that actually made the change!
520 $user = User
::newFromName( $name );
521 $this->compose( $user );
525 wfProfileOut( __METHOD__
);
529 * @param $editor User
530 * @param $title Title bool
534 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
535 global $wgEnotifUserTalk;
536 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
538 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
539 $targetUser = User
::newFromName( $title->getText() );
541 if ( !$targetUser ||
$targetUser->isAnon() ) {
542 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
543 } elseif ( $targetUser->getId() == $editor->getId() ) {
544 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
545 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) &&
546 ( !$minorEdit ||
$targetUser->getOption( 'enotifminoredits' ) ) )
548 if ( $targetUser->isEmailConfirmed() ) {
549 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
552 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
555 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
562 * Generate the generic "this page has been changed" e-mail text.
564 private function composeCommonMailtext() {
565 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
566 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
567 global $wgEnotifImpersonal, $wgEnotifUseRealName;
569 $this->composed_common
= true;
571 # You as the WikiAdmin and Sysops can make use of plenty of
572 # named variables when composing your notification emails while
573 # simply editing the Meta pages
577 if ( $this->oldid
) {
578 if ( $wgEnotifImpersonal ) {
579 // For impersonal mail, show a diff link to the last revision.
580 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
581 $this->title
->getCanonicalUrl( 'diff=next&oldid=' . $this->oldid
) );
583 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited',
584 $this->title
->getCanonicalUrl( 'diff=0&oldid=' . $this->oldid
) );
586 $keys['$OLDID'] = $this->oldid
;
587 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
589 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
590 # clear $OLDID placeholder in the message template
591 $keys['$OLDID'] = '';
592 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
595 $keys['$PAGETITLE'] = $this->title
->getPrefixedText();
596 $keys['$PAGETITLE_URL'] = $this->title
->getCanonicalUrl();
597 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
wfMsgForContent( 'minoredit' ) : '';
598 $keys['$PAGESUMMARY'] = $this->summary
== '' ?
' - ' : $this->summary
;
599 $keys['$UNWATCHURL'] = $this->title
->getCanonicalUrl( 'action=unwatch' );
601 if ( $this->editor
->isAnon() ) {
602 # real anon (user:xxx.xxx.xxx.xxx)
603 $keys['$PAGEEDITOR'] = wfMsgForContent( 'enotif_anon_editor', $this->editor
->getName() );
604 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
606 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName ?
$this->editor
->getRealName() : $this->editor
->getName();
607 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $this->editor
->getName() );
608 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalUrl();
611 $keys['$PAGEEDITOR_WIKI'] = $this->editor
->getUserPage()->getCanonicalUrl();
613 # Now build message's subject and body
615 $subject = wfMsgExt( 'enotif_subject', 'content' );
616 $subject = strtr( $subject, $keys );
617 $this->subject
= MessageCache
::singleton()->transform( $subject, false, null, $this->title
);
619 $body = wfMsgExt( 'enotif_body', 'content' );
620 $body = strtr( $body, $keys );
621 $body = MessageCache
::singleton()->transform( $body, false, null, $this->title
);
622 $this->body
= wordwrap( $body, 72 );
624 # Reveal the page editor's address as REPLY-TO address only if
625 # the user has not opted-out and the option is enabled at the
626 # global configuration level.
627 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
628 if ( $wgEnotifRevealEditorAddress
629 && ( $this->editor
->getEmail() != '' )
630 && $this->editor
->getOption( 'enotifrevealaddr' ) )
632 $editorAddress = new MailAddress( $this->editor
);
633 if ( $wgEnotifFromEditor ) {
634 $this->from
= $editorAddress;
636 $this->from
= $adminAddress;
637 $this->replyto
= $editorAddress;
640 $this->from
= $adminAddress;
641 $this->replyto
= new MailAddress( $wgNoReplyAddress );
646 * Compose a mail to a given user and either queue it for sending, or send it now,
647 * depending on settings.
649 * Call sendMails() to send any mails that were queued.
652 function compose( $user ) {
653 global $wgEnotifImpersonal;
655 if ( !$this->composed_common
)
656 $this->composeCommonMailtext();
658 if ( $wgEnotifImpersonal ) {
659 $this->mailTargets
[] = new MailAddress( $user );
661 $this->sendPersonalised( $user );
666 * Send any queued mails
668 function sendMails() {
669 global $wgEnotifImpersonal;
670 if ( $wgEnotifImpersonal ) {
671 $this->sendImpersonal( $this->mailTargets
);
676 * Does the per-user customizations to a notification e-mail (name,
677 * timestamp in proper timezone, etc) and sends it out.
678 * Returns true if the mail was sent successfully.
680 * @param $watchingUser User object
684 function sendPersonalised( $watchingUser ) {
685 global $wgContLang, $wgEnotifUseRealName;
686 // From the PHP manual:
687 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
688 // The mail command will not parse this properly while talking with the MTA.
689 $to = new MailAddress( $watchingUser );
691 # $PAGEEDITDATE is the time and date of the page change
692 # expressed in terms of individual local time of the notification
693 # recipient, i.e. watching user
695 array( '$WATCHINGUSERNAME',
698 array( $wgEnotifUseRealName ?
$watchingUser->getRealName() : $watchingUser->getName(),
699 $wgContLang->userDate( $this->timestamp
, $watchingUser ),
700 $wgContLang->userTime( $this->timestamp
, $watchingUser ) ),
703 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, $this->replyto
);
707 * Same as sendPersonalised but does impersonal mail suitable for bulk
708 * mailing. Takes an array of MailAddress objects.
711 function sendImpersonal( $addresses ) {
714 if ( empty( $addresses ) )
718 array( '$WATCHINGUSERNAME',
721 array( wfMsgForContent( 'enotif_impersonal_salutation' ),
722 $wgContLang->date( $this->timestamp
, false, false ),
723 $wgContLang->time( $this->timestamp
, false, false ) ),
726 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, $this->replyto
);
729 } # end of class EmailNotification