3 * Base class for all changes lists.
5 * The class is used for formatting recent changes, related changes and watchlist.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Linker\LinkRenderer
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\Rdbms\ResultWrapper
;
28 class ChangesList
extends ContextSource
{
34 protected $watchlist = false;
38 protected $rcCacheIndex;
39 protected $rclistOpen;
40 protected $rcMoveIndex;
43 protected $watchMsgCache;
48 protected $linkRenderer;
51 * Changeslist constructor
53 * @param Skin|IContextSource $obj
55 public function __construct( $obj ) {
56 if ( $obj instanceof IContextSource
) {
57 $this->setContext( $obj );
58 $this->skin
= $obj->getSkin();
60 $this->setContext( $obj->getContext() );
63 $this->preCacheMessages();
64 $this->watchMsgCache
= new HashBagOStuff( [ 'maxKeys' => 50 ] );
65 $this->linkRenderer
= MediaWikiServices
::getInstance()->getLinkRenderer();
69 * Fetch an appropriate changes list class for the specified context
70 * Some users might want to use an enhanced list format, for instance
72 * @param IContextSource $context
75 public static function newFromContext( IContextSource
$context ) {
76 $user = $context->getUser();
77 $sk = $context->getSkin();
79 if ( Hooks
::run( 'FetchChangesList', [ $user, &$sk, &$list ] ) ) {
80 $new = $context->getRequest()->getBool( 'enhanced', $user->getOption( 'usenewrc' ) );
82 return $new ?
new EnhancedChangesList( $context ) : new OldChangesList( $context );
93 * @param RecentChange $rc Passed by reference
94 * @param bool $watched (default false)
95 * @param int $linenumber (default null)
99 public function recentChangesLine( &$rc, $watched = false, $linenumber = null ) {
100 throw new RuntimeException( 'recentChangesLine should be implemented' );
104 * Sets the list to use a "<li class='watchlist-(namespace)-(page)'>" tag
107 public function setWatchlistDivs( $value = true ) {
108 $this->watchlist
= $value;
112 * @return bool True when setWatchlistDivs has been called
115 public function isWatchlist() {
116 return (bool)$this->watchlist
;
120 * As we use the same small set of messages in various methods and that
121 * they are called often, we call them once and save them in $this->message
123 private function preCacheMessages() {
124 if ( !isset( $this->message
) ) {
126 'cur', 'diff', 'hist', 'enhancedrc-history', 'last', 'blocklink', 'history',
127 'semicolon-separator', 'pipe-separator' ] as $msg
129 $this->message
[$msg] = $this->msg( $msg )->escaped();
135 * Returns the appropriate flags for new page, minor change and patrolling
136 * @param array $flags Associative array of 'flag' => Bool
137 * @param string $nothing To use for empty space
140 public function recentChangesFlags( $flags, $nothing = ' ' ) {
142 foreach ( array_keys( $this->getConfig()->get( 'RecentChangesFlags' ) ) as $flag ) {
143 $f .= isset( $flags[$flag] ) && $flags[$flag]
144 ? self
::flag( $flag, $this->getContext() )
152 * Get an array of default HTML class attributes for the change.
154 * @param RecentChange|RCCacheEntry $rc
155 * @param string|bool $watched Optionally timestamp for adding watched class
157 * @return array of classes
159 protected function getHTMLClasses( $rc, $watched ) {
161 $logType = $rc->mAttribs
['rc_log_type'];
162 $prefix = 'mw-changeslist-';
165 $classes[] = Sanitizer
::escapeClass( $prefix . 'log-' . $logType );
167 $classes[] = Sanitizer
::escapeClass( $prefix . 'ns' .
168 $rc->mAttribs
['rc_namespace'] . '-' . $rc->mAttribs
['rc_title'] );
171 // Indicate watched status on the line to allow for more
172 // comprehensive styling.
173 $classes[] = $watched && $rc->mAttribs
['rc_timestamp'] >= $watched
174 ?
$prefix . 'line-watched'
175 : $prefix . 'line-not-watched';
177 $classes = array_merge( $classes, $this->getHTMLClassesForFilters( $rc ) );
182 protected function getHTMLClassesForFilters( $rc ) {
184 $prefix = 'mw-changeslist-';
186 $classes[] = $prefix . ( $rc->getAttribute( 'rc_bot' ) ?
'bot' : 'human' );
187 $classes[] = $prefix . ( $rc->getAttribute( 'rc_user' ) ?
'liu' : 'anon' );
188 $classes[] = $prefix . ( $rc->getAttribute( 'rc_minor' ) ?
'minor' : 'major' );
189 $classes[] = $prefix .
190 ( $rc->getAttribute( 'rc_patrolled' ) ?
'patrolled' : 'unpatrolled' );
191 $classes[] = $prefix .
192 ( $this->getUser()->equals( $rc->getPerformer() ) ?
'self' : 'others' );
193 $classes[] = $prefix . 'src-' . str_replace( '.', '-', $rc->getAttribute( 'rc_source' ) );
195 $performer = $rc->getPerformer();
196 if ( $performer && $performer->isLoggedIn() ) {
197 $classes[] = $prefix . 'user-' . $performer->getExperienceLevel();
204 * Make an "<abbr>" element for a given change flag. The flag indicating a new page, minor edit,
205 * bot edit, or unpatrolled edit. In English it typically contains "N", "m", "b", or "!".
207 * @param string $flag One key of $wgRecentChangesFlags
208 * @param IContextSource $context
209 * @return string HTML
211 public static function flag( $flag, IContextSource
$context = null ) {
212 static $map = [ 'minoredit' => 'minor', 'botedit' => 'bot' ];
213 static $flagInfos = null;
215 if ( is_null( $flagInfos ) ) {
216 global $wgRecentChangesFlags;
218 foreach ( $wgRecentChangesFlags as $key => $value ) {
219 $flagInfos[$key]['letter'] = $value['letter'];
220 $flagInfos[$key]['title'] = $value['title'];
221 // Allow customized class name, fall back to flag name
222 $flagInfos[$key]['class'] = isset( $value['class'] ) ?
$value['class'] : $key;
226 $context = $context ?
: RequestContext
::getMain();
228 // Inconsistent naming, kepted for b/c
229 if ( isset( $map[$flag] ) ) {
233 $info = $flagInfos[$flag];
234 return Html
::element( 'abbr', [
235 'class' => $info['class'],
236 'title' => wfMessage( $info['title'] )->setContext( $context )->text(),
237 ], wfMessage( $info['letter'] )->setContext( $context )->text() );
241 * Returns text for the start of the tabular part of RC
244 public function beginRecentChangesList() {
245 $this->rc_cache
= [];
246 $this->rcMoveIndex
= 0;
247 $this->rcCacheIndex
= 0;
248 $this->lastdate
= '';
249 $this->rclistOpen
= false;
250 $this->getOutput()->addModuleStyles( 'mediawiki.special.changeslist' );
252 return '<div class="mw-changeslist">';
256 * @param ResultWrapper|array $rows
258 public function initChangesListRows( $rows ) {
259 Hooks
::run( 'ChangesListInitRows', [ $this, $rows ] );
263 * Show formatted char difference
265 * Needs the css module 'mediawiki.special.changeslist' to style output
267 * @param int $old Number of bytes
268 * @param int $new Number of bytes
269 * @param IContextSource $context
272 public static function showCharacterDifference( $old, $new, IContextSource
$context = null ) {
274 $context = RequestContext
::getMain();
279 $szdiff = $new - $old;
281 $lang = $context->getLanguage();
282 $config = $context->getConfig();
283 $code = $lang->getCode();
284 static $fastCharDiff = [];
285 if ( !isset( $fastCharDiff[$code] ) ) {
286 $fastCharDiff[$code] = $config->get( 'MiserMode' )
287 ||
$context->msg( 'rc-change-size' )->plain() === '$1';
290 $formattedSize = $lang->formatNum( $szdiff );
292 if ( !$fastCharDiff[$code] ) {
293 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
296 if ( abs( $szdiff ) > abs( $config->get( 'RCChangedSizeThreshold' ) ) ) {
302 if ( $szdiff === 0 ) {
303 $formattedSizeClass = 'mw-plusminus-null';
304 } elseif ( $szdiff > 0 ) {
305 $formattedSize = '+' . $formattedSize;
306 $formattedSizeClass = 'mw-plusminus-pos';
308 $formattedSizeClass = 'mw-plusminus-neg';
311 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
313 return Html
::element( $tag,
314 [ 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ],
315 $context->msg( 'parentheses', $formattedSize )->plain() ) . $lang->getDirMark();
319 * Format the character difference of one or several changes.
321 * @param RecentChange $old
322 * @param RecentChange $new Last change to use, if not provided, $old will be used
323 * @return string HTML fragment
325 public function formatCharacterDifference( RecentChange
$old, RecentChange
$new = null ) {
326 $oldlen = $old->mAttribs
['rc_old_len'];
329 $newlen = $new->mAttribs
['rc_new_len'];
331 $newlen = $old->mAttribs
['rc_new_len'];
334 if ( $oldlen === null ||
$newlen === null ) {
338 return self
::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
342 * Returns text for the end of RC
345 public function endRecentChangesList() {
346 $out = $this->rclistOpen ?
"</ul>\n" : '';
353 * @param string $s HTML to update
354 * @param mixed $rc_timestamp
356 public function insertDateHeader( &$s, $rc_timestamp ) {
357 # Make date header if necessary
358 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
359 if ( $date != $this->lastdate
) {
360 if ( $this->lastdate
!= '' ) {
363 $s .= Xml
::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
364 $this->lastdate
= $date;
365 $this->rclistOpen
= true;
370 * @param string $s HTML to update
371 * @param Title $title
372 * @param string $logtype
374 public function insertLog( &$s, $title, $logtype ) {
375 $page = new LogPage( $logtype );
376 $logname = $page->getName()->setContext( $this->getContext() )->text();
377 $s .= $this->msg( 'parentheses' )->rawParams(
378 $this->linkRenderer
->makeKnownLink( $title, $logname )
383 * @param string $s HTML to update
384 * @param RecentChange $rc
385 * @param bool|null $unpatrolled Unused variable, since 1.27.
387 public function insertDiffHist( &$s, &$rc, $unpatrolled = null ) {
390 $rc->mAttribs
['rc_type'] == RC_NEW ||
391 $rc->mAttribs
['rc_type'] == RC_LOG ||
392 $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
394 $diffLink = $this->message
['diff'];
395 } elseif ( !self
::userCan( $rc, Revision
::DELETED_TEXT
, $this->getUser() ) ) {
396 $diffLink = $this->message
['diff'];
399 'curid' => $rc->mAttribs
['rc_cur_id'],
400 'diff' => $rc->mAttribs
['rc_this_oldid'],
401 'oldid' => $rc->mAttribs
['rc_last_oldid']
404 $diffLink = $this->linkRenderer
->makeKnownLink(
406 new HtmlArmor( $this->message
['diff'] ),
407 [ 'class' => 'mw-changeslist-diff' ],
411 if ( $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
) {
412 $diffhist = $diffLink . $this->message
['pipe-separator'] . $this->message
['hist'];
414 $diffhist = $diffLink . $this->message
['pipe-separator'];
416 $diffhist .= $this->linkRenderer
->makeKnownLink(
418 new HtmlArmor( $this->message
['hist'] ),
419 [ 'class' => 'mw-changeslist-history' ],
421 'curid' => $rc->mAttribs
['rc_cur_id'],
422 'action' => 'history'
427 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
428 $s .= $this->msg( 'parentheses' )->rawParams( $diffhist )->escaped() .
429 ' <span class="mw-changeslist-separator">. .</span> ';
433 * @param string $s Article link will be appended to this string, in place.
434 * @param RecentChange $rc
435 * @param bool $unpatrolled
436 * @param bool $watched
437 * @deprecated since 1.27, use getArticleLink instead.
439 public function insertArticleLink( &$s, RecentChange
$rc, $unpatrolled, $watched ) {
440 $s .= $this->getArticleLink( $rc, $unpatrolled, $watched );
444 * @param RecentChange $rc
445 * @param bool $unpatrolled
446 * @param bool $watched
447 * @return string HTML
450 public function getArticleLink( &$rc, $unpatrolled, $watched ) {
452 if ( $rc->getTitle()->isRedirect() ) {
453 $params = [ 'redirect' => 'no' ];
456 $articlelink = $this->linkRenderer
->makeLink(
459 [ 'class' => 'mw-changeslist-title' ],
462 if ( $this->isDeleted( $rc, Revision
::DELETED_TEXT
) ) {
463 $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
465 # To allow for boldening pages watched by this user
466 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
468 $articlelink .= $this->getLanguage()->getDirMark();
470 # TODO: Deprecate the $s argument, it seems happily unused.
472 # Avoid PHP 7.1 warning from passing $this by reference
473 $changesList = $this;
474 Hooks
::run( 'ChangesListInsertArticleLink',
475 [ &$changesList, &$articlelink, &$s, &$rc, $unpatrolled, $watched ] );
477 return "{$s} {$articlelink}";
481 * Get the timestamp from $rc formatted with current user's settings
484 * @param RecentChange $rc
485 * @return string HTML fragment
487 public function getTimestamp( $rc ) {
488 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
489 return $this->message
['semicolon-separator'] . '<span class="mw-changeslist-date">' .
490 $this->getLanguage()->userTime(
491 $rc->mAttribs
['rc_timestamp'],
493 ) . '</span> <span class="mw-changeslist-separator">. .</span> ';
497 * Insert time timestamp string from $rc into $s
499 * @param string $s HTML to update
500 * @param RecentChange $rc
502 public function insertTimestamp( &$s, $rc ) {
503 $s .= $this->getTimestamp( $rc );
507 * Insert links to user page, user talk page and eventually a blocking link
509 * @param string &$s HTML to update
510 * @param RecentChange &$rc
512 public function insertUserRelatedLinks( &$s, &$rc ) {
513 if ( $this->isDeleted( $rc, Revision
::DELETED_USER
) ) {
514 $s .= ' <span class="history-deleted">' .
515 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
517 $s .= $this->getLanguage()->getDirMark() . Linker
::userLink( $rc->mAttribs
['rc_user'],
518 $rc->mAttribs
['rc_user_text'] );
519 $s .= Linker
::userToolLinks( $rc->mAttribs
['rc_user'], $rc->mAttribs
['rc_user_text'] );
524 * Insert a formatted action
526 * @param RecentChange $rc
529 public function insertLogEntry( $rc ) {
530 $formatter = LogFormatter
::newFromRow( $rc->mAttribs
);
531 $formatter->setContext( $this->getContext() );
532 $formatter->setShowUserToolLinks( true );
533 $mark = $this->getLanguage()->getDirMark();
535 return $formatter->getActionText() . " $mark" . $formatter->getComment();
539 * Insert a formatted comment
540 * @param RecentChange $rc
543 public function insertComment( $rc ) {
544 if ( $this->isDeleted( $rc, Revision
::DELETED_COMMENT
) ) {
545 return ' <span class="history-deleted">' .
546 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
548 return Linker
::commentBlock( $rc->mAttribs
['rc_comment'], $rc->getTitle() );
553 * Returns the string which indicates the number of watching users
554 * @param int $count Number of user watching a page
557 protected function numberofWatchingusers( $count ) {
561 $cache = $this->watchMsgCache
;
562 return $cache->getWithSetCallback( $count, $cache::TTL_INDEFINITE
,
563 function () use ( $count ) {
564 return $this->msg( 'number_of_watching_users_RCview' )
565 ->numParams( $count )->escaped();
571 * Determine if said field of a revision is hidden
572 * @param RCCacheEntry|RecentChange $rc
573 * @param int $field One of DELETED_* bitfield constants
576 public static function isDeleted( $rc, $field ) {
577 return ( $rc->mAttribs
['rc_deleted'] & $field ) == $field;
581 * Determine if the current user is allowed to view a particular
582 * field of this revision, if it's marked as deleted.
583 * @param RCCacheEntry|RecentChange $rc
585 * @param User $user User object to check, or null to use $wgUser
588 public static function userCan( $rc, $field, User
$user = null ) {
589 if ( $rc->mAttribs
['rc_type'] == RC_LOG
) {
590 return LogEventsList
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
592 return Revision
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
597 * @param string $link
598 * @param bool $watched
601 protected function maybeWatchedLink( $link, $watched = false ) {
603 return '<strong class="mw-watched">' . $link . '</strong>';
605 return '<span class="mw-rc-unwatched">' . $link . '</span>';
609 /** Inserts a rollback link
612 * @param RecentChange $rc
614 public function insertRollback( &$s, &$rc ) {
615 if ( $rc->mAttribs
['rc_type'] == RC_EDIT
616 && $rc->mAttribs
['rc_this_oldid']
617 && $rc->mAttribs
['rc_cur_id']
619 $page = $rc->getTitle();
620 /** Check for rollback and edit permissions, disallow special pages, and only
621 * show a link on the top-most revision */
622 if ( $this->getUser()->isAllowed( 'rollback' )
623 && $rc->mAttribs
['page_latest'] == $rc->mAttribs
['rc_this_oldid']
625 $rev = new Revision( [
627 'id' => $rc->mAttribs
['rc_this_oldid'],
628 'user' => $rc->mAttribs
['rc_user'],
629 'user_text' => $rc->mAttribs
['rc_user_text'],
630 'deleted' => $rc->mAttribs
['rc_deleted']
632 $s .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
638 * @param RecentChange $rc
642 public function getRollback( RecentChange
$rc ) {
644 $this->insertRollback( $s, $rc );
650 * @param RecentChange $rc
651 * @param array $classes
653 public function insertTags( &$s, &$rc, &$classes ) {
654 if ( empty( $rc->mAttribs
['ts_tags'] ) ) {
658 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
659 $rc->mAttribs
['ts_tags'],
663 $classes = array_merge( $classes, $newClasses );
664 $s .= ' ' . $tagSummary;
668 * @param RecentChange $rc
669 * @param array $classes
673 public function getTags( RecentChange
$rc, array &$classes ) {
675 $this->insertTags( $s, $rc, $classes );
679 public function insertExtra( &$s, &$rc, &$classes ) {
680 // Empty, used for subclasses to add anything special.
683 protected function showAsUnpatrolled( RecentChange
$rc ) {
684 return self
::isUnpatrolled( $rc, $this->getUser() );
688 * @param object|RecentChange $rc Database row from recentchanges or a RecentChange object
692 public static function isUnpatrolled( $rc, User
$user ) {
693 if ( $rc instanceof RecentChange
) {
694 $isPatrolled = $rc->mAttribs
['rc_patrolled'];
695 $rcType = $rc->mAttribs
['rc_type'];
696 $rcLogType = $rc->mAttribs
['rc_log_type'];
698 $isPatrolled = $rc->rc_patrolled
;
699 $rcType = $rc->rc_type
;
700 $rcLogType = $rc->rc_log_type
;
703 if ( !$isPatrolled ) {
704 if ( $user->useRCPatrol() ) {
707 if ( $user->useNPPatrol() && $rcType == RC_NEW
) {
710 if ( $user->useFilePatrol() && $rcLogType == 'upload' ) {
719 * Determines whether a revision is linked to this change; this may not be the case
720 * when the categorization wasn't done by an edit but a conditional parser function
724 * @param RecentChange|RCCacheEntry $rcObj
727 protected function isCategorizationWithoutRevision( $rcObj ) {
728 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
729 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;