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>
29 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
31 function wfRFC822Phrase( $phrase ) {
32 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
33 return '"' . $phrase . '"';
38 * @param mixed $address String with an email address, or a User object
39 * @param string $name Human-readable name if a string address is given
41 function MailAddress( $address, $name=null ) {
42 if( is_object( $address ) && is_a( $address, 'User' ) ) {
43 $this->address
= $address->getEmail();
44 $this->name
= $address->getName();
46 $this->address
= strval( $address );
47 $this->name
= strval( $name );
52 * Return formatted and quoted address to insert into SMTP headers
56 # PHP's mail() implementation under Windows is somewhat shite, and
57 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
58 # so don't bother generating them
59 if( $this->name
!= '' && !wfIsWindows() ) {
60 $quoted = wfQuotedPrintable( $this->name
);
61 if( strpos( $quoted, '.' ) !== false ) {
62 $quoted = '"' . $quoted . '"';
64 return "$quoted <{$this->address}>";
66 return $this->address
;
72 * This function will perform a direct (authenticated) login to
73 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
74 * array of parameters. It requires PEAR:Mail to do that.
75 * Otherwise it just uses the standard PHP 'mail' function.
77 * @param $to MailAddress: recipient's email
78 * @param $from MailAddress: sender's email
79 * @param $subject String: email's subject.
80 * @param $body String: email's text.
81 * @param $replyto String: optional reply-to email (default: false).
83 function userMailer( $to, $from, $subject, $body, $replyto=false ) {
84 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString;
86 if (is_array( $wgSMTP )) {
87 require_once( 'Mail.php' );
92 $headers['From'] = $from->toString();
93 $headers['To'] = $to->toString();
95 $headers['Reply-To'] = $replyto;
97 $headers['Subject'] = wfQuotedPrintable( $subject );
98 $headers['Date'] = date( 'r' );
99 $headers['MIME-Version'] = '1.0';
100 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
101 $headers['Content-transfer-encoding'] = '8bit';
102 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>'; // FIXME
103 $headers['X-Mailer'] = 'MediaWiki mailer';
105 // Create the mail object using the Mail::factory method
106 $mail_object =& Mail
::factory('smtp', $wgSMTP);
107 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
108 $mailResult =& $mail_object->send($dest, $headers, $body);
110 # Based on the result return an error string,
111 if ($mailResult === true) {
113 } elseif (is_object($mailResult)) {
114 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
115 return $mailResult->getMessage();
117 wfDebug( "PEAR::Mail failed, unknown error result\n" );
118 return 'Mail object return unknown error.';
121 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
122 # (fifth parameter of the PHP mail function, see some lines below)
124 "MIME-Version: 1.0\n" .
125 "Content-type: text/plain; charset={$wgOutputEncoding}\n" .
126 "Content-Transfer-Encoding: 8bit\n" .
127 "X-Mailer: MediaWiki mailer\n".
128 'From: ' . $from->toString() . "\n";
130 $headers .= "Reply-To: $replyto\n";
133 $dest = $to->toString();
136 set_error_handler( 'mailErrorHandler' );
137 wfDebug( "Sending mail via internal mail() function to $dest\n" );
138 mail( $dest, wfQuotedPrintable( $subject ), $body, $headers );
139 restore_error_handler();
141 if ( $wgErrorString ) {
142 wfDebug( "Error sending mail: $wgErrorString\n" );
144 return $wgErrorString;
149 * Get the mail error message in global $wgErrorString
151 * @param $code Integer: error number
152 * @param $string String: error message
154 function mailErrorHandler( $code, $string ) {
155 global $wgErrorString;
156 $wgErrorString = preg_replace( "/^mail\(\): /", '', $string );
161 * This module processes the email notifications when the current page is
162 * changed. It looks up the table watchlist to find out which users are watching
165 * The current implementation sends independent emails to each watching user for
166 * the following reason:
168 * - Each watching user will be notified about the page edit time expressed in
169 * his/her local time (UTC is shown additionally). To achieve this, we need to
170 * find the individual timeoffset of each watching user from the preferences..
172 * Suggested improvement to slack down the number of sent emails: We could think
173 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
174 * same timeoffset in their preferences.
176 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
181 class EmailNotification
{
185 var $to, $subject, $body, $replyto, $from;
186 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
192 * @param $title Title object
196 * @param $oldid (default: false)
198 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
200 # we use $wgEmergencyContact as sender's address
201 global $wgUser, $wgEnotifWatchlist;
202 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
204 $fname = 'UserMailer::notifyOnPageChange';
205 wfProfileIn( $fname );
207 # The following code is only run, if several conditions are met:
208 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
209 # 2. minor edits (changes) are only regarded if the global flag indicates so
211 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK
);
212 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
213 $enotifwatchlistpage = $wgEnotifWatchlist;
215 if ( (!$minorEdit ||
$wgEnotifMinorEdits) ) {
216 if( $wgEnotifWatchlist ) {
217 // Send updates to watchers other than the current editor
218 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
219 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK
) {
220 $targetUser = User
::newFromName( $title->getText() );
221 if( is_null( $targetUser ) ) {
222 wfDebug( "$fname: user-talk-only mode; no such user\n" );
223 $userCondition = false;
224 } elseif( $targetUser->getId() == $wgUser->getId() ) {
225 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
226 $userCondition = false;
228 // Don't notify anyone other than the owner of the talk page
229 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
232 // Notifications disabled
233 $userCondition = false;
235 if( $userCondition ) {
236 $dbr =& wfGetDB( DB_MASTER
);
237 extract( $dbr->tableNames( 'watchlist' ) );
239 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
241 'wl_title' => $title->getDBkey(),
242 'wl_namespace' => $title->getNamespace(),
244 'wl_notificationtimestamp IS NULL',
247 # if anyone is watching ... set up the email message text which is
248 # common for all receipients ...
249 if ( $dbr->numRows( $res ) > 0 ) {
250 $this->title
=& $title;
251 $this->timestamp
= $timestamp;
252 $this->summary
= $summary;
253 $this->minorEdit
= $minorEdit;
254 $this->oldid
= $oldid;
256 $this->composeCommonMailtext();
257 $watchingUser = new User();
259 # ... now do for all watching users ... if the options fit
260 for ($i = 1; $i <= $dbr->numRows( $res ); $i++
) {
262 $wuser = $dbr->fetchObject( $res );
263 $watchingUser->setID($wuser->wl_user
);
265 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
266 ( $enotifusertalkpage
267 && $watchingUser->getOption('enotifusertalkpages')
268 && $title->equals( $watchingUser->getTalkPage() ) )
269 && (!$minorEdit ||
($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
270 && ($watchingUser->isEmailConfirmed() ) ) {
271 # ... adjust remaining text and page edit time placeholders
272 # which needs to be personalized for each user
273 $this->composeAndSendPersonalisedMail( $watchingUser );
275 } # if the watching user has an email address in the preferences
278 } # if anyone is watching
279 } # if $wgEnotifWatchlist = true
281 if ( $wgShowUpdatedMarker ||
$wgEnotifWatchlist ) {
282 # mark the changed watch-listed page with a timestamp, so that the page is
283 # listed with an "updated since your last visit" icon in the watch list, ...
284 $dbw =& wfGetDB( DB_MASTER
);
285 $success = $dbw->update( 'watchlist',
287 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
288 ), array( /* WHERE */
289 'wl_title' => $title->getDBkey(),
290 'wl_namespace' => $title->getNamespace(),
291 ), 'UserMailer::NotifyOnChange'
293 # FIXME what do we do on failure ?
295 wfProfileOut( $fname );
296 } # function NotifyOnChange
301 function composeCommonMailtext() {
302 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
303 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
305 $summary = ($this->summary
== '') ?
' - ' : $this->summary
;
306 $medit = ($this->minorEdit
) ?
wfMsg( 'minoredit' ) : '';
308 # You as the WikiAdmin and Sysops can make use of plenty of
309 # named variables when composing your notification emails while
310 # simply editing the Meta pages
312 $subject = wfMsgForContent( 'enotif_subject' );
313 $body = wfMsgForContent( 'enotif_body' );
314 $from = ''; /* fail safe */
315 $replyto = ''; /* fail safe */
318 # regarding the use of oldid as an indicator for the last visited version, see also
319 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
320 # However, in the case of a new page which is already watched, we have no previous version to compare
322 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
323 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
324 $keys['$OLDID'] = $this->oldid
;
325 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
327 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
328 # clear $OLDID placeholder in the message template
329 $keys['$OLDID'] = '';
330 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
333 $body = strtr( $body, $keys );
334 $pagetitle = $this->title
->getPrefixedText();
335 $keys['$PAGETITLE'] = $pagetitle;
336 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
338 $keys['$PAGEMINOREDIT'] = $medit;
339 $keys['$PAGESUMMARY'] = $summary;
341 $subject = strtr( $subject, $keys );
343 # Reveal the page editor's address as REPLY-TO address only if
344 # the user has not opted-out and the option is enabled at the
345 # global configuration level.
346 $name = $wgUser->getName();
347 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
348 $editorAddress = new MailAddress( $wgUser );
349 if( $wgEnotifRevealEditorAddress
350 && ( $wgUser->getEmail() != '' )
351 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
352 if( $wgEnotifFromEditor ) {
353 $from = $editorAddress;
355 $from = $adminAddress;
356 $replyto = $editorAddress;
359 $from = $adminAddress;
360 $replyto = $wgNoReplyAddress;
363 if( $wgUser->isIP( $name ) ) {
364 #real anon (user:xxx.xxx.xxx.xxx)
365 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
366 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
367 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
369 $subject = str_replace('$PAGEEDITOR', $name, $subject);
370 $keys['$PAGEEDITOR'] = $name;
371 $emailPage = Title
::makeTitle( NS_SPECIAL
, 'Emailuser/' . $name );
372 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
374 $userPage = $wgUser->getUserPage();
375 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
376 $body = strtr( $body, $keys );
377 $body = wordwrap( $body, 72 );
379 # now save this as the constant user-independent part of the message
381 $this->replyto
= $replyto;
382 $this->subject
= $subject;
389 * Does the per-user customizations to a notification e-mail (name,
390 * timestamp in proper timezone, etc) and sends it out.
391 * Returns true if the mail was sent successfully.
393 * @param User $watchingUser
394 * @param object $mail
398 function composeAndSendPersonalisedMail( $watchingUser ) {
400 // From the PHP manual:
401 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
402 // The mail command will not parse this properly while talking with the MTA.
403 $to = new MailAddress( $watchingUser );
404 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body
);
406 $timecorrection = $watchingUser->getOption( 'timecorrection' );
408 # $PAGEEDITDATE is the time and date of the page change
409 # expressed in terms of individual local time of the notification
410 # recipient, i.e. watching user
411 $body = str_replace('$PAGEEDITDATE',
412 $wgLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
415 $error = userMailer( $to, $this->from
, $this->subject
, $body, $this->replyto
);
416 return ($error == '');
419 } # end of class EmailNotification