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
{
33 public $mDefaultDirection = IndexPager
::DIR_DESCENDING
;
36 * @var string[] Local cache for escaped messages
41 * @var string User name, or a string describing an IP address range
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".
52 * @var string|int A single namespace number, or an empty string for all namespaces
54 public $namespace = '';
57 * @var string|false Name of tag to filter, or false to ignore tags
62 * @var bool Set to true to invert the namespace selection
67 * @var bool Set to true to show both the subject and talk namespace, no matter which got
73 * @var bool Set to true to show only deleted revisions
78 * @var bool Set to true to show only latest (a.k.a. current) revisions
83 * @var bool Set to true to show only new pages
88 * @var bool Set to true to hide edits marked as minor by the user
93 public $preventClickjacking = false;
101 protected $mParentLens;
104 * @var TemplateParser
106 protected $templateParser;
108 function __construct( IContextSource
$context, array $options ) {
109 parent
::__construct( $context );
118 foreach ( $msgs as $msg ) {
119 $this->messages
[$msg] = $this->msg( $msg )->escaped();
122 $this->target
= $options['target'] ??
'';
123 $this->contribs
= $options['contribs'] ??
'users';
124 $this->namespace = $options['namespace'] ??
'';
125 $this->tagFilter
= $options['tagfilter'] ??
false;
126 $this->nsInvert
= $options['nsInvert'] ??
false;
127 $this->associated
= $options['associated'] ??
false;
129 $this->deletedOnly
= !empty( $options['deletedOnly'] );
130 $this->topOnly
= !empty( $options['topOnly'] );
131 $this->newOnly
= !empty( $options['newOnly'] );
132 $this->hideMinor
= !empty( $options['hideMinor'] );
134 // Date filtering: use timestamp if available
135 $startTimestamp = '';
137 if ( $options['start'] ) {
138 $startTimestamp = $options['start'] . ' 00:00:00';
140 if ( $options['end'] ) {
141 $endTimestamp = $options['end'] . ' 23:59:59';
143 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
145 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
146 // with extra user based indexes or partioning by user. The additional metadata
147 // queries should use a regular replica DB since the lookup pattern is not all by user.
148 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
149 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
150 $this->templateParser
= new TemplateParser();
153 function getDefaultQuery() {
154 $query = parent
::getDefaultQuery();
155 $query['target'] = $this->target
;
161 * This method basically executes the exact same code as the parent class, though with
162 * a hook added, to allow extensions to add additional queries.
164 * @param string $offset Index offset, inclusive
165 * @param int $limit Exact query limit
166 * @param bool $descending Query direction, false for ascending, true for descending
167 * @return IResultWrapper
169 function reallyDoQuery( $offset, $limit, $descending ) {
170 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
177 * This hook will allow extensions to add in additional queries, so they can get their data
178 * in My Contributions as well. Extensions should append their results to the $data array.
180 * Extension queries have to implement the navbar requirement as well. They should
181 * - have a column aliased as $pager->getIndexField()
183 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
184 * - have the ORDER BY specified based upon the details provided by the navbar
186 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
188 * &$data: an array of results of all contribs queries
189 * $pager: the ContribsPager object hooked into
190 * $offset: see phpdoc above
191 * $limit: see phpdoc above
192 * $descending: see phpdoc above
194 $data = [ $this->mDb
->select(
195 $tables, $fields, $conds, $fname, $options, $join_conds
198 'ContribsPager::reallyDoQuery',
199 [ &$data, $this, $offset, $limit, $descending ]
204 // loop all results and collect them in an array
205 foreach ( $data as $query ) {
206 foreach ( $query as $i => $row ) {
207 // use index column as key, allowing us to easily sort in PHP
208 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
220 $result = array_slice( $result, 0, $limit );
222 // get rid of array keys
223 $result = array_values( $result );
225 return new FakeResultWrapper( $result );
228 function getQueryInfo() {
229 $revQuery = Revision
::getQueryInfo( [ 'page', 'user' ] );
231 'tables' => $revQuery['tables'],
232 'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
235 'join_conds' => $revQuery['joins'],
238 if ( $this->contribs
== 'newbie' ) {
239 $max = $this->mDb
->selectField( 'user', 'max(user_id)', '', __METHOD__
);
240 $queryInfo['conds'][] = $revQuery['fields']['rev_user'] . ' >' . (int)( $max - $max / 100 );
241 # ignore local groups with the bot right
242 # @todo FIXME: Global groups may have 'bot' rights
243 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
244 if ( count( $groupsWithBotPermission ) ) {
245 $queryInfo['tables'][] = 'user_groups';
246 $queryInfo['conds'][] = 'ug_group IS NULL';
247 $queryInfo['join_conds']['user_groups'] = [
249 'ug_user = ' . $revQuery['fields']['rev_user'],
250 'ug_group' => $groupsWithBotPermission,
251 'ug_expiry IS NULL OR ug_expiry >= ' .
252 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
256 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
257 // a timestamp offset far in the past such that there are no edits by users with user_ids in
258 // the range, we would end up scanning all revisions from that offset until start of time.
259 $queryInfo['conds'][] = 'rev_timestamp > ' .
260 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
262 $user = User
::newFromName( $this->target
, false );
263 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
264 if ( $ipRangeConds ) {
265 $queryInfo['tables'][] = 'ip_changes';
267 * These aliases make `ORDER BY rev_timestamp, rev_id` from {@see getIndexField} and
268 * {@see getExtraSortFields} use the replicated `ipc_rev_timestamp` and `ipc_rev_id`
269 * columns from the `ip_changes` table, for more efficient queries.
270 * @see https://phabricator.wikimedia.org/T200259#4832318
272 $queryInfo['fields'] = array_merge(
274 'rev_timestamp' => 'ipc_rev_timestamp',
275 'rev_id' => 'ipc_rev_id',
277 array_diff( $queryInfo['fields'], [
282 $queryInfo['join_conds']['ip_changes'] = [
283 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
285 $queryInfo['conds'][] = $ipRangeConds;
287 // tables and joins are already handled by Revision::getQueryInfo()
288 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
289 $queryInfo['conds'][] = $conds['conds'];
290 // Force the appropriate index to avoid bad query plans (T189026)
291 if ( isset( $conds['orconds']['actor'] ) ) {
292 // @todo: This will need changing when revision_comment_temp goes away
293 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
294 // Alias 'rev_timestamp' => 'revactor_timestamp' so "ORDER BY rev_timestamp" is interpreted to
295 // use revactor_timestamp instead.
296 $queryInfo['fields'] = array_merge(
297 array_diff( $queryInfo['fields'], [ 'rev_timestamp' ] ),
298 [ 'rev_timestamp' => 'revactor_timestamp' ]
301 $queryInfo['options']['USE INDEX']['revision'] =
302 isset( $conds['orconds']['userid'] ) ?
'user_timestamp' : 'usertext_timestamp';
307 if ( $this->deletedOnly
) {
308 $queryInfo['conds'][] = 'rev_deleted != 0';
311 if ( $this->topOnly
) {
312 $queryInfo['conds'][] = 'rev_id = page_latest';
315 if ( $this->newOnly
) {
316 $queryInfo['conds'][] = 'rev_parent_id = 0';
319 if ( $this->hideMinor
) {
320 $queryInfo['conds'][] = 'rev_minor_edit = 0';
323 $user = $this->getUser();
324 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
326 // Paranoia: avoid brute force searches (T19342)
327 if ( !$user->isAllowed( 'deletedhistory' ) ) {
328 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
329 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
330 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
331 ' != ' . Revision
::SUPPRESSED_USER
;
334 // For IPv6, we use ipc_rev_timestamp on ip_changes as the index field,
335 // which will be referenced when parsing the results of a query.
336 if ( self
::isQueryableRange( $this->target
) ) {
337 $queryInfo['fields'][] = 'ipc_rev_timestamp';
340 ChangeTags
::modifyDisplayQuery(
341 $queryInfo['tables'],
342 $queryInfo['fields'],
344 $queryInfo['join_conds'],
345 $queryInfo['options'],
349 // Avoid PHP 7.1 warning from passing $this by reference
351 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
356 function getNamespaceCond() {
357 if ( $this->namespace !== '' ) {
358 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
359 $eq_op = $this->nsInvert ?
'!=' : '=';
360 $bool_op = $this->nsInvert ?
'AND' : 'OR';
362 if ( !$this->associated
) {
363 return [ "page_namespace $eq_op $selectedNS" ];
366 $associatedNS = $this->mDb
->addQuotes(
367 MWNamespace
::getAssociated( $this->namespace )
371 "page_namespace $eq_op $selectedNS " .
373 " page_namespace $eq_op $associatedNS"
381 * Get SQL conditions for an IP range, if applicable
382 * @param IDatabase $db
383 * @param string $ip The IP address or CIDR
384 * @return string|false SQL for valid IP ranges, false if invalid
386 private function getIpRangeConds( $db, $ip ) {
387 // First make sure it is a valid range and they are not outside the CIDR limit
388 if ( !$this->isQueryableRange( $ip ) ) {
392 list( $start, $end ) = IP
::parseRange( $ip );
394 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
398 * Is the given IP a range and within the CIDR limit?
400 * @param string $ipRange
401 * @return bool True if it is valid
404 public function isQueryableRange( $ipRange ) {
405 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
407 $bits = IP
::parseCIDR( $ipRange )[1];
409 ( $bits === false ) ||
410 ( IP
::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
411 ( IP
::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
422 public function getIndexField() {
423 // Note this is run via parent::__construct() *before* $this->target is set!
424 return 'rev_timestamp';
430 protected function getExtraSortFields() {
431 // Note this is run via parent::__construct() *before* $this->target is set!
435 function doBatchLookups() {
436 # Do a link batch query
437 $this->mResult
->seek( 0 );
439 $this->mParentLens
= [];
440 $batch = new LinkBatch();
441 $isIpRange = $this->isQueryableRange( $this->target
);
442 # Give some pointers to make (last) links
443 foreach ( $this->mResult
as $row ) {
444 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
445 $parentRevIds[] = $row->rev_parent_id
;
447 if ( isset( $row->rev_id
) ) {
448 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
449 if ( $this->contribs
=== 'newbie' ) { // multiple users
450 $batch->add( NS_USER
, $row->user_name
);
451 $batch->add( NS_USER_TALK
, $row->user_name
);
452 } elseif ( $isIpRange ) {
453 // If this is an IP range, batch the IP's talk page
454 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
456 $batch->add( $row->page_namespace
, $row->page_title
);
459 # Fetch rev_len for revisions not already scanned above
460 $this->mParentLens +
= Revision
::getParentLengths(
462 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
465 $this->mResult
->seek( 0 );
471 function getStartBody() {
472 return "<ul class=\"mw-contributions-list\">\n";
478 function getEndBody() {
483 * Check whether the revision associated is valid for formatting. If has no associated revision
484 * id then null is returned.
487 * @param Title|null $title
488 * @return Revision|null
490 public function tryToCreateValidRevision( $row, $title = null ) {
492 * There may be more than just revision rows. To make sure that we'll only be processing
493 * revisions here, let's _try_ to build a revision out of our row (without displaying
494 * notices though) and then trying to grab data from the built object. If we succeed,
495 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
496 * to extensions to subscribe to the hook to parse the row.
498 Wikimedia\
suppressWarnings();
500 $rev = new Revision( $row, 0, $title );
501 $validRevision = (bool)$rev->getId();
502 } catch ( Exception
$e ) {
503 $validRevision = false;
505 Wikimedia\restoreWarnings
();
506 return $validRevision ?
$rev : null;
510 * Generates each row in the contributions list.
512 * Contributions which are marked "top" are currently on top of the history.
513 * For these contributions, a [rollback] link is shown for users with roll-
514 * back privileges. The rollback link restores the most recent version that
515 * was not written by the target user.
517 * @todo This would probably look a lot nicer in a table.
521 function formatRow( $row ) {
526 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
529 // Create a title for the revision if possible
530 // Rows from the hook may not include title information
531 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
532 $page = Title
::newFromRow( $row );
534 $rev = $this->tryToCreateValidRevision( $row, $page );
536 $attribs['data-mw-revid'] = $rev->getId();
538 $link = $linkRenderer->makeLink(
540 $page->getPrefixedText(),
541 [ 'class' => 'mw-contributions-title' ],
542 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
544 # Mark current revisions
546 $user = $this->getUser();
548 if ( $row->rev_id
=== $row->page_latest
) {
549 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
550 $classes[] = 'mw-contributions-current';
552 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
553 && $page->quickUserCan( 'edit', $user )
555 $this->preventClickjacking();
556 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
559 # Is there a visible previous revision?
560 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
561 $difftext = $linkRenderer->makeKnownLink(
563 new HtmlArmor( $this->messages
['diff'] ),
564 [ 'class' => 'mw-changeslist-diff' ],
567 'oldid' => $row->rev_id
571 $difftext = $this->messages
['diff'];
573 $histlink = $linkRenderer->makeKnownLink(
575 new HtmlArmor( $this->messages
['hist'] ),
576 [ 'class' => 'mw-changeslist-history' ],
577 [ 'action' => 'history' ]
580 if ( $row->rev_parent_id
=== null ) {
581 // For some reason rev_parent_id isn't populated for this row.
582 // Its rumoured this is true on wikipedia for some revisions (T36922).
583 // Next best thing is to have the total number of bytes.
584 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
585 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
586 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
589 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
590 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
593 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
594 $chardiff .= ChangesList
::showCharacterDifference(
599 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
602 $lang = $this->getLanguage();
603 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
604 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
605 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
606 $d = $linkRenderer->makeKnownLink(
609 [ 'class' => 'mw-changeslist-date' ],
610 [ 'oldid' => intval( $row->rev_id
) ]
613 $d = htmlspecialchars( $date );
615 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
616 $d = '<span class="history-deleted">' . $d . '</span>';
619 # Show user names for /newbies as there may be different users.
620 # Note that only unprivileged users have rows with hidden user names excluded.
621 # When querying for an IP range, we want to always show user and user talk links.
623 if ( ( $this->contribs
== 'newbie' && !$rev->isDeleted( Revision
::DELETED_USER
) )
624 ||
$this->isQueryableRange( $this->target
) ) {
625 $userlink = ' <span class="mw-changeslist-separator"></span> '
626 . $lang->getDirMark()
627 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
628 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
629 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
633 if ( $rev->getParentId() === 0 ) {
634 $flags[] = ChangesList
::flag( 'newpage' );
637 if ( $rev->isMinor() ) {
638 $flags[] = ChangesList
::flag( 'minor' );
641 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
646 // While it might be tempting to use a list here
647 // this would result in clutter and slows down navigating the content
648 // in assistive technology.
649 // See https://phabricator.wikimedia.org/T205581#4734812
650 $diffHistLinks = Html
::rawElement( 'span',
651 [ 'class' => 'mw-changeslist-links' ],
652 // The spans are needed to ensure the dividing '|' elements are not
653 // themselves styled as links.
654 Html
::rawElement( 'span', [], $difftext ) .
655 ' ' . // Space needed for separating two words.
656 Html
::rawElement( 'span', [], $histlink )
660 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
665 $classes = array_merge( $classes, $newClasses );
667 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
672 'diffHistLinks' => $diffHistLinks,
673 'charDifference' => $chardiff,
675 'articleLink' => $link,
676 'userlink' => $userlink,
677 'logText' => $comment,
678 'topmarktext' => $topmarktext,
679 'tagSummary' => $tagSummary,
682 # Denote if username is redacted for this edit
683 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
684 $templateParams['rev-deleted-user-contribs'] =
685 $this->msg( 'rev-deleted-user-contribs' )->escaped();
688 $ret = $this->templateParser
->processTemplate(
689 'SpecialContributionsLine',
694 // Let extensions add data
695 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
696 $attribs = array_filter( $attribs,
697 [ Sanitizer
::class, 'isReservedDataAttribute' ],
701 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
702 // receiving empty rows?
704 if ( $classes === [] && $attribs === [] && $ret === '' ) {
705 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
706 return "<!-- Could not format Special:Contribution row. -->\n";
708 $attribs['class'] = $classes;
710 // FIXME: The signature of the ContributionsLineEnding hook makes it
711 // very awkward to move this LI wrapper into the template.
712 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
716 * Overwrite Pager function and return a helpful comment
719 function getSqlComment() {
720 if ( $this->namespace ||
$this->deletedOnly
) {
721 // potentially slow, see CR r58153
722 return 'contributions page filtered for namespace or RevisionDeleted edits';
724 return 'contributions page unfiltered';
728 protected function preventClickjacking() {
729 $this->preventClickjacking
= true;
735 public function getPreventClickjacking() {
736 return $this->preventClickjacking
;
740 * Set up date filter options, given request data.
742 * @param array $opts Options array
743 * @return array Options array with processed start and end date filter options
745 public static function processDateFilter( array $opts ) {
746 $start = $opts['start'] ??
'';
747 $end = $opts['end'] ??
'';
748 $year = $opts['year'] ??
'';
749 $month = $opts['month'] ??
'';
751 if ( $start !== '' && $end !== '' && $start > $end ) {
757 // If year/month legacy filtering options are set, convert them to display the new stamp
758 if ( $year !== '' ||
$month !== '' ) {
759 // Reuse getDateCond logic, but subtract a day because
760 // the endpoints of our date range appear inclusive
761 // but the internal end offsets are always exclusive
762 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
763 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
764 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
766 // Clear the new timestamp range options if used and
767 // replace with the converted legacy timestamp
769 $end = $legacyDateTime->format( 'Y-m-d' );
772 $opts['start'] = $start;