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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * http://www.gnu.org/copyleft/gpl.html
22 * @author <brion@pobox.com>
23 * @author <mail@tgries.de>
28 require_once( 'WikiError.php' );
31 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
33 function wfRFC822Phrase( $phrase ) {
34 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
35 return '"' . $phrase . '"';
39 * This function will perform a direct (authenticated) login to
40 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
41 * array of parameters. It requires PEAR:Mail to do that.
42 * Otherwise it just uses the standard PHP 'mail' function.
44 * @param string $to recipient's email
45 * @param string $from sender's email
46 * @param string $subject email's subject
47 * @param string $body email's text
48 * @param string $replyto optional reply-to email (default : false)
50 function userMailer( $to, $from, $subject, $body, $replyto=false ) {
51 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString;
53 if (is_array( $wgSMTP )) {
54 require_once( 'Mail.php' );
58 $headers['From'] = $from;
60 $headers['Reply-To'] = $replyto;
62 $headers['Subject'] = $subject;
63 $headers['MIME-Version'] = '1.0';
64 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
65 $headers['Content-transfer-encoding'] = '8bit';
66 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>';
67 $headers['X-Mailer'] = 'MediaWiki mailer';
69 // Create the mail object using the Mail::factory method
70 $mail_object =& Mail
::factory('smtp', $wgSMTP);
71 wfDebug( "Sending mail via PEAR::Mail to $to\n" );
72 $mailResult =& $mail_object->send($to, $headers, $body);
74 # Based on the result return an error string,
75 if ($mailResult === true) {
77 } elseif (is_object($mailResult)) {
78 return $mailResult->getMessage();
80 return 'Mail object return unknown error.';
83 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
84 # (fifth parameter of the PHP mail function, see some lines below)
86 "MIME-Version: 1.0\n" .
87 "Content-type: text/plain; charset={$wgOutputEncoding}\n" .
88 "Content-Transfer-Encoding: 8bit\n" .
89 "X-Mailer: MediaWiki mailer\n".
90 'From: ' . $from . "\n";
92 $headers .= "Reply-To: $replyto\n";
96 set_error_handler( 'mailErrorHandler' );
97 wfDebug( "Sending mail via internal mail() function to $to\n" );
98 mail( $to, $subject, $body, $headers );
99 restore_error_handler();
101 if ( $wgErrorString ) {
102 wfDebug( "Error sending mail: $wgErrorString\n" );
104 return $wgErrorString;
109 * Get the mail error message in global $wgErrorString
111 * @parameter $code error number
112 * @parameter $string error message
114 function mailErrorHandler( $code, $string ) {
115 global $wgErrorString;
116 $wgErrorString = preg_replace( "/^mail\(\): /", '', $string );
121 * This module processes the email notifications when the current page is
122 * changed. It looks up the table watchlist to find out which users are watching
125 * The current implementation sends independent emails to each watching user for
126 * the following reason:
128 * - Each watching user will be notified about the page edit time expressed in
129 * his/her local time (UTC is shown additionally). To achieve this, we need to
130 * find the individual timeoffset of each watching user from the preferences..
132 * Suggested improvement to slack down the number of sent emails: We could think
133 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
134 * same timeoffset in their preferences.
136 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
141 class EmailNotification
{
145 var $to, $subject, $body, $replyto, $from;
146 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
152 * @param $currentPage
155 * @param $currentSummary
156 * @param $currentMinorEdit
157 * @param $oldid (default: false)
159 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
161 # we use $wgEmergencyContact as sender's address
162 global $wgUser, $wgEnotifWatchlist;
163 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
165 $fname = 'UserMailer::notifyOnPageChange';
166 wfProfileIn( $fname );
168 # The following code is only run, if several conditions are met:
169 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
170 # 2. minor edits (changes) are only regarded if the global flag indicates so
172 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK
);
173 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
174 $enotifwatchlistpage = $wgEnotifWatchlist;
176 if ( (!$minorEdit ||
$wgEnotifMinorEdits) ) {
177 if( $wgEnotifWatchlist ) {
178 // Send updates to watchers other than the current editor
179 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
180 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK
) {
181 $targetUser = User
::newFromName( $title->getText() );
182 if( is_null( $targetUser ) ) {
183 wfDebug( "$fname: user-talk-only mode; no such user\n" );
184 $userCondition = false;
185 } elseif( $targetUser->getId() == $wgUser->getId() ) {
186 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
187 $userCondition = false;
189 // Don't notify anyone other than the owner of the talk page
190 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
193 // Notifications disabled
194 $userCondition = false;
196 if( $userCondition ) {
197 $dbr =& wfGetDB( DB_MASTER
);
198 extract( $dbr->tableNames( 'watchlist' ) );
200 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
202 'wl_title' => $title->getDBkey(),
203 'wl_namespace' => $title->getNamespace(),
205 'wl_notificationtimestamp IS NULL',
208 # if anyone is watching ... set up the email message text which is
209 # common for all receipients ...
210 if ( $dbr->numRows( $res ) > 0 ) {
211 $this->title
=& $title;
212 $this->timestamp
= $timestamp;
213 $this->summary
= $summary;
214 $this->minorEdit
= $minorEdit;
215 $this->oldid
= $oldid;
217 $this->composeCommonMailtext();
218 $watchingUser = new User();
220 # ... now do for all watching users ... if the options fit
221 for ($i = 1; $i <= $dbr->numRows( $res ); $i++
) {
223 $wuser = $dbr->fetchObject( $res );
224 $watchingUser->setID($wuser->wl_user
);
225 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
226 ( $enotifusertalkpage && $watchingUser->getOption('enotifusertalkpages') )
227 && (!$minorEdit ||
($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
228 && ($watchingUser->isEmailConfirmed() ) ) {
229 # ... adjust remaining text and page edit time placeholders
230 # which needs to be personalized for each user
231 $this->composeAndSendPersonalisedMail( $watchingUser );
233 } # if the watching user has an email address in the preferences
236 } # if anyone is watching
237 } # if $wgEnotifWatchlist = true
239 if ( $wgShowUpdatedMarker ||
$wgEnotifWatchlist ) {
240 # mark the changed watch-listed page with a timestamp, so that the page is
241 # listed with an "updated since your last visit" icon in the watch list, ...
242 $dbw =& wfGetDB( DB_MASTER
);
243 $success = $dbw->update( 'watchlist',
245 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
246 ), array( /* WHERE */
247 'wl_title' => $title->getDBkey(),
248 'wl_namespace' => $title->getNamespace(),
249 ), 'UserMailer::NotifyOnChange'
251 # FIXME what do we do on failure ?
254 } # function NotifyOnChange
259 function composeCommonMailtext() {
260 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
261 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
263 $summary = ($this->summary
== '') ?
' - ' : $this->summary
;
264 $medit = ($this->minorEdit
) ?
wfMsg( 'minoredit' ) : '';
266 # You as the WikiAdmin and Sysops can make use of plenty of
267 # named variables when composing your notification emails while
268 # simply editing the Meta pages
270 $subject = wfMsgForContent( 'enotif_subject' );
271 $body = wfMsgForContent( 'enotif_body' );
272 $from = ''; /* fail safe */
273 $replyto = ''; /* fail safe */
276 # regarding the use of oldid as an indicator for the last visited version, see also
277 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
278 # However, in the case of a new page which is already watched, we have no previous version to compare
280 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
281 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
282 $keys['$OLDID'] = $this->oldid
;
283 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
285 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
286 # clear $OLDID placeholder in the message template
287 $keys['$OLDID'] = '';
288 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
291 $body = strtr( $body, $keys );
292 $pagetitle = $this->title
->getPrefixedText();
293 $keys['$PAGETITLE'] = $pagetitle;
294 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
296 $keys['$PAGEMINOREDIT'] = $medit;
297 $keys['$PAGESUMMARY'] = $summary;
299 $subject = strtr( $subject, $keys );
301 # Reveal the page editor's address as REPLY-TO address only if
302 # the user has not opted-out and the option is enabled at the
303 # global configuration level.
304 $name = $wgUser->getName();
305 $adminAddress = 'WikiAdmin <' . $wgEmergencyContact . '>';
306 $editorAddress = wfRFC822Phrase( $name ) . ' <' . $wgUser->getEmail() . '>';
307 if( $wgEnotifRevealEditorAddress
308 && ( $wgUser->getEmail() != '' )
309 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
310 if( $wgEnotifFromEditor ) {
311 $from = $editorAddress;
313 $from = $adminAddress;
314 $replyto = $editorAddress;
317 $from = $adminAddress;
318 $replyto = $wgNoReplyAddress;
321 if( $wgUser->isIP( $name ) ) {
322 #real anon (user:xxx.xxx.xxx.xxx)
323 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
324 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
325 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
327 $subject = str_replace('$PAGEEDITOR', $name, $subject);
328 $keys['$PAGEEDITOR'] = $name;
329 $emailPage = Title
::makeTitle( NS_SPECIAL
, 'Emailuser/' . $name );
330 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
332 $userPage = $wgUser->getUserPage();
333 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
334 $body = strtr( $body, $keys );
335 $body = wordwrap( $body, 72 );
337 # now save this as the constant user-independent part of the message
339 $this->replyto
= $replyto;
340 $this->subject
= $subject;
347 * Does the per-user customizations to a notification e-mail (name,
348 * timestamp in proper timezone, etc) and sends it out.
349 * Returns true if the mail was sent successfully.
351 * @param User $watchingUser
352 * @param object $mail
356 function composeAndSendPersonalisedMail( $watchingUser ) {
358 // From the PHP manual:
359 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
360 // The mail command will not parse this properly while talking with the MTA.
361 $to = $watchingUser->getEmail();
362 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body
);
364 $timecorrection = $watchingUser->getOption( 'timecorrection' );
366 # $PAGEEDITDATE is the time and date of the page change
367 # expressed in terms of individual local time of the notification
368 # recipient, i.e. watching user
369 $body = str_replace('$PAGEEDITDATE',
370 $wgLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
373 $error = userMailer( $to, $this->from
, $this->subject
, $body, $this->replyto
);
374 return ($error == '');
377 } # end of class EmailNotification