4 * Copyright (C) 2004 Thomas Gries <mail@tgries.de>
5 * http://www.mediawiki.org/
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.
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.
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
22 * @author <brion@pobox.com>
23 * @author <mail@tgries.de>
28 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
30 function wfRFC822Phrase( $phrase ) {
31 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
32 return '"' . $phrase . '"';
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.
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
45 function __construct( $address, $name=null ) {
46 if( is_object( $address ) && $address instanceof User
) {
47 $this->address
= $address->getEmail();
48 $this->name
= $address->getName();
50 $this->address
= strval( $address );
51 $this->name
= strval( $name );
56 * Return formatted and quoted address to insert into SMTP headers
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 . '"';
68 return "$quoted <{$this->address}>";
70 return $this->address
;
75 function send_mail($mailer, $dest, $headers, $body)
77 $mailResult =& $mailer->send($dest, $headers, $body);
79 # Based on the result return an error string,
80 if ($mailResult === true) {
82 } elseif (is_object($mailResult)) {
83 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
84 return $mailResult->getMessage();
86 wfDebug( "PEAR::Mail failed, unknown error result\n" );
87 return 'Mail object return unknown error.';
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.
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).
103 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
104 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
105 global $wgEnotifMaxRecips;
107 if (is_array( $wgSMTP )) {
108 require_once( 'Mail.php' );
115 $dest[] = $u->address
;
117 $dest = $to->address
;
119 $headers['From'] = $from->toString();
121 if ($wgEnotifImpersonal)
122 $headers['To'] = 'undisclosed-recipients:;';
124 $headers['To'] = $to->toString();
127 $headers['Reply-To'] = $replyto->toString();
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';
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();
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, $chunk, $headers, $body);
153 return $mail_object->send($dest, $headers, $body);
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)
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 );
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();
174 $headers .= "{$endl}Reply-To: " . $replyto->toString();
178 set_error_handler( 'mailErrorHandler' );
179 wfDebug( "Sending mail via internal mail() function\n" );
182 foreach ($to as $recip)
183 mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
185 mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
187 restore_error_handler();
189 if ( $wgErrorString ) {
190 wfDebug( "Error sending mail: $wgErrorString\n" );
192 return $wgErrorString;
197 * Get the mail error message in global $wgErrorString
199 * @param $code Integer: error number
200 * @param $string String: error message
202 function mailErrorHandler( $code, $string ) {
203 global $wgErrorString;
204 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
209 * This module processes the email notifications when the current page is
210 * changed. It looks up the table watchlist to find out which users are watching
213 * The current implementation sends independent emails to each watching user for
214 * the following reason:
216 * - Each watching user will be notified about the page edit time expressed in
217 * his/her local time (UTC is shown additionally). To achieve this, we need to
218 * find the individual timeoffset of each watching user from the preferences..
220 * Suggested improvement to slack down the number of sent emails: We could think
221 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
222 * same timeoffset in their preferences.
224 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
228 class EmailNotification
{
232 var $to, $subject, $body, $replyto, $from;
233 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
239 * @param $title Title object
243 * @param $oldid (default: false)
245 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
247 # we use $wgEmergencyContact as sender's address
248 global $wgUser, $wgEnotifWatchlist;
249 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
250 global $wgEnotifImpersonal;
252 $fname = 'UserMailer::notifyOnPageChange';
253 wfProfileIn( $fname );
255 # The following code is only run, if several conditions are met:
256 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
257 # 2. minor edits (changes) are only regarded if the global flag indicates so
259 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK
);
260 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
261 $enotifwatchlistpage = $wgEnotifWatchlist;
263 $this->title
=& $title;
264 $this->timestamp
= $timestamp;
265 $this->summary
= $summary;
266 $this->minorEdit
= $minorEdit;
267 $this->oldid
= $oldid;
268 $this->composeCommonMailtext();
270 $impersonals = array();
272 if ( (!$minorEdit ||
$wgEnotifMinorEdits) ) {
273 if( $wgEnotifWatchlist ) {
274 // Send updates to watchers other than the current editor
275 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
276 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK
) {
277 $targetUser = User
::newFromName( $title->getText() );
278 if( is_null( $targetUser ) ) {
279 wfDebug( "$fname: user-talk-only mode; no such user\n" );
280 $userCondition = false;
281 } elseif( $targetUser->getId() == $wgUser->getId() ) {
282 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
283 $userCondition = false;
285 // Don't notify anyone other than the owner of the talk page
286 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
289 // Notifications disabled
290 $userCondition = false;
292 if( $userCondition ) {
293 $dbr = wfGetDB( DB_MASTER
);
295 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
297 'wl_title' => $title->getDBkey(),
298 'wl_namespace' => $title->getNamespace(),
300 'wl_notificationtimestamp IS NULL',
303 # if anyone is watching ... set up the email message text which is
304 # common for all receipients ...
305 if ( $dbr->numRows( $res ) > 0 ) {
307 $watchingUser = new User();
309 # ... now do for all watching users ... if the options fit
310 for ($i = 1; $i <= $dbr->numRows( $res ); $i++
) {
312 $wuser = $dbr->fetchObject( $res );
313 $watchingUser->setID($wuser->wl_user
);
315 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
316 ( $enotifusertalkpage
317 && $watchingUser->getOption('enotifusertalkpages')
318 && $title->equals( $watchingUser->getTalkPage() ) )
319 && (!$minorEdit ||
($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
320 && ($watchingUser->isEmailConfirmed() ) ) {
321 # ... adjust remaining text and page edit time placeholders
322 # which needs to be personalized for each user
323 if ($wgEnotifImpersonal)
324 $impersonals[] = $watchingUser;
326 $this->composeAndSendPersonalisedMail( $watchingUser );
328 } # if the watching user has an email address in the preferences
331 } # if anyone is watching
332 } # if $wgEnotifWatchlist = true
334 global $wgUsersNotifedOnAllChanges;
335 foreach ( $wgUsersNotifedOnAllChanges as $name ) {
336 $user = User
::newFromName( $name );
337 if ($wgEnotifImpersonal)
338 $impersonals[] = $user;
340 $this->composeAndSendPersonalisedMail( $user );
343 $this->composeAndSendImpersonalMail($impersonals);
345 if ( $wgShowUpdatedMarker ||
$wgEnotifWatchlist ) {
346 # mark the changed watch-listed page with a timestamp, so that the page is
347 # listed with an "updated since your last visit" icon in the watch list, ...
348 $dbw = wfGetDB( DB_MASTER
);
349 $success = $dbw->update( 'watchlist',
351 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
352 ), array( /* WHERE */
353 'wl_title' => $title->getDBkey(),
354 'wl_namespace' => $title->getNamespace(),
355 ), 'UserMailer::NotifyOnChange'
357 # FIXME what do we do on failure ?
359 wfProfileOut( $fname );
360 } # function NotifyOnChange
365 function composeCommonMailtext() {
366 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
367 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
368 global $wgEnotifImpersonal;
370 $summary = ($this->summary
== '') ?
' - ' : $this->summary
;
371 $medit = ($this->minorEdit
) ?
wfMsg( 'minoredit' ) : '';
373 # You as the WikiAdmin and Sysops can make use of plenty of
374 # named variables when composing your notification emails while
375 # simply editing the Meta pages
377 $subject = wfMsgForContent( 'enotif_subject' );
378 $body = wfMsgForContent( 'enotif_body' );
379 $from = ''; /* fail safe */
380 $replyto = ''; /* fail safe */
383 # regarding the use of oldid as an indicator for the last visited version, see also
384 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
385 # However, in the case of a new page which is already watched, we have no previous version to compare
387 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
388 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
389 $keys['$OLDID'] = $this->oldid
;
390 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
392 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
393 # clear $OLDID placeholder in the message template
394 $keys['$OLDID'] = '';
395 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
398 if ($wgEnotifImpersonal && $this->oldid
)
400 * For impersonal mail, show a diff link to the last
403 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
404 $this->title
->getFullURL("oldid={$this->oldid}&diff=prev"));
406 $body = strtr( $body, $keys );
407 $pagetitle = $this->title
->getPrefixedText();
408 $keys['$PAGETITLE'] = $pagetitle;
409 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
411 $keys['$PAGEMINOREDIT'] = $medit;
412 $keys['$PAGESUMMARY'] = $summary;
414 $subject = strtr( $subject, $keys );
416 # Reveal the page editor's address as REPLY-TO address only if
417 # the user has not opted-out and the option is enabled at the
418 # global configuration level.
419 $name = $wgUser->getName();
420 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
421 $editorAddress = new MailAddress( $wgUser );
422 if( $wgEnotifRevealEditorAddress
423 && ( $wgUser->getEmail() != '' )
424 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
425 if( $wgEnotifFromEditor ) {
426 $from = $editorAddress;
428 $from = $adminAddress;
429 $replyto = $editorAddress;
432 $from = $adminAddress;
433 $replyto = new MailAddress( $wgNoReplyAddress );
436 if( $wgUser->isIP( $name ) ) {
437 #real anon (user:xxx.xxx.xxx.xxx)
438 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
439 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
440 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
442 $subject = str_replace('$PAGEEDITOR', $name, $subject);
443 $keys['$PAGEEDITOR'] = $name;
444 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
445 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
447 $userPage = $wgUser->getUserPage();
448 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
449 $body = strtr( $body, $keys );
450 $body = wordwrap( $body, 72 );
452 # now save this as the constant user-independent part of the message
454 $this->replyto
= $replyto;
455 $this->subject
= $subject;
460 * Does the per-user customizations to a notification e-mail (name,
461 * timestamp in proper timezone, etc) and sends it out.
462 * Returns true if the mail was sent successfully.
464 * @param User $watchingUser
465 * @param object $mail
469 function composeAndSendPersonalisedMail( $watchingUser ) {
471 // From the PHP manual:
472 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
473 // The mail command will not parse this properly while talking with the MTA.
474 $to = new MailAddress( $watchingUser );
475 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body
);
477 $timecorrection = $watchingUser->getOption( 'timecorrection' );
479 # $PAGEEDITDATE is the time and date of the page change
480 # expressed in terms of individual local time of the notification
481 # recipient, i.e. watching user
482 $body = str_replace('$PAGEEDITDATE',
483 $wgLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
486 return $this->send_or_queue_mail($to, $this->from
, $this->subject
, $body, $this->replyto
);
490 * Same as composeAndSendPersonalisedMail but does impersonal mail
491 * suitable for bulk mailing. Takes an array of users.
493 function composeAndSendImpersonalMail($users) {
500 foreach ($users as $user)
501 $to[] = new MailAddress($user);
504 array( '$WATCHINGUSERNAME',
506 array( wfMsgForContent('enotif_impersonal_salutation'),
507 $wgLang->timeanddate($this->timestamp
, true, false, false)),
510 return $this->send_or_queue_mail($to, $this->from
, $this->subject
, $body, $this->replyto
);
514 * Either send an email or add it to the job queue to be sent later.
516 function send_or_queue_mail($to, $from, $subj, $body, $replyto) {
517 global $wgEnotifUseJobQ, $wgEnotifMaxRecips;
519 if (!$wgEnotifUseJobQ)
520 return '' != userMailer($to, $from, $subj, $body, $replyto);
525 $chunks = array_chunk($to, $wgEnotifMaxRecips);
526 foreach ($chunks as $chunk) {
527 $job = new EmaillingJob(array(
532 'replyto' => $replyto));
538 } # end of class EmailNotification