* Fix object variable used for displaying "not-patrolled" CSS class on list
[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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @author <brion@pobox.com>
23 * @author <mail@tgries.de>
24 *
25 */
26
27 /**
28 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
29 */
30 function wfRFC822Phrase( $phrase ) {
31 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
32 return '"' . $phrase . '"';
33 }
34
35 /**
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.
39 */
40 class MailAddress {
41 /**
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
44 */
45 function __construct( $address, $name=null ) {
46 if( is_object( $address ) && $address instanceof User ) {
47 $this->address = $address->getEmail();
48 $this->name = $address->getName();
49 } else {
50 $this->address = strval( $address );
51 $this->name = strval( $name );
52 }
53 }
54
55 /**
56 * Return formatted and quoted address to insert into SMTP headers
57 * @return string
58 */
59 function toString() {
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 . '"';
67 }
68 return "$quoted <{$this->address}>";
69 } else {
70 return $this->address;
71 }
72 }
73 }
74
75 /**
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.
80 *
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).
86 */
87 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
88 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString;
89
90 if (is_array( $wgSMTP )) {
91 require_once( 'Mail.php' );
92
93 $timestamp = time();
94 $dest = $to->address;
95
96 $headers['From'] = $from->toString();
97 $headers['To'] = $to->toString();
98 if ( $replyto ) {
99 $headers['Reply-To'] = $replyto->toString();
100 }
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';
108
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();
114 }
115
116 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
117 $mailResult =& $mail_object->send($dest, $headers, $body);
118
119 # Based on the result return an error string,
120 if ($mailResult === true) {
121 return '';
122 } elseif (is_object($mailResult)) {
123 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
124 return $mailResult->getMessage();
125 } else {
126 wfDebug( "PEAR::Mail failed, unknown error result\n" );
127 return 'Mail object return unknown error.';
128 }
129 } else {
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)
132
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 );
137 $endl = "\r\n";
138 } else {
139 $endl = "\n";
140 }
141 $headers =
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();
147 if ($replyto) {
148 $headers .= "{$endl}Reply-To: " . $replyto->toString();
149 }
150
151 $dest = $to->toString();
152
153 $wgErrorString = '';
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();
158
159 if ( $wgErrorString ) {
160 wfDebug( "Error sending mail: $wgErrorString\n" );
161 }
162 return $wgErrorString;
163 }
164 }
165
166 /**
167 * Get the mail error message in global $wgErrorString
168 *
169 * @param $code Integer: error number
170 * @param $string String: error message
171 */
172 function mailErrorHandler( $code, $string ) {
173 global $wgErrorString;
174 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
175 }
176
177
178 /**
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
181 * that page.
182 *
183 * The current implementation sends independent emails to each watching user for
184 * the following reason:
185 *
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..
189 *
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.
193 *
194 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
195 *
196 *
197 */
198 class EmailNotification {
199 /**@{{
200 * @private
201 */
202 var $to, $subject, $body, $replyto, $from;
203 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
204
205 /**@}}*/
206
207 /**
208 * @todo document
209 * @param $title Title object
210 * @param $timestamp
211 * @param $summary
212 * @param $minorEdit
213 * @param $oldid (default: false)
214 */
215 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
216
217 # we use $wgEmergencyContact as sender's address
218 global $wgUser, $wgEnotifWatchlist;
219 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
220
221 $fname = 'UserMailer::notifyOnPageChange';
222 wfProfileIn( $fname );
223
224 # The following code is only run, if several conditions are met:
225 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
226 # 2. minor edits (changes) are only regarded if the global flag indicates so
227
228 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
229 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
230 $enotifwatchlistpage = $wgEnotifWatchlist;
231
232 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
233 if( $wgEnotifWatchlist ) {
234 // Send updates to watchers other than the current editor
235 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
236 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK ) {
237 $targetUser = User::newFromName( $title->getText() );
238 if( is_null( $targetUser ) ) {
239 wfDebug( "$fname: user-talk-only mode; no such user\n" );
240 $userCondition = false;
241 } elseif( $targetUser->getId() == $wgUser->getId() ) {
242 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
243 $userCondition = false;
244 } else {
245 // Don't notify anyone other than the owner of the talk page
246 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
247 }
248 } else {
249 // Notifications disabled
250 $userCondition = false;
251 }
252 if( $userCondition ) {
253 $dbr = wfGetDB( DB_MASTER );
254
255 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
256 array(
257 'wl_title' => $title->getDBkey(),
258 'wl_namespace' => $title->getNamespace(),
259 $userCondition,
260 'wl_notificationtimestamp IS NULL',
261 ), $fname );
262
263 # if anyone is watching ... set up the email message text which is
264 # common for all receipients ...
265 if ( $dbr->numRows( $res ) > 0 ) {
266 $this->title =& $title;
267 $this->timestamp = $timestamp;
268 $this->summary = $summary;
269 $this->minorEdit = $minorEdit;
270 $this->oldid = $oldid;
271
272 $this->composeCommonMailtext();
273 $watchingUser = new User();
274
275 # ... now do for all watching users ... if the options fit
276 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
277
278 $wuser = $dbr->fetchObject( $res );
279 $watchingUser->setID($wuser->wl_user);
280
281 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
282 ( $enotifusertalkpage
283 && $watchingUser->getOption('enotifusertalkpages')
284 && $title->equals( $watchingUser->getTalkPage() ) )
285 && (!$minorEdit || ($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
286 && ($watchingUser->isEmailConfirmed() ) ) {
287 # ... adjust remaining text and page edit time placeholders
288 # which needs to be personalized for each user
289 $this->composeAndSendPersonalisedMail( $watchingUser );
290
291 } # if the watching user has an email address in the preferences
292 }
293 }
294 } # if anyone is watching
295 } # if $wgEnotifWatchlist = true
296
297 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
298 # mark the changed watch-listed page with a timestamp, so that the page is
299 # listed with an "updated since your last visit" icon in the watch list, ...
300 $dbw = wfGetDB( DB_MASTER );
301 $success = $dbw->update( 'watchlist',
302 array( /* SET */
303 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
304 ), array( /* WHERE */
305 'wl_title' => $title->getDBkey(),
306 'wl_namespace' => $title->getNamespace(),
307 ), 'UserMailer::NotifyOnChange'
308 );
309 # FIXME what do we do on failure ?
310 }
311 wfProfileOut( $fname );
312 } # function NotifyOnChange
313
314 /**
315 * @private
316 */
317 function composeCommonMailtext() {
318 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
319 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
320
321 $summary = ($this->summary == '') ? ' - ' : $this->summary;
322 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
323
324 # You as the WikiAdmin and Sysops can make use of plenty of
325 # named variables when composing your notification emails while
326 # simply editing the Meta pages
327
328 $subject = wfMsgForContent( 'enotif_subject' );
329 $body = wfMsgForContent( 'enotif_body' );
330 $from = ''; /* fail safe */
331 $replyto = ''; /* fail safe */
332 $keys = array();
333
334 # regarding the use of oldid as an indicator for the last visited version, see also
335 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
336 # However, in the case of a new page which is already watched, we have no previous version to compare
337 if( $this->oldid ) {
338 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
339 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
340 $keys['$OLDID'] = $this->oldid;
341 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
342 } else {
343 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
344 # clear $OLDID placeholder in the message template
345 $keys['$OLDID'] = '';
346 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
347 }
348
349 $body = strtr( $body, $keys );
350 $pagetitle = $this->title->getPrefixedText();
351 $keys['$PAGETITLE'] = $pagetitle;
352 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
353
354 $keys['$PAGEMINOREDIT'] = $medit;
355 $keys['$PAGESUMMARY'] = $summary;
356
357 $subject = strtr( $subject, $keys );
358
359 # Reveal the page editor's address as REPLY-TO address only if
360 # the user has not opted-out and the option is enabled at the
361 # global configuration level.
362 $name = $wgUser->getName();
363 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
364 $editorAddress = new MailAddress( $wgUser );
365 if( $wgEnotifRevealEditorAddress
366 && ( $wgUser->getEmail() != '' )
367 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
368 if( $wgEnotifFromEditor ) {
369 $from = $editorAddress;
370 } else {
371 $from = $adminAddress;
372 $replyto = $editorAddress;
373 }
374 } else {
375 $from = $adminAddress;
376 $replyto = new MailAddress( $wgNoReplyAddress );
377 }
378
379 if( $wgUser->isIP( $name ) ) {
380 #real anon (user:xxx.xxx.xxx.xxx)
381 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
382 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
383 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
384 } else {
385 $subject = str_replace('$PAGEEDITOR', $name, $subject);
386 $keys['$PAGEEDITOR'] = $name;
387 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
388 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
389 }
390 $userPage = $wgUser->getUserPage();
391 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
392 $body = strtr( $body, $keys );
393 $body = wordwrap( $body, 72 );
394
395 # now save this as the constant user-independent part of the message
396 $this->from = $from;
397 $this->replyto = $replyto;
398 $this->subject = $subject;
399 $this->body = $body;
400 }
401
402
403
404 /**
405 * Does the per-user customizations to a notification e-mail (name,
406 * timestamp in proper timezone, etc) and sends it out.
407 * Returns true if the mail was sent successfully.
408 *
409 * @param User $watchingUser
410 * @param object $mail
411 * @return bool
412 * @private
413 */
414 function composeAndSendPersonalisedMail( $watchingUser ) {
415 global $wgLang;
416 // From the PHP manual:
417 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
418 // The mail command will not parse this properly while talking with the MTA.
419 $to = new MailAddress( $watchingUser );
420 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
421
422 $timecorrection = $watchingUser->getOption( 'timecorrection' );
423
424 # $PAGEEDITDATE is the time and date of the page change
425 # expressed in terms of individual local time of the notification
426 # recipient, i.e. watching user
427 $body = str_replace('$PAGEEDITDATE',
428 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
429 $body);
430
431 $error = userMailer( $to, $this->from, $this->subject, $body, $this->replyto );
432 return ($error == '');
433 }
434
435 } # end of class EmailNotification
436 ?>