Revised styling of sister-search sidebar.
[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 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
232 '1' :
233 'ug_expiry IS NULL OR ug_expiry >= ' .
234 $this->mDb->addQuotes( $this->mDb->timestamp() )
235 ]
236 ];
237 }
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 ) );
243 } else {
244 $uid = User::idFromName( $this->target );
245 if ( $uid ) {
246 $condition['rev_user'] = $uid;
247 $index = 'user_timestamp';
248 } else {
249 $condition['rev_user_text'] = $this->target;
250 $index = 'usertext_timestamp';
251 }
252 }
253
254 if ( $this->deletedOnly ) {
255 $condition[] = 'rev_deleted != 0';
256 }
257
258 if ( $this->topOnly ) {
259 $condition[] = 'rev_id = page_latest';
260 }
261
262 if ( $this->newOnly ) {
263 $condition[] = 'rev_parent_id = 0';
264 }
265
266 if ( $this->hideMinor ) {
267 $condition[] = 'rev_minor_edit = 0';
268 }
269
270 return [ $tables, $index, $condition, $join_conds ];
271 }
272
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';
278
279 if ( !$this->associated ) {
280 return [ "page_namespace $eq_op $selectedNS" ];
281 }
282
283 $associatedNS = $this->mDb->addQuotes(
284 MWNamespace::getAssociated( $this->namespace )
285 );
286
287 return [
288 "page_namespace $eq_op $selectedNS " .
289 $bool_op .
290 " page_namespace $eq_op $associatedNS"
291 ];
292 }
293
294 return [];
295 }
296
297 function getIndexField() {
298 return 'rev_timestamp';
299 }
300
301 function doBatchLookups() {
302 # Do a link batch query
303 $this->mResult->seek( 0 );
304 $parentRevIds = [];
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;
311 }
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 );
317 }
318 $batch->add( $row->page_namespace, $row->page_title );
319 }
320 }
321 # Fetch rev_len for revisions not already scanned above
322 $this->mParentLens += Revision::getParentLengths(
323 $this->mDbSecondary,
324 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
325 );
326 $batch->execute();
327 $this->mResult->seek( 0 );
328 }
329
330 /**
331 * @return string
332 */
333 function getStartBody() {
334 return "<ul class=\"mw-contributions-list\">\n";
335 }
336
337 /**
338 * @return string
339 */
340 function getEndBody() {
341 return "</ul>\n";
342 }
343
344 /**
345 * Generates each row in the contributions list.
346 *
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.
351 *
352 * @todo This would probably look a lot nicer in a table.
353 * @param object $row
354 * @return string
355 */
356 function formatRow( $row ) {
357
358 $ret = '';
359 $classes = [];
360
361 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
362
363 /*
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.
369 */
370 MediaWiki\suppressWarnings();
371 try {
372 $rev = new Revision( $row );
373 $validRevision = (bool)$rev->getId();
374 } catch ( Exception $e ) {
375 $validRevision = false;
376 }
377 MediaWiki\restoreWarnings();
378
379 if ( $validRevision ) {
380 $classes = [];
381
382 $page = Title::newFromRow( $row );
383 $link = $linkRenderer->makeLink(
384 $page,
385 $page->getPrefixedText(),
386 [ 'class' => 'mw-contributions-title' ],
387 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
388 );
389 # Mark current revisions
390 $topmarktext = '';
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';
395 # Add rollback link
396 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
397 && $page->quickUserCan( 'edit', $user )
398 ) {
399 $this->preventClickjacking();
400 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
401 }
402 }
403 # Is there a visible previous revision?
404 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
405 $difftext = $linkRenderer->makeKnownLink(
406 $page,
407 new HtmlArmor( $this->messages['diff'] ),
408 [ 'class' => 'mw-changeslist-diff' ],
409 [
410 'diff' => 'prev',
411 'oldid' => $row->rev_id
412 ]
413 );
414 } else {
415 $difftext = $this->messages['diff'];
416 }
417 $histlink = $linkRenderer->makeKnownLink(
418 $page,
419 new HtmlArmor( $this->messages['hist'] ),
420 [ 'class' => 'mw-changeslist-history' ],
421 [ 'action' => 'history' ]
422 );
423
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> ';
431 } else {
432 $parentLen = 0;
433 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
434 $parentLen = $this->mParentLens[$row->rev_parent_id];
435 }
436
437 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
438 $chardiff .= ChangesList::showCharacterDifference(
439 $parentLen,
440 $row->rev_len,
441 $this->getContext()
442 );
443 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
444 }
445
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(
451 $page,
452 $date,
453 [ 'class' => 'mw-changeslist-date' ],
454 [ 'oldid' => intval( $row->rev_id ) ]
455 );
456 } else {
457 $d = htmlspecialchars( $date );
458 }
459 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
460 $d = '<span class="history-deleted">' . $d . '</span>';
461 }
462
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() . ' ';
470 } else {
471 $userlink = '';
472 }
473
474 $flags = [];
475 if ( $rev->getParentId() === 0 ) {
476 $flags[] = ChangesList::flag( 'newpage' );
477 }
478
479 if ( $rev->isMinor() ) {
480 $flags[] = ChangesList::flag( 'minor' );
481 }
482
483 $del = Linker::getRevDeleteLink( $user, $rev, $page );
484 if ( $del !== '' ) {
485 $del .= ' ';
486 }
487
488 $diffHistLinks = $this->msg( 'parentheses' )
489 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
490 ->escaped();
491
492 # Tags, if any.
493 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
494 $row->ts_tags,
495 'contributions',
496 $this->getContext()
497 );
498 $classes = array_merge( $classes, $newClasses );
499
500 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
501
502 $templateParams = [
503 'del' => $del,
504 'timestamp' => $d,
505 'diffHistLinks' => $diffHistLinks,
506 'charDifference' => $chardiff,
507 'flags' => $flags,
508 'articleLink' => $link,
509 'userlink' => $userlink,
510 'logText' => $comment,
511 'topmarktext' => $topmarktext,
512 'tagSummary' => $tagSummary,
513 ];
514
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();
519 }
520
521 $templateParser = new TemplateParser();
522 $ret = $templateParser->processTemplate(
523 'SpecialContributionsLine',
524 $templateParams
525 );
526 }
527
528 // Let extensions add data
529 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
530
531 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
532 // receiving empty rows?
533
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";
537 }
538
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";
542 }
543
544 /**
545 * Overwrite Pager function and return a helpful comment
546 * @return string
547 */
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';
552 } else {
553 return 'contributions page unfiltered';
554 }
555 }
556
557 protected function preventClickjacking() {
558 $this->preventClickjacking = true;
559 }
560
561 /**
562 * @return bool
563 */
564 public function getPreventClickjacking() {
565 return $this->preventClickjacking;
566 }
567 }