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
;
28 class ContribsPager
extends ReverseChronologicalPager
{
30 public $mDefaultDirection = IndexPager
::DIR_DESCENDING
;
33 public $namespace = '';
35 public $preventClickjacking = false;
43 protected $mParentLens;
45 function __construct( IContextSource
$context, array $options ) {
46 parent
::__construct( $context );
55 foreach ( $msgs as $msg ) {
56 $this->messages
[$msg] = $this->msg( $msg )->escaped();
59 $this->target
= isset( $options['target'] ) ?
$options['target'] : '';
60 $this->contribs
= isset( $options['contribs'] ) ?
$options['contribs'] : 'users';
61 $this->namespace = isset( $options['namespace'] ) ?
$options['namespace'] : '';
62 $this->tagFilter
= isset( $options['tagfilter'] ) ?
$options['tagfilter'] : false;
63 $this->nsInvert
= isset( $options['nsInvert'] ) ?
$options['nsInvert'] : false;
64 $this->associated
= isset( $options['associated'] ) ?
$options['associated'] : false;
66 $this->deletedOnly
= !empty( $options['deletedOnly'] );
67 $this->topOnly
= !empty( $options['topOnly'] );
68 $this->newOnly
= !empty( $options['newOnly'] );
69 $this->hideMinor
= !empty( $options['hideMinor'] );
71 $year = isset( $options['year'] ) ?
$options['year'] : false;
72 $month = isset( $options['month'] ) ?
$options['month'] : false;
73 $this->getDateCond( $year, $month );
75 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
76 // with extra user based indexes or partioning by user. The additional metadata
77 // queries should use a regular replica DB since the lookup pattern is not all by user.
78 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
79 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
82 function getDefaultQuery() {
83 $query = parent
::getDefaultQuery();
84 $query['target'] = $this->target
;
90 * This method basically executes the exact same code as the parent class, though with
91 * a hook added, to allow extensions to add additional queries.
93 * @param string $offset Index offset, inclusive
94 * @param int $limit Exact query limit
95 * @param bool $descending Query direction, false for ascending, true for descending
96 * @return ResultWrapper
98 function reallyDoQuery( $offset, $limit, $descending ) {
99 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
106 * This hook will allow extensions to add in additional queries, so they can get their data
107 * in My Contributions as well. Extensions should append their results to the $data array.
109 * Extension queries have to implement the navbar requirement as well. They should
110 * - have a column aliased as $pager->getIndexField()
112 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
113 * - have the ORDER BY specified based upon the details provided by the navbar
115 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
117 * &$data: an array of results of all contribs queries
118 * $pager: the ContribsPager object hooked into
119 * $offset: see phpdoc above
120 * $limit: see phpdoc above
121 * $descending: see phpdoc above
123 $data = [ $this->mDb
->select(
124 $tables, $fields, $conds, $fname, $options, $join_conds
127 'ContribsPager::reallyDoQuery',
128 [ &$data, $this, $offset, $limit, $descending ]
133 // loop all results and collect them in an array
134 foreach ( $data as $query ) {
135 foreach ( $query as $i => $row ) {
136 // use index column as key, allowing us to easily sort in PHP
137 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
149 $result = array_slice( $result, 0, $limit );
151 // get rid of array keys
152 $result = array_values( $result );
154 return new FakeResultWrapper( $result );
157 function getQueryInfo() {
158 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
160 $user = $this->getUser();
161 $conds = array_merge( $userCond, $this->getNamespaceCond() );
163 // Paranoia: avoid brute force searches (bug 17342)
164 if ( !$user->isAllowed( 'deletedhistory' ) ) {
165 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
166 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
167 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
168 ' != ' . Revision
::SUPPRESSED_USER
;
171 # Don't include orphaned revisions
172 $join_cond['page'] = Revision
::pageJoinCond();
173 # Get the current user name for accounts
174 $join_cond['user'] = Revision
::userJoinCond();
178 $options['USE INDEX'] = [ 'revision' => $index ];
183 'fields' => array_merge(
184 Revision
::selectFields(),
185 Revision
::selectUserFields(),
186 [ 'page_namespace', 'page_title', 'page_is_new',
187 'page_latest', 'page_is_redirect', 'page_len' ]
190 'options' => $options,
191 'join_conds' => $join_cond
194 ChangeTags
::modifyDisplayQuery(
195 $queryInfo['tables'],
196 $queryInfo['fields'],
198 $queryInfo['join_conds'],
199 $queryInfo['options'],
203 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$this, &$queryInfo ] );
208 function getUserCond() {
211 $tables = [ 'revision', 'page', 'user' ];
213 if ( $this->contribs
== 'newbie' ) {
214 $max = $this->mDb
->selectField( 'user', 'max(user_id)', false, __METHOD__
);
215 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
216 # ignore local groups with the bot right
217 # @todo FIXME: Global groups may have 'bot' rights
218 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
219 if ( count( $groupsWithBotPermission ) ) {
220 $tables[] = 'user_groups';
221 $condition[] = 'ug_group IS NULL';
222 $join_conds['user_groups'] = [
224 'ug_user = rev_user',
225 'ug_group' => $groupsWithBotPermission,
226 'ug_expiry IS NULL OR ug_expiry >= ' . $this->mDb
->addQuotes( $this->mDb
->timestamp() )
230 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
231 // a timestamp offset far in the past such that there are no edits by users with user_ids in
232 // the range, we would end up scanning all revisions from that offset until start of time.
233 $condition[] = 'rev_timestamp > ' .
234 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
236 $uid = User
::idFromName( $this->target
);
238 $condition['rev_user'] = $uid;
239 $index = 'user_timestamp';
241 $condition['rev_user_text'] = $this->target
;
242 $index = 'usertext_timestamp';
246 if ( $this->deletedOnly
) {
247 $condition[] = 'rev_deleted != 0';
250 if ( $this->topOnly
) {
251 $condition[] = 'rev_id = page_latest';
254 if ( $this->newOnly
) {
255 $condition[] = 'rev_parent_id = 0';
258 if ( $this->hideMinor
) {
259 $condition[] = 'rev_minor_edit = 0';
262 return [ $tables, $index, $condition, $join_conds ];
265 function getNamespaceCond() {
266 if ( $this->namespace !== '' ) {
267 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
268 $eq_op = $this->nsInvert ?
'!=' : '=';
269 $bool_op = $this->nsInvert ?
'AND' : 'OR';
271 if ( !$this->associated
) {
272 return [ "page_namespace $eq_op $selectedNS" ];
275 $associatedNS = $this->mDb
->addQuotes(
276 MWNamespace
::getAssociated( $this->namespace )
280 "page_namespace $eq_op $selectedNS " .
282 " page_namespace $eq_op $associatedNS"
289 function getIndexField() {
290 return 'rev_timestamp';
293 function doBatchLookups() {
294 # Do a link batch query
295 $this->mResult
->seek( 0 );
297 $this->mParentLens
= [];
298 $batch = new LinkBatch();
299 # Give some pointers to make (last) links
300 foreach ( $this->mResult
as $row ) {
301 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
302 $parentRevIds[] = $row->rev_parent_id
;
304 if ( isset( $row->rev_id
) ) {
305 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
306 if ( $this->contribs
=== 'newbie' ) { // multiple users
307 $batch->add( NS_USER
, $row->user_name
);
308 $batch->add( NS_USER_TALK
, $row->user_name
);
310 $batch->add( $row->page_namespace
, $row->page_title
);
313 # Fetch rev_len for revisions not already scanned above
314 $this->mParentLens +
= Revision
::getParentLengths(
316 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
319 $this->mResult
->seek( 0 );
325 function getStartBody() {
326 return "<ul class=\"mw-contributions-list\">\n";
332 function getEndBody() {
337 * Generates each row in the contributions list.
339 * Contributions which are marked "top" are currently on top of the history.
340 * For these contributions, a [rollback] link is shown for users with roll-
341 * back privileges. The rollback link restores the most recent version that
342 * was not written by the target user.
344 * @todo This would probably look a lot nicer in a table.
348 function formatRow( $row ) {
353 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
356 * There may be more than just revision rows. To make sure that we'll only be processing
357 * revisions here, let's _try_ to build a revision out of our row (without displaying
358 * notices though) and then trying to grab data from the built object. If we succeed,
359 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
360 * to extensions to subscribe to the hook to parse the row.
362 MediaWiki\
suppressWarnings();
364 $rev = new Revision( $row );
365 $validRevision = (bool)$rev->getId();
366 } catch ( Exception
$e ) {
367 $validRevision = false;
369 MediaWiki\restoreWarnings
();
371 if ( $validRevision ) {
374 $page = Title
::newFromRow( $row );
375 $link = $linkRenderer->makeLink(
377 $page->getPrefixedText(),
378 [ 'class' => 'mw-contributions-title' ],
379 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
381 # Mark current revisions
383 $user = $this->getUser();
384 if ( $row->rev_id
=== $row->page_latest
) {
385 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
386 $classes[] = 'mw-contributions-current';
388 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
389 && $page->quickUserCan( 'edit', $user )
391 $this->preventClickjacking();
392 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
395 # Is there a visible previous revision?
396 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
397 $difftext = $linkRenderer->makeKnownLink(
399 new HtmlArmor( $this->messages
['diff'] ),
403 'oldid' => $row->rev_id
407 $difftext = $this->messages
['diff'];
409 $histlink = $linkRenderer->makeKnownLink(
411 new HtmlArmor( $this->messages
['hist'] ),
413 [ 'action' => 'history' ]
416 if ( $row->rev_parent_id
=== null ) {
417 // For some reason rev_parent_id isn't populated for this row.
418 // Its rumoured this is true on wikipedia for some revisions (bug 34922).
419 // Next best thing is to have the total number of bytes.
420 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
421 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
422 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
425 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
426 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
429 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
430 $chardiff .= ChangesList
::showCharacterDifference(
435 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
438 $lang = $this->getLanguage();
439 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true );
440 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
441 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
442 $d = $linkRenderer->makeKnownLink(
445 [ 'class' => 'mw-changeslist-date' ],
446 [ 'oldid' => intval( $row->rev_id
) ]
449 $d = htmlspecialchars( $date );
451 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
452 $d = '<span class="history-deleted">' . $d . '</span>';
455 # Show user names for /newbies as there may be different users.
456 # Note that we already excluded rows with hidden user names.
457 if ( $this->contribs
== 'newbie' ) {
458 $userlink = ' . . ' . $lang->getDirMark()
459 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
460 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
461 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
467 if ( $rev->getParentId() === 0 ) {
468 $flags[] = ChangesList
::flag( 'newpage' );
471 if ( $rev->isMinor() ) {
472 $flags[] = ChangesList
::flag( 'minor' );
475 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
480 $diffHistLinks = $this->msg( 'parentheses' )
481 ->rawParams( $difftext . $this->messages
['pipe-separator'] . $histlink )
485 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
490 $classes = array_merge( $classes, $newClasses );
492 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
497 'diffHistLinks' => $diffHistLinks,
498 'charDifference' => $chardiff,
500 'articleLink' => $link,
501 'userlink' => $userlink,
502 'logText' => $comment,
503 'topmarktext' => $topmarktext,
504 'tagSummary' => $tagSummary,
507 # Denote if username is redacted for this edit
508 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
509 $templateParams['rev-deleted-user-contribs'] =
510 $this->msg( 'rev-deleted-user-contribs' )->escaped();
513 $templateParser = new TemplateParser();
514 $ret = $templateParser->processTemplate(
515 'SpecialContributionsLine',
520 // Let extensions add data
521 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
523 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
524 // receiving empty rows?
526 if ( $classes === [] && $ret === '' ) {
527 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
528 return "<!-- Could not format Special:Contribution row. -->\n";
531 // FIXME: The signature of the ContributionsLineEnding hook makes it
532 // very awkward to move this LI wrapper into the template.
533 return Html
::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
537 * Overwrite Pager function and return a helpful comment
540 function getSqlComment() {
541 if ( $this->namespace ||
$this->deletedOnly
) {
542 // potentially slow, see CR r58153
543 return 'contributions page filtered for namespace or RevisionDeleted edits';
545 return 'contributions page unfiltered';
549 protected function preventClickjacking() {
550 $this->preventClickjacking
= true;
556 public function getPreventClickjacking() {
557 return $this->preventClickjacking
;