4 * Copyright (C) 2004 Thomas Gries <mail@tgries.de>
5 * http://www.mediawiki.org/
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
22 * @author <brion@pobox.com>
23 * @author <mail@tgries.de>
28 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
30 function wfRFC822Phrase( $phrase ) {
31 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
32 return '"' . $phrase . '"';
36 * Stores a single person's name and email address.
37 * These are passed in via the constructor, and will be returned in SMTP
38 * header format when requested.
42 * @param mixed $address String with an email address, or a User object
43 * @param string $name Human-readable name if a string address is given
45 function __construct( $address, $name=null ) {
46 if( is_object( $address ) && $address instanceof User
) {
47 $this->address
= $address->getEmail();
48 $this->name
= $address->getName();
50 $this->address
= strval( $address );
51 $this->name
= strval( $name );
56 * Return formatted and quoted address to insert into SMTP headers
60 # PHP's mail() implementation under Windows is somewhat shite, and
61 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
62 # so don't bother generating them
63 if( $this->name
!= '' && !wfIsWindows() ) {
64 $quoted = wfQuotedPrintable( $this->name
);
65 if( strpos( $quoted, '.' ) !== false ) {
66 $quoted = '"' . $quoted . '"';
68 return "$quoted <{$this->address}>";
70 return $this->address
;
76 * This function will perform a direct (authenticated) login to
77 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
78 * array of parameters. It requires PEAR:Mail to do that.
79 * Otherwise it just uses the standard PHP 'mail' function.
81 * @param $to MailAddress: recipient's email
82 * @param $from MailAddress: sender's email
83 * @param $subject String: email's subject.
84 * @param $body String: email's text.
85 * @param $replyto String: optional reply-to email (default: null).
87 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
88 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString;
90 if (is_array( $wgSMTP )) {
91 require_once( 'Mail.php' );
96 $headers['From'] = $from->toString();
97 $headers['To'] = $to->toString();
99 $headers['Reply-To'] = $replyto->toString();
101 $headers['Subject'] = wfQuotedPrintable( $subject );
102 $headers['Date'] = date( 'r' );
103 $headers['MIME-Version'] = '1.0';
104 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
105 $headers['Content-transfer-encoding'] = '8bit';
106 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>'; // FIXME
107 $headers['X-Mailer'] = 'MediaWiki mailer';
109 // Create the mail object using the Mail::factory method
110 $mail_object =& Mail
::factory('smtp', $wgSMTP);
111 if( PEAR
::isError( $mail_object ) ) {
112 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
113 return $mail_object->getMessage();
116 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
117 $mailResult =& $mail_object->send($dest, $headers, $body);
119 # Based on the result return an error string,
120 if ($mailResult === true) {
122 } elseif (is_object($mailResult)) {
123 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
124 return $mailResult->getMessage();
126 wfDebug( "PEAR::Mail failed, unknown error result\n" );
127 return 'Mail object return unknown error.';
130 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
131 # (fifth parameter of the PHP mail function, see some lines below)
133 # Line endings need to be different on Unix and Windows due to
134 # the bug described at http://trac.wordpress.org/ticket/2603
135 if ( wfIsWindows() ) {
136 $body = str_replace( "\n", "\r\n", $body );
142 "MIME-Version: 1.0$endl" .
143 "Content-type: text/plain; charset={$wgOutputEncoding}$endl" .
144 "Content-Transfer-Encoding: 8bit$endl" .
145 "X-Mailer: MediaWiki mailer$endl".
146 'From: ' . $from->toString();
148 $headers .= "{$endl}Reply-To: " . $replyto->toString();
151 $dest = $to->toString();
154 set_error_handler( 'mailErrorHandler' );
155 wfDebug( "Sending mail via internal mail() function to $dest\n" );
156 mail( $dest, wfQuotedPrintable( $subject ), $body, $headers );
157 restore_error_handler();
159 if ( $wgErrorString ) {
160 wfDebug( "Error sending mail: $wgErrorString\n" );
162 return $wgErrorString;
167 * Get the mail error message in global $wgErrorString
169 * @param $code Integer: error number
170 * @param $string String: error message
172 function mailErrorHandler( $code, $string ) {
173 global $wgErrorString;
174 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
179 * This module processes the email notifications when the current page is
180 * changed. It looks up the table watchlist to find out which users are watching
183 * The current implementation sends independent emails to each watching user for
184 * the following reason:
186 * - Each watching user will be notified about the page edit time expressed in
187 * his/her local time (UTC is shown additionally). To achieve this, we need to
188 * find the individual timeoffset of each watching user from the preferences..
190 * Suggested improvement to slack down the number of sent emails: We could think
191 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
192 * same timeoffset in their preferences.
194 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
198 class EmailNotification
{
200 * @private member variables:
202 var $to, $subject, $body, $replyto, $from;
203 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
207 * @param $title Title object
211 * @param $oldid (default: false)
213 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
215 # we use $wgEmergencyContact as sender's address
216 global $wgUser, $wgEnotifWatchlist;
217 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
219 $fname = 'UserMailer::notifyOnPageChange';
220 wfProfileIn( $fname );
222 # The following code is only run, if several conditions are met:
223 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
224 # 2. minor edits (changes) are only regarded if the global flag indicates so
226 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK
);
227 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
228 $enotifwatchlistpage = $wgEnotifWatchlist;
230 if ( (!$minorEdit ||
$wgEnotifMinorEdits) ) {
231 if( $wgEnotifWatchlist ) {
232 // Send updates to watchers other than the current editor
233 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
234 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK
) {
235 $targetUser = User
::newFromName( $title->getText() );
236 if( is_null( $targetUser ) ) {
237 wfDebug( "$fname: user-talk-only mode; no such user\n" );
238 $userCondition = false;
239 } elseif( $targetUser->getId() == $wgUser->getId() ) {
240 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
241 $userCondition = false;
243 // Don't notify anyone other than the owner of the talk page
244 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
247 // Notifications disabled
248 $userCondition = false;
250 if( $userCondition ) {
251 $dbr = wfGetDB( DB_MASTER
);
253 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
255 'wl_title' => $title->getDBkey(),
256 'wl_namespace' => $title->getNamespace(),
258 'wl_notificationtimestamp IS NULL',
261 # if anyone is watching ... set up the email message text which is
262 # common for all receipients ...
263 if ( $dbr->numRows( $res ) > 0 ) {
264 $this->title
=& $title;
265 $this->timestamp
= $timestamp;
266 $this->summary
= $summary;
267 $this->minorEdit
= $minorEdit;
268 $this->oldid
= $oldid;
270 $this->composeCommonMailtext();
271 $watchingUser = new User();
273 # ... now do for all watching users ... if the options fit
274 for ($i = 1; $i <= $dbr->numRows( $res ); $i++
) {
276 $wuser = $dbr->fetchObject( $res );
277 $watchingUser->setID($wuser->wl_user
);
279 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
280 ( $enotifusertalkpage
281 && $watchingUser->getOption('enotifusertalkpages')
282 && $title->equals( $watchingUser->getTalkPage() ) )
283 && (!$minorEdit ||
($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
284 && ($watchingUser->isEmailConfirmed() ) ) {
285 # ... adjust remaining text and page edit time placeholders
286 # which needs to be personalized for each user
287 $this->composeAndSendPersonalisedMail( $watchingUser );
289 } # if the watching user has an email address in the preferences
292 } # if anyone is watching
293 } # if $wgEnotifWatchlist = true
295 if ( $wgShowUpdatedMarker ||
$wgEnotifWatchlist ) {
296 # mark the changed watch-listed page with a timestamp, so that the page is
297 # listed with an "updated since your last visit" icon in the watch list, ...
298 $dbw = wfGetDB( DB_MASTER
);
299 $success = $dbw->update( 'watchlist',
301 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
302 ), array( /* WHERE */
303 'wl_title' => $title->getDBkey(),
304 'wl_namespace' => $title->getNamespace(),
305 ), 'UserMailer::NotifyOnChange'
307 # FIXME what do we do on failure ?
309 wfProfileOut( $fname );
310 } # function NotifyOnChange
315 function composeCommonMailtext() {
316 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
317 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
319 $summary = ($this->summary
== '') ?
' - ' : $this->summary
;
320 $medit = ($this->minorEdit
) ?
wfMsg( 'minoredit' ) : '';
322 # You as the WikiAdmin and Sysops can make use of plenty of
323 # named variables when composing your notification emails while
324 # simply editing the Meta pages
326 $subject = wfMsgForContent( 'enotif_subject' );
327 $body = wfMsgForContent( 'enotif_body' );
328 $from = ''; /* fail safe */
329 $replyto = ''; /* fail safe */
332 # regarding the use of oldid as an indicator for the last visited version, see also
333 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
334 # However, in the case of a new page which is already watched, we have no previous version to compare
336 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
337 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
338 $keys['$OLDID'] = $this->oldid
;
339 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
341 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
342 # clear $OLDID placeholder in the message template
343 $keys['$OLDID'] = '';
344 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
347 $body = strtr( $body, $keys );
348 $pagetitle = $this->title
->getPrefixedText();
349 $keys['$PAGETITLE'] = $pagetitle;
350 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
352 $keys['$PAGEMINOREDIT'] = $medit;
353 $keys['$PAGESUMMARY'] = $summary;
355 $subject = strtr( $subject, $keys );
357 # Reveal the page editor's address as REPLY-TO address only if
358 # the user has not opted-out and the option is enabled at the
359 # global configuration level.
360 $name = $wgUser->getName();
361 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
362 $editorAddress = new MailAddress( $wgUser );
363 if( $wgEnotifRevealEditorAddress
364 && ( $wgUser->getEmail() != '' )
365 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
366 if( $wgEnotifFromEditor ) {
367 $from = $editorAddress;
369 $from = $adminAddress;
370 $replyto = $editorAddress;
373 $from = $adminAddress;
374 $replyto = new MailAddress( $wgNoReplyAddress );
377 if( $wgUser->isIP( $name ) ) {
378 #real anon (user:xxx.xxx.xxx.xxx)
379 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
380 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
381 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
383 $subject = str_replace('$PAGEEDITOR', $name, $subject);
384 $keys['$PAGEEDITOR'] = $name;
385 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
386 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
388 $userPage = $wgUser->getUserPage();
389 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
390 $body = strtr( $body, $keys );
391 $body = wordwrap( $body, 72 );
393 # now save this as the constant user-independent part of the message
395 $this->replyto
= $replyto;
396 $this->subject
= $subject;
403 * Does the per-user customizations to a notification e-mail (name,
404 * timestamp in proper timezone, etc) and sends it out.
405 * Returns true if the mail was sent successfully.
407 * @param User $watchingUser
408 * @param object $mail
412 function composeAndSendPersonalisedMail( $watchingUser ) {
414 // From the PHP manual:
415 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
416 // The mail command will not parse this properly while talking with the MTA.
417 $to = new MailAddress( $watchingUser );
418 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body
);
420 $timecorrection = $watchingUser->getOption( 'timecorrection' );
422 # $PAGEEDITDATE is the time and date of the page change
423 # expressed in terms of individual local time of the notification
424 # recipient, i.e. watching user
425 $body = str_replace('$PAGEEDITDATE',
426 $wgLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
429 $error = userMailer( $to, $this->from
, $this->subject
, $body, $this->replyto
);
430 return ($error == '');
433 } # end of class EmailNotification