Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
100 / 110
77.78% covered (warning)
77.78%
7 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
GlobalUserPageManager
90.91% covered (success)
90.91%
100 / 110
77.78% covered (warning)
77.78%
7 / 9
39.08
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 shouldDisplayGlobalPage
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 shouldDisplayGlobalPageBatched
100.00% covered (success)
100.00%
53 / 53
100.00% covered (success)
100.00%
1 / 1
17
 getCentralTouched
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getCentralTouchedBatch
89.66% covered (warning)
89.66%
26 / 29
0.00% covered (danger)
0.00%
0 / 1
7.05
 isGlobalPage
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 canBeGlobal
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 getUserIdentity
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 getEnabledWikis
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace MediaWiki\GlobalUserPage;
4
5use MediaWiki\Config\ServiceOptions;
6use MediaWiki\GlobalUserPage\Hooks\HookRunner;
7use MediaWiki\HookContainer\HookContainer;
8use MediaWiki\Linker\LinkTarget;
9use MediaWiki\MainConfigNames;
10use MediaWiki\Title\TitleValue;
11use MediaWiki\User\CentralId\CentralIdLookup;
12use MediaWiki\User\UserIdentity;
13use MediaWiki\User\UserIdentityLookup;
14use MediaWiki\User\UserIdentityValue;
15use MediaWiki\User\UserNameUtils;
16use MediaWiki\WikiMap\WikiMap;
17use Wikimedia\ObjectCache\MapCacheLRU;
18use Wikimedia\Rdbms\IConnectionProvider;
19use Wikimedia\Rdbms\IDBAccessObject;
20
21class GlobalUserPageManager {
22    public const CONSTRUCTOR_OPTIONS = [
23        'GlobalUserPageDBname',
24        MainConfigNames::LocalDatabases,
25    ];
26
27    private MapCacheLRU $displayCache;
28    private MapCacheLRU $touchedCache;
29    private readonly HookRunner $hookRunner;
30    /** @var string[]|null */
31    private ?array $enabledWikisList = null;
32    private readonly bool $isCentralWiki;
33
34    public function __construct(
35        private readonly IConnectionProvider $connectionProvider,
36        private readonly UserIdentityLookup $userIdentityLookup,
37        private readonly UserNameUtils $userNameUtils,
38        private readonly CentralIdLookup $centralIdLookup,
39        private readonly ServiceOptions $options,
40        HookContainer $hookContainer,
41    ) {
42        $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
43        $this->hookRunner = new HookRunner( $hookContainer );
44
45        // Do some instance caching since this can be
46        // called frequently due do the Linker hook
47        $this->displayCache = new MapCacheLRU( 100 );
48        $this->touchedCache = new MapCacheLRU( 100 );
49
50        $this->isCentralWiki = WikiMap::isCurrentWikiId( $options->get( 'GlobalUserPageDBname' ) );
51    }
52
53    /**
54     * Given a Title, assuming it doesn't exist, should
55     * we display a global user page on it
56     *
57     * @param LinkTarget $title
58     * @return bool
59     */
60    public function shouldDisplayGlobalPage( LinkTarget $title ): bool {
61        return $this->shouldDisplayGlobalPageBatched( [ $title ] )[0];
62    }
63
64    /**
65     * Batched variant of {@link shouldDisplayGlobalPage}, resolving many titles in a bounded
66     * number of queries (at most two CentralAuth attachment lookups and one central-touched query).
67     *
68     * @param iterable<LinkTarget> $titles
69     * @return bool[] One entry per input, preserving the input keys.
70     */
71    public function shouldDisplayGlobalPageBatched( iterable $titles ): array {
72        // Materialize so we can iterate more than once (input may be a generator).
73        $titlesByKey = [];
74        foreach ( $titles as $key => $title ) {
75            $titlesByKey[$key] = $title;
76        }
77
78        $results = [];
79
80        // Don't run this code for Hub.
81        if ( $this->isCentralWiki ) {
82            foreach ( $titlesByKey as $key => $title ) {
83                $results[$key] = false;
84            }
85            return $results;
86        }
87
88        // Titles that still need an attachment -> touched resolution, keyed the same
89        // as the input. Value is the normalized username.
90        $candidateUserNames = [];
91
92        // First pass: apply the cheap cache and canBeGlobal checks and canonicalize the
93        // remaining usernames. The attachment and central-touched lookups below key on
94        // the canonical name only, so no local user table lookup is needed (T408666).
95        foreach ( $titlesByKey as $key => $title ) {
96            $cacheKey = "{$title->getNamespace()}:{$title->getDBkey()}";
97            if ( $this->displayCache->has( $cacheKey ) ) {
98                $results[$key] = $this->displayCache->get( $cacheKey );
99                continue;
100            }
101
102            $canonical = $this->canBeGlobal( $title )
103                ? $this->userNameUtils->getCanonical( $title->getText() )
104                : false;
105            if ( $canonical === false ) {
106                $this->displayCache->set( $cacheKey, false );
107                $results[$key] = false;
108                continue;
109            }
110
111            $candidateUserNames[$key] = $canonical;
112        }
113
114        if ( !$candidateUserNames ) {
115            return $results;
116        }
117
118        $uniqueNames = array_map(
119            'strval',
120            array_values( array_unique( $candidateUserNames ) )
121        );
122
123        // Check for an existing central user page first: it is the more selective filter
124        // (most users have no central user page) and a cheaper query than the CentralAuth
125        // attachment lookups, which then only need to cover the names that pass it.
126        $touchedByName = $this->getCentralTouchedBatch( $uniqueNames );
127
128        $namesWithCentralPage = [];
129        foreach ( $uniqueNames as $name ) {
130            if ( $touchedByName[$name] ) {
131                $namesWithCentralPage[] = $name;
132            }
133        }
134
135        // Make sure that the username represents the same user on both wikis.
136        $attachedBoth = [];
137        if ( $namesWithCentralPage ) {
138            $seed = array_fill_keys( $namesWithCentralPage, 0 );
139            $attachedLocal = $this->centralIdLookup->lookupAttachedUserNames(
140                $seed, CentralIdLookup::AUDIENCE_RAW );
141            $attachedCentral = $this->centralIdLookup->lookupAttachedUserNames(
142                $seed, CentralIdLookup::AUDIENCE_RAW, IDBAccessObject::READ_NORMAL,
143                $this->options->get( 'GlobalUserPageDBname' ) );
144
145            foreach ( $namesWithCentralPage as $name ) {
146                if ( $attachedLocal[$name] !== 0 && $attachedCentral[$name] !== 0 ) {
147                    $attachedBoth[$name] = true;
148                }
149            }
150        }
151
152        foreach ( $candidateUserNames as $key => $name ) {
153            $display = isset( $attachedBoth[$name] );
154            $results[$key] = $display;
155
156            $title = $titlesByKey[$key];
157            $this->displayCache->set( "{$title->getNamespace()}:{$title->getDBkey()}", $display );
158        }
159
160        // Return in input order; the loops above populate non-candidates and candidates
161        // in separate passes, so $results is not necessarily in the original order.
162        $ordered = [];
163        foreach ( array_keys( $titlesByKey ) as $key ) {
164            $ordered[$key] = $results[$key];
165        }
166        return $ordered;
167    }
168
169    /**
170     * Get the page_touched timestamp of the central user page.
171     *
172     * @param UserIdentity $user
173     * @return string|false MediaWiki timestamp, or `false` if the page does not exist or is excluded via
174     * the __NOGLOBAL__ magic word.
175     */
176    public function getCentralTouched( UserIdentity $user ) {
177        return $this->getCentralTouchedBatch( [ $user->getName() ] )[$user->getName()];
178    }
179
180    /**
181     * Batched variant of {@link getCentralTouched}, resolving many usernames in one query.
182     *
183     * @param string[] $userNames
184     * @return array<string,string|false> Map of username to MediaWiki timestamp, or `false` if the
185     * page does not exist or is excluded via the __NOGLOBAL__ magic word.
186     */
187    public function getCentralTouchedBatch( array $userNames ): array {
188        $results = [];
189        $dbKeyToName = [];
190
191        foreach ( $userNames as $name ) {
192            if ( $this->touchedCache->has( $name ) ) {
193                $results[$name] = $this->touchedCache->get( $name );
194                continue;
195            }
196            $dbKey = ( new TitleValue( NS_USER, $name ) )->getDBkey();
197            $dbKeyToName[$dbKey] = $name;
198        }
199
200        if ( !$dbKeyToName ) {
201            return $results;
202        }
203
204        $dbr = $this->connectionProvider->getReplicaDatabase( $this->options->get( 'GlobalUserPageDBname' ) );
205
206        $rows = $dbr->newSelectQueryBuilder()
207            ->select( [ 'page_title', 'page_touched', 'pp_propname' ] )
208            ->from( 'page' )
209            ->leftJoin( 'page_props', null, [ 'page_id=pp_page', 'pp_propname' => 'noglobal' ] )
210            ->where( [
211                'page_namespace' => NS_USER,
212                'page_title' => array_map( 'strval', array_keys( $dbKeyToName ) ),
213            ] )
214            ->caller( __METHOD__ )
215            ->fetchResultSet();
216
217        $touchedByDbKey = [];
218        foreach ( $rows as $row ) {
219            $touchedByDbKey[$row->page_title] = $row->pp_propname == 'noglobal' ? false : $row->page_touched;
220        }
221
222        foreach ( $dbKeyToName as $dbKey => $name ) {
223            $touched = $touchedByDbKey[$dbKey] ?? false;
224            $this->touchedCache->set( $name, $touched );
225            $results[$name] = $touched;
226        }
227
228        return $results;
229    }
230
231    /**
232     * Whether a page is the global user page on the central wiki
233     */
234    public function isGlobalPage( LinkTarget $title ): bool {
235        // Global user page must be on the central wiki
236        return $this->isCentralWiki
237            // and match some more criteria
238            && $this->canBeGlobal( $title );
239    }
240
241    /**
242     * Checks whether the given page can be global
243     * doesn't check the actual database
244     * @param LinkTarget $title
245     * @return bool
246     */
247    private function canBeGlobal( LinkTarget $title ): bool {
248        return (
249            // Must be a user page
250            $title->inNamespace( NS_USER ) &&
251            // Check valid username (also handles IP usernames and user subpages)
252            $this->userNameUtils->isValid( $title->getText() ) &&
253            // Temporary accounts cannot have global userpages (T326920).
254            !$this->userNameUtils->isTemp( $title->getText() )
255        );
256    }
257
258    public function getUserIdentity( string $userName ): ?UserIdentity {
259        $user = $this->userIdentityLookup->getUserIdentityByName( $userName );
260        if ( $user ) {
261            return $user;
262        }
263
264        // Check if user is invalid, UserIdentityLookup also calls getCanonical, so do this only in the bad case
265        $canonical = $this->userNameUtils->getCanonical( $userName );
266        if ( $canonical !== false ) {
267            // User does not exist locally, create an anonymous identity
268            return UserIdentityValue::newAnonymous( $canonical );
269        }
270
271        return null;
272    }
273
274    public function getEnabledWikis(): array {
275        if ( $this->enabledWikisList === null ) {
276            $list = [];
277            if ( $this->hookRunner->onGlobalUserPageWikis( $list ) ) {
278                // Fallback if no hook override
279                $list = $this->options->get( MainConfigNames::LocalDatabases );
280            }
281            $this->enabledWikisList = $list;
282        }
283
284        return $this->enabledWikisList;
285    }
286}