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