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