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