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 $address Mixed: string with an email address, or a User object
33 * @param $name String: human-readable name if a string address is given
35 function __construct( $address, $name = null, $realName = null ) {
36 if( is_object( $address ) && $address instanceof User
) {
37 $this->address
= $address->getEmail();
38 $this->name
= $address->getName();
39 $this->realName
= $address->getRealName();
41 $this->address
= strval( $address );
42 $this->name
= strval( $name );
43 $this->reaName
= strval( $realName );
48 * Return formatted and quoted address to insert into SMTP headers
52 # PHP's mail() implementation under Windows is somewhat shite, and
53 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
54 # so don't bother generating them
55 if( $this->name
!= '' && !wfIsWindows() ) {
56 global $wgEnotifUseRealName;
57 $name = ( $wgEnotifUseRealName && $this->realName
) ?
$this->realName
: $this->name
;
58 $quoted = wfQuotedPrintable( $name );
59 if( strpos( $quoted, '.' ) !== false ||
strpos( $quoted, ',' ) !== false ) {
60 $quoted = '"' . $quoted . '"';
62 return "$quoted <{$this->address}>";
64 return $this->address
;
68 function __toString() {
69 return $this->toString();
75 * Collection of static functions for sending mail
79 * Send mail using a PEAR mailer
81 protected static function sendWithPear($mailer, $dest, $headers, $body)
83 $mailResult = $mailer->send($dest, $headers, $body);
85 # Based on the result return an error string,
86 if( PEAR
::isError( $mailResult ) ) {
87 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
88 return new WikiError( $mailResult->getMessage() );
95 * This function will perform a direct (authenticated) login to
96 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
97 * array of parameters. It requires PEAR:Mail to do that.
98 * Otherwise it just uses the standard PHP 'mail' function.
100 * @param $to MailAddress: recipient's email
101 * @param $from MailAddress: sender's email
102 * @param $subject String: email's subject.
103 * @param $body String: email's text.
104 * @param $replyto String: optional reply-to email (default: null).
105 * @param $contentType String: optional custom Content-Type
106 * @return mixed True on success, a WikiError object on failure.
108 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
109 global $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
110 global $wgEnotifMaxRecips;
112 if ( is_array( $to ) ) {
113 wfDebug( __METHOD__
.': sending mail to ' . implode( ',', $to ) . "\n" );
115 wfDebug( __METHOD__
.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
118 if (is_array( $wgSMTP )) {
119 require_once( 'Mail.php' );
121 $msgid = str_replace(" ", "_", microtime());
122 if (function_exists('posix_getpid'))
123 $msgid .= '.' . posix_getpid();
128 $dest[] = $u->address
;
130 $dest = $to->address
;
132 $headers['From'] = $from->toString();
134 if ($wgEnotifImpersonal) {
135 $headers['To'] = 'undisclosed-recipients:;';
138 $headers['To'] = implode( ", ", (array )$dest );
142 $headers['Reply-To'] = $replyto->toString();
144 $headers['Subject'] = wfQuotedPrintable( $subject );
145 $headers['Date'] = date( 'r' );
146 $headers['MIME-Version'] = '1.0';
147 $headers['Content-type'] = (is_null($contentType) ?
148 'text/plain; charset='.$wgOutputEncoding : $contentType);
149 $headers['Content-transfer-encoding'] = '8bit';
150 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
151 $headers['X-Mailer'] = 'MediaWiki mailer';
153 // Create the mail object using the Mail::factory method
154 $mail_object =& Mail
::factory('smtp', $wgSMTP);
155 if( PEAR
::isError( $mail_object ) ) {
156 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
157 return new WikiError( $mail_object->getMessage() );
160 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
161 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
162 foreach ($chunks as $chunk) {
163 $e = self
::sendWithPear($mail_object, $chunk, $headers, $body);
164 if( WikiError
::isError( $e ) )
168 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
169 # (fifth parameter of the PHP mail function, see some lines below)
171 # Line endings need to be different on Unix and Windows due to
172 # the bug described at http://trac.wordpress.org/ticket/2603
173 if ( wfIsWindows() ) {
174 $body = str_replace( "\n", "\r\n", $body );
179 $ctype = (is_null($contentType) ?
180 'text/plain; charset='.$wgOutputEncoding : $contentType);
182 "MIME-Version: 1.0$endl" .
183 "Content-type: $ctype$endl" .
184 "Content-Transfer-Encoding: 8bit$endl" .
185 "X-Mailer: MediaWiki mailer$endl".
186 'From: ' . $from->toString();
188 $headers .= "{$endl}Reply-To: " . $replyto->toString();
192 $html_errors = ini_get( 'html_errors' );
193 ini_set( 'html_errors', '0' );
194 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
195 wfDebug( "Sending mail via internal mail() function\n" );
197 if (function_exists('mail')) {
199 foreach ($to as $recip) {
200 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
203 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
206 $wgErrorString = 'PHP is not configured to send mail';
209 restore_error_handler();
210 ini_set( 'html_errors', $html_errors );
212 if ( $wgErrorString ) {
213 wfDebug( "Error sending mail: $wgErrorString\n" );
214 return new WikiError( $wgErrorString );
216 //mail function only tells if there's an error
217 wfDebug( "Error sending mail\n" );
218 return new WikiError( 'mailer error' );
226 * Get the mail error message in global $wgErrorString
228 * @param $code Integer: error number
229 * @param $string String: error message
231 static function errorHandler( $code, $string ) {
232 global $wgErrorString;
233 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
237 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
239 static function rfc822Phrase( $phrase ) {
240 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
241 return '"' . $phrase . '"';
246 class EmailNotification
{
249 * Send users an email.
251 * @param $editor User whose action precipitated the notification.
252 * @param $timestamp of the event.
253 * @param Callback that returns an an array of Users who will recieve the notification.
254 * @param Callback that returns an array($keys, $body, $subject) where
255 * * $keys is a dictionary whose keys will be replaced with the corresponding
256 * values within the subject and body of the message.
257 * * $body is the name of the message that will be used for the email body.
258 * * $subject is the name of the message that will be used for the subject.
259 * Both messages are resolved using the content language.
260 * The messageCompositionFunction is invoked for each recipient user;
261 * The keys returned are merged with those given by EmailNotification::commonMessageKeys().
262 * The recipient is appended to the arguments given to messageCompositionFunction.
263 * Both callbacks are to be given in the same formats accepted by the hook system.
265 function notify($editor, $timestamp, $userListFunction, $messageCompositionFunction) {
266 global $wgEnotifUseRealName, $wgEnotifImpersonal;
269 $common_keys = self
::commonMessageKeys($editor);
270 $users = wfInvoke($userListFunction);
271 foreach($users as $u) {
272 list($user_keys, $body_msg_name, $subj_msg_name) =
273 wfInvoke($messageCompositionFunction, array($u));
274 $keys = array_merge($common_keys, $user_keys);
276 if( $wgEnotifImpersonal ) {
277 $keys['$WATCHINGUSERNAME'] = wfMsgForContent('enotif_impersonal_salutation');
278 $keys['$PAGEEDITDATE'] = $wgLang->timeanddate($timestamp, true, false, false);
280 $keys['$WATCHINGUSERNAME'] = $wgEnotifUseRealName ?
$u->getRealName() : $u->getName();
281 $keys['$PAGEEDITDATE'] = $wgLang->timeAndDate($timestamp, true, false,
282 $u->getOption('timecorrection'));
285 $subject = strtr(wfMsgForContent( $subj_msg_name ), $keys);
286 $body = wordwrap( strtr( wfMsgForContent( $body_msg_name ), $keys ), 72 );
288 $to = new MailAddress($u);
289 $from = $keys['$FROM_HEADER'];
290 $replyto = $keys['$REPLYTO_HEADER'];
291 UserMailer
::send($to, $from, $subject, $body, $replyto);
296 static function commonMessageKeys($editor) {
297 global $wgEnotifUseRealName, $wgEnotifRevealEditorAddress;
298 global $wgNoReplyAddress, $wgPasswordSender;
302 $name = $wgEnotifUseRealName ?
$editor->getRealName() : $editor->getName();
304 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
305 $editorAddress = new MailAddress( $editor );
306 if( $wgEnotifRevealEditorAddress
307 && $editor->getEmail() != ''
308 && $editor->getOption( 'enotifrevealaddr' ) ) {
309 if( $wgEnotifFromEditor ) {
310 $from = $editorAddress;
312 $from = $adminAddress;
313 $replyto = $editorAddress;
316 $from = $adminAddress;
317 $replyto = new MailAddress( $wgNoReplyAddress );
319 $keys['$FROM_HEADER'] = $from;
320 $keys['$REPLYTO_HEADER'] = $replyto;
322 if( $editor->isAnon() ) {
323 $keys['$PAGEEDITOR'] = wfMsgForContent('enotif_anon_editor', $name);
324 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
326 $keys['$PAGEEDITOR'] = $name;
327 $keys['$PAGEEDITOR_EMAIL'] = SpecialPage
::getSafeTitleFor('Emailuser', $name)->getFullUrl();
329 $keys['$PAGEEDITOR_WIKI'] = $editor->getUserPage()->getFullUrl();
338 * Use PageChangeNotification::notifyOnPageChange instead.
340 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
341 PageChangeNotification
::notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
345 class PageChangeNotification
{
348 * Send emails corresponding to the user $editor editing the page $title.
349 * Also updates wl_notificationtimestamp.
351 * May be deferred via the job queue.
353 * @param $editor User object
354 * @param $title Title object
358 * @param $oldid (default: false)
360 static function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
361 global $wgEnotifUseJobQ;
363 if( $title->getNamespace() < 0 )
366 if ($wgEnotifUseJobQ) {
368 "editor" => $editor->getName(),
369 "editorID" => $editor->getID(),
370 "timestamp" => $timestamp,
371 "summary" => $summary,
372 "minorEdit" => $minorEdit,
374 $job = new EnotifNotifyJob( $title, $params );
377 self
::actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
383 * Immediate version of notifyOnPageChange().
385 * Send emails corresponding to the user $editor editing the page $title.
386 * Also updates wl_notificationtimestamp.
388 * @param $editor User object
389 * @param $title Title object
393 * @param $oldid (default: false)
395 static function actuallyNotifyOnPageChange($editor, $title, $timestamp,
396 $summary, $minorEdit, $oldid=false) {
397 global $wgShowUpdatedMarker, $wgEnotifWatchlist;
399 wfProfileIn( __METHOD__
);
401 EmailNotification
::notify($editor, $timestamp,
402 array('PageChangeNotification::usersList', array($editor, $title, $minorEdit)),
403 array('PageChangeNotification::message', array($oldid, $minorEdit, $summary, $title, $editor) ) );
405 $latestTimestamp = Revision
::getTimestampFromId( $title, $title->getLatestRevID() );
406 // Do not update watchlists if something else already did.
407 if ( $timestamp >= $latestTimestamp && ($wgShowUpdatedMarker ||
$wgEnotifWatchlist) ) {
408 # Mark the changed watch-listed page with a timestamp, so that the page is
409 # listed with an "updated since your last visit" icon in the watch list. Do
410 # not do this to users for their own edits.
411 $dbw = wfGetDB( DB_MASTER
);
412 $dbw->update( 'watchlist',
414 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
415 ), array( /* WHERE */
416 'wl_title' => $title->getDBkey(),
417 'wl_namespace' => $title->getNamespace(),
418 'wl_notificationtimestamp IS NULL',
419 'wl_user != ' . $editor->getID()
424 wfProfileOut( __METHOD__
);
428 static function message( $stuff ) {
429 global $wgEnotifImpersonal;
431 list($oldid, $medit, $summary, $title, $user) = $stuff;
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 = $title->getFullUrl( 'diff=0&oldid=' . $oldid );
439 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
440 $keys['$OLDID'] = $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 && $oldid) {
450 # For impersonal mail, show a diff link to the last revision.
451 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
452 $title->getFullURL("oldid={$oldid}&diff=prev"));
455 $keys['$PAGETITLE'] = $title->getPrefixedText();
456 $keys['$PAGETITLE_URL'] = $title->getFullUrl();
457 $keys['$PAGEMINOREDIT'] = $medit ?
wfMsg( 'minoredit' ) : '';
458 $keys['$PAGESUMMARY'] = ($summary == '') ?
' - ' : $summary;
460 return array($keys, 'enotif_body', 'enotif_subject');
463 static function usersList($stuff) {
464 global $wgEnotifWatchlist, $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges;
466 list($editor, $title, $minorEdit) = $stuff;
467 $recipients = array();
471 if( $title->getNamespace() == NS_USER_TALK
&& (!$minorEdit ||
$wgEnotifMinorEdits) ) {
472 $targetUser = User
::newFromName($title->getText());
474 if ( !$targetUser ||
$targetUser->isAnon() )
475 $msg = "user talk page edited, but user does not exist";
477 else if ( $targetUser->getId() == $editor->getId() )
478 $msg = "user edited their own talk page, no notification sent";
480 else if ( !$targetUser->getOption('enotifusertalkpages') )
481 $msg = "talk page owner doesn't want notifications";
483 else if ( !$targetUser->isEmailConfirmed() )
484 $msg = "talk page owner doesn't have validated email";
487 $msg = "sending talk page update notification";
488 $recipients[] = $targetUser;
489 $userTalkId = $targetUser->getId(); # won't be included in watchlist, below.
491 wfDebug( __METHOD__
.": ". $msg . "\n" );
493 wfDebug("Did not send a user-talk notification.\n");
495 if( $wgEnotifWatchlist && (!$minorEdit ||
$wgEnotifMinorEdits) ) {
496 // Send updates to watchers other than the current editor
497 $userCondition = 'wl_user != ' . $editor->getID();
499 if ( $userTalkId !== false ) {
500 // Already sent an email to this person
501 $userCondition .= ' AND wl_user != ' . intval( $userTalkId );
503 $dbr = wfGetDB( DB_SLAVE
);
505 list( $user ) = $dbr->tableNamesN( 'user' );
507 $res = $dbr->select( array( 'watchlist', 'user' ),
511 'wl_title' => $title->getDBkey(),
512 'wl_namespace' => $title->getNamespace(),
514 'wl_notificationtimestamp IS NULL',
516 $userArray = UserArray
::newFromResult( $res );
518 foreach ( $userArray as $watchingUser ) {
519 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
520 ( !$minorEdit ||
$watchingUser->getOption('enotifminoredits') ) &&
521 $watchingUser->isEmailConfirmed() ) {
522 $recipients[] = $watchingUser;
527 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
528 $recipients[] = User
::newFromName($name);
536 * Backwards compatibility functions
538 function wfRFC822Phrase( $s ) {
539 return UserMailer
::rfc822Phrase( $s );
542 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
543 return UserMailer
::send( $to, $from, $subject, $body, $replyto );