3 * Utility class for creating and accessing recent change entries.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Utility class for creating new RC entries
27 * rc_id id of the row in the recentchanges table
28 * rc_timestamp time the entry was made
29 * rc_namespace namespace #
30 * rc_title non-prefixed db key
31 * rc_type is new entry, used to determine whether updating is necessary
32 * rc_source string representation of change source
34 * rc_cur_id page_id of associated page entry
35 * rc_user user id who made the entry
36 * rc_user_text user name who made the entry
37 * rc_comment edit summary
38 * rc_this_oldid rev_id associated with this entry (or zero)
39 * rc_last_oldid rev_id associated with the entry before this one (or zero)
40 * rc_bot is bot, hidden
41 * rc_ip IP address of the user in dotted quad notation
42 * rc_new obsolete, use rc_type==RC_NEW
43 * rc_patrolled boolean whether or not someone has marked this edit as patrolled
44 * rc_old_len integer byte length of the text before the edit
45 * rc_new_len the same after the edit
46 * rc_deleted partial deletion
47 * rc_logid the log_id value for this log entry (or zero)
48 * rc_log_type the log type (or null)
49 * rc_log_action the log action (or null)
50 * rc_params log params
53 * prefixedDBkey prefixed db key, used by external app via msg queue
54 * lastTimestamp timestamp of previous entry, used in WHERE clause during update
55 * oldSize text size before the change
56 * newSize text size after the change
57 * pageStatus status of the page: created, deleted, moved, restored, changed
59 * temporary: not stored in the database
60 * notificationtimestamp
61 * numberofWatchingusers
64 // Constants for the rc_source field. Extensions may also have
65 // their own source constants.
66 const SRC_EDIT
= 'mw.edit';
67 const SRC_NEW
= 'mw.new';
68 const SRC_LOG
= 'mw.log';
69 const SRC_EXTERNAL
= 'mw.external'; // obsolete
71 public $mAttribs = array();
72 public $mExtra = array();
77 public $mTitle = false;
82 private $mPerformer = false;
84 public $numberofWatchingusers = 0; # Dummy to prevent error message in SpecialRecentChangesLinked
85 public $notificationtimestamp;
88 * @var int Line number of recent change. Default -1.
96 * @return RecentChange
98 public static function newFromRow( $row ) {
99 $rc = new RecentChange
;
100 $rc->loadFromRow( $row );
106 * Parsing text to RC_* constants
108 * @param string|array $type
109 * @throws MWException
110 * @return int|array RC_TYPE
112 public static function parseToRCType( $type ) {
113 if ( is_array( $type ) ) {
115 foreach ( $type as $t ) {
116 $retval[] = RecentChange
::parseToRCType( $t );
132 throw new MWException( "Unknown type '$type'" );
137 * Parsing RC_* constants to human-readable test
140 * @return string $type
142 public static function parseFromRCType( $rcType ) {
164 * Obtain the recent change with a given rc_id value
166 * @param int $rcid The rc_id value to retrieve
167 * @return RecentChange|null
169 public static function newFromId( $rcid ) {
170 return self
::newFromConds( array( 'rc_id' => $rcid ), __METHOD__
);
174 * Find the first recent change matching some specific conditions
176 * @param array $conds Array of conditions
177 * @param mixed $fname Override the method name in profiling/logs
178 * @param array $options Query options
179 * @return RecentChange|null
181 public static function newFromConds( $conds, $fname = __METHOD__
, $options = array() ) {
182 $dbr = wfGetDB( DB_SLAVE
);
183 $row = $dbr->selectRow( 'recentchanges', self
::selectFields(), $conds, $fname, $options );
184 if ( $row !== false ) {
185 return self
::newFromRow( $row );
192 * Return the list of recentchanges fields that should be selected to create
193 * a new recentchanges object.
196 public static function selectFields() {
228 * @param array $attribs
230 public function setAttribs( $attribs ) {
231 $this->mAttribs
= $attribs;
235 * @param array $extra
237 public function setExtra( $extra ) {
238 $this->mExtra
= $extra;
244 public function &getTitle() {
245 if ( $this->mTitle
=== false ) {
246 $this->mTitle
= Title
::makeTitle( $this->mAttribs
['rc_namespace'], $this->mAttribs
['rc_title'] );
249 return $this->mTitle
;
253 * Get the User object of the person who performed this change.
257 public function getPerformer() {
258 if ( $this->mPerformer
=== false ) {
259 if ( $this->mAttribs
['rc_user'] ) {
260 $this->mPerformer
= User
::newFromId( $this->mAttribs
['rc_user'] );
262 $this->mPerformer
= User
::newFromName( $this->mAttribs
['rc_user_text'], false );
266 return $this->mPerformer
;
270 * Writes the data in this object to the database
273 public function save( $noudp = false ) {
274 global $wgPutIPinRC, $wgUseEnotif, $wgShowUpdatedMarker, $wgContLang;
276 $dbw = wfGetDB( DB_MASTER
);
277 if ( !is_array( $this->mExtra
) ) {
278 $this->mExtra
= array();
281 if ( !$wgPutIPinRC ) {
282 $this->mAttribs
['rc_ip'] = '';
285 # If our database is strict about IP addresses, use NULL instead of an empty string
286 if ( $dbw->strictIPs() && $this->mAttribs
['rc_ip'] == '' ) {
287 unset( $this->mAttribs
['rc_ip'] );
290 # Trim spaces on user supplied text
291 $this->mAttribs
['rc_comment'] = trim( $this->mAttribs
['rc_comment'] );
293 # Make sure summary is truncated (whole multibyte characters)
294 $this->mAttribs
['rc_comment'] = $wgContLang->truncate( $this->mAttribs
['rc_comment'], 255 );
296 # Fixup database timestamps
297 $this->mAttribs
['rc_timestamp'] = $dbw->timestamp( $this->mAttribs
['rc_timestamp'] );
298 $this->mAttribs
['rc_id'] = $dbw->nextSequenceValue( 'recentchanges_rc_id_seq' );
300 ## If we are using foreign keys, an entry of 0 for the page_id will fail, so use NULL
301 if ( $dbw->cascadingDeletes() && $this->mAttribs
['rc_cur_id'] == 0 ) {
302 unset( $this->mAttribs
['rc_cur_id'] );
306 $dbw->insert( 'recentchanges', $this->mAttribs
, __METHOD__
);
309 $this->mAttribs
['rc_id'] = $dbw->insertId();
312 Hooks
::run( 'RecentChange_save', array( &$this ) );
314 # Notify external application via UDP
316 $this->notifyRCFeeds();
319 # E-mail notifications
320 if ( $wgUseEnotif ||
$wgShowUpdatedMarker ) {
321 $editor = $this->getPerformer();
322 $title = $this->getTitle();
324 if ( Hooks
::run( 'AbortEmailNotification', array( $editor, $title, $this ) ) ) {
325 # @todo FIXME: This would be better as an extension hook
326 $enotif = new EmailNotification();
327 $enotif->notifyOnPageChange( $editor, $title,
328 $this->mAttribs
['rc_timestamp'],
329 $this->mAttribs
['rc_comment'],
330 $this->mAttribs
['rc_minor'],
331 $this->mAttribs
['rc_last_oldid'],
332 $this->mExtra
['pageStatus'] );
336 // Update the cached list of active users
337 if ( $this->mAttribs
['rc_user'] > 0 ) {
338 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newCacheUpdateJob() );
343 * Notify all the feeds about the change.
344 * @param array $feeds Optional feeds to send to, defaults to $wgRCFeeds
346 public function notifyRCFeeds( array $feeds = null ) {
348 if ( $feeds === null ) {
352 $performer = $this->getPerformer();
354 foreach ( $feeds as $feed ) {
356 'omit_bots' => false,
357 'omit_anon' => false,
358 'omit_user' => false,
359 'omit_minor' => false,
360 'omit_patrolled' => false,
364 ( $feed['omit_bots'] && $this->mAttribs
['rc_bot'] ) ||
365 ( $feed['omit_anon'] && $performer->isAnon() ) ||
366 ( $feed['omit_user'] && !$performer->isAnon() ) ||
367 ( $feed['omit_minor'] && $this->mAttribs
['rc_minor'] ) ||
368 ( $feed['omit_patrolled'] && $this->mAttribs
['rc_patrolled'] ) ||
369 $this->mAttribs
['rc_type'] == RC_EXTERNAL
374 $engine = self
::getEngine( $feed['uri'] );
376 if ( isset( $this->mExtra
['actionCommentIRC'] ) ) {
377 $actionComment = $this->mExtra
['actionCommentIRC'];
379 $actionComment = null;
382 /** @var $formatter RCFeedFormatter */
383 $formatter = is_object( $feed['formatter'] ) ?
$feed['formatter'] : new $feed['formatter']();
384 $line = $formatter->getLine( $feed, $this, $actionComment );
386 $engine->send( $feed, $line );
391 * Gets the stream engine object for a given URI from $wgRCEngines
393 * @param string $uri URI to get the engine object for
394 * @throws MWException
395 * @return RCFeedEngine The engine object
397 public static function getEngine( $uri ) {
400 $scheme = parse_url( $uri, PHP_URL_SCHEME
);
402 throw new MWException( __FUNCTION__
. ": Invalid stream logger URI: '$uri'" );
405 if ( !isset( $wgRCEngines[$scheme] ) ) {
406 throw new MWException( __FUNCTION__
. ": Unknown stream logger URI scheme: $scheme" );
409 return new $wgRCEngines[$scheme];
413 * Mark a given change as patrolled
415 * @param RecentChange|int $change RecentChange or corresponding rc_id
416 * @param bool $auto For automatic patrol
417 * @return array See doMarkPatrolled(), or null if $change is not an existing rc_id
419 public static function markPatrolled( $change, $auto = false ) {
422 $change = $change instanceof RecentChange
424 : RecentChange
::newFromId( $change );
426 if ( !$change instanceof RecentChange
) {
430 return $change->doMarkPatrolled( $wgUser, $auto );
434 * Mark this RecentChange as patrolled
436 * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
437 * 'markedaspatrollederror-noautopatrol' as errors
438 * @param User $user User object doing the action
439 * @param bool $auto For automatic patrol
440 * @return array Array of permissions errors, see Title::getUserPermissionsErrors()
442 public function doMarkPatrolled( User
$user, $auto = false ) {
443 global $wgUseRCPatrol, $wgUseNPPatrol;
445 // If recentchanges patrol is disabled, only new pages
447 if ( !$wgUseRCPatrol && ( !$wgUseNPPatrol ||
$this->getAttribute( 'rc_type' ) != RC_NEW
) ) {
448 $errors[] = array( 'rcpatroldisabled' );
450 // Automatic patrol needs "autopatrol", ordinary patrol needs "patrol"
451 $right = $auto ?
'autopatrol' : 'patrol';
452 $errors = array_merge( $errors, $this->getTitle()->getUserPermissionsErrors( $right, $user ) );
453 if ( !Hooks
::run( 'MarkPatrolled', array( $this->getAttribute( 'rc_id' ), &$user, false ) ) ) {
454 $errors[] = array( 'hookaborted' );
456 // Users without the 'autopatrol' right can't patrol their
458 if ( $user->getName() === $this->getAttribute( 'rc_user_text' )
459 && !$user->isAllowed( 'autopatrol' )
461 $errors[] = array( 'markedaspatrollederror-noautopatrol' );
466 // If the change was patrolled already, do nothing
467 if ( $this->getAttribute( 'rc_patrolled' ) ) {
470 // Actually set the 'patrolled' flag in RC
471 $this->reallyMarkPatrolled();
472 // Log this patrol event
473 PatrolLog
::record( $this, $auto, $user );
474 Hooks
::run( 'MarkPatrolledComplete', array( $this->getAttribute( 'rc_id' ), &$user, false ) );
480 * Mark this RecentChange patrolled, without error checking
481 * @return int Number of affected rows
483 public function reallyMarkPatrolled() {
484 $dbw = wfGetDB( DB_MASTER
);
491 'rc_id' => $this->getAttribute( 'rc_id' )
495 // Invalidate the page cache after the page has been patrolled
496 // to make sure that the Patrol link isn't visible any longer!
497 $this->getTitle()->invalidateCache();
499 return $dbw->affectedRows();
503 * Makes an entry in the database corresponding to an edit
505 * @param string $timestamp
506 * @param Title $title
509 * @param string $comment
511 * @param string $lastTimestamp
514 * @param int $oldSize
515 * @param int $newSize
518 * @return RecentChange
520 public static function notifyEdit(
521 $timestamp, &$title, $minor, &$user, $comment, $oldId, $lastTimestamp,
522 $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0
524 $rc = new RecentChange
;
525 $rc->mTitle
= $title;
526 $rc->mPerformer
= $user;
527 $rc->mAttribs
= array(
528 'rc_timestamp' => $timestamp,
529 'rc_namespace' => $title->getNamespace(),
530 'rc_title' => $title->getDBkey(),
531 'rc_type' => RC_EDIT
,
532 'rc_source' => self
::SRC_EDIT
,
533 'rc_minor' => $minor ?
1 : 0,
534 'rc_cur_id' => $title->getArticleID(),
535 'rc_user' => $user->getId(),
536 'rc_user_text' => $user->getName(),
537 'rc_comment' => $comment,
538 'rc_this_oldid' => $newId,
539 'rc_last_oldid' => $oldId,
540 'rc_bot' => $bot ?
1 : 0,
541 'rc_ip' => self
::checkIPAddress( $ip ),
542 'rc_patrolled' => intval( $patrol ),
543 'rc_new' => 0, # obsolete
544 'rc_old_len' => $oldSize,
545 'rc_new_len' => $newSize,
548 'rc_log_type' => null,
549 'rc_log_action' => '',
554 'prefixedDBkey' => $title->getPrefixedDBkey(),
555 'lastTimestamp' => $lastTimestamp,
556 'oldSize' => $oldSize,
557 'newSize' => $newSize,
558 'pageStatus' => 'changed'
561 DeferredUpdates
::addCallableUpdate( function() use ( $rc ) {
563 if ( $rc->mAttribs
['rc_patrolled'] ) {
564 PatrolLog
::record( $rc, true, $rc->getPerformer() );
572 * Makes an entry in the database corresponding to page creation
573 * Note: the title object must be loaded with the new id using resetArticleID()
575 * @param string $timestamp
576 * @param Title $title
579 * @param string $comment
585 * @return RecentChange
587 public static function notifyNew(
588 $timestamp, &$title, $minor, &$user, $comment, $bot,
589 $ip = '', $size = 0, $newId = 0, $patrol = 0
591 $rc = new RecentChange
;
592 $rc->mTitle
= $title;
593 $rc->mPerformer
= $user;
594 $rc->mAttribs
= array(
595 'rc_timestamp' => $timestamp,
596 'rc_namespace' => $title->getNamespace(),
597 'rc_title' => $title->getDBkey(),
599 'rc_source' => self
::SRC_NEW
,
600 'rc_minor' => $minor ?
1 : 0,
601 'rc_cur_id' => $title->getArticleID(),
602 'rc_user' => $user->getId(),
603 'rc_user_text' => $user->getName(),
604 'rc_comment' => $comment,
605 'rc_this_oldid' => $newId,
606 'rc_last_oldid' => 0,
607 'rc_bot' => $bot ?
1 : 0,
608 'rc_ip' => self
::checkIPAddress( $ip ),
609 'rc_patrolled' => intval( $patrol ),
610 'rc_new' => 1, # obsolete
612 'rc_new_len' => $size,
615 'rc_log_type' => null,
616 'rc_log_action' => '',
621 'prefixedDBkey' => $title->getPrefixedDBkey(),
622 'lastTimestamp' => 0,
625 'pageStatus' => 'created'
628 DeferredUpdates
::addCallableUpdate( function() use ( $rc ) {
630 if ( $rc->mAttribs
['rc_patrolled'] ) {
631 PatrolLog
::record( $rc, true, $rc->getPerformer() );
639 * @param string $timestamp
640 * @param Title $title
642 * @param string $actionComment
644 * @param string $type
645 * @param string $action
646 * @param Title $target
647 * @param string $logComment
648 * @param string $params
650 * @param string $actionCommentIRC
653 public static function notifyLog( $timestamp, &$title, &$user, $actionComment, $ip, $type,
654 $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = ''
656 global $wgLogRestrictions;
658 # Don't add private logs to RC!
659 if ( isset( $wgLogRestrictions[$type] ) && $wgLogRestrictions[$type] != '*' ) {
662 $rc = self
::newLogEntry( $timestamp, $title, $user, $actionComment, $ip, $type, $action,
663 $target, $logComment, $params, $newId, $actionCommentIRC );
670 * @param string $timestamp
671 * @param Title $title
673 * @param string $actionComment
675 * @param string $type
676 * @param string $action
677 * @param Title $target
678 * @param string $logComment
679 * @param string $params
681 * @param string $actionCommentIRC
682 * @return RecentChange
684 public static function newLogEntry( $timestamp, &$title, &$user, $actionComment, $ip,
685 $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '' ) {
688 ## Get pageStatus for email notification
689 switch ( $type . '-' . $action ) {
690 case 'delete-delete':
691 $pageStatus = 'deleted';
694 case 'move-move_redir':
695 $pageStatus = 'moved';
697 case 'delete-restore':
698 $pageStatus = 'restored';
700 case 'upload-upload':
701 $pageStatus = 'created';
703 case 'upload-overwrite':
705 $pageStatus = 'changed';
709 $rc = new RecentChange
;
710 $rc->mTitle
= $target;
711 $rc->mPerformer
= $user;
712 $rc->mAttribs
= array(
713 'rc_timestamp' => $timestamp,
714 'rc_namespace' => $target->getNamespace(),
715 'rc_title' => $target->getDBkey(),
717 'rc_source' => self
::SRC_LOG
,
719 'rc_cur_id' => $target->getArticleID(),
720 'rc_user' => $user->getId(),
721 'rc_user_text' => $user->getName(),
722 'rc_comment' => $logComment,
723 'rc_this_oldid' => 0,
724 'rc_last_oldid' => 0,
725 'rc_bot' => $user->isAllowed( 'bot' ) ?
$wgRequest->getBool( 'bot', true ) : 0,
726 'rc_ip' => self
::checkIPAddress( $ip ),
728 'rc_new' => 0, # obsolete
729 'rc_old_len' => null,
730 'rc_new_len' => null,
732 'rc_logid' => $newId,
733 'rc_log_type' => $type,
734 'rc_log_action' => $action,
735 'rc_params' => $params
739 'prefixedDBkey' => $title->getPrefixedDBkey(),
740 'lastTimestamp' => 0,
741 'actionComment' => $actionComment, // the comment appended to the action, passed from LogPage
742 'pageStatus' => $pageStatus,
743 'actionCommentIRC' => $actionCommentIRC
750 * Initialises the members of this object from a mysql row object
754 public function loadFromRow( $row ) {
755 $this->mAttribs
= get_object_vars( $row );
756 $this->mAttribs
['rc_timestamp'] = wfTimestamp( TS_MW
, $this->mAttribs
['rc_timestamp'] );
757 $this->mAttribs
['rc_deleted'] = $row->rc_deleted
; // MUST be set
761 * Get an attribute value
763 * @param string $name Attribute name
766 public function getAttribute( $name ) {
767 return isset( $this->mAttribs
[$name] ) ?
$this->mAttribs
[$name] : null;
773 public function getAttributes() {
774 return $this->mAttribs
;
778 * Gets the end part of the diff URL associated with this object
779 * Blank if no diff link should be displayed
780 * @param bool $forceCur
783 public function diffLinkTrail( $forceCur ) {
784 if ( $this->mAttribs
['rc_type'] == RC_EDIT
) {
785 $trail = "curid=" . (int)( $this->mAttribs
['rc_cur_id'] ) .
786 "&oldid=" . (int)( $this->mAttribs
['rc_last_oldid'] );
790 $trail .= '&diff=' . (int)( $this->mAttribs
['rc_this_oldid'] );
800 * Returns the change size (HTML).
801 * The lengths can be given optionally.
806 public function getCharacterDifference( $old = 0, $new = 0 ) {
808 $old = $this->mAttribs
['rc_old_len'];
811 $new = $this->mAttribs
['rc_new_len'];
813 if ( $old === null ||
$new === null ) {
817 return ChangesList
::showCharacterDifference( $old, $new );
820 private static function checkIPAddress( $ip ) {
823 if ( !IP
::isIPAddress( $ip ) ) {
824 throw new MWException( "Attempt to write \"" . $ip .
825 "\" as an IP address into recent changes" );
828 $ip = $wgRequest->getIP();
838 * Check whether the given timestamp is new enough to have a RC row with a given tolerance
839 * as the recentchanges table might not be cleared out regularly (so older entries might exist)
840 * or rows which will be deleted soon shouldn't be included.
842 * @param mixed $timestamp MWTimestamp compatible timestamp
843 * @param int $tolerance Tolerance in seconds
846 public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
849 return wfTimestamp( TS_UNIX
, $timestamp ) > time() - $tolerance - $wgRCMaxAge;
853 * Parses and returns the rc_params attribute
859 public function parseParams() {
860 $rcParams = $this->getAttribute( 'rc_params' );
862 MediaWiki\
suppressWarnings();
863 $unserializedParams = unserialize( $rcParams );
864 MediaWiki\restoreWarnings
();
866 return $unserializedParams;