Merge "Drop index oi_name_archive_name on table oldimage"
[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
30 class ContribsPager extends ReverseChronologicalPager {
31
32 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
33 public $messages;
34 public $target;
35 public $namespace = '';
36 public $mDb;
37 public $preventClickjacking = false;
38
39 /** @var IDatabase */
40 public $mDbSecondary;
41
42 /**
43 * @var array
44 */
45 protected $mParentLens;
46
47 function __construct( IContextSource $context, array $options ) {
48 parent::__construct( $context );
49
50 $msgs = [
51 'diff',
52 'hist',
53 'pipe-separator',
54 'uctop'
55 ];
56
57 foreach ( $msgs as $msg ) {
58 $this->messages[$msg] = $this->msg( $msg )->escaped();
59 }
60
61 $this->target = isset( $options['target'] ) ? $options['target'] : '';
62 $this->contribs = isset( $options['contribs'] ) ? $options['contribs'] : 'users';
63 $this->namespace = isset( $options['namespace'] ) ? $options['namespace'] : '';
64 $this->tagFilter = isset( $options['tagfilter'] ) ? $options['tagfilter'] : false;
65 $this->nsInvert = isset( $options['nsInvert'] ) ? $options['nsInvert'] : false;
66 $this->associated = isset( $options['associated'] ) ? $options['associated'] : false;
67
68 $this->deletedOnly = !empty( $options['deletedOnly'] );
69 $this->topOnly = !empty( $options['topOnly'] );
70 $this->newOnly = !empty( $options['newOnly'] );
71 $this->hideMinor = !empty( $options['hideMinor'] );
72
73 $year = isset( $options['year'] ) ? $options['year'] : false;
74 $month = isset( $options['month'] ) ? $options['month'] : false;
75 $this->getDateCond( $year, $month );
76
77 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
78 // with extra user based indexes or partioning by user. The additional metadata
79 // queries should use a regular replica DB since the lookup pattern is not all by user.
80 $this->mDbSecondary = wfGetDB( DB_REPLICA ); // any random replica DB
81 $this->mDb = wfGetDB( DB_REPLICA, 'contributions' );
82 }
83
84 function getDefaultQuery() {
85 $query = parent::getDefaultQuery();
86 $query['target'] = $this->target;
87
88 return $query;
89 }
90
91 /**
92 * This method basically executes the exact same code as the parent class, though with
93 * a hook added, to allow extensions to add additional queries.
94 *
95 * @param string $offset Index offset, inclusive
96 * @param int $limit Exact query limit
97 * @param bool $descending Query direction, false for ascending, true for descending
98 * @return ResultWrapper
99 */
100 function reallyDoQuery( $offset, $limit, $descending ) {
101 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
102 $offset,
103 $limit,
104 $descending
105 );
106
107 /*
108 * This hook will allow extensions to add in additional queries, so they can get their data
109 * in My Contributions as well. Extensions should append their results to the $data array.
110 *
111 * Extension queries have to implement the navbar requirement as well. They should
112 * - have a column aliased as $pager->getIndexField()
113 * - have LIMIT set
114 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
115 * - have the ORDER BY specified based upon the details provided by the navbar
116 *
117 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
118 *
119 * &$data: an array of results of all contribs queries
120 * $pager: the ContribsPager object hooked into
121 * $offset: see phpdoc above
122 * $limit: see phpdoc above
123 * $descending: see phpdoc above
124 */
125 $data = [ $this->mDb->select(
126 $tables, $fields, $conds, $fname, $options, $join_conds
127 ) ];
128 Hooks::run(
129 'ContribsPager::reallyDoQuery',
130 [ &$data, $this, $offset, $limit, $descending ]
131 );
132
133 $result = [];
134
135 // loop all results and collect them in an array
136 foreach ( $data as $query ) {
137 foreach ( $query as $i => $row ) {
138 // use index column as key, allowing us to easily sort in PHP
139 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
140 }
141 }
142
143 // sort results
144 if ( $descending ) {
145 ksort( $result );
146 } else {
147 krsort( $result );
148 }
149
150 // enforce limit
151 $result = array_slice( $result, 0, $limit );
152
153 // get rid of array keys
154 $result = array_values( $result );
155
156 return new FakeResultWrapper( $result );
157 }
158
159 function getQueryInfo() {
160 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
161
162 $user = $this->getUser();
163 $conds = array_merge( $userCond, $this->getNamespaceCond() );
164
165 // Paranoia: avoid brute force searches (T19342)
166 if ( !$user->isAllowed( 'deletedhistory' ) ) {
167 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0';
168 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
169 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::SUPPRESSED_USER ) .
170 ' != ' . Revision::SUPPRESSED_USER;
171 }
172
173 # Don't include orphaned revisions
174 $join_cond['page'] = Revision::pageJoinCond();
175 # Get the current user name for accounts
176 $join_cond['user'] = Revision::userJoinCond();
177
178 $options = [];
179 if ( $index ) {
180 $options['USE INDEX'] = [ 'revision' => $index ];
181 }
182
183 $queryInfo = [
184 'tables' => $tables,
185 'fields' => array_merge(
186 Revision::selectFields(),
187 Revision::selectUserFields(),
188 [ 'page_namespace', 'page_title', 'page_is_new',
189 'page_latest', 'page_is_redirect', 'page_len' ]
190 ),
191 'conds' => $conds,
192 'options' => $options,
193 'join_conds' => $join_cond
194 ];
195
196 ChangeTags::modifyDisplayQuery(
197 $queryInfo['tables'],
198 $queryInfo['fields'],
199 $queryInfo['conds'],
200 $queryInfo['join_conds'],
201 $queryInfo['options'],
202 $this->tagFilter
203 );
204
205 // Avoid PHP 7.1 warning from passing $this by reference
206 $pager = $this;
207 Hooks::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
208
209 return $queryInfo;
210 }
211
212 function getUserCond() {
213 $condition = [];
214 $join_conds = [];
215 $tables = [ 'revision', 'page', 'user' ];
216 $index = false;
217 if ( $this->contribs == 'newbie' ) {
218 $max = $this->mDb->selectField( 'user', 'max(user_id)', false, __METHOD__ );
219 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
220 # ignore local groups with the bot right
221 # @todo FIXME: Global groups may have 'bot' rights
222 $groupsWithBotPermission = User::getGroupsWithPermission( 'bot' );
223 if ( count( $groupsWithBotPermission ) ) {
224 $tables[] = 'user_groups';
225 $condition[] = 'ug_group IS NULL';
226 $join_conds['user_groups'] = [
227 'LEFT JOIN', [
228 'ug_user = rev_user',
229 'ug_group' => $groupsWithBotPermission,
230 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
231 '1' :
232 'ug_expiry IS NULL OR ug_expiry >= ' .
233 $this->mDb->addQuotes( $this->mDb->timestamp() )
234 ]
235 ];
236 }
237 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
238 // a timestamp offset far in the past such that there are no edits by users with user_ids in
239 // the range, we would end up scanning all revisions from that offset until start of time.
240 $condition[] = 'rev_timestamp > ' .
241 $this->mDb->addQuotes( $this->mDb->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
242 } else {
243 $uid = User::idFromName( $this->target );
244 if ( $uid ) {
245 $condition['rev_user'] = $uid;
246 $index = 'user_timestamp';
247 } else {
248 $condition['rev_user_text'] = $this->target;
249 $index = 'usertext_timestamp';
250 }
251 }
252
253 if ( $this->deletedOnly ) {
254 $condition[] = 'rev_deleted != 0';
255 }
256
257 if ( $this->topOnly ) {
258 $condition[] = 'rev_id = page_latest';
259 }
260
261 if ( $this->newOnly ) {
262 $condition[] = 'rev_parent_id = 0';
263 }
264
265 if ( $this->hideMinor ) {
266 $condition[] = 'rev_minor_edit = 0';
267 }
268
269 return [ $tables, $index, $condition, $join_conds ];
270 }
271
272 function getNamespaceCond() {
273 if ( $this->namespace !== '' ) {
274 $selectedNS = $this->mDb->addQuotes( $this->namespace );
275 $eq_op = $this->nsInvert ? '!=' : '=';
276 $bool_op = $this->nsInvert ? 'AND' : 'OR';
277
278 if ( !$this->associated ) {
279 return [ "page_namespace $eq_op $selectedNS" ];
280 }
281
282 $associatedNS = $this->mDb->addQuotes(
283 MWNamespace::getAssociated( $this->namespace )
284 );
285
286 return [
287 "page_namespace $eq_op $selectedNS " .
288 $bool_op .
289 " page_namespace $eq_op $associatedNS"
290 ];
291 }
292
293 return [];
294 }
295
296 function getIndexField() {
297 return 'rev_timestamp';
298 }
299
300 function doBatchLookups() {
301 # Do a link batch query
302 $this->mResult->seek( 0 );
303 $parentRevIds = [];
304 $this->mParentLens = [];
305 $batch = new LinkBatch();
306 # Give some pointers to make (last) links
307 foreach ( $this->mResult as $row ) {
308 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
309 $parentRevIds[] = $row->rev_parent_id;
310 }
311 if ( isset( $row->rev_id ) ) {
312 $this->mParentLens[$row->rev_id] = $row->rev_len;
313 if ( $this->contribs === 'newbie' ) { // multiple users
314 $batch->add( NS_USER, $row->user_name );
315 $batch->add( NS_USER_TALK, $row->user_name );
316 }
317 $batch->add( $row->page_namespace, $row->page_title );
318 }
319 }
320 # Fetch rev_len for revisions not already scanned above
321 $this->mParentLens += Revision::getParentLengths(
322 $this->mDbSecondary,
323 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
324 );
325 $batch->execute();
326 $this->mResult->seek( 0 );
327 }
328
329 /**
330 * @return string
331 */
332 function getStartBody() {
333 return "<ul class=\"mw-contributions-list\">\n";
334 }
335
336 /**
337 * @return string
338 */
339 function getEndBody() {
340 return "</ul>\n";
341 }
342
343 /**
344 * Generates each row in the contributions list.
345 *
346 * Contributions which are marked "top" are currently on top of the history.
347 * For these contributions, a [rollback] link is shown for users with roll-
348 * back privileges. The rollback link restores the most recent version that
349 * was not written by the target user.
350 *
351 * @todo This would probably look a lot nicer in a table.
352 * @param object $row
353 * @return string
354 */
355 function formatRow( $row ) {
356
357 $ret = '';
358 $classes = [];
359
360 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
361
362 /*
363 * There may be more than just revision rows. To make sure that we'll only be processing
364 * revisions here, let's _try_ to build a revision out of our row (without displaying
365 * notices though) and then trying to grab data from the built object. If we succeed,
366 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
367 * to extensions to subscribe to the hook to parse the row.
368 */
369 MediaWiki\suppressWarnings();
370 try {
371 $rev = new Revision( $row );
372 $validRevision = (bool)$rev->getId();
373 } catch ( Exception $e ) {
374 $validRevision = false;
375 }
376 MediaWiki\restoreWarnings();
377
378 if ( $validRevision ) {
379 $classes = [];
380
381 $page = Title::newFromRow( $row );
382 $link = $linkRenderer->makeLink(
383 $page,
384 $page->getPrefixedText(),
385 [ 'class' => 'mw-contributions-title' ],
386 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
387 );
388 # Mark current revisions
389 $topmarktext = '';
390 $user = $this->getUser();
391 if ( $row->rev_id === $row->page_latest ) {
392 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
393 $classes[] = 'mw-contributions-current';
394 # Add rollback link
395 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
396 && $page->quickUserCan( 'edit', $user )
397 ) {
398 $this->preventClickjacking();
399 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
400 }
401 }
402 # Is there a visible previous revision?
403 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
404 $difftext = $linkRenderer->makeKnownLink(
405 $page,
406 new HtmlArmor( $this->messages['diff'] ),
407 [ 'class' => 'mw-changeslist-diff' ],
408 [
409 'diff' => 'prev',
410 'oldid' => $row->rev_id
411 ]
412 );
413 } else {
414 $difftext = $this->messages['diff'];
415 }
416 $histlink = $linkRenderer->makeKnownLink(
417 $page,
418 new HtmlArmor( $this->messages['hist'] ),
419 [ 'class' => 'mw-changeslist-history' ],
420 [ 'action' => 'history' ]
421 );
422
423 if ( $row->rev_parent_id === null ) {
424 // For some reason rev_parent_id isn't populated for this row.
425 // Its rumoured this is true on wikipedia for some revisions (T36922).
426 // Next best thing is to have the total number of bytes.
427 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
428 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
429 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
430 } else {
431 $parentLen = 0;
432 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
433 $parentLen = $this->mParentLens[$row->rev_parent_id];
434 }
435
436 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
437 $chardiff .= ChangesList::showCharacterDifference(
438 $parentLen,
439 $row->rev_len,
440 $this->getContext()
441 );
442 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
443 }
444
445 $lang = $this->getLanguage();
446 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true );
447 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
448 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
449 $d = $linkRenderer->makeKnownLink(
450 $page,
451 $date,
452 [ 'class' => 'mw-changeslist-date' ],
453 [ 'oldid' => intval( $row->rev_id ) ]
454 );
455 } else {
456 $d = htmlspecialchars( $date );
457 }
458 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
459 $d = '<span class="history-deleted">' . $d . '</span>';
460 }
461
462 # Show user names for /newbies as there may be different users.
463 # Note that we already excluded rows with hidden user names.
464 if ( $this->contribs == 'newbie' ) {
465 $userlink = ' . . ' . $lang->getDirMark()
466 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
467 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
468 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
469 } else {
470 $userlink = '';
471 }
472
473 $flags = [];
474 if ( $rev->getParentId() === 0 ) {
475 $flags[] = ChangesList::flag( 'newpage' );
476 }
477
478 if ( $rev->isMinor() ) {
479 $flags[] = ChangesList::flag( 'minor' );
480 }
481
482 $del = Linker::getRevDeleteLink( $user, $rev, $page );
483 if ( $del !== '' ) {
484 $del .= ' ';
485 }
486
487 $diffHistLinks = $this->msg( 'parentheses' )
488 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
489 ->escaped();
490
491 # Tags, if any.
492 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
493 $row->ts_tags,
494 'contributions',
495 $this->getContext()
496 );
497 $classes = array_merge( $classes, $newClasses );
498
499 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
500
501 $templateParams = [
502 'del' => $del,
503 'timestamp' => $d,
504 'diffHistLinks' => $diffHistLinks,
505 'charDifference' => $chardiff,
506 'flags' => $flags,
507 'articleLink' => $link,
508 'userlink' => $userlink,
509 'logText' => $comment,
510 'topmarktext' => $topmarktext,
511 'tagSummary' => $tagSummary,
512 ];
513
514 # Denote if username is redacted for this edit
515 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
516 $templateParams['rev-deleted-user-contribs'] =
517 $this->msg( 'rev-deleted-user-contribs' )->escaped();
518 }
519
520 $templateParser = new TemplateParser();
521 $ret = $templateParser->processTemplate(
522 'SpecialContributionsLine',
523 $templateParams
524 );
525 }
526
527 // Let extensions add data
528 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
529
530 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
531 // receiving empty rows?
532
533 if ( $classes === [] && $ret === '' ) {
534 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
535 return "<!-- Could not format Special:Contribution row. -->\n";
536 }
537
538 // FIXME: The signature of the ContributionsLineEnding hook makes it
539 // very awkward to move this LI wrapper into the template.
540 return Html::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
541 }
542
543 /**
544 * Overwrite Pager function and return a helpful comment
545 * @return string
546 */
547 function getSqlComment() {
548 if ( $this->namespace || $this->deletedOnly ) {
549 // potentially slow, see CR r58153
550 return 'contributions page filtered for namespace or RevisionDeleted edits';
551 } else {
552 return 'contributions page unfiltered';
553 }
554 }
555
556 protected function preventClickjacking() {
557 $this->preventClickjacking = true;
558 }
559
560 /**
561 * @return bool
562 */
563 public function getPreventClickjacking() {
564 return $this->preventClickjacking;
565 }
566 }