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