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