enotif should have a way to send bulk mail without customisations, for large sites
[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 */
26
27 /**
28 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
29 */
30 function wfRFC822Phrase( $phrase ) {
31 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
32 return '"' . $phrase . '"';
33 }
34
35 /**
36 * Stores a single person's name and email address.
37 * These are passed in via the constructor, and will be returned in SMTP
38 * header format when requested.
39 */
40 class MailAddress {
41 /**
42 * @param mixed $address String with an email address, or a User object
43 * @param string $name Human-readable name if a string address is given
44 */
45 function __construct( $address, $name=null ) {
46 if( is_object( $address ) && $address instanceof User ) {
47 $this->address = $address->getEmail();
48 $this->name = $address->getName();
49 } else {
50 $this->address = strval( $address );
51 $this->name = strval( $name );
52 }
53 }
54
55 /**
56 * Return formatted and quoted address to insert into SMTP headers
57 * @return string
58 */
59 function toString() {
60 # PHP's mail() implementation under Windows is somewhat shite, and
61 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
62 # so don't bother generating them
63 if( $this->name != '' && !wfIsWindows() ) {
64 $quoted = wfQuotedPrintable( $this->name );
65 if( strpos( $quoted, '.' ) !== false ) {
66 $quoted = '"' . $quoted . '"';
67 }
68 return "$quoted <{$this->address}>";
69 } else {
70 return $this->address;
71 }
72 }
73 }
74
75 function send_mail($mailer, $dest, $headers, $body)
76 {
77 $mailResult =& $mailer->send($dest, $headers, $body);
78
79 # Based on the result return an error string,
80 if ($mailResult === true) {
81 return '';
82 } elseif (is_object($mailResult)) {
83 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
84 return $mailResult->getMessage();
85 } else {
86 wfDebug( "PEAR::Mail failed, unknown error result\n" );
87 return 'Mail object return unknown error.';
88 }
89 }
90
91 /**
92 * This function will perform a direct (authenticated) login to
93 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
94 * array of parameters. It requires PEAR:Mail to do that.
95 * Otherwise it just uses the standard PHP 'mail' function.
96 *
97 * @param $to MailAddress: recipient's email
98 * @param $from MailAddress: sender's email
99 * @param $subject String: email's subject.
100 * @param $body String: email's text.
101 * @param $replyto String: optional reply-to email (default: null).
102 */
103 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
104 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
105 global $wgEnotifMaxRecips;
106
107 if (is_array( $wgSMTP )) {
108 require_once( 'Mail.php' );
109
110 $timestamp = time();
111
112 if (is_array($to)) {
113 $dest = array();
114 foreach ($to as $u)
115 $dest[] = $u->address;
116 } else
117 $dest = $to->address;
118
119 $headers['From'] = $from->toString();
120
121 if ($wgEnotifImpersonal)
122 $headers['To'] = 'undisclosed-recipients:;';
123 else
124 $headers['To'] = $to->toString();
125
126 if ( $replyto ) {
127 $headers['Reply-To'] = $replyto->toString();
128 }
129 $headers['Subject'] = wfQuotedPrintable( $subject );
130 $headers['Date'] = date( 'r' );
131 $headers['MIME-Version'] = '1.0';
132 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
133 $headers['Content-transfer-encoding'] = '8bit';
134 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>'; // FIXME
135 $headers['X-Mailer'] = 'MediaWiki mailer';
136
137 // Create the mail object using the Mail::factory method
138 $mail_object =& Mail::factory('smtp', $wgSMTP);
139 if( PEAR::isError( $mail_object ) ) {
140 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
141 return $mail_object->getMessage();
142 }
143
144 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
145 if (is_array($dest)) {
146 $chunks = array_chunk($dest, $wgEnotifMaxRecips);
147 foreach ($chunks as $chunk) {
148 $e = send_mail($mail_object, $dest, $headers, $body);
149 if ($e != '')
150 return $e;
151 }
152 } else
153 return $mail_object->send($dest, $headers, $body);
154
155 } else {
156 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
157 # (fifth parameter of the PHP mail function, see some lines below)
158
159 # Line endings need to be different on Unix and Windows due to
160 # the bug described at http://trac.wordpress.org/ticket/2603
161 if ( wfIsWindows() ) {
162 $body = str_replace( "\n", "\r\n", $body );
163 $endl = "\r\n";
164 } else {
165 $endl = "\n";
166 }
167 $headers =
168 "MIME-Version: 1.0$endl" .
169 "Content-type: text/plain; charset={$wgOutputEncoding}$endl" .
170 "Content-Transfer-Encoding: 8bit$endl" .
171 "X-Mailer: MediaWiki mailer$endl".
172 'From: ' . $from->toString();
173 if ($replyto) {
174 $headers .= "{$endl}Reply-To: " . $replyto->toString();
175 }
176
177 $dest = $to->toString();
178
179 $wgErrorString = '';
180 set_error_handler( 'mailErrorHandler' );
181 wfDebug( "Sending mail via internal mail() function to $dest\n" );
182 mail( $dest, wfQuotedPrintable( $subject ), $body, $headers );
183 restore_error_handler();
184
185 if ( $wgErrorString ) {
186 wfDebug( "Error sending mail: $wgErrorString\n" );
187 }
188 return $wgErrorString;
189 }
190 }
191
192 /**
193 * Get the mail error message in global $wgErrorString
194 *
195 * @param $code Integer: error number
196 * @param $string String: error message
197 */
198 function mailErrorHandler( $code, $string ) {
199 global $wgErrorString;
200 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
201 }
202
203
204 /**
205 * This module processes the email notifications when the current page is
206 * changed. It looks up the table watchlist to find out which users are watching
207 * that page.
208 *
209 * The current implementation sends independent emails to each watching user for
210 * the following reason:
211 *
212 * - Each watching user will be notified about the page edit time expressed in
213 * his/her local time (UTC is shown additionally). To achieve this, we need to
214 * find the individual timeoffset of each watching user from the preferences..
215 *
216 * Suggested improvement to slack down the number of sent emails: We could think
217 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
218 * same timeoffset in their preferences.
219 *
220 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
221 *
222 *
223 */
224 class EmailNotification {
225 /**@{{
226 * @private
227 */
228 var $to, $subject, $body, $replyto, $from;
229 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
230
231 /**@}}*/
232
233 /**
234 * @todo document
235 * @param $title Title object
236 * @param $timestamp
237 * @param $summary
238 * @param $minorEdit
239 * @param $oldid (default: false)
240 */
241 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
242
243 # we use $wgEmergencyContact as sender's address
244 global $wgUser, $wgEnotifWatchlist;
245 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
246 global $wgEnotifImpersonal;
247
248 $fname = 'UserMailer::notifyOnPageChange';
249 wfProfileIn( $fname );
250
251 # The following code is only run, if several conditions are met:
252 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
253 # 2. minor edits (changes) are only regarded if the global flag indicates so
254
255 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
256 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
257 $enotifwatchlistpage = $wgEnotifWatchlist;
258
259 $this->title =& $title;
260 $this->timestamp = $timestamp;
261 $this->summary = $summary;
262 $this->minorEdit = $minorEdit;
263 $this->oldid = $oldid;
264 $this->composeCommonMailtext();
265
266 $impersonals = array();
267
268 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
269 if( $wgEnotifWatchlist ) {
270 // Send updates to watchers other than the current editor
271 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
272 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK ) {
273 $targetUser = User::newFromName( $title->getText() );
274 if( is_null( $targetUser ) ) {
275 wfDebug( "$fname: user-talk-only mode; no such user\n" );
276 $userCondition = false;
277 } elseif( $targetUser->getId() == $wgUser->getId() ) {
278 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
279 $userCondition = false;
280 } else {
281 // Don't notify anyone other than the owner of the talk page
282 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
283 }
284 } else {
285 // Notifications disabled
286 $userCondition = false;
287 }
288 if( $userCondition ) {
289 $dbr = wfGetDB( DB_MASTER );
290
291 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
292 array(
293 'wl_title' => $title->getDBkey(),
294 'wl_namespace' => $title->getNamespace(),
295 $userCondition,
296 'wl_notificationtimestamp IS NULL',
297 ), $fname );
298
299 # if anyone is watching ... set up the email message text which is
300 # common for all receipients ...
301 if ( $dbr->numRows( $res ) > 0 ) {
302
303 $watchingUser = new User();
304
305 # ... now do for all watching users ... if the options fit
306 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
307
308 $wuser = $dbr->fetchObject( $res );
309 $watchingUser->setID($wuser->wl_user);
310
311 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
312 ( $enotifusertalkpage
313 && $watchingUser->getOption('enotifusertalkpages')
314 && $title->equals( $watchingUser->getTalkPage() ) )
315 && (!$minorEdit || ($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
316 && ($watchingUser->isEmailConfirmed() ) ) {
317 # ... adjust remaining text and page edit time placeholders
318 # which needs to be personalized for each user
319 if ($wgEnotifImpersonal)
320 $impersonals[] = $watchingUser;
321 else
322 $this->composeAndSendPersonalisedMail( $watchingUser );
323
324 } # if the watching user has an email address in the preferences
325 }
326 }
327 } # if anyone is watching
328 } # if $wgEnotifWatchlist = true
329
330 global $wgUsersNotifedOnAllChanges;
331 foreach ( $wgUsersNotifedOnAllChanges as $name ) {
332 $user = User::newFromName( $name );
333 if ($wgEnotifImpersonal)
334 $impersonals[] = $user;
335 else
336 $this->composeAndSendPersonalisedMail( $user );
337 }
338
339 $this->composeAndSendImpersonalMail($impersonals);
340
341 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
342 # mark the changed watch-listed page with a timestamp, so that the page is
343 # listed with an "updated since your last visit" icon in the watch list, ...
344 $dbw = wfGetDB( DB_MASTER );
345 $success = $dbw->update( 'watchlist',
346 array( /* SET */
347 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
348 ), array( /* WHERE */
349 'wl_title' => $title->getDBkey(),
350 'wl_namespace' => $title->getNamespace(),
351 ), 'UserMailer::NotifyOnChange'
352 );
353 # FIXME what do we do on failure ?
354 }
355 wfProfileOut( $fname );
356 } # function NotifyOnChange
357
358 /**
359 * @private
360 */
361 function composeCommonMailtext() {
362 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
363 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
364 global $wgEnotifImpersonal;
365
366 $summary = ($this->summary == '') ? ' - ' : $this->summary;
367 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
368
369 # You as the WikiAdmin and Sysops can make use of plenty of
370 # named variables when composing your notification emails while
371 # simply editing the Meta pages
372
373 $subject = wfMsgForContent( 'enotif_subject' );
374 $body = wfMsgForContent( 'enotif_body' );
375 $from = ''; /* fail safe */
376 $replyto = ''; /* fail safe */
377 $keys = array();
378
379 # regarding the use of oldid as an indicator for the last visited version, see also
380 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
381 # However, in the case of a new page which is already watched, we have no previous version to compare
382 if( $this->oldid ) {
383 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
384 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
385 $keys['$OLDID'] = $this->oldid;
386 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
387 } else {
388 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
389 # clear $OLDID placeholder in the message template
390 $keys['$OLDID'] = '';
391 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
392 }
393
394 if ($wgEnotifImpersonal && $this->oldid)
395 /*
396 * For impersonal mail, show a diff link to the last
397 * revision.
398 */
399 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
400 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
401
402 $body = strtr( $body, $keys );
403 $pagetitle = $this->title->getPrefixedText();
404 $keys['$PAGETITLE'] = $pagetitle;
405 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
406
407 $keys['$PAGEMINOREDIT'] = $medit;
408 $keys['$PAGESUMMARY'] = $summary;
409
410 $subject = strtr( $subject, $keys );
411
412 # Reveal the page editor's address as REPLY-TO address only if
413 # the user has not opted-out and the option is enabled at the
414 # global configuration level.
415 $name = $wgUser->getName();
416 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
417 $editorAddress = new MailAddress( $wgUser );
418 if( $wgEnotifRevealEditorAddress
419 && ( $wgUser->getEmail() != '' )
420 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
421 if( $wgEnotifFromEditor ) {
422 $from = $editorAddress;
423 } else {
424 $from = $adminAddress;
425 $replyto = $editorAddress;
426 }
427 } else {
428 $from = $adminAddress;
429 $replyto = new MailAddress( $wgNoReplyAddress );
430 }
431
432 if( $wgUser->isIP( $name ) ) {
433 #real anon (user:xxx.xxx.xxx.xxx)
434 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
435 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
436 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
437 } else {
438 $subject = str_replace('$PAGEEDITOR', $name, $subject);
439 $keys['$PAGEEDITOR'] = $name;
440 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
441 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
442 }
443 $userPage = $wgUser->getUserPage();
444 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
445 $body = strtr( $body, $keys );
446 $body = wordwrap( $body, 72 );
447
448 # now save this as the constant user-independent part of the message
449 $this->from = $from;
450 $this->replyto = $replyto;
451 $this->subject = $subject;
452 $this->body = $body;
453 }
454
455 /**
456 * Does the per-user customizations to a notification e-mail (name,
457 * timestamp in proper timezone, etc) and sends it out.
458 * Returns true if the mail was sent successfully.
459 *
460 * @param User $watchingUser
461 * @param object $mail
462 * @return bool
463 * @private
464 */
465 function composeAndSendPersonalisedMail( $watchingUser ) {
466 global $wgLang;
467 // From the PHP manual:
468 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
469 // The mail command will not parse this properly while talking with the MTA.
470 $to = new MailAddress( $watchingUser );
471 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
472
473 $timecorrection = $watchingUser->getOption( 'timecorrection' );
474
475 # $PAGEEDITDATE is the time and date of the page change
476 # expressed in terms of individual local time of the notification
477 # recipient, i.e. watching user
478 $body = str_replace('$PAGEEDITDATE',
479 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
480 $body);
481
482 $error = userMailer( $to, $this->from, $this->subject, $body, $this->replyto );
483 return ($error == '');
484 }
485
486 /**
487 * Same as composeAndSendPersonalisedMail but does impersonal mail
488 * suitable for bulk mailing. Takes an array of users.
489 */
490 function composeAndSendImpersonalMail($users) {
491 global $wgLang;
492
493 if (empty($users))
494 return;
495
496 $to = array();
497 foreach ($users as $user)
498 $to[] = new MailAddress($user);
499
500 $body = str_replace(
501 array( '$WATCHINGUSERNAME',
502 '$PAGEEDITDATE'),
503 array( wfMsgForContent('enotif_impersonal_salutation'),
504 $wgLang->timeanddate($this->timestamp, true, false, false)),
505 $this->body);
506 $error = userMailer($to, $this->from, $this->subject, $body, $this->replyto);
507 return $error == '';
508 }
509
510 } # end of class EmailNotification
511 ?>