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 );
387 // If a feed formatter returns null, this will otherwise cause an
388 // error in at least RedisPubSubFeedEngine.
389 // Not sure where/how this should best be handled.
393 $engine->send( $feed, $line );
398 * Gets the stream engine object for a given URI from $wgRCEngines
400 * @param string $uri URI to get the engine object for
401 * @throws MWException
402 * @return RCFeedEngine The engine object
404 public static function getEngine( $uri ) {
407 $scheme = parse_url( $uri, PHP_URL_SCHEME
);
409 throw new MWException( __FUNCTION__
. ": Invalid stream logger URI: '$uri'" );
412 if ( !isset( $wgRCEngines[$scheme] ) ) {
413 throw new MWException( __FUNCTION__
. ": Unknown stream logger URI scheme: $scheme" );
416 return new $wgRCEngines[$scheme];
420 * Mark a given change as patrolled
422 * @param RecentChange|int $change RecentChange or corresponding rc_id
423 * @param bool $auto For automatic patrol
424 * @return array See doMarkPatrolled(), or null if $change is not an existing rc_id
426 public static function markPatrolled( $change, $auto = false ) {
429 $change = $change instanceof RecentChange
431 : RecentChange
::newFromId( $change );
433 if ( !$change instanceof RecentChange
) {
437 return $change->doMarkPatrolled( $wgUser, $auto );
441 * Mark this RecentChange as patrolled
443 * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
444 * 'markedaspatrollederror-noautopatrol' as errors
445 * @param User $user User object doing the action
446 * @param bool $auto For automatic patrol
447 * @return array Array of permissions errors, see Title::getUserPermissionsErrors()
449 public function doMarkPatrolled( User
$user, $auto = false ) {
450 global $wgUseRCPatrol, $wgUseNPPatrol;
452 // If recentchanges patrol is disabled, only new pages
454 if ( !$wgUseRCPatrol && ( !$wgUseNPPatrol ||
$this->getAttribute( 'rc_type' ) != RC_NEW
) ) {
455 $errors[] = array( 'rcpatroldisabled' );
457 // Automatic patrol needs "autopatrol", ordinary patrol needs "patrol"
458 $right = $auto ?
'autopatrol' : 'patrol';
459 $errors = array_merge( $errors, $this->getTitle()->getUserPermissionsErrors( $right, $user ) );
460 if ( !Hooks
::run( 'MarkPatrolled', array( $this->getAttribute( 'rc_id' ), &$user, false ) ) ) {
461 $errors[] = array( 'hookaborted' );
463 // Users without the 'autopatrol' right can't patrol their
465 if ( $user->getName() === $this->getAttribute( 'rc_user_text' )
466 && !$user->isAllowed( 'autopatrol' )
468 $errors[] = array( 'markedaspatrollederror-noautopatrol' );
473 // If the change was patrolled already, do nothing
474 if ( $this->getAttribute( 'rc_patrolled' ) ) {
477 // Actually set the 'patrolled' flag in RC
478 $this->reallyMarkPatrolled();
479 // Log this patrol event
480 PatrolLog
::record( $this, $auto, $user );
481 Hooks
::run( 'MarkPatrolledComplete', array( $this->getAttribute( 'rc_id' ), &$user, false ) );
487 * Mark this RecentChange patrolled, without error checking
488 * @return int Number of affected rows
490 public function reallyMarkPatrolled() {
491 $dbw = wfGetDB( DB_MASTER
);
498 'rc_id' => $this->getAttribute( 'rc_id' )
502 // Invalidate the page cache after the page has been patrolled
503 // to make sure that the Patrol link isn't visible any longer!
504 $this->getTitle()->invalidateCache();
506 return $dbw->affectedRows();
510 * Makes an entry in the database corresponding to an edit
512 * @param string $timestamp
513 * @param Title $title
516 * @param string $comment
518 * @param string $lastTimestamp
521 * @param int $oldSize
522 * @param int $newSize
525 * @return RecentChange
527 public static function notifyEdit(
528 $timestamp, &$title, $minor, &$user, $comment, $oldId, $lastTimestamp,
529 $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0
531 $rc = new RecentChange
;
532 $rc->mTitle
= $title;
533 $rc->mPerformer
= $user;
534 $rc->mAttribs
= array(
535 'rc_timestamp' => $timestamp,
536 'rc_namespace' => $title->getNamespace(),
537 'rc_title' => $title->getDBkey(),
538 'rc_type' => RC_EDIT
,
539 'rc_source' => self
::SRC_EDIT
,
540 'rc_minor' => $minor ?
1 : 0,
541 'rc_cur_id' => $title->getArticleID(),
542 'rc_user' => $user->getId(),
543 'rc_user_text' => $user->getName(),
544 'rc_comment' => $comment,
545 'rc_this_oldid' => $newId,
546 'rc_last_oldid' => $oldId,
547 'rc_bot' => $bot ?
1 : 0,
548 'rc_ip' => self
::checkIPAddress( $ip ),
549 'rc_patrolled' => intval( $patrol ),
550 'rc_new' => 0, # obsolete
551 'rc_old_len' => $oldSize,
552 'rc_new_len' => $newSize,
555 'rc_log_type' => null,
556 'rc_log_action' => '',
561 'prefixedDBkey' => $title->getPrefixedDBkey(),
562 'lastTimestamp' => $lastTimestamp,
563 'oldSize' => $oldSize,
564 'newSize' => $newSize,
565 'pageStatus' => 'changed'
568 DeferredUpdates
::addCallableUpdate( function() use ( $rc ) {
570 if ( $rc->mAttribs
['rc_patrolled'] ) {
571 PatrolLog
::record( $rc, true, $rc->getPerformer() );
579 * Makes an entry in the database corresponding to page creation
580 * Note: the title object must be loaded with the new id using resetArticleID()
582 * @param string $timestamp
583 * @param Title $title
586 * @param string $comment
592 * @return RecentChange
594 public static function notifyNew(
595 $timestamp, &$title, $minor, &$user, $comment, $bot,
596 $ip = '', $size = 0, $newId = 0, $patrol = 0
598 $rc = new RecentChange
;
599 $rc->mTitle
= $title;
600 $rc->mPerformer
= $user;
601 $rc->mAttribs
= array(
602 'rc_timestamp' => $timestamp,
603 'rc_namespace' => $title->getNamespace(),
604 'rc_title' => $title->getDBkey(),
606 'rc_source' => self
::SRC_NEW
,
607 'rc_minor' => $minor ?
1 : 0,
608 'rc_cur_id' => $title->getArticleID(),
609 'rc_user' => $user->getId(),
610 'rc_user_text' => $user->getName(),
611 'rc_comment' => $comment,
612 'rc_this_oldid' => $newId,
613 'rc_last_oldid' => 0,
614 'rc_bot' => $bot ?
1 : 0,
615 'rc_ip' => self
::checkIPAddress( $ip ),
616 'rc_patrolled' => intval( $patrol ),
617 'rc_new' => 1, # obsolete
619 'rc_new_len' => $size,
622 'rc_log_type' => null,
623 'rc_log_action' => '',
628 'prefixedDBkey' => $title->getPrefixedDBkey(),
629 'lastTimestamp' => 0,
632 'pageStatus' => 'created'
635 DeferredUpdates
::addCallableUpdate( function() use ( $rc ) {
637 if ( $rc->mAttribs
['rc_patrolled'] ) {
638 PatrolLog
::record( $rc, true, $rc->getPerformer() );
646 * @param string $timestamp
647 * @param Title $title
649 * @param string $actionComment
651 * @param string $type
652 * @param string $action
653 * @param Title $target
654 * @param string $logComment
655 * @param string $params
657 * @param string $actionCommentIRC
660 public static function notifyLog( $timestamp, &$title, &$user, $actionComment, $ip, $type,
661 $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = ''
663 global $wgLogRestrictions;
665 # Don't add private logs to RC!
666 if ( isset( $wgLogRestrictions[$type] ) && $wgLogRestrictions[$type] != '*' ) {
669 $rc = self
::newLogEntry( $timestamp, $title, $user, $actionComment, $ip, $type, $action,
670 $target, $logComment, $params, $newId, $actionCommentIRC );
677 * @param string $timestamp
678 * @param Title $title
680 * @param string $actionComment
682 * @param string $type
683 * @param string $action
684 * @param Title $target
685 * @param string $logComment
686 * @param string $params
688 * @param string $actionCommentIRC
689 * @return RecentChange
691 public static function newLogEntry( $timestamp, &$title, &$user, $actionComment, $ip,
692 $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '' ) {
695 ## Get pageStatus for email notification
696 switch ( $type . '-' . $action ) {
697 case 'delete-delete':
698 $pageStatus = 'deleted';
701 case 'move-move_redir':
702 $pageStatus = 'moved';
704 case 'delete-restore':
705 $pageStatus = 'restored';
707 case 'upload-upload':
708 $pageStatus = 'created';
710 case 'upload-overwrite':
712 $pageStatus = 'changed';
716 $rc = new RecentChange
;
717 $rc->mTitle
= $target;
718 $rc->mPerformer
= $user;
719 $rc->mAttribs
= array(
720 'rc_timestamp' => $timestamp,
721 'rc_namespace' => $target->getNamespace(),
722 'rc_title' => $target->getDBkey(),
724 'rc_source' => self
::SRC_LOG
,
726 'rc_cur_id' => $target->getArticleID(),
727 'rc_user' => $user->getId(),
728 'rc_user_text' => $user->getName(),
729 'rc_comment' => $logComment,
730 'rc_this_oldid' => 0,
731 'rc_last_oldid' => 0,
732 'rc_bot' => $user->isAllowed( 'bot' ) ?
$wgRequest->getBool( 'bot', true ) : 0,
733 'rc_ip' => self
::checkIPAddress( $ip ),
735 'rc_new' => 0, # obsolete
736 'rc_old_len' => null,
737 'rc_new_len' => null,
739 'rc_logid' => $newId,
740 'rc_log_type' => $type,
741 'rc_log_action' => $action,
742 'rc_params' => $params
746 'prefixedDBkey' => $title->getPrefixedDBkey(),
747 'lastTimestamp' => 0,
748 'actionComment' => $actionComment, // the comment appended to the action, passed from LogPage
749 'pageStatus' => $pageStatus,
750 'actionCommentIRC' => $actionCommentIRC
757 * Initialises the members of this object from a mysql row object
761 public function loadFromRow( $row ) {
762 $this->mAttribs
= get_object_vars( $row );
763 $this->mAttribs
['rc_timestamp'] = wfTimestamp( TS_MW
, $this->mAttribs
['rc_timestamp'] );
764 $this->mAttribs
['rc_deleted'] = $row->rc_deleted
; // MUST be set
768 * Get an attribute value
770 * @param string $name Attribute name
773 public function getAttribute( $name ) {
774 return isset( $this->mAttribs
[$name] ) ?
$this->mAttribs
[$name] : null;
780 public function getAttributes() {
781 return $this->mAttribs
;
785 * Gets the end part of the diff URL associated with this object
786 * Blank if no diff link should be displayed
787 * @param bool $forceCur
790 public function diffLinkTrail( $forceCur ) {
791 if ( $this->mAttribs
['rc_type'] == RC_EDIT
) {
792 $trail = "curid=" . (int)( $this->mAttribs
['rc_cur_id'] ) .
793 "&oldid=" . (int)( $this->mAttribs
['rc_last_oldid'] );
797 $trail .= '&diff=' . (int)( $this->mAttribs
['rc_this_oldid'] );
807 * Returns the change size (HTML).
808 * The lengths can be given optionally.
813 public function getCharacterDifference( $old = 0, $new = 0 ) {
815 $old = $this->mAttribs
['rc_old_len'];
818 $new = $this->mAttribs
['rc_new_len'];
820 if ( $old === null ||
$new === null ) {
824 return ChangesList
::showCharacterDifference( $old, $new );
827 private static function checkIPAddress( $ip ) {
830 if ( !IP
::isIPAddress( $ip ) ) {
831 throw new MWException( "Attempt to write \"" . $ip .
832 "\" as an IP address into recent changes" );
835 $ip = $wgRequest->getIP();
845 * Check whether the given timestamp is new enough to have a RC row with a given tolerance
846 * as the recentchanges table might not be cleared out regularly (so older entries might exist)
847 * or rows which will be deleted soon shouldn't be included.
849 * @param mixed $timestamp MWTimestamp compatible timestamp
850 * @param int $tolerance Tolerance in seconds
853 public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
856 return wfTimestamp( TS_UNIX
, $timestamp ) > time() - $tolerance - $wgRCMaxAge;
860 * Parses and returns the rc_params attribute
866 public function parseParams() {
867 $rcParams = $this->getAttribute( 'rc_params' );
869 MediaWiki\
suppressWarnings();
870 $unserializedParams = unserialize( $rcParams );
871 MediaWiki\restoreWarnings
();
873 return $unserializedParams;