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\ResultWrapper
;
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
= isset( $options['target'] ) ?
$options['target'] : '';
68 $this->contribs
= isset( $options['contribs'] ) ?
$options['contribs'] : 'users';
69 $this->namespace = isset( $options['namespace'] ) ?
$options['namespace'] : '';
70 $this->tagFilter
= isset( $options['tagfilter'] ) ?
$options['tagfilter'] : false;
71 $this->nsInvert
= isset( $options['nsInvert'] ) ?
$options['nsInvert'] : false;
72 $this->associated
= isset( $options['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 ResultWrapper
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 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
176 $user = $this->getUser();
177 $conds = array_merge( $userCond, $this->getNamespaceCond() );
179 // Paranoia: avoid brute force searches (T19342)
180 if ( !$user->isAllowed( 'deletedhistory' ) ) {
181 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
182 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
183 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
184 ' != ' . Revision
::SUPPRESSED_USER
;
187 # Don't include orphaned revisions
188 $join_cond['page'] = Revision
::pageJoinCond();
189 # Get the current user name for accounts
190 $join_cond['user'] = Revision
::userJoinCond();
194 $options['USE INDEX'] = [ 'revision' => $index ];
199 'fields' => array_merge(
200 Revision
::selectFields(),
201 Revision
::selectUserFields(),
202 [ 'page_namespace', 'page_title', 'page_is_new',
203 'page_latest', 'page_is_redirect', 'page_len' ]
206 'options' => $options,
207 'join_conds' => $join_cond
210 ChangeTags
::modifyDisplayQuery(
211 $queryInfo['tables'],
212 $queryInfo['fields'],
214 $queryInfo['join_conds'],
215 $queryInfo['options'],
219 // Avoid PHP 7.1 warning from passing $this by reference
221 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
226 function getUserCond() {
229 $tables = [ 'revision', 'page', 'user' ];
231 if ( $this->contribs
== 'newbie' ) {
232 $max = $this->mDb
->selectField( 'user', 'max(user_id)', false, __METHOD__
);
233 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
234 # ignore local groups with the bot right
235 # @todo FIXME: Global groups may have 'bot' rights
236 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
237 if ( count( $groupsWithBotPermission ) ) {
238 $tables[] = 'user_groups';
239 $condition[] = 'ug_group IS NULL';
240 $join_conds['user_groups'] = [
242 'ug_user = rev_user',
243 'ug_group' => $groupsWithBotPermission,
244 'ug_expiry IS NULL OR ug_expiry >= ' .
245 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
249 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
250 // a timestamp offset far in the past such that there are no edits by users with user_ids in
251 // the range, we would end up scanning all revisions from that offset until start of time.
252 $condition[] = 'rev_timestamp > ' .
253 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
255 $uid = User
::idFromName( $this->target
);
257 $condition['rev_user'] = $uid;
258 $index = 'user_timestamp';
260 $condition['rev_user_text'] = $this->target
;
261 $index = 'usertext_timestamp';
265 if ( $this->deletedOnly
) {
266 $condition[] = 'rev_deleted != 0';
269 if ( $this->topOnly
) {
270 $condition[] = 'rev_id = page_latest';
273 if ( $this->newOnly
) {
274 $condition[] = 'rev_parent_id = 0';
277 if ( $this->hideMinor
) {
278 $condition[] = 'rev_minor_edit = 0';
281 return [ $tables, $index, $condition, $join_conds ];
284 function getNamespaceCond() {
285 if ( $this->namespace !== '' ) {
286 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
287 $eq_op = $this->nsInvert ?
'!=' : '=';
288 $bool_op = $this->nsInvert ?
'AND' : 'OR';
290 if ( !$this->associated
) {
291 return [ "page_namespace $eq_op $selectedNS" ];
294 $associatedNS = $this->mDb
->addQuotes(
295 MWNamespace
::getAssociated( $this->namespace )
299 "page_namespace $eq_op $selectedNS " .
301 " page_namespace $eq_op $associatedNS"
308 function getIndexField() {
309 return 'rev_timestamp';
312 function doBatchLookups() {
313 # Do a link batch query
314 $this->mResult
->seek( 0 );
316 $this->mParentLens
= [];
317 $batch = new LinkBatch();
318 # Give some pointers to make (last) links
319 foreach ( $this->mResult
as $row ) {
320 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
321 $parentRevIds[] = $row->rev_parent_id
;
323 if ( isset( $row->rev_id
) ) {
324 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
325 if ( $this->contribs
=== 'newbie' ) { // multiple users
326 $batch->add( NS_USER
, $row->user_name
);
327 $batch->add( NS_USER_TALK
, $row->user_name
);
329 $batch->add( $row->page_namespace
, $row->page_title
);
332 # Fetch rev_len for revisions not already scanned above
333 $this->mParentLens +
= Revision
::getParentLengths(
335 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
338 $this->mResult
->seek( 0 );
344 function getStartBody() {
345 return "<ul class=\"mw-contributions-list\">\n";
351 function getEndBody() {
356 * Generates each row in the contributions list.
358 * Contributions which are marked "top" are currently on top of the history.
359 * For these contributions, a [rollback] link is shown for users with roll-
360 * back privileges. The rollback link restores the most recent version that
361 * was not written by the target user.
363 * @todo This would probably look a lot nicer in a table.
367 function formatRow( $row ) {
372 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
375 * There may be more than just revision rows. To make sure that we'll only be processing
376 * revisions here, let's _try_ to build a revision out of our row (without displaying
377 * notices though) and then trying to grab data from the built object. If we succeed,
378 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
379 * to extensions to subscribe to the hook to parse the row.
381 MediaWiki\
suppressWarnings();
383 $rev = new Revision( $row );
384 $validRevision = (bool)$rev->getId();
385 } catch ( Exception
$e ) {
386 $validRevision = false;
388 MediaWiki\restoreWarnings
();
390 if ( $validRevision ) {
391 $attribs['data-mw-revid'] = $rev->getId();
393 $page = Title
::newFromRow( $row );
394 $link = $linkRenderer->makeLink(
396 $page->getPrefixedText(),
397 [ 'class' => 'mw-contributions-title' ],
398 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
400 # Mark current revisions
402 $user = $this->getUser();
403 if ( $row->rev_id
=== $row->page_latest
) {
404 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
405 $classes[] = 'mw-contributions-current';
407 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
408 && $page->quickUserCan( 'edit', $user )
410 $this->preventClickjacking();
411 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
414 # Is there a visible previous revision?
415 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
416 $difftext = $linkRenderer->makeKnownLink(
418 new HtmlArmor( $this->messages
['diff'] ),
419 [ 'class' => 'mw-changeslist-diff' ],
422 'oldid' => $row->rev_id
426 $difftext = $this->messages
['diff'];
428 $histlink = $linkRenderer->makeKnownLink(
430 new HtmlArmor( $this->messages
['hist'] ),
431 [ 'class' => 'mw-changeslist-history' ],
432 [ 'action' => 'history' ]
435 if ( $row->rev_parent_id
=== null ) {
436 // For some reason rev_parent_id isn't populated for this row.
437 // Its rumoured this is true on wikipedia for some revisions (T36922).
438 // Next best thing is to have the total number of bytes.
439 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
440 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
441 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
444 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
445 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
448 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
449 $chardiff .= ChangesList
::showCharacterDifference(
454 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
457 $lang = $this->getLanguage();
458 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true );
459 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
460 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
461 $d = $linkRenderer->makeKnownLink(
464 [ 'class' => 'mw-changeslist-date' ],
465 [ 'oldid' => intval( $row->rev_id
) ]
468 $d = htmlspecialchars( $date );
470 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
471 $d = '<span class="history-deleted">' . $d . '</span>';
474 # Show user names for /newbies as there may be different users.
475 # Note that only unprivileged users have rows with hidden user names excluded.
477 if ( $this->contribs
== 'newbie' && !$rev->isDeleted( Revision
::DELETED_USER
) ) {
478 $userlink = ' . . ' . $lang->getDirMark()
479 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
480 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
481 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
485 if ( $rev->getParentId() === 0 ) {
486 $flags[] = ChangesList
::flag( 'newpage' );
489 if ( $rev->isMinor() ) {
490 $flags[] = ChangesList
::flag( 'minor' );
493 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
498 $diffHistLinks = $this->msg( 'parentheses' )
499 ->rawParams( $difftext . $this->messages
['pipe-separator'] . $histlink )
503 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
508 $classes = array_merge( $classes, $newClasses );
510 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
515 'diffHistLinks' => $diffHistLinks,
516 'charDifference' => $chardiff,
518 'articleLink' => $link,
519 'userlink' => $userlink,
520 'logText' => $comment,
521 'topmarktext' => $topmarktext,
522 'tagSummary' => $tagSummary,
525 # Denote if username is redacted for this edit
526 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
527 $templateParams['rev-deleted-user-contribs'] =
528 $this->msg( 'rev-deleted-user-contribs' )->escaped();
531 $ret = $this->templateParser
->processTemplate(
532 'SpecialContributionsLine',
537 // Let extensions add data
538 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
539 $attribs = wfArrayFilterByKey( $attribs, [ Sanitizer
::class, 'isReservedDataAttribute' ] );
541 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
542 // receiving empty rows?
544 if ( $classes === [] && $attribs === [] && $ret === '' ) {
545 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
546 return "<!-- Could not format Special:Contribution row. -->\n";
548 $attribs['class'] = $classes;
550 // FIXME: The signature of the ContributionsLineEnding hook makes it
551 // very awkward to move this LI wrapper into the template.
552 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
556 * Overwrite Pager function and return a helpful comment
559 function getSqlComment() {
560 if ( $this->namespace ||
$this->deletedOnly
) {
561 // potentially slow, see CR r58153
562 return 'contributions page filtered for namespace or RevisionDeleted edits';
564 return 'contributions page unfiltered';
568 protected function preventClickjacking() {
569 $this->preventClickjacking
= true;
575 public function getPreventClickjacking() {
576 return $this->preventClickjacking
;
580 * Set up date filter options, given request data.
582 * @param array $opts Options array
583 * @return array Options array with processed start and end date filter options
585 public static function processDateFilter( $opts ) {
586 $start = isset( $opts['start'] ) ?
$opts['start'] : '';
587 $end = isset( $opts['end'] ) ?
$opts['end'] : '';
588 $year = isset( $opts['year'] ) ?
$opts['year'] : '';
589 $month = isset( $opts['month'] ) ?
$opts['month'] : '';
591 if ( $start !== '' && $end !== '' && $start > $end ) {
597 // If year/month legacy filtering options are set, convert them to display the new stamp
598 if ( $year !== '' ||
$month !== '' ) {
599 // Reuse getDateCond logic, but subtract a day because
600 // the endpoints of our date range appear inclusive
601 // but the internal end offsets are always exclusive
602 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
603 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
604 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
606 // Clear the new timestamp range options if used and
607 // replace with the converted legacy timestamp
609 $end = $legacyDateTime->format( 'Y-m-d' );
612 $opts['start'] = $start;