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'],
272 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
274 // WARNING: Keep this in sync with getTargetTable()!
275 $user = User
::newFromName( $this->target
, false );
276 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
277 if ( $ipRangeConds ) {
278 $queryInfo['tables'][] = 'ip_changes';
279 $queryInfo['join_conds']['ip_changes'] = [
280 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
282 $queryInfo['conds'][] = $ipRangeConds;
284 // tables and joins are already handled by Revision::getQueryInfo()
285 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
286 $queryInfo['conds'][] = $conds['conds'];
287 // Force the appropriate index to avoid bad query plans (T189026)
288 if ( isset( $conds['orconds']['actor'] ) ) {
289 // @todo: This will need changing when revision_actor_temp goes away
290 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
292 $queryInfo['options']['USE INDEX']['revision'] =
293 isset( $conds['orconds']['userid'] ) ?
'user_timestamp' : 'usertext_timestamp';
297 if ( $this->deletedOnly
) {
298 $queryInfo['conds'][] = 'rev_deleted != 0';
301 if ( $this->topOnly
) {
302 $queryInfo['conds'][] = 'rev_id = page_latest';
305 if ( $this->newOnly
) {
306 $queryInfo['conds'][] = 'rev_parent_id = 0';
309 if ( $this->hideMinor
) {
310 $queryInfo['conds'][] = 'rev_minor_edit = 0';
313 $user = $this->getUser();
314 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
316 // Paranoia: avoid brute force searches (T19342)
317 if ( !$permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
318 $queryInfo['conds'][] = $this->mDb
->bitAnd(
319 'rev_deleted', RevisionRecord
::DELETED_USER
321 } elseif ( !$permissionManager->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' ) ) {
322 $queryInfo['conds'][] = $this->mDb
->bitAnd(
323 'rev_deleted', RevisionRecord
::SUPPRESSED_USER
324 ) . ' != ' . RevisionRecord
::SUPPRESSED_USER
;
327 // $this->getIndexField() must be in the result rows, as reallyDoQuery() tries to access it.
328 $indexField = $this->getIndexField();
329 if ( $indexField !== 'rev_timestamp' ) {
330 $queryInfo['fields'][] = $indexField;
333 ChangeTags
::modifyDisplayQuery(
334 $queryInfo['tables'],
335 $queryInfo['fields'],
337 $queryInfo['join_conds'],
338 $queryInfo['options'],
342 // Avoid PHP 7.1 warning from passing $this by reference
344 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
349 function getNamespaceCond() {
350 if ( $this->namespace !== '' ) {
351 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
352 $eq_op = $this->nsInvert ?
'!=' : '=';
353 $bool_op = $this->nsInvert ?
'AND' : 'OR';
355 if ( !$this->associated
) {
356 return [ "page_namespace $eq_op $selectedNS" ];
359 $associatedNS = $this->mDb
->addQuotes(
360 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociated( $this->namespace )
364 "page_namespace $eq_op $selectedNS " .
366 " page_namespace $eq_op $associatedNS"
374 * Get SQL conditions for an IP range, if applicable
375 * @param IDatabase $db
376 * @param string $ip The IP address or CIDR
377 * @return string|false SQL for valid IP ranges, false if invalid
379 private function getIpRangeConds( $db, $ip ) {
380 // First make sure it is a valid range and they are not outside the CIDR limit
381 if ( !$this->isQueryableRange( $ip ) ) {
385 list( $start, $end ) = IP
::parseRange( $ip );
387 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
391 * Is the given IP a range and within the CIDR limit?
393 * @param string $ipRange
394 * @return bool True if it is valid
397 public function isQueryableRange( $ipRange ) {
398 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
400 $bits = IP
::parseCIDR( $ipRange )[1];
402 ( $bits === false ) ||
403 ( IP
::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
404 ( IP
::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
415 public function getIndexField() {
416 // The returned column is used for sorting and continuation, so we need to
417 // make sure to use the right denormalized column depending on which table is
418 // being targeted by the query to avoid bad query plans.
419 // See T200259, T204669, T220991, and T221380.
420 $target = $this->getTargetTable();
423 return 'rev_timestamp';
425 return 'ipc_rev_timestamp';
426 case 'revision_actor_temp':
427 return 'revactor_timestamp';
430 __METHOD__
. ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
432 return 'rev_timestamp';
437 * @return false|string
439 public function getTagFilter() {
440 return $this->tagFilter
;
446 public function getTarget() {
447 return $this->target
;
453 public function isNewOnly() {
454 return $this->newOnly
;
460 public function getNamespace() {
461 return $this->namespace;
467 protected function getExtraSortFields() {
468 // The returned columns are used for sorting, so we need to make sure
469 // to use the right denormalized column depending on which table is
470 // being targeted by the query to avoid bad query plans.
471 // See T200259, T204669, T220991, and T221380.
472 $target = $this->getTargetTable();
477 return [ 'ipc_rev_id' ];
478 case 'revision_actor_temp':
479 return [ 'revactor_rev' ];
482 __METHOD__
. ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
488 protected function doBatchLookups() {
489 # Do a link batch query
490 $this->mResult
->seek( 0 );
492 $this->mParentLens
= [];
493 $batch = new LinkBatch();
494 $isIpRange = $this->isQueryableRange( $this->target
);
495 # Give some pointers to make (last) links
496 foreach ( $this->mResult
as $row ) {
497 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
498 $parentRevIds[] = $row->rev_parent_id
;
500 if ( isset( $row->rev_id
) ) {
501 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
503 // If this is an IP range, batch the IP's talk page
504 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
506 $batch->add( $row->page_namespace
, $row->page_title
);
509 # Fetch rev_len for revisions not already scanned above
510 $this->mParentLens +
= Revision
::getParentLengths(
512 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
515 $this->mResult
->seek( 0 );
521 protected function getStartBody() {
522 return "<ul class=\"mw-contributions-list\">\n";
528 protected function getEndBody() {
533 * Check whether the revision associated is valid for formatting. If has no associated revision
534 * id then null is returned.
537 * @param Title|null $title
538 * @return Revision|null
540 public function tryToCreateValidRevision( $row, $title = null ) {
542 * There may be more than just revision rows. To make sure that we'll only be processing
543 * revisions here, let's _try_ to build a revision out of our row (without displaying
544 * notices though) and then trying to grab data from the built object. If we succeed,
545 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
546 * to extensions to subscribe to the hook to parse the row.
548 Wikimedia\
suppressWarnings();
550 $rev = new Revision( $row, 0, $title );
551 $validRevision = (bool)$rev->getId();
552 } catch ( Exception
$e ) {
553 $validRevision = false;
555 Wikimedia\restoreWarnings
();
556 return $validRevision ?
$rev : null;
560 * Generates each row in the contributions list.
562 * Contributions which are marked "top" are currently on top of the history.
563 * For these contributions, a [rollback] link is shown for users with roll-
564 * back privileges. The rollback link restores the most recent version that
565 * was not written by the target user.
567 * @todo This would probably look a lot nicer in a table.
571 function formatRow( $row ) {
576 $linkRenderer = $this->getLinkRenderer();
577 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
580 // Create a title for the revision if possible
581 // Rows from the hook may not include title information
582 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
583 $page = Title
::newFromRow( $row );
585 $rev = $this->tryToCreateValidRevision( $row, $page );
587 $attribs['data-mw-revid'] = $rev->getId();
589 $link = $linkRenderer->makeLink(
591 $page->getPrefixedText(),
592 [ 'class' => 'mw-contributions-title' ],
593 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
595 # Mark current revisions
597 $user = $this->getUser();
599 if ( $row->rev_id
=== $row->page_latest
) {
600 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
601 $classes[] = 'mw-contributions-current';
603 if ( !$row->page_is_new
&&
604 $permissionManager->quickUserCan( 'rollback', $user, $page ) &&
605 $permissionManager->quickUserCan( 'edit', $user, $page )
607 $this->preventClickjacking();
608 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext(),
612 # Is there a visible previous revision?
613 if ( $rev->userCan( RevisionRecord
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
614 $difftext = $linkRenderer->makeKnownLink(
616 new HtmlArmor( $this->messages
['diff'] ),
617 [ 'class' => 'mw-changeslist-diff' ],
620 'oldid' => $row->rev_id
624 $difftext = $this->messages
['diff'];
626 $histlink = $linkRenderer->makeKnownLink(
628 new HtmlArmor( $this->messages
['hist'] ),
629 [ 'class' => 'mw-changeslist-history' ],
630 [ 'action' => 'history' ]
633 if ( $row->rev_parent_id
=== null ) {
634 // For some reason rev_parent_id isn't populated for this row.
635 // Its rumoured this is true on wikipedia for some revisions (T36922).
636 // Next best thing is to have the total number of bytes.
637 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
638 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
639 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
642 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
643 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
646 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
647 $chardiff .= ChangesList
::showCharacterDifference(
652 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
655 $lang = $this->getLanguage();
656 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
657 $d = ChangesList
::revDateLink( $rev, $user, $lang, $page );
659 # When querying for an IP range, we want to always show user and user talk links.
661 if ( $this->isQueryableRange( $this->target
) ) {
662 $userlink = ' <span class="mw-changeslist-separator"></span> '
663 . $lang->getDirMark()
664 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
665 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
666 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
670 if ( $rev->getParentId() === 0 ) {
671 $flags[] = ChangesList
::flag( 'newpage' );
674 if ( $rev->isMinor() ) {
675 $flags[] = ChangesList
::flag( 'minor' );
678 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
683 // While it might be tempting to use a list here
684 // this would result in clutter and slows down navigating the content
685 // in assistive technology.
686 // See https://phabricator.wikimedia.org/T205581#4734812
687 $diffHistLinks = Html
::rawElement( 'span',
688 [ 'class' => 'mw-changeslist-links' ],
689 // The spans are needed to ensure the dividing '|' elements are not
690 // themselves styled as links.
691 Html
::rawElement( 'span', [], $difftext ) .
692 ' ' . // Space needed for separating two words.
693 Html
::rawElement( 'span', [], $histlink )
697 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
702 $classes = array_merge( $classes, $newClasses );
704 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
709 'diffHistLinks' => $diffHistLinks,
710 'charDifference' => $chardiff,
712 'articleLink' => $link,
713 'userlink' => $userlink,
714 'logText' => $comment,
715 'topmarktext' => $topmarktext,
716 'tagSummary' => $tagSummary,
719 # Denote if username is redacted for this edit
720 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
721 $templateParams['rev-deleted-user-contribs'] =
722 $this->msg( 'rev-deleted-user-contribs' )->escaped();
725 $ret = $this->templateParser
->processTemplate(
726 'SpecialContributionsLine',
731 // Let extensions add data
732 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
733 $attribs = array_filter( $attribs,
734 [ Sanitizer
::class, 'isReservedDataAttribute' ],
738 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
739 // receiving empty rows?
741 if ( $classes === [] && $attribs === [] && $ret === '' ) {
742 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
743 return "<!-- Could not format Special:Contribution row. -->\n";
745 $attribs['class'] = $classes;
747 // FIXME: The signature of the ContributionsLineEnding hook makes it
748 // very awkward to move this LI wrapper into the template.
749 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
753 * Overwrite Pager function and return a helpful comment
756 function getSqlComment() {
757 if ( $this->namespace ||
$this->deletedOnly
) {
758 // potentially slow, see CR r58153
759 return 'contributions page filtered for namespace or RevisionDeleted edits';
761 return 'contributions page unfiltered';
765 protected function preventClickjacking() {
766 $this->preventClickjacking
= true;
772 public function getPreventClickjacking() {
773 return $this->preventClickjacking
;
777 * Set up date filter options, given request data.
779 * @param array $opts Options array
780 * @return array Options array with processed start and end date filter options
782 public static function processDateFilter( array $opts ) {
783 $start = $opts['start'] ??
'';
784 $end = $opts['end'] ??
'';
785 $year = $opts['year'] ??
'';
786 $month = $opts['month'] ??
'';
788 if ( $start !== '' && $end !== '' && $start > $end ) {
794 // If year/month legacy filtering options are set, convert them to display the new stamp
795 if ( $year !== '' ||
$month !== '' ) {
796 // Reuse getDateCond logic, but subtract a day because
797 // the endpoints of our date range appear inclusive
798 // but the internal end offsets are always exclusive
799 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
800 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
801 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
803 // Clear the new timestamp range options if used and
804 // replace with the converted legacy timestamp
806 $end = $legacyDateTime->format( 'Y-m-d' );
809 $opts['start'] = $start;