Attempting to get enotif into working order. Many aesthetic changes, a fair number...
[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 # added -f parameter, see PHP manual for the fifth parameter when using the mail function
97 mail( $to, $subject, $body, $headers, "-f{$wgEmergencyContact}\n");
98 restore_error_handler();
99
100 if ( $wgErrorString ) {
101 wfDebug( "Error sending mail: $wgErrorString\n" );
102 }
103 return $wgErrorString;
104 }
105 }
106
107 /**
108 * @todo document
109 */
110 function mailErrorHandler( $code, $string ) {
111 global $wgErrorString;
112 $wgErrorString = preg_replace( "/^mail\(\): /", "", $string );
113 }
114
115
116 /**
117 * This module processes the email notifications when the current page is
118 * changed. It looks up the table watchlist to find out which users are watching
119 * that page.
120 *
121 * The current implementation sends independent emails to each watching user for
122 * the following reason:
123 *
124 * - Each watching user will be notified about the page edit time expressed in
125 * his/her local time (UTC is shown additionally). To achieve this, we need to
126 * find the individual timeoffset of each watching user from the preferences..
127 *
128 * Suggested improvement to slack down the number of sent emails: We could think
129 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
130 * same timeoffset in their preferences.
131 *
132 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
133 *
134 * @package MediaWiki
135 *
136 */
137 class EmailNotification {
138 /**#@+
139 * @access private
140 */
141 var $to, $subject, $body, $replyto, $from;
142 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
143
144 /**#@-*/
145
146 /**
147 * @todo document
148 * @param $currentPage
149 * @param $currentNs
150 * @param $timestamp
151 * @param $currentSummary
152 * @param $currentMinorEdit
153 * @param $oldid (default: false)
154 */
155 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
156
157 # we use $wgEmergencyContact as sender's address
158 global $wgUser, $wgLang, $wgEmergencyContact;
159 global $wgEnotifWatchlist, $wgEnotifMinorEdits;
160 global $wgEnotifUserTalk;
161 global $wgEnotifRevealEditorAddress;
162 global $wgEnotifFromEditor;
163 global $wgEmailAuthentication;
164
165 # The following code is only run, if several conditions are met:
166 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
167 # 2. minor edits (changes) are only regarded if the global flag indicates so
168
169 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
170 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
171 $enotifwatchlistpage = (!$isUserTalkPage && $wgEnotifWatchlist);
172
173 if ( ($enotifusertalkpage || $enotifwatchlistpage)
174 && (!$minorEdit || $wgEnotifMinorEdits) ) {
175
176 $dbr =& wfGetDB( DB_MASTER );
177 extract( $dbr->tableNames( 'watchlist' ) );
178 $sql = "SELECT wl_user FROM $watchlist
179 WHERE wl_title='" . $dbr->strencode($title->getDBkey()).
180 "' AND wl_namespace = " . $title->getNamespace() .
181 " AND wl_user <>" . $wgUser->getID() . " AND wl_notificationtimestamp <= 1";
182 $res = $dbr->query( $sql,'UserMailer::NotifyOnChange');
183
184 # if anyone is watching ... set up the email message text which is
185 # common for all receipients ...
186 if ( $dbr->numRows( $res ) > 0 ) {
187 $this->user &= $wgUser;
188 $this->title =& $title;
189 $this->timestamp = $timestamp;
190 $this->summary = $summary;
191 $this->minorEdit = $minorEdit;
192 $this->oldid = $oldid;
193
194 $this->composeCommonMailtext();
195 $watchingUser = new User();
196
197 # ... now do for all watching users ... if the options fit
198 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
199
200 $wuser = $dbr->fetchObject( $res );
201 $watchingUser->setID($wuser->wl_user);
202 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
203 ( $enotifusertalkpage && $watchingUser->getOption('enotifusertalkpages') )
204 && (!$minorEdit || ($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
205 && ($watchingUser->isEmailConfirmed() ) ) {
206 # ... adjust remaining text and page edit time placeholders
207 # which needs to be personalized for each user
208 $this->composeAndSendPersonalisedMail( $watchingUser );
209
210 } # if the watching user has an email address in the preferences
211 # mark the changed watch-listed page with a timestamp, so that the page is listed with an "updated since your last visit" icon in the watch list, ...
212 # ... no matter, if the watching user has or has not indicated an email address in his/her preferences.
213 # We memorise the event of sending out a notification and use this as a flag to suppress further mails for changes on the same page for that watching user
214 $dbw =& wfGetDB( DB_MASTER );
215 $succes = $dbw->update( 'watchlist',
216 array( /* SET */
217 'wl_notificationtimestamp' => $timestamp
218 ), array( /* WHERE */
219 'wl_title' => $title->getDBkey(),
220 'wl_namespace' => $title->getNamespace(),
221 'wl_user' => $wuser->wl_user
222 ), 'UserMailer::NotifyOnChange'
223 );
224 } # for every watching user
225 } # if anyone is watching
226 } # if $wgEnotifWatchlist = true
227 } # function NotifyOnChange
228
229 /**
230 * @access private
231 */
232 function composeCommonMailtext() {
233 global $wgLang, $wgUser, $wgEmergencyContact;
234 global $wgEnotifRevealEditorAddress;
235 global $wgEnotifFromEditor;
236 global $wgNoReplyAddress;
237
238 $summary = ($this->summary == '') ? ' - ' : $this->summary;
239 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
240
241 # You as the WikiAdmin and Sysops can make use of plenty of
242 # named variables when composing your notification emails while
243 # simply editing the Meta pages
244
245 $to = wfMsgForContent( 'enotif_to' );
246 $subject = wfMsgForContent( 'enotif_subject' );
247 $body = wfMsgForContent( 'enotif_body' );
248 $from = ''; /* fail safe */
249 $replyto = ''; /* fail safe */
250 $keys = array();
251
252 # regarding the use of oldid as an indicator for the last visited version, see also
253 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
254 # However, in the case of a new page which is already watched, we have no previous version to compare
255 if( $this->oldid ) {
256 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited' );
257 $keys['$OLDID'] = $this->oldid;
258 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
259 } else {
260 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
261 # clear $OLDID placeholder in the message template
262 $keys['$OLDID'] = '';
263 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
264 }
265
266 $body = strtr( $body, $keys );
267 $pagetitle = $this->title->getPrefixedText();
268
269 $keys['%24PAGETITLE_RAWURL'] = wfUrlencode( $pagetitle );
270 $keys['$PAGETITLE_RAWURL'] = wfUrlencode( $pagetitle );
271 $keys['%24PAGETITLE'] = $pagetitle; # needed for the {{localurl:$PAGETITLE}} in the messagetext, "$" appears here as "%24"
272 $keys['$PAGETITLE'] = $pagetitle;
273 $keys['$PAGETIMESTAMP'] = $article->mTimestamp; # this is the raw internal timestamp - can be useful, too
274 $keys['$PAGEEDITDATEUTC'] = $wgLang->timeanddate( $article->mTimestamp, false, false, false );
275 $keys['$PAGEMINOREDIT'] = $medit;
276 $keys['$PAGESUMMARY'] = $summary;
277
278 $subject = strtr( $subject, $keys );
279
280 # Reveal the page editor's address as REPLY-TO address only if
281 # the user has not opted-out and the option is enabled at the
282 # global configuration level.
283 $name = $wgUser->getName();
284 $adminAddress = 'WikiAdmin <' . $wgEmergencyContact . '>';
285 $editorAddress = wfRFC822Phrase( $name ) . ' <' . $wgUser->getEmail() . '>';
286 if( $wgEnotifRevealEditorAddress
287 && ( $wgUser->getEmail() != '' )
288 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
289 if( $wgEnotifFromEditor ) {
290 $from = $editorAddress;
291 } else {
292 $from = $adminAddress;
293 $replyto = $editorAddress;
294 }
295 $keys['$PAGEEDITORNAMEANDEMAILADDR'] = $editorAddress;
296 } else {
297 $from = $adminAddress;
298 $replyto = $wgNoReplyAddress;
299 $keys['$PAGEEDITORNAMEANDEMAILADDR'] = $replyto;
300 }
301
302 if( $wgUser->isIP( $name ) ) {
303 #real anon (user:xxx.xxx.xxx.xxx)
304 $anon = $name . ' (anonymous user)';
305 $anonUrl = wfUrlencode( $name ) . ' (anonymous user)';
306 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
307
308 $keys['$PAGEEDITOR_RAWURL'] = $anonUrl;
309 $keys['%24PAGEEDITOR_RAWURL'] = $anonUrl;
310 $keys['%24PAGEEDITORE'] = $anon;
311 $keys['$PAGEEDITORE'] = $anon;
312 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
313 } else {
314 $subject = str_replace('$PAGEEDITOR', $name, $subject);
315 $keys['$PAGEEDITOR_RAWURL'] = wfUrlencode( $name );
316 $keys['%24PAGEEDITOR_RAWURL'] = wfUrlencode( $name );
317 $keys['%24PAGEEDITORE'] = $wgUser->getTitleKey();
318 $keys['$PAGEEDITORE'] = $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->to = $to;
325 $this->from = $from;
326 $this->replyto = $replyto;
327 $this->subject = $subject;
328 $this->body = $body;
329 }
330
331
332
333 /**
334 * Does the per-user customizations to a notification e-mail (name,
335 * timestamp in proper timezone, etc) and sends it out.
336 * Returns true if the mail was sent successfully.
337 *
338 * @param User $watchingUser
339 * @param object $mail
340 * @return bool
341 * @access private
342 */
343 function composeAndSendPersonalisedMail( $watchingUser ) {
344 global $wgLang;
345 // From the PHP manual:
346 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
347 // The mail command will not parse this properly while talking with the MTA.
348 $to = $watchingUser->getEmail();
349 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
350 $body = str_replace( '$WATCHINGUSEREMAILADDR', $watchingUser->getEmail(), $body );
351
352 $timecorrection = $watchingUser->getOption( 'timecorrection' );
353 if( !$timecorrection ) {
354 # fail safe - I prefer it. TomGries
355 $timecorrection = '00:00';
356 }
357 # $PAGEEDITDATE is the time and date of the page change
358 # expressed in terms of individual local time of the notification
359 # recipient, i.e. watching user
360 $body = str_replace('$PAGEEDITDATE',
361 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
362 $body);
363
364 $error = userMailer( $to, $this->from, $this->subject, $body, $this->replyto );
365 return ($error == '');
366 }
367
368 } # end of class EmailNotification
369 ?>