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\Linker\LinkRenderer
;
28 use MediaWiki\Storage\RevisionRecord
;
29 use Wikimedia\Rdbms\IResultWrapper
;
30 use Wikimedia\Rdbms\FakeResultWrapper
;
31 use Wikimedia\Rdbms\IDatabase
;
33 class ContribsPager
extends RangeChronologicalPager
{
36 * @var string[] Local cache for escaped messages
41 * @var string User name, or a string describing an IP address range
46 * @var string|int A single namespace number, or an empty string for all namespaces
48 private $namespace = '';
51 * @var string|false Name of tag to filter, or false to ignore tags
56 * @var bool Set to true to invert the namespace selection
61 * @var bool Set to true to show both the subject and talk namespace, no matter which got
67 * @var bool Set to true to show only deleted revisions
72 * @var bool Set to true to show only latest (a.k.a. current) revisions
77 * @var bool Set to true to show only new pages
82 * @var bool Set to true to hide edits marked as minor by the user
86 private $preventClickjacking = false;
89 private $mDbSecondary;
99 private $templateParser;
101 public function __construct( IContextSource
$context, array $options,
102 LinkRenderer
$linkRenderer = null
104 // Set ->target before calling parent::__construct() so
105 // parent can call $this->getIndexField() and get the right result. Set
106 // the rest too just to keep things simple.
107 $this->target
= $options['target'] ??
'';
108 $this->namespace = $options['namespace'] ??
'';
109 $this->tagFilter
= $options['tagfilter'] ??
false;
110 $this->nsInvert
= $options['nsInvert'] ??
false;
111 $this->associated
= $options['associated'] ??
false;
113 $this->deletedOnly
= !empty( $options['deletedOnly'] );
114 $this->topOnly
= !empty( $options['topOnly'] );
115 $this->newOnly
= !empty( $options['newOnly'] );
116 $this->hideMinor
= !empty( $options['hideMinor'] );
118 parent
::__construct( $context, $linkRenderer );
127 foreach ( $msgs as $msg ) {
128 $this->messages
[$msg] = $this->msg( $msg )->escaped();
131 // Date filtering: use timestamp if available
132 $startTimestamp = '';
134 if ( $options['start'] ) {
135 $startTimestamp = $options['start'] . ' 00:00:00';
137 if ( $options['end'] ) {
138 $endTimestamp = $options['end'] . ' 23:59:59';
140 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
142 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
143 // with extra user based indexes or partioning by user. The additional metadata
144 // queries should use a regular replica DB since the lookup pattern is not all by user.
145 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
146 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
147 $this->templateParser
= new TemplateParser();
150 function getDefaultQuery() {
151 $query = parent
::getDefaultQuery();
152 $query['target'] = $this->target
;
158 * Wrap the navigation bar in a p element with identifying class.
159 * In future we may want to change the `p` tag to a `div` and upstream
160 * this to the parent class.
162 * @return string HTML
164 function getNavigationBar() {
165 return Html
::rawElement( 'p', [ 'class' => 'mw-pager-navigation-bar' ],
166 parent
::getNavigationBar()
171 * This method basically executes the exact same code as the parent class, though with
172 * a hook added, to allow extensions to add additional queries.
174 * @param string $offset Index offset, inclusive
175 * @param int $limit Exact query limit
176 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
177 * @return IResultWrapper
179 function reallyDoQuery( $offset, $limit, $order ) {
180 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
187 * This hook will allow extensions to add in additional queries, so they can get their data
188 * in My Contributions as well. Extensions should append their results to the $data array.
190 * Extension queries have to implement the navbar requirement as well. They should
191 * - have a column aliased as $pager->getIndexField()
193 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
194 * - have the ORDER BY specified based upon the details provided by the navbar
196 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
198 * &$data: an array of results of all contribs queries
199 * $pager: the ContribsPager object hooked into
200 * $offset: see phpdoc above
201 * $limit: see phpdoc above
202 * $descending: see phpdoc above
204 $data = [ $this->mDb
->select(
205 $tables, $fields, $conds, $fname, $options, $join_conds
208 'ContribsPager::reallyDoQuery',
209 [ &$data, $this, $offset, $limit, $order ]
214 // loop all results and collect them in an array
215 foreach ( $data as $query ) {
216 foreach ( $query as $i => $row ) {
217 // use index column as key, allowing us to easily sort in PHP
218 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
223 if ( $order === self
::QUERY_ASCENDING
) {
230 $result = array_slice( $result, 0, $limit );
232 // get rid of array keys
233 $result = array_values( $result );
235 return new FakeResultWrapper( $result );
239 * Return the table targeted for ordering and continuation
241 * See T200259 and T221380.
243 * @warning Keep this in sync with self::getQueryInfo()!
247 private function getTargetTable() {
248 $user = User
::newFromName( $this->target
, false );
249 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
250 if ( $ipRangeConds ) {
253 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
254 if ( isset( $conds['orconds']['actor'] ) ) {
255 // @todo: This will need changing when revision_actor_temp goes away
256 return 'revision_actor_temp';
263 function getQueryInfo() {
264 $revQuery = Revision
::getQueryInfo( [ 'page', 'user' ] );
266 'tables' => $revQuery['tables'],
267 'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
270 'join_conds' => $revQuery['joins'],
273 // WARNING: Keep this in sync with getTargetTable()!
274 $user = User
::newFromName( $this->target
, false );
275 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
276 if ( $ipRangeConds ) {
277 $queryInfo['tables'][] = 'ip_changes';
278 $queryInfo['join_conds']['ip_changes'] = [
279 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
281 $queryInfo['conds'][] = $ipRangeConds;
283 // tables and joins are already handled by Revision::getQueryInfo()
284 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
285 $queryInfo['conds'][] = $conds['conds'];
286 // Force the appropriate index to avoid bad query plans (T189026)
287 if ( isset( $conds['orconds']['actor'] ) ) {
288 // @todo: This will need changing when revision_actor_temp goes away
289 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
291 $queryInfo['options']['USE INDEX']['revision'] =
292 isset( $conds['orconds']['userid'] ) ?
'user_timestamp' : 'usertext_timestamp';
296 if ( $this->deletedOnly
) {
297 $queryInfo['conds'][] = 'rev_deleted != 0';
300 if ( $this->topOnly
) {
301 $queryInfo['conds'][] = 'rev_id = page_latest';
304 if ( $this->newOnly
) {
305 $queryInfo['conds'][] = 'rev_parent_id = 0';
308 if ( $this->hideMinor
) {
309 $queryInfo['conds'][] = 'rev_minor_edit = 0';
312 $user = $this->getUser();
313 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
315 // Paranoia: avoid brute force searches (T19342)
316 if ( !$user->isAllowed( 'deletedhistory' ) ) {
317 $queryInfo['conds'][] = $this->mDb
->bitAnd(
318 'rev_deleted', RevisionRecord
::DELETED_USER
320 } elseif ( !MediaWikiServices
::getInstance()
321 ->getPermissionManager()
322 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
324 $queryInfo['conds'][] = $this->mDb
->bitAnd(
325 'rev_deleted', RevisionRecord
::SUPPRESSED_USER
326 ) . ' != ' . RevisionRecord
::SUPPRESSED_USER
;
329 // $this->getIndexField() must be in the result rows, as reallyDoQuery() tries to access it.
330 $indexField = $this->getIndexField();
331 if ( $indexField !== 'rev_timestamp' ) {
332 $queryInfo['fields'][] = $indexField;
335 ChangeTags
::modifyDisplayQuery(
336 $queryInfo['tables'],
337 $queryInfo['fields'],
339 $queryInfo['join_conds'],
340 $queryInfo['options'],
344 // Avoid PHP 7.1 warning from passing $this by reference
346 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
351 function getNamespaceCond() {
352 if ( $this->namespace !== '' ) {
353 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
354 $eq_op = $this->nsInvert ?
'!=' : '=';
355 $bool_op = $this->nsInvert ?
'AND' : 'OR';
357 if ( !$this->associated
) {
358 return [ "page_namespace $eq_op $selectedNS" ];
361 $associatedNS = $this->mDb
->addQuotes(
362 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociated( $this->namespace )
366 "page_namespace $eq_op $selectedNS " .
368 " page_namespace $eq_op $associatedNS"
376 * Get SQL conditions for an IP range, if applicable
377 * @param IDatabase $db
378 * @param string $ip The IP address or CIDR
379 * @return string|false SQL for valid IP ranges, false if invalid
381 private function getIpRangeConds( $db, $ip ) {
382 // First make sure it is a valid range and they are not outside the CIDR limit
383 if ( !$this->isQueryableRange( $ip ) ) {
387 list( $start, $end ) = IP
::parseRange( $ip );
389 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
393 * Is the given IP a range and within the CIDR limit?
395 * @param string $ipRange
396 * @return bool True if it is valid
399 public function isQueryableRange( $ipRange ) {
400 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
402 $bits = IP
::parseCIDR( $ipRange )[1];
404 ( $bits === false ) ||
405 ( IP
::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
406 ( IP
::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
417 public function getIndexField() {
418 // The returned column is used for sorting and continuation, so we need to
419 // make sure to use the right denormalized column depending on which table is
420 // being targeted by the query to avoid bad query plans.
421 // See T200259, T204669, T220991, and T221380.
422 $target = $this->getTargetTable();
425 return 'rev_timestamp';
427 return 'ipc_rev_timestamp';
428 case 'revision_actor_temp':
429 return 'revactor_timestamp';
432 __METHOD__
. ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
434 return 'rev_timestamp';
439 * @return false|string
441 public function getTagFilter() {
442 return $this->tagFilter
;
448 public function getTarget() {
449 return $this->target
;
455 public function isNewOnly() {
456 return $this->newOnly
;
462 public function getNamespace() {
463 return $this->namespace;
469 protected function getExtraSortFields() {
470 // The returned columns are used for sorting, so we need to make sure
471 // to use the right denormalized column depending on which table is
472 // being targeted by the query to avoid bad query plans.
473 // See T200259, T204669, T220991, and T221380.
474 $target = $this->getTargetTable();
479 return [ 'ipc_rev_id' ];
480 case 'revision_actor_temp':
481 return [ 'revactor_rev' ];
484 __METHOD__
. ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
490 protected function doBatchLookups() {
491 # Do a link batch query
492 $this->mResult
->seek( 0 );
494 $this->mParentLens
= [];
495 $batch = new LinkBatch();
496 $isIpRange = $this->isQueryableRange( $this->target
);
497 # Give some pointers to make (last) links
498 foreach ( $this->mResult
as $row ) {
499 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
500 $parentRevIds[] = $row->rev_parent_id
;
502 if ( isset( $row->rev_id
) ) {
503 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
505 // If this is an IP range, batch the IP's talk page
506 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
508 $batch->add( $row->page_namespace
, $row->page_title
);
511 # Fetch rev_len for revisions not already scanned above
512 $this->mParentLens +
= Revision
::getParentLengths(
514 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
517 $this->mResult
->seek( 0 );
523 protected function getStartBody() {
524 return "<ul class=\"mw-contributions-list\">\n";
530 protected function getEndBody() {
535 * Check whether the revision associated is valid for formatting. If has no associated revision
536 * id then null is returned.
539 * @param Title|null $title
540 * @return Revision|null
542 public function tryToCreateValidRevision( $row, $title = null ) {
544 * There may be more than just revision rows. To make sure that we'll only be processing
545 * revisions here, let's _try_ to build a revision out of our row (without displaying
546 * notices though) and then trying to grab data from the built object. If we succeed,
547 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
548 * to extensions to subscribe to the hook to parse the row.
550 Wikimedia\
suppressWarnings();
552 $rev = new Revision( $row, 0, $title );
553 $validRevision = (bool)$rev->getId();
554 } catch ( Exception
$e ) {
555 $validRevision = false;
557 Wikimedia\restoreWarnings
();
558 return $validRevision ?
$rev : null;
562 * Generates each row in the contributions list.
564 * Contributions which are marked "top" are currently on top of the history.
565 * For these contributions, a [rollback] link is shown for users with roll-
566 * back privileges. The rollback link restores the most recent version that
567 * was not written by the target user.
569 * @todo This would probably look a lot nicer in a table.
573 function formatRow( $row ) {
578 $linkRenderer = $this->getLinkRenderer();
579 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
582 // Create a title for the revision if possible
583 // Rows from the hook may not include title information
584 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
585 $page = Title
::newFromRow( $row );
587 $rev = $this->tryToCreateValidRevision( $row, $page );
589 $attribs['data-mw-revid'] = $rev->getId();
591 $link = $linkRenderer->makeLink(
593 $page->getPrefixedText(),
594 [ 'class' => 'mw-contributions-title' ],
595 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
597 # Mark current revisions
599 $user = $this->getUser();
601 if ( $row->rev_id
=== $row->page_latest
) {
602 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
603 $classes[] = 'mw-contributions-current';
605 if ( !$row->page_is_new
&&
606 $permissionManager->quickUserCan( 'rollback', $user, $page ) &&
607 $permissionManager->quickUserCan( 'edit', $user, $page )
609 $this->preventClickjacking();
610 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext(),
614 # Is there a visible previous revision?
615 if ( $rev->userCan( RevisionRecord
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
616 $difftext = $linkRenderer->makeKnownLink(
618 new HtmlArmor( $this->messages
['diff'] ),
619 [ 'class' => 'mw-changeslist-diff' ],
622 'oldid' => $row->rev_id
626 $difftext = $this->messages
['diff'];
628 $histlink = $linkRenderer->makeKnownLink(
630 new HtmlArmor( $this->messages
['hist'] ),
631 [ 'class' => 'mw-changeslist-history' ],
632 [ 'action' => 'history' ]
635 if ( $row->rev_parent_id
=== null ) {
636 // For some reason rev_parent_id isn't populated for this row.
637 // Its rumoured this is true on wikipedia for some revisions (T36922).
638 // Next best thing is to have the total number of bytes.
639 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
640 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
641 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
644 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
645 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
648 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
649 $chardiff .= ChangesList
::showCharacterDifference(
654 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
657 $lang = $this->getLanguage();
658 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
659 $d = ChangesList
::revDateLink( $rev, $user, $lang, $page );
661 # When querying for an IP range, we want to always show user and user talk links.
663 if ( $this->isQueryableRange( $this->target
) ) {
664 $userlink = ' <span class="mw-changeslist-separator"></span> '
665 . $lang->getDirMark()
666 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
667 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
668 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
672 if ( $rev->getParentId() === 0 ) {
673 $flags[] = ChangesList
::flag( 'newpage' );
676 if ( $rev->isMinor() ) {
677 $flags[] = ChangesList
::flag( 'minor' );
680 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
685 // While it might be tempting to use a list here
686 // this would result in clutter and slows down navigating the content
687 // in assistive technology.
688 // See https://phabricator.wikimedia.org/T205581#4734812
689 $diffHistLinks = Html
::rawElement( 'span',
690 [ 'class' => 'mw-changeslist-links' ],
691 // The spans are needed to ensure the dividing '|' elements are not
692 // themselves styled as links.
693 Html
::rawElement( 'span', [], $difftext ) .
694 ' ' . // Space needed for separating two words.
695 Html
::rawElement( 'span', [], $histlink )
699 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
704 $classes = array_merge( $classes, $newClasses );
706 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
711 'diffHistLinks' => $diffHistLinks,
712 'charDifference' => $chardiff,
714 'articleLink' => $link,
715 'userlink' => $userlink,
716 'logText' => $comment,
717 'topmarktext' => $topmarktext,
718 'tagSummary' => $tagSummary,
721 # Denote if username is redacted for this edit
722 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
723 $templateParams['rev-deleted-user-contribs'] =
724 $this->msg( 'rev-deleted-user-contribs' )->escaped();
727 $ret = $this->templateParser
->processTemplate(
728 'SpecialContributionsLine',
733 // Let extensions add data
734 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
735 $attribs = array_filter( $attribs,
736 [ Sanitizer
::class, 'isReservedDataAttribute' ],
740 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
741 // receiving empty rows?
743 if ( $classes === [] && $attribs === [] && $ret === '' ) {
744 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
745 return "<!-- Could not format Special:Contribution row. -->\n";
747 $attribs['class'] = $classes;
749 // FIXME: The signature of the ContributionsLineEnding hook makes it
750 // very awkward to move this LI wrapper into the template.
751 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
755 * Overwrite Pager function and return a helpful comment
758 function getSqlComment() {
759 if ( $this->namespace ||
$this->deletedOnly
) {
760 // potentially slow, see CR r58153
761 return 'contributions page filtered for namespace or RevisionDeleted edits';
763 return 'contributions page unfiltered';
767 protected function preventClickjacking() {
768 $this->preventClickjacking
= true;
774 public function getPreventClickjacking() {
775 return $this->preventClickjacking
;
779 * Set up date filter options, given request data.
781 * @param array $opts Options array
782 * @return array Options array with processed start and end date filter options
784 public static function processDateFilter( array $opts ) {
785 $start = $opts['start'] ??
'';
786 $end = $opts['end'] ??
'';
787 $year = $opts['year'] ??
'';
788 $month = $opts['month'] ??
'';
790 if ( $start !== '' && $end !== '' && $start > $end ) {
796 // If year/month legacy filtering options are set, convert them to display the new stamp
797 if ( $year !== '' ||
$month !== '' ) {
798 // Reuse getDateCond logic, but subtract a day because
799 // the endpoints of our date range appear inclusive
800 // but the internal end offsets are always exclusive
801 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
802 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
803 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
805 // Clear the new timestamp range options if used and
806 // replace with the converted legacy timestamp
808 $end = $legacyDateTime->format( 'Y-m-d' );
811 $opts['start'] = $start;