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 * @return RecentChange|null
176 public static function newFromConds( $conds, $fname = __METHOD__
) {
177 $dbr = wfGetDB( DB_SLAVE
);
178 $row = $dbr->selectRow( 'recentchanges', self
::selectFields(), $conds, $fname );
179 if ( $row !== false ) {
180 return self
::newFromRow( $row );
187 * Return the list of recentchanges fields that should be selected to create
188 * a new recentchanges object.
191 public static function selectFields() {
223 * @param array $attribs
225 public function setAttribs( $attribs ) {
226 $this->mAttribs
= $attribs;
230 * @param array $extra
232 public function setExtra( $extra ) {
233 $this->mExtra
= $extra;
239 public function &getTitle() {
240 if ( $this->mTitle
=== false ) {
241 $this->mTitle
= Title
::makeTitle( $this->mAttribs
['rc_namespace'], $this->mAttribs
['rc_title'] );
244 return $this->mTitle
;
248 * Get the User object of the person who performed this change.
252 public function getPerformer() {
253 if ( $this->mPerformer
=== false ) {
254 if ( $this->mAttribs
['rc_user'] ) {
255 $this->mPerformer
= User
::newFromId( $this->mAttribs
['rc_user'] );
257 $this->mPerformer
= User
::newFromName( $this->mAttribs
['rc_user_text'], false );
261 return $this->mPerformer
;
265 * Writes the data in this object to the database
268 public function save( $noudp = false ) {
269 global $wgPutIPinRC, $wgUseEnotif, $wgShowUpdatedMarker, $wgContLang;
271 $dbw = wfGetDB( DB_MASTER
);
272 if ( !is_array( $this->mExtra
) ) {
273 $this->mExtra
= array();
276 if ( !$wgPutIPinRC ) {
277 $this->mAttribs
['rc_ip'] = '';
280 # If our database is strict about IP addresses, use NULL instead of an empty string
281 if ( $dbw->strictIPs() && $this->mAttribs
['rc_ip'] == '' ) {
282 unset( $this->mAttribs
['rc_ip'] );
285 # Trim spaces on user supplied text
286 $this->mAttribs
['rc_comment'] = trim( $this->mAttribs
['rc_comment'] );
288 # Make sure summary is truncated (whole multibyte characters)
289 $this->mAttribs
['rc_comment'] = $wgContLang->truncate( $this->mAttribs
['rc_comment'], 255 );
291 # Fixup database timestamps
292 $this->mAttribs
['rc_timestamp'] = $dbw->timestamp( $this->mAttribs
['rc_timestamp'] );
293 $this->mAttribs
['rc_id'] = $dbw->nextSequenceValue( 'recentchanges_rc_id_seq' );
295 # # If we are using foreign keys, an entry of 0 for the page_id will fail, so use NULL
296 if ( $dbw->cascadingDeletes() && $this->mAttribs
['rc_cur_id'] == 0 ) {
297 unset( $this->mAttribs
['rc_cur_id'] );
301 $dbw->insert( 'recentchanges', $this->mAttribs
, __METHOD__
);
304 $this->mAttribs
['rc_id'] = $dbw->insertId();
307 Hooks
::run( 'RecentChange_save', array( &$this ) );
309 # Notify external application via UDP
311 $this->notifyRCFeeds();
314 # E-mail notifications
315 if ( $wgUseEnotif ||
$wgShowUpdatedMarker ) {
316 $editor = $this->getPerformer();
317 $title = $this->getTitle();
319 if ( Hooks
::run( 'AbortEmailNotification', array( $editor, $title, $this ) ) ) {
320 # @todo FIXME: This would be better as an extension hook
321 $enotif = new EmailNotification();
322 $enotif->notifyOnPageChange( $editor, $title,
323 $this->mAttribs
['rc_timestamp'],
324 $this->mAttribs
['rc_comment'],
325 $this->mAttribs
['rc_minor'],
326 $this->mAttribs
['rc_last_oldid'],
327 $this->mExtra
['pageStatus'] );
331 // Update the cached list of active users
332 if ( $this->mAttribs
['rc_user'] > 0 ) {
333 JobQueueGroup
::singleton()->lazyPush( RecentChangesUpdateJob
::newCacheUpdateJob() );
338 * Notify all the feeds about the change.
339 * @param array $feeds Optional feeds to send to, defaults to $wgRCFeeds
341 public function notifyRCFeeds( array $feeds = null ) {
343 if ( $feeds === null ) {
347 $performer = $this->getPerformer();
349 foreach ( $feeds as $feed ) {
351 'omit_bots' => false,
352 'omit_anon' => false,
353 'omit_user' => false,
354 'omit_minor' => false,
355 'omit_patrolled' => false,
359 ( $feed['omit_bots'] && $this->mAttribs
['rc_bot'] ) ||
360 ( $feed['omit_anon'] && $performer->isAnon() ) ||
361 ( $feed['omit_user'] && !$performer->isAnon() ) ||
362 ( $feed['omit_minor'] && $this->mAttribs
['rc_minor'] ) ||
363 ( $feed['omit_patrolled'] && $this->mAttribs
['rc_patrolled'] ) ||
364 $this->mAttribs
['rc_type'] == RC_EXTERNAL
369 $engine = self
::getEngine( $feed['uri'] );
371 if ( isset( $this->mExtra
['actionCommentIRC'] ) ) {
372 $actionComment = $this->mExtra
['actionCommentIRC'];
374 $actionComment = null;
377 /** @var $formatter RCFeedFormatter */
378 $formatter = is_object( $feed['formatter'] ) ?
$feed['formatter'] : new $feed['formatter']();
379 $line = $formatter->getLine( $feed, $this, $actionComment );
382 // If a feed formatter returns null, this will otherwise cause an
383 // error in at least RedisPubSubFeedEngine.
384 // Not sure where/how this should best be handled.
388 $engine->send( $feed, $line );
393 * Gets the stream engine object for a given URI from $wgRCEngines
395 * @param string $uri URI to get the engine object for
396 * @throws MWException
397 * @return RCFeedEngine The engine object
399 public static function getEngine( $uri ) {
402 $scheme = parse_url( $uri, PHP_URL_SCHEME
);
404 throw new MWException( __FUNCTION__
. ": Invalid stream logger URI: '$uri'" );
407 if ( !isset( $wgRCEngines[$scheme] ) ) {
408 throw new MWException( __FUNCTION__
. ": Unknown stream logger URI scheme: $scheme" );
411 return new $wgRCEngines[$scheme];
415 * Mark a given change as patrolled
417 * @param RecentChange|int $change RecentChange or corresponding rc_id
418 * @param bool $auto For automatic patrol
419 * @return array See doMarkPatrolled(), or null if $change is not an existing rc_id
421 public static function markPatrolled( $change, $auto = false ) {
424 $change = $change instanceof RecentChange
426 : RecentChange
::newFromId( $change );
428 if ( !$change instanceof RecentChange
) {
432 return $change->doMarkPatrolled( $wgUser, $auto );
436 * Mark this RecentChange as patrolled
438 * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
439 * 'markedaspatrollederror-noautopatrol' as errors
440 * @param User $user User object doing the action
441 * @param bool $auto For automatic patrol
442 * @return array Array of permissions errors, see Title::getUserPermissionsErrors()
444 public function doMarkPatrolled( User
$user, $auto = false ) {
445 global $wgUseRCPatrol, $wgUseNPPatrol;
447 // If recentchanges patrol is disabled, only new pages
449 if ( !$wgUseRCPatrol && ( !$wgUseNPPatrol ||
$this->getAttribute( 'rc_type' ) != RC_NEW
) ) {
450 $errors[] = array( 'rcpatroldisabled' );
452 // Automatic patrol needs "autopatrol", ordinary patrol needs "patrol"
453 $right = $auto ?
'autopatrol' : 'patrol';
454 $errors = array_merge( $errors, $this->getTitle()->getUserPermissionsErrors( $right, $user ) );
455 if ( !Hooks
::run( 'MarkPatrolled', array( $this->getAttribute( 'rc_id' ), &$user, false ) ) ) {
456 $errors[] = array( 'hookaborted' );
458 // Users without the 'autopatrol' right can't patrol their
460 if ( $user->getName() === $this->getAttribute( 'rc_user_text' )
461 && !$user->isAllowed( 'autopatrol' )
463 $errors[] = array( 'markedaspatrollederror-noautopatrol' );
468 // If the change was patrolled already, do nothing
469 if ( $this->getAttribute( 'rc_patrolled' ) ) {
472 // Actually set the 'patrolled' flag in RC
473 $this->reallyMarkPatrolled();
474 // Log this patrol event
475 PatrolLog
::record( $this, $auto, $user );
476 Hooks
::run( 'MarkPatrolledComplete', array( $this->getAttribute( 'rc_id' ), &$user, false ) );
482 * Mark this RecentChange patrolled, without error checking
483 * @return int Number of affected rows
485 public function reallyMarkPatrolled() {
486 $dbw = wfGetDB( DB_MASTER
);
493 'rc_id' => $this->getAttribute( 'rc_id' )
497 // Invalidate the page cache after the page has been patrolled
498 // to make sure that the Patrol link isn't visible any longer!
499 $this->getTitle()->invalidateCache();
501 return $dbw->affectedRows();
505 * Makes an entry in the database corresponding to an edit
507 * @param string $timestamp
508 * @param Title $title
511 * @param string $comment
513 * @param string $lastTimestamp
516 * @param int $oldSize
517 * @param int $newSize
520 * @return RecentChange
522 public static function notifyEdit(
523 $timestamp, &$title, $minor, &$user, $comment, $oldId, $lastTimestamp,
524 $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0
526 $rc = new RecentChange
;
527 $rc->mTitle
= $title;
528 $rc->mPerformer
= $user;
529 $rc->mAttribs
= array(
530 'rc_timestamp' => $timestamp,
531 'rc_namespace' => $title->getNamespace(),
532 'rc_title' => $title->getDBkey(),
533 'rc_type' => RC_EDIT
,
534 'rc_source' => self
::SRC_EDIT
,
535 'rc_minor' => $minor ?
1 : 0,
536 'rc_cur_id' => $title->getArticleID(),
537 'rc_user' => $user->getId(),
538 'rc_user_text' => $user->getName(),
539 'rc_comment' => $comment,
540 'rc_this_oldid' => $newId,
541 'rc_last_oldid' => $oldId,
542 'rc_bot' => $bot ?
1 : 0,
543 'rc_ip' => self
::checkIPAddress( $ip ),
544 'rc_patrolled' => intval( $patrol ),
545 'rc_new' => 0, # obsolete
546 'rc_old_len' => $oldSize,
547 'rc_new_len' => $newSize,
550 'rc_log_type' => null,
551 'rc_log_action' => '',
556 'prefixedDBkey' => $title->getPrefixedDBkey(),
557 'lastTimestamp' => $lastTimestamp,
558 'oldSize' => $oldSize,
559 'newSize' => $newSize,
560 'pageStatus' => 'changed'
563 DeferredUpdates
::addCallableUpdate( function() use ( $rc ) {
565 if ( $rc->mAttribs
['rc_patrolled'] ) {
566 PatrolLog
::record( $rc, true, $rc->getPerformer() );
574 * Makes an entry in the database corresponding to page creation
575 * Note: the title object must be loaded with the new id using resetArticleID()
577 * @param string $timestamp
578 * @param Title $title
581 * @param string $comment
587 * @return RecentChange
589 public static function notifyNew(
590 $timestamp, &$title, $minor, &$user, $comment, $bot,
591 $ip = '', $size = 0, $newId = 0, $patrol = 0
593 $rc = new RecentChange
;
594 $rc->mTitle
= $title;
595 $rc->mPerformer
= $user;
596 $rc->mAttribs
= array(
597 'rc_timestamp' => $timestamp,
598 'rc_namespace' => $title->getNamespace(),
599 'rc_title' => $title->getDBkey(),
601 'rc_source' => self
::SRC_NEW
,
602 'rc_minor' => $minor ?
1 : 0,
603 'rc_cur_id' => $title->getArticleID(),
604 'rc_user' => $user->getId(),
605 'rc_user_text' => $user->getName(),
606 'rc_comment' => $comment,
607 'rc_this_oldid' => $newId,
608 'rc_last_oldid' => 0,
609 'rc_bot' => $bot ?
1 : 0,
610 'rc_ip' => self
::checkIPAddress( $ip ),
611 'rc_patrolled' => intval( $patrol ),
612 'rc_new' => 1, # obsolete
614 'rc_new_len' => $size,
617 'rc_log_type' => null,
618 'rc_log_action' => '',
623 'prefixedDBkey' => $title->getPrefixedDBkey(),
624 'lastTimestamp' => 0,
627 'pageStatus' => 'created'
630 DeferredUpdates
::addCallableUpdate( function() use ( $rc ) {
632 if ( $rc->mAttribs
['rc_patrolled'] ) {
633 PatrolLog
::record( $rc, true, $rc->getPerformer() );
641 * @param string $timestamp
642 * @param Title $title
644 * @param string $actionComment
646 * @param string $type
647 * @param string $action
648 * @param Title $target
649 * @param string $logComment
650 * @param string $params
652 * @param string $actionCommentIRC
655 public static function notifyLog( $timestamp, &$title, &$user, $actionComment, $ip, $type,
656 $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = ''
658 global $wgLogRestrictions;
660 # Don't add private logs to RC!
661 if ( isset( $wgLogRestrictions[$type] ) && $wgLogRestrictions[$type] != '*' ) {
664 $rc = self
::newLogEntry( $timestamp, $title, $user, $actionComment, $ip, $type, $action,
665 $target, $logComment, $params, $newId, $actionCommentIRC );
672 * @param string $timestamp
673 * @param Title $title
675 * @param string $actionComment
677 * @param string $type
678 * @param string $action
679 * @param Title $target
680 * @param string $logComment
681 * @param string $params
683 * @param string $actionCommentIRC
684 * @return RecentChange
686 public static function newLogEntry( $timestamp, &$title, &$user, $actionComment, $ip,
687 $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '' ) {
690 # # Get pageStatus for email notification
691 switch ( $type . '-' . $action ) {
692 case 'delete-delete':
693 $pageStatus = 'deleted';
696 case 'move-move_redir':
697 $pageStatus = 'moved';
699 case 'delete-restore':
700 $pageStatus = 'restored';
702 case 'upload-upload':
703 $pageStatus = 'created';
705 case 'upload-overwrite':
707 $pageStatus = 'changed';
711 $rc = new RecentChange
;
712 $rc->mTitle
= $target;
713 $rc->mPerformer
= $user;
714 $rc->mAttribs
= array(
715 'rc_timestamp' => $timestamp,
716 'rc_namespace' => $target->getNamespace(),
717 'rc_title' => $target->getDBkey(),
719 'rc_source' => self
::SRC_LOG
,
721 'rc_cur_id' => $target->getArticleID(),
722 'rc_user' => $user->getId(),
723 'rc_user_text' => $user->getName(),
724 'rc_comment' => $logComment,
725 'rc_this_oldid' => 0,
726 'rc_last_oldid' => 0,
727 'rc_bot' => $user->isAllowed( 'bot' ) ?
$wgRequest->getBool( 'bot', true ) : 0,
728 'rc_ip' => self
::checkIPAddress( $ip ),
730 'rc_new' => 0, # obsolete
731 'rc_old_len' => null,
732 'rc_new_len' => null,
734 'rc_logid' => $newId,
735 'rc_log_type' => $type,
736 'rc_log_action' => $action,
737 'rc_params' => $params
741 'prefixedDBkey' => $title->getPrefixedDBkey(),
742 'lastTimestamp' => 0,
743 'actionComment' => $actionComment, // the comment appended to the action, passed from LogPage
744 'pageStatus' => $pageStatus,
745 'actionCommentIRC' => $actionCommentIRC
752 * Initialises the members of this object from a mysql row object
756 public function loadFromRow( $row ) {
757 $this->mAttribs
= get_object_vars( $row );
758 $this->mAttribs
['rc_timestamp'] = wfTimestamp( TS_MW
, $this->mAttribs
['rc_timestamp'] );
759 $this->mAttribs
['rc_deleted'] = $row->rc_deleted
; // MUST be set
763 * Get an attribute value
765 * @param string $name Attribute name
768 public function getAttribute( $name ) {
769 return isset( $this->mAttribs
[$name] ) ?
$this->mAttribs
[$name] : null;
775 public function getAttributes() {
776 return $this->mAttribs
;
780 * Gets the end part of the diff URL associated with this object
781 * Blank if no diff link should be displayed
782 * @param bool $forceCur
785 public function diffLinkTrail( $forceCur ) {
786 if ( $this->mAttribs
['rc_type'] == RC_EDIT
) {
787 $trail = "curid=" . (int)( $this->mAttribs
['rc_cur_id'] ) .
788 "&oldid=" . (int)( $this->mAttribs
['rc_last_oldid'] );
792 $trail .= '&diff=' . (int)( $this->mAttribs
['rc_this_oldid'] );
802 * Returns the change size (HTML).
803 * The lengths can be given optionally.
808 public function getCharacterDifference( $old = 0, $new = 0 ) {
810 $old = $this->mAttribs
['rc_old_len'];
813 $new = $this->mAttribs
['rc_new_len'];
815 if ( $old === null ||
$new === null ) {
819 return ChangesList
::showCharacterDifference( $old, $new );
822 private static function checkIPAddress( $ip ) {
825 if ( !IP
::isIPAddress( $ip ) ) {
826 throw new MWException( "Attempt to write \"" . $ip .
827 "\" as an IP address into recent changes" );
830 $ip = $wgRequest->getIP();
840 * Check whether the given timestamp is new enough to have a RC row with a given tolerance
841 * as the recentchanges table might not be cleared out regularly (so older entries might exist)
842 * or rows which will be deleted soon shouldn't be included.
844 * @param mixed $timestamp MWTimestamp compatible timestamp
845 * @param int $tolerance Tolerance in seconds
848 public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
851 return wfTimestamp( TS_UNIX
, $timestamp ) > time() - $tolerance - $wgRCMaxAge;
855 * Parses and returns the rc_params attribute
861 public function parseParams() {
862 $rcParams = $this->getAttribute( 'rc_params' );
864 MediaWiki\
suppressWarnings();
865 $unserializedParams = unserialize( $rcParams );
866 MediaWiki\restoreWarnings
();
868 return $unserializedParams;