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->realName = 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 MailAddress: 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 * This module processes the email notifications when the current page is
247 * changed. It looks up the table watchlist to find out which users are watching
250 * The current implementation sends independent emails to each watching user for
251 * the following reason:
253 * - Each watching user will be notified about the page edit time expressed in
254 * his/her local time (UTC is shown additionally). To achieve this, we need to
255 * find the individual timeoffset of each watching user from the preferences..
257 * Suggested improvement to slack down the number of sent emails: We could think
258 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
259 * same timeoffset in their preferences.
261 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
265 class EmailNotification {
266 private $to, $subject, $body, $replyto, $from;
267 private $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
268 private $mailTargets = array();
271 * Send emails corresponding to the user $editor editing the page $title.
272 * Also updates wl_notificationtimestamp.
274 * May be deferred via the job queue.
276 * @param $editor User object
277 * @param $title Title object
281 * @param $oldid (default: false)
283 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
284 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
286 if ($title->getNamespace() < 0)
289 // Build a list of users to notfiy
291 if ($wgEnotifWatchlist || $wgShowUpdatedMarker) {
292 $dbw = wfGetDB( DB_MASTER );
293 $res = $dbw->select( array( 'watchlist' ),
296 'wl_title' => $title->getDBkey(),
297 'wl_namespace' => $title->getNamespace(),
298 'wl_user != ' . intval( $editor->getID() ),
299 'wl_notificationtimestamp IS NULL',
302 while ($row = $dbw->fetchObject( $res ) ) {
303 $watchers[] = intval( $row->wl_user );
306 // Update wl_notificationtimestamp for all watching users except
309 $dbw->update( 'watchlist',
311 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
312 ), array( /* WHERE */
313 'wl_title' => $title->getDBkey(),
314 'wl_namespace' => $title->getNamespace(),
315 'wl_user' => $watchers
322 if ($wgEnotifUseJobQ) {
324 "editor" => $editor->getName(),
325 "editorID" => $editor->getID(),
326 "timestamp" => $timestamp,
327 "summary" => $summary,
328 "minorEdit" => $minorEdit,
330 "watchers" => $watchers);
331 $job = new EnotifNotifyJob( $title, $params );
334 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
340 * Immediate version of notifyOnPageChange().
342 * Send emails corresponding to the user $editor editing the page $title.
343 * Also updates wl_notificationtimestamp.
345 * @param $editor User object
346 * @param $title Title object
347 * @param $timestamp string Edit timestamp
348 * @param $summary string Edit summary
349 * @param $minorEdit bool
350 * @param $oldid int Revision ID
351 * @param $watchers array of user IDs
353 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers) {
354 # we use $wgPasswordSender as sender's address
355 global $wgEnotifWatchlist;
356 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
357 global $wgEnotifImpersonal;
359 wfProfileIn( __METHOD__ );
361 # The following code is only run, if several conditions are met:
362 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
363 # 2. minor edits (changes) are only regarded if the global flag indicates so
365 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
366 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
367 $enotifwatchlistpage = $wgEnotifWatchlist;
369 $this->title = $title;
370 $this->timestamp = $timestamp;
371 $this->summary = $summary;
372 $this->minorEdit = $minorEdit;
373 $this->oldid = $oldid;
374 $this->editor = $editor;
375 $this->composed_common = false;
379 if ( !$minorEdit || ($wgEnotifMinorEdits && !$editor->isAllowed('nominornewtalk') ) ) {
380 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
381 $targetUser = User::newFromName( $title->getText() );
382 if ( !$targetUser || $targetUser->isAnon() ) {
383 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
384 } elseif ( $targetUser->getId() == $editor->getId() ) {
385 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
386 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
387 if( $targetUser->isEmailConfirmed() ) {
388 wfDebug( __METHOD__.": sending talk page update notification\n" );
389 $this->compose( $targetUser );
390 $userTalkId = $targetUser->getId();
392 wfDebug( __METHOD__.": talk page owner doesn't have validated email\n" );
395 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
399 if ( $wgEnotifWatchlist ) {
400 // Send updates to watchers other than the current editor
401 $userArray = UserArray::newFromIDs( $watchers );
402 foreach ( $userArray as $watchingUser ) {
403 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
404 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
405 $watchingUser->isEmailConfirmed() &&
406 $watchingUser->getID() != $userTalkId )
408 $this->compose( $watchingUser );
414 global $wgUsersNotifiedOnAllChanges;
415 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
416 $user = User::newFromName( $name );
417 $this->compose( $user );
421 wfProfileOut( __METHOD__ );
427 function composeCommonMailtext() {
428 global $wgPasswordSender, $wgNoReplyAddress;
429 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
430 global $wgEnotifImpersonal, $wgEnotifUseRealName;
432 $this->composed_common = true;
434 $summary = ($this->summary == '') ? ' - ' : $this->summary;
435 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
437 # You as the WikiAdmin and Sysops can make use of plenty of
438 # named variables when composing your notification emails while
439 # simply editing the Meta pages
441 $subject = wfMsgForContent( 'enotif_subject' );
442 $body = wfMsgForContent( 'enotif_body' );
443 $from = ''; /* fail safe */
444 $replyto = ''; /* fail safe */
448 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
449 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
450 $keys['$OLDID'] = $this->oldid;
451 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
453 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
454 # clear $OLDID placeholder in the message template
455 $keys['$OLDID'] = '';
456 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
459 if ($wgEnotifImpersonal && $this->oldid)
461 * For impersonal mail, show a diff link to the last
464 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
465 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
467 $body = strtr( $body, $keys );
468 $pagetitle = $this->title->getPrefixedText();
469 $keys['$PAGETITLE'] = $pagetitle;
470 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
472 $keys['$PAGEMINOREDIT'] = $medit;
473 $keys['$PAGESUMMARY'] = $summary;
475 $subject = strtr( $subject, $keys );
477 # Reveal the page editor's address as REPLY-TO address only if
478 # the user has not opted-out and the option is enabled at the
479 # global configuration level.
480 $editor = $this->editor;
481 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
482 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
483 $editorAddress = new MailAddress( $editor );
484 if( $wgEnotifRevealEditorAddress
485 && ( $editor->getEmail() != '' )
486 && $editor->getOption( 'enotifrevealaddr' ) ) {
487 if( $wgEnotifFromEditor ) {
488 $from = $editorAddress;
490 $from = $adminAddress;
491 $replyto = $editorAddress;
494 $from = $adminAddress;
495 $replyto = new MailAddress( $wgNoReplyAddress );
498 if( $editor->isIP( $name ) ) {
499 #real anon (user:xxx.xxx.xxx.xxx)
500 $utext = wfMsgForContent('enotif_anon_editor', $name);
501 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
502 $keys['$PAGEEDITOR'] = $utext;
503 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
505 $subject = str_replace('$PAGEEDITOR', $name, $subject);
506 $keys['$PAGEEDITOR'] = $name;
507 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
508 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
510 $userPage = $editor->getUserPage();
511 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
512 $body = strtr( $body, $keys );
513 $body = wordwrap( $body, 72 );
515 # now save this as the constant user-independent part of the message
517 $this->replyto = $replyto;
518 $this->subject = $subject;
523 * Compose a mail to a given user and either queue it for sending, or send it now,
524 * depending on settings.
526 * Call sendMails() to send any mails that were queued.
528 function compose( $user ) {
529 global $wgEnotifImpersonal;
531 if ( !$this->composed_common )
532 $this->composeCommonMailtext();
534 if ( $wgEnotifImpersonal ) {
535 $this->mailTargets[] = new MailAddress( $user );
537 $this->sendPersonalised( $user );
542 * Send any queued mails
544 function sendMails() {
545 global $wgEnotifImpersonal;
546 if ( $wgEnotifImpersonal ) {
547 $this->sendImpersonal( $this->mailTargets );
552 * Does the per-user customizations to a notification e-mail (name,
553 * timestamp in proper timezone, etc) and sends it out.
554 * Returns true if the mail was sent successfully.
556 * @param User $watchingUser
557 * @param object $mail
561 function sendPersonalised( $watchingUser ) {
562 global $wgContLang, $wgEnotifUseRealName;
563 // From the PHP manual:
564 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
565 // The mail command will not parse this properly while talking with the MTA.
566 $to = new MailAddress( $watchingUser );
567 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
568 $body = str_replace( '$WATCHINGUSERNAME', $name , $this->body );
570 $timecorrection = $watchingUser->getOption( 'timecorrection' );
572 # $PAGEEDITDATE is the time and date of the page change
573 # expressed in terms of individual local time of the notification
574 # recipient, i.e. watching user
575 $body = str_replace('$PAGEEDITDATE',
576 $wgContLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
579 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
583 * Same as sendPersonalised but does impersonal mail suitable for bulk
584 * mailing. Takes an array of MailAddress objects.
586 function sendImpersonal( $addresses ) {
589 if (empty($addresses))
593 array( '$WATCHINGUSERNAME',
595 array( wfMsgForContent('enotif_impersonal_salutation'),
596 $wgContLang->timeanddate($this->timestamp, true, false, false)),
599 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
602 } # end of class EmailNotification
605 * Backwards compatibility functions
607 function wfRFC822Phrase( $s ) {
608 return UserMailer::rfc822Phrase( $s );
611 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
612 return UserMailer::send( $to, $from, $subject, $body, $replyto );