9032eec82a04182cc229b791bb3c997453e25787
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /** Copyright (C) 2004 Thomas Gries <mail@tgries.de>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19 **/
20
21 /**
22 * Provide mail capabilities
23 *
24 * @package MediaWiki
25 */
26
27 function wfQuotedPrintable_name_and_emailaddr( $string ) {
28 /* it takes formats like "name <emailaddr>" into account,
29 for which the partial string "name" will be quoted-printable converted
30 but not "<emailaddr>".
31
32 The php mail() function does not accept the email address partial string
33 to be quotedprintable, it does not accept inputs as quotedprintable("name <emailaddr>") .
34
35 case 1:
36 input: "name <emailaddr> rest"
37 output: "quoted-printable(name) <emailaddr>"
38
39 case 2: (should not happen)
40 input: "<emailaddr> rest"
41 output: "<emailaddr>"
42
43 case 3: (should not happen)
44 input: "name"
45 output: "quoted-printable(name)"
46
47 T. Gries 18.11.2004
48 */
49
50 /* do not quote printable for email address string <emailaddr>, but only for the (leading) string, usually the name */
51 preg_match( '/^([^<]*)?(<([A-z0-9_.-]+([A-z0-9_.-]+)*\@[A-z0-9_-]+([A-z0-9_.-]+)*([A-z.]{2,})+)>)?$/', $string, $part );
52 if ( !isset($part[1]) ) return $part[2];
53 if ( !isset($part[2]) ) return wfQuotedprintable($part[1]);
54 return wfQuotedprintable($part[1]) . $part[2] ;
55 }
56
57 /**
58 * This function will perform a direct (authenticated) login to
59 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
60 * array of parameters. It requires PEAR:Mail to do that.
61 * Otherwise it just uses the standard PHP 'mail' function.
62 *
63 * @param string $to recipient's email
64 * @param string $from sender's email
65 * @param string $subject email's subject
66 * @param string $body email's text
67 */
68 function userMailer( $to, $from, $subject, $body, $replyto=false ) {
69 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEmergencyContact;
70
71 $qto = wfQuotedPrintable_name_and_emailaddr( $to );
72
73 if (is_array( $wgSMTP )) {
74 require_once( 'Mail.php' );
75
76 $timestamp = time();
77
78 $headers['From'] = $from;
79 /* removing to: field as it should be set by the send() function below
80 UNTESTED - Hashar */
81 // $headers['To'] = $qto;
82 /* Reply-To:
83 UNTESTED - Tom Gries */
84 $headers['Reply-To'] = $replyto;
85 $headers['Subject'] = $subject;
86 $headers['MIME-Version'] = '1.0';
87 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
88 $headers['Content-transfer-encoding'] = '8bit';
89 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>';
90 $headers['X-Mailer'] = 'MediaWiki mailer';
91
92 // Create the mail object using the Mail::factory method
93 $mail_object =& Mail::factory('smtp', $wgSMTP);
94
95 $mailResult =& $mail_object->send($to, $headers, $body);
96
97 # Based on the result return an error string,
98 if ($mailResult === true)
99 return '';
100 else if (is_object($mailResult))
101 return $mailResult->getMessage();
102 else
103 return 'Mail object return unknown error.';
104 } else {
105 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
106 # (fifth parameter of the PHP mail function, see some lines below)
107 $headers =
108 "MIME-Version: 1.0\n" .
109 "Content-type: text/plain; charset={$wgOutputEncoding}\n" .
110 "Content-Transfer-Encoding: 8bit\n" .
111 "X-Mailer: MediaWiki mailer\n".
112 'From:' . wfQuotedPrintable_name_and_emailaddr($from) . "\n";
113 if ($replyto) {
114 $headers .= 'Reply-To: '.wfQuotedPrintable_name_and_emailaddr($replyto)."\n";
115 }
116
117 $wgErrorString = '';
118 set_error_handler( 'mailErrorHandler' );
119 # added -f parameter, see PHP manual for the fifth parameter when using the mail function
120 mail( wfQuotedPrintable_name_and_emailaddr($to), $subject, $body, $headers, "-f{$wgEmergencyContact}\n");
121 restore_error_handler();
122
123 return $wgErrorString;
124 }
125 }
126
127 /**
128 *
129 */
130 function mailErrorHandler( $code, $string ) {
131 global $wgErrorString;
132 $wgErrorString = preg_replace( "/^mail\(\): /", "", $string );
133 }
134
135
136 /**
137 * Patch for email notification on page changes T.Gries/M.Arndt 11.09.2004
138 *
139 * This new module processes the email notifications when the current page is changed.
140 * It looks up the table watchlist to find out which users are watching that page.
141 *
142 * The current implementation sends independent emails to each watching user for the following reason:
143 *
144 * - Each watching user will be notified about the page edit time expressed in his/her local time (UTC is shown additionally).
145 * To achieve this, we need to find the individual timeoffset of each watching user from the preferences..
146 *
147 * Suggested improvement to slack down the number of sent emails:
148 * We could think of sending out bulk mails (bcc:user1,user2...) for all these users having the same timeoffset in their preferences.
149 *
150 * - Visit the documentation pages under http://meta.wikipedia.com/Enotif
151 */
152 class EmailNotification {
153 var $to, $subject, $body, $replyto, $from;
154
155 function NotifyOnPageChange($currentUser, $currentPage, $currentNs, $timestamp, $currentSummary, $currentMinorEdit, $oldid=false) {
156
157 # we use $wgEmergencyContact as sender's address
158 global $wgUser, $wgLang, $wgEmergencyContact;
159 global $wgEmailNotificationForWatchlistPages, $wgEmailNotificationForMinorEdits;
160 global $wgEmailNotificationSystembeep, $wgEmailNotificationForUserTalkPages;
161 global $wgEmailNotificationRevealPageEditorAddress;
162 global $wgEmailNotificationMailsSentFromPageEditor;
163 global $wgEmailAuthentication;
164 global $beeped;
165
166 # The following code is only run, if several conditions are met:
167 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
168 # 2. minor edits (changes) are only regarded if the global flag indicates so
169
170 $isUserTalkPage = ($currentNs == NS_USER_TALK);
171 $enotifusertalkpage = ($isUserTalkPage && $wgEmailNotificationForUserTalkPages);
172 $enotifwatchlistpage = (!$isUserTalkPage && $wgEmailNotificationForWatchlistPages);
173
174 if ( ($enotifusertalkpage || $enotifwatchlistpage)
175 && (!$currentMinorEdit || $wgEmailNotificationForMinorEdits) ) {
176
177 $dbr =& wfGetDB( DB_MASTER );
178 extract( $dbr->tableNames( 'watchlist' ) );
179 $sql = "SELECT wl_user FROM $watchlist
180 WHERE wl_title='" . $dbr->strencode($currentPage)."' AND wl_namespace = " . $currentNs .
181 " AND wl_user <>" . $currentUser . " AND wl_notificationtimestamp <= 1";
182 $res = $dbr->query( $sql,'UserMailer::NotifyOnChange');
183
184 if ( $dbr->numRows( $res ) > 0 ) { # if anyone is watching ... set up the email message text which is common for all receipients ...
185
186 # This is a switch for one beep on the server when sending notification mails
187 $beeped = false;
188
189 $article->mTimestamp = $timestamp;
190 $article->mSummary = $currentSummary;
191 $article->mMinorEdit = $currentMinorEdit;
192 $article->mNamespace = $currentNs;
193 $article->mTitle = $currentPage;
194 $article->mOldid = $oldid;
195
196 $mail = $this->composeCommonMailtext( $wgUser, $article );
197 $watchingUser = new User();
198
199 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) { # ... now do for all watching users ... if the options fit
200
201 $wuser = $dbr->fetchObject( $res );
202 $watchingUser->setID($wuser->wl_user);
203 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
204 ( $enotifusertalkpage && $watchingUser->getOption('enotifusertalkpages') )
205 && (!$currentMinorEdit || ($wgEmailNotificationForMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
206 && ($watchingUser->getEmail() != '')
207 && (!$wgEmailAuthentication || ($watchingUser->getEmailAuthenticationtimestamp() != 0 ) ) ) {
208 # ... adjust remaining text and page edit time placeholders
209 # which needs to be personalized for each user
210 $sent = $this->composeAndSendPersonalisedMail( $watchingUser, $mail, $article );
211 /* the beep here beeps once when a watched-listed page is changed */
212 if ($sent && !$beeped && ($wgEmailNotificationSystembeep != '') ) {
213 $last_line = system($wgEmailNotificationSystembeep);
214 $beeped=true;
215 }
216 } # if the watching user has an email address in the preferences
217 # 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, ...
218 # ... no matter, if the watching user has or has not indicated an email address in his/her preferences.
219 # 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
220 $dbw =& wfGetDB( DB_MASTER );
221 $succes = $dbw->update( 'watchlist',
222 array( /* SET */
223 'wl_notificationtimestamp' => $article->mTimestamp
224 ), array( /* WHERE */
225 'wl_title' => $currentPage,
226 'wl_namespace' => $currentNs,
227 'wl_user' => $wuser->wl_user
228 ), 'UserMailer::NotifyOnChange'
229 );
230 } # for every watching user
231 } # if anyone is watching
232 } # if $wgEmailNotificationForWatchlistPages = true
233 } # function NotifyOnChange
234
235 /**
236 * @param User $pageeditorUser
237 * @param Article $article
238 * @access private
239 */
240 function composeCommonMailtext( $pageeditorUser, $article ) {
241 global $wgLang, $wgEmergencyContact;
242 global $wgEmailNotificationRevealPageEditorAddress;
243 global $wgEmailNotificationMailsSentFromPageEditor;
244 global $wgNoReplyAddress;
245
246 $summary = ($article->mSummary == '') ? ' - ' : $article->mSummary;
247 $medit = ($article->mMinorEdit) ? wfMsg( 'minoredit' ) : '';
248
249 # You as the WikiAdmin and Sysops can make use of plenty of
250 # named variables when composing your notification emails while
251 # simply editing the Meta pages
252
253 $to = wfMsg( 'email_notification_to' );
254 $subject = wfMsg( 'email_notification_subject' );
255 $body = wfMsg( 'email_notification_body' );
256 $from = ''; /* fail safe */
257 $replyto = ''; /* fail safe */
258 $keys = array();
259
260 # regarding the use of oldid as an indicator for the last visited version, see also
261 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
262 # However, in the case of a new page which is already watched, we have no previous version to compare
263 if( $article->mOldid ) {
264 $keys['$NEWPAGE'] = wfMsg( 'email_notification_lastvisitedrevisiontext' );
265 $keys['$OLDID'] = $article->mOldid;
266 } else {
267 $keys['$NEWPAGE'] = wfMsg( 'email_notification_newpagetext' );
268 # clear $OLDID placeholder in the message template
269 $keys['$OLDID'] = '';
270 }
271
272 $body = strtr( $body, $keys );
273
274 $pagetitle = $article->mTitle;
275 if( $article->mNamespace != NS_MAIN ) {
276 $pagetitle = $wgLang->getNsText( $article->mNamespace ) . ':' . $pagetitle;
277 }
278 $subject = str_replace( '$PAGETITLE_QP', wfQuotedPrintable( str_replace( '_', ' ', $pagetitle ) ), $subject);
279 $keys['%24PAGETITLE_RAWURL'] = wfUrlencode( $pagetitle );
280 $keys['$PAGETITLE_RAWURL'] = wfUrlencode( $pagetitle );
281 $keys['%24PAGETITLE'] = $pagetitle; # needed for the {{localurl:$PAGETITLE}} in the messagetext, "$" appears here as "%24"
282 $keys['$PAGETITLE'] = $pagetitle;
283 $keys['$PAGETIMESTAMP'] = $article->mTimestamp; # this is the raw internal timestamp - can be useful, too
284 $keys['$PAGEEDITDATEUTC'] = $wgLang->timeanddate( $article->mTimestamp, false, false, false, true );
285 $keys['$PAGEMINOREDIT'] = $medit;
286 $keys['$PAGESUMMARY'] = $summary;
287
288
289 # Reveal the page editor's address as REPLY-TO address only if
290 # the user has not opted-out and the option is enabled at the
291 # global configuration level.
292 $pageeditor_qp = wfQuotedPrintable( $pageeditorUser->getName() );
293 $adminAddress = 'WikiAdmin <' . $wgEmergencyContact . '>';
294 $editorAddress = $pageeditorUser->getName() . ' <' . $pageeditorUser->getEmail() . '>';
295 if( $wgEmailNotificationRevealPageEditorAddress
296 && ( $pageeditorUser->getEmail() != '' )
297 && $pageeditorUser->getOption( 'enotifrevealaddr' ) ) {
298 if( $wgEmailNotificationMailsSentFromPageEditor ) {
299 $from = $editorAddress;
300 } else {
301 $from = $adminAddress;
302 $replyto = $editorAddress;
303 }
304 $keys['$PAGEEDITORNAMEANDEMAILADDR'] = $editorAddress;
305 } else {
306 $from = $adminAddress;
307 $replyto = $wgNoReplyAddress;
308 $keys['$PAGEEDITORNAMEANDEMAILADDR'] = $replyto;
309 }
310
311 if( $pageeditorUser->isIP( $pageeditorUser->getName() ) ) {
312 #real anon (user:xxx.xxx.xxx.xxx)
313 $subject = str_replace('$PAGEEDITOR_QP', 'anonymous user ' . $pageeditorUser->getName(), $subject);
314 $name = $pageeditorUser->getName();
315 $anon = $name . ' (anonymous user)';
316 $anonUrl = wfUrlencode( $name ) . ' (anonymous user)';
317
318 $keys['$PAGEEDITOR_RAWURL'] = $anonUrl;
319 $keys['%24PAGEEDITOR_RAWURL'] = $anonUrl;
320 $keys['%24PAGEEDITORE'] = $anon;
321 $keys['$PAGEEDITORE'] = $anon;
322 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
323 } else {
324 $name = $pageeditorUser->getName();
325 $subject = str_replace('$PAGEEDITOR_QP', $pageeditor_qp, $subject);
326 $keys['$PAGEEDITOR_RAWURL'] = wfUrlencode( $name );
327 $keys['%24PAGEEDITOR_RAWURL'] = wfUrlencode( $name );
328 $keys['%24PAGEEDITORE'] = $pageeditorUser->getTitleKey();
329 $keys['$PAGEEDITORE'] = $pageeditorUser->getTitleKey();
330 $keys['$PAGEEDITOR'] = $pageeditorUser->getName();
331 }
332 $body = strtr( $body, $keys );
333
334 # now save this as the constant user-independent part of the message
335 $this->to = $to;
336 $this->from = $from;
337 $this->replyto = $replyto;
338 $this->subject = $subject;
339 $this->body = $body;
340 return $this;
341 }
342
343
344
345 /**
346 * Does the per-user customizations to a notification e-mail (name,
347 * timestamp in proper timezone, etc) and sends it out.
348 * Returns true if the mail was sent successfully.
349 *
350 * @param User $watchingUser
351 * @param object $mail
352 * @param Article $article
353 * @return bool
354 * @access private
355 */
356 function composeAndSendPersonalisedMail( $watchingUser, $mail, $article ) {
357 global $wgLang;
358
359 $to = $watchingUser->getName() . ' <' . $watchingUser->getEmail() . '>';
360 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $mail->body );
361 $body = str_replace( '$WATCHINGUSEREMAILADDR', $watchingUser->getEmail(), $body );
362
363 $timecorrection = $watchingUser->getOption( 'timecorrection' );
364 if( !$timecorrection ) {
365 # fail safe - I prefer it. TomGries
366 $timecorrection = '00:00';
367 }
368 # $PAGEEDITDATE is the time and date of the page change
369 # expressed in terms of individual local time of the notification
370 # recipient, i.e. watching user
371 $body = str_replace('$PAGEEDITDATE',
372 $wgLang->timeanddate( $article->mTimestamp, true, false, $timecorrection, true),
373 $body);
374
375 $error = userMailer( $to, $mail->from, $mail->subject, $body, $mail->replyto );
376 return ($error == '');
377 }
378
379 } # end of class EmailNotification
380 ?>