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 ReverseChronologicalPager
{
33 public $mDefaultDirection = IndexPager
::DIR_DESCENDING
;
36 public $namespace = '';
38 public $preventClickjacking = false;
46 protected $mParentLens;
48 function __construct( IContextSource
$context, array $options ) {
49 parent
::__construct( $context );
58 foreach ( $msgs as $msg ) {
59 $this->messages
[$msg] = $this->msg( $msg )->escaped();
62 $this->target
= isset( $options['target'] ) ?
$options['target'] : '';
63 $this->contribs
= isset( $options['contribs'] ) ?
$options['contribs'] : 'users';
64 $this->namespace = isset( $options['namespace'] ) ?
$options['namespace'] : '';
65 $this->tagFilter
= isset( $options['tagfilter'] ) ?
$options['tagfilter'] : false;
66 $this->nsInvert
= isset( $options['nsInvert'] ) ?
$options['nsInvert'] : false;
67 $this->associated
= isset( $options['associated'] ) ?
$options['associated'] : false;
69 $this->deletedOnly
= !empty( $options['deletedOnly'] );
70 $this->topOnly
= !empty( $options['topOnly'] );
71 $this->newOnly
= !empty( $options['newOnly'] );
72 $this->hideMinor
= !empty( $options['hideMinor'] );
74 $year = isset( $options['year'] ) ?
$options['year'] : false;
75 $month = isset( $options['month'] ) ?
$options['month'] : false;
76 $this->getDateCond( $year, $month );
78 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
79 // with extra user based indexes or partioning by user. The additional metadata
80 // queries should use a regular replica DB since the lookup pattern is not all by user.
81 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
82 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
85 function getDefaultQuery() {
86 $query = parent
::getDefaultQuery();
87 $query['target'] = $this->target
;
93 * This method basically executes the exact same code as the parent class, though with
94 * a hook added, to allow extensions to add additional queries.
96 * @param string $offset Index offset, inclusive
97 * @param int $limit Exact query limit
98 * @param bool $descending Query direction, false for ascending, true for descending
99 * @return ResultWrapper
101 function reallyDoQuery( $offset, $limit, $descending ) {
102 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
109 * This hook will allow extensions to add in additional queries, so they can get their data
110 * in My Contributions as well. Extensions should append their results to the $data array.
112 * Extension queries have to implement the navbar requirement as well. They should
113 * - have a column aliased as $pager->getIndexField()
115 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
116 * - have the ORDER BY specified based upon the details provided by the navbar
118 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
120 * &$data: an array of results of all contribs queries
121 * $pager: the ContribsPager object hooked into
122 * $offset: see phpdoc above
123 * $limit: see phpdoc above
124 * $descending: see phpdoc above
126 $data = [ $this->mDb
->select(
127 $tables, $fields, $conds, $fname, $options, $join_conds
130 'ContribsPager::reallyDoQuery',
131 [ &$data, $this, $offset, $limit, $descending ]
136 // loop all results and collect them in an array
137 foreach ( $data as $query ) {
138 foreach ( $query as $i => $row ) {
139 // use index column as key, allowing us to easily sort in PHP
140 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
152 $result = array_slice( $result, 0, $limit );
154 // get rid of array keys
155 $result = array_values( $result );
157 return new FakeResultWrapper( $result );
160 function getQueryInfo() {
161 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
163 $user = $this->getUser();
164 $conds = array_merge( $userCond, $this->getNamespaceCond() );
166 // Paranoia: avoid brute force searches (T19342)
167 if ( !$user->isAllowed( 'deletedhistory' ) ) {
168 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
169 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
170 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
171 ' != ' . Revision
::SUPPRESSED_USER
;
174 # Don't include orphaned revisions
175 $join_cond['page'] = Revision
::pageJoinCond();
176 # Get the current user name for accounts
177 $join_cond['user'] = Revision
::userJoinCond();
181 $options['USE INDEX'] = [ 'revision' => $index ];
186 'fields' => array_merge(
187 Revision
::selectFields(),
188 Revision
::selectUserFields(),
189 [ 'page_namespace', 'page_title', 'page_is_new',
190 'page_latest', 'page_is_redirect', 'page_len' ]
193 'options' => $options,
194 'join_conds' => $join_cond
197 ChangeTags
::modifyDisplayQuery(
198 $queryInfo['tables'],
199 $queryInfo['fields'],
201 $queryInfo['join_conds'],
202 $queryInfo['options'],
206 // Avoid PHP 7.1 warning from passing $this by reference
208 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
213 function getUserCond() {
216 $tables = [ 'revision', 'page', 'user' ];
218 if ( $this->contribs
== 'newbie' ) {
219 $max = $this->mDb
->selectField( 'user', 'max(user_id)', false, __METHOD__
);
220 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
221 # ignore local groups with the bot right
222 # @todo FIXME: Global groups may have 'bot' rights
223 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
224 if ( count( $groupsWithBotPermission ) ) {
225 $tables[] = 'user_groups';
226 $condition[] = 'ug_group IS NULL';
227 $join_conds['user_groups'] = [
229 'ug_user = rev_user',
230 'ug_group' => $groupsWithBotPermission,
231 'ug_expiry IS NULL OR ug_expiry >= ' .
232 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
236 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
237 // a timestamp offset far in the past such that there are no edits by users with user_ids in
238 // the range, we would end up scanning all revisions from that offset until start of time.
239 $condition[] = 'rev_timestamp > ' .
240 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
242 $uid = User
::idFromName( $this->target
);
244 $condition['rev_user'] = $uid;
245 $index = 'user_timestamp';
247 $condition['rev_user_text'] = $this->target
;
248 $index = 'usertext_timestamp';
252 if ( $this->deletedOnly
) {
253 $condition[] = 'rev_deleted != 0';
256 if ( $this->topOnly
) {
257 $condition[] = 'rev_id = page_latest';
260 if ( $this->newOnly
) {
261 $condition[] = 'rev_parent_id = 0';
264 if ( $this->hideMinor
) {
265 $condition[] = 'rev_minor_edit = 0';
268 return [ $tables, $index, $condition, $join_conds ];
271 function getNamespaceCond() {
272 if ( $this->namespace !== '' ) {
273 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
274 $eq_op = $this->nsInvert ?
'!=' : '=';
275 $bool_op = $this->nsInvert ?
'AND' : 'OR';
277 if ( !$this->associated
) {
278 return [ "page_namespace $eq_op $selectedNS" ];
281 $associatedNS = $this->mDb
->addQuotes(
282 MWNamespace
::getAssociated( $this->namespace )
286 "page_namespace $eq_op $selectedNS " .
288 " page_namespace $eq_op $associatedNS"
295 function getIndexField() {
296 return 'rev_timestamp';
299 function doBatchLookups() {
300 # Do a link batch query
301 $this->mResult
->seek( 0 );
303 $this->mParentLens
= [];
304 $batch = new LinkBatch();
305 # Give some pointers to make (last) links
306 foreach ( $this->mResult
as $row ) {
307 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
308 $parentRevIds[] = $row->rev_parent_id
;
310 if ( isset( $row->rev_id
) ) {
311 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
312 if ( $this->contribs
=== 'newbie' ) { // multiple users
313 $batch->add( NS_USER
, $row->user_name
);
314 $batch->add( NS_USER_TALK
, $row->user_name
);
316 $batch->add( $row->page_namespace
, $row->page_title
);
319 # Fetch rev_len for revisions not already scanned above
320 $this->mParentLens +
= Revision
::getParentLengths(
322 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
325 $this->mResult
->seek( 0 );
331 function getStartBody() {
332 return "<ul class=\"mw-contributions-list\">\n";
338 function getEndBody() {
343 * Generates each row in the contributions list.
345 * Contributions which are marked "top" are currently on top of the history.
346 * For these contributions, a [rollback] link is shown for users with roll-
347 * back privileges. The rollback link restores the most recent version that
348 * was not written by the target user.
350 * @todo This would probably look a lot nicer in a table.
354 function formatRow( $row ) {
359 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
362 * There may be more than just revision rows. To make sure that we'll only be processing
363 * revisions here, let's _try_ to build a revision out of our row (without displaying
364 * notices though) and then trying to grab data from the built object. If we succeed,
365 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
366 * to extensions to subscribe to the hook to parse the row.
368 MediaWiki\
suppressWarnings();
370 $rev = new Revision( $row );
371 $validRevision = (bool)$rev->getId();
372 } catch ( Exception
$e ) {
373 $validRevision = false;
375 MediaWiki\restoreWarnings
();
377 if ( $validRevision ) {
380 $page = Title
::newFromRow( $row );
381 $link = $linkRenderer->makeLink(
383 $page->getPrefixedText(),
384 [ 'class' => 'mw-contributions-title' ],
385 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
387 # Mark current revisions
389 $user = $this->getUser();
390 if ( $row->rev_id
=== $row->page_latest
) {
391 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
392 $classes[] = 'mw-contributions-current';
394 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
395 && $page->quickUserCan( 'edit', $user )
397 $this->preventClickjacking();
398 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
401 # Is there a visible previous revision?
402 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
403 $difftext = $linkRenderer->makeKnownLink(
405 new HtmlArmor( $this->messages
['diff'] ),
406 [ 'class' => 'mw-changeslist-diff' ],
409 'oldid' => $row->rev_id
413 $difftext = $this->messages
['diff'];
415 $histlink = $linkRenderer->makeKnownLink(
417 new HtmlArmor( $this->messages
['hist'] ),
418 [ 'class' => 'mw-changeslist-history' ],
419 [ 'action' => 'history' ]
422 if ( $row->rev_parent_id
=== null ) {
423 // For some reason rev_parent_id isn't populated for this row.
424 // Its rumoured this is true on wikipedia for some revisions (T36922).
425 // Next best thing is to have the total number of bytes.
426 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
427 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
428 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
431 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
432 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
435 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
436 $chardiff .= ChangesList
::showCharacterDifference(
441 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
444 $lang = $this->getLanguage();
445 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true );
446 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
447 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
448 $d = $linkRenderer->makeKnownLink(
451 [ 'class' => 'mw-changeslist-date' ],
452 [ 'oldid' => intval( $row->rev_id
) ]
455 $d = htmlspecialchars( $date );
457 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
458 $d = '<span class="history-deleted">' . $d . '</span>';
461 # Show user names for /newbies as there may be different users.
462 # Note that we already excluded rows with hidden user names.
463 if ( $this->contribs
== 'newbie' ) {
464 $userlink = ' . . ' . $lang->getDirMark()
465 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
466 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
467 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
473 if ( $rev->getParentId() === 0 ) {
474 $flags[] = ChangesList
::flag( 'newpage' );
477 if ( $rev->isMinor() ) {
478 $flags[] = ChangesList
::flag( 'minor' );
481 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
486 $diffHistLinks = $this->msg( 'parentheses' )
487 ->rawParams( $difftext . $this->messages
['pipe-separator'] . $histlink )
491 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
496 $classes = array_merge( $classes, $newClasses );
498 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
503 'diffHistLinks' => $diffHistLinks,
504 'charDifference' => $chardiff,
506 'articleLink' => $link,
507 'userlink' => $userlink,
508 'logText' => $comment,
509 'topmarktext' => $topmarktext,
510 'tagSummary' => $tagSummary,
513 # Denote if username is redacted for this edit
514 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
515 $templateParams['rev-deleted-user-contribs'] =
516 $this->msg( 'rev-deleted-user-contribs' )->escaped();
519 $templateParser = new TemplateParser();
520 $ret = $templateParser->processTemplate(
521 'SpecialContributionsLine',
526 // Let extensions add data
527 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
529 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
530 // receiving empty rows?
532 if ( $classes === [] && $ret === '' ) {
533 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
534 return "<!-- Could not format Special:Contribution row. -->\n";
537 // FIXME: The signature of the ContributionsLineEnding hook makes it
538 // very awkward to move this LI wrapper into the template.
539 return Html
::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
543 * Overwrite Pager function and return a helpful comment
546 function getSqlComment() {
547 if ( $this->namespace ||
$this->deletedOnly
) {
548 // potentially slow, see CR r58153
549 return 'contributions page filtered for namespace or RevisionDeleted edits';
551 return 'contributions page unfiltered';
555 protected function preventClickjacking() {
556 $this->preventClickjacking
= true;
562 public function getPreventClickjacking() {
563 return $this->preventClickjacking
;