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.
93 * @var array Array of change types
95 private static $changeTypes = array(
99 'external' => RC_EXTERNAL
,
106 * @return RecentChange
108 public static function newFromRow( $row ) {
109 $rc = new RecentChange
;
110 $rc->loadFromRow( $row );
116 * Parsing text to RC_* constants
118 * @param string|array $type
119 * @throws MWException
120 * @return int|array RC_TYPE
122 public static function parseToRCType( $type ) {
123 if ( is_array( $type ) ) {
125 foreach ( $type as $t ) {
126 $retval[] = RecentChange
::parseToRCType( $t );
132 if ( !array_key_exists( $type, self
::$changeTypes ) ) {
133 throw new MWException( "Unknown type '$type'" );
135 return self
::$changeTypes[$type];
139 * Parsing RC_* constants to human-readable test
142 * @return string $type
144 public static function parseFromRCType( $rcType ) {
145 return array_search( $rcType, self
::$changeTypes, true ) ?
: "$rcType";
149 * Get an array of all change types
155 public static function getChangeTypes() {
156 return array_keys( self
::$changeTypes );
160 * Obtain the recent change with a given rc_id value
162 * @param int $rcid The rc_id value to retrieve
163 * @return RecentChange|null
165 public static function newFromId( $rcid ) {
166 return self
::newFromConds( array( 'rc_id' => $rcid ), __METHOD__
);
170 * Find the first recent change matching some specific conditions
172 * @param array $conds Array of conditions
173 * @param mixed $fname Override the method name in profiling/logs
174 * @param array $options Query options
175 * @return RecentChange|null
177 public static function newFromConds( $conds, $fname = __METHOD__
, $options = array() ) {
178 $dbr = wfGetDB( DB_SLAVE
);
179 $row = $dbr->selectRow( 'recentchanges', self
::selectFields(), $conds, $fname, $options );
180 if ( $row !== false ) {
181 return self
::newFromRow( $row );
188 * Return the list of recentchanges fields that should be selected to create
189 * a new recentchanges object.
192 public static function selectFields() {
224 * @param array $attribs
226 public function setAttribs( $attribs ) {
227 $this->mAttribs
= $attribs;
231 * @param array $extra
233 public function setExtra( $extra ) {
234 $this->mExtra
= $extra;
240 public function &getTitle() {
241 if ( $this->mTitle
=== false ) {
242 $this->mTitle
= Title
::makeTitle( $this->mAttribs
['rc_namespace'], $this->mAttribs
['rc_title'] );
245 return $this->mTitle
;
249 * Get the User object of the person who performed this change.
253 public function getPerformer() {
254 if ( $this->mPerformer
=== false ) {
255 if ( $this->mAttribs
['rc_user'] ) {
256 $this->mPerformer
= User
::newFromId( $this->mAttribs
['rc_user'] );
258 $this->mPerformer
= User
::newFromName( $this->mAttribs
['rc_user_text'], false );
262 return $this->mPerformer
;
266 * Writes the data in this object to the database
269 public function save( $noudp = false ) {
270 global $wgPutIPinRC, $wgUseEnotif, $wgShowUpdatedMarker, $wgContLang;
272 $dbw = wfGetDB( DB_MASTER
);
273 if ( !is_array( $this->mExtra
) ) {
274 $this->mExtra
= array();
277 if ( !$wgPutIPinRC ) {
278 $this->mAttribs
['rc_ip'] = '';
281 # If our database is strict about IP addresses, use NULL instead of an empty string
282 if ( $dbw->strictIPs() && $this->mAttribs
['rc_ip'] == '' ) {
283 unset( $this->mAttribs
['rc_ip'] );
286 # Trim spaces on user supplied text
287 $this->mAttribs
['rc_comment'] = trim( $this->mAttribs
['rc_comment'] );
289 # Make sure summary is truncated (whole multibyte characters)
290 $this->mAttribs
['rc_comment'] = $wgContLang->truncate( $this->mAttribs
['rc_comment'], 255 );
292 # Fixup database timestamps
293 $this->mAttribs
['rc_timestamp'] = $dbw->timestamp( $this->mAttribs
['rc_timestamp'] );
294 $this->mAttribs
['rc_id'] = $dbw->nextSequenceValue( 'recentchanges_rc_id_seq' );
296 ## If we are using foreign keys, an entry of 0 for the page_id will fail, so use NULL
297 if ( $dbw->cascadingDeletes() && $this->mAttribs
['rc_cur_id'] == 0 ) {
298 unset( $this->mAttribs
['rc_cur_id'] );
302 $dbw->insert( 'recentchanges', $this->mAttribs
, __METHOD__
);
305 $this->mAttribs
['rc_id'] = $dbw->insertId();
308 Hooks
::run( 'RecentChange_save', array( &$this ) );
310 # Notify external application via UDP
312 $this->notifyRCFeeds();
315 # E-mail notifications
316 if ( $wgUseEnotif ||
$wgShowUpdatedMarker ) {
317 $editor = $this->getPerformer();
318 $title = $this->getTitle();
320 if ( Hooks
::run( 'AbortEmailNotification', array( $editor, $title, $this ) ) ) {
321 # @todo FIXME: This would be better as an extension hook
322 $enotif = new EmailNotification();
323 $enotif->notifyOnPageChange( $editor, $title,
324 $this->mAttribs
['rc_timestamp'],
325 $this->mAttribs
['rc_comment'],
326 $this->mAttribs
['rc_minor'],
327 $this->mAttribs
['rc_last_oldid'],
328 $this->mExtra
['pageStatus'] );
332 // Update the cached list of active users
333 if ( $this->mAttribs
['rc_user'] > 0 ) {
334 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newCacheUpdateJob() );
339 * Notify all the feeds about the change.
340 * @param array $feeds Optional feeds to send to, defaults to $wgRCFeeds
342 public function notifyRCFeeds( array $feeds = null ) {
344 if ( $feeds === null ) {
348 $performer = $this->getPerformer();
350 foreach ( $feeds as $feed ) {
352 'omit_bots' => false,
353 'omit_anon' => false,
354 'omit_user' => false,
355 'omit_minor' => false,
356 'omit_patrolled' => false,
360 ( $feed['omit_bots'] && $this->mAttribs
['rc_bot'] ) ||
361 ( $feed['omit_anon'] && $performer->isAnon() ) ||
362 ( $feed['omit_user'] && !$performer->isAnon() ) ||
363 ( $feed['omit_minor'] && $this->mAttribs
['rc_minor'] ) ||
364 ( $feed['omit_patrolled'] && $this->mAttribs
['rc_patrolled'] ) ||
365 $this->mAttribs
['rc_type'] == RC_EXTERNAL
370 $engine = self
::getEngine( $feed['uri'] );
372 if ( isset( $this->mExtra
['actionCommentIRC'] ) ) {
373 $actionComment = $this->mExtra
['actionCommentIRC'];
375 $actionComment = null;
378 /** @var $formatter RCFeedFormatter */
379 $formatter = is_object( $feed['formatter'] ) ?
$feed['formatter'] : new $feed['formatter']();
380 $line = $formatter->getLine( $feed, $this, $actionComment );
383 // If a feed formatter returns null, this will otherwise cause an
384 // error in at least RedisPubSubFeedEngine.
385 // Not sure where/how this should best be handled.
389 $engine->send( $feed, $line );
394 * Gets the stream engine object for a given URI from $wgRCEngines
396 * @param string $uri URI to get the engine object for
397 * @throws MWException
398 * @return RCFeedEngine The engine object
400 public static function getEngine( $uri ) {
403 $scheme = parse_url( $uri, PHP_URL_SCHEME
);
405 throw new MWException( __FUNCTION__
. ": Invalid stream logger URI: '$uri'" );
408 if ( !isset( $wgRCEngines[$scheme] ) ) {
409 throw new MWException( __FUNCTION__
. ": Unknown stream logger URI scheme: $scheme" );
412 return new $wgRCEngines[$scheme];
416 * Mark a given change as patrolled
418 * @param RecentChange|int $change RecentChange or corresponding rc_id
419 * @param bool $auto For automatic patrol
420 * @return array See doMarkPatrolled(), or null if $change is not an existing rc_id
422 public static function markPatrolled( $change, $auto = false ) {
425 $change = $change instanceof RecentChange
427 : RecentChange
::newFromId( $change );
429 if ( !$change instanceof RecentChange
) {
433 return $change->doMarkPatrolled( $wgUser, $auto );
437 * Mark this RecentChange as patrolled
439 * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
440 * 'markedaspatrollederror-noautopatrol' as errors
441 * @param User $user User object doing the action
442 * @param bool $auto For automatic patrol
443 * @return array Array of permissions errors, see Title::getUserPermissionsErrors()
445 public function doMarkPatrolled( User
$user, $auto = false ) {
446 global $wgUseRCPatrol, $wgUseNPPatrol;
448 // If recentchanges patrol is disabled, only new pages
450 if ( !$wgUseRCPatrol && ( !$wgUseNPPatrol ||
$this->getAttribute( 'rc_type' ) != RC_NEW
) ) {
451 $errors[] = array( 'rcpatroldisabled' );
453 // Automatic patrol needs "autopatrol", ordinary patrol needs "patrol"
454 $right = $auto ?
'autopatrol' : 'patrol';
455 $errors = array_merge( $errors, $this->getTitle()->getUserPermissionsErrors( $right, $user ) );
456 if ( !Hooks
::run( 'MarkPatrolled', array( $this->getAttribute( 'rc_id' ), &$user, false ) ) ) {
457 $errors[] = array( 'hookaborted' );
459 // Users without the 'autopatrol' right can't patrol their
461 if ( $user->getName() === $this->getAttribute( 'rc_user_text' )
462 && !$user->isAllowed( 'autopatrol' )
464 $errors[] = array( 'markedaspatrollederror-noautopatrol' );
469 // If the change was patrolled already, do nothing
470 if ( $this->getAttribute( 'rc_patrolled' ) ) {
473 // Actually set the 'patrolled' flag in RC
474 $this->reallyMarkPatrolled();
475 // Log this patrol event
476 PatrolLog
::record( $this, $auto, $user );
477 Hooks
::run( 'MarkPatrolledComplete', array( $this->getAttribute( 'rc_id' ), &$user, false ) );
483 * Mark this RecentChange patrolled, without error checking
484 * @return int Number of affected rows
486 public function reallyMarkPatrolled() {
487 $dbw = wfGetDB( DB_MASTER
);
494 'rc_id' => $this->getAttribute( 'rc_id' )
498 // Invalidate the page cache after the page has been patrolled
499 // to make sure that the Patrol link isn't visible any longer!
500 $this->getTitle()->invalidateCache();
502 return $dbw->affectedRows();
506 * Makes an entry in the database corresponding to an edit
508 * @param string $timestamp
509 * @param Title $title
512 * @param string $comment
514 * @param string $lastTimestamp
517 * @param int $oldSize
518 * @param int $newSize
521 * @return RecentChange
523 public static function notifyEdit(
524 $timestamp, &$title, $minor, &$user, $comment, $oldId, $lastTimestamp,
525 $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0
527 $rc = new RecentChange
;
528 $rc->mTitle
= $title;
529 $rc->mPerformer
= $user;
530 $rc->mAttribs
= array(
531 'rc_timestamp' => $timestamp,
532 'rc_namespace' => $title->getNamespace(),
533 'rc_title' => $title->getDBkey(),
534 'rc_type' => RC_EDIT
,
535 'rc_source' => self
::SRC_EDIT
,
536 'rc_minor' => $minor ?
1 : 0,
537 'rc_cur_id' => $title->getArticleID(),
538 'rc_user' => $user->getId(),
539 'rc_user_text' => $user->getName(),
540 'rc_comment' => $comment,
541 'rc_this_oldid' => $newId,
542 'rc_last_oldid' => $oldId,
543 'rc_bot' => $bot ?
1 : 0,
544 'rc_ip' => self
::checkIPAddress( $ip ),
545 'rc_patrolled' => intval( $patrol ),
546 'rc_new' => 0, # obsolete
547 'rc_old_len' => $oldSize,
548 'rc_new_len' => $newSize,
551 'rc_log_type' => null,
552 'rc_log_action' => '',
557 'prefixedDBkey' => $title->getPrefixedDBkey(),
558 'lastTimestamp' => $lastTimestamp,
559 'oldSize' => $oldSize,
560 'newSize' => $newSize,
561 'pageStatus' => 'changed'
564 DeferredUpdates
::addCallableUpdate( function() use ( $rc ) {
566 if ( $rc->mAttribs
['rc_patrolled'] ) {
567 PatrolLog
::record( $rc, true, $rc->getPerformer() );
575 * Makes an entry in the database corresponding to page creation
576 * Note: the title object must be loaded with the new id using resetArticleID()
578 * @param string $timestamp
579 * @param Title $title
582 * @param string $comment
588 * @return RecentChange
590 public static function notifyNew(
591 $timestamp, &$title, $minor, &$user, $comment, $bot,
592 $ip = '', $size = 0, $newId = 0, $patrol = 0
594 $rc = new RecentChange
;
595 $rc->mTitle
= $title;
596 $rc->mPerformer
= $user;
597 $rc->mAttribs
= array(
598 'rc_timestamp' => $timestamp,
599 'rc_namespace' => $title->getNamespace(),
600 'rc_title' => $title->getDBkey(),
602 'rc_source' => self
::SRC_NEW
,
603 'rc_minor' => $minor ?
1 : 0,
604 'rc_cur_id' => $title->getArticleID(),
605 'rc_user' => $user->getId(),
606 'rc_user_text' => $user->getName(),
607 'rc_comment' => $comment,
608 'rc_this_oldid' => $newId,
609 'rc_last_oldid' => 0,
610 'rc_bot' => $bot ?
1 : 0,
611 'rc_ip' => self
::checkIPAddress( $ip ),
612 'rc_patrolled' => intval( $patrol ),
613 'rc_new' => 1, # obsolete
615 'rc_new_len' => $size,
618 'rc_log_type' => null,
619 'rc_log_action' => '',
624 'prefixedDBkey' => $title->getPrefixedDBkey(),
625 'lastTimestamp' => 0,
628 'pageStatus' => 'created'
631 DeferredUpdates
::addCallableUpdate( function() use ( $rc ) {
633 if ( $rc->mAttribs
['rc_patrolled'] ) {
634 PatrolLog
::record( $rc, true, $rc->getPerformer() );
642 * @param string $timestamp
643 * @param Title $title
645 * @param string $actionComment
647 * @param string $type
648 * @param string $action
649 * @param Title $target
650 * @param string $logComment
651 * @param string $params
653 * @param string $actionCommentIRC
656 public static function notifyLog( $timestamp, &$title, &$user, $actionComment, $ip, $type,
657 $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = ''
659 global $wgLogRestrictions;
661 # Don't add private logs to RC!
662 if ( isset( $wgLogRestrictions[$type] ) && $wgLogRestrictions[$type] != '*' ) {
665 $rc = self
::newLogEntry( $timestamp, $title, $user, $actionComment, $ip, $type, $action,
666 $target, $logComment, $params, $newId, $actionCommentIRC );
673 * @param string $timestamp
674 * @param Title $title
676 * @param string $actionComment
678 * @param string $type
679 * @param string $action
680 * @param Title $target
681 * @param string $logComment
682 * @param string $params
684 * @param string $actionCommentIRC
685 * @return RecentChange
687 public static function newLogEntry( $timestamp, &$title, &$user, $actionComment, $ip,
688 $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '' ) {
691 ## Get pageStatus for email notification
692 switch ( $type . '-' . $action ) {
693 case 'delete-delete':
694 $pageStatus = 'deleted';
697 case 'move-move_redir':
698 $pageStatus = 'moved';
700 case 'delete-restore':
701 $pageStatus = 'restored';
703 case 'upload-upload':
704 $pageStatus = 'created';
706 case 'upload-overwrite':
708 $pageStatus = 'changed';
712 $rc = new RecentChange
;
713 $rc->mTitle
= $target;
714 $rc->mPerformer
= $user;
715 $rc->mAttribs
= array(
716 'rc_timestamp' => $timestamp,
717 'rc_namespace' => $target->getNamespace(),
718 'rc_title' => $target->getDBkey(),
720 'rc_source' => self
::SRC_LOG
,
722 'rc_cur_id' => $target->getArticleID(),
723 'rc_user' => $user->getId(),
724 'rc_user_text' => $user->getName(),
725 'rc_comment' => $logComment,
726 'rc_this_oldid' => 0,
727 'rc_last_oldid' => 0,
728 'rc_bot' => $user->isAllowed( 'bot' ) ?
$wgRequest->getBool( 'bot', true ) : 0,
729 'rc_ip' => self
::checkIPAddress( $ip ),
731 'rc_new' => 0, # obsolete
732 'rc_old_len' => null,
733 'rc_new_len' => null,
735 'rc_logid' => $newId,
736 'rc_log_type' => $type,
737 'rc_log_action' => $action,
738 'rc_params' => $params
742 'prefixedDBkey' => $title->getPrefixedDBkey(),
743 'lastTimestamp' => 0,
744 'actionComment' => $actionComment, // the comment appended to the action, passed from LogPage
745 'pageStatus' => $pageStatus,
746 'actionCommentIRC' => $actionCommentIRC
753 * Initialises the members of this object from a mysql row object
757 public function loadFromRow( $row ) {
758 $this->mAttribs
= get_object_vars( $row );
759 $this->mAttribs
['rc_timestamp'] = wfTimestamp( TS_MW
, $this->mAttribs
['rc_timestamp'] );
760 $this->mAttribs
['rc_deleted'] = $row->rc_deleted
; // MUST be set
764 * Get an attribute value
766 * @param string $name Attribute name
769 public function getAttribute( $name ) {
770 return isset( $this->mAttribs
[$name] ) ?
$this->mAttribs
[$name] : null;
776 public function getAttributes() {
777 return $this->mAttribs
;
781 * Gets the end part of the diff URL associated with this object
782 * Blank if no diff link should be displayed
783 * @param bool $forceCur
786 public function diffLinkTrail( $forceCur ) {
787 if ( $this->mAttribs
['rc_type'] == RC_EDIT
) {
788 $trail = "curid=" . (int)( $this->mAttribs
['rc_cur_id'] ) .
789 "&oldid=" . (int)( $this->mAttribs
['rc_last_oldid'] );
793 $trail .= '&diff=' . (int)( $this->mAttribs
['rc_this_oldid'] );
803 * Returns the change size (HTML).
804 * The lengths can be given optionally.
809 public function getCharacterDifference( $old = 0, $new = 0 ) {
811 $old = $this->mAttribs
['rc_old_len'];
814 $new = $this->mAttribs
['rc_new_len'];
816 if ( $old === null ||
$new === null ) {
820 return ChangesList
::showCharacterDifference( $old, $new );
823 private static function checkIPAddress( $ip ) {
826 if ( !IP
::isIPAddress( $ip ) ) {
827 throw new MWException( "Attempt to write \"" . $ip .
828 "\" as an IP address into recent changes" );
831 $ip = $wgRequest->getIP();
841 * Check whether the given timestamp is new enough to have a RC row with a given tolerance
842 * as the recentchanges table might not be cleared out regularly (so older entries might exist)
843 * or rows which will be deleted soon shouldn't be included.
845 * @param mixed $timestamp MWTimestamp compatible timestamp
846 * @param int $tolerance Tolerance in seconds
849 public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
852 return wfTimestamp( TS_UNIX
, $timestamp ) > time() - $tolerance - $wgRCMaxAge;
856 * Parses and returns the rc_params attribute
862 public function parseParams() {
863 $rcParams = $this->getAttribute( 'rc_params' );
865 MediaWiki\
suppressWarnings();
866 $unserializedParams = unserialize( $rcParams );
867 MediaWiki\restoreWarnings
();
869 return $unserializedParams;