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 ) ) {
131 if ( function_exists( 'stream_resolve_include_path' ) ) {
132 $found = stream_resolve_include_path( 'Mail.php' );
134 $found = Fallback
::stream_resolve_include_path( 'Mail.php' );
137 throw new MWException( 'PEAR mail package is not installed' );
139 require_once( 'Mail.php' );
141 $msgid = str_replace( " ", "_", microtime() );
142 if ( function_exists( 'posix_getpid' ) )
143 $msgid .= '.' . posix_getpid();
145 if ( is_array( $to ) ) {
147 foreach ( $to as $u )
148 $dest[] = $u->address
;
150 $dest = $to->address
;
152 $headers['From'] = $from->toString();
154 if ( $wgEnotifImpersonal ) {
155 $headers['To'] = 'undisclosed-recipients:;';
158 $headers['To'] = implode( ", ", (array )$dest );
162 $headers['Reply-To'] = $replyto->toString();
164 $headers['Subject'] = self
::quotedPrintable( $subject );
165 $headers['Date'] = date( 'r' );
166 $headers['MIME-Version'] = '1.0';
167 $headers['Content-type'] = ( is_null( $contentType ) ?
168 'text/plain; charset=' . $wgOutputEncoding : $contentType );
169 $headers['Content-transfer-encoding'] = '8bit';
170 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
171 $headers['X-Mailer'] = 'MediaWiki mailer';
173 wfSuppressWarnings();
175 // Create the mail object using the Mail::factory method
176 $mail_object =& Mail
::factory( 'smtp', $wgSMTP );
177 if ( PEAR
::isError( $mail_object ) ) {
178 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
180 return Status
::newFatal( 'pear-mail-error', $mail_object->getMessage() );
183 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
184 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
185 foreach ( $chunks as $chunk ) {
186 $status = self
::sendWithPear( $mail_object, $chunk, $headers, $body );
187 if ( !$status->isOK() ) {
193 return Status
::newGood();
195 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
196 # (fifth parameter of the PHP mail function, see some lines below)
198 # Line endings need to be different on Unix and Windows due to
199 # the bug described at http://trac.wordpress.org/ticket/2603
200 if ( wfIsWindows() ) {
201 $body = str_replace( "\n", "\r\n", $body );
206 $ctype = ( is_null( $contentType ) ?
207 'text/plain; charset=' . $wgOutputEncoding : $contentType );
209 "MIME-Version: 1.0$endl" .
210 "Content-type: $ctype$endl" .
211 "Content-Transfer-Encoding: 8bit$endl" .
212 "X-Mailer: MediaWiki mailer$endl" .
213 'From: ' . $from->toString();
215 $headers .= "{$endl}Reply-To: " . $replyto->toString();
218 wfDebug( "Sending mail via internal mail() function\n" );
220 self
::$mErrorString = '';
221 $html_errors = ini_get( 'html_errors' );
222 ini_set( 'html_errors', '0' );
223 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
225 // We need to check for safe_mode, because mail() throws an E_NOTICE
226 // on the 5th parameter when it's turned on
227 $sm = wfIniGetBool( 'safe_mode' );
229 if ( !is_array( $to ) ) {
232 foreach ( $to as $recip ) {
234 $sent = mail( $recip->toString(), self
::quotedPrintable( $subject ), $body, $headers );
236 $sent = mail( $recip->toString(), self
::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
240 restore_error_handler();
241 ini_set( 'html_errors', $html_errors );
243 if ( self
::$mErrorString ) {
244 wfDebug( "Error sending mail: " . self
::$mErrorString . "\n" );
245 return Status
::newFatal( 'php-mail-error', self
::$mErrorString );
246 } elseif ( ! $sent ) {
247 // mail function only tells if there's an error
248 wfDebug( "Error sending mail\n" );
249 return Status
::newFatal( 'php-mail-error-unknown' );
251 return Status
::newGood();
257 * Set the mail error message in self::$mErrorString
259 * @param $code Integer: error number
260 * @param $string String: error message
262 static function errorHandler( $code, $string ) {
263 self
::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
267 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
269 public static function rfc822Phrase( $phrase ) {
270 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
271 return '"' . $phrase . '"';
275 * Converts a string into quoted-printable format
278 public static function quotedPrintable( $string, $charset = '' ) {
279 # Probably incomplete; see RFC 2045
280 if( empty( $charset ) ) {
281 global $wgInputEncoding;
282 $charset = $wgInputEncoding;
284 $charset = strtoupper( $charset );
285 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
287 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
288 $replace = $illegal . '\t ?_';
289 if( !preg_match( "/[$illegal]/", $string ) ) {
292 $out = "=?$charset?Q?";
293 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
300 * This module processes the email notifications when the current page is
301 * changed. It looks up the table watchlist to find out which users are watching
304 * The current implementation sends independent emails to each watching user for
305 * the following reason:
307 * - Each watching user will be notified about the page edit time expressed in
308 * his/her local time (UTC is shown additionally). To achieve this, we need to
309 * find the individual timeoffset of each watching user from the preferences..
311 * Suggested improvement to slack down the number of sent emails: We could think
312 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
313 * same timeoffset in their preferences.
315 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
319 class EmailNotification
{
320 protected $to, $subject, $body, $replyto, $from;
321 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
322 protected $mailTargets = array();
325 * Send emails corresponding to the user $editor editing the page $title.
326 * Also updates wl_notificationtimestamp.
328 * May be deferred via the job queue.
330 * @param $editor User object
331 * @param $title Title object
335 * @param $oldid (default: false)
337 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
338 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
340 if ( $title->getNamespace() < 0 )
343 // Build a list of users to notfiy
345 if ( $wgEnotifWatchlist ||
$wgShowUpdatedMarker ) {
346 $dbw = wfGetDB( DB_MASTER
);
347 $res = $dbw->select( array( 'watchlist' ),
350 'wl_title' => $title->getDBkey(),
351 'wl_namespace' => $title->getNamespace(),
352 'wl_user != ' . intval( $editor->getID() ),
353 'wl_notificationtimestamp IS NULL',
356 foreach ( $res as $row ) {
357 $watchers[] = intval( $row->wl_user
);
360 // Update wl_notificationtimestamp for all watching users except
363 $dbw->update( 'watchlist',
365 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
366 ), array( /* WHERE */
367 'wl_title' => $title->getDBkey(),
368 'wl_namespace' => $title->getNamespace(),
369 'wl_user' => $watchers
376 if ( $wgEnotifUseJobQ ) {
378 "editor" => $editor->getName(),
379 "editorID" => $editor->getID(),
380 "timestamp" => $timestamp,
381 "summary" => $summary,
382 "minorEdit" => $minorEdit,
384 "watchers" => $watchers );
385 $job = new EnotifNotifyJob( $title, $params );
388 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
394 * Immediate version of notifyOnPageChange().
396 * Send emails corresponding to the user $editor editing the page $title.
397 * Also updates wl_notificationtimestamp.
399 * @param $editor User object
400 * @param $title Title object
401 * @param $timestamp string Edit timestamp
402 * @param $summary string Edit summary
403 * @param $minorEdit bool
404 * @param $oldid int Revision ID
405 * @param $watchers array of user IDs
407 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
408 # we use $wgPasswordSender as sender's address
409 global $wgEnotifWatchlist;
410 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
412 wfProfileIn( __METHOD__
);
414 # The following code is only run, if several conditions are met:
415 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
416 # 2. minor edits (changes) are only regarded if the global flag indicates so
418 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
420 $this->title
= $title;
421 $this->timestamp
= $timestamp;
422 $this->summary
= $summary;
423 $this->minorEdit
= $minorEdit;
424 $this->oldid
= $oldid;
425 $this->editor
= $editor;
426 $this->composed_common
= false;
430 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
431 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
432 $targetUser = User
::newFromName( $title->getText() );
433 if ( !$targetUser ||
$targetUser->isAnon() ) {
434 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
435 } elseif ( $targetUser->getId() == $editor->getId() ) {
436 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
437 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) ) {
438 if ( $targetUser->isEmailConfirmed() ) {
439 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
440 $this->compose( $targetUser );
441 $userTalkId = $targetUser->getId();
443 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
446 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
450 if ( $wgEnotifWatchlist ) {
451 // Send updates to watchers other than the current editor
452 $userArray = UserArray
::newFromIDs( $watchers );
453 foreach ( $userArray as $watchingUser ) {
454 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
455 ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) ) &&
456 $watchingUser->isEmailConfirmed() &&
457 $watchingUser->getID() != $userTalkId )
459 $this->compose( $watchingUser );
465 global $wgUsersNotifiedOnAllChanges;
466 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
467 $user = User
::newFromName( $name );
468 $this->compose( $user );
472 wfProfileOut( __METHOD__
);
476 * Generate the generic "this page has been changed" e-mail text.
478 private function composeCommonMailtext() {
479 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
480 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
481 global $wgEnotifImpersonal, $wgEnotifUseRealName;
483 $this->composed_common
= true;
485 $summary = ( $this->summary
== '' ) ?
' - ' : $this->summary
;
486 $medit = ( $this->minorEdit
) ?
wfMsgForContent( 'minoredit' ) : '';
488 # You as the WikiAdmin and Sysops can make use of plenty of
489 # named variables when composing your notification emails while
490 # simply editing the Meta pages
492 $subject = wfMsgForContent( 'enotif_subject' );
493 $body = wfMsgForContent( 'enotif_body' );
494 $from = ''; /* fail safe */
495 $replyto = ''; /* fail safe */
498 if ( $this->oldid
) {
499 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
500 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
501 $keys['$OLDID'] = $this->oldid
;
502 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
504 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
505 # clear $OLDID placeholder in the message template
506 $keys['$OLDID'] = '';
507 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
510 if ( $wgEnotifImpersonal && $this->oldid
) {
512 * For impersonal mail, show a diff link to the last
515 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
516 $this->title
->getFullURL( "oldid={$this->oldid}&diff=next" ) );
519 $body = strtr( $body, $keys );
520 $pagetitle = $this->title
->getPrefixedText();
521 $keys['$PAGETITLE'] = $pagetitle;
522 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
524 $keys['$PAGEMINOREDIT'] = $medit;
525 $keys['$PAGESUMMARY'] = $summary;
526 $keys['$UNWATCHURL'] = $this->title
->getFullUrl( 'action=unwatch' );
528 $subject = strtr( $subject, $keys );
530 # Reveal the page editor's address as REPLY-TO address only if
531 # the user has not opted-out and the option is enabled at the
532 # global configuration level.
533 $editor = $this->editor
;
534 $name = $wgEnotifUseRealName ?
$editor->getRealName() : $editor->getName();
535 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
536 $editorAddress = new MailAddress( $editor );
537 if ( $wgEnotifRevealEditorAddress
538 && ( $editor->getEmail() != '' )
539 && $editor->getOption( 'enotifrevealaddr' ) ) {
540 if ( $wgEnotifFromEditor ) {
541 $from = $editorAddress;
543 $from = $adminAddress;
544 $replyto = $editorAddress;
547 $from = $adminAddress;
548 $replyto = new MailAddress( $wgNoReplyAddress );
551 if ( $editor->isIP( $name ) ) {
552 # real anon (user:xxx.xxx.xxx.xxx)
553 $utext = wfMsgForContent( 'enotif_anon_editor', $name );
554 $subject = str_replace( '$PAGEEDITOR', $utext, $subject );
555 $keys['$PAGEEDITOR'] = $utext;
556 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
558 $subject = str_replace( '$PAGEEDITOR', $name, $subject );
559 $keys['$PAGEEDITOR'] = $name;
560 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
561 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
563 $userPage = $editor->getUserPage();
564 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
565 $body = strtr( $body, $keys );
566 $body = wordwrap( $body, 72 );
568 # now save this as the constant user-independent part of the message
570 $this->replyto
= $replyto;
571 $this->subject
= $subject;
576 * Compose a mail to a given user and either queue it for sending, or send it now,
577 * depending on settings.
579 * Call sendMails() to send any mails that were queued.
581 function compose( $user ) {
582 global $wgEnotifImpersonal;
584 if ( !$this->composed_common
)
585 $this->composeCommonMailtext();
587 if ( $wgEnotifImpersonal ) {
588 $this->mailTargets
[] = new MailAddress( $user );
590 $this->sendPersonalised( $user );
595 * Send any queued mails
597 function sendMails() {
598 global $wgEnotifImpersonal;
599 if ( $wgEnotifImpersonal ) {
600 $this->sendImpersonal( $this->mailTargets
);
605 * Does the per-user customizations to a notification e-mail (name,
606 * timestamp in proper timezone, etc) and sends it out.
607 * Returns true if the mail was sent successfully.
609 * @param $watchingUser User object
613 function sendPersonalised( $watchingUser ) {
614 global $wgContLang, $wgEnotifUseRealName;
615 // From the PHP manual:
616 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
617 // The mail command will not parse this properly while talking with the MTA.
618 $to = new MailAddress( $watchingUser );
619 $name = $wgEnotifUseRealName ?
$watchingUser->getRealName() : $watchingUser->getName();
620 $body = str_replace( '$WATCHINGUSERNAME', $name, $this->body
);
622 $timecorrection = $watchingUser->getOption( 'timecorrection' );
624 # $PAGEEDITDATE is the time and date of the page change
625 # expressed in terms of individual local time of the notification
626 # recipient, i.e. watching user
628 array( '$PAGEEDITDATEANDTIME',
631 array( $wgContLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
632 $wgContLang->date( $this->timestamp
, true, false, $timecorrection ),
633 $wgContLang->time( $this->timestamp
, true, false, $timecorrection ) ),
636 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, $this->replyto
);
640 * Same as sendPersonalised but does impersonal mail suitable for bulk
641 * mailing. Takes an array of MailAddress objects.
643 function sendImpersonal( $addresses ) {
646 if ( empty( $addresses ) )
650 array( '$WATCHINGUSERNAME',
652 array( wfMsgForContent( 'enotif_impersonal_salutation' ),
653 $wgContLang->timeanddate( $this->timestamp
, true, false, false ) ),
656 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, $this->replyto
);
659 } # end of class EmailNotification
662 * Backwards compatibility functions
664 * @deprecated Use UserMailer method deprecated in 1.18, remove in 1.19.
666 function wfRFC822Phrase( $s ) {
667 wfDeprecated( __FUNCTION__
);
668 return UserMailer
::rfc822Phrase( $s );
672 * @deprecated Use UserMailer method deprecated in 1.18, remove in 1.19.
674 function userMailer( $to, $from, $subject, $body, $replyto = null ) {
675 wfDeprecated( __FUNCTION__
);
676 return UserMailer
::send( $to, $from, $subject, $body, $replyto );