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