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';
437 protected function getExtraSortFields() {
438 // Note this is run via parent::__construct() *before* $this->target is set!
442 protected function doBatchLookups() {
443 # Do a link batch query
444 $this->mResult
->seek( 0 );
446 $this->mParentLens
= [];
447 $batch = new LinkBatch();
448 $isIpRange = $this->isQueryableRange( $this->target
);
449 # Give some pointers to make (last) links
450 foreach ( $this->mResult
as $row ) {
451 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
452 $parentRevIds[] = $row->rev_parent_id
;
454 if ( isset( $row->rev_id
) ) {
455 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
456 if ( $this->contribs
=== 'newbie' ) { // multiple users
457 $batch->add( NS_USER
, $row->user_name
);
458 $batch->add( NS_USER_TALK
, $row->user_name
);
459 } elseif ( $isIpRange ) {
460 // If this is an IP range, batch the IP's talk page
461 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
463 $batch->add( $row->page_namespace
, $row->page_title
);
466 # Fetch rev_len for revisions not already scanned above
467 $this->mParentLens +
= Revision
::getParentLengths(
469 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
472 $this->mResult
->seek( 0 );
478 protected function getStartBody() {
479 return "<ul class=\"mw-contributions-list\">\n";
485 protected function getEndBody() {
490 * Check whether the revision associated is valid for formatting. If has no associated revision
491 * id then null is returned.
494 * @param Title|null $title
495 * @return Revision|null
497 public function tryToCreateValidRevision( $row, $title = null ) {
499 * There may be more than just revision rows. To make sure that we'll only be processing
500 * revisions here, let's _try_ to build a revision out of our row (without displaying
501 * notices though) and then trying to grab data from the built object. If we succeed,
502 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
503 * to extensions to subscribe to the hook to parse the row.
505 Wikimedia\
suppressWarnings();
507 $rev = new Revision( $row, 0, $title );
508 $validRevision = (bool)$rev->getId();
509 } catch ( Exception
$e ) {
510 $validRevision = false;
512 Wikimedia\restoreWarnings
();
513 return $validRevision ?
$rev : null;
517 * Generates each row in the contributions list.
519 * Contributions which are marked "top" are currently on top of the history.
520 * For these contributions, a [rollback] link is shown for users with roll-
521 * back privileges. The rollback link restores the most recent version that
522 * was not written by the target user.
524 * @todo This would probably look a lot nicer in a table.
528 function formatRow( $row ) {
533 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
536 // Create a title for the revision if possible
537 // Rows from the hook may not include title information
538 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
539 $page = Title
::newFromRow( $row );
541 $rev = $this->tryToCreateValidRevision( $row, $page );
543 $attribs['data-mw-revid'] = $rev->getId();
545 $link = $linkRenderer->makeLink(
547 $page->getPrefixedText(),
548 [ 'class' => 'mw-contributions-title' ],
549 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
551 # Mark current revisions
553 $user = $this->getUser();
555 if ( $row->rev_id
=== $row->page_latest
) {
556 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
557 $classes[] = 'mw-contributions-current';
559 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
560 && $page->quickUserCan( 'edit', $user )
562 $this->preventClickjacking();
563 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
566 # Is there a visible previous revision?
567 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
568 $difftext = $linkRenderer->makeKnownLink(
570 new HtmlArmor( $this->messages
['diff'] ),
571 [ 'class' => 'mw-changeslist-diff' ],
574 'oldid' => $row->rev_id
578 $difftext = $this->messages
['diff'];
580 $histlink = $linkRenderer->makeKnownLink(
582 new HtmlArmor( $this->messages
['hist'] ),
583 [ 'class' => 'mw-changeslist-history' ],
584 [ 'action' => 'history' ]
587 if ( $row->rev_parent_id
=== null ) {
588 // For some reason rev_parent_id isn't populated for this row.
589 // Its rumoured this is true on wikipedia for some revisions (T36922).
590 // Next best thing is to have the total number of bytes.
591 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
592 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
593 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
596 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
597 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
600 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
601 $chardiff .= ChangesList
::showCharacterDifference(
606 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
609 $lang = $this->getLanguage();
610 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
611 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
612 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
613 $d = $linkRenderer->makeKnownLink(
616 [ 'class' => 'mw-changeslist-date' ],
617 [ 'oldid' => intval( $row->rev_id
) ]
620 $d = htmlspecialchars( $date );
622 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
623 $d = '<span class="history-deleted">' . $d . '</span>';
626 # Show user names for /newbies as there may be different users.
627 # Note that only unprivileged users have rows with hidden user names excluded.
628 # When querying for an IP range, we want to always show user and user talk links.
630 if ( ( $this->contribs
== 'newbie' && !$rev->isDeleted( Revision
::DELETED_USER
) )
631 ||
$this->isQueryableRange( $this->target
) ) {
632 $userlink = ' <span class="mw-changeslist-separator"></span> '
633 . $lang->getDirMark()
634 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
635 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
636 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
640 if ( $rev->getParentId() === 0 ) {
641 $flags[] = ChangesList
::flag( 'newpage' );
644 if ( $rev->isMinor() ) {
645 $flags[] = ChangesList
::flag( 'minor' );
648 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
653 // While it might be tempting to use a list here
654 // this would result in clutter and slows down navigating the content
655 // in assistive technology.
656 // See https://phabricator.wikimedia.org/T205581#4734812
657 $diffHistLinks = Html
::rawElement( 'span',
658 [ 'class' => 'mw-changeslist-links' ],
659 // The spans are needed to ensure the dividing '|' elements are not
660 // themselves styled as links.
661 Html
::rawElement( 'span', [], $difftext ) .
662 ' ' . // Space needed for separating two words.
663 Html
::rawElement( 'span', [], $histlink )
667 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
672 $classes = array_merge( $classes, $newClasses );
674 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
679 'diffHistLinks' => $diffHistLinks,
680 'charDifference' => $chardiff,
682 'articleLink' => $link,
683 'userlink' => $userlink,
684 'logText' => $comment,
685 'topmarktext' => $topmarktext,
686 'tagSummary' => $tagSummary,
689 # Denote if username is redacted for this edit
690 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
691 $templateParams['rev-deleted-user-contribs'] =
692 $this->msg( 'rev-deleted-user-contribs' )->escaped();
695 $ret = $this->templateParser
->processTemplate(
696 'SpecialContributionsLine',
701 // Let extensions add data
702 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
703 $attribs = array_filter( $attribs,
704 [ Sanitizer
::class, 'isReservedDataAttribute' ],
708 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
709 // receiving empty rows?
711 if ( $classes === [] && $attribs === [] && $ret === '' ) {
712 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
713 return "<!-- Could not format Special:Contribution row. -->\n";
715 $attribs['class'] = $classes;
717 // FIXME: The signature of the ContributionsLineEnding hook makes it
718 // very awkward to move this LI wrapper into the template.
719 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
723 * Overwrite Pager function and return a helpful comment
726 function getSqlComment() {
727 if ( $this->namespace ||
$this->deletedOnly
) {
728 // potentially slow, see CR r58153
729 return 'contributions page filtered for namespace or RevisionDeleted edits';
731 return 'contributions page unfiltered';
735 protected function preventClickjacking() {
736 $this->preventClickjacking
= true;
742 public function getPreventClickjacking() {
743 return $this->preventClickjacking
;
747 * Set up date filter options, given request data.
749 * @param array $opts Options array
750 * @return array Options array with processed start and end date filter options
752 public static function processDateFilter( array $opts ) {
753 $start = $opts['start'] ??
'';
754 $end = $opts['end'] ??
'';
755 $year = $opts['year'] ??
'';
756 $month = $opts['month'] ??
'';
758 if ( $start !== '' && $end !== '' && $start > $end ) {
764 // If year/month legacy filtering options are set, convert them to display the new stamp
765 if ( $year !== '' ||
$month !== '' ) {
766 // Reuse getDateCond logic, but subtract a day because
767 // the endpoints of our date range appear inclusive
768 // but the internal end offsets are always exclusive
769 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
770 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
771 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
773 // Clear the new timestamp range options if used and
774 // replace with the converted legacy timestamp
776 $end = $legacyDateTime->format( 'Y-m-d' );
779 $opts['start'] = $start;