(bug 5378) General logs link in Special:Contributions
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /**
3 * UserMailer.php
4 * Copyright (C) 2004 Thomas Gries <mail@tgries.de>
5 * http://www.mediawiki.org/
6 *
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.
11 *
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.
16 *
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
21 *
22 * @author <brion@pobox.com>
23 * @author <mail@tgries.de>
24 *
25 * @package MediaWiki
26 */
27
28 require_once( 'WikiError.php' );
29
30 /**
31 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
32 */
33 function wfRFC822Phrase( $phrase ) {
34 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
35 return '"' . $phrase . '"';
36 }
37
38 class MailAddress {
39 /**
40 * @param mixed $address String with an email address, or a User object
41 * @param string $name Human-readable name if a string address is given
42 */
43 function MailAddress( $address, $name=null ) {
44 if( is_object( $address ) && is_a( $address, 'User' ) ) {
45 $this->address = $address->getEmail();
46 $this->name = $address->getName();
47 } else {
48 $this->address = strval( $address );
49 $this->name = strval( $name );
50 }
51 }
52
53 /**
54 * Return formatted and quoted address to insert into SMTP headers
55 * @return string
56 */
57 function toString() {
58 if( $this->name != '' ) {
59 return wfQuotedPrintable( $this->name ) . " <" . $this->address . ">";
60 } else {
61 return $this->address;
62 }
63 }
64 }
65
66 /**
67 * This function will perform a direct (authenticated) login to
68 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
69 * array of parameters. It requires PEAR:Mail to do that.
70 * Otherwise it just uses the standard PHP 'mail' function.
71 *
72 * @param MailAddress $to recipient's email
73 * @param MailAddress $from sender's email
74 * @param string $subject email's subject
75 * @param string $body email's text
76 * @param string $replyto optional reply-to email (default : false)
77 */
78 function userMailer( $to, $from, $subject, $body, $replyto=false ) {
79 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString;
80
81 if (is_array( $wgSMTP )) {
82 require_once( 'Mail.php' );
83
84 $timestamp = time();
85 $dest = $to->toString();
86
87 $headers['From'] = $from->toString();
88 $headers['To'] = $dest;
89 if ( $replyto ) {
90 $headers['Reply-To'] = $replyto;
91 }
92 $headers['Subject'] = wfQuotedPrintable( $subject );
93 $headers['Date'] = date( 'r' );
94 $headers['MIME-Version'] = '1.0';
95 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
96 $headers['Content-transfer-encoding'] = '8bit';
97 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>'; // FIXME
98 $headers['X-Mailer'] = 'MediaWiki mailer';
99
100 // Create the mail object using the Mail::factory method
101 $mail_object =& Mail::factory('smtp', $wgSMTP);
102 wfDebug( "Sending mail via PEAR::Mail to $dest" );
103 $mailResult =& $mail_object->send($dest, $headers, $body);
104
105 # Based on the result return an error string,
106 if ($mailResult === true) {
107 return '';
108 } elseif (is_object($mailResult)) {
109 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
110 return $mailResult->getMessage();
111 } else {
112 wfDebug( "PEAR::Mail failed, unknown error result\n" );
113 return 'Mail object return unknown error.';
114 }
115 } else {
116 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
117 # (fifth parameter of the PHP mail function, see some lines below)
118 $headers =
119 "MIME-Version: 1.0\n" .
120 "Content-type: text/plain; charset={$wgOutputEncoding}\n" .
121 "Content-Transfer-Encoding: 8bit\n" .
122 "X-Mailer: MediaWiki mailer\n".
123 'From: ' . $from->toString() . "\n";
124 if ($replyto) {
125 $headers .= "Reply-To: $replyto\n";
126 }
127
128 $dest = $to->toString();
129
130 $wgErrorString = '';
131 set_error_handler( 'mailErrorHandler' );
132 wfDebug( "Sending mail via internal mail() function to $dest\n" );
133 mail( $dest, wfQuotedPrintable( $subject ), $body, $headers );
134 restore_error_handler();
135
136 if ( $wgErrorString ) {
137 wfDebug( "Error sending mail: $wgErrorString\n" );
138 }
139 return $wgErrorString;
140 }
141 }
142
143 /**
144 * Get the mail error message in global $wgErrorString
145 *
146 * @parameter $code error number
147 * @parameter $string error message
148 */
149 function mailErrorHandler( $code, $string ) {
150 global $wgErrorString;
151 $wgErrorString = preg_replace( "/^mail\(\): /", '', $string );
152 }
153
154
155 /**
156 * This module processes the email notifications when the current page is
157 * changed. It looks up the table watchlist to find out which users are watching
158 * that page.
159 *
160 * The current implementation sends independent emails to each watching user for
161 * the following reason:
162 *
163 * - Each watching user will be notified about the page edit time expressed in
164 * his/her local time (UTC is shown additionally). To achieve this, we need to
165 * find the individual timeoffset of each watching user from the preferences..
166 *
167 * Suggested improvement to slack down the number of sent emails: We could think
168 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
169 * same timeoffset in their preferences.
170 *
171 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
172 *
173 * @package MediaWiki
174 *
175 */
176 class EmailNotification {
177 /**#@+
178 * @access private
179 */
180 var $to, $subject, $body, $replyto, $from;
181 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
182
183 /**#@-*/
184
185 /**
186 * @todo document
187 * @param $currentPage
188 * @param $currentNs
189 * @param $timestamp
190 * @param $currentSummary
191 * @param $currentMinorEdit
192 * @param $oldid (default: false)
193 */
194 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
195
196 # we use $wgEmergencyContact as sender's address
197 global $wgUser, $wgEnotifWatchlist;
198 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
199
200 $fname = 'UserMailer::notifyOnPageChange';
201 wfProfileIn( $fname );
202
203 # The following code is only run, if several conditions are met:
204 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
205 # 2. minor edits (changes) are only regarded if the global flag indicates so
206
207 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
208 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
209 $enotifwatchlistpage = $wgEnotifWatchlist;
210
211 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
212 if( $wgEnotifWatchlist ) {
213 // Send updates to watchers other than the current editor
214 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
215 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK ) {
216 $targetUser = User::newFromName( $title->getText() );
217 if( is_null( $targetUser ) ) {
218 wfDebug( "$fname: user-talk-only mode; no such user\n" );
219 $userCondition = false;
220 } elseif( $targetUser->getId() == $wgUser->getId() ) {
221 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
222 $userCondition = false;
223 } else {
224 // Don't notify anyone other than the owner of the talk page
225 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
226 }
227 } else {
228 // Notifications disabled
229 $userCondition = false;
230 }
231 if( $userCondition ) {
232 $dbr =& wfGetDB( DB_MASTER );
233 extract( $dbr->tableNames( 'watchlist' ) );
234
235 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
236 array(
237 'wl_title' => $title->getDBkey(),
238 'wl_namespace' => $title->getNamespace(),
239 $userCondition,
240 'wl_notificationtimestamp IS NULL',
241 ), $fname );
242
243 # if anyone is watching ... set up the email message text which is
244 # common for all receipients ...
245 if ( $dbr->numRows( $res ) > 0 ) {
246 $this->title =& $title;
247 $this->timestamp = $timestamp;
248 $this->summary = $summary;
249 $this->minorEdit = $minorEdit;
250 $this->oldid = $oldid;
251
252 $this->composeCommonMailtext();
253 $watchingUser = new User();
254
255 # ... now do for all watching users ... if the options fit
256 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
257
258 $wuser = $dbr->fetchObject( $res );
259 $watchingUser->setID($wuser->wl_user);
260 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
261 ( $enotifusertalkpage && $watchingUser->getOption('enotifusertalkpages') )
262 && (!$minorEdit || ($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
263 && ($watchingUser->isEmailConfirmed() ) ) {
264 # ... adjust remaining text and page edit time placeholders
265 # which needs to be personalized for each user
266 $this->composeAndSendPersonalisedMail( $watchingUser );
267
268 } # if the watching user has an email address in the preferences
269 }
270 }
271 } # if anyone is watching
272 } # if $wgEnotifWatchlist = true
273
274 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
275 # mark the changed watch-listed page with a timestamp, so that the page is
276 # listed with an "updated since your last visit" icon in the watch list, ...
277 $dbw =& wfGetDB( DB_MASTER );
278 $success = $dbw->update( 'watchlist',
279 array( /* SET */
280 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
281 ), array( /* WHERE */
282 'wl_title' => $title->getDBkey(),
283 'wl_namespace' => $title->getNamespace(),
284 ), 'UserMailer::NotifyOnChange'
285 );
286 # FIXME what do we do on failure ?
287 }
288
289 } # function NotifyOnChange
290
291 /**
292 * @access private
293 */
294 function composeCommonMailtext() {
295 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
296 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
297
298 $summary = ($this->summary == '') ? ' - ' : $this->summary;
299 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
300
301 # You as the WikiAdmin and Sysops can make use of plenty of
302 # named variables when composing your notification emails while
303 # simply editing the Meta pages
304
305 $subject = wfMsgForContent( 'enotif_subject' );
306 $body = wfMsgForContent( 'enotif_body' );
307 $from = ''; /* fail safe */
308 $replyto = ''; /* fail safe */
309 $keys = array();
310
311 # regarding the use of oldid as an indicator for the last visited version, see also
312 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
313 # However, in the case of a new page which is already watched, we have no previous version to compare
314 if( $this->oldid ) {
315 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
316 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
317 $keys['$OLDID'] = $this->oldid;
318 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
319 } else {
320 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
321 # clear $OLDID placeholder in the message template
322 $keys['$OLDID'] = '';
323 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
324 }
325
326 $body = strtr( $body, $keys );
327 $pagetitle = $this->title->getPrefixedText();
328 $keys['$PAGETITLE'] = $pagetitle;
329 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
330
331 $keys['$PAGEMINOREDIT'] = $medit;
332 $keys['$PAGESUMMARY'] = $summary;
333
334 $subject = strtr( $subject, $keys );
335
336 # Reveal the page editor's address as REPLY-TO address only if
337 # the user has not opted-out and the option is enabled at the
338 # global configuration level.
339 $name = $wgUser->getName();
340 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
341 $editorAddress = new MailAddress( $wgUser );
342 if( $wgEnotifRevealEditorAddress
343 && ( $wgUser->getEmail() != '' )
344 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
345 if( $wgEnotifFromEditor ) {
346 $from = $editorAddress;
347 } else {
348 $from = $adminAddress;
349 $replyto = $editorAddress;
350 }
351 } else {
352 $from = $adminAddress;
353 $replyto = $wgNoReplyAddress;
354 }
355
356 if( $wgUser->isIP( $name ) ) {
357 #real anon (user:xxx.xxx.xxx.xxx)
358 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
359 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
360 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
361 } else {
362 $subject = str_replace('$PAGEEDITOR', $name, $subject);
363 $keys['$PAGEEDITOR'] = $name;
364 $emailPage = Title::makeTitle( NS_SPECIAL, 'Emailuser/' . $name );
365 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
366 }
367 $userPage = $wgUser->getUserPage();
368 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
369 $body = strtr( $body, $keys );
370 $body = wordwrap( $body, 72 );
371
372 # now save this as the constant user-independent part of the message
373 $this->from = $from;
374 $this->replyto = $replyto;
375 $this->subject = $subject;
376 $this->body = $body;
377 }
378
379
380
381 /**
382 * Does the per-user customizations to a notification e-mail (name,
383 * timestamp in proper timezone, etc) and sends it out.
384 * Returns true if the mail was sent successfully.
385 *
386 * @param User $watchingUser
387 * @param object $mail
388 * @return bool
389 * @access private
390 */
391 function composeAndSendPersonalisedMail( $watchingUser ) {
392 global $wgLang;
393 // From the PHP manual:
394 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
395 // The mail command will not parse this properly while talking with the MTA.
396 $to = new MailAddress( $watchingUser );
397 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
398
399 $timecorrection = $watchingUser->getOption( 'timecorrection' );
400
401 # $PAGEEDITDATE is the time and date of the page change
402 # expressed in terms of individual local time of the notification
403 # recipient, i.e. watching user
404 $body = str_replace('$PAGEEDITDATE',
405 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
406 $body);
407
408 $error = userMailer( $to, $this->from, $this->subject, $body, $this->replyto );
409 return ($error == '');
410 }
411
412 } # end of class EmailNotification
413 ?>