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