3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @author <brion@pobox.com>
19 * @author <mail@tgries.de>
20 * @author Tim Starling
26 * Stores a single person's name and email address.
27 * These are passed in via the constructor, and will be returned in SMTP
28 * header format when requested.
32 * @param mixed $address String with an email address, or a User object
33 * @param string $name Human-readable name if a string address is given
35 function __construct( $address, $name=null ) {
36 if( is_object( $address ) && $address instanceof User
) {
37 $this->address
= $address->getEmail();
38 $this->name
= $address->getName();
40 $this->address
= strval( $address );
41 $this->name
= strval( $name );
46 * Return formatted and quoted address to insert into SMTP headers
50 # PHP's mail() implementation under Windows is somewhat shite, and
51 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
52 # so don't bother generating them
53 if( $this->name
!= '' && !wfIsWindows() ) {
54 $quoted = wfQuotedPrintable( $this->name
);
55 if( strpos( $quoted, '.' ) !== false ||
strpos( $quoted, ',' ) !== false ) {
56 $quoted = '"' . $quoted . '"';
58 return "$quoted <{$this->address}>";
60 return $this->address
;
64 function __toString() {
65 return $this->toString();
71 * Collection of static functions for sending mail
75 * Send mail using a PEAR mailer
77 protected static function sendWithPear($mailer, $dest, $headers, $body)
79 $mailResult = $mailer->send($dest, $headers, $body);
81 # Based on the result return an error string,
82 if( PEAR
::isError( $mailResult ) ) {
83 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
84 return new WikiError( $mailResult->getMessage() );
91 * This function will perform a direct (authenticated) login to
92 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
93 * array of parameters. It requires PEAR:Mail to do that.
94 * Otherwise it just uses the standard PHP 'mail' function.
96 * @param $to MailAddress: recipient's email
97 * @param $from MailAddress: sender's email
98 * @param $subject String: email's subject.
99 * @param $body String: email's text.
100 * @param $replyto String: optional reply-to email (default: null).
101 * @return mixed True on success, a WikiError object on failure.
103 static function send( $to, $from, $subject, $body, $replyto=null ) {
104 global $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
105 global $wgEnotifMaxRecips;
107 if ( is_array( $to ) ) {
108 wfDebug( __METHOD__
.': sending mail to ' . implode( ',', $to ) . "\n" );
110 wfDebug( __METHOD__
.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
113 if (is_array( $wgSMTP )) {
114 require_once( 'Mail.php' );
116 $msgid = str_replace(" ", "_", microtime());
117 if (function_exists('posix_getpid'))
118 $msgid .= '.' . posix_getpid();
123 $dest[] = $u->address
;
125 $dest = $to->address
;
127 $headers['From'] = $from->toString();
129 if ($wgEnotifImpersonal)
130 $headers['To'] = 'undisclosed-recipients:;';
132 $headers['To'] = $to->toString();
135 $headers['Reply-To'] = $replyto->toString();
137 $headers['Subject'] = wfQuotedPrintable( $subject );
138 $headers['Date'] = date( 'r' );
139 $headers['MIME-Version'] = '1.0';
140 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
141 $headers['Content-transfer-encoding'] = '8bit';
142 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
143 $headers['X-Mailer'] = 'MediaWiki mailer';
145 // Create the mail object using the Mail::factory method
146 $mail_object =& Mail
::factory('smtp', $wgSMTP);
147 if( PEAR
::isError( $mail_object ) ) {
148 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
149 return new WikiError( $mail_object->getMessage() );
152 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
153 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
154 foreach ($chunks as $chunk) {
155 $e = self
::sendWithPear($mail_object, $chunk, $headers, $body);
156 if( WikiError
::isError( $e ) )
160 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
161 # (fifth parameter of the PHP mail function, see some lines below)
163 # Line endings need to be different on Unix and Windows due to
164 # the bug described at http://trac.wordpress.org/ticket/2603
165 if ( wfIsWindows() ) {
166 $body = str_replace( "\n", "\r\n", $body );
172 "MIME-Version: 1.0$endl" .
173 "Content-type: text/plain; charset={$wgOutputEncoding}$endl" .
174 "Content-Transfer-Encoding: 8bit$endl" .
175 "X-Mailer: MediaWiki mailer$endl".
176 'From: ' . $from->toString();
178 $headers .= "{$endl}Reply-To: " . $replyto->toString();
182 $html_errors = ini_get( 'html_errors' );
183 ini_set( 'html_errors', '0' );
184 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
185 wfDebug( "Sending mail via internal mail() function\n" );
187 if (function_exists('mail')) {
189 foreach ($to as $recip) {
190 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
193 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
196 $wgErrorString = 'PHP is not configured to send mail';
199 restore_error_handler();
200 ini_set( 'html_errors', $html_errors );
202 if ( $wgErrorString ) {
203 wfDebug( "Error sending mail: $wgErrorString\n" );
204 return new WikiError( $wgErrorString );
206 //mail function only tells if there's an error
207 wfDebug( "Error sending mail\n" );
208 return new WikiError( 'mailer error' );
216 * Get the mail error message in global $wgErrorString
218 * @param $code Integer: error number
219 * @param $string String: error message
221 static function errorHandler( $code, $string ) {
222 global $wgErrorString;
223 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
227 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
229 static function rfc822Phrase( $phrase ) {
230 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
231 return '"' . $phrase . '"';
236 * This module processes the email notifications when the current page is
237 * changed. It looks up the table watchlist to find out which users are watching
240 * The current implementation sends independent emails to each watching user for
241 * the following reason:
243 * - Each watching user will be notified about the page edit time expressed in
244 * his/her local time (UTC is shown additionally). To achieve this, we need to
245 * find the individual timeoffset of each watching user from the preferences..
247 * Suggested improvement to slack down the number of sent emails: We could think
248 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
249 * same timeoffset in their preferences.
251 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
255 class EmailNotification
{
259 var $to, $subject, $body, $replyto, $from;
260 var $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
261 var $mailTargets = array();
266 * Send emails corresponding to the user $editor editing the page $title.
267 * Also updates wl_notificationtimestamp.
269 * May be deferred via the job queue.
271 * @param $editor User object
272 * @param $title Title object
276 * @param $oldid (default: false)
278 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
279 global $wgEnotifUseJobQ;
281 if( $title->getNamespace() < 0 )
284 if ($wgEnotifUseJobQ) {
286 "editor" => $editor->getName(),
287 "timestamp" => $timestamp,
288 "summary" => $summary,
289 "minorEdit" => $minorEdit,
291 $job = new EnotifNotifyJob( $title, $params );
294 $this->actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
300 * Immediate version of notifyOnPageChange().
302 * Send emails corresponding to the user $editor editing the page $title.
303 * Also updates wl_notificationtimestamp.
305 * @param $editor User object
306 * @param $title Title object
310 * @param $oldid (default: false)
312 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid=false) {
314 # we use $wgEmergencyContact as sender's address
315 global $wgEnotifWatchlist;
316 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
317 global $wgEnotifImpersonal;
319 wfProfileIn( __METHOD__
);
321 # The following code is only run, if several conditions are met:
322 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
323 # 2. minor edits (changes) are only regarded if the global flag indicates so
325 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK
);
326 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
327 $enotifwatchlistpage = $wgEnotifWatchlist;
329 $this->title
= $title;
330 $this->timestamp
= $timestamp;
331 $this->summary
= $summary;
332 $this->minorEdit
= $minorEdit;
333 $this->oldid
= $oldid;
334 $this->editor
= $editor;
335 $this->composed_common
= false;
339 if ( (!$minorEdit ||
$wgEnotifMinorEdits) ) {
340 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
341 $targetUser = User
::newFromName( $title->getText() );
342 if ( !$targetUser ||
$targetUser->isAnon() ) {
343 wfDebug( __METHOD__
.": user talk page edited, but user does not exist\n" );
344 } elseif ( $targetUser->getId() == $editor->getId() ) {
345 wfDebug( __METHOD__
.": user edited their own talk page, no notification sent\n" );
346 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
347 wfDebug( __METHOD__
.": sending talk page update notification\n" );
348 $this->compose( $targetUser );
349 $userTalkId = $targetUser->getId();
351 wfDebug( __METHOD__
.": talk page owner doesn't want notifications\n" );
356 if ( $wgEnotifWatchlist ) {
357 // Send updates to watchers other than the current editor
358 $userCondition = 'wl_user <> ' . intval( $editor->getId() );
359 if ( $userTalkId !== false ) {
360 // Already sent an email to this person
361 $userCondition .= ' AND wl_user <> ' . intval( $userTalkId );
363 $dbr = wfGetDB( DB_SLAVE
);
365 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
367 'wl_title' => $title->getDBkey(),
368 'wl_namespace' => $title->getNamespace(),
370 'wl_notificationtimestamp IS NULL',
373 foreach ( $res as $row ) {
374 $watchingUser = User
::newFromId( $row->wl_user
);
375 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
376 ( !$minorEdit ||
$watchingUser->getOption('enotifminoredits') ) &&
377 $watchingUser->isEmailConfirmed() )
379 $this->compose( $watchingUser );
385 global $wgUsersNotifedOnAllChanges;
386 foreach ( $wgUsersNotifedOnAllChanges as $name ) {
387 $user = User
::newFromName( $name );
388 $this->compose( $user );
393 if ( $wgShowUpdatedMarker ||
$wgEnotifWatchlist ) {
394 # mark the changed watch-listed page with a timestamp, so that the page is
395 # listed with an "updated since your last visit" icon in the watch list, ...
396 $dbw = wfGetDB( DB_MASTER
);
397 $dbw->update( 'watchlist',
399 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
400 ), array( /* WHERE */
401 'wl_title' => $title->getDBkey(),
402 'wl_namespace' => $title->getNamespace(),
403 'wl_notificationtimestamp IS NULL'
408 wfProfileOut( __METHOD__
);
409 } # function NotifyOnChange
414 function composeCommonMailtext() {
415 global $wgEmergencyContact, $wgNoReplyAddress;
416 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
417 global $wgEnotifImpersonal;
419 $this->composed_common
= true;
421 $summary = ($this->summary
== '') ?
' - ' : $this->summary
;
422 $medit = ($this->minorEdit
) ?
wfMsg( 'minoredit' ) : '';
424 # You as the WikiAdmin and Sysops can make use of plenty of
425 # named variables when composing your notification emails while
426 # simply editing the Meta pages
428 $subject = wfMsgForContent( 'enotif_subject' );
429 $body = wfMsgForContent( 'enotif_body' );
430 $from = ''; /* fail safe */
431 $replyto = ''; /* fail safe */
434 # regarding the use of oldid as an indicator for the last visited version, see also
435 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
436 # However, in the case of a new page which is already watched, we have no previous version to compare
438 $difflink = $this->title
->getFullUrl( 'diff=0&oldid=' . $this->oldid
);
439 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
440 $keys['$OLDID'] = $this->oldid
;
441 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
443 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
444 # clear $OLDID placeholder in the message template
445 $keys['$OLDID'] = '';
446 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
449 if ($wgEnotifImpersonal && $this->oldid
)
451 * For impersonal mail, show a diff link to the last
454 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
455 $this->title
->getFullURL("oldid={$this->oldid}&diff=prev"));
457 $body = strtr( $body, $keys );
458 $pagetitle = $this->title
->getPrefixedText();
459 $keys['$PAGETITLE'] = $pagetitle;
460 $keys['$PAGETITLE_URL'] = $this->title
->getFullUrl();
462 $keys['$PAGEMINOREDIT'] = $medit;
463 $keys['$PAGESUMMARY'] = $summary;
465 $subject = strtr( $subject, $keys );
467 # Reveal the page editor's address as REPLY-TO address only if
468 # the user has not opted-out and the option is enabled at the
469 # global configuration level.
470 $editor = $this->editor
;
471 $name = $editor->getName();
472 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
473 $editorAddress = new MailAddress( $editor );
474 if( $wgEnotifRevealEditorAddress
475 && ( $editor->getEmail() != '' )
476 && $editor->getOption( 'enotifrevealaddr' ) ) {
477 if( $wgEnotifFromEditor ) {
478 $from = $editorAddress;
480 $from = $adminAddress;
481 $replyto = $editorAddress;
484 $from = $adminAddress;
485 $replyto = new MailAddress( $wgNoReplyAddress );
488 if( $editor->isIP( $name ) ) {
489 #real anon (user:xxx.xxx.xxx.xxx)
490 $utext = wfMsgForContent('enotif_anon_editor', $name);
491 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
492 $keys['$PAGEEDITOR'] = $utext;
493 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
495 $subject = str_replace('$PAGEEDITOR', $name, $subject);
496 $keys['$PAGEEDITOR'] = $name;
497 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $name );
498 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
500 $userPage = $editor->getUserPage();
501 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
502 $body = strtr( $body, $keys );
503 $body = wordwrap( $body, 72 );
505 # now save this as the constant user-independent part of the message
507 $this->replyto
= $replyto;
508 $this->subject
= $subject;
513 * Compose a mail to a given user and either queue it for sending, or send it now,
514 * depending on settings.
516 * Call sendMails() to send any mails that were queued.
518 function compose( $user ) {
519 global $wgEnotifImpersonal;
521 if ( !$this->composed_common
)
522 $this->composeCommonMailtext();
524 if ( $wgEnotifImpersonal ) {
525 $this->mailTargets
[] = new MailAddress( $user );
527 $this->sendPersonalised( $user );
532 * Send any queued mails
534 function sendMails() {
535 global $wgEnotifImpersonal;
536 if ( $wgEnotifImpersonal ) {
537 $this->sendImpersonal( $this->mailTargets
);
542 * Does the per-user customizations to a notification e-mail (name,
543 * timestamp in proper timezone, etc) and sends it out.
544 * Returns true if the mail was sent successfully.
546 * @param User $watchingUser
547 * @param object $mail
551 function sendPersonalised( $watchingUser ) {
553 // From the PHP manual:
554 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
555 // The mail command will not parse this properly while talking with the MTA.
556 $to = new MailAddress( $watchingUser );
557 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body
);
559 $timecorrection = $watchingUser->getOption( 'timecorrection' );
561 # $PAGEEDITDATE is the time and date of the page change
562 # expressed in terms of individual local time of the notification
563 # recipient, i.e. watching user
564 $body = str_replace('$PAGEEDITDATE',
565 $wgLang->timeanddate( $this->timestamp
, true, false, $timecorrection ),
568 return UserMailer
::send($to, $this->from
, $this->subject
, $body, $this->replyto
);
572 * Same as sendPersonalised but does impersonal mail suitable for bulk
573 * mailing. Takes an array of MailAddress objects.
575 function sendImpersonal( $addresses ) {
578 if (empty($addresses))
582 array( '$WATCHINGUSERNAME',
584 array( wfMsgForContent('enotif_impersonal_salutation'),
585 $wgLang->timeanddate($this->timestamp
, true, false, false)),
588 return UserMailer
::send($addresses, $this->from
, $this->subject
, $body, $this->replyto
);
591 } # end of class EmailNotification
594 * Backwards compatibility functions
596 function wfRFC822Phrase( $s ) {
597 return UserMailer
::rfc822Phrase( $s );
599 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
600 return UserMailer
::send( $to, $from, $subject, $body, $replyto );