Update docs/hooks.txt for ShowSearchHitTitle
[mediawiki.git] / includes / specials / pagers / ContribsPager.php
blob39c55c8a0c35af18a8709d14887cfe3353dad4f9
1 <?php
2 /**
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
18 * @file
19 * @ingroup Pager
22 /**
23 * Pager for Special:Contributions
24 * @ingroup Pager
26 use MediaWiki\MediaWikiServices;
28 class ContribsPager extends ReverseChronologicalPager {
30 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
31 public $messages;
32 public $target;
33 public $namespace = '';
34 public $mDb;
35 public $preventClickjacking = false;
37 /** @var IDatabase */
38 public $mDbSecondary;
40 /**
41 * @var array
43 protected $mParentLens;
45 function __construct( IContextSource $context, array $options ) {
46 parent::__construct( $context );
48 $msgs = [
49 'diff',
50 'hist',
51 'pipe-separator',
52 'uctop'
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;
86 return $query;
89 /**
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(
100 $offset,
101 $limit,
102 $descending
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()
111 * - have LIMIT set
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
125 ) ];
126 Hooks::run(
127 'ContribsPager::reallyDoQuery',
128 [ &$data, $this, $offset, $limit, $descending ]
131 $result = [];
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;
141 // sort results
142 if ( $descending ) {
143 ksort( $result );
144 } else {
145 krsort( $result );
148 // enforce limit
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();
176 $options = [];
177 if ( $index ) {
178 $options['USE INDEX'] = [ 'revision' => $index ];
181 $queryInfo = [
182 'tables' => $tables,
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' ]
189 'conds' => $conds,
190 'options' => $options,
191 'join_conds' => $join_cond
194 ChangeTags::modifyDisplayQuery(
195 $queryInfo['tables'],
196 $queryInfo['fields'],
197 $queryInfo['conds'],
198 $queryInfo['join_conds'],
199 $queryInfo['options'],
200 $this->tagFilter
203 Hooks::run( 'ContribsPager::getQueryInfo', [ &$this, &$queryInfo ] );
205 return $queryInfo;
208 function getUserCond() {
209 $condition = [];
210 $join_conds = [];
211 $tables = [ 'revision', 'page', 'user' ];
212 $index = false;
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'] = [
223 'LEFT JOIN', [
224 'ug_user = rev_user',
225 'ug_group' => $groupsWithBotPermission
229 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
230 // a timestamp offset far in the past such that there are no edits by users with user_ids in
231 // the range, we would end up scanning all revisions from that offset until start of time.
232 $condition[] = 'rev_timestamp > ' .
233 $this->mDb->addQuotes( $this->mDb->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
234 } else {
235 $uid = User::idFromName( $this->target );
236 if ( $uid ) {
237 $condition['rev_user'] = $uid;
238 $index = 'user_timestamp';
239 } else {
240 $condition['rev_user_text'] = $this->target;
241 $index = 'usertext_timestamp';
245 if ( $this->deletedOnly ) {
246 $condition[] = 'rev_deleted != 0';
249 if ( $this->topOnly ) {
250 $condition[] = 'rev_id = page_latest';
253 if ( $this->newOnly ) {
254 $condition[] = 'rev_parent_id = 0';
257 if ( $this->hideMinor ) {
258 $condition[] = 'rev_minor_edit = 0';
261 return [ $tables, $index, $condition, $join_conds ];
264 function getNamespaceCond() {
265 if ( $this->namespace !== '' ) {
266 $selectedNS = $this->mDb->addQuotes( $this->namespace );
267 $eq_op = $this->nsInvert ? '!=' : '=';
268 $bool_op = $this->nsInvert ? 'AND' : 'OR';
270 if ( !$this->associated ) {
271 return [ "page_namespace $eq_op $selectedNS" ];
274 $associatedNS = $this->mDb->addQuotes(
275 MWNamespace::getAssociated( $this->namespace )
278 return [
279 "page_namespace $eq_op $selectedNS " .
280 $bool_op .
281 " page_namespace $eq_op $associatedNS"
285 return [];
288 function getIndexField() {
289 return 'rev_timestamp';
292 function doBatchLookups() {
293 # Do a link batch query
294 $this->mResult->seek( 0 );
295 $parentRevIds = [];
296 $this->mParentLens = [];
297 $batch = new LinkBatch();
298 # Give some pointers to make (last) links
299 foreach ( $this->mResult as $row ) {
300 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
301 $parentRevIds[] = $row->rev_parent_id;
303 if ( isset( $row->rev_id ) ) {
304 $this->mParentLens[$row->rev_id] = $row->rev_len;
305 if ( $this->contribs === 'newbie' ) { // multiple users
306 $batch->add( NS_USER, $row->user_name );
307 $batch->add( NS_USER_TALK, $row->user_name );
309 $batch->add( $row->page_namespace, $row->page_title );
312 # Fetch rev_len for revisions not already scanned above
313 $this->mParentLens += Revision::getParentLengths(
314 $this->mDbSecondary,
315 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
317 $batch->execute();
318 $this->mResult->seek( 0 );
322 * @return string
324 function getStartBody() {
325 return "<ul class=\"mw-contributions-list\">\n";
329 * @return string
331 function getEndBody() {
332 return "</ul>\n";
336 * Generates each row in the contributions list.
338 * Contributions which are marked "top" are currently on top of the history.
339 * For these contributions, a [rollback] link is shown for users with roll-
340 * back privileges. The rollback link restores the most recent version that
341 * was not written by the target user.
343 * @todo This would probably look a lot nicer in a table.
344 * @param object $row
345 * @return string
347 function formatRow( $row ) {
349 $ret = '';
350 $classes = [];
352 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
355 * There may be more than just revision rows. To make sure that we'll only be processing
356 * revisions here, let's _try_ to build a revision out of our row (without displaying
357 * notices though) and then trying to grab data from the built object. If we succeed,
358 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
359 * to extensions to subscribe to the hook to parse the row.
361 MediaWiki\suppressWarnings();
362 try {
363 $rev = new Revision( $row );
364 $validRevision = (bool)$rev->getId();
365 } catch ( Exception $e ) {
366 $validRevision = false;
368 MediaWiki\restoreWarnings();
370 if ( $validRevision ) {
371 $classes = [];
373 $page = Title::newFromRow( $row );
374 $link = $linkRenderer->makeLink(
375 $page,
376 $page->getPrefixedText(),
377 [ 'class' => 'mw-contributions-title' ],
378 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
380 # Mark current revisions
381 $topmarktext = '';
382 $user = $this->getUser();
383 if ( $row->rev_id === $row->page_latest ) {
384 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
385 $classes[] = 'mw-contributions-current';
386 # Add rollback link
387 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
388 && $page->quickUserCan( 'edit', $user )
390 $this->preventClickjacking();
391 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
394 # Is there a visible previous revision?
395 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
396 $difftext = $linkRenderer->makeKnownLink(
397 $page,
398 new HtmlArmor( $this->messages['diff'] ),
401 'diff' => 'prev',
402 'oldid' => $row->rev_id
405 } else {
406 $difftext = $this->messages['diff'];
408 $histlink = $linkRenderer->makeKnownLink(
409 $page,
410 new HtmlArmor( $this->messages['hist'] ),
412 [ 'action' => 'history' ]
415 if ( $row->rev_parent_id === null ) {
416 // For some reason rev_parent_id isn't populated for this row.
417 // Its rumoured this is true on wikipedia for some revisions (bug 34922).
418 // Next best thing is to have the total number of bytes.
419 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
420 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
421 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
422 } else {
423 $parentLen = 0;
424 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
425 $parentLen = $this->mParentLens[$row->rev_parent_id];
428 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
429 $chardiff .= ChangesList::showCharacterDifference(
430 $parentLen,
431 $row->rev_len,
432 $this->getContext()
434 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
437 $lang = $this->getLanguage();
438 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true );
439 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
440 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
441 $d = $linkRenderer->makeKnownLink(
442 $page,
443 $date,
444 [ 'class' => 'mw-changeslist-date' ],
445 [ 'oldid' => intval( $row->rev_id ) ]
447 } else {
448 $d = htmlspecialchars( $date );
450 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
451 $d = '<span class="history-deleted">' . $d . '</span>';
454 # Show user names for /newbies as there may be different users.
455 # Note that we already excluded rows with hidden user names.
456 if ( $this->contribs == 'newbie' ) {
457 $userlink = ' . . ' . $lang->getDirMark()
458 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
459 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
460 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
461 } else {
462 $userlink = '';
465 $flags = [];
466 if ( $rev->getParentId() === 0 ) {
467 $flags[] = ChangesList::flag( 'newpage' );
470 if ( $rev->isMinor() ) {
471 $flags[] = ChangesList::flag( 'minor' );
474 $del = Linker::getRevDeleteLink( $user, $rev, $page );
475 if ( $del !== '' ) {
476 $del .= ' ';
479 $diffHistLinks = $this->msg( 'parentheses' )
480 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
481 ->escaped();
483 # Tags, if any.
484 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
485 $row->ts_tags,
486 'contributions',
487 $this->getContext()
489 $classes = array_merge( $classes, $newClasses );
491 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
493 $templateParams = [
494 'del' => $del,
495 'timestamp' => $d,
496 'diffHistLinks' => $diffHistLinks,
497 'charDifference' => $chardiff,
498 'flags' => $flags,
499 'articleLink' => $link,
500 'userlink' => $userlink,
501 'logText' => $comment,
502 'topmarktext' => $topmarktext,
503 'tagSummary' => $tagSummary,
506 # Denote if username is redacted for this edit
507 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
508 $templateParams['rev-deleted-user-contribs'] =
509 $this->msg( 'rev-deleted-user-contribs' )->escaped();
512 $templateParser = new TemplateParser();
513 $ret = $templateParser->processTemplate(
514 'SpecialContributionsLine',
515 $templateParams
519 // Let extensions add data
520 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
522 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
523 // receiving empty rows?
525 if ( $classes === [] && $ret === '' ) {
526 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
527 return "<!-- Could not format Special:Contribution row. -->\n";
530 // FIXME: The signature of the ContributionsLineEnding hook makes it
531 // very awkward to move this LI wrapper into the template.
532 return Html::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
536 * Overwrite Pager function and return a helpful comment
537 * @return string
539 function getSqlComment() {
540 if ( $this->namespace || $this->deletedOnly ) {
541 // potentially slow, see CR r58153
542 return 'contributions page filtered for namespace or RevisionDeleted edits';
543 } else {
544 return 'contributions page unfiltered';
548 protected function preventClickjacking() {
549 $this->preventClickjacking = true;
553 * @return bool
555 public function getPreventClickjacking() {
556 return $this->preventClickjacking;