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 Wikimedia\Rdbms\IResultWrapper
;
28 use Wikimedia\Rdbms\FakeResultWrapper
;
29 use Wikimedia\Rdbms\IDatabase
;
31 class ContribsPager
extends RangeChronologicalPager
{
34 * @var string[] Local cache for escaped messages
39 * @var string User name, or a string describing an IP address range
41 * @fixme Make private again after Flow got fixed.
46 * @var string Set to "newbie" to list contributions from the most recent 1% registered users.
47 * $this->target is ignored then. Defaults to "users".
49 * @fixme Make private again after Flow got fixed.
54 * @var string|int A single namespace number, or an empty string for all namespaces
56 * @fixme Make private again after Flow got fixed.
58 public $namespace = '';
61 * @var string|false Name of tag to filter, or false to ignore tags
63 * @fixme Make private again after Flow got fixed.
68 * @var bool Set to true to invert the namespace selection
73 * @var bool Set to true to show both the subject and talk namespace, no matter which got
79 * @var bool Set to true to show only deleted revisions
84 * @var bool Set to true to show only latest (a.k.a. current) revisions
89 * @var bool Set to true to show only new pages
91 * @fixme Make private again after Flow got fixed.
96 * @var bool Set to true to hide edits marked as minor by the user
100 private $preventClickjacking = false;
102 /** @var IDatabase */
103 private $mDbSecondary;
108 private $mParentLens;
111 * @var TemplateParser
113 private $templateParser;
115 public function __construct( IContextSource
$context, array $options ) {
116 parent
::__construct( $context );
125 foreach ( $msgs as $msg ) {
126 $this->messages
[$msg] = $this->msg( $msg )->escaped();
129 $this->target
= $options['target'] ??
'';
130 $this->contribs
= $options['contribs'] ??
'users';
131 $this->namespace = $options['namespace'] ??
'';
132 $this->tagFilter
= $options['tagfilter'] ??
false;
133 $this->nsInvert
= $options['nsInvert'] ??
false;
134 $this->associated
= $options['associated'] ??
false;
136 $this->deletedOnly
= !empty( $options['deletedOnly'] );
137 $this->topOnly
= !empty( $options['topOnly'] );
138 $this->newOnly
= !empty( $options['newOnly'] );
139 $this->hideMinor
= !empty( $options['hideMinor'] );
141 // Date filtering: use timestamp if available
142 $startTimestamp = '';
144 if ( $options['start'] ) {
145 $startTimestamp = $options['start'] . ' 00:00:00';
147 if ( $options['end'] ) {
148 $endTimestamp = $options['end'] . ' 23:59:59';
150 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
152 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
153 // with extra user based indexes or partioning by user. The additional metadata
154 // queries should use a regular replica DB since the lookup pattern is not all by user.
155 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
156 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
157 $this->templateParser
= new TemplateParser();
160 function getDefaultQuery() {
161 $query = parent
::getDefaultQuery();
162 $query['target'] = $this->target
;
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 $descending Query direction, false for ascending, true for descending
174 * @return IResultWrapper
176 function reallyDoQuery( $offset, $limit, $descending ) {
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, $descending ]
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;
227 $result = array_slice( $result, 0, $limit );
229 // get rid of array keys
230 $result = array_values( $result );
232 return new FakeResultWrapper( $result );
235 function getQueryInfo() {
236 $revQuery = Revision
::getQueryInfo( [ 'page', 'user' ] );
238 'tables' => $revQuery['tables'],
239 'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
242 'join_conds' => $revQuery['joins'],
245 if ( $this->contribs
== 'newbie' ) {
246 $max = $this->mDb
->selectField( 'user', 'max(user_id)', '', __METHOD__
);
247 $queryInfo['conds'][] = $revQuery['fields']['rev_user'] . ' >' . (int)( $max - $max / 100 );
248 # ignore local groups with the bot right
249 # @todo FIXME: Global groups may have 'bot' rights
250 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
251 if ( count( $groupsWithBotPermission ) ) {
252 $queryInfo['tables'][] = 'user_groups';
253 $queryInfo['conds'][] = 'ug_group IS NULL';
254 $queryInfo['join_conds']['user_groups'] = [
256 'ug_user = ' . $revQuery['fields']['rev_user'],
257 'ug_group' => $groupsWithBotPermission,
258 'ug_expiry IS NULL OR ug_expiry >= ' .
259 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
263 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
264 // a timestamp offset far in the past such that there are no edits by users with user_ids in
265 // the range, we would end up scanning all revisions from that offset until start of time.
266 $queryInfo['conds'][] = 'rev_timestamp > ' .
267 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
269 $user = User
::newFromName( $this->target
, false );
270 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
271 if ( $ipRangeConds ) {
272 $queryInfo['tables'][] = 'ip_changes';
274 * These aliases make `ORDER BY rev_timestamp, rev_id` from {@see getIndexField} and
275 * {@see getExtraSortFields} use the replicated `ipc_rev_timestamp` and `ipc_rev_id`
276 * columns from the `ip_changes` table, for more efficient queries.
277 * @see https://phabricator.wikimedia.org/T200259#4832318
279 $queryInfo['fields'] = array_merge(
281 'rev_timestamp' => 'ipc_rev_timestamp',
282 'rev_id' => 'ipc_rev_id',
284 array_diff( $queryInfo['fields'], [
289 $queryInfo['join_conds']['ip_changes'] = [
290 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
292 $queryInfo['conds'][] = $ipRangeConds;
294 // tables and joins are already handled by Revision::getQueryInfo()
295 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
296 $queryInfo['conds'][] = $conds['conds'];
297 // Force the appropriate index to avoid bad query plans (T189026)
298 if ( isset( $conds['orconds']['actor'] ) ) {
299 // @todo: This will need changing when revision_comment_temp goes away
300 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
301 // Alias 'rev_timestamp' => 'revactor_timestamp' so "ORDER BY rev_timestamp" is interpreted to
302 // use revactor_timestamp instead.
303 $queryInfo['fields'] = array_merge(
304 array_diff( $queryInfo['fields'], [ 'rev_timestamp' ] ),
305 [ 'rev_timestamp' => 'revactor_timestamp' ]
308 $queryInfo['options']['USE INDEX']['revision'] =
309 isset( $conds['orconds']['userid'] ) ?
'user_timestamp' : 'usertext_timestamp';
314 if ( $this->deletedOnly
) {
315 $queryInfo['conds'][] = 'rev_deleted != 0';
318 if ( $this->topOnly
) {
319 $queryInfo['conds'][] = 'rev_id = page_latest';
322 if ( $this->newOnly
) {
323 $queryInfo['conds'][] = 'rev_parent_id = 0';
326 if ( $this->hideMinor
) {
327 $queryInfo['conds'][] = 'rev_minor_edit = 0';
330 $user = $this->getUser();
331 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
333 // Paranoia: avoid brute force searches (T19342)
334 if ( !$user->isAllowed( 'deletedhistory' ) ) {
335 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
336 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
337 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
338 ' != ' . Revision
::SUPPRESSED_USER
;
341 // For IPv6, we use ipc_rev_timestamp on ip_changes as the index field,
342 // which will be referenced when parsing the results of a query.
343 if ( self
::isQueryableRange( $this->target
) ) {
344 $queryInfo['fields'][] = 'ipc_rev_timestamp';
347 ChangeTags
::modifyDisplayQuery(
348 $queryInfo['tables'],
349 $queryInfo['fields'],
351 $queryInfo['join_conds'],
352 $queryInfo['options'],
356 // Avoid PHP 7.1 warning from passing $this by reference
358 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
363 function getNamespaceCond() {
364 if ( $this->namespace !== '' ) {
365 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
366 $eq_op = $this->nsInvert ?
'!=' : '=';
367 $bool_op = $this->nsInvert ?
'AND' : 'OR';
369 if ( !$this->associated
) {
370 return [ "page_namespace $eq_op $selectedNS" ];
373 $associatedNS = $this->mDb
->addQuotes(
374 MWNamespace
::getAssociated( $this->namespace )
378 "page_namespace $eq_op $selectedNS " .
380 " page_namespace $eq_op $associatedNS"
388 * Get SQL conditions for an IP range, if applicable
389 * @param IDatabase $db
390 * @param string $ip The IP address or CIDR
391 * @return string|false SQL for valid IP ranges, false if invalid
393 private function getIpRangeConds( $db, $ip ) {
394 // First make sure it is a valid range and they are not outside the CIDR limit
395 if ( !$this->isQueryableRange( $ip ) ) {
399 list( $start, $end ) = IP
::parseRange( $ip );
401 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
405 * Is the given IP a range and within the CIDR limit?
407 * @param string $ipRange
408 * @return bool True if it is valid
411 public function isQueryableRange( $ipRange ) {
412 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
414 $bits = IP
::parseCIDR( $ipRange )[1];
416 ( $bits === false ) ||
417 ( IP
::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
418 ( IP
::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
429 public function getIndexField() {
430 // Note this is run via parent::__construct() *before* $this->target is set!
431 return 'rev_timestamp';
435 * @return false|string
437 public function getTagFilter() {
438 return $this->tagFilter
;
444 public function getContribs() {
445 return $this->contribs
;
451 public function getTarget() {
452 return $this->target
;
458 public function isNewOnly() {
459 return $this->newOnly
;
465 public function getNamespace() {
466 return $this->namespace;
472 protected function getExtraSortFields() {
473 // Note this is run via parent::__construct() *before* $this->target is set!
477 protected function doBatchLookups() {
478 # Do a link batch query
479 $this->mResult
->seek( 0 );
481 $this->mParentLens
= [];
482 $batch = new LinkBatch();
483 $isIpRange = $this->isQueryableRange( $this->target
);
484 # Give some pointers to make (last) links
485 foreach ( $this->mResult
as $row ) {
486 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
487 $parentRevIds[] = $row->rev_parent_id
;
489 if ( isset( $row->rev_id
) ) {
490 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
491 if ( $this->contribs
=== 'newbie' ) { // multiple users
492 $batch->add( NS_USER
, $row->user_name
);
493 $batch->add( NS_USER_TALK
, $row->user_name
);
494 } elseif ( $isIpRange ) {
495 // If this is an IP range, batch the IP's talk page
496 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
498 $batch->add( $row->page_namespace
, $row->page_title
);
501 # Fetch rev_len for revisions not already scanned above
502 $this->mParentLens +
= Revision
::getParentLengths(
504 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
507 $this->mResult
->seek( 0 );
513 protected function getStartBody() {
514 return "<ul class=\"mw-contributions-list\">\n";
520 protected function getEndBody() {
525 * Check whether the revision associated is valid for formatting. If has no associated revision
526 * id then null is returned.
529 * @param Title|null $title
530 * @return Revision|null
532 public function tryToCreateValidRevision( $row, $title = null ) {
534 * There may be more than just revision rows. To make sure that we'll only be processing
535 * revisions here, let's _try_ to build a revision out of our row (without displaying
536 * notices though) and then trying to grab data from the built object. If we succeed,
537 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
538 * to extensions to subscribe to the hook to parse the row.
540 Wikimedia\
suppressWarnings();
542 $rev = new Revision( $row, 0, $title );
543 $validRevision = (bool)$rev->getId();
544 } catch ( Exception
$e ) {
545 $validRevision = false;
547 Wikimedia\restoreWarnings
();
548 return $validRevision ?
$rev : null;
552 * Generates each row in the contributions list.
554 * Contributions which are marked "top" are currently on top of the history.
555 * For these contributions, a [rollback] link is shown for users with roll-
556 * back privileges. The rollback link restores the most recent version that
557 * was not written by the target user.
559 * @todo This would probably look a lot nicer in a table.
563 function formatRow( $row ) {
568 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
571 // Create a title for the revision if possible
572 // Rows from the hook may not include title information
573 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
574 $page = Title
::newFromRow( $row );
576 $rev = $this->tryToCreateValidRevision( $row, $page );
578 $attribs['data-mw-revid'] = $rev->getId();
580 $link = $linkRenderer->makeLink(
582 $page->getPrefixedText(),
583 [ 'class' => 'mw-contributions-title' ],
584 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
586 # Mark current revisions
588 $user = $this->getUser();
590 if ( $row->rev_id
=== $row->page_latest
) {
591 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
592 $classes[] = 'mw-contributions-current';
594 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
595 && $page->quickUserCan( 'edit', $user )
597 $this->preventClickjacking();
598 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
601 # Is there a visible previous revision?
602 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
603 $difftext = $linkRenderer->makeKnownLink(
605 new HtmlArmor( $this->messages
['diff'] ),
606 [ 'class' => 'mw-changeslist-diff' ],
609 'oldid' => $row->rev_id
613 $difftext = $this->messages
['diff'];
615 $histlink = $linkRenderer->makeKnownLink(
617 new HtmlArmor( $this->messages
['hist'] ),
618 [ 'class' => 'mw-changeslist-history' ],
619 [ 'action' => 'history' ]
622 if ( $row->rev_parent_id
=== null ) {
623 // For some reason rev_parent_id isn't populated for this row.
624 // Its rumoured this is true on wikipedia for some revisions (T36922).
625 // Next best thing is to have the total number of bytes.
626 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
627 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
628 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
631 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
632 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
635 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
636 $chardiff .= ChangesList
::showCharacterDifference(
641 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
644 $lang = $this->getLanguage();
645 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
646 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
647 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
648 $d = $linkRenderer->makeKnownLink(
651 [ 'class' => 'mw-changeslist-date' ],
652 [ 'oldid' => intval( $row->rev_id
) ]
655 $d = htmlspecialchars( $date );
657 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
658 $d = '<span class="history-deleted">' . $d . '</span>';
661 # Show user names for /newbies as there may be different users.
662 # Note that only unprivileged users have rows with hidden user names excluded.
663 # When querying for an IP range, we want to always show user and user talk links.
665 if ( ( $this->contribs
== 'newbie' && !$rev->isDeleted( Revision
::DELETED_USER
) )
666 ||
$this->isQueryableRange( $this->target
) ) {
667 $userlink = ' <span class="mw-changeslist-separator"></span> '
668 . $lang->getDirMark()
669 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
670 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
671 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
675 if ( $rev->getParentId() === 0 ) {
676 $flags[] = ChangesList
::flag( 'newpage' );
679 if ( $rev->isMinor() ) {
680 $flags[] = ChangesList
::flag( 'minor' );
683 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
688 // While it might be tempting to use a list here
689 // this would result in clutter and slows down navigating the content
690 // in assistive technology.
691 // See https://phabricator.wikimedia.org/T205581#4734812
692 $diffHistLinks = Html
::rawElement( 'span',
693 [ 'class' => 'mw-changeslist-links' ],
694 // The spans are needed to ensure the dividing '|' elements are not
695 // themselves styled as links.
696 Html
::rawElement( 'span', [], $difftext ) .
697 ' ' . // Space needed for separating two words.
698 Html
::rawElement( 'span', [], $histlink )
702 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
707 $classes = array_merge( $classes, $newClasses );
709 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
714 'diffHistLinks' => $diffHistLinks,
715 'charDifference' => $chardiff,
717 'articleLink' => $link,
718 'userlink' => $userlink,
719 'logText' => $comment,
720 'topmarktext' => $topmarktext,
721 'tagSummary' => $tagSummary,
724 # Denote if username is redacted for this edit
725 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
726 $templateParams['rev-deleted-user-contribs'] =
727 $this->msg( 'rev-deleted-user-contribs' )->escaped();
730 $ret = $this->templateParser
->processTemplate(
731 'SpecialContributionsLine',
736 // Let extensions add data
737 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
738 $attribs = array_filter( $attribs,
739 [ Sanitizer
::class, 'isReservedDataAttribute' ],
743 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
744 // receiving empty rows?
746 if ( $classes === [] && $attribs === [] && $ret === '' ) {
747 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
748 return "<!-- Could not format Special:Contribution row. -->\n";
750 $attribs['class'] = $classes;
752 // FIXME: The signature of the ContributionsLineEnding hook makes it
753 // very awkward to move this LI wrapper into the template.
754 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
758 * Overwrite Pager function and return a helpful comment
761 function getSqlComment() {
762 if ( $this->namespace ||
$this->deletedOnly
) {
763 // potentially slow, see CR r58153
764 return 'contributions page filtered for namespace or RevisionDeleted edits';
766 return 'contributions page unfiltered';
770 protected function preventClickjacking() {
771 $this->preventClickjacking
= true;
777 public function getPreventClickjacking() {
778 return $this->preventClickjacking
;
782 * Set up date filter options, given request data.
784 * @param array $opts Options array
785 * @return array Options array with processed start and end date filter options
787 public static function processDateFilter( array $opts ) {
788 $start = $opts['start'] ??
'';
789 $end = $opts['end'] ??
'';
790 $year = $opts['year'] ??
'';
791 $month = $opts['month'] ??
'';
793 if ( $start !== '' && $end !== '' && $start > $end ) {
799 // If year/month legacy filtering options are set, convert them to display the new stamp
800 if ( $year !== '' ||
$month !== '' ) {
801 // Reuse getDateCond logic, but subtract a day because
802 // the endpoints of our date range appear inclusive
803 // but the internal end offsets are always exclusive
804 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
805 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
806 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
808 // Clear the new timestamp range options if used and
809 // replace with the converted legacy timestamp
811 $end = $legacyDateTime->format( 'Y-m-d' );
814 $opts['start'] = $start;