bd773e190b410050238ffab8ff90a28df319e916
[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 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 $to MailAddress: recipient's email
73 * @param $from MailAddress: sender's email
74 * @param $subject String: email's subject.
75 * @param $body String: email's text.
76 * @param $replyto String: 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 * @param $code Integer: error number
147 * @param $string 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 * @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 $title Title object
188 * @param $timestamp
189 * @param $summary
190 * @param $minorEdit
191 * @param $oldid (default: false)
192 */
193 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
194
195 # we use $wgEmergencyContact as sender's address
196 global $wgUser, $wgEnotifWatchlist;
197 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
198
199 $fname = 'UserMailer::notifyOnPageChange';
200 wfProfileIn( $fname );
201
202 # The following code is only run, if several conditions are met:
203 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
204 # 2. minor edits (changes) are only regarded if the global flag indicates so
205
206 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
207 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
208 $enotifwatchlistpage = $wgEnotifWatchlist;
209
210 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
211 if( $wgEnotifWatchlist ) {
212 // Send updates to watchers other than the current editor
213 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
214 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK ) {
215 $targetUser = User::newFromName( $title->getText() );
216 if( is_null( $targetUser ) ) {
217 wfDebug( "$fname: user-talk-only mode; no such user\n" );
218 $userCondition = false;
219 } elseif( $targetUser->getId() == $wgUser->getId() ) {
220 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
221 $userCondition = false;
222 } else {
223 // Don't notify anyone other than the owner of the talk page
224 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
225 }
226 } else {
227 // Notifications disabled
228 $userCondition = false;
229 }
230 if( $userCondition ) {
231 $dbr =& wfGetDB( DB_MASTER );
232 extract( $dbr->tableNames( 'watchlist' ) );
233
234 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
235 array(
236 'wl_title' => $title->getDBkey(),
237 'wl_namespace' => $title->getNamespace(),
238 $userCondition,
239 'wl_notificationtimestamp IS NULL',
240 ), $fname );
241
242 # if anyone is watching ... set up the email message text which is
243 # common for all receipients ...
244 if ( $dbr->numRows( $res ) > 0 ) {
245 $this->title =& $title;
246 $this->timestamp = $timestamp;
247 $this->summary = $summary;
248 $this->minorEdit = $minorEdit;
249 $this->oldid = $oldid;
250
251 $this->composeCommonMailtext();
252 $watchingUser = new User();
253
254 # ... now do for all watching users ... if the options fit
255 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
256
257 $wuser = $dbr->fetchObject( $res );
258 $watchingUser->setID($wuser->wl_user);
259 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
260 ( $enotifusertalkpage && $watchingUser->getOption('enotifusertalkpages') )
261 && (!$minorEdit || ($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
262 && ($watchingUser->isEmailConfirmed() ) ) {
263 # ... adjust remaining text and page edit time placeholders
264 # which needs to be personalized for each user
265 $this->composeAndSendPersonalisedMail( $watchingUser );
266
267 } # if the watching user has an email address in the preferences
268 }
269 }
270 } # if anyone is watching
271 } # if $wgEnotifWatchlist = true
272
273 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
274 # mark the changed watch-listed page with a timestamp, so that the page is
275 # listed with an "updated since your last visit" icon in the watch list, ...
276 $dbw =& wfGetDB( DB_MASTER );
277 $success = $dbw->update( 'watchlist',
278 array( /* SET */
279 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
280 ), array( /* WHERE */
281 'wl_title' => $title->getDBkey(),
282 'wl_namespace' => $title->getNamespace(),
283 ), 'UserMailer::NotifyOnChange'
284 );
285 # FIXME what do we do on failure ?
286 }
287
288 } # function NotifyOnChange
289
290 /**
291 * @private
292 */
293 function composeCommonMailtext() {
294 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
295 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
296
297 $summary = ($this->summary == '') ? ' - ' : $this->summary;
298 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
299
300 # You as the WikiAdmin and Sysops can make use of plenty of
301 # named variables when composing your notification emails while
302 # simply editing the Meta pages
303
304 $subject = wfMsgForContent( 'enotif_subject' );
305 $body = wfMsgForContent( 'enotif_body' );
306 $from = ''; /* fail safe */
307 $replyto = ''; /* fail safe */
308 $keys = array();
309
310 # regarding the use of oldid as an indicator for the last visited version, see also
311 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
312 # However, in the case of a new page which is already watched, we have no previous version to compare
313 if( $this->oldid ) {
314 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
315 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
316 $keys['$OLDID'] = $this->oldid;
317 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
318 } else {
319 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
320 # clear $OLDID placeholder in the message template
321 $keys['$OLDID'] = '';
322 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
323 }
324
325 $body = strtr( $body, $keys );
326 $pagetitle = $this->title->getPrefixedText();
327 $keys['$PAGETITLE'] = $pagetitle;
328 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
329
330 $keys['$PAGEMINOREDIT'] = $medit;
331 $keys['$PAGESUMMARY'] = $summary;
332
333 $subject = strtr( $subject, $keys );
334
335 # Reveal the page editor's address as REPLY-TO address only if
336 # the user has not opted-out and the option is enabled at the
337 # global configuration level.
338 $name = $wgUser->getName();
339 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
340 $editorAddress = new MailAddress( $wgUser );
341 if( $wgEnotifRevealEditorAddress
342 && ( $wgUser->getEmail() != '' )
343 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
344 if( $wgEnotifFromEditor ) {
345 $from = $editorAddress;
346 } else {
347 $from = $adminAddress;
348 $replyto = $editorAddress;
349 }
350 } else {
351 $from = $adminAddress;
352 $replyto = $wgNoReplyAddress;
353 }
354
355 if( $wgUser->isIP( $name ) ) {
356 #real anon (user:xxx.xxx.xxx.xxx)
357 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
358 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
359 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
360 } else {
361 $subject = str_replace('$PAGEEDITOR', $name, $subject);
362 $keys['$PAGEEDITOR'] = $name;
363 $emailPage = Title::makeTitle( NS_SPECIAL, 'Emailuser/' . $name );
364 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
365 }
366 $userPage = $wgUser->getUserPage();
367 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
368 $body = strtr( $body, $keys );
369 $body = wordwrap( $body, 72 );
370
371 # now save this as the constant user-independent part of the message
372 $this->from = $from;
373 $this->replyto = $replyto;
374 $this->subject = $subject;
375 $this->body = $body;
376 }
377
378
379
380 /**
381 * Does the per-user customizations to a notification e-mail (name,
382 * timestamp in proper timezone, etc) and sends it out.
383 * Returns true if the mail was sent successfully.
384 *
385 * @param User $watchingUser
386 * @param object $mail
387 * @return bool
388 * @private
389 */
390 function composeAndSendPersonalisedMail( $watchingUser ) {
391 global $wgLang;
392 // From the PHP manual:
393 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
394 // The mail command will not parse this properly while talking with the MTA.
395 $to = new MailAddress( $watchingUser );
396 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
397
398 $timecorrection = $watchingUser->getOption( 'timecorrection' );
399
400 # $PAGEEDITDATE is the time and date of the page change
401 # expressed in terms of individual local time of the notification
402 # recipient, i.e. watching user
403 $body = str_replace('$PAGEEDITDATE',
404 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
405 $body);
406
407 $error = userMailer( $to, $this->from, $this->subject, $body, $this->replyto );
408 return ($error == '');
409 }
410
411 } # end of class EmailNotification
412 ?>