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