Merge "Don't fill in the skin's search box on Special:Search"
[lhc/web/wiklou.git] / includes / specials / pagers / ContribsPager.php
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @ingroup Pager
20 */
21
22 /**
23 * Pager for Special:Contributions
24 * @ingroup Pager
25 */
26 use MediaWiki\MediaWikiServices;
27 use Wikimedia\Rdbms\ResultWrapper;
28 use Wikimedia\Rdbms\FakeResultWrapper;
29 use Wikimedia\Rdbms\IDatabase;
30
31 class ContribsPager extends ReverseChronologicalPager {
32
33 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
34 public $messages;
35 public $target;
36 public $namespace = '';
37 public $mDb;
38 public $preventClickjacking = false;
39
40 /** @var IDatabase */
41 public $mDbSecondary;
42
43 /**
44 * @var array
45 */
46 protected $mParentLens;
47
48 /**
49 * @var TemplateParser
50 */
51 protected $templateParser;
52
53 function __construct( IContextSource $context, array $options ) {
54 parent::__construct( $context );
55
56 $msgs = [
57 'diff',
58 'hist',
59 'pipe-separator',
60 'uctop'
61 ];
62
63 foreach ( $msgs as $msg ) {
64 $this->messages[$msg] = $this->msg( $msg )->escaped();
65 }
66
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;
73
74 $this->deletedOnly = !empty( $options['deletedOnly'] );
75 $this->topOnly = !empty( $options['topOnly'] );
76 $this->newOnly = !empty( $options['newOnly'] );
77 $this->hideMinor = !empty( $options['hideMinor'] );
78
79 $year = isset( $options['year'] ) ? $options['year'] : false;
80 $month = isset( $options['month'] ) ? $options['month'] : false;
81 $this->getDateCond( $year, $month );
82
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();
89 }
90
91 function getDefaultQuery() {
92 $query = parent::getDefaultQuery();
93 $query['target'] = $this->target;
94
95 return $query;
96 }
97
98 /**
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.
101 *
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
106 */
107 function reallyDoQuery( $offset, $limit, $descending ) {
108 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
109 $offset,
110 $limit,
111 $descending
112 );
113
114 /*
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.
117 *
118 * Extension queries have to implement the navbar requirement as well. They should
119 * - have a column aliased as $pager->getIndexField()
120 * - have LIMIT set
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
123 *
124 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
125 *
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
131 */
132 $data = [ $this->mDb->select(
133 $tables, $fields, $conds, $fname, $options, $join_conds
134 ) ];
135 Hooks::run(
136 'ContribsPager::reallyDoQuery',
137 [ &$data, $this, $offset, $limit, $descending ]
138 );
139
140 $result = [];
141
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;
147 }
148 }
149
150 // sort results
151 if ( $descending ) {
152 ksort( $result );
153 } else {
154 krsort( $result );
155 }
156
157 // enforce limit
158 $result = array_slice( $result, 0, $limit );
159
160 // get rid of array keys
161 $result = array_values( $result );
162
163 return new FakeResultWrapper( $result );
164 }
165
166 function getQueryInfo() {
167 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
168
169 $user = $this->getUser();
170 $conds = array_merge( $userCond, $this->getNamespaceCond() );
171
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;
178 }
179
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();
184
185 $options = [];
186 if ( $index ) {
187 $options['USE INDEX'] = [ 'revision' => $index ];
188 }
189
190 $queryInfo = [
191 'tables' => $tables,
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' ]
197 ),
198 'conds' => $conds,
199 'options' => $options,
200 'join_conds' => $join_cond
201 ];
202
203 ChangeTags::modifyDisplayQuery(
204 $queryInfo['tables'],
205 $queryInfo['fields'],
206 $queryInfo['conds'],
207 $queryInfo['join_conds'],
208 $queryInfo['options'],
209 $this->tagFilter
210 );
211
212 // Avoid PHP 7.1 warning from passing $this by reference
213 $pager = $this;
214 Hooks::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
215
216 return $queryInfo;
217 }
218
219 function getUserCond() {
220 $condition = [];
221 $join_conds = [];
222 $tables = [ 'revision', 'page', 'user' ];
223 $index = false;
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'] = [
234 'LEFT JOIN', [
235 'ug_user = rev_user',
236 'ug_group' => $groupsWithBotPermission,
237 'ug_expiry IS NULL OR ug_expiry >= ' .
238 $this->mDb->addQuotes( $this->mDb->timestamp() )
239 ]
240 ];
241 }
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 ) );
247 } else {
248 $uid = User::idFromName( $this->target );
249 if ( $uid ) {
250 $condition['rev_user'] = $uid;
251 $index = 'user_timestamp';
252 } else {
253 $condition['rev_user_text'] = $this->target;
254 $index = 'usertext_timestamp';
255 }
256 }
257
258 if ( $this->deletedOnly ) {
259 $condition[] = 'rev_deleted != 0';
260 }
261
262 if ( $this->topOnly ) {
263 $condition[] = 'rev_id = page_latest';
264 }
265
266 if ( $this->newOnly ) {
267 $condition[] = 'rev_parent_id = 0';
268 }
269
270 if ( $this->hideMinor ) {
271 $condition[] = 'rev_minor_edit = 0';
272 }
273
274 return [ $tables, $index, $condition, $join_conds ];
275 }
276
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';
282
283 if ( !$this->associated ) {
284 return [ "page_namespace $eq_op $selectedNS" ];
285 }
286
287 $associatedNS = $this->mDb->addQuotes(
288 MWNamespace::getAssociated( $this->namespace )
289 );
290
291 return [
292 "page_namespace $eq_op $selectedNS " .
293 $bool_op .
294 " page_namespace $eq_op $associatedNS"
295 ];
296 }
297
298 return [];
299 }
300
301 function getIndexField() {
302 return 'rev_timestamp';
303 }
304
305 function doBatchLookups() {
306 # Do a link batch query
307 $this->mResult->seek( 0 );
308 $parentRevIds = [];
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;
315 }
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 );
321 }
322 $batch->add( $row->page_namespace, $row->page_title );
323 }
324 }
325 # Fetch rev_len for revisions not already scanned above
326 $this->mParentLens += Revision::getParentLengths(
327 $this->mDbSecondary,
328 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
329 );
330 $batch->execute();
331 $this->mResult->seek( 0 );
332 }
333
334 /**
335 * @return string
336 */
337 function getStartBody() {
338 return "<ul class=\"mw-contributions-list\">\n";
339 }
340
341 /**
342 * @return string
343 */
344 function getEndBody() {
345 return "</ul>\n";
346 }
347
348 /**
349 * Generates each row in the contributions list.
350 *
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.
355 *
356 * @todo This would probably look a lot nicer in a table.
357 * @param object $row
358 * @return string
359 */
360 function formatRow( $row ) {
361
362 $ret = '';
363 $classes = [];
364
365 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
366
367 /*
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.
373 */
374 MediaWiki\suppressWarnings();
375 try {
376 $rev = new Revision( $row );
377 $validRevision = (bool)$rev->getId();
378 } catch ( Exception $e ) {
379 $validRevision = false;
380 }
381 MediaWiki\restoreWarnings();
382
383 if ( $validRevision ) {
384 $classes = [];
385
386 $page = Title::newFromRow( $row );
387 $link = $linkRenderer->makeLink(
388 $page,
389 $page->getPrefixedText(),
390 [ 'class' => 'mw-contributions-title' ],
391 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
392 );
393 # Mark current revisions
394 $topmarktext = '';
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';
399 # Add rollback link
400 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
401 && $page->quickUserCan( 'edit', $user )
402 ) {
403 $this->preventClickjacking();
404 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
405 }
406 }
407 # Is there a visible previous revision?
408 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
409 $difftext = $linkRenderer->makeKnownLink(
410 $page,
411 new HtmlArmor( $this->messages['diff'] ),
412 [ 'class' => 'mw-changeslist-diff' ],
413 [
414 'diff' => 'prev',
415 'oldid' => $row->rev_id
416 ]
417 );
418 } else {
419 $difftext = $this->messages['diff'];
420 }
421 $histlink = $linkRenderer->makeKnownLink(
422 $page,
423 new HtmlArmor( $this->messages['hist'] ),
424 [ 'class' => 'mw-changeslist-history' ],
425 [ 'action' => 'history' ]
426 );
427
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> ';
435 } else {
436 $parentLen = 0;
437 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
438 $parentLen = $this->mParentLens[$row->rev_parent_id];
439 }
440
441 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
442 $chardiff .= ChangesList::showCharacterDifference(
443 $parentLen,
444 $row->rev_len,
445 $this->getContext()
446 );
447 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
448 }
449
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(
455 $page,
456 $date,
457 [ 'class' => 'mw-changeslist-date' ],
458 [ 'oldid' => intval( $row->rev_id ) ]
459 );
460 } else {
461 $d = htmlspecialchars( $date );
462 }
463 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
464 $d = '<span class="history-deleted">' . $d . '</span>';
465 }
466
467 # Show user names for /newbies as there may be different users.
468 # Note that only unprivileged users have rows with hidden user names excluded.
469 $userlink = '';
470 if ( $this->contribs == 'newbie' && !$rev->isDeleted( Revision::DELETED_USER ) ) {
471 $userlink = ' . . ' . $lang->getDirMark()
472 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
473 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
474 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
475 }
476
477 $flags = [];
478 if ( $rev->getParentId() === 0 ) {
479 $flags[] = ChangesList::flag( 'newpage' );
480 }
481
482 if ( $rev->isMinor() ) {
483 $flags[] = ChangesList::flag( 'minor' );
484 }
485
486 $del = Linker::getRevDeleteLink( $user, $rev, $page );
487 if ( $del !== '' ) {
488 $del .= ' ';
489 }
490
491 $diffHistLinks = $this->msg( 'parentheses' )
492 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
493 ->escaped();
494
495 # Tags, if any.
496 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
497 $row->ts_tags,
498 'contributions',
499 $this->getContext()
500 );
501 $classes = array_merge( $classes, $newClasses );
502
503 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
504
505 $templateParams = [
506 'del' => $del,
507 'timestamp' => $d,
508 'diffHistLinks' => $diffHistLinks,
509 'charDifference' => $chardiff,
510 'flags' => $flags,
511 'articleLink' => $link,
512 'userlink' => $userlink,
513 'logText' => $comment,
514 'topmarktext' => $topmarktext,
515 'tagSummary' => $tagSummary,
516 ];
517
518 # Denote if username is redacted for this edit
519 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
520 $templateParams['rev-deleted-user-contribs'] =
521 $this->msg( 'rev-deleted-user-contribs' )->escaped();
522 }
523
524 $ret = $this->templateParser->processTemplate(
525 'SpecialContributionsLine',
526 $templateParams
527 );
528 }
529
530 // Let extensions add data
531 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
532
533 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
534 // receiving empty rows?
535
536 if ( $classes === [] && $ret === '' ) {
537 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
538 return "<!-- Could not format Special:Contribution row. -->\n";
539 }
540
541 // FIXME: The signature of the ContributionsLineEnding hook makes it
542 // very awkward to move this LI wrapper into the template.
543 return Html::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
544 }
545
546 /**
547 * Overwrite Pager function and return a helpful comment
548 * @return string
549 */
550 function getSqlComment() {
551 if ( $this->namespace || $this->deletedOnly ) {
552 // potentially slow, see CR r58153
553 return 'contributions page filtered for namespace or RevisionDeleted edits';
554 } else {
555 return 'contributions page unfiltered';
556 }
557 }
558
559 protected function preventClickjacking() {
560 $this->preventClickjacking = true;
561 }
562
563 /**
564 * @return bool
565 */
566 public function getPreventClickjacking() {
567 return $this->preventClickjacking;
568 }
569 }