3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
23 * Pager for Special:Contributions
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Storage\RevisionRecord
;
28 use Wikimedia\Rdbms\IResultWrapper
;
29 use Wikimedia\Rdbms\FakeResultWrapper
;
30 use Wikimedia\Rdbms\IDatabase
;
32 class ContribsPager
extends RangeChronologicalPager
{
35 * @var string[] Local cache for escaped messages
40 * @var string User name, or a string describing an IP address range
45 * @var string|int A single namespace number, or an empty string for all namespaces
47 private $namespace = '';
50 * @var string|false Name of tag to filter, or false to ignore tags
55 * @var bool Set to true to invert the namespace selection
60 * @var bool Set to true to show both the subject and talk namespace, no matter which got
66 * @var bool Set to true to show only deleted revisions
71 * @var bool Set to true to show only latest (a.k.a. current) revisions
76 * @var bool Set to true to show only new pages
81 * @var bool Set to true to hide edits marked as minor by the user
85 private $preventClickjacking = false;
88 private $mDbSecondary;
98 private $templateParser;
100 public function __construct( IContextSource
$context, array $options ) {
101 // Set ->target before calling parent::__construct() so
102 // parent can call $this->getIndexField() and get the right result. Set
103 // the rest too just to keep things simple.
104 $this->target
= $options['target'] ??
'';
105 $this->namespace = $options['namespace'] ??
'';
106 $this->tagFilter
= $options['tagfilter'] ??
false;
107 $this->nsInvert
= $options['nsInvert'] ??
false;
108 $this->associated
= $options['associated'] ??
false;
110 $this->deletedOnly
= !empty( $options['deletedOnly'] );
111 $this->topOnly
= !empty( $options['topOnly'] );
112 $this->newOnly
= !empty( $options['newOnly'] );
113 $this->hideMinor
= !empty( $options['hideMinor'] );
115 parent
::__construct( $context );
124 foreach ( $msgs as $msg ) {
125 $this->messages
[$msg] = $this->msg( $msg )->escaped();
128 // Date filtering: use timestamp if available
129 $startTimestamp = '';
131 if ( $options['start'] ) {
132 $startTimestamp = $options['start'] . ' 00:00:00';
134 if ( $options['end'] ) {
135 $endTimestamp = $options['end'] . ' 23:59:59';
137 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
139 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
140 // with extra user based indexes or partioning by user. The additional metadata
141 // queries should use a regular replica DB since the lookup pattern is not all by user.
142 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
143 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
144 $this->templateParser
= new TemplateParser();
147 function getDefaultQuery() {
148 $query = parent
::getDefaultQuery();
149 $query['target'] = $this->target
;
155 * Wrap the navigation bar in a p element with identifying class.
156 * In future we may want to change the `p` tag to a `div` and upstream
157 * this to the parent class.
159 * @return string HTML
161 function getNavigationBar() {
162 return Html
::rawElement( 'p', [ 'class' => 'mw-pager-navigation-bar' ],
163 parent
::getNavigationBar()
168 * This method basically executes the exact same code as the parent class, though with
169 * a hook added, to allow extensions to add additional queries.
171 * @param string $offset Index offset, inclusive
172 * @param int $limit Exact query limit
173 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
174 * @return IResultWrapper
176 function reallyDoQuery( $offset, $limit, $order ) {
177 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
184 * This hook will allow extensions to add in additional queries, so they can get their data
185 * in My Contributions as well. Extensions should append their results to the $data array.
187 * Extension queries have to implement the navbar requirement as well. They should
188 * - have a column aliased as $pager->getIndexField()
190 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
191 * - have the ORDER BY specified based upon the details provided by the navbar
193 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
195 * &$data: an array of results of all contribs queries
196 * $pager: the ContribsPager object hooked into
197 * $offset: see phpdoc above
198 * $limit: see phpdoc above
199 * $descending: see phpdoc above
201 $data = [ $this->mDb
->select(
202 $tables, $fields, $conds, $fname, $options, $join_conds
205 'ContribsPager::reallyDoQuery',
206 [ &$data, $this, $offset, $limit, $order ]
211 // loop all results and collect them in an array
212 foreach ( $data as $query ) {
213 foreach ( $query as $i => $row ) {
214 // use index column as key, allowing us to easily sort in PHP
215 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
220 if ( $order === self
::QUERY_ASCENDING
) {
227 $result = array_slice( $result, 0, $limit );
229 // get rid of array keys
230 $result = array_values( $result );
232 return new FakeResultWrapper( $result );
236 * Return the table targeted for ordering and continuation
238 * See T200259 and T221380.
240 * @warning Keep this in sync with self::getQueryInfo()!
244 private function getTargetTable() {
245 $user = User
::newFromName( $this->target
, false );
246 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
247 if ( $ipRangeConds ) {
250 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
251 if ( isset( $conds['orconds']['actor'] ) ) {
252 // @todo: This will need changing when revision_actor_temp goes away
253 return 'revision_actor_temp';
260 function getQueryInfo() {
261 $revQuery = Revision
::getQueryInfo( [ 'page', 'user' ] );
263 'tables' => $revQuery['tables'],
264 'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
267 'join_conds' => $revQuery['joins'],
270 // WARNING: Keep this in sync with getTargetTable()!
271 $user = User
::newFromName( $this->target
, false );
272 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
273 if ( $ipRangeConds ) {
274 $queryInfo['tables'][] = 'ip_changes';
275 $queryInfo['join_conds']['ip_changes'] = [
276 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
278 $queryInfo['conds'][] = $ipRangeConds;
280 // tables and joins are already handled by Revision::getQueryInfo()
281 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
282 $queryInfo['conds'][] = $conds['conds'];
283 // Force the appropriate index to avoid bad query plans (T189026)
284 if ( isset( $conds['orconds']['actor'] ) ) {
285 // @todo: This will need changing when revision_actor_temp goes away
286 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
288 $queryInfo['options']['USE INDEX']['revision'] =
289 isset( $conds['orconds']['userid'] ) ?
'user_timestamp' : 'usertext_timestamp';
293 if ( $this->deletedOnly
) {
294 $queryInfo['conds'][] = 'rev_deleted != 0';
297 if ( $this->topOnly
) {
298 $queryInfo['conds'][] = 'rev_id = page_latest';
301 if ( $this->newOnly
) {
302 $queryInfo['conds'][] = 'rev_parent_id = 0';
305 if ( $this->hideMinor
) {
306 $queryInfo['conds'][] = 'rev_minor_edit = 0';
309 $user = $this->getUser();
310 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
312 // Paranoia: avoid brute force searches (T19342)
313 if ( !$user->isAllowed( 'deletedhistory' ) ) {
314 $queryInfo['conds'][] = $this->mDb
->bitAnd(
315 'rev_deleted', RevisionRecord
::DELETED_USER
317 } elseif ( !MediaWikiServices
::getInstance()
318 ->getPermissionManager()
319 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
321 $queryInfo['conds'][] = $this->mDb
->bitAnd(
322 'rev_deleted', RevisionRecord
::SUPPRESSED_USER
323 ) . ' != ' . RevisionRecord
::SUPPRESSED_USER
;
326 // $this->getIndexField() must be in the result rows, as reallyDoQuery() tries to access it.
327 $indexField = $this->getIndexField();
328 if ( $indexField !== 'rev_timestamp' ) {
329 $queryInfo['fields'][] = $indexField;
332 ChangeTags
::modifyDisplayQuery(
333 $queryInfo['tables'],
334 $queryInfo['fields'],
336 $queryInfo['join_conds'],
337 $queryInfo['options'],
341 // Avoid PHP 7.1 warning from passing $this by reference
343 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
348 function getNamespaceCond() {
349 if ( $this->namespace !== '' ) {
350 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
351 $eq_op = $this->nsInvert ?
'!=' : '=';
352 $bool_op = $this->nsInvert ?
'AND' : 'OR';
354 if ( !$this->associated
) {
355 return [ "page_namespace $eq_op $selectedNS" ];
358 $associatedNS = $this->mDb
->addQuotes(
359 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociated( $this->namespace )
363 "page_namespace $eq_op $selectedNS " .
365 " page_namespace $eq_op $associatedNS"
373 * Get SQL conditions for an IP range, if applicable
374 * @param IDatabase $db
375 * @param string $ip The IP address or CIDR
376 * @return string|false SQL for valid IP ranges, false if invalid
378 private function getIpRangeConds( $db, $ip ) {
379 // First make sure it is a valid range and they are not outside the CIDR limit
380 if ( !$this->isQueryableRange( $ip ) ) {
384 list( $start, $end ) = IP
::parseRange( $ip );
386 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
390 * Is the given IP a range and within the CIDR limit?
392 * @param string $ipRange
393 * @return bool True if it is valid
396 public function isQueryableRange( $ipRange ) {
397 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
399 $bits = IP
::parseCIDR( $ipRange )[1];
401 ( $bits === false ) ||
402 ( IP
::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
403 ( IP
::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
414 public function getIndexField() {
415 // The returned column is used for sorting and continuation, so we need to
416 // make sure to use the right denormalized column depending on which table is
417 // being targeted by the query to avoid bad query plans.
418 // See T200259, T204669, T220991, and T221380.
419 $target = $this->getTargetTable();
422 return 'rev_timestamp';
424 return 'ipc_rev_timestamp';
425 case 'revision_actor_temp':
426 return 'revactor_timestamp';
429 __METHOD__
. ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
431 return 'rev_timestamp';
436 * @return false|string
438 public function getTagFilter() {
439 return $this->tagFilter
;
443 * @deprecated since 1.34, redundant.
445 * @return string "users"
447 public function getContribs() {
448 // Brought back for backwards compatibility, see T231540.
455 public function getTarget() {
456 return $this->target
;
462 public function isNewOnly() {
463 return $this->newOnly
;
469 public function getNamespace() {
470 return $this->namespace;
476 protected function getExtraSortFields() {
477 // The returned columns are used for sorting, so we need to make sure
478 // to use the right denormalized column depending on which table is
479 // being targeted by the query to avoid bad query plans.
480 // See T200259, T204669, T220991, and T221380.
481 $target = $this->getTargetTable();
486 return [ 'ipc_rev_id' ];
487 case 'revision_actor_temp':
488 return [ 'revactor_rev' ];
491 __METHOD__
. ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
497 protected function doBatchLookups() {
498 # Do a link batch query
499 $this->mResult
->seek( 0 );
501 $this->mParentLens
= [];
502 $batch = new LinkBatch();
503 $isIpRange = $this->isQueryableRange( $this->target
);
504 # Give some pointers to make (last) links
505 foreach ( $this->mResult
as $row ) {
506 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
507 $parentRevIds[] = $row->rev_parent_id
;
509 if ( isset( $row->rev_id
) ) {
510 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
512 // If this is an IP range, batch the IP's talk page
513 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
515 $batch->add( $row->page_namespace
, $row->page_title
);
518 # Fetch rev_len for revisions not already scanned above
519 $this->mParentLens +
= Revision
::getParentLengths(
521 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
524 $this->mResult
->seek( 0 );
530 protected function getStartBody() {
531 return "<ul class=\"mw-contributions-list\">\n";
537 protected function getEndBody() {
542 * Check whether the revision associated is valid for formatting. If has no associated revision
543 * id then null is returned.
546 * @param Title|null $title
547 * @return Revision|null
549 public function tryToCreateValidRevision( $row, $title = null ) {
551 * There may be more than just revision rows. To make sure that we'll only be processing
552 * revisions here, let's _try_ to build a revision out of our row (without displaying
553 * notices though) and then trying to grab data from the built object. If we succeed,
554 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
555 * to extensions to subscribe to the hook to parse the row.
557 Wikimedia\
suppressWarnings();
559 $rev = new Revision( $row, 0, $title );
560 $validRevision = (bool)$rev->getId();
561 } catch ( Exception
$e ) {
562 $validRevision = false;
564 Wikimedia\restoreWarnings
();
565 return $validRevision ?
$rev : null;
569 * Generates each row in the contributions list.
571 * Contributions which are marked "top" are currently on top of the history.
572 * For these contributions, a [rollback] link is shown for users with roll-
573 * back privileges. The rollback link restores the most recent version that
574 * was not written by the target user.
576 * @todo This would probably look a lot nicer in a table.
580 function formatRow( $row ) {
585 $linkRenderer = $this->getLinkRenderer();
586 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
589 // Create a title for the revision if possible
590 // Rows from the hook may not include title information
591 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
592 $page = Title
::newFromRow( $row );
594 $rev = $this->tryToCreateValidRevision( $row, $page );
596 $attribs['data-mw-revid'] = $rev->getId();
598 $link = $linkRenderer->makeLink(
600 $page->getPrefixedText(),
601 [ 'class' => 'mw-contributions-title' ],
602 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
604 # Mark current revisions
606 $user = $this->getUser();
608 if ( $row->rev_id
=== $row->page_latest
) {
609 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
610 $classes[] = 'mw-contributions-current';
612 if ( !$row->page_is_new
&&
613 $permissionManager->quickUserCan( 'rollback', $user, $page ) &&
614 $permissionManager->quickUserCan( 'edit', $user, $page )
616 $this->preventClickjacking();
617 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext(),
621 # Is there a visible previous revision?
622 if ( $rev->userCan( RevisionRecord
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
623 $difftext = $linkRenderer->makeKnownLink(
625 new HtmlArmor( $this->messages
['diff'] ),
626 [ 'class' => 'mw-changeslist-diff' ],
629 'oldid' => $row->rev_id
633 $difftext = $this->messages
['diff'];
635 $histlink = $linkRenderer->makeKnownLink(
637 new HtmlArmor( $this->messages
['hist'] ),
638 [ 'class' => 'mw-changeslist-history' ],
639 [ 'action' => 'history' ]
642 if ( $row->rev_parent_id
=== null ) {
643 // For some reason rev_parent_id isn't populated for this row.
644 // Its rumoured this is true on wikipedia for some revisions (T36922).
645 // Next best thing is to have the total number of bytes.
646 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
647 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
648 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
651 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
652 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
655 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
656 $chardiff .= ChangesList
::showCharacterDifference(
661 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
664 $lang = $this->getLanguage();
665 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
666 $d = ChangesList
::revDateLink( $rev, $user, $lang, $page );
668 # When querying for an IP range, we want to always show user and user talk links.
670 if ( $this->isQueryableRange( $this->target
) ) {
671 $userlink = ' <span class="mw-changeslist-separator"></span> '
672 . $lang->getDirMark()
673 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
674 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
675 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
679 if ( $rev->getParentId() === 0 ) {
680 $flags[] = ChangesList
::flag( 'newpage' );
683 if ( $rev->isMinor() ) {
684 $flags[] = ChangesList
::flag( 'minor' );
687 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
692 // While it might be tempting to use a list here
693 // this would result in clutter and slows down navigating the content
694 // in assistive technology.
695 // See https://phabricator.wikimedia.org/T205581#4734812
696 $diffHistLinks = Html
::rawElement( 'span',
697 [ 'class' => 'mw-changeslist-links' ],
698 // The spans are needed to ensure the dividing '|' elements are not
699 // themselves styled as links.
700 Html
::rawElement( 'span', [], $difftext ) .
701 ' ' . // Space needed for separating two words.
702 Html
::rawElement( 'span', [], $histlink )
706 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
711 $classes = array_merge( $classes, $newClasses );
713 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
718 'diffHistLinks' => $diffHistLinks,
719 'charDifference' => $chardiff,
721 'articleLink' => $link,
722 'userlink' => $userlink,
723 'logText' => $comment,
724 'topmarktext' => $topmarktext,
725 'tagSummary' => $tagSummary,
728 # Denote if username is redacted for this edit
729 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
730 $templateParams['rev-deleted-user-contribs'] =
731 $this->msg( 'rev-deleted-user-contribs' )->escaped();
734 $ret = $this->templateParser
->processTemplate(
735 'SpecialContributionsLine',
740 // Let extensions add data
741 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
742 $attribs = array_filter( $attribs,
743 [ Sanitizer
::class, 'isReservedDataAttribute' ],
747 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
748 // receiving empty rows?
750 if ( $classes === [] && $attribs === [] && $ret === '' ) {
751 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
752 return "<!-- Could not format Special:Contribution row. -->\n";
754 $attribs['class'] = $classes;
756 // FIXME: The signature of the ContributionsLineEnding hook makes it
757 // very awkward to move this LI wrapper into the template.
758 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
762 * Overwrite Pager function and return a helpful comment
765 function getSqlComment() {
766 if ( $this->namespace ||
$this->deletedOnly
) {
767 // potentially slow, see CR r58153
768 return 'contributions page filtered for namespace or RevisionDeleted edits';
770 return 'contributions page unfiltered';
774 protected function preventClickjacking() {
775 $this->preventClickjacking
= true;
781 public function getPreventClickjacking() {
782 return $this->preventClickjacking
;
786 * Set up date filter options, given request data.
788 * @param array $opts Options array
789 * @return array Options array with processed start and end date filter options
791 public static function processDateFilter( array $opts ) {
792 $start = $opts['start'] ??
'';
793 $end = $opts['end'] ??
'';
794 $year = $opts['year'] ??
'';
795 $month = $opts['month'] ??
'';
797 if ( $start !== '' && $end !== '' && $start > $end ) {
803 // If year/month legacy filtering options are set, convert them to display the new stamp
804 if ( $year !== '' ||
$month !== '' ) {
805 // Reuse getDateCond logic, but subtract a day because
806 // the endpoints of our date range appear inclusive
807 // but the internal end offsets are always exclusive
808 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
809 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
810 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
812 // Clear the new timestamp range options if used and
813 // replace with the converted legacy timestamp
815 $end = $legacyDateTime->format( 'Y-m-d' );
818 $opts['start'] = $start;