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 $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
105 global $wgEnotifMaxRecips;
107 if (is_array( $wgSMTP )) {
108 require_once( 'Mail.php' );
110 $msgid = str_replace(" ", "_", microtime());
111 if (function_exists('posix_getpid'))
112 $msgid .= '.' . posix_getpid();
117 $dest[] = $u->address
;
119 $dest = $to->address
;
121 $headers['From'] = $from->toString();
123 if ($wgEnotifImpersonal)
124 $headers['To'] = 'undisclosed-recipients:;';
126 $headers['To'] = $to->toString();
129 $headers['Reply-To'] = $replyto->toString();
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';
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();
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);
155 return $mail_object->send($dest, $headers, $body);
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)
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 );
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();
176 $headers .= "{$endl}Reply-To: " . $replyto->toString();
180 set_error_handler( 'mailErrorHandler' );
181 wfDebug( "Sending mail via internal mail() function\n" );
183 if (function_exists('mail'))
185 foreach ($to as $recip)
186 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
188 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
190 $wgErrorString = 'PHP is not configured to send mail';
193 restore_error_handler();
195 if ( $wgErrorString ) {
196 wfDebug( "Error sending mail: $wgErrorString\n" );
197 return $wgErrorString;
199 //mail function only tells if there's an error
200 wfDebug( "Error sending mail\n" );
201 return 'mailer error';
211 * Get the mail error message in global $wgErrorString
213 * @param $code Integer: error number
214 * @param $string String: error message
216 function mailErrorHandler( $code, $string ) {
217 global $wgErrorString;
218 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
223 * This module processes the email notifications when the current page is
224 * changed. It looks up the table watchlist to find out which users are watching
227 * The current implementation sends independent emails to each watching user for
228 * the following reason:
230 * - Each watching user will be notified about the page edit time expressed in
231 * his/her local time (UTC is shown additionally). To achieve this, we need to
232 * find the individual timeoffset of each watching user from the preferences..
234 * Suggested improvement to slack down the number of sent emails: We could think
235 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
236 * same timeoffset in their preferences.
238 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
242 class EmailNotification
{
246 var $to, $subject, $body, $replyto, $from;
247 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
251 function notifyOnPageChange($editor, &$title, $timestamp, $summary, $minorEdit, $oldid = false) {
252 global $wgEnotifUseJobQ;
254 if( $title->getNamespace() < 0 )
257 if ($wgEnotifUseJobQ) {
259 "editor" => $editor->getName(),
260 "timestamp" => $timestamp,
261 "summary" => $summary,
262 "minorEdit" => $minorEdit,
264 $job = new EnotifNotifyJob( $title, $params );
267 $this->actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
274 * @param $title Title object
278 * @param $oldid (default: false)
280 function actuallyNotifyOnPageChange($editor, &$title, $timestamp, $summary, $minorEdit, $oldid=false) {
282 # we use $wgEmergencyContact as sender's address
283 global $wgEnotifWatchlist;
284 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
285 global $wgEnotifImpersonal;
287 $fname = 'UserMailer::notifyOnPageChange';
288 wfProfileIn( $fname );
290 # The following code is only run, if several conditions are met:
291 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
292 # 2. minor edits (changes) are only regarded if the global flag indicates so
294 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK
);
295 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
296 $enotifwatchlistpage = $wgEnotifWatchlist;
298 $this->title
=& $title;
299 $this->timestamp
= $timestamp;
300 $this->summary
= $summary;
301 $this->minorEdit
= $minorEdit;
302 $this->oldid
= $oldid;
303 $this->composeCommonMailtext($editor);
305 $impersonals = array();
307 if ( (!$minorEdit ||
$wgEnotifMinorEdits) ) {
308 if( $wgEnotifWatchlist ) {
309 // Send updates to watchers other than the current editor
310 $userCondition = 'wl_user <> ' . intval( $editor->getId() );
311 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK
) {
312 $targetUser = User
::newFromName( $title->getText() );
313 if( is_null( $targetUser ) ) {
314 wfDebug( "$fname: user-talk-only mode; no such user\n" );
315 $userCondition = false;
316 } elseif( $targetUser->getId() == $editor->getId() ) {
317 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
318 $userCondition = false;
320 // Don't notify anyone other than the owner of the talk page
321 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
324 // Notifications disabled
325 $userCondition = false;
327 if( $userCondition ) {
328 $dbr = wfGetDB( DB_MASTER
);
330 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
332 'wl_title' => $title->getDBkey(),
333 'wl_namespace' => $title->getNamespace(),
335 'wl_notificationtimestamp IS NULL',
338 # if anyone is watching ... set up the email message text which is
339 # common for all receipients ...
340 if ( $dbr->numRows( $res ) > 0 ) {
342 $watchingUser = new User();
344 # ... now do for all watching users ... if the options fit
345 for ($i = 1; $i <= $dbr->numRows( $res ); $i++
) {
347 $wuser = $dbr->fetchObject( $res );
348 $watchingUser->setID($wuser->wl_user
);
350 if ( ( ( $enotifwatchlistpage
351 && $watchingUser->getOption('enotifwatchlistpages') )
352 ||
( $enotifusertalkpage
353 && $watchingUser->getOption('enotifusertalkpages')
354 && $title->equals( $watchingUser->getTalkPage() ) ) )
356 ||
( $wgEnotifMinorEdits
357 && $watchingUser->getOption('enotifminoredits') ) )
358 && ( $watchingUser->isEmailConfirmed() ) ) {
359 # ... adjust remaining text and page edit time placeholders
360 # which needs to be personalized for each user
361 if ($wgEnotifImpersonal)
362 $impersonals[] = $watchingUser;
364 $this->composeAndSendPersonalisedMail( $watchingUser );
366 } # if the watching user has an email address in the preferences
369 } # if anyone is watching
370 } # if $wgEnotifWatchlist = true
372 global $wgUsersNotifedOnAllChanges;
373 foreach ( $wgUsersNotifedOnAllChanges as $name ) {
374 $user = User
::newFromName( $name );
375 if ($wgEnotifImpersonal)
376 $impersonals[] = $user;
378 $this->composeAndSendPersonalisedMail( $user );
381 $this->composeAndSendImpersonalMail($impersonals);
383 if ( $wgShowUpdatedMarker ||
$wgEnotifWatchlist ) {
384 # mark the changed watch-listed page with a timestamp, so that the page is
385 # listed with an "updated since your last visit" icon in the watch list, ...
386 $dbw = wfGetDB( DB_MASTER
);
387 $success = $dbw->update( 'watchlist',
389 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
390 ), array( /* WHERE */
391 'wl_title' => $title->getDBkey(),
392 'wl_namespace' => $title->getNamespace(),
393 'wl_notificationtimestamp IS NULL'
394 ), 'UserMailer::NotifyOnChange'
396 # FIXME what do we do on failure ?
399 wfProfileOut( $fname );
400 } # function NotifyOnChange
405 function composeCommonMailtext($editor) {
406 global $wgEmergencyContact, $wgNoReplyAddress;
407 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
408 global $wgEnotifImpersonal;
410 $summary = ($this->summary
== '') ?
' - ' : $this->summary
;
411 $medit = ($this->minorEdit
) ?
wfMsg( 'minoredit' ) : '';
413 # You as the WikiAdmin and Sysops can make use of plenty of
414 # named variables when composing your notification emails while
415 # simply editing the Meta pages
417 $subject = wfMsgForContent( 'enotif_subject' );
418 $body = wfMsgForContent( 'enotif_body' );
419 $from = ''; /* fail safe */
420 $replyto = ''; /* fail safe */
423 # regarding the use of oldid as an indicator for the last visited version, see also
424 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
425 # However, in the case of a new page which is already watched, we have no previous version to compare
427 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
428 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
429 $keys['$OLDID'] = $this->oldid
;
430 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
432 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
433 # clear $OLDID placeholder in the message template
434 $keys['$OLDID'] = '';
435 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
438 if ($wgEnotifImpersonal && $this->oldid
)
440 * For impersonal mail, show a diff link to the last
443 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
444 $this->title
->getFullURL("oldid={$this->oldid}&diff=prev"));
446 $body = strtr( $body, $keys );
447 $pagetitle = $this->title
->getPrefixedText();
448 $keys['$PAGETITLE'] = $pagetitle;
449 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
451 $keys['$PAGEMINOREDIT'] = $medit;
452 $keys['$PAGESUMMARY'] = $summary;
454 $subject = strtr( $subject, $keys );
456 # Reveal the page editor's address as REPLY-TO address only if
457 # the user has not opted-out and the option is enabled at the
458 # global configuration level.
459 $name = $editor->getName();
460 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
461 $editorAddress = new MailAddress( $editor );
462 if( $wgEnotifRevealEditorAddress
463 && ( $editor->getEmail() != '' )
464 && $editor->getOption( 'enotifrevealaddr' ) ) {
465 if( $wgEnotifFromEditor ) {
466 $from = $editorAddress;
468 $from = $adminAddress;
469 $replyto = $editorAddress;
472 $from = $adminAddress;
473 $replyto = new MailAddress( $wgNoReplyAddress );
476 if( $editor->isIP( $name ) ) {
477 #real anon (user:xxx.xxx.xxx.xxx)
478 $utext = wfMsgForContent('enotif_anon_editor', $name);
479 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
480 $keys['$PAGEEDITOR'] = $utext;
481 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
483 $subject = str_replace('$PAGEEDITOR', $name, $subject);
484 $keys['$PAGEEDITOR'] = $name;
485 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
486 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
488 $userPage = $editor->getUserPage();
489 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
490 $body = strtr( $body, $keys );
491 $body = wordwrap( $body, 72 );
493 # now save this as the constant user-independent part of the message
495 $this->replyto
= $replyto;
496 $this->subject
= $subject;
501 * Does the per-user customizations to a notification e-mail (name,
502 * timestamp in proper timezone, etc) and sends it out.
503 * Returns true if the mail was sent successfully.
505 * @param User $watchingUser
506 * @param object $mail
510 function composeAndSendPersonalisedMail( $watchingUser ) {
512 // From the PHP manual:
513 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
514 // The mail command will not parse this properly while talking with the MTA.
515 $to = new MailAddress( $watchingUser );
516 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body
);
518 $timecorrection = $watchingUser->getOption( 'timecorrection' );
520 # $PAGEEDITDATE is the time and date of the page change
521 # expressed in terms of individual local time of the notification
522 # recipient, i.e. watching user
523 $body = str_replace('$PAGEEDITDATE',
524 $wgLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
527 return userMailer($to, $this->from
, $this->subject
, $body, $this->replyto
);
531 * Same as composeAndSendPersonalisedMail but does impersonal mail
532 * suitable for bulk mailing. Takes an array of users.
534 function composeAndSendImpersonalMail($users) {
541 foreach ($users as $user)
542 $to[] = new MailAddress($user);
545 array( '$WATCHINGUSERNAME',
547 array( wfMsgForContent('enotif_impersonal_salutation'),
548 $wgLang->timeanddate($this->timestamp
, true, false, false)),
551 return userMailer($to, $this->from
, $this->subject
, $body, $this->replyto
);
554 } # end of class EmailNotification