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 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
233 'ug_expiry IS NULL OR ug_expiry >= ' .
234 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
238 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
239 // a timestamp offset far in the past such that there are no edits by users with user_ids in
240 // the range, we would end up scanning all revisions from that offset until start of time.
241 $condition[] = 'rev_timestamp > ' .
242 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
244 $uid = User
::idFromName( $this->target
);
246 $condition['rev_user'] = $uid;
247 $index = 'user_timestamp';
249 $condition['rev_user_text'] = $this->target
;
250 $index = 'usertext_timestamp';
254 if ( $this->deletedOnly
) {
255 $condition[] = 'rev_deleted != 0';
258 if ( $this->topOnly
) {
259 $condition[] = 'rev_id = page_latest';
262 if ( $this->newOnly
) {
263 $condition[] = 'rev_parent_id = 0';
266 if ( $this->hideMinor
) {
267 $condition[] = 'rev_minor_edit = 0';
270 return [ $tables, $index, $condition, $join_conds ];
273 function getNamespaceCond() {
274 if ( $this->namespace !== '' ) {
275 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
276 $eq_op = $this->nsInvert ?
'!=' : '=';
277 $bool_op = $this->nsInvert ?
'AND' : 'OR';
279 if ( !$this->associated
) {
280 return [ "page_namespace $eq_op $selectedNS" ];
283 $associatedNS = $this->mDb
->addQuotes(
284 MWNamespace
::getAssociated( $this->namespace )
288 "page_namespace $eq_op $selectedNS " .
290 " page_namespace $eq_op $associatedNS"
297 function getIndexField() {
298 return 'rev_timestamp';
301 function doBatchLookups() {
302 # Do a link batch query
303 $this->mResult
->seek( 0 );
305 $this->mParentLens
= [];
306 $batch = new LinkBatch();
307 # Give some pointers to make (last) links
308 foreach ( $this->mResult
as $row ) {
309 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
310 $parentRevIds[] = $row->rev_parent_id
;
312 if ( isset( $row->rev_id
) ) {
313 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
314 if ( $this->contribs
=== 'newbie' ) { // multiple users
315 $batch->add( NS_USER
, $row->user_name
);
316 $batch->add( NS_USER_TALK
, $row->user_name
);
318 $batch->add( $row->page_namespace
, $row->page_title
);
321 # Fetch rev_len for revisions not already scanned above
322 $this->mParentLens +
= Revision
::getParentLengths(
324 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
327 $this->mResult
->seek( 0 );
333 function getStartBody() {
334 return "<ul class=\"mw-contributions-list\">\n";
340 function getEndBody() {
345 * Generates each row in the contributions list.
347 * Contributions which are marked "top" are currently on top of the history.
348 * For these contributions, a [rollback] link is shown for users with roll-
349 * back privileges. The rollback link restores the most recent version that
350 * was not written by the target user.
352 * @todo This would probably look a lot nicer in a table.
356 function formatRow( $row ) {
361 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
364 * There may be more than just revision rows. To make sure that we'll only be processing
365 * revisions here, let's _try_ to build a revision out of our row (without displaying
366 * notices though) and then trying to grab data from the built object. If we succeed,
367 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
368 * to extensions to subscribe to the hook to parse the row.
370 MediaWiki\
suppressWarnings();
372 $rev = new Revision( $row );
373 $validRevision = (bool)$rev->getId();
374 } catch ( Exception
$e ) {
375 $validRevision = false;
377 MediaWiki\restoreWarnings
();
379 if ( $validRevision ) {
382 $page = Title
::newFromRow( $row );
383 $link = $linkRenderer->makeLink(
385 $page->getPrefixedText(),
386 [ 'class' => 'mw-contributions-title' ],
387 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
389 # Mark current revisions
391 $user = $this->getUser();
392 if ( $row->rev_id
=== $row->page_latest
) {
393 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
394 $classes[] = 'mw-contributions-current';
396 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
397 && $page->quickUserCan( 'edit', $user )
399 $this->preventClickjacking();
400 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
403 # Is there a visible previous revision?
404 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
405 $difftext = $linkRenderer->makeKnownLink(
407 new HtmlArmor( $this->messages
['diff'] ),
408 [ 'class' => 'mw-changeslist-diff' ],
411 'oldid' => $row->rev_id
415 $difftext = $this->messages
['diff'];
417 $histlink = $linkRenderer->makeKnownLink(
419 new HtmlArmor( $this->messages
['hist'] ),
420 [ 'class' => 'mw-changeslist-history' ],
421 [ 'action' => 'history' ]
424 if ( $row->rev_parent_id
=== null ) {
425 // For some reason rev_parent_id isn't populated for this row.
426 // Its rumoured this is true on wikipedia for some revisions (T36922).
427 // Next best thing is to have the total number of bytes.
428 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
429 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
430 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
433 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
434 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
437 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
438 $chardiff .= ChangesList
::showCharacterDifference(
443 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
446 $lang = $this->getLanguage();
447 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true );
448 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
449 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
450 $d = $linkRenderer->makeKnownLink(
453 [ 'class' => 'mw-changeslist-date' ],
454 [ 'oldid' => intval( $row->rev_id
) ]
457 $d = htmlspecialchars( $date );
459 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
460 $d = '<span class="history-deleted">' . $d . '</span>';
463 # Show user names for /newbies as there may be different users.
464 # Note that we already excluded rows with hidden user names.
465 if ( $this->contribs
== 'newbie' ) {
466 $userlink = ' . . ' . $lang->getDirMark()
467 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
468 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
469 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
475 if ( $rev->getParentId() === 0 ) {
476 $flags[] = ChangesList
::flag( 'newpage' );
479 if ( $rev->isMinor() ) {
480 $flags[] = ChangesList
::flag( 'minor' );
483 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
488 $diffHistLinks = $this->msg( 'parentheses' )
489 ->rawParams( $difftext . $this->messages
['pipe-separator'] . $histlink )
493 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
498 $classes = array_merge( $classes, $newClasses );
500 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
505 'diffHistLinks' => $diffHistLinks,
506 'charDifference' => $chardiff,
508 'articleLink' => $link,
509 'userlink' => $userlink,
510 'logText' => $comment,
511 'topmarktext' => $topmarktext,
512 'tagSummary' => $tagSummary,
515 # Denote if username is redacted for this edit
516 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
517 $templateParams['rev-deleted-user-contribs'] =
518 $this->msg( 'rev-deleted-user-contribs' )->escaped();
521 $templateParser = new TemplateParser();
522 $ret = $templateParser->processTemplate(
523 'SpecialContributionsLine',
528 // Let extensions add data
529 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
531 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
532 // receiving empty rows?
534 if ( $classes === [] && $ret === '' ) {
535 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
536 return "<!-- Could not format Special:Contribution row. -->\n";
539 // FIXME: The signature of the ContributionsLineEnding hook makes it
540 // very awkward to move this LI wrapper into the template.
541 return Html
::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
545 * Overwrite Pager function and return a helpful comment
548 function getSqlComment() {
549 if ( $this->namespace ||
$this->deletedOnly
) {
550 // potentially slow, see CR r58153
551 return 'contributions page filtered for namespace or RevisionDeleted edits';
553 return 'contributions page unfiltered';
557 protected function preventClickjacking() {
558 $this->preventClickjacking
= true;
564 public function getPreventClickjacking() {
565 return $this->preventClickjacking
;