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 Mixed: 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->name
!= '' && !wfIsWindows() ) {
59 global $wgEnotifUseRealName;
60 $name = ( $wgEnotifUseRealName && $this->realName
) ?
$this->realName
: $this->name
;
61 $quoted = UserMailer
::quotedPrintable( $name );
62 if ( strpos( $quoted, '.' ) !== false ||
strpos( $quoted, ',' ) !== false ) {
63 $quoted = '"' . $quoted . '"';
65 return "$quoted <{$this->address}>";
67 return $this->address
;
71 function __toString() {
72 return $this->toString();
78 * Collection of static functions for sending mail
84 * Send mail using a PEAR mailer
86 protected static function sendWithPear( $mailer, $dest, $headers, $body ) {
87 $mailResult = $mailer->send( $dest, $headers, $body );
89 # Based on the result return an error string,
90 if ( PEAR
::isError( $mailResult ) ) {
91 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
92 return Status
::newFatal( 'pear-mail-error', $mailResult->getMessage() );
94 return Status
::newGood();
99 * This function will perform a direct (authenticated) login to
100 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
101 * array of parameters. It requires PEAR:Mail to do that.
102 * Otherwise it just uses the standard PHP 'mail' function.
104 * @param $to MailAddress: recipient's email (or an array of them)
105 * @param $from MailAddress: sender's email
106 * @param $subject String: email's subject.
107 * @param $body String: email's text.
108 * @param $replyto MailAddress: optional reply-to email (default: null).
109 * @param $contentType String: optional custom Content-Type
110 * @return Status object
112 public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = null ) {
113 global $wgSMTP, $wgOutputEncoding, $wgEnotifImpersonal;
114 global $wgEnotifMaxRecips, $wgAdditionalMailParams;
116 if ( is_array( $to ) ) {
118 // This wouldn't be necessary if implode() worked on arrays of
119 // objects using __toString(). http://bugs.php.net/bug.php?id=36612
120 foreach ( $to as $t ) {
121 $emails .= $t->toString() . ",";
123 $emails = rtrim( $emails, ',' );
124 wfDebug( __METHOD__
. ': sending mail to ' . $emails . "\n" );
126 wfDebug( __METHOD__
. ': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
129 if ( is_array( $wgSMTP ) ) {
130 if ( function_exists( 'stream_resolve_include_path' ) ) {
131 $found = stream_resolve_include_path( 'Mail.php' );
133 $found = Fallback
::stream_resolve_include_path( 'Mail.php' );
136 throw new MWException( 'PEAR mail package is not installed' );
138 require_once( 'Mail.php' );
140 $msgid = str_replace( " ", "_", microtime() );
141 if ( function_exists( 'posix_getpid' ) )
142 $msgid .= '.' . posix_getpid();
144 if ( is_array( $to ) ) {
146 foreach ( $to as $u )
147 $dest[] = $u->address
;
149 $dest = $to->address
;
151 $headers['From'] = $from->toString();
153 if ( $wgEnotifImpersonal ) {
154 $headers['To'] = 'undisclosed-recipients:;';
157 $headers['To'] = implode( ", ", (array )$dest );
161 $headers['Reply-To'] = $replyto->toString();
163 $headers['Subject'] = self
::quotedPrintable( $subject );
164 $headers['Date'] = date( 'r' );
165 $headers['MIME-Version'] = '1.0';
166 $headers['Content-type'] = ( is_null( $contentType ) ?
167 'text/plain; charset=' . $wgOutputEncoding : $contentType );
168 $headers['Content-transfer-encoding'] = '8bit';
169 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
170 $headers['X-Mailer'] = 'MediaWiki mailer';
172 wfSuppressWarnings();
174 // Create the mail object using the Mail::factory method
175 $mail_object =& Mail
::factory( 'smtp', $wgSMTP );
176 if ( PEAR
::isError( $mail_object ) ) {
177 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
179 return Status
::newFatal( 'pear-mail-error', $mail_object->getMessage() );
182 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
183 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
184 foreach ( $chunks as $chunk ) {
185 $status = self
::sendWithPear( $mail_object, $chunk, $headers, $body );
186 if ( !$status->isOK() ) {
192 return Status
::newGood();
194 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
195 # (fifth parameter of the PHP mail function, see some lines below)
197 # Line endings need to be different on Unix and Windows due to
198 # the bug described at http://trac.wordpress.org/ticket/2603
199 if ( wfIsWindows() ) {
200 $body = str_replace( "\n", "\r\n", $body );
205 $ctype = ( is_null( $contentType ) ?
206 'text/plain; charset=' . $wgOutputEncoding : $contentType );
208 "MIME-Version: 1.0$endl" .
209 "Content-type: $ctype$endl" .
210 "Content-Transfer-Encoding: 8bit$endl" .
211 "X-Mailer: MediaWiki mailer$endl" .
212 'From: ' . $from->toString();
214 $headers .= "{$endl}Reply-To: " . $replyto->toString();
217 wfDebug( "Sending mail via internal mail() function\n" );
219 self
::$mErrorString = '';
220 $html_errors = ini_get( 'html_errors' );
221 ini_set( 'html_errors', '0' );
222 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
224 // We need to check for safe_mode, because mail() throws an E_NOTICE
225 // on the 5th parameter when it's turned on
226 $sm = wfIniGetBool( 'safe_mode' );
228 if ( !is_array( $to ) ) {
231 foreach ( $to as $recip ) {
233 $sent = mail( $recip->toString(), self
::quotedPrintable( $subject ), $body, $headers );
235 $sent = mail( $recip->toString(), self
::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
239 restore_error_handler();
240 ini_set( 'html_errors', $html_errors );
242 if ( self
::$mErrorString ) {
243 wfDebug( "Error sending mail: " . self
::$mErrorString . "\n" );
244 return Status
::newFatal( 'php-mail-error', self
::$mErrorString );
245 } elseif ( ! $sent ) {
246 // mail function only tells if there's an error
247 wfDebug( "Error sending mail\n" );
248 return Status
::newFatal( 'php-mail-error-unknown' );
250 return Status
::newGood();
256 * Set the mail error message in self::$mErrorString
258 * @param $code Integer: error number
259 * @param $string String: error message
261 static function errorHandler( $code, $string ) {
262 self
::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
266 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
268 public static function rfc822Phrase( $phrase ) {
269 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
270 return '"' . $phrase . '"';
274 * Converts a string into quoted-printable format
277 public static function quotedPrintable( $string, $charset = '' ) {
278 # Probably incomplete; see RFC 2045
279 if( empty( $charset ) ) {
280 global $wgInputEncoding;
281 $charset = $wgInputEncoding;
283 $charset = strtoupper( $charset );
284 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
286 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
287 $replace = $illegal . '\t ?_';
288 if( !preg_match( "/[$illegal]/", $string ) ) {
291 $out = "=?$charset?Q?";
292 $out .= preg_replace_callback( "/([$replace])/",
293 array( __CLASS__
, 'quotedPrintableCallback' ), $string );
298 protected static function quotedPrintableCallback( $matches ) {
299 return sprintf( "=%02X", ord( $matches[1] ) );
304 * This module processes the email notifications when the current page is
305 * changed. It looks up the table watchlist to find out which users are watching
308 * The current implementation sends independent emails to each watching user for
309 * the following reason:
311 * - Each watching user will be notified about the page edit time expressed in
312 * his/her local time (UTC is shown additionally). To achieve this, we need to
313 * find the individual timeoffset of each watching user from the preferences..
315 * Suggested improvement to slack down the number of sent emails: We could think
316 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
317 * same timeoffset in their preferences.
319 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
323 class EmailNotification
{
324 protected $to, $subject, $body, $replyto, $from;
325 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
326 protected $mailTargets = array();
329 * Send emails corresponding to the user $editor editing the page $title.
330 * Also updates wl_notificationtimestamp.
332 * May be deferred via the job queue.
334 * @param $editor User object
335 * @param $title Title object
339 * @param $oldid (default: false)
341 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
342 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
344 if ( $title->getNamespace() < 0 )
347 // Build a list of users to notfiy
349 if ( $wgEnotifWatchlist ||
$wgShowUpdatedMarker ) {
350 $dbw = wfGetDB( DB_MASTER
);
351 $res = $dbw->select( array( 'watchlist' ),
354 'wl_title' => $title->getDBkey(),
355 'wl_namespace' => $title->getNamespace(),
356 'wl_user != ' . intval( $editor->getID() ),
357 'wl_notificationtimestamp IS NULL',
360 foreach ( $res as $row ) {
361 $watchers[] = intval( $row->wl_user
);
364 // Update wl_notificationtimestamp for all watching users except
367 $dbw->update( 'watchlist',
369 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
370 ), array( /* WHERE */
371 'wl_title' => $title->getDBkey(),
372 'wl_namespace' => $title->getNamespace(),
373 'wl_user' => $watchers
380 if ( $wgEnotifUseJobQ ) {
382 "editor" => $editor->getName(),
383 "editorID" => $editor->getID(),
384 "timestamp" => $timestamp,
385 "summary" => $summary,
386 "minorEdit" => $minorEdit,
388 "watchers" => $watchers );
389 $job = new EnotifNotifyJob( $title, $params );
392 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
398 * Immediate version of notifyOnPageChange().
400 * Send emails corresponding to the user $editor editing the page $title.
401 * Also updates wl_notificationtimestamp.
403 * @param $editor User object
404 * @param $title Title object
405 * @param $timestamp string Edit timestamp
406 * @param $summary string Edit summary
407 * @param $minorEdit bool
408 * @param $oldid int Revision ID
409 * @param $watchers array of user IDs
411 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
412 # we use $wgPasswordSender as sender's address
413 global $wgEnotifWatchlist;
414 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
416 wfProfileIn( __METHOD__
);
418 # The following code is only run, if several conditions are met:
419 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
420 # 2. minor edits (changes) are only regarded if the global flag indicates so
422 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
424 $this->title
= $title;
425 $this->timestamp
= $timestamp;
426 $this->summary
= $summary;
427 $this->minorEdit
= $minorEdit;
428 $this->oldid
= $oldid;
429 $this->editor
= $editor;
430 $this->composed_common
= false;
434 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
435 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
436 $targetUser = User
::newFromName( $title->getText() );
437 if ( !$targetUser ||
$targetUser->isAnon() ) {
438 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
439 } elseif ( $targetUser->getId() == $editor->getId() ) {
440 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
441 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) ) {
442 if ( $targetUser->isEmailConfirmed() ) {
443 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
444 $this->compose( $targetUser );
445 $userTalkId = $targetUser->getId();
447 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
450 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
454 if ( $wgEnotifWatchlist ) {
455 // Send updates to watchers other than the current editor
456 $userArray = UserArray
::newFromIDs( $watchers );
457 foreach ( $userArray as $watchingUser ) {
458 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
459 ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) ) &&
460 $watchingUser->isEmailConfirmed() &&
461 $watchingUser->getID() != $userTalkId )
463 $this->compose( $watchingUser );
469 global $wgUsersNotifiedOnAllChanges;
470 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
471 $user = User
::newFromName( $name );
472 $this->compose( $user );
476 wfProfileOut( __METHOD__
);
480 * Generate the generic "this page has been changed" e-mail text.
482 private function composeCommonMailtext() {
483 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
484 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
485 global $wgEnotifImpersonal, $wgEnotifUseRealName;
487 $this->composed_common
= true;
489 $summary = ( $this->summary
== '' ) ?
' - ' : $this->summary
;
490 $medit = ( $this->minorEdit
) ?
wfMsgForContent( 'minoredit' ) : '';
492 # You as the WikiAdmin and Sysops can make use of plenty of
493 # named variables when composing your notification emails while
494 # simply editing the Meta pages
496 $subject = wfMsgForContent( 'enotif_subject' );
497 $body = wfMsgForContent( 'enotif_body' );
498 $from = ''; /* fail safe */
499 $replyto = ''; /* fail safe */
502 if ( $this->oldid
) {
503 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
504 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
505 $keys['$OLDID'] = $this->oldid
;
506 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
508 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
509 # clear $OLDID placeholder in the message template
510 $keys['$OLDID'] = '';
511 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
514 if ( $wgEnotifImpersonal && $this->oldid
) {
516 * For impersonal mail, show a diff link to the last
519 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
520 $this->title
->getFullURL( "oldid={$this->oldid}&diff=next" ) );
523 $body = strtr( $body, $keys );
524 $pagetitle = $this->title
->getPrefixedText();
525 $keys['$PAGETITLE'] = $pagetitle;
526 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
528 $keys['$PAGEMINOREDIT'] = $medit;
529 $keys['$PAGESUMMARY'] = $summary;
530 $keys['$UNWATCHURL'] = $this->title
->getFullUrl( 'action=unwatch' );
532 $subject = strtr( $subject, $keys );
534 # Reveal the page editor's address as REPLY-TO address only if
535 # the user has not opted-out and the option is enabled at the
536 # global configuration level.
537 $editor = $this->editor
;
538 $name = $wgEnotifUseRealName ?
$editor->getRealName() : $editor->getName();
539 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
540 $editorAddress = new MailAddress( $editor );
541 if ( $wgEnotifRevealEditorAddress
542 && ( $editor->getEmail() != '' )
543 && $editor->getOption( 'enotifrevealaddr' ) ) {
544 if ( $wgEnotifFromEditor ) {
545 $from = $editorAddress;
547 $from = $adminAddress;
548 $replyto = $editorAddress;
551 $from = $adminAddress;
552 $replyto = new MailAddress( $wgNoReplyAddress );
555 if ( $editor->isIP( $name ) ) {
556 # real anon (user:xxx.xxx.xxx.xxx)
557 $utext = wfMsgForContent( 'enotif_anon_editor', $name );
558 $subject = str_replace( '$PAGEEDITOR', $utext, $subject );
559 $keys['$PAGEEDITOR'] = $utext;
560 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
562 $subject = str_replace( '$PAGEEDITOR', $name, $subject );
563 $keys['$PAGEEDITOR'] = $name;
564 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
565 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
567 $userPage = $editor->getUserPage();
568 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
569 $body = strtr( $body, $keys );
570 $body = wordwrap( $body, 72 );
572 # now save this as the constant user-independent part of the message
574 $this->replyto
= $replyto;
575 $this->subject
= $subject;
580 * Compose a mail to a given user and either queue it for sending, or send it now,
581 * depending on settings.
583 * Call sendMails() to send any mails that were queued.
585 function compose( $user ) {
586 global $wgEnotifImpersonal;
588 if ( !$this->composed_common
)
589 $this->composeCommonMailtext();
591 if ( $wgEnotifImpersonal ) {
592 $this->mailTargets
[] = new MailAddress( $user );
594 $this->sendPersonalised( $user );
599 * Send any queued mails
601 function sendMails() {
602 global $wgEnotifImpersonal;
603 if ( $wgEnotifImpersonal ) {
604 $this->sendImpersonal( $this->mailTargets
);
609 * Does the per-user customizations to a notification e-mail (name,
610 * timestamp in proper timezone, etc) and sends it out.
611 * Returns true if the mail was sent successfully.
613 * @param $watchingUser User object
617 function sendPersonalised( $watchingUser ) {
618 global $wgContLang, $wgEnotifUseRealName;
619 // From the PHP manual:
620 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
621 // The mail command will not parse this properly while talking with the MTA.
622 $to = new MailAddress( $watchingUser );
623 $name = $wgEnotifUseRealName ?
$watchingUser->getRealName() : $watchingUser->getName();
624 $body = str_replace( '$WATCHINGUSERNAME', $name, $this->body
);
626 $timecorrection = $watchingUser->getOption( 'timecorrection' );
628 # $PAGEEDITDATE is the time and date of the page change
629 # expressed in terms of individual local time of the notification
630 # recipient, i.e. watching user
632 array( '$PAGEEDITDATEANDTIME',
635 array( $wgContLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
636 $wgContLang->date( $this->timestamp
, true, false, $timecorrection ),
637 $wgContLang->time( $this->timestamp
, true, false, $timecorrection ) ),
640 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, $this->replyto
);
644 * Same as sendPersonalised but does impersonal mail suitable for bulk
645 * mailing. Takes an array of MailAddress objects.
647 function sendImpersonal( $addresses ) {
650 if ( empty( $addresses ) )
654 array( '$WATCHINGUSERNAME',
656 array( wfMsgForContent( 'enotif_impersonal_salutation' ),
657 $wgContLang->timeanddate( $this->timestamp
, true, false, false ) ),
660 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, $this->replyto
);
663 } # end of class EmailNotification
666 * Backwards compatibility functions
668 * @deprecated Use UserMailer method deprecated in 1.18, remove in 1.19.
670 function wfRFC822Phrase( $s ) {
671 wfDeprecated( __FUNCTION__
);
672 return UserMailer
::rfc822Phrase( $s );
676 * @deprecated Use UserMailer method deprecated in 1.18, remove in 1.19.
678 function userMailer( $to, $from, $subject, $body, $replyto = null ) {
679 wfDeprecated( __FUNCTION__
);
680 return UserMailer
::send( $to, $from, $subject, $body, $replyto );