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