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 $pathArray = explode( PATH_SEPARATOR
, get_include_path() );
131 foreach ( $pathArray as $path ) {
132 if ( file_exists( $path . DIRECTORY_SEPARATOR
. 'Mail.php' ) ) {
138 throw new MWException( 'PEAR mail package is not installed' );
140 require_once( 'Mail.php' );
142 $msgid = str_replace( " ", "_", microtime() );
143 if ( function_exists( 'posix_getpid' ) )
144 $msgid .= '.' . posix_getpid();
146 if ( is_array( $to ) ) {
148 foreach ( $to as $u )
149 $dest[] = $u->address
;
151 $dest = $to->address
;
153 $headers['From'] = $from->toString();
155 if ( $wgEnotifImpersonal ) {
156 $headers['To'] = 'undisclosed-recipients:;';
159 $headers['To'] = implode( ", ", (array )$dest );
163 $headers['Reply-To'] = $replyto->toString();
165 $headers['Subject'] = self
::quotedPrintable( $subject );
166 $headers['Date'] = date( 'r' );
167 $headers['MIME-Version'] = '1.0';
168 $headers['Content-type'] = ( is_null( $contentType ) ?
169 'text/plain; charset=' . $wgOutputEncoding : $contentType );
170 $headers['Content-transfer-encoding'] = '8bit';
171 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
172 $headers['X-Mailer'] = 'MediaWiki mailer';
174 wfSuppressWarnings();
176 // Create the mail object using the Mail::factory method
177 $mail_object =& Mail
::factory( 'smtp', $wgSMTP );
178 if ( PEAR
::isError( $mail_object ) ) {
179 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
181 return Status
::newFatal( 'pear-mail-error', $mail_object->getMessage() );
184 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
185 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
186 foreach ( $chunks as $chunk ) {
187 $status = self
::sendWithPear( $mail_object, $chunk, $headers, $body );
188 if ( !$status->isOK() ) {
194 return Status
::newGood();
196 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
197 # (fifth parameter of the PHP mail function, see some lines below)
199 # Line endings need to be different on Unix and Windows due to
200 # the bug described at http://trac.wordpress.org/ticket/2603
201 if ( wfIsWindows() ) {
202 $body = str_replace( "\n", "\r\n", $body );
207 $ctype = ( is_null( $contentType ) ?
208 'text/plain; charset=' . $wgOutputEncoding : $contentType );
210 "MIME-Version: 1.0$endl" .
211 "Content-type: $ctype$endl" .
212 "Content-Transfer-Encoding: 8bit$endl" .
213 "X-Mailer: MediaWiki mailer$endl" .
214 'From: ' . $from->toString();
216 $headers .= "{$endl}Reply-To: " . $replyto->toString();
219 wfDebug( "Sending mail via internal mail() function\n" );
221 self
::$mErrorString = '';
222 $html_errors = ini_get( 'html_errors' );
223 ini_set( 'html_errors', '0' );
224 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
226 // We need to check for safe_mode, because mail() throws an E_NOTICE
227 // on the 5th parameter when it's turned on
228 $sm = wfIniGetBool( 'safe_mode' );
230 if ( !is_array( $to ) ) {
233 foreach ( $to as $recip ) {
235 $sent = mail( $recip->toString(), self
::quotedPrintable( $subject ), $body, $headers );
237 $sent = mail( $recip->toString(), self
::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
241 restore_error_handler();
242 ini_set( 'html_errors', $html_errors );
244 if ( self
::$mErrorString ) {
245 wfDebug( "Error sending mail: " . self
::$mErrorString . "\n" );
246 return Status
::newFatal( 'php-mail-error', self
::$mErrorString );
247 } elseif ( ! $sent ) {
248 // mail function only tells if there's an error
249 wfDebug( "Error sending mail\n" );
250 return Status
::newFatal( 'php-mail-error-unknown' );
252 return Status
::newGood();
258 * Set the mail error message in self::$mErrorString
260 * @param $code Integer: error number
261 * @param $string String: error message
263 static function errorHandler( $code, $string ) {
264 self
::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
268 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
270 public static function rfc822Phrase( $phrase ) {
271 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
272 return '"' . $phrase . '"';
276 * Converts a string into quoted-printable format
279 public static function quotedPrintable( $string, $charset = '' ) {
280 # Probably incomplete; see RFC 2045
281 if( empty( $charset ) ) {
282 global $wgInputEncoding;
283 $charset = $wgInputEncoding;
285 $charset = strtoupper( $charset );
286 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
288 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
289 $replace = $illegal . '\t ?_';
290 if( !preg_match( "/[$illegal]/", $string ) ) {
293 $out = "=?$charset?Q?";
294 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
301 * This module processes the email notifications when the current page is
302 * changed. It looks up the table watchlist to find out which users are watching
305 * The current implementation sends independent emails to each watching user for
306 * the following reason:
308 * - Each watching user will be notified about the page edit time expressed in
309 * his/her local time (UTC is shown additionally). To achieve this, we need to
310 * find the individual timeoffset of each watching user from the preferences..
312 * Suggested improvement to slack down the number of sent emails: We could think
313 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
314 * same timeoffset in their preferences.
316 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
320 class EmailNotification
{
321 protected $to, $subject, $body, $replyto, $from;
322 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
323 protected $mailTargets = array();
326 * Send emails corresponding to the user $editor editing the page $title.
327 * Also updates wl_notificationtimestamp.
329 * May be deferred via the job queue.
331 * @param $editor User object
332 * @param $title Title object
336 * @param $oldid (default: false)
338 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
339 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
341 if ( $title->getNamespace() < 0 )
344 // Build a list of users to notfiy
346 if ( $wgEnotifWatchlist ||
$wgShowUpdatedMarker ) {
347 $dbw = wfGetDB( DB_MASTER
);
348 $res = $dbw->select( array( 'watchlist' ),
351 'wl_title' => $title->getDBkey(),
352 'wl_namespace' => $title->getNamespace(),
353 'wl_user != ' . intval( $editor->getID() ),
354 'wl_notificationtimestamp IS NULL',
357 foreach ( $res as $row ) {
358 $watchers[] = intval( $row->wl_user
);
361 // Update wl_notificationtimestamp for all watching users except
364 $dbw->update( 'watchlist',
366 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
367 ), array( /* WHERE */
368 'wl_title' => $title->getDBkey(),
369 'wl_namespace' => $title->getNamespace(),
370 'wl_user' => $watchers
377 if ( $wgEnotifUseJobQ ) {
379 "editor" => $editor->getName(),
380 "editorID" => $editor->getID(),
381 "timestamp" => $timestamp,
382 "summary" => $summary,
383 "minorEdit" => $minorEdit,
385 "watchers" => $watchers );
386 $job = new EnotifNotifyJob( $title, $params );
389 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
395 * Immediate version of notifyOnPageChange().
397 * Send emails corresponding to the user $editor editing the page $title.
398 * Also updates wl_notificationtimestamp.
400 * @param $editor User object
401 * @param $title Title object
402 * @param $timestamp string Edit timestamp
403 * @param $summary string Edit summary
404 * @param $minorEdit bool
405 * @param $oldid int Revision ID
406 * @param $watchers array of user IDs
408 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
409 # we use $wgPasswordSender as sender's address
410 global $wgEnotifWatchlist;
411 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
413 wfProfileIn( __METHOD__
);
415 # The following code is only run, if several conditions are met:
416 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
417 # 2. minor edits (changes) are only regarded if the global flag indicates so
419 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
421 $this->title
= $title;
422 $this->timestamp
= $timestamp;
423 $this->summary
= $summary;
424 $this->minorEdit
= $minorEdit;
425 $this->oldid
= $oldid;
426 $this->editor
= $editor;
427 $this->composed_common
= false;
431 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
432 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
433 $targetUser = User
::newFromName( $title->getText() );
434 if ( !$targetUser ||
$targetUser->isAnon() ) {
435 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
436 } elseif ( $targetUser->getId() == $editor->getId() ) {
437 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
438 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) ) {
439 if ( $targetUser->isEmailConfirmed() ) {
440 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
441 $this->compose( $targetUser );
442 $userTalkId = $targetUser->getId();
444 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
447 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
451 if ( $wgEnotifWatchlist ) {
452 // Send updates to watchers other than the current editor
453 $userArray = UserArray
::newFromIDs( $watchers );
454 foreach ( $userArray as $watchingUser ) {
455 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
456 ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) ) &&
457 $watchingUser->isEmailConfirmed() &&
458 $watchingUser->getID() != $userTalkId )
460 $this->compose( $watchingUser );
466 global $wgUsersNotifiedOnAllChanges;
467 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
468 $user = User
::newFromName( $name );
469 $this->compose( $user );
473 wfProfileOut( __METHOD__
);
477 * Generate the generic "this page has been changed" e-mail text.
479 private function composeCommonMailtext() {
480 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
481 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
482 global $wgEnotifImpersonal, $wgEnotifUseRealName;
484 $this->composed_common
= true;
486 $summary = ( $this->summary
== '' ) ?
' - ' : $this->summary
;
487 $medit = ( $this->minorEdit
) ?
wfMsgForContent( 'minoredit' ) : '';
489 # You as the WikiAdmin and Sysops can make use of plenty of
490 # named variables when composing your notification emails while
491 # simply editing the Meta pages
493 $subject = wfMsgForContent( 'enotif_subject' );
494 $body = wfMsgForContent( 'enotif_body' );
495 $from = ''; /* fail safe */
496 $replyto = ''; /* fail safe */
499 if ( $this->oldid
) {
500 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
501 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
502 $keys['$OLDID'] = $this->oldid
;
503 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
505 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
506 # clear $OLDID placeholder in the message template
507 $keys['$OLDID'] = '';
508 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
511 if ( $wgEnotifImpersonal && $this->oldid
) {
513 * For impersonal mail, show a diff link to the last
516 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
517 $this->title
->getFullURL( "oldid={$this->oldid}&diff=next" ) );
520 $body = strtr( $body, $keys );
521 $pagetitle = $this->title
->getPrefixedText();
522 $keys['$PAGETITLE'] = $pagetitle;
523 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
525 $keys['$PAGEMINOREDIT'] = $medit;
526 $keys['$PAGESUMMARY'] = $summary;
527 $keys['$UNWATCHURL'] = $this->title
->getFullUrl( 'action=unwatch' );
529 $subject = strtr( $subject, $keys );
531 # Reveal the page editor's address as REPLY-TO address only if
532 # the user has not opted-out and the option is enabled at the
533 # global configuration level.
534 $editor = $this->editor
;
535 $name = $wgEnotifUseRealName ?
$editor->getRealName() : $editor->getName();
536 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
537 $editorAddress = new MailAddress( $editor );
538 if ( $wgEnotifRevealEditorAddress
539 && ( $editor->getEmail() != '' )
540 && $editor->getOption( 'enotifrevealaddr' ) ) {
541 if ( $wgEnotifFromEditor ) {
542 $from = $editorAddress;
544 $from = $adminAddress;
545 $replyto = $editorAddress;
548 $from = $adminAddress;
549 $replyto = new MailAddress( $wgNoReplyAddress );
552 if ( $editor->isIP( $name ) ) {
553 # real anon (user:xxx.xxx.xxx.xxx)
554 $utext = wfMsgForContent( 'enotif_anon_editor', $name );
555 $subject = str_replace( '$PAGEEDITOR', $utext, $subject );
556 $keys['$PAGEEDITOR'] = $utext;
557 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
559 $subject = str_replace( '$PAGEEDITOR', $name, $subject );
560 $keys['$PAGEEDITOR'] = $name;
561 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
562 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
564 $userPage = $editor->getUserPage();
565 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
566 $body = strtr( $body, $keys );
567 $body = wordwrap( $body, 72 );
569 # now save this as the constant user-independent part of the message
571 $this->replyto
= $replyto;
572 $this->subject
= $subject;
577 * Compose a mail to a given user and either queue it for sending, or send it now,
578 * depending on settings.
580 * Call sendMails() to send any mails that were queued.
582 function compose( $user ) {
583 global $wgEnotifImpersonal;
585 if ( !$this->composed_common
)
586 $this->composeCommonMailtext();
588 if ( $wgEnotifImpersonal ) {
589 $this->mailTargets
[] = new MailAddress( $user );
591 $this->sendPersonalised( $user );
596 * Send any queued mails
598 function sendMails() {
599 global $wgEnotifImpersonal;
600 if ( $wgEnotifImpersonal ) {
601 $this->sendImpersonal( $this->mailTargets
);
606 * Does the per-user customizations to a notification e-mail (name,
607 * timestamp in proper timezone, etc) and sends it out.
608 * Returns true if the mail was sent successfully.
610 * @param $watchingUser User object
614 function sendPersonalised( $watchingUser ) {
615 global $wgContLang, $wgEnotifUseRealName;
616 // From the PHP manual:
617 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
618 // The mail command will not parse this properly while talking with the MTA.
619 $to = new MailAddress( $watchingUser );
620 $name = $wgEnotifUseRealName ?
$watchingUser->getRealName() : $watchingUser->getName();
621 $body = str_replace( '$WATCHINGUSERNAME', $name, $this->body
);
623 $timecorrection = $watchingUser->getOption( 'timecorrection' );
625 # $PAGEEDITDATE is the time and date of the page change
626 # expressed in terms of individual local time of the notification
627 # recipient, i.e. watching user
629 array( '$PAGEEDITDATEANDTIME',
632 array( $wgContLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
633 $wgContLang->date( $this->timestamp
, true, false, $timecorrection ),
634 $wgContLang->time( $this->timestamp
, true, false, $timecorrection ) ),
637 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, $this->replyto
);
641 * Same as sendPersonalised but does impersonal mail suitable for bulk
642 * mailing. Takes an array of MailAddress objects.
644 function sendImpersonal( $addresses ) {
647 if ( empty( $addresses ) )
651 array( '$WATCHINGUSERNAME',
653 array( wfMsgForContent( 'enotif_impersonal_salutation' ),
654 $wgContLang->timeanddate( $this->timestamp
, true, false, false ) ),
657 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, $this->replyto
);
660 } # end of class EmailNotification
663 * Backwards compatibility functions
665 * @deprecated Use UserMailer method deprecated in 1.18, remove in 1.19.
667 function wfRFC822Phrase( $s ) {
668 wfDeprecated( __FUNCTION__
);
669 return UserMailer
::rfc822Phrase( $s );
673 * @deprecated Use UserMailer method deprecated in 1.18, remove in 1.19.
675 function userMailer( $to, $from, $subject, $body, $replyto = null ) {
676 wfDeprecated( __FUNCTION__
);
677 return UserMailer
::send( $to, $from, $subject, $body, $replyto );