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 ) ) {
117 // This wouldn't be necessary if implode() worked on arrays of
118 // objects using __toString(). http://bugs.php.net/bug.php?id=36612
119 foreach ( $to as $t ) {
120 $emails .= $t->toString() . ",";
122 $emails = rtrim( $emails, ',' );
123 wfDebug( __METHOD__
. ': sending mail to ' . $emails . "\n" );
125 wfDebug( __METHOD__
. ': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
128 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( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
299 * This module processes the email notifications when the current page is
300 * changed. It looks up the table watchlist to find out which users are watching
303 * The current implementation sends independent emails to each watching user for
304 * the following reason:
306 * - Each watching user will be notified about the page edit time expressed in
307 * his/her local time (UTC is shown additionally). To achieve this, we need to
308 * find the individual timeoffset of each watching user from the preferences..
310 * Suggested improvement to slack down the number of sent emails: We could think
311 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
312 * same timeoffset in their preferences.
314 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
318 class EmailNotification
{
319 protected $to, $subject, $body, $replyto, $from;
320 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
321 protected $mailTargets = array();
324 * Send emails corresponding to the user $editor editing the page $title.
325 * Also updates wl_notificationtimestamp.
327 * May be deferred via the job queue.
329 * @param $editor User object
330 * @param $title Title object
334 * @param $oldid (default: false)
336 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
337 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
339 if ( $title->getNamespace() < 0 )
342 // Build a list of users to notfiy
344 if ( $wgEnotifWatchlist ||
$wgShowUpdatedMarker ) {
345 $dbw = wfGetDB( DB_MASTER
);
346 $res = $dbw->select( array( 'watchlist' ),
349 'wl_title' => $title->getDBkey(),
350 'wl_namespace' => $title->getNamespace(),
351 'wl_user != ' . intval( $editor->getID() ),
352 'wl_notificationtimestamp IS NULL',
355 foreach ( $res as $row ) {
356 $watchers[] = intval( $row->wl_user
);
359 // Update wl_notificationtimestamp for all watching users except
362 $dbw->update( 'watchlist',
364 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
365 ), array( /* WHERE */
366 'wl_title' => $title->getDBkey(),
367 'wl_namespace' => $title->getNamespace(),
368 'wl_user' => $watchers
375 if ( $wgEnotifUseJobQ ) {
377 "editor" => $editor->getName(),
378 "editorID" => $editor->getID(),
379 "timestamp" => $timestamp,
380 "summary" => $summary,
381 "minorEdit" => $minorEdit,
383 "watchers" => $watchers );
384 $job = new EnotifNotifyJob( $title, $params );
387 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
393 * Immediate version of notifyOnPageChange().
395 * Send emails corresponding to the user $editor editing the page $title.
396 * Also updates wl_notificationtimestamp.
398 * @param $editor User object
399 * @param $title Title object
400 * @param $timestamp string Edit timestamp
401 * @param $summary string Edit summary
402 * @param $minorEdit bool
403 * @param $oldid int Revision ID
404 * @param $watchers array of user IDs
406 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
407 # we use $wgPasswordSender as sender's address
408 global $wgEnotifWatchlist;
409 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
411 wfProfileIn( __METHOD__
);
413 # The following code is only run, if several conditions are met:
414 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
415 # 2. minor edits (changes) are only regarded if the global flag indicates so
417 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
419 $this->title
= $title;
420 $this->timestamp
= $timestamp;
421 $this->summary
= $summary;
422 $this->minorEdit
= $minorEdit;
423 $this->oldid
= $oldid;
424 $this->editor
= $editor;
425 $this->composed_common
= false;
429 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
430 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
431 $targetUser = User
::newFromName( $title->getText() );
432 if ( !$targetUser ||
$targetUser->isAnon() ) {
433 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
434 } elseif ( $targetUser->getId() == $editor->getId() ) {
435 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
436 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) ) {
437 if ( $targetUser->isEmailConfirmed() ) {
438 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
439 $this->compose( $targetUser );
440 $userTalkId = $targetUser->getId();
442 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
445 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
449 if ( $wgEnotifWatchlist ) {
450 // Send updates to watchers other than the current editor
451 $userArray = UserArray
::newFromIDs( $watchers );
452 foreach ( $userArray as $watchingUser ) {
453 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
454 ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) ) &&
455 $watchingUser->isEmailConfirmed() &&
456 $watchingUser->getID() != $userTalkId )
458 $this->compose( $watchingUser );
464 global $wgUsersNotifiedOnAllChanges;
465 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
466 $user = User
::newFromName( $name );
467 $this->compose( $user );
471 wfProfileOut( __METHOD__
);
475 * Generate the generic "this page has been changed" e-mail text.
477 private function composeCommonMailtext() {
478 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
479 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
480 global $wgEnotifImpersonal, $wgEnotifUseRealName;
482 $this->composed_common
= true;
484 $summary = ( $this->summary
== '' ) ?
' - ' : $this->summary
;
485 $medit = ( $this->minorEdit
) ?
wfMsgForContent( 'minoredit' ) : '';
487 # You as the WikiAdmin and Sysops can make use of plenty of
488 # named variables when composing your notification emails while
489 # simply editing the Meta pages
491 $subject = wfMsgForContent( 'enotif_subject' );
492 $body = wfMsgForContent( 'enotif_body' );
493 $from = ''; /* fail safe */
494 $replyto = ''; /* fail safe */
497 if ( $this->oldid
) {
498 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
499 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
500 $keys['$OLDID'] = $this->oldid
;
501 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
503 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
504 # clear $OLDID placeholder in the message template
505 $keys['$OLDID'] = '';
506 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
509 if ( $wgEnotifImpersonal && $this->oldid
) {
511 * For impersonal mail, show a diff link to the last
514 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
515 $this->title
->getFullURL( "oldid={$this->oldid}&diff=next" ) );
518 $body = strtr( $body, $keys );
519 $pagetitle = $this->title
->getPrefixedText();
520 $keys['$PAGETITLE'] = $pagetitle;
521 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
523 $keys['$PAGEMINOREDIT'] = $medit;
524 $keys['$PAGESUMMARY'] = $summary;
525 $keys['$UNWATCHURL'] = $this->title
->getFullUrl( 'action=unwatch' );
527 $subject = strtr( $subject, $keys );
529 # Reveal the page editor's address as REPLY-TO address only if
530 # the user has not opted-out and the option is enabled at the
531 # global configuration level.
532 $editor = $this->editor
;
533 $name = $wgEnotifUseRealName ?
$editor->getRealName() : $editor->getName();
534 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
535 $editorAddress = new MailAddress( $editor );
536 if ( $wgEnotifRevealEditorAddress
537 && ( $editor->getEmail() != '' )
538 && $editor->getOption( 'enotifrevealaddr' ) ) {
539 if ( $wgEnotifFromEditor ) {
540 $from = $editorAddress;
542 $from = $adminAddress;
543 $replyto = $editorAddress;
546 $from = $adminAddress;
547 $replyto = new MailAddress( $wgNoReplyAddress );
550 if ( $editor->isIP( $name ) ) {
551 # real anon (user:xxx.xxx.xxx.xxx)
552 $utext = wfMsgForContent( 'enotif_anon_editor', $name );
553 $subject = str_replace( '$PAGEEDITOR', $utext, $subject );
554 $keys['$PAGEEDITOR'] = $utext;
555 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
557 $subject = str_replace( '$PAGEEDITOR', $name, $subject );
558 $keys['$PAGEEDITOR'] = $name;
559 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
560 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
562 $userPage = $editor->getUserPage();
563 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
564 $body = strtr( $body, $keys );
565 $body = wordwrap( $body, 72 );
567 # now save this as the constant user-independent part of the message
569 $this->replyto
= $replyto;
570 $this->subject
= $subject;
575 * Compose a mail to a given user and either queue it for sending, or send it now,
576 * depending on settings.
578 * Call sendMails() to send any mails that were queued.
580 function compose( $user ) {
581 global $wgEnotifImpersonal;
583 if ( !$this->composed_common
)
584 $this->composeCommonMailtext();
586 if ( $wgEnotifImpersonal ) {
587 $this->mailTargets
[] = new MailAddress( $user );
589 $this->sendPersonalised( $user );
594 * Send any queued mails
596 function sendMails() {
597 global $wgEnotifImpersonal;
598 if ( $wgEnotifImpersonal ) {
599 $this->sendImpersonal( $this->mailTargets
);
604 * Does the per-user customizations to a notification e-mail (name,
605 * timestamp in proper timezone, etc) and sends it out.
606 * Returns true if the mail was sent successfully.
608 * @param $watchingUser User object
612 function sendPersonalised( $watchingUser ) {
613 global $wgContLang, $wgEnotifUseRealName;
614 // From the PHP manual:
615 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
616 // The mail command will not parse this properly while talking with the MTA.
617 $to = new MailAddress( $watchingUser );
618 $name = $wgEnotifUseRealName ?
$watchingUser->getRealName() : $watchingUser->getName();
619 $body = str_replace( '$WATCHINGUSERNAME', $name, $this->body
);
621 $timecorrection = $watchingUser->getOption( 'timecorrection' );
623 # $PAGEEDITDATE is the time and date of the page change
624 # expressed in terms of individual local time of the notification
625 # recipient, i.e. watching user
627 array( '$PAGEEDITDATEANDTIME',
630 array( $wgContLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
631 $wgContLang->date( $this->timestamp
, true, false, $timecorrection ),
632 $wgContLang->time( $this->timestamp
, true, false, $timecorrection ) ),
635 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, $this->replyto
);
639 * Same as sendPersonalised but does impersonal mail suitable for bulk
640 * mailing. Takes an array of MailAddress objects.
642 function sendImpersonal( $addresses ) {
645 if ( empty( $addresses ) )
649 array( '$WATCHINGUSERNAME',
651 array( wfMsgForContent( 'enotif_impersonal_salutation' ),
652 $wgContLang->timeanddate( $this->timestamp
, true, false, false ) ),
655 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, $this->replyto
);
658 } # end of class EmailNotification
661 * Backwards compatibility functions
663 * @deprecated Use UserMailer method deprecated in 1.18, remove in 1.19.
665 function wfRFC822Phrase( $s ) {
666 wfDeprecated( __FUNCTION__
);
667 return UserMailer
::rfc822Phrase( $s );
671 * @deprecated Use UserMailer method deprecated in 1.18, remove in 1.19.
673 function userMailer( $to, $from, $subject, $body, $replyto = null ) {
674 wfDeprecated( __FUNCTION__
);
675 return UserMailer
::send( $to, $from, $subject, $body, $replyto );