Debian Codegraph @

includes/specialpage/ContributionsSpecialPage.php

raw symbols SCIP
1 <?php
2 /**
3 * Implements Special:Contributions
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 namespace MediaWiki\SpecialPage;
25
26 use LogEventsList;
27 use MediaWiki\Block\Block;
28 use MediaWiki\Block\DatabaseBlockStore;
29 use MediaWiki\Html\Html;
30 use MediaWiki\HTMLForm\Field\HTMLMultiSelectField;
31 use MediaWiki\HTMLForm\HTMLForm;
32 use MediaWiki\MainConfigNames;
33 use MediaWiki\Pager\ContribsPager;
34 use MediaWiki\Pager\ContributionsPager;
35 use MediaWiki\Permissions\PermissionManager;
36 use MediaWiki\PoolCounter\PoolCounterWorkViaCallback;
37 use MediaWiki\Specials\SpecialUserRights;
38 use MediaWiki\Status\Status;
39 use MediaWiki\Title\NamespaceInfo;
40 use MediaWiki\Title\Title;
41 use MediaWiki\User\ExternalUserNames;
42 use MediaWiki\User\Options\UserOptionsLookup;
43 use MediaWiki\User\User;
44 use MediaWiki\User\UserFactory;
45 use MediaWiki\User\UserIdentity;
46 use MediaWiki\User\UserIdentityLookup;
47 use MediaWiki\User\UserNamePrefixSearch;
48 use MediaWiki\User\UserNameUtils;
49 use MediaWiki\User\UserRigorOptions;
50 use Wikimedia\IPUtils;
51 use Wikimedia\Rdbms\IConnectionProvider;
52
53 /**
54 * Show user contributions in a paged list.
55 *
56 * This was refactored out from SpecialContributions to make it easier to
57 * add new special pages with similar functionality and similar output.
58 * Hooks formerly for SpecialContributions are run here to avoid needing
59 * to duplicate hooks for each subclass.
60 *
61 * The subclass must provide an implementation of ::getPager, and may
62 * disable syndication feed functionality by overriding ::providesFeeds.
63 *
64 * @stable to extend
65 * @ingroup SpecialPage
66 * @since 1.43 Refactored from SpecialContributions
67 */
68 class ContributionsSpecialPage extends IncludableSpecialPage {
69 /** @var array */
70 protected $opts = [];
71 /** @var bool */
72 protected $formErrors = false;
73
74 protected IConnectionProvider $dbProvider;
75 protected NamespaceInfo $namespaceInfo;
76 protected PermissionManager $permissionManager;
77 protected UserNameUtils $userNameUtils;
78 protected UserNamePrefixSearch $userNamePrefixSearch;
79 protected UserOptionsLookup $userOptionsLookup;
80 protected UserFactory $userFactory;
81 protected UserIdentityLookup $userIdentityLookup;
82 protected DatabaseBlockStore $blockStore;
83
84 /**
85 * @param PermissionManager $permissionManager
86 * @param IConnectionProvider $dbProvider
87 * @param NamespaceInfo $namespaceInfo
88 * @param UserNameUtils $userNameUtils
89 * @param UserNamePrefixSearch $userNamePrefixSearch
90 * @param UserOptionsLookup $userOptionsLookup
91 * @param UserFactory $userFactory
92 * @param UserIdentityLookup $userIdentityLookup
93 * @param DatabaseBlockStore $blockStore
94 * @param string $name
95 * @param string $restriction
96 */
97 public function __construct(
98 PermissionManager $permissionManager,
99 IConnectionProvider $dbProvider,
100 NamespaceInfo $namespaceInfo,
101 UserNameUtils $userNameUtils,
102 UserNamePrefixSearch $userNamePrefixSearch,
103 UserOptionsLookup $userOptionsLookup,
104 UserFactory $userFactory,
105 UserIdentityLookup $userIdentityLookup,
106 DatabaseBlockStore $blockStore,
107 $name,
108 $restriction = ''
109 ) {
110 parent::__construct( $name, $restriction );
111 $this->permissionManager = $permissionManager;
112 $this->dbProvider = $dbProvider;
113 $this->namespaceInfo = $namespaceInfo;
114 $this->userNameUtils = $userNameUtils;
115 $this->userNamePrefixSearch = $userNamePrefixSearch;
116 $this->userOptionsLookup = $userOptionsLookup;
117 $this->userFactory = $userFactory;
118 $this->userIdentityLookup = $userIdentityLookup;
119 $this->blockStore = $blockStore;
120 }
121
122 /**
123 * @inheritDoc
124 */
125 public function execute( $par ) {
126 $this->setHeaders();
127 $this->outputHeader();
128 $this->checkPermissions();
129 $out = $this->getOutput();
130 // Modules required for viewing the list of contributions (also when included on other pages)
131 $out->addModuleStyles( [
132 'jquery.makeCollapsible.styles',
133 'mediawiki.interface.helpers.styles',
134 'mediawiki.special',
135 'mediawiki.special.changeslist',
136 ] );
137 $out->addBodyClasses( 'mw-special-ContributionsSpecialPage' );
138 $out->addModules( [
139 // Certain skins e.g. Minerva might have disabled this module.
140 'mediawiki.page.ready'
141 ] );
142 $this->addHelpLink( 'Help:User contributions' );
143
144 $request = $this->getRequest();
145
146 $target = $par ?? $request->getVal( 'target', '' );
147 '@phan-var string $target'; // getVal does not return null here
148
149 $this->opts['deletedOnly'] = $request->getBool( 'deletedOnly' );
150
151 // Explicitly check for empty string as this needs to account for
152 // the rare case where the target parameter is '0' which is a valid
153 // target but resolves to false in boolean context (T379515).
154 if ( $target === '' ) {
155 $out->addHTML( $this->getForm( $this->opts ) );
156
157 return;
158 }
159
160 $user = $this->getUser();
161
162 $this->opts['limit'] = $request->getInt( 'limit', $this->userOptionsLookup->getIntOption( $user, 'rclimit' ) );
163 $this->opts['target'] = $target;
164 $this->opts['topOnly'] = $request->getBool( 'topOnly' );
165 $this->opts['newOnly'] = $request->getBool( 'newOnly' );
166 $this->opts['hideMinor'] = $request->getBool( 'hideMinor' );
167
168 $ns = $request->getVal( 'namespace', null );
169 if ( $ns !== null && $ns !== '' && $ns !== 'all' ) {
170 $this->opts['namespace'] = intval( $ns );
171 } else {
172 $this->opts['namespace'] = '';
173 }
174
175 // Backwards compatibility: Before using OOUI form the old HTML form had
176 // fields for nsInvert and associated. These have now been replaced with the
177 // wpFilters query string parameters. These are retained to keep old URIs working.
178 $this->opts['associated'] = $request->getBool( 'associated' );
179 $this->opts['nsInvert'] = (bool)$request->getVal( 'nsInvert' );
180 $nsFilters = $request->getArray( 'wpfilters', null );
181 if ( $nsFilters !== null ) {
182 $this->opts['associated'] = in_array( 'associated', $nsFilters );
183 $this->opts['nsInvert'] = in_array( 'nsInvert', $nsFilters );
184 }
185
186 $this->opts['tagfilter'] = array_filter( explode(
187 '|',
188 (string)$request->getVal( 'tagfilter' )
189 ), static function ( $el ) {
190 return $el !== '';
191 } );
192 $this->opts['tagInvert'] = $request->getBool( 'tagInvert' );
193
194 // Allows reverts to have the bot flag in recent changes. It is just here to
195 // be passed in the form at the top of the page
196 if ( $this->permissionManager->userHasRight( $user, 'markbotedits' ) && $request->getBool( 'bot' ) ) {
197 $this->opts['bot'] = '1';
198 }
199
200 $this->opts['year'] = $request->getIntOrNull( 'year' );
201 $this->opts['month'] = $request->getIntOrNull( 'month' );
202 $this->opts['start'] = $request->getVal( 'start' );
203 $this->opts['end'] = $request->getVal( 'end' );
204
205 $notExternal = !ExternalUserNames::isExternal( $target );
206 if ( $notExternal ) {
207 $nt = Title::makeTitleSafe( NS_USER, $target );
208 if ( !$nt ) {
209 $out->addHTML( $this->getForm( $this->opts ) );
210 return;
211 }
212 $target = $nt->getText();
213 if ( IPUtils::isValidRange( $target ) ) {
214 $target = IPUtils::sanitizeRange( $target );
215 }
216 }
217
218 $userObj = $this->userFactory->newFromName( $target, UserRigorOptions::RIGOR_NONE );
219 if ( !$userObj ) {
220 $out->addHTML( $this->getForm( $this->opts ) );
221 return;
222 }
223 $out->addSubtitle( $this->contributionsSub( $userObj, $target ) );
224 $out->setPageTitleMsg(
225 $this->msg( $this->getResultsPageTitleMessageKey( $userObj ) )
226 ->rawParams( Html::element( 'bdi', [], $target ) )
227 );
228
229 # For IP ranges, we want the contributionsSub, but not the skin-dependent
230 # links under 'Tools', which may include irrelevant links like 'Logs'.
231 if ( $notExternal && !IPUtils::isValidRange( $target ) &&
232 ( $this->userNameUtils->isIP( $target ) || $userObj->isRegistered() )
233 ) {
234 // Don't add non-existent users, because hidden users
235 // that we add here will be removed later to pretend
236 // that they don't exist, and if users that actually don't
237 // exist are added here and then not removed, it exposes
238 // which users exist and are hidden vs. which actually don't
239 // exist. But, do set the relevant user for single IPs.
240 $this->getSkin()->setRelevantUser( $userObj );
241 }
242
243 $this->opts = ContribsPager::processDateFilter( $this->opts );
244
245 if ( $this->opts['namespace'] !== '' && $this->opts['namespace'] < NS_MAIN ) {
246 $this->getOutput()->wrapWikiMsg(
247 "<div class=\"mw-negative-namespace-not-supported error\">\n\$1\n</div>",
248 [ 'negative-namespace-not-supported' ]
249 );
250 $out->addHTML( $this->getForm( $this->opts ) );
251 return;
252 }
253
254 if ( $this->providesFeeds() ) {
255 $feedType = $request->getVal( 'feed' );
256
257 $feedParams = [
258 'action' => 'feedcontributions',
259 'user' => $target,
260 ];
261 if ( $this->opts['topOnly'] ) {
262 $feedParams['toponly'] = true;
263 }
264 if ( $this->opts['newOnly'] ) {
265 $feedParams['newonly'] = true;
266 }
267 if ( $this->opts['hideMinor'] ) {
268 $feedParams['hideminor'] = true;
269 }
270 if ( $this->opts['deletedOnly'] ) {
271 $feedParams['deletedonly'] = true;
272 }
273
274 if ( $this->opts['tagfilter'] !== [] ) {
275 $feedParams['tagfilter'] = $this->opts['tagfilter'];
276 }
277 if ( $this->opts['namespace'] !== '' ) {
278 $feedParams['namespace'] = $this->opts['namespace'];
279 }
280 // Don't use year and month for the feed URL, but pass them on if
281 // we redirect to API (if $feedType is specified)
282 if ( $feedType && isset( $this->opts['year'] ) ) {
283 $feedParams['year'] = $this->opts['year'];
284 }
285 if ( $feedType && isset( $this->opts['month'] ) ) {
286 $feedParams['month'] = $this->opts['month'];
287 }
288
289 if ( $feedType ) {
290 // Maintain some level of backwards compatibility
291 // If people request feeds using the old parameters, redirect to API
292 $feedParams['feedformat'] = $feedType;
293 $url = wfAppendQuery( wfScript( 'api' ), $feedParams );
294
295 $out->redirect( $url, '301' );
296
297 return;
298 }
299
300 // Add RSS/atom links
301 $this->addFeedLinks( $feedParams );
302 }
303
304 if ( $this->getHookRunner()->onSpecialContributionsBeforeMainOutput(
305 $notExternal ? $userObj->getId() : 0, $userObj, $this )
306 ) {
307 $out->addHTML( $this->getForm( $this->opts ) );
308 if ( $this->formErrors ) {
309 return;
310 }
311 // We want a pure UserIdentity for imported actors, so the first letter
312 // of them is in lowercase and queryable.
313 $userIdentity = $notExternal ? $userObj :
314 $this->userIdentityLookup->getUserIdentityByName( $target ) ?? $userObj;
315 $pager = $this->getPager( $userIdentity );
316 if ( IPUtils::isValidRange( $target ) &&
317 !ContribsPager::isQueryableRange( $target, $this->getConfig() )
318 ) {
319 // Valid range, but outside CIDR limit.
320 $limits = $this->getConfig()->get( MainConfigNames::RangeContributionsCIDRLimit );
321 $limit = $limits[ IPUtils::isIPv4( $target ) ? 'IPv4' : 'IPv6' ];
322 $out->addWikiMsg( 'sp-contributions-outofrange', $limit );
323 } else {
324 // @todo We just want a wiki ID here, not a "DB domain", but
325 // current status of MediaWiki conflates the two. See T235955.
326 $poolKey = $this->dbProvider->getReplicaDatabase()->getDomainID() . ':Special' . $this->mName . ':';
327 if ( $this->getUser()->isAnon() ) {
328 $poolKey .= 'a:' . $this->getUser()->getName();
329 } else {
330 $poolKey .= 'u:' . $this->getUser()->getId();
331 }
332 $work = new PoolCounterWorkViaCallback( 'Special' . $this->mName, $poolKey, [
333 'doWork' => function () use ( $pager, $out, $target ) {
334 # Show a message about replica DB lag, if applicable
335 $lag = $pager->getDatabase()->getSessionLagStatus()['lag'];
336 if ( $lag > 0 ) {
337 $out->showLagWarning( $lag );
338 }
339
340 $output = $pager->getBody();
341 if ( !$this->including() ) {
342 $output = $pager->getNavigationBar() .
343 $output .
344 $pager->getNavigationBar();
345 }
346 $out->addHTML( $output );
347 },
348 'error' => function () use ( $out ) {
349 $msg = $this->getUser()->isAnon()
350 ? 'sp-contributions-concurrency-ip'
351 : 'sp-contributions-concurrency-user';
352 $out->addHTML(
353 Html::errorBox(
354 $out->msg( $msg )->parse()
355 )
356 );
357 }
358 ] );
359 $work->execute();
360 }
361
362 $out->setPreventClickjacking( $pager->getPreventClickjacking() );
363
364 # Show the appropriate "footer" message - WHOIS tools, etc.
365 if ( IPUtils::isValidRange( $target ) &&
366 ContribsPager::isQueryableRange( $target, $this->getConfig() )
367 ) {
368 $message = 'sp-contributions-footer-anon-range';
369 } elseif ( IPUtils::isIPAddress( $target ) ) {
370 $message = 'sp-contributions-footer-anon';
371 } elseif ( $userObj->isAnon() ) {
372 // No message for non-existing users
373 $message = '';
374 } elseif ( $userObj->isHidden() &&
375 !$this->permissionManager->userHasRight( $this->getUser(), 'hideuser' )
376 ) {
377 // User is registered, but make sure that the viewer can't see them, to avoid
378 // having different behavior for missing and hidden users; see T120883
379 $message = '';
380 } else {
381 // Not hidden, or hidden but the viewer can still see it
382 $message = 'sp-contributions-footer';
383 }
384
385 if ( $message && !$this->including() && !$this->msg( $message, $target )->isDisabled() ) {
386 $out->wrapWikiMsg(
387 "<div class='mw-contributions-footer'>\n$1\n</div>",
388 [ $message, $target ] );
389 }
390 }
391 }
392
393 /**
394 * Generates the subheading with links
395 * @param User $userObj User object for the target
396 * @param string $targetName This mostly the same as $userObj->getName() but
397 * normalization may make it differ. // T272225
398 * @return string Appropriately-escaped HTML to be output literally
399 */
400 protected function contributionsSub( $userObj, $targetName ) {
401 $isAnon = $userObj->isAnon();
402 if ( !$isAnon && $userObj->isHidden() &&
403 !$this->permissionManager->userHasRight( $this->getUser(), 'hideuser' )
404 ) {
405 // T120883 if the user is hidden and the viewer cannot see hidden
406 // users, pretend like it does not exist at all.
407 $isAnon = true;
408 }
409
410 if ( $isAnon ) {
411 // Show a warning message that the user being searched for doesn't exist.
412 // UserNameUtils::isIP returns true for IP address and usemod IPs like '123.123.123.xxx',
413 // but returns false for IP ranges. We don't want to suggest either of these are
414 // valid usernames which we would with the 'contributions-userdoesnotexist' message.
415 if ( !$this->userNameUtils->isIP( $userObj->getName() )
416 && !IPUtils::isValidRange( $userObj->getName() )
417 ) {
418 $this->getOutput()->addHTML( Html::warningBox(
419 $this->getOutput()->msg( 'contributions-userdoesnotexist',
420 wfEscapeWikiText( $userObj->getName() ) )->parse(),
421 'mw-userpage-userdoesnotexist'
422 ) );
423 if ( !$this->including() ) {
424 $this->getOutput()->setStatusCode( 404 );
425 }
426 }
427 $user = htmlspecialchars( $userObj->getName() );
428 } else {
429 $user = $this->getLinkRenderer()->makeLink( $userObj->getUserPage(), $userObj->getName() );
430 }
431 $nt = $userObj->getUserPage();
432 $talk = $userObj->getTalkPage();
433 $links = '';
434
435 // T211910. Don't show action links if a range is outside block limit
436 $showForIp = IPUtils::isValid( $userObj ) ||
437 ( IPUtils::isValidRange( $userObj ) && ContribsPager::isQueryableRange( $userObj, $this->getConfig() ) );
438
439 // T276306. if the user is hidden and the viewer cannot see hidden, pretend that it does not exist
440 $registeredAndVisible = $userObj->isRegistered() && ( !$userObj->isHidden()
441 || $this->permissionManager->userHasRight( $this->getUser(), 'hideuser' ) );
442
443 $shouldShowLinks = $talk && ( $registeredAndVisible || $showForIp );
444 if ( $shouldShowLinks ) {
445 $tools = $this->getUserLinks(
446 $this,
447 $userObj
448 );
449 $links = Html::openElement( 'span', [ 'class' => 'mw-changeslist-links' ] );
450 foreach ( $tools as $tool ) {
451 $links .= Html::rawElement( 'span', [], $tool ) . ' ';
452 }
453 $links = trim( $links ) . Html::closeElement( 'span' );
454
455 // Show a note if the user is blocked and display the last block log entry.
456 // Do not expose the autoblocks, since that may lead to a leak of accounts' IPs,
457 // and also this will display a totally irrelevant log entry as a current block.
458 $shouldShowBlocks = $this->shouldShowBlockLogExtract( $userObj );
459 if ( $shouldShowBlocks ) {
460 // For IP ranges you must give DatabaseBlock::newFromTarget the CIDR string
461 // and not a user object.
462 if ( IPUtils::isValidRange( $userObj->getName() ) ) {
463 $block = $this->blockStore
464 ->newFromTarget( $userObj->getName(), $userObj->getName() );
465 } else {
466 $block = $this->blockStore->newFromTarget( $userObj, $userObj );
467 }
468
469 if ( $block !== null && $block->getType() != Block::TYPE_AUTO ) {
470 if ( $block->getType() == Block::TYPE_RANGE ) {
471 $nt = $this->namespaceInfo->getCanonicalName( NS_USER )
472 . ':' . $block->getTargetName();
473 }
474
475 $out = $this->getOutput(); // showLogExtract() wants first parameter by reference
476 if ( $userObj->isAnon() ) {
477 $msgKey = $block->isSitewide() ?
478 'sp-contributions-blocked-notice-anon' :
479 'sp-contributions-blocked-notice-anon-partial';
480 } else {
481 $msgKey = $block->isSitewide() ?
482 'sp-contributions-blocked-notice' :
483 'sp-contributions-blocked-notice-partial';
484 }
485 // Allow local styling overrides for different types of block
486 $class = $block->isSitewide() ?
487 'mw-contributions-blocked-notice' :
488 'mw-contributions-blocked-notice-partial';
489 LogEventsList::showLogExtract(
490 $out,
491 'block',
492 $nt,
493 '',
494 [
495 'lim' => 1,
496 'showIfEmpty' => false,
497 'msgKey' => [
498 $msgKey,
499 $userObj->getName() # Support GENDER in 'sp-contributions-blocked-notice'
500 ],
501 'offset' => '', # don't use WebRequest parameter offset
502 'wrap' => Html::rawElement(
503 'div',
504 [ 'class' => $class ],
505 '$1'
506 ),
507 ]
508 );
509 }
510 }
511 }
512
513 // First subheading. "For Username (talk | block log | logs | etc.)"
514 $userName = $userObj->getName();
515 $subHeadingsHtml = Html::rawElement( 'div', [ 'class' => 'mw-contributions-user-tools' ],
516 $this->msg( 'contributions-subtitle' )->rawParams( $user )->params( $userName )
517 . ' ' . $links
518 );
519
520 // Second subheading. "A user with 37,208 edits. Account created on 2008-09-17."
521 if ( $talk && $registeredAndVisible ) {
522 $editCount = $userObj->getEditCount();
523 $userInfo = $this->msg( 'contributions-edit-count' )
524 ->params( $userName )
525 ->numParams( $editCount )
526 ->escaped();
527
528 $accountCreationDate = $userObj->getRegistration();
529 if ( $accountCreationDate ) {
530 $date = $this->getLanguage()->date( $accountCreationDate, true );
531 $userInfo .= $this->msg( 'word-separator' )
532 ->escaped();
533 $userInfo .= $this->msg( 'contributions-account-creation-date' )
534 ->plaintextParams( $date )
535 ->escaped();
536 }
537
538 $subHeadingsHtml .= Html::rawElement(
539 'div',
540 [ 'class' => 'mw-contributions-editor-info' ],
541 $userInfo
542 );
543 }
544
545 return $subHeadingsHtml;
546 }
547
548 /**
549 * Links to different places.
550 *
551 * @note This function is also called in DeletedContributionsPage
552 * @param SpecialPage $sp SpecialPage instance, for context
553 * @param User $target Target user object
554 * @return array
555 */
556 protected function getUserLinks(
557 SpecialPage $sp,
558 User $target
559 ) {
560 $id = $target->getId();
561 $username = $target->getName();
562 $userpage = $target->getUserPage();
563 $talkpage = $target->getTalkPage();
564 $isIP = IPUtils::isValid( $username );
565 $isRange = IPUtils::isValidRange( $username );
566
567 $linkRenderer = $sp->getLinkRenderer();
568
569 $tools = [];
570 # No talk pages for IP ranges.
571 if ( !$isRange ) {
572 $tools['user-talk'] = $linkRenderer->makeLink(
573 $talkpage,
574 $sp->msg( 'sp-contributions-talk' )->text(),
575 [ 'class' => 'mw-contributions-link-talk' ]
576 );
577 }
578
579 # Block / Change block / Unblock links
580 if ( $this->permissionManager->userHasRight( $sp->getUser(), 'block' ) ) {
581 if ( $target->getBlock() && $target->getBlock()->getType() != Block::TYPE_AUTO ) {
582 $tools['block'] = $linkRenderer->makeKnownLink( # Change block link
583 SpecialPage::getTitleFor( 'Block', $username ),
584 $sp->msg( 'change-blocklink' )->text(),
585 [ 'class' => 'mw-contributions-link-change-block' ]
586 );
587 $tools['unblock'] = $linkRenderer->makeKnownLink( # Unblock link
588 SpecialPage::getTitleFor( 'Unblock', $username ),
589 $sp->msg( 'unblocklink' )->text(),
590 [ 'class' => 'mw-contributions-link-unblock' ]
591 );
592 } else { # User is not blocked
593 $tools['block'] = $linkRenderer->makeKnownLink( # Block link
594 SpecialPage::getTitleFor( 'Block', $username ),
595 $sp->msg( 'blocklink' )->text(),
596 [ 'class' => 'mw-contributions-link-block' ]
597 );
598 }
599 }
600
601 # Block log link
602 $tools['log-block'] = $linkRenderer->makeKnownLink(
603 SpecialPage::getTitleFor( 'Log', 'block' ),
604 $sp->msg( 'sp-contributions-blocklog' )->text(),
605 [ 'class' => 'mw-contributions-link-block-log' ],
606 [ 'page' => $userpage->getPrefixedText() ]
607 );
608
609 # Suppression log link (T61120)
610 if ( $this->permissionManager->userHasRight( $sp->getUser(), 'suppressionlog' ) ) {
611 $tools['log-suppression'] = $linkRenderer->makeKnownLink(
612 SpecialPage::getTitleFor( 'Log', 'suppress' ),
613 $sp->msg( 'sp-contributions-suppresslog', $username )->text(),
614 [ 'class' => 'mw-contributions-link-suppress-log' ],
615 [ 'offender' => $username ]
616 );
617 }
618
619 # Don't show some links for IP ranges
620 if ( !$isRange ) {
621 # Uploads: hide if IPs cannot upload (T220674)
622 if ( !$isIP || $this->permissionManager->userHasRight( $target, 'upload' ) ) {
623 $tools['uploads'] = $linkRenderer->makeKnownLink(
624 SpecialPage::getTitleFor( 'Listfiles', $username ),
625 $sp->msg( 'sp-contributions-uploads' )->text(),
626 [ 'class' => 'mw-contributions-link-uploads' ]
627 );
628 }
629
630 # Other logs link
631 # Todo: T146628
632 $tools['logs'] = $linkRenderer->makeKnownLink(
633 SpecialPage::getTitleFor( 'Log', $username ),
634 $sp->msg( 'sp-contributions-logs' )->text(),
635 [ 'class' => 'mw-contributions-link-logs' ]
636 );
637
638 # Add link to deleted user contributions for privileged users
639 # Todo: T183457
640 if ( $this->permissionManager->userHasRight( $sp->getUser(), 'deletedhistory' ) ) {
641 $tools['deletedcontribs'] = $linkRenderer->makeKnownLink(
642 SpecialPage::getTitleFor( 'DeletedContributions', $username ),
643 $sp->msg( 'sp-contributions-deleted', $username )->text(),
644 [ 'class' => 'mw-contributions-link-deleted-contribs' ]
645 );
646 }
647 }
648
649 # (T373988) Don't show some links for temporary accounts
650 if ( !$target->isTemp() ) {
651 # Add a link to change user rights for privileged users
652 $userrightsPage = new SpecialUserRights();
653 $userrightsPage->setContext( $sp->getContext() );
654 if ( $userrightsPage->userCanChangeRights( $target ) ) {
655 $tools['userrights'] = $linkRenderer->makeKnownLink(
656 SpecialPage::getTitleFor( 'Userrights', $username ),
657 $sp->msg( 'sp-contributions-userrights', $username )->text(),
658 [ 'class' => 'mw-contributions-link-user-rights' ]
659 );
660 }
661
662 # Add a link to rename the user
663 if ( $id && $this->permissionManager->userHasRight( $sp->getUser(), 'renameuser' ) ) {
664 $tools['renameuser'] = $sp->getLinkRenderer()->makeKnownLink(
665 SpecialPage::getTitleFor( 'Renameuser' ),
666 $sp->msg( 'renameuser-linkoncontribs', $userpage->getText() )->text(),
667 [ 'title' => $sp->msg( 'renameuser-linkoncontribs-text', $userpage->getText() )->parse() ],
668 [ 'oldusername' => $userpage->getText() ]
669 );
670 }
671 }
672
673 $this->getHookRunner()->onContributionsToolLinks( $id, $userpage, $tools, $sp );
674
675 return $tools;
676 }
677
678 /**
679 * Get the target field for the form
680 *
681 * @param string $target
682 * @return array
683 */
684 protected function getTargetField( $target ) {
685 return [
686 'type' => 'user',
687 'default' => str_replace( '_', ' ', $target ),
688 'label' => $this->msg( 'sp-contributions-username' )->text(),
689 'name' => 'target',
690 'id' => 'mw-target-user-or-ip',
691 'size' => 40,
692 'autofocus' => $target === '',
693 'section' => 'contribs-top',
694 'ipallowed' => true,
695 'usemodwiki-ipallowed' => true,
696 'iprange' => true,
697 'external' => true,
698 'required' => true,
699 ];
700 }
701
702 /**
703 * Generates the namespace selector form with hidden attributes.
704 * @param array $pagerOptions with keys contribs, user, deletedOnly, limit, target, topOnly,
705 * newOnly, hideMinor, namespace, associated, nsInvert, tagfilter, tagInvert, year, start, end
706 * @return string HTML fragment
707 */
708 protected function getForm( array $pagerOptions ) {
709 if ( $this->including() ) {
710 // Do not show a form when special page is included in wikitext
711 return '';
712 }
713
714 // Modules required only for the form
715 $this->getOutput()->addModules( [
716 'mediawiki.special.contributions',
717 ] );
718 $this->getOutput()->enableOOUI();
719 $fields = [];
720
721 # Add hidden params for tracking except for parameters in $skipParameters
722 $skipParameters = [
723 'namespace',
724 'nsInvert',
725 'deletedOnly',
726 'target',
727 'year',
728 'month',
729 'start',
730 'end',
731 'topOnly',
732 'newOnly',
733 'hideMinor',
734 'associated',
735 'tagfilter',
736 'tagInvert',
737 'title',
738 ];
739
740 foreach ( $pagerOptions as $name => $value ) {
741 if ( in_array( $name, $skipParameters ) ) {
742 continue;
743 }
744
745 $fields[$name] = [
746 'name' => $name,
747 'type' => 'hidden',
748 'default' => $value,
749 ];
750 }
751
752 $target = $pagerOptions['target'] ?? '';
753 $fields['target'] = $this->getTargetField( $target );
754
755 $ns = $pagerOptions['namespace'] ?? null;
756 $fields['namespace'] = [
757 'type' => 'namespaceselect',
758 'label' => $this->msg( 'namespace' )->text(),
759 'name' => 'namespace',
760 'cssclass' => 'namespaceselector',
761 'default' => $ns,
762 'id' => 'namespace',
763 'section' => 'contribs-top',
764 ];
765 $fields['nsFilters'] = [
766 'class' => HTMLMultiSelectField::class,
767 'label' => '',
768 'name' => 'wpfilters',
769 'flatlist' => true,
770 // Only shown when namespaces are selected.
771 'hide-if' => [ '===', 'namespace', 'all' ],
772 'options-messages' => [
773 'invert' => 'nsInvert',
774 'namespace_association' => 'associated',
775 ],
776 'section' => 'contribs-top',
777 ];
778 $fields['tagfilter'] = [
779 'type' => 'tagfilter',
780 'cssclass' => 'mw-tagfilter-input',
781 'id' => 'tagfilter',
782 'label-message' => [ 'tag-filter', 'parse' ],
783 'name' => 'tagfilter',
784 'size' => 20,
785 'section' => 'contribs-top',
786 ];
787 $fields['tagInvert'] = [
788 'type' => 'check',
789 'id' => 'tagInvert',
790 'label' => $this->msg( 'invert' ),
791 'name' => 'tagInvert',
792 'hide-if' => [ '===', 'tagfilter', '' ],
793 'section' => 'contribs-top',
794 ];
795
796 if ( $this->permissionManager->userHasRight( $this->getUser(), 'deletedhistory' ) ) {
797 $fields['deletedOnly'] = [
798 'type' => 'check',
799 'id' => 'mw-show-deleted-only',
800 'label' => $this->msg( 'history-show-deleted' )->text(),
801 'name' => 'deletedOnly',
802 'section' => 'contribs-top',
803 ];
804 }
805
806 if ( !$this->isArchive() ) {
807 $fields['topOnly'] = [
808 'type' => 'check',
809 'id' => 'mw-show-top-only',
810 'label' => $this->msg( 'sp-contributions-toponly' )->text(),
811 'name' => 'topOnly',
812 'section' => 'contribs-top',
813 ];
814 }
815
816 $fields['newOnly'] = [
817 'type' => 'check',
818 'id' => 'mw-show-new-only',
819 'label' => $this->msg( 'sp-contributions-newonly' )->text(),
820 'name' => 'newOnly',
821 'section' => 'contribs-top',
822 ];
823 $fields['hideMinor'] = [
824 'type' => 'check',
825 'cssclass' => 'mw-hide-minor-edits',
826 'id' => 'mw-show-new-only',
827 'label' => $this->msg( 'sp-contributions-hideminor' )->text(),
828 'name' => 'hideMinor',
829 'section' => 'contribs-top',
830 ];
831
832 // Allow additions at this point to the filters.
833 $rawFilters = [];
834 $this->getHookRunner()->onSpecialContributions__getForm__filters(
835 $this, $rawFilters );
836 foreach ( $rawFilters as $filter ) {
837 // Backwards compatibility support for previous hook function signature.
838 if ( is_string( $filter ) ) {
839 $fields[] = [
840 'type' => 'info',
841 'default' => $filter,
842 'raw' => true,
843 'section' => 'contribs-top',
844 ];
845 wfDeprecatedMsg(
846 'A SpecialContributions::getForm::filters hook handler returned ' .
847 'an array of strings, this is deprecated since MediaWiki 1.33',
848 '1.33', false, false
849 );
850 } else {
851 // Preferred append method.
852 $fields[] = $filter;
853 }
854 }
855
856 $fields['start'] = [
857 'type' => 'date',
858 'default' => '',
859 'id' => 'mw-date-start',
860 'label' => $this->msg( 'date-range-from' )->text(),
861 'name' => 'start',
862 'section' => 'contribs-date',
863 ];
864 $fields['end'] = [
865 'type' => 'date',
866 'default' => '',
867 'id' => 'mw-date-end',
868 'label' => $this->msg( 'date-range-to' )->text(),
869 'name' => 'end',
870 'section' => 'contribs-date',
871 ];
872
873 $htmlForm = HTMLForm::factory( 'ooui', $fields, $this->getContext() );
874 $htmlForm
875 ->setMethod( 'get' )
876 ->setTitle( $this->getPageTitle() )
877 // When offset is defined, the user is paging through results
878 // so we hide the form by default to allow users to focus on browsing
879 // rather than defining search parameters
880 ->setCollapsibleOptions(
881 ( $pagerOptions['target'] ?? null ) ||
882 ( $pagerOptions['start'] ?? null ) ||
883 ( $pagerOptions['end'] ?? null )
884 )
885 ->setAction( wfScript() )
886 ->setSubmitTextMsg( 'sp-contributions-submit' )
887 ->setWrapperLegendMsg( $this->getFormWrapperLegendMessageKey() );
888
889 $htmlForm->prepareForm();
890
891 // Submission is handled elsewhere, but do this to check for and display errors
892 $htmlForm->setSubmitCallback( static function () {
893 return true;
894 } );
895 $result = $htmlForm->tryAuthorizedSubmit();
896 if ( !( $result === true || ( $result instanceof Status && $result->isGood() ) ) ) {
897 // Uncollapse if there are errors
898 $htmlForm->setCollapsibleOptions( false );
899 $this->formErrors = true;
900 }
901
902 return $htmlForm->getHTML( $result );
903 }
904
905 /**
906 * Return an array of subpages beginning with $search that this special page will accept.
907 *
908 * @param string $search Prefix to search for
909 * @param int $limit Maximum number of results to return (usually 10)
910 * @param int $offset Number of results to skip (usually 0)
911 * @return string[] Matching subpages
912 */
913 public function prefixSearchSubpages( $search, $limit, $offset ) {
914 $search = $this->userNameUtils->getCanonical( $search );
915 if ( !$search ) {
916 // No prefix suggestion for invalid user
917 return [];
918 }
919 // Autocomplete subpage as user list - public to allow caching
920 return $this->userNamePrefixSearch
921 ->search( UserNamePrefixSearch::AUDIENCE_PUBLIC, $search, $limit, $offset );
922 }
923
924 /**
925 * @return bool This SpecialPage provides syndication feeds.
926 */
927 protected function providesFeeds() {
928 return true;
929 }
930
931 /**
932 * Define whether this page shows existing revisions (from the revision table) or
933 * revisions of deleted pages (from the archive table).
934 *
935 * @return bool This page shows existing revisions
936 */
937 protected function isArchive() {
938 return false;
939 }
940
941 /**
942 * @param UserIdentity $targetUser The normalized target user identity
943 * @return ContributionsPager
944 */
945 protected function getPager( $targetUser ) {
946 // TODO: This class and the classes it extends should be abstract, and this
947 // method should be abstract.
948 throw new \LogicException( __METHOD__ . " must be overridden" );
949 }
950
951 /**
952 * @inheritDoc
953 */
954 protected function getGroupName() {
955 return 'users';
956 }
957
958 /**
959 * @return string Message key for the fieldset wrapping the form
960 */
961 protected function getFormWrapperLegendMessageKey() {
962 return 'sp-contributions-search';
963 }
964
965 /**
966 * @param UserIdentity $target The target of the search that produced the results page
967 * @return string Message key for the results page title
968 */
969 protected function getResultsPageTitleMessageKey( UserIdentity $target ) {
970 return 'contributions-title';
971 }
972
973 /**
974 * Whether the block log extract should be shown on the special page. This is public to allow extensions which
975 * add block log entries to skip adding them when this returns false.
976 *
977 * @since 1.43
978 * @param UserIdentity $target The target of the search that produced the results page
979 * @return bool Whether the block log extract should be shown if the target is blocked.
980 */
981 public function shouldShowBlockLogExtract( UserIdentity $target ): bool {
982 return !$this->including();
983 }
984 }