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