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
;
30 class ContribsPager
extends ReverseChronologicalPager
{
32 public $mDefaultDirection = IndexPager
::DIR_DESCENDING
;
35 public $namespace = '';
37 public $preventClickjacking = false;
45 protected $mParentLens;
47 function __construct( IContextSource
$context, array $options ) {
48 parent
::__construct( $context );
57 foreach ( $msgs as $msg ) {
58 $this->messages
[$msg] = $this->msg( $msg )->escaped();
61 $this->target
= isset( $options['target'] ) ?
$options['target'] : '';
62 $this->contribs
= isset( $options['contribs'] ) ?
$options['contribs'] : 'users';
63 $this->namespace = isset( $options['namespace'] ) ?
$options['namespace'] : '';
64 $this->tagFilter
= isset( $options['tagfilter'] ) ?
$options['tagfilter'] : false;
65 $this->nsInvert
= isset( $options['nsInvert'] ) ?
$options['nsInvert'] : false;
66 $this->associated
= isset( $options['associated'] ) ?
$options['associated'] : false;
68 $this->deletedOnly
= !empty( $options['deletedOnly'] );
69 $this->topOnly
= !empty( $options['topOnly'] );
70 $this->newOnly
= !empty( $options['newOnly'] );
71 $this->hideMinor
= !empty( $options['hideMinor'] );
73 $year = isset( $options['year'] ) ?
$options['year'] : false;
74 $month = isset( $options['month'] ) ?
$options['month'] : false;
75 $this->getDateCond( $year, $month );
77 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
78 // with extra user based indexes or partioning by user. The additional metadata
79 // queries should use a regular replica DB since the lookup pattern is not all by user.
80 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
81 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
84 function getDefaultQuery() {
85 $query = parent
::getDefaultQuery();
86 $query['target'] = $this->target
;
92 * This method basically executes the exact same code as the parent class, though with
93 * a hook added, to allow extensions to add additional queries.
95 * @param string $offset Index offset, inclusive
96 * @param int $limit Exact query limit
97 * @param bool $descending Query direction, false for ascending, true for descending
98 * @return ResultWrapper
100 function reallyDoQuery( $offset, $limit, $descending ) {
101 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
108 * This hook will allow extensions to add in additional queries, so they can get their data
109 * in My Contributions as well. Extensions should append their results to the $data array.
111 * Extension queries have to implement the navbar requirement as well. They should
112 * - have a column aliased as $pager->getIndexField()
114 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
115 * - have the ORDER BY specified based upon the details provided by the navbar
117 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
119 * &$data: an array of results of all contribs queries
120 * $pager: the ContribsPager object hooked into
121 * $offset: see phpdoc above
122 * $limit: see phpdoc above
123 * $descending: see phpdoc above
125 $data = [ $this->mDb
->select(
126 $tables, $fields, $conds, $fname, $options, $join_conds
129 'ContribsPager::reallyDoQuery',
130 [ &$data, $this, $offset, $limit, $descending ]
135 // loop all results and collect them in an array
136 foreach ( $data as $query ) {
137 foreach ( $query as $i => $row ) {
138 // use index column as key, allowing us to easily sort in PHP
139 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
151 $result = array_slice( $result, 0, $limit );
153 // get rid of array keys
154 $result = array_values( $result );
156 return new FakeResultWrapper( $result );
159 function getQueryInfo() {
160 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
162 $user = $this->getUser();
163 $conds = array_merge( $userCond, $this->getNamespaceCond() );
165 // Paranoia: avoid brute force searches (T19342)
166 if ( !$user->isAllowed( 'deletedhistory' ) ) {
167 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
168 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
169 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
170 ' != ' . Revision
::SUPPRESSED_USER
;
173 # Don't include orphaned revisions
174 $join_cond['page'] = Revision
::pageJoinCond();
175 # Get the current user name for accounts
176 $join_cond['user'] = Revision
::userJoinCond();
180 $options['USE INDEX'] = [ 'revision' => $index ];
185 'fields' => array_merge(
186 Revision
::selectFields(),
187 Revision
::selectUserFields(),
188 [ 'page_namespace', 'page_title', 'page_is_new',
189 'page_latest', 'page_is_redirect', 'page_len' ]
192 'options' => $options,
193 'join_conds' => $join_cond
196 ChangeTags
::modifyDisplayQuery(
197 $queryInfo['tables'],
198 $queryInfo['fields'],
200 $queryInfo['join_conds'],
201 $queryInfo['options'],
205 // Avoid PHP 7.1 warning from passing $this by reference
207 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
212 function getUserCond() {
215 $tables = [ 'revision', 'page', 'user' ];
217 if ( $this->contribs
== 'newbie' ) {
218 $max = $this->mDb
->selectField( 'user', 'max(user_id)', false, __METHOD__
);
219 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
220 # ignore local groups with the bot right
221 # @todo FIXME: Global groups may have 'bot' rights
222 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
223 if ( count( $groupsWithBotPermission ) ) {
224 $tables[] = 'user_groups';
225 $condition[] = 'ug_group IS NULL';
226 $join_conds['user_groups'] = [
228 'ug_user = rev_user',
229 'ug_group' => $groupsWithBotPermission,
230 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
232 'ug_expiry IS NULL OR ug_expiry >= ' .
233 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
237 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
238 // a timestamp offset far in the past such that there are no edits by users with user_ids in
239 // the range, we would end up scanning all revisions from that offset until start of time.
240 $condition[] = 'rev_timestamp > ' .
241 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
243 $uid = User
::idFromName( $this->target
);
245 $condition['rev_user'] = $uid;
246 $index = 'user_timestamp';
248 $condition['rev_user_text'] = $this->target
;
249 $index = 'usertext_timestamp';
253 if ( $this->deletedOnly
) {
254 $condition[] = 'rev_deleted != 0';
257 if ( $this->topOnly
) {
258 $condition[] = 'rev_id = page_latest';
261 if ( $this->newOnly
) {
262 $condition[] = 'rev_parent_id = 0';
265 if ( $this->hideMinor
) {
266 $condition[] = 'rev_minor_edit = 0';
269 return [ $tables, $index, $condition, $join_conds ];
272 function getNamespaceCond() {
273 if ( $this->namespace !== '' ) {
274 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
275 $eq_op = $this->nsInvert ?
'!=' : '=';
276 $bool_op = $this->nsInvert ?
'AND' : 'OR';
278 if ( !$this->associated
) {
279 return [ "page_namespace $eq_op $selectedNS" ];
282 $associatedNS = $this->mDb
->addQuotes(
283 MWNamespace
::getAssociated( $this->namespace )
287 "page_namespace $eq_op $selectedNS " .
289 " page_namespace $eq_op $associatedNS"
296 function getIndexField() {
297 return 'rev_timestamp';
300 function doBatchLookups() {
301 # Do a link batch query
302 $this->mResult
->seek( 0 );
304 $this->mParentLens
= [];
305 $batch = new LinkBatch();
306 # Give some pointers to make (last) links
307 foreach ( $this->mResult
as $row ) {
308 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
309 $parentRevIds[] = $row->rev_parent_id
;
311 if ( isset( $row->rev_id
) ) {
312 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
313 if ( $this->contribs
=== 'newbie' ) { // multiple users
314 $batch->add( NS_USER
, $row->user_name
);
315 $batch->add( NS_USER_TALK
, $row->user_name
);
317 $batch->add( $row->page_namespace
, $row->page_title
);
320 # Fetch rev_len for revisions not already scanned above
321 $this->mParentLens +
= Revision
::getParentLengths(
323 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
326 $this->mResult
->seek( 0 );
332 function getStartBody() {
333 return "<ul class=\"mw-contributions-list\">\n";
339 function getEndBody() {
344 * Generates each row in the contributions list.
346 * Contributions which are marked "top" are currently on top of the history.
347 * For these contributions, a [rollback] link is shown for users with roll-
348 * back privileges. The rollback link restores the most recent version that
349 * was not written by the target user.
351 * @todo This would probably look a lot nicer in a table.
355 function formatRow( $row ) {
360 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
363 * There may be more than just revision rows. To make sure that we'll only be processing
364 * revisions here, let's _try_ to build a revision out of our row (without displaying
365 * notices though) and then trying to grab data from the built object. If we succeed,
366 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
367 * to extensions to subscribe to the hook to parse the row.
369 MediaWiki\
suppressWarnings();
371 $rev = new Revision( $row );
372 $validRevision = (bool)$rev->getId();
373 } catch ( Exception
$e ) {
374 $validRevision = false;
376 MediaWiki\restoreWarnings
();
378 if ( $validRevision ) {
381 $page = Title
::newFromRow( $row );
382 $link = $linkRenderer->makeLink(
384 $page->getPrefixedText(),
385 [ 'class' => 'mw-contributions-title' ],
386 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
388 # Mark current revisions
390 $user = $this->getUser();
391 if ( $row->rev_id
=== $row->page_latest
) {
392 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
393 $classes[] = 'mw-contributions-current';
395 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
396 && $page->quickUserCan( 'edit', $user )
398 $this->preventClickjacking();
399 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
402 # Is there a visible previous revision?
403 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
404 $difftext = $linkRenderer->makeKnownLink(
406 new HtmlArmor( $this->messages
['diff'] ),
407 [ 'class' => 'mw-changeslist-diff' ],
410 'oldid' => $row->rev_id
414 $difftext = $this->messages
['diff'];
416 $histlink = $linkRenderer->makeKnownLink(
418 new HtmlArmor( $this->messages
['hist'] ),
419 [ 'class' => 'mw-changeslist-history' ],
420 [ 'action' => 'history' ]
423 if ( $row->rev_parent_id
=== null ) {
424 // For some reason rev_parent_id isn't populated for this row.
425 // Its rumoured this is true on wikipedia for some revisions (T36922).
426 // Next best thing is to have the total number of bytes.
427 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
428 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
429 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
432 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
433 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
436 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
437 $chardiff .= ChangesList
::showCharacterDifference(
442 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
445 $lang = $this->getLanguage();
446 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true );
447 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
448 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
449 $d = $linkRenderer->makeKnownLink(
452 [ 'class' => 'mw-changeslist-date' ],
453 [ 'oldid' => intval( $row->rev_id
) ]
456 $d = htmlspecialchars( $date );
458 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
459 $d = '<span class="history-deleted">' . $d . '</span>';
462 # Show user names for /newbies as there may be different users.
463 # Note that we already excluded rows with hidden user names.
464 if ( $this->contribs
== 'newbie' ) {
465 $userlink = ' . . ' . $lang->getDirMark()
466 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
467 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
468 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
474 if ( $rev->getParentId() === 0 ) {
475 $flags[] = ChangesList
::flag( 'newpage' );
478 if ( $rev->isMinor() ) {
479 $flags[] = ChangesList
::flag( 'minor' );
482 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
487 $diffHistLinks = $this->msg( 'parentheses' )
488 ->rawParams( $difftext . $this->messages
['pipe-separator'] . $histlink )
492 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
497 $classes = array_merge( $classes, $newClasses );
499 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
504 'diffHistLinks' => $diffHistLinks,
505 'charDifference' => $chardiff,
507 'articleLink' => $link,
508 'userlink' => $userlink,
509 'logText' => $comment,
510 'topmarktext' => $topmarktext,
511 'tagSummary' => $tagSummary,
514 # Denote if username is redacted for this edit
515 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
516 $templateParams['rev-deleted-user-contribs'] =
517 $this->msg( 'rev-deleted-user-contribs' )->escaped();
520 $templateParser = new TemplateParser();
521 $ret = $templateParser->processTemplate(
522 'SpecialContributionsLine',
527 // Let extensions add data
528 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
530 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
531 // receiving empty rows?
533 if ( $classes === [] && $ret === '' ) {
534 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
535 return "<!-- Could not format Special:Contribution row. -->\n";
538 // FIXME: The signature of the ContributionsLineEnding hook makes it
539 // very awkward to move this LI wrapper into the template.
540 return Html
::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
544 * Overwrite Pager function and return a helpful comment
547 function getSqlComment() {
548 if ( $this->namespace ||
$this->deletedOnly
) {
549 // potentially slow, see CR r58153
550 return 'contributions page filtered for namespace or RevisionDeleted edits';
552 return 'contributions page unfiltered';
556 protected function preventClickjacking() {
557 $this->preventClickjacking
= true;
563 public function getPreventClickjacking() {
564 return $this->preventClickjacking
;