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
;
445 public function getTarget() {
446 return $this->target
;
452 public function isNewOnly() {
453 return $this->newOnly
;
459 public function getNamespace() {
460 return $this->namespace;
466 protected function getExtraSortFields() {
467 // The returned columns are used for sorting, so we need to make sure
468 // to use the right denormalized column depending on which table is
469 // being targeted by the query to avoid bad query plans.
470 // See T200259, T204669, T220991, and T221380.
471 $target = $this->getTargetTable();
476 return [ 'ipc_rev_id' ];
477 case 'revision_actor_temp':
478 return [ 'revactor_rev' ];
481 __METHOD__
. ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
487 protected function doBatchLookups() {
488 # Do a link batch query
489 $this->mResult
->seek( 0 );
491 $this->mParentLens
= [];
492 $batch = new LinkBatch();
493 $isIpRange = $this->isQueryableRange( $this->target
);
494 # Give some pointers to make (last) links
495 foreach ( $this->mResult
as $row ) {
496 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
497 $parentRevIds[] = $row->rev_parent_id
;
499 if ( isset( $row->rev_id
) ) {
500 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
502 // If this is an IP range, batch the IP's talk page
503 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
505 $batch->add( $row->page_namespace
, $row->page_title
);
508 # Fetch rev_len for revisions not already scanned above
509 $this->mParentLens +
= Revision
::getParentLengths(
511 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
514 $this->mResult
->seek( 0 );
520 protected function getStartBody() {
521 return "<ul class=\"mw-contributions-list\">\n";
527 protected function getEndBody() {
532 * Check whether the revision associated is valid for formatting. If has no associated revision
533 * id then null is returned.
536 * @param Title|null $title
537 * @return Revision|null
539 public function tryToCreateValidRevision( $row, $title = null ) {
541 * There may be more than just revision rows. To make sure that we'll only be processing
542 * revisions here, let's _try_ to build a revision out of our row (without displaying
543 * notices though) and then trying to grab data from the built object. If we succeed,
544 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
545 * to extensions to subscribe to the hook to parse the row.
547 Wikimedia\
suppressWarnings();
549 $rev = new Revision( $row, 0, $title );
550 $validRevision = (bool)$rev->getId();
551 } catch ( Exception
$e ) {
552 $validRevision = false;
554 Wikimedia\restoreWarnings
();
555 return $validRevision ?
$rev : null;
559 * Generates each row in the contributions list.
561 * Contributions which are marked "top" are currently on top of the history.
562 * For these contributions, a [rollback] link is shown for users with roll-
563 * back privileges. The rollback link restores the most recent version that
564 * was not written by the target user.
566 * @todo This would probably look a lot nicer in a table.
570 function formatRow( $row ) {
575 $linkRenderer = $this->getLinkRenderer();
578 // Create a title for the revision if possible
579 // Rows from the hook may not include title information
580 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
581 $page = Title
::newFromRow( $row );
583 $rev = $this->tryToCreateValidRevision( $row, $page );
585 $attribs['data-mw-revid'] = $rev->getId();
587 $link = $linkRenderer->makeLink(
589 $page->getPrefixedText(),
590 [ 'class' => 'mw-contributions-title' ],
591 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
593 # Mark current revisions
595 $user = $this->getUser();
597 if ( $row->rev_id
=== $row->page_latest
) {
598 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
599 $classes[] = 'mw-contributions-current';
601 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
602 && $page->quickUserCan( 'edit', $user )
604 $this->preventClickjacking();
605 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext(),
609 # Is there a visible previous revision?
610 if ( $rev->userCan( RevisionRecord
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
611 $difftext = $linkRenderer->makeKnownLink(
613 new HtmlArmor( $this->messages
['diff'] ),
614 [ 'class' => 'mw-changeslist-diff' ],
617 'oldid' => $row->rev_id
621 $difftext = $this->messages
['diff'];
623 $histlink = $linkRenderer->makeKnownLink(
625 new HtmlArmor( $this->messages
['hist'] ),
626 [ 'class' => 'mw-changeslist-history' ],
627 [ 'action' => 'history' ]
630 if ( $row->rev_parent_id
=== null ) {
631 // For some reason rev_parent_id isn't populated for this row.
632 // Its rumoured this is true on wikipedia for some revisions (T36922).
633 // Next best thing is to have the total number of bytes.
634 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
635 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
636 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
639 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
640 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
643 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
644 $chardiff .= ChangesList
::showCharacterDifference(
649 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
652 $lang = $this->getLanguage();
653 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
654 $d = ChangesList
::revDateLink( $rev, $user, $lang, $page );
656 # When querying for an IP range, we want to always show user and user talk links.
658 if ( $this->isQueryableRange( $this->target
) ) {
659 $userlink = ' <span class="mw-changeslist-separator"></span> '
660 . $lang->getDirMark()
661 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
662 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
663 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
667 if ( $rev->getParentId() === 0 ) {
668 $flags[] = ChangesList
::flag( 'newpage' );
671 if ( $rev->isMinor() ) {
672 $flags[] = ChangesList
::flag( 'minor' );
675 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
680 // While it might be tempting to use a list here
681 // this would result in clutter and slows down navigating the content
682 // in assistive technology.
683 // See https://phabricator.wikimedia.org/T205581#4734812
684 $diffHistLinks = Html
::rawElement( 'span',
685 [ 'class' => 'mw-changeslist-links' ],
686 // The spans are needed to ensure the dividing '|' elements are not
687 // themselves styled as links.
688 Html
::rawElement( 'span', [], $difftext ) .
689 ' ' . // Space needed for separating two words.
690 Html
::rawElement( 'span', [], $histlink )
694 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
699 $classes = array_merge( $classes, $newClasses );
701 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
706 'diffHistLinks' => $diffHistLinks,
707 'charDifference' => $chardiff,
709 'articleLink' => $link,
710 'userlink' => $userlink,
711 'logText' => $comment,
712 'topmarktext' => $topmarktext,
713 'tagSummary' => $tagSummary,
716 # Denote if username is redacted for this edit
717 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
718 $templateParams['rev-deleted-user-contribs'] =
719 $this->msg( 'rev-deleted-user-contribs' )->escaped();
722 $ret = $this->templateParser
->processTemplate(
723 'SpecialContributionsLine',
728 // Let extensions add data
729 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
730 $attribs = array_filter( $attribs,
731 [ Sanitizer
::class, 'isReservedDataAttribute' ],
735 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
736 // receiving empty rows?
738 if ( $classes === [] && $attribs === [] && $ret === '' ) {
739 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
740 return "<!-- Could not format Special:Contribution row. -->\n";
742 $attribs['class'] = $classes;
744 // FIXME: The signature of the ContributionsLineEnding hook makes it
745 // very awkward to move this LI wrapper into the template.
746 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
750 * Overwrite Pager function and return a helpful comment
753 function getSqlComment() {
754 if ( $this->namespace ||
$this->deletedOnly
) {
755 // potentially slow, see CR r58153
756 return 'contributions page filtered for namespace or RevisionDeleted edits';
758 return 'contributions page unfiltered';
762 protected function preventClickjacking() {
763 $this->preventClickjacking
= true;
769 public function getPreventClickjacking() {
770 return $this->preventClickjacking
;
774 * Set up date filter options, given request data.
776 * @param array $opts Options array
777 * @return array Options array with processed start and end date filter options
779 public static function processDateFilter( array $opts ) {
780 $start = $opts['start'] ??
'';
781 $end = $opts['end'] ??
'';
782 $year = $opts['year'] ??
'';
783 $month = $opts['month'] ??
'';
785 if ( $start !== '' && $end !== '' && $start > $end ) {
791 // If year/month legacy filtering options are set, convert them to display the new stamp
792 if ( $year !== '' ||
$month !== '' ) {
793 // Reuse getDateCond logic, but subtract a day because
794 // the endpoints of our date range appear inclusive
795 // but the internal end offsets are always exclusive
796 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
797 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
798 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
800 // Clear the new timestamp range options if used and
801 // replace with the converted legacy timestamp
803 $end = $legacyDateTime->format( 'Y-m-d' );
806 $opts['start'] = $start;