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 public $namespace = '';
38 public $preventClickjacking = false;
46 protected $mParentLens;
51 protected $templateParser;
53 function __construct( IContextSource
$context, array $options ) {
54 parent
::__construct( $context );
63 foreach ( $msgs as $msg ) {
64 $this->messages
[$msg] = $this->msg( $msg )->escaped();
67 $this->target
= $options['target'] ??
'';
68 $this->contribs
= $options['contribs'] ??
'users';
69 $this->namespace = $options['namespace'] ??
'';
70 $this->tagFilter
= $options['tagfilter'] ??
false;
71 $this->nsInvert
= $options['nsInvert'] ??
false;
72 $this->associated
= $options['associated'] ??
false;
74 $this->deletedOnly
= !empty( $options['deletedOnly'] );
75 $this->topOnly
= !empty( $options['topOnly'] );
76 $this->newOnly
= !empty( $options['newOnly'] );
77 $this->hideMinor
= !empty( $options['hideMinor'] );
79 // Date filtering: use timestamp if available
82 if ( $options['start'] ) {
83 $startTimestamp = $options['start'] . ' 00:00:00';
85 if ( $options['end'] ) {
86 $endTimestamp = $options['end'] . ' 23:59:59';
88 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
90 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
91 // with extra user based indexes or partioning by user. The additional metadata
92 // queries should use a regular replica DB since the lookup pattern is not all by user.
93 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
94 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
95 $this->templateParser
= new TemplateParser();
98 function getDefaultQuery() {
99 $query = parent
::getDefaultQuery();
100 $query['target'] = $this->target
;
106 * This method basically executes the exact same code as the parent class, though with
107 * a hook added, to allow extensions to add additional queries.
109 * @param string $offset Index offset, inclusive
110 * @param int $limit Exact query limit
111 * @param bool $descending Query direction, false for ascending, true for descending
112 * @return IResultWrapper
114 function reallyDoQuery( $offset, $limit, $descending ) {
115 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
122 * This hook will allow extensions to add in additional queries, so they can get their data
123 * in My Contributions as well. Extensions should append their results to the $data array.
125 * Extension queries have to implement the navbar requirement as well. They should
126 * - have a column aliased as $pager->getIndexField()
128 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
129 * - have the ORDER BY specified based upon the details provided by the navbar
131 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
133 * &$data: an array of results of all contribs queries
134 * $pager: the ContribsPager object hooked into
135 * $offset: see phpdoc above
136 * $limit: see phpdoc above
137 * $descending: see phpdoc above
139 $data = [ $this->mDb
->select(
140 $tables, $fields, $conds, $fname, $options, $join_conds
143 'ContribsPager::reallyDoQuery',
144 [ &$data, $this, $offset, $limit, $descending ]
149 // loop all results and collect them in an array
150 foreach ( $data as $query ) {
151 foreach ( $query as $i => $row ) {
152 // use index column as key, allowing us to easily sort in PHP
153 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
165 $result = array_slice( $result, 0, $limit );
167 // get rid of array keys
168 $result = array_values( $result );
170 return new FakeResultWrapper( $result );
173 function getQueryInfo() {
174 $revQuery = Revision
::getQueryInfo( [ 'page', 'user' ] );
176 'tables' => $revQuery['tables'],
177 'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
180 'join_conds' => $revQuery['joins'],
183 if ( $this->contribs
== 'newbie' ) {
184 $max = $this->mDb
->selectField( 'user', 'max(user_id)', '', __METHOD__
);
185 $queryInfo['conds'][] = $revQuery['fields']['rev_user'] . ' >' . (int)( $max - $max / 100 );
186 # ignore local groups with the bot right
187 # @todo FIXME: Global groups may have 'bot' rights
188 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
189 if ( count( $groupsWithBotPermission ) ) {
190 $queryInfo['tables'][] = 'user_groups';
191 $queryInfo['conds'][] = 'ug_group IS NULL';
192 $queryInfo['join_conds']['user_groups'] = [
194 'ug_user = ' . $revQuery['fields']['rev_user'],
195 'ug_group' => $groupsWithBotPermission,
196 'ug_expiry IS NULL OR ug_expiry >= ' .
197 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
201 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
202 // a timestamp offset far in the past such that there are no edits by users with user_ids in
203 // the range, we would end up scanning all revisions from that offset until start of time.
204 $queryInfo['conds'][] = 'rev_timestamp > ' .
205 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
207 $user = User
::newFromName( $this->target
, false );
208 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
209 if ( $ipRangeConds ) {
210 $queryInfo['tables'][] = 'ip_changes';
212 * These aliases make `ORDER BY rev_timestamp, rev_id` from {@see getIndexField} and
213 * {@see getExtraSortFields} use the replicated `ipc_rev_timestamp` and `ipc_rev_id`
214 * columns from the `ip_changes` table, for more efficient queries.
215 * @see https://phabricator.wikimedia.org/T200259#4832318
217 $queryInfo['fields'] = array_merge(
219 'rev_timestamp' => 'ipc_rev_timestamp',
220 'rev_id' => 'ipc_rev_id',
222 array_diff( $queryInfo['fields'], [
227 $queryInfo['join_conds']['ip_changes'] = [
228 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
230 $queryInfo['conds'][] = $ipRangeConds;
232 // tables and joins are already handled by Revision::getQueryInfo()
233 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
234 $queryInfo['conds'][] = $conds['conds'];
235 // Force the appropriate index to avoid bad query plans (T189026)
236 if ( isset( $conds['orconds']['actor'] ) ) {
237 // @todo: This will need changing when revision_comment_temp goes away
238 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
239 // Alias 'rev_timestamp' => 'revactor_timestamp' so "ORDER BY rev_timestamp" is interpreted to
240 // use revactor_timestamp instead.
241 $queryInfo['fields'] = array_merge(
242 array_diff( $queryInfo['fields'], [ 'rev_timestamp' ] ),
243 [ 'rev_timestamp' => 'revactor_timestamp' ]
246 $queryInfo['options']['USE INDEX']['revision'] =
247 isset( $conds['orconds']['userid'] ) ?
'user_timestamp' : 'usertext_timestamp';
252 if ( $this->deletedOnly
) {
253 $queryInfo['conds'][] = 'rev_deleted != 0';
256 if ( $this->topOnly
) {
257 $queryInfo['conds'][] = 'rev_id = page_latest';
260 if ( $this->newOnly
) {
261 $queryInfo['conds'][] = 'rev_parent_id = 0';
264 if ( $this->hideMinor
) {
265 $queryInfo['conds'][] = 'rev_minor_edit = 0';
268 $user = $this->getUser();
269 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
271 // Paranoia: avoid brute force searches (T19342)
272 if ( !$user->isAllowed( 'deletedhistory' ) ) {
273 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
274 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
275 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
276 ' != ' . Revision
::SUPPRESSED_USER
;
279 // For IPv6, we use ipc_rev_timestamp on ip_changes as the index field,
280 // which will be referenced when parsing the results of a query.
281 if ( self
::isQueryableRange( $this->target
) ) {
282 $queryInfo['fields'][] = 'ipc_rev_timestamp';
285 ChangeTags
::modifyDisplayQuery(
286 $queryInfo['tables'],
287 $queryInfo['fields'],
289 $queryInfo['join_conds'],
290 $queryInfo['options'],
294 // Avoid PHP 7.1 warning from passing $this by reference
296 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
301 function getNamespaceCond() {
302 if ( $this->namespace !== '' ) {
303 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
304 $eq_op = $this->nsInvert ?
'!=' : '=';
305 $bool_op = $this->nsInvert ?
'AND' : 'OR';
307 if ( !$this->associated
) {
308 return [ "page_namespace $eq_op $selectedNS" ];
311 $associatedNS = $this->mDb
->addQuotes(
312 MWNamespace
::getAssociated( $this->namespace )
316 "page_namespace $eq_op $selectedNS " .
318 " page_namespace $eq_op $associatedNS"
326 * Get SQL conditions for an IP range, if applicable
327 * @param IDatabase $db
328 * @param string $ip The IP address or CIDR
329 * @return string|false SQL for valid IP ranges, false if invalid
331 private function getIpRangeConds( $db, $ip ) {
332 // First make sure it is a valid range and they are not outside the CIDR limit
333 if ( !$this->isQueryableRange( $ip ) ) {
337 list( $start, $end ) = IP
::parseRange( $ip );
339 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
343 * Is the given IP a range and within the CIDR limit?
345 * @param string $ipRange
346 * @return bool True if it is valid
349 public function isQueryableRange( $ipRange ) {
350 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
352 $bits = IP
::parseCIDR( $ipRange )[1];
354 ( $bits === false ) ||
355 ( IP
::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
356 ( IP
::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
367 public function getIndexField() {
368 // Note this is run via parent::__construct() *before* $this->target is set!
369 return 'rev_timestamp';
375 protected function getExtraSortFields() {
376 // Note this is run via parent::__construct() *before* $this->target is set!
380 function doBatchLookups() {
381 # Do a link batch query
382 $this->mResult
->seek( 0 );
384 $this->mParentLens
= [];
385 $batch = new LinkBatch();
386 $isIpRange = $this->isQueryableRange( $this->target
);
387 # Give some pointers to make (last) links
388 foreach ( $this->mResult
as $row ) {
389 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
390 $parentRevIds[] = $row->rev_parent_id
;
392 if ( isset( $row->rev_id
) ) {
393 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
394 if ( $this->contribs
=== 'newbie' ) { // multiple users
395 $batch->add( NS_USER
, $row->user_name
);
396 $batch->add( NS_USER_TALK
, $row->user_name
);
397 } elseif ( $isIpRange ) {
398 // If this is an IP range, batch the IP's talk page
399 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
401 $batch->add( $row->page_namespace
, $row->page_title
);
404 # Fetch rev_len for revisions not already scanned above
405 $this->mParentLens +
= Revision
::getParentLengths(
407 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
410 $this->mResult
->seek( 0 );
416 function getStartBody() {
417 return "<ul class=\"mw-contributions-list\">\n";
423 function getEndBody() {
428 * Check whether the revision associated is valid for formatting. If has no associated revision
429 * id then null is returned.
432 * @return Revision|null
434 public function tryToCreateValidRevision( $row ) {
436 * There may be more than just revision rows. To make sure that we'll only be processing
437 * revisions here, let's _try_ to build a revision out of our row (without displaying
438 * notices though) and then trying to grab data from the built object. If we succeed,
439 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
440 * to extensions to subscribe to the hook to parse the row.
442 Wikimedia\
suppressWarnings();
444 $rev = new Revision( $row );
445 $validRevision = (bool)$rev->getId();
446 } catch ( Exception
$e ) {
447 $validRevision = false;
449 Wikimedia\restoreWarnings
();
450 return $validRevision ?
$rev : null;
454 * Generates each row in the contributions list.
456 * Contributions which are marked "top" are currently on top of the history.
457 * For these contributions, a [rollback] link is shown for users with roll-
458 * back privileges. The rollback link restores the most recent version that
459 * was not written by the target user.
461 * @todo This would probably look a lot nicer in a table.
465 function formatRow( $row ) {
470 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
472 $rev = $this->tryToCreateValidRevision( $row );
474 $attribs['data-mw-revid'] = $rev->getId();
476 $page = Title
::newFromRow( $row );
477 $link = $linkRenderer->makeLink(
479 $page->getPrefixedText(),
480 [ 'class' => 'mw-contributions-title' ],
481 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
483 # Mark current revisions
485 $user = $this->getUser();
487 if ( $row->rev_id
=== $row->page_latest
) {
488 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
489 $classes[] = 'mw-contributions-current';
491 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
492 && $page->quickUserCan( 'edit', $user )
494 $this->preventClickjacking();
495 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
498 # Is there a visible previous revision?
499 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
500 $difftext = $linkRenderer->makeKnownLink(
502 new HtmlArmor( $this->messages
['diff'] ),
503 [ 'class' => 'mw-changeslist-diff' ],
506 'oldid' => $row->rev_id
510 $difftext = $this->messages
['diff'];
512 $histlink = $linkRenderer->makeKnownLink(
514 new HtmlArmor( $this->messages
['hist'] ),
515 [ 'class' => 'mw-changeslist-history' ],
516 [ 'action' => 'history' ]
519 if ( $row->rev_parent_id
=== null ) {
520 // For some reason rev_parent_id isn't populated for this row.
521 // Its rumoured this is true on wikipedia for some revisions (T36922).
522 // Next best thing is to have the total number of bytes.
523 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
524 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
525 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
528 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
529 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
532 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
533 $chardiff .= ChangesList
::showCharacterDifference(
538 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
541 $lang = $this->getLanguage();
542 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true );
543 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
544 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
545 $d = $linkRenderer->makeKnownLink(
548 [ 'class' => 'mw-changeslist-date' ],
549 [ 'oldid' => intval( $row->rev_id
) ]
552 $d = htmlspecialchars( $date );
554 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
555 $d = '<span class="history-deleted">' . $d . '</span>';
558 # Show user names for /newbies as there may be different users.
559 # Note that only unprivileged users have rows with hidden user names excluded.
560 # When querying for an IP range, we want to always show user and user talk links.
562 if ( ( $this->contribs
== 'newbie' && !$rev->isDeleted( Revision
::DELETED_USER
) )
563 ||
$this->isQueryableRange( $this->target
) ) {
564 $userlink = ' <span class="mw-changeslist-separator"></span> '
565 . $lang->getDirMark()
566 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
567 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
568 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
572 if ( $rev->getParentId() === 0 ) {
573 $flags[] = ChangesList
::flag( 'newpage' );
576 if ( $rev->isMinor() ) {
577 $flags[] = ChangesList
::flag( 'minor' );
580 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
585 $diffHistLinks = Html
::rawElement( 'ul',
586 [ 'class' => 'mw-changeslist-link-list' ],
587 Html
::rawElement( 'li', [], $difftext ) .
588 Html
::rawElement( 'li', [], $histlink )
592 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
597 $classes = array_merge( $classes, $newClasses );
599 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
604 'diffHistLinks' => $diffHistLinks,
605 'charDifference' => $chardiff,
607 'articleLink' => $link,
608 'userlink' => $userlink,
609 'logText' => $comment,
610 'topmarktext' => $topmarktext,
611 'tagSummary' => $tagSummary,
614 # Denote if username is redacted for this edit
615 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
616 $templateParams['rev-deleted-user-contribs'] =
617 $this->msg( 'rev-deleted-user-contribs' )->escaped();
620 $ret = $this->templateParser
->processTemplate(
621 'SpecialContributionsLine',
626 // Let extensions add data
627 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
628 $attribs = array_filter( $attribs,
629 [ Sanitizer
::class, 'isReservedDataAttribute' ],
633 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
634 // receiving empty rows?
636 if ( $classes === [] && $attribs === [] && $ret === '' ) {
637 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
638 return "<!-- Could not format Special:Contribution row. -->\n";
640 $attribs['class'] = $classes;
642 // FIXME: The signature of the ContributionsLineEnding hook makes it
643 // very awkward to move this LI wrapper into the template.
644 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
648 * Overwrite Pager function and return a helpful comment
651 function getSqlComment() {
652 if ( $this->namespace ||
$this->deletedOnly
) {
653 // potentially slow, see CR r58153
654 return 'contributions page filtered for namespace or RevisionDeleted edits';
656 return 'contributions page unfiltered';
660 protected function preventClickjacking() {
661 $this->preventClickjacking
= true;
667 public function getPreventClickjacking() {
668 return $this->preventClickjacking
;
672 * Set up date filter options, given request data.
674 * @param array $opts Options array
675 * @return array Options array with processed start and end date filter options
677 public static function processDateFilter( array $opts ) {
678 $start = $opts['start'] ??
'';
679 $end = $opts['end'] ??
'';
680 $year = $opts['year'] ??
'';
681 $month = $opts['month'] ??
'';
683 if ( $start !== '' && $end !== '' && $start > $end ) {
689 // If year/month legacy filtering options are set, convert them to display the new stamp
690 if ( $year !== '' ||
$month !== '' ) {
691 // Reuse getDateCond logic, but subtract a day because
692 // the endpoints of our date range appear inclusive
693 // but the internal end offsets are always exclusive
694 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
695 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
696 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
698 // Clear the new timestamp range options if used and
699 // replace with the converted legacy timestamp
701 $end = $legacyDateTime->format( 'Y-m-d' );
704 $opts['start'] = $start;