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;
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 $year = isset( $options['year'] ) ?
$options['year'] : false;
80 $month = isset( $options['month'] ) ?
$options['month'] : false;
81 $this->getDateCond( $year, $month );
83 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
84 // with extra user based indexes or partioning by user. The additional metadata
85 // queries should use a regular replica DB since the lookup pattern is not all by user.
86 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
87 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
88 $this->templateParser
= new TemplateParser();
91 function getDefaultQuery() {
92 $query = parent
::getDefaultQuery();
93 $query['target'] = $this->target
;
99 * This method basically executes the exact same code as the parent class, though with
100 * a hook added, to allow extensions to add additional queries.
102 * @param string $offset Index offset, inclusive
103 * @param int $limit Exact query limit
104 * @param bool $descending Query direction, false for ascending, true for descending
105 * @return ResultWrapper
107 function reallyDoQuery( $offset, $limit, $descending ) {
108 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
115 * This hook will allow extensions to add in additional queries, so they can get their data
116 * in My Contributions as well. Extensions should append their results to the $data array.
118 * Extension queries have to implement the navbar requirement as well. They should
119 * - have a column aliased as $pager->getIndexField()
121 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
122 * - have the ORDER BY specified based upon the details provided by the navbar
124 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
126 * &$data: an array of results of all contribs queries
127 * $pager: the ContribsPager object hooked into
128 * $offset: see phpdoc above
129 * $limit: see phpdoc above
130 * $descending: see phpdoc above
132 $data = [ $this->mDb
->select(
133 $tables, $fields, $conds, $fname, $options, $join_conds
136 'ContribsPager::reallyDoQuery',
137 [ &$data, $this, $offset, $limit, $descending ]
142 // loop all results and collect them in an array
143 foreach ( $data as $query ) {
144 foreach ( $query as $i => $row ) {
145 // use index column as key, allowing us to easily sort in PHP
146 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
158 $result = array_slice( $result, 0, $limit );
160 // get rid of array keys
161 $result = array_values( $result );
163 return new FakeResultWrapper( $result );
166 function getQueryInfo() {
167 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
169 $user = $this->getUser();
170 $conds = array_merge( $userCond, $this->getNamespaceCond() );
172 // Paranoia: avoid brute force searches (T19342)
173 if ( !$user->isAllowed( 'deletedhistory' ) ) {
174 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
175 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
176 $conds[] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
177 ' != ' . Revision
::SUPPRESSED_USER
;
180 # Don't include orphaned revisions
181 $join_cond['page'] = Revision
::pageJoinCond();
182 # Get the current user name for accounts
183 $join_cond['user'] = Revision
::userJoinCond();
187 $options['USE INDEX'] = [ 'revision' => $index ];
192 'fields' => array_merge(
193 Revision
::selectFields(),
194 Revision
::selectUserFields(),
195 [ 'page_namespace', 'page_title', 'page_is_new',
196 'page_latest', 'page_is_redirect', 'page_len' ]
199 'options' => $options,
200 'join_conds' => $join_cond
203 ChangeTags
::modifyDisplayQuery(
204 $queryInfo['tables'],
205 $queryInfo['fields'],
207 $queryInfo['join_conds'],
208 $queryInfo['options'],
212 // Avoid PHP 7.1 warning from passing $this by reference
214 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
219 function getUserCond() {
222 $tables = [ 'revision', 'page', 'user' ];
224 if ( $this->contribs
== 'newbie' ) {
225 $max = $this->mDb
->selectField( 'user', 'max(user_id)', false, __METHOD__
);
226 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
227 # ignore local groups with the bot right
228 # @todo FIXME: Global groups may have 'bot' rights
229 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
230 if ( count( $groupsWithBotPermission ) ) {
231 $tables[] = 'user_groups';
232 $condition[] = 'ug_group IS NULL';
233 $join_conds['user_groups'] = [
235 'ug_user = rev_user',
236 'ug_group' => $groupsWithBotPermission,
237 'ug_expiry IS NULL OR ug_expiry >= ' .
238 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
242 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
243 // a timestamp offset far in the past such that there are no edits by users with user_ids in
244 // the range, we would end up scanning all revisions from that offset until start of time.
245 $condition[] = 'rev_timestamp > ' .
246 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
248 $uid = User
::idFromName( $this->target
);
250 $condition['rev_user'] = $uid;
251 $index = 'user_timestamp';
253 $condition['rev_user_text'] = $this->target
;
254 $index = 'usertext_timestamp';
258 if ( $this->deletedOnly
) {
259 $condition[] = 'rev_deleted != 0';
262 if ( $this->topOnly
) {
263 $condition[] = 'rev_id = page_latest';
266 if ( $this->newOnly
) {
267 $condition[] = 'rev_parent_id = 0';
270 if ( $this->hideMinor
) {
271 $condition[] = 'rev_minor_edit = 0';
274 return [ $tables, $index, $condition, $join_conds ];
277 function getNamespaceCond() {
278 if ( $this->namespace !== '' ) {
279 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
280 $eq_op = $this->nsInvert ?
'!=' : '=';
281 $bool_op = $this->nsInvert ?
'AND' : 'OR';
283 if ( !$this->associated
) {
284 return [ "page_namespace $eq_op $selectedNS" ];
287 $associatedNS = $this->mDb
->addQuotes(
288 MWNamespace
::getAssociated( $this->namespace )
292 "page_namespace $eq_op $selectedNS " .
294 " page_namespace $eq_op $associatedNS"
301 function getIndexField() {
302 return 'rev_timestamp';
305 function doBatchLookups() {
306 # Do a link batch query
307 $this->mResult
->seek( 0 );
309 $this->mParentLens
= [];
310 $batch = new LinkBatch();
311 # Give some pointers to make (last) links
312 foreach ( $this->mResult
as $row ) {
313 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
314 $parentRevIds[] = $row->rev_parent_id
;
316 if ( isset( $row->rev_id
) ) {
317 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
318 if ( $this->contribs
=== 'newbie' ) { // multiple users
319 $batch->add( NS_USER
, $row->user_name
);
320 $batch->add( NS_USER_TALK
, $row->user_name
);
322 $batch->add( $row->page_namespace
, $row->page_title
);
325 # Fetch rev_len for revisions not already scanned above
326 $this->mParentLens +
= Revision
::getParentLengths(
328 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
331 $this->mResult
->seek( 0 );
337 function getStartBody() {
338 return "<ul class=\"mw-contributions-list\">\n";
344 function getEndBody() {
349 * Generates each row in the contributions list.
351 * Contributions which are marked "top" are currently on top of the history.
352 * For these contributions, a [rollback] link is shown for users with roll-
353 * back privileges. The rollback link restores the most recent version that
354 * was not written by the target user.
356 * @todo This would probably look a lot nicer in a table.
360 function formatRow( $row ) {
365 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
368 * There may be more than just revision rows. To make sure that we'll only be processing
369 * revisions here, let's _try_ to build a revision out of our row (without displaying
370 * notices though) and then trying to grab data from the built object. If we succeed,
371 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
372 * to extensions to subscribe to the hook to parse the row.
374 MediaWiki\
suppressWarnings();
376 $rev = new Revision( $row );
377 $validRevision = (bool)$rev->getId();
378 } catch ( Exception
$e ) {
379 $validRevision = false;
381 MediaWiki\restoreWarnings
();
383 if ( $validRevision ) {
386 $page = Title
::newFromRow( $row );
387 $link = $linkRenderer->makeLink(
389 $page->getPrefixedText(),
390 [ 'class' => 'mw-contributions-title' ],
391 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
393 # Mark current revisions
395 $user = $this->getUser();
396 if ( $row->rev_id
=== $row->page_latest
) {
397 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
398 $classes[] = 'mw-contributions-current';
400 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
401 && $page->quickUserCan( 'edit', $user )
403 $this->preventClickjacking();
404 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
407 # Is there a visible previous revision?
408 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
409 $difftext = $linkRenderer->makeKnownLink(
411 new HtmlArmor( $this->messages
['diff'] ),
412 [ 'class' => 'mw-changeslist-diff' ],
415 'oldid' => $row->rev_id
419 $difftext = $this->messages
['diff'];
421 $histlink = $linkRenderer->makeKnownLink(
423 new HtmlArmor( $this->messages
['hist'] ),
424 [ 'class' => 'mw-changeslist-history' ],
425 [ 'action' => 'history' ]
428 if ( $row->rev_parent_id
=== null ) {
429 // For some reason rev_parent_id isn't populated for this row.
430 // Its rumoured this is true on wikipedia for some revisions (T36922).
431 // Next best thing is to have the total number of bytes.
432 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
433 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
434 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
437 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
438 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
441 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
442 $chardiff .= ChangesList
::showCharacterDifference(
447 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
450 $lang = $this->getLanguage();
451 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true );
452 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
453 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
454 $d = $linkRenderer->makeKnownLink(
457 [ 'class' => 'mw-changeslist-date' ],
458 [ 'oldid' => intval( $row->rev_id
) ]
461 $d = htmlspecialchars( $date );
463 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
464 $d = '<span class="history-deleted">' . $d . '</span>';
467 # Show user names for /newbies as there may be different users.
468 # Note that we already excluded rows with hidden user names.
469 if ( $this->contribs
== 'newbie' ) {
470 $userlink = ' . . ' . $lang->getDirMark()
471 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
472 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
473 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
479 if ( $rev->getParentId() === 0 ) {
480 $flags[] = ChangesList
::flag( 'newpage' );
483 if ( $rev->isMinor() ) {
484 $flags[] = ChangesList
::flag( 'minor' );
487 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
492 $diffHistLinks = $this->msg( 'parentheses' )
493 ->rawParams( $difftext . $this->messages
['pipe-separator'] . $histlink )
497 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
502 $classes = array_merge( $classes, $newClasses );
504 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
509 'diffHistLinks' => $diffHistLinks,
510 'charDifference' => $chardiff,
512 'articleLink' => $link,
513 'userlink' => $userlink,
514 'logText' => $comment,
515 'topmarktext' => $topmarktext,
516 'tagSummary' => $tagSummary,
519 # Denote if username is redacted for this edit
520 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
521 $templateParams['rev-deleted-user-contribs'] =
522 $this->msg( 'rev-deleted-user-contribs' )->escaped();
525 $ret = $this->templateParser
->processTemplate(
526 'SpecialContributionsLine',
531 // Let extensions add data
532 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
534 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
535 // receiving empty rows?
537 if ( $classes === [] && $ret === '' ) {
538 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
539 return "<!-- Could not format Special:Contribution row. -->\n";
542 // FIXME: The signature of the ContributionsLineEnding hook makes it
543 // very awkward to move this LI wrapper into the template.
544 return Html
::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
548 * Overwrite Pager function and return a helpful comment
551 function getSqlComment() {
552 if ( $this->namespace ||
$this->deletedOnly
) {
553 // potentially slow, see CR r58153
554 return 'contributions page filtered for namespace or RevisionDeleted edits';
556 return 'contributions page unfiltered';
560 protected function preventClickjacking() {
561 $this->preventClickjacking
= true;
567 public function getPreventClickjacking() {
568 return $this->preventClickjacking
;