Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.97% covered (warning)
85.97%
472 / 549
47.06% covered (danger)
47.06%
8 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
RepoHooks
85.97% covered (warning)
85.97%
472 / 549
47.06% covered (danger)
47.06%
8 / 17
112.35
0.00% covered (danger)
0.00%
0 / 1
 registerExtension
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 registerRepoModeConfig
99.48% covered (success)
99.48%
191 / 192
0.00% covered (danger)
0.00%
0 / 1
2
 registerAbstractModeConfig
100.00% covered (success)
100.00%
39 / 39
100.00% covered (success)
100.00%
1 / 1
1
 registerAbstractClientModeConfig
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 applyRegisteredConfig
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
8.12
 applyGrantConfig
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 onMediaWikiServices
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 onLoadExtensionSchemaUpdates
100.00% covered (success)
100.00%
68 / 68
100.00% covered (success)
100.00%
1 / 1
19
 getDataPath
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getInitialContentFilenames
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 ensureZObjectContentModelDefined
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
4.94
 maybeRestoreInitialContent
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
42
 createInitialContent
82.86% covered (warning)
82.86%
29 / 35
0.00% covered (danger)
0.00%
0 / 1
7.25
 insertContentObject
82.14% covered (warning)
82.14%
46 / 56
0.00% covered (danger)
0.00%
0 / 1
16.28
 initializeZObjectJoinTable
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
3.21
 updateSecondaryTables
72.09% covered (warning)
72.09%
31 / 43
0.00% covered (danger)
0.00%
0 / 1
12.17
 ensureZObjectStoreIsPresent
11.11% covered (danger)
11.11%
2 / 18
0.00% covered (danger)
0.00%
0 / 1
9.32
1<?php
2
3/**
4 * WikiLambda extension 'repo-mode' hooks
5 *
6 * @file
7 * @ingroup Extensions
8 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
9 * @license MIT
10 */
11
12namespace MediaWiki\Extension\WikiLambda\HookHandler;
13
14use MediaWiki\CommentStore\CommentStoreComment;
15use MediaWiki\Config\ConfigException;
16use MediaWiki\Deferred\DeferredUpdates;
17use MediaWiki\Extension\WikiLambda\InitialContentSnapshot;
18use MediaWiki\Extension\WikiLambda\Registry\ZLangRegistry;
19use MediaWiki\Extension\WikiLambda\Registry\ZTypeRegistry;
20use MediaWiki\Extension\WikiLambda\WikiLambdaServices;
21use MediaWiki\Extension\WikiLambda\ZErrorException;
22use MediaWiki\Extension\WikiLambda\ZObjectContent\ZObjectContentHandler;
23use MediaWiki\Extension\WikiLambda\ZObjectContent\ZObjectSecondaryDataUpdate;
24use MediaWiki\Installer\DatabaseUpdater;
25use MediaWiki\MediaWikiServices;
26use MediaWiki\RecentChanges\RecentChange;
27use MediaWiki\Revision\SlotRecord;
28use MediaWiki\Title\Title;
29use MediaWiki\User\User;
30use Wikimedia\Services\NoSuchServiceException;
31
32class RepoHooks implements
33    \MediaWiki\Installer\Hook\LoadExtensionSchemaUpdatesHook,
34    \MediaWiki\Hook\MediaWikiServicesHook
35    {
36
37    public static function registerExtension() {
38        // We define the content models regardless of if 'repo mode' or 'abstract mode' are enabled
39        require_once __DIR__ . '/../defines.php';
40
41        // Can't use MediaWikiServices or config objects yet, so use globals
42        global $wgWikiLambdaEnableRepoMode, $wgWikiLambdaEnableAbstractMode,
43            $wgWikiLambdaEnableAbstractClientMode;
44
45        if ( $wgWikiLambdaEnableRepoMode ) {
46            self::registerRepoModeConfig();
47        }
48
49        if ( $wgWikiLambdaEnableAbstractMode ) {
50            self::registerAbstractModeConfig();
51        }
52
53        if ( $wgWikiLambdaEnableAbstractClientMode ) {
54            self::registerAbstractClientModeConfig();
55        }
56    }
57
58    /**
59     * Configure namespaces, user rights, groups, rate limits, and OAuth grants that exist
60     * only on a Wikifunctions-style repo wiki. Doing this from the registerExtension callback
61     * (rather than statically in extension.json) keeps them off Special:ListGroupRights and
62     * Special:ListGrants on client-only wikis such as Wikipedia. (T407066, T423542)
63     *
64     * Safe to call repeatedly: the merges are duplicate-free so tests that re-fire
65     * the callback via setUpAsRepoMode() converge on the same state.
66     */
67    private static function registerRepoModeConfig(): void {
68        // Register the namespace as using content our content model
69        global $wgNamespaceContentModels;
70        $wgNamespaceContentModels[ NS_MAIN ] = CONTENT_MODEL_ZOBJECT;
71
72        // Ensure that the namespace is protected with the right permissions
73        global $wgNamespaceProtection;
74        $wgNamespaceProtection[ NS_MAIN ] = [ 'wikilambda-edit', 'wikilambda-create' ];
75
76        // (T267232) Prevent ZObject pages from being transcluded; sadly this isn't available as
77        // an extension.json attribute as of yet.
78        global $wgNonincludableNamespaces;
79        if ( !in_array( NS_MAIN, $wgNonincludableNamespaces, true ) ) {
80            $wgNonincludableNamespaces[] = NS_MAIN;
81        }
82
83        $availableRights = [
84            'wikilambda-bypass-cache',
85            'wikilambda-connect-implementation',
86            'wikilambda-connect-tester',
87            'wikilambda-create',
88            'wikilambda-create-arbitrary-zid',
89            'wikilambda-create-boolean',
90            'wikilambda-create-converter',
91            'wikilambda-create-enum-value',
92            'wikilambda-create-function',
93            'wikilambda-create-function-call',
94            'wikilambda-create-generic-enum',
95            'wikilambda-create-implementation',
96            'wikilambda-create-language',
97            'wikilambda-create-predefined',
98            'wikilambda-create-programming',
99            'wikilambda-create-tester',
100            'wikilambda-create-type',
101            'wikilambda-create-unit',
102            'wikilambda-disconnect-implementation',
103            'wikilambda-disconnect-tester',
104            'wikilambda-edit',
105            'wikilambda-edit-argument-label',
106            'wikilambda-edit-attached-implementation',
107            'wikilambda-edit-attached-tester',
108            'wikilambda-edit-boolean',
109            'wikilambda-edit-function-attached-implementation',
110            'wikilambda-edit-function-attached-tester',
111            'wikilambda-edit-builtin-function',
112            'wikilambda-edit-connected-converter',
113            'wikilambda-edit-converter',
114            'wikilambda-edit-enum-value',
115            'wikilambda-edit-error-key-label',
116            'wikilambda-edit-function-call',
117            'wikilambda-edit-generic-enum-type',
118            'wikilambda-edit-generic-enum-item',
119            'wikilambda-edit-generic-enum-id',
120            'wikilambda-edit-implementation',
121            'wikilambda-edit-key-label',
122            'wikilambda-edit-language',
123            'wikilambda-edit-object-alias',
124            'wikilambda-edit-object-description',
125            'wikilambda-edit-object-label',
126            'wikilambda-edit-object-type',
127            'wikilambda-edit-predefined',
128            'wikilambda-edit-programming',
129            'wikilambda-edit-running-function',
130            'wikilambda-edit-running-function-definition',
131            'wikilambda-edit-tester',
132            'wikilambda-edit-type',
133            'wikilambda-edit-unit',
134            'wikilambda-edit-user-function',
135            'wikilambda-execute',
136            'wikilambda-execute-unsaved-code',
137            'wikilambda-request-fresh-result',
138            'wikifunctions-run',
139        ];
140
141        // '*'-group entries set to false are explicit denials we keep recorded so a
142        // downstream wiki adding the right to '*' doesn't accidentally re-grant it.
143        // 'functioneer' and 'functionmaintainer' inherit 'user' rights via the implicit
144        // 'user' group membership in User::getEffectiveGroups(), so they only list deltas.
145        $groupPermissions = [
146            '*' => [
147                'wikilambda-bypass-cache' => false,
148                'wikilambda-create-function-call' => false,
149                'wikilambda-edit-function-call' => false,
150                'wikilambda-execute' => true,
151                'wikifunctions-run' => true,
152            ],
153            'user' => [
154                'wikilambda-execute-unsaved-code' => true,
155                'wikilambda-create' => true,
156                'wikilambda-create-converter' => true,
157                'wikilambda-create-function' => true,
158                'wikilambda-create-implementation' => true,
159                'wikilambda-create-tester' => true,
160                'wikilambda-edit' => true,
161                'wikilambda-edit-argument-label' => true,
162                'wikilambda-edit-converter' => true,
163                'wikilambda-edit-error-key-label' => true,
164                'wikilambda-edit-implementation' => true,
165                'wikilambda-edit-key-label' => true,
166                'wikilambda-edit-object-alias' => true,
167                'wikilambda-edit-object-description' => true,
168                'wikilambda-edit-object-label' => true,
169                'wikilambda-edit-tester' => true,
170                'wikilambda-edit-user-function' => true,
171            ],
172            'autoconfirmed' => [
173                'wikilambda-request-fresh-result' => true,
174            ],
175            'functioneer' => [
176                'wikilambda-connect-implementation' => true,
177                'wikilambda-connect-tester' => true,
178                'wikilambda-create-generic-enum' => true,
179                'wikilambda-create-type' => true,
180                'wikilambda-disconnect-implementation' => true,
181                'wikilambda-disconnect-tester' => true,
182                'wikilambda-edit-attached-implementation' => true,
183                'wikilambda-edit-attached-tester' => true,
184                'wikilambda-edit-generic-enum-item' => true,
185                'wikilambda-edit-running-function' => true,
186            ],
187            'functionmaintainer' => [
188                'wikilambda-create-arbitrary-zid' => true,
189                'wikilambda-create-boolean' => true,
190                'wikilambda-create-enum-value' => true,
191                'wikilambda-create-language' => true,
192                'wikilambda-create-predefined' => true,
193                'wikilambda-create-programming' => true,
194                'wikilambda-create-unit' => true,
195                'wikilambda-edit-boolean' => true,
196                'wikilambda-edit-builtin-function' => true,
197                'wikilambda-edit-connected-converter' => true,
198                'wikilambda-edit-enum-value' => true,
199                'wikilambda-edit-generic-enum-id' => true,
200                'wikilambda-edit-generic-enum-type' => true,
201                'wikilambda-edit-language' => true,
202                'wikilambda-edit-object-type' => true,
203                'wikilambda-edit-predefined' => true,
204                'wikilambda-edit-programming' => true,
205                'wikilambda-edit-running-function-definition' => true,
206                'wikilambda-edit-type' => true,
207                'wikilambda-edit-unit' => true,
208                'wikilambda-edit-function-attached-implementation' => true,
209                'wikilambda-edit-function-attached-tester' => true,
210            ],
211        ];
212
213        // Buckets for $wgRateLimits['wikilambda-execute']. MediaWiki applies these only to a
214        // user with an account. A logged-out caller needs an 'ip' or 'subnet' bucket, which we
215        // cannot add until app server addresses are excluded: fragment rendering calls the API
216        // over HTTP from an app server, and one address then carries the whole wiki.
217        //
218        // A group bucket must name an *explicit* group. RateLimiter::limit() matches
219        // against UserGroupManager::getUserGroups(), which reads the user_groups table, so the
220        // implicit groups from getUserImplicitGroups(), such as 'autoconfirmed', aren't used here.
221        $rateLimits = [
222            'wikilambda-execute' => [
223                // Functioneers can make 50 calls per minute
224                'functioneer' => [ 50, 60 ],
225                // Regular (logged-in) users can make 20 calls per minute
226                'user' => [ 20, 60 ],
227                // Brand new users and temporary accounts can only make 5 calls per minute
228                'newbie' => [ 5, 60 ],
229                // Logged-out users have no account to count against. Count them by address,
230                // and by /24 or /64 block so that one operator cannot rotate through addresses.
231                'ip' => [ 5, 60 ],
232                'subnet' => [ 20, 60 ],
233            ],
234            // Set requests for fresh results to lower rate limits, due to the impact these
235            // requests might have in the network requests between the orchestrator and Wikidata
236            'wikilambda-request-fresh-result' => [
237                // Function maintainers can make 10 fresh calls per minute
238                'functionmaintainer' => [ 10, 60 ],
239                // Functioneers can make 5 fresh calls per minute
240                'functioneer' => [ 5, 60 ],
241                // Everyone else holding the right can make 2 fresh calls per minute
242                'user' => [ 2, 60 ],
243            ]
244        ];
245
246        // 'sysop' can promote/demote 'functioneer'; 'bureaucrat' the same for 'functionmaintainer'.
247        $groupChangeRights = [
248            'sysop' => 'functioneer',
249            'bureaucrat' => 'functionmaintainer',
250        ];
251
252        self::applyRegisteredConfig(
253            $availableRights, $groupPermissions, $rateLimits, $groupChangeRights
254        );
255
256        // OAuth grants. 'basic' and 'editpage' are core grant groups we extend; 'wikilambda-
257        // specialedit' is a new grant group, flagged 'page-interaction'/'vandalism' below so bot
258        // operators see that the rights it can assign carry real risk. Note that users can't grant
259        // a bot rights they don't hold themselves, so assigning the special group won't let a
260        // non-Functioneer's tool connect or disconnect Implementations. The maintainer- and
261        // staff-only rights are deliberately left out of every grant group for now.
262        $grantPermissions = [
263            // Always granted: run Functions (including unsaved code) and embedded Wikifunctions.
264            'basic' => [
265                'wikilambda-execute' => true,
266                'wikilambda-execute-unsaved-code' => true,
267                'wikifunctions-run' => true,
268            ],
269            // Normal page editing: creating tests, adding labels, and similar everyday edits.
270            // Matches the repo-mode 'user' group permissions above. (The abstract-authoring
271            // rights also live on 'editpage', but are added by registerAbstractModeConfig().)
272            'editpage' => [
273                'wikilambda-execute-unsaved-code' => true,
274                'wikilambda-create' => true,
275                'wikilambda-create-converter' => true,
276                'wikilambda-create-function' => true,
277                'wikilambda-create-implementation' => true,
278                'wikilambda-create-tester' => true,
279                'wikilambda-edit' => true,
280                'wikilambda-edit-argument-label' => true,
281                'wikilambda-edit-converter' => true,
282                'wikilambda-edit-error-key-label' => true,
283                'wikilambda-edit-implementation' => true,
284                'wikilambda-edit-key-label' => true,
285                'wikilambda-edit-object-alias' => true,
286                'wikilambda-edit-object-description' => true,
287                'wikilambda-edit-object-label' => true,
288                'wikilambda-edit-tester' => true,
289                'wikilambda-edit-user-function' => true,
290            ],
291            // Higher-impact edits: (dis)connecting implementations and testers, editing attached
292            // implementations and testers, and creating types and generic enums.
293            'wikilambda-specialedit' => [
294                'wikilambda-connect-implementation' => true,
295                'wikilambda-connect-tester' => true,
296                'wikilambda-create-generic-enum' => true,
297                'wikilambda-create-type' => true,
298                'wikilambda-disconnect-implementation' => true,
299                'wikilambda-disconnect-tester' => true,
300                'wikilambda-edit-attached-implementation' => true,
301                'wikilambda-edit-attached-tester' => true,
302                'wikilambda-edit-generic-enum-item' => true,
303                'wikilambda-edit-running-function' => true,
304            ],
305        ];
306
307        self::applyGrantConfig(
308            $grantPermissions,
309            [ 'wikilambda-specialedit' => 'page-interaction' ],
310            [ 'wikilambda-specialedit' => 'vandalism' ]
311        );
312    }
313
314    /**
315     * Configure the user rights and group permissions needed for Abstract Wikipedia
316     * content authoring. Gated separately from repo-mode rights so an abstract-mode
317     * wiki that is not a Wikifunctions repo still gets these. (T407066)
318     *
319     * Safe to call repeatedly.
320     */
321    private static function registerAbstractModeConfig(): void {
322        $availableRights = [
323            'wikilambda-abstract-create',
324            'wikilambda-abstract-edit',
325            'wikilambda-abstract-request-fresh-result',
326            'wikilambda-abstract-run-unsaved-fragment',
327        ];
328
329        $groupPermissions = [
330            '*' => [
331                'wikilambda-abstract-create' => false,
332                'wikilambda-abstract-edit' => false,
333                'wikilambda-abstract-request-fresh-result' => false,
334                'wikilambda-abstract-run-unsaved-fragment' => false,
335            ],
336            'user' => [
337                'wikilambda-abstract-create' => true,
338                'wikilambda-abstract-edit' => true,
339                'wikilambda-abstract-run-unsaved-fragment' => true,
340            ],
341            // Asking for a fragment to be rendered again with the latest data costs work on
342            // Wikifunctions and Wikidata, so only established accounts may do it, as on
343            // Wikifunctions with wikilambda-request-fresh-result. (T442772)
344            'autoconfirmed' => [
345                'wikilambda-abstract-request-fresh-result' => true,
346            ],
347        ];
348
349        // A rate-limit bucket must name an explicit group, and 'autoconfirmed' is implicit
350        // (see registerRepoModeConfig()), so the 'user' bucket covers every account with the right.
351        $rateLimits = [
352            'wikilambda-abstract-request-fresh-result' => [
353                // Two fresh results per minute, as for most users on Wikifunctions
354                'user' => [ 2, 60 ],
355            ],
356        ];
357
358        self::applyRegisteredConfig( $availableRights, $groupPermissions, $rateLimits, [] );
359
360        // The abstract-authoring rights are also reachable through the core 'editpage' OAuth grant.
361        // Registered here (not in registerRepoModeConfig) so they only appear on Special:ListGrants
362        // where abstract mode is enabled. (T423542) wikilambda-abstract-request-fresh-result is
363        // deliberately in no grant: tools should not trigger fresh results without a decision
364        // to allow it. (T442772)
365        self::applyGrantConfig(
366            [
367                'editpage' => [
368                    'wikilambda-abstract-create' => true,
369                    'wikilambda-abstract-edit' => true,
370                    'wikilambda-abstract-run-unsaved-fragment' => true,
371                ],
372            ],
373            [],
374            []
375        );
376    }
377
378    /**
379     * Configure the user right that gates the Abstract Wikipedia opt-in action: choosing which
380     * local articles render from Abstract Wikipedia content in the absence of a local article.
381     * Gated on abstract-client mode, as that's where the opt-in list lives (managed through the
382     * AbstractWikiOptedInArticles CommunityConfiguration provider). (T422697)
383     *
384     * Granted to 'sysop' by default — the assignment every WMF wiki is expected to start with —
385     * but registered as a first-class right so communities can reassign it through the standard
386     * $wgGroupPermissions / $wgRevokePermissions mechanisms with no code change on our side. Pairs
387     * with the staff- and maintainer-only rights in being deliberately kept out of every OAuth
388     * grant group: it manages site configuration, not everyday page editing.
389     *
390     * Safe to call repeatedly.
391     */
392    private static function registerAbstractClientModeConfig(): void {
393        $availableRights = [
394            'wikilambda-abstract-optin',
395        ];
396
397        // '*' => false is an explicit denial we keep on record, matching registerRepoModeConfig().
398        $groupPermissions = [
399            '*' => [
400                'wikilambda-abstract-optin' => false,
401            ],
402            'sysop' => [
403                'wikilambda-abstract-optin' => true,
404            ],
405        ];
406
407        self::applyRegisteredConfig( $availableRights, $groupPermissions, [], [] );
408    }
409
410    /**
411     * Idempotent merge of WikiLambda's permission-shaped globals.
412     *
413     * Indexed arrays ($wgAvailableRights, $wgPrivilegedGroups, $wgAddGroups[<admin>],
414     * $wgRemoveGroups[<admin>]) are appended only with entries not already present.
415     * Associative permission maps ($wgGroupPermissions[<group>], $wgRateLimits[<right>])
416     * are merged using the '+' operator so values from LocalSettings.php (or any earlier
417     * registration pass) win over our defaults — matching the merge semantics that
418     * MediaWiki's ExtensionProcessor applies when these are declared in extension.json.
419     *
420     * @param string[] $availableRights
421     * @param array<string,array<string,bool>> $groupPermissions
422     * @param array<string,array<string,int[]>> $rateLimits Per-entity-type [count, period] entries per user right
423     * @param array<string,string> $groupChangeRights Map of administrator group => target group
424     */
425    private static function applyRegisteredConfig(
426        array $availableRights,
427        array $groupPermissions,
428        array $rateLimits,
429        array $groupChangeRights
430    ): void {
431        global $wgAvailableRights, $wgGroupPermissions, $wgRateLimits,
432            $wgAddGroups, $wgRemoveGroups, $wgPrivilegedGroups;
433
434        $wgAvailableRights = array_values( array_unique(
435            array_merge( $wgAvailableRights, $availableRights )
436        ) );
437
438        foreach ( $groupPermissions as $group => $perms ) {
439            $wgGroupPermissions[$group] = ( $wgGroupPermissions[$group] ?? [] ) + $perms;
440        }
441
442        if ( $rateLimits ) {
443            foreach ( $rateLimits as $action => $limits ) {
444                $wgRateLimits[$action] = ( $wgRateLimits[$action] ?? [] ) + $limits;
445            }
446        }
447
448        foreach ( $groupChangeRights as $admin => $target ) {
449            foreach ( [ &$wgAddGroups, &$wgRemoveGroups ] as &$bucket ) {
450                $bucket[$admin] ??= [];
451                if ( !in_array( $target, $bucket[$admin], true ) ) {
452                    $bucket[$admin][] = $target;
453                }
454            }
455            unset( $bucket );
456
457            if ( !in_array( $target, $wgPrivilegedGroups, true ) ) {
458                $wgPrivilegedGroups[] = $target;
459            }
460        }
461    }
462
463    /**
464     * Idempotent merge of WikiLambda's OAuth grant declarations.
465     *
466     * Mirrors applyRegisteredConfig()'s semantics: grant→right maps ($wgGrantPermissions[<grant>])
467     * are merged with the '+' operator so values from LocalSettings.php (or an earlier pass) win
468     * over our defaults, and the flat grant→category / grant→risk maps are only filled in for keys
469     * we haven't already declared. Kept out of extension.json so WikiLambda's rights stay off
470     * Special:ListGrants on client-only wikis where the underlying rights aren't registered. (T423542)
471     *
472     * @param array<string,array<string,bool>> $grantPermissions Map of grant group => [ right => true ]
473     * @param array<string,string> $grantPermissionGroups Map of (new) grant group => category
474     * @param array<string,string> $grantRiskGroups Map of (new) grant group => risk level
475     */
476    private static function applyGrantConfig(
477        array $grantPermissions,
478        array $grantPermissionGroups,
479        array $grantRiskGroups
480    ): void {
481        global $wgGrantPermissions, $wgGrantPermissionGroups, $wgGrantRiskGroups;
482
483        foreach ( $grantPermissions as $grant => $rights ) {
484            $wgGrantPermissions[$grant] = ( $wgGrantPermissions[$grant] ?? [] ) + $rights;
485        }
486
487        $wgGrantPermissionGroups += $grantPermissionGroups;
488        $wgGrantRiskGroups += $grantRiskGroups;
489    }
490
491    /**
492     * We do this here because registerExtension() is called too early to use i18n messages.
493     *
494     * @see https://www.mediawiki.org/wiki/Manual:Hooks/MediaWikiServices
495     *
496     * @param MediaWikiServices $services MediaWikiServices instance
497     */
498    public function onMediaWikiServices( $services ) {
499        $config = $services->getMainConfig();
500        // Read the flag directly (not via WikiLambdaMode): this hook fires during
501        // service-container construction, so we use the passed-in $services rather
502        // than re-entering MediaWikiServices::getInstance() to resolve a service.
503        if ( !$config->get( 'WikiLambdaEnableAbstractMode' ) ) {
504            // Nothing for us to do.
505            return;
506        }
507
508        $abstractNamespaceConfig = $config->get( 'WikiLambdaAbstractNamespaces' );
509
510        // We support multiple abstract namespaces, so loop through; initial deployment will only be for one.
511        foreach ( $abstractNamespaceConfig as $namespaceID => $nsdata ) {
512
513            // We only need to do the below steps if we're in dev-mode, and not occupying the main namespace
514            // (T420617) HACK: Ignore all NSes lower than 10, not just NS_MAIN, whilst we fix prod config.
515            if ( $namespaceID > 10 ) {
516                $namespaceEnglishName = $nsdata[0];
517
518                // Register the namespace at all (plus its talk)
519                global $wgExtraNamespaces;
520                $wgExtraNamespaces[ $namespaceID ] = $namespaceEnglishName;
521                $wgExtraNamespaces[ $namespaceID + 1 ] = $namespaceEnglishName . '_talk';
522
523                // Register the namespace as including content
524                global $wgContentNamespaces;
525                $wgContentNamespaces[] = $namespaceID;
526            }
527
528            // Register the namespace as using content our content model
529            global $wgNamespaceContentModels;
530            $wgNamespaceContentModels[ $namespaceID ] = CONTENT_MODEL_ABSTRACT;
531
532            // Ensure that the namespace is protected with the right permissions
533            global $wgNamespaceProtection;
534            $wgNamespaceProtection[ $namespaceID ] = [ 'wikilambda-abstract-edit', 'wikilambda-abstract-create' ];
535
536            // Set that our namespace cannot be transcluded
537            global $wgNonincludableNamespaces;
538            $wgNonincludableNamespaces[] = $namespaceID;
539        }
540    }
541
542    /**
543     * @see https://www.mediawiki.org/wiki/Manual:Hooks/LoadExtensionSchemaUpdates
544     *
545     * @param DatabaseUpdater $updater DatabaseUpdater subclass
546     */
547    public function onLoadExtensionSchemaUpdates( $updater ) {
548        $db = $updater->getDB();
549        $type = $db->getType();
550        $dir = __DIR__ . '/../../sql';
551
552        if ( !in_array( $type, [ 'mysql', 'sqlite', 'postgres' ] ) ) {
553            wfWarn( "Database type '$type' is not supported by the WikiLambda extension." );
554            return;
555        }
556
557        $config = MediaWikiServices::getInstance()->getMainConfig();
558
559        // Drop the legacy per-wiki client usage table; usage is now tracked in the shared
560        // cross-wiki wikifunctions_usage table (T390557). (::has() first, as we'll likely be
561        // in pre-extension registry mode.)
562        if ( $config->has( 'WikiLambdaEnableClientMode' ) && $config->get( 'WikiLambdaEnableClientMode' ) ) {
563            $updater->dropExtensionTable( 'wikifunctionsclient_usage' );
564        }
565
566        // Insert the shared cross-wiki Function-usage table, if needed.
567        // Written by client wikis (pages using {{#function:}}) and by the abstract wiki
568        // (Abstract articles calling Functions), and read by the repo (to display that
569        // usage), so it is created whenever any of those modes is on.
570        // Virtual domain must be defined for the 'virtual-wikifunctions-usage' key:
571        //
572        // Locally, use the same DB with:
573        // $wgVirtualDomainsMapping['virtual-wikifunctions-usage'] = [
574        //     'db' => false
575        // ];
576        //
577        // In production, use the x1 shared DB with:
578        // $wgVirtualDomainsMapping['virtual-wikifunctions-usage'] = [
579        //   'cluster' => 'extension1',
580        //   'db' => 'wikishared'
581        // ];
582        if (
583            ( $config->has( 'WikiLambdaEnableClientMode' ) && $config->get( 'WikiLambdaEnableClientMode' ) ) ||
584            ( $config->has( 'WikiLambdaEnableRepoMode' ) && $config->get( 'WikiLambdaEnableRepoMode' ) ) ||
585            ( $config->has( 'WikiLambdaEnableAbstractMode' ) && $config->get( 'WikiLambdaEnableAbstractMode' ) )
586        ) {
587            // Domain name is kept canonical in WikifunctionsUsageStore::USAGE_VIRTUAL_DOMAIN;
588            // inlined here as a literal so this schema-installation step stands alone.
589            // Create the normalised (wiki, namespace) dimension table first, as
590            // wikifunctions_usage references it by wfu_wiki_id.
591            $updater->addExtensionUpdateOnVirtualDomain( [
592                'virtual-wikifunctions-usage',
593                'addTable',
594                'wikifunctions_usage_wikis',
595                "$dir/$type/table-wikifunctions_usage_wikis.sql",
596                true
597            ] );
598            $updater->addExtensionUpdateOnVirtualDomain( [
599                'virtual-wikifunctions-usage',
600                'addTable',
601                'wikifunctions_usage',
602                "$dir/$type/table-wikifunctions_usage.sql",
603                true
604            ] );
605        }
606
607        // Insert the shared cross-wiki Abstract Wikipedia integrations table, if needed.
608        // Written by abstract client wikis, and read by the abstract wiki. Virtual domain
609        // must be defined for the 'virtual-abstractwiki' key, as for 'virtual-wikifunctions-usage'.
610        if (
611            (
612                $config->has( 'WikiLambdaEnableAbstractClientMode' ) &&
613                $config->get( 'WikiLambdaEnableAbstractClientMode' )
614            ) ||
615            ( $config->has( 'WikiLambdaEnableAbstractMode' ) && $config->get( 'WikiLambdaEnableAbstractMode' ) )
616        ) {
617            $updater->addExtensionUpdateOnVirtualDomain( [
618                'virtual-abstractwiki',
619                'addTable',
620                'abstractwiki_integrations',
621                "$dir/$type/table-abstractwiki_integrations.sql",
622                true
623            ] );
624        }
625
626        // Insert the shared Abstract Wikipedia render status table, if needed.
627        // Only the abstract wiki writes it, from the article store update script.
628        if ( $config->has( 'WikiLambdaEnableAbstractMode' ) && $config->get( 'WikiLambdaEnableAbstractMode' ) ) {
629            $updater->addExtensionUpdateOnVirtualDomain( [
630                'virtual-abstractwiki',
631                'addTable',
632                'abstractwiki_render_status',
633                "$dir/$type/table-abstractwiki_render_status.sql",
634                true
635            ] );
636        }
637
638        // Insert the tables for repo-mode, if needed (Wikifunctions.org and development machines only)
639        if ( $config->has( 'WikiLambdaEnableRepoMode' ) && $config->get( 'WikiLambdaEnableRepoMode' ) ) {
640            $repoTables = [
641                'zobject_labels',
642                'zobject_label_conflicts',
643                'zobject_function_join',
644                'ztester_results',
645                'zlanguages',
646                'zobject_join'
647            ];
648
649            foreach ( $repoTables as $table ) {
650                $updater->addExtensionTable( 'wikilambda_' . $table, "$dir/$type/table-$table.sql" );
651            }
652
653            // Database updates:
654            // (T285368) Add primary label field to labels table
655            $updater->addExtensionField(
656                'wikilambda_zobject_labels',
657                'wlzl_label_primary',
658                "$dir/$type/patch-add-primary-label-field.sql"
659            );
660
661            // (T262089) Add return type field to labels table
662            $updater->addExtensionField(
663                'wikilambda_zobject_labels',
664                'wlzl_return_type',
665                "$dir/$type/patch-add-return-type-field.sql"
666            );
667
668            $updater->addExtensionUpdate( [ [ self::class, 'maybeRestoreInitialContent' ] ] );
669            $updater->addExtensionUpdate( [ [ self::class, 'createInitialContent' ] ] );
670            $updater->addExtensionUpdate( [ [ self::class, 'initializeZObjectJoinTable' ] ] );
671        }
672    }
673
674    /**
675     * Return path of data definition JSON files.
676     *
677     * @return string
678     */
679    protected static function getDataPath() {
680        return dirname( __DIR__ ) . '/../function-schemata/data/definitions/';
681    }
682
683    /**
684     * Enumerate the built-in ZObject definition filenames (e.g. "Z2.json") shipped in the
685     * function-schemata data directory, naturally sorted so that dependencies such as Z2
686     * (Persistent Object) sort ahead of higher-numbered objects.
687     *
688     * @return string[] List of "Z<n>.json" filenames, natsorted
689     */
690    protected static function getInitialContentFilenames(): array {
691        $listing = array_filter(
692            scandir( static::getDataPath() ),
693            static function ( $key ) {
694                return (bool)preg_match( '/^Z\d+\.json$/', $key );
695            }
696        );
697
698        // Naturally sort, so Z2/Persistent Object gets created before others
699        natsort( $listing );
700
701        return $listing;
702    }
703
704    /**
705     * Ensure the ZObject content model is registered, injecting it if necessary. Both the snapshot
706     * restore and the per-object createInitialContent() path create/import ZObject-model revisions,
707     * and update.php can run before the model is otherwise defined.
708     */
709    private static function ensureZObjectContentModelDefined(): void {
710        $contentHandler = MediaWikiServices::getInstance()->getContentHandlerFactory();
711        if ( !$contentHandler->isDefinedModel( CONTENT_MODEL_ZOBJECT ) ) {
712            if ( method_exists( $contentHandler, 'defineContentHandler' ) ) {
713                // @phan-suppress-next-line PhanUndeclaredMethod this apparently phan doesn't take the hint above
714                $contentHandler->defineContentHandler( CONTENT_MODEL_ZOBJECT, ZObjectContentHandler::class );
715            } else {
716                throw new ConfigException( 'WikiLambda content model is not registered and we cannot inject it.' );
717            }
718        }
719    }
720
721    /**
722     * Installer/Updater callback that, on a fresh repo-mode install with a valid committed snapshot
723     * bundle, restores the built-in ZObject pages and their secondary tables from the bundle instead
724     * of leaving createInitialContent() to replay the ~1,500 per-object edits. Records the snapshot
725     * marker on success so createInitialContent()/initializeZObjectJoinTable() no-op in the same run.
726     *
727     * Safe on an existing wiki: it never restores when initial content is already present, and any
728     * missing/invalid/mismatched bundle simply leaves the slow path to run.
729     *
730     * @param DatabaseUpdater $updater
731     */
732    public static function maybeRestoreInitialContent( DatabaseUpdater $updater ) {
733        // Ensure the extension is set up (namespace is defined) even when running update.php outside MW.
734        self::registerExtension();
735
736        if ( !WikiLambdaServices::getMode()->isRepo() ) {
737            return;
738        }
739
740        if ( $updater->updateRowExists( InitialContentSnapshot::MARKER ) ) {
741            return;
742        }
743
744        $db = $updater->getDB();
745        $fname = __METHOD__;
746
747        // Only restore on a genuinely fresh install: if any initial content is already present, this
748        // is an existing (or partially-installed) wiki, so leave createInitialContent() to handle it
749        // and never re-import over live content. The labels table is created earlier in this run.
750        if ( !$db->tableExists( 'wikilambda_zobject_labels', $fname ) ) {
751            return;
752        }
753        $hasContent = $db->newSelectQueryBuilder()
754            ->select( '1' )
755            ->from( 'wikilambda_zobject_labels' )
756            ->limit( 1 )
757            ->caller( $fname )
758            ->fetchField();
759        if ( $hasContent ) {
760            return;
761        }
762
763        // The bundle's revisions use the ZObject content model, so ensure it's registered before
764        // importing (mirrors createInitialContent(); update.php may run before it's otherwise defined).
765        self::ensureZObjectContentModelDefined();
766
767        $restored = InitialContentSnapshot::restore(
768            $db,
769            InitialContentSnapshot::DEFAULT_DIR,
770            static fn ( $m ) => $updater->output( "...$m\n" )
771        );
772        if ( $restored ) {
773            // Use insertUpdateRow() so DatabaseUpdater's own state records the marker, letting the
774            // createInitialContent()/initializeZObjectJoinTable() guards see it in this same run.
775            $updater->insertUpdateRow( InitialContentSnapshot::MARKER );
776        }
777    }
778
779    /**
780     * Installer/Updater callback to create the initial "system" ZObjects on any installation. This
781     * is a callback so that it runs after the tables have been created/updated.
782     *
783     * @param DatabaseUpdater $updater
784     * @param bool $overwrite If true, overwrites the content, else skips if present
785     */
786    public static function createInitialContent( DatabaseUpdater $updater, $overwrite = false ) {
787        // Ensure that the extension is set up (namespace is defined) even when running in update.php outside of MW.
788        self::registerExtension();
789
790        if ( !WikiLambdaServices::getMode()->isRepo() ) {
791            // Nothing for us to do.
792            return;
793        }
794
795        // If the initial content was restored from a snapshot bundle, the pages and their
796        // secondary tables are already in place; skip the ~1,500-object edit-and-purge loop.
797        if ( $updater->updateRowExists( InitialContentSnapshot::MARKER ) ) {
798            $updater->output( "...WikiLambda initial content already restored from snapshot; skipping.\n" );
799            return;
800        }
801
802        self::ensureZObjectContentModelDefined();
803
804        // Note: Hard-coding the English version for messages as this can run without a Context and so no language set.
805        $creatingUserName = wfMessage( 'wikilambda-systemuser' )->inLanguage( 'en' )->text();
806        $creatingUser = User::newSystemUser( $creatingUserName, [ 'steal' => true ] );
807        // We use wikilambda-bootstrapupdatingeditsummary in maintenance scripts when updating.
808        $creatingComment = wfMessage( 'wikilambda-bootstrapcreationeditsummary' )->inLanguage( 'en' )->text();
809
810        if ( !$creatingUser ) {
811            // Something went wrong, give up.
812            return;
813        }
814
815        // The save hook checks the rights to create each built-in object.
816        $userGroupManager = MediaWikiServices::getInstance()->getUserGroupManager();
817        foreach ( [ 'sysop', 'functionmaintainer', 'functioneer', 'wikifunctions-staff' ] as $group ) {
818            $userGroupManager->addUserToGroup( $creatingUser, $group );
819        }
820
821        $initialDataToLoadPath = static::getDataPath();
822
823        $dependenciesFile = file_get_contents( $initialDataToLoadPath . 'dependencies.json' );
824        if ( $dependenciesFile === false ) {
825            throw new ConfigException(
826                'Could not load dependencies file from function-schemata sub-repository of the WikiLambda extension.'
827                    . ' Have you initiated & fetched it? Try `git submodule update --init --recursive`.'
828            );
829        }
830        $dependencies = json_decode( $dependenciesFile, true );
831
832        $initialDataToLoadListing = static::getInitialContentFilenames();
833
834        $inserted = [];
835        foreach ( $initialDataToLoadListing as $filename ) {
836            static::insertContentObject(
837                $updater,
838                $filename,
839                $dependencies,
840                $creatingUser,
841                $creatingComment,
842                $overwrite,
843                $inserted
844            );
845        }
846    }
847
848    /**
849     * Inserts into the database the ZObject found in a given filename of the data directory. First checks
850     * whether the ZObject has any dependencies, according to the dependencies.json manifest file, and if so,
851     * inserts all the dependencies before trying the current ZObject.
852     *
853     * Runs in a static context and so can't be part of the normal code in ZObjectStore.
854     *
855     * @param DatabaseUpdater $updater
856     * @param string $filename
857     * @param array $dependencies
858     * @param User $user
859     * @param string $comment
860     * @param bool $overwrite
861     * @param string[] &$inserted
862     * @param string[] $track
863     * @return bool Has successfully inserted the content object
864     */
865    protected static function insertContentObject(
866        $updater, $filename, $dependencies, $user, $comment, $overwrite = false, &$inserted = [], $track = []
867    ) {
868        $initialDataToLoadPath = static::getDataPath();
869        $updateRowName = "create WikiLambda initial content - $filename";
870
871        $langReg = ZLangRegistry::singleton();
872        $typeReg = ZTypeRegistry::singleton();
873
874        // Check dependencies
875        $zid = substr( $filename, 0, -5 );
876
877        if ( array_key_exists( $zid, $dependencies ) ) {
878            $deps = $dependencies[ $zid ];
879            foreach ( $deps as $dep ) {
880                if (
881                    // Avoid circular dependencies
882                    !in_array( $dep, $track )
883                    && !$langReg->isZidCached( $dep )
884                    && !$typeReg->isZidCached( $dep )
885                ) {
886                    // Call recursively till all dependencies have been added
887                    $success = self::insertContentObject(
888                        $updater,
889                        "$dep.json",
890                        $dependencies,
891                        $user,
892                        $comment,
893                        $overwrite,
894                        $inserted,
895                        array_merge( $track, (array)$dep )
896                    );
897                    // If any of the dependencies fail, we desist on the current insertion
898                    if ( !$success ) {
899                        return false;
900                    }
901                }
902            }
903        }
904
905        $zid = substr( $filename, 0, -5 );
906        $title = Title::newFromText( $zid, NS_MAIN );
907        $services = MediaWikiServices::getInstance();
908        $page = $services->getWikiPageFactory()->newFromTitle( $title );
909
910        // If we don't want to overwrite the ZObjects, and if Zid has already been inserted,
911        // just purge the page to update secondary data and return true
912        if (
913            ( $overwrite && in_array( $zid, $inserted ) ) ||
914            ( !$overwrite && $updater->updateRowExists( $updateRowName ) )
915        ) {
916            $page->doPurge();
917            return true;
918        }
919
920        $data = file_get_contents( $initialDataToLoadPath . $filename );
921        if ( !$data ) {
922            // something went wrong, give up.
923            $updater->output( "\t❌ Unable to load file contents for {$title->getPrefixedText()}.\n" );
924            return false;
925        }
926
927        try {
928            $content = ZObjectContentHandler::makeContent( $data, $title );
929        } catch ( ZErrorException ) {
930            $updater->output( "\t❌ Unable to make a ZObject for {$title->getPrefixedText()}.\n" );
931            return false;
932        }
933
934        static::ensureZObjectStoreIsPresent( $services );
935
936        $pageUpdater = $page->newPageUpdater( $user );
937        $pageUpdater->setContent( SlotRecord::MAIN, $content );
938        $pageUpdater->setRcPatrolStatus( RecentChange::PRC_PATROLLED );
939
940        $pageUpdater->saveRevision(
941            CommentStoreComment::newUnsavedComment( $comment ?? '' ),
942            EDIT_AUTOSUMMARY | EDIT_NEW
943        );
944
945        if ( $pageUpdater->wasSuccessful() ) {
946            $inserted[] = $zid;
947            $updater->insertUpdateRow( $updateRowName );
948            if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
949                // Don't log this during unit testing, quibble thinks it means we're broken.
950                $updater->output( "\tSuccessfully created {$title->getPrefixedText()}.\n" );
951            }
952        } else {
953            $firstError = $pageUpdater->getStatus()->getErrors()[0];
954            $error = wfMessage( $firstError[ 'message' ], $firstError[ 'params' ] )->text();
955            $updater->output( "\t❌ Unable to make a page for {$title->getPrefixedText()}: $error\n" );
956        }
957
958        return $pageUpdater->wasSuccessful();
959    }
960
961    /**
962     * Installer/Updater callback to ensure that wikilambda_zobject_join has been populated for all
963     * existing functions (Z8s). This is a callback so that it runs after the tables have been
964     * created/updated.  This function can be removed when we are confident that all WikiLambda
965     * installations have a fully populated wikilambda_zobject_join table.
966     *
967     * @param DatabaseUpdater $updater
968     */
969    public static function initializeZObjectJoinTable( DatabaseUpdater $updater ) {
970        // A snapshot restore already populated wikilambda_zobject_join, so there's nothing to do.
971        if ( $updater->updateRowExists( InitialContentSnapshot::MARKER ) ) {
972            return;
973        }
974
975        $updateKey = 'Initialized wikilambda_zobject_join for Z8s';
976
977        if ( !$updater->updateRowExists( $updateKey ) ) {
978            static::updateSecondaryTables( $updater, 'Z8' );
979            $updater->insertUpdateRow( $updateKey );
980        } else {
981            $updater->output( "...wikilambda_zobject_join table already initialized\n" );
982        }
983    }
984
985    /**
986     * Ensures that secondary DB tables have been populated for ZObjects of the given zType.  For
987     * each such ZObject, a new instance of ZObjectSecondaryDataUpdate is created and added to
988     * DeferredUpdates.
989     *
990     * N.B. This function assumes that wikilambda_zobject_labels is fully populated; it calls
991     * fetchZidsOfType to get a list of ZObjects of the given zType.
992     *
993     * Note there is a WikiLambda maintenance script (updateSecondaryTables.php) that provides
994     * similar functionality (and with some code that duplicates what's here, which could not
995     * easily be avoided).
996     *
997     * @param DatabaseUpdater $updater
998     * @param string $zType The type of ZObject for which to do updates.
999     * @param bool $verbose If true, print the ZID of each ZObject for which updating is done
1000     * (default = false)
1001     * @param bool $dryRun If true, do nothing, just print the output statements
1002     * (default = false)
1003     */
1004    public static function updateSecondaryTables(
1005        $updater,
1006        $zType,
1007        $verbose = false,
1008        $dryRun = false
1009    ) {
1010        $services = MediaWikiServices::getInstance();
1011
1012        $config = $services->getMainConfig();
1013        if ( !WikiLambdaServices::getMode()->isRepo() ) {
1014            // Nothing for us to do.
1015            return;
1016        }
1017
1018        static::ensureZObjectStoreIsPresent( $services );
1019        $zObjectStore = WikiLambdaServices::getZObjectStore();
1020        $zObjectCache = WikiLambdaServices::getMemcachedWrapper();
1021        $handler = new ZObjectContentHandler( CONTENT_MODEL_ZOBJECT, $config, $zObjectStore, $zObjectCache );
1022
1023        $targets = $zObjectStore->fetchZidsOfType( $zType );
1024
1025        if ( count( $targets ) === 0 ) {
1026            if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1027                // Don't output during unit testing; causes the test to be labeled as risky.
1028                $updater->output( "No ZObjects of type " . $zType . " for which secondary tables need updating\n" );
1029            }
1030            return;
1031        }
1032
1033        if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1034            // Don't output during unit testing; causes the test to be labeled as risky.
1035            if ( $dryRun ) {
1036                $updater->output( "Would have updated" );
1037            } else {
1038                $updater->output( "Updating" );
1039            }
1040            $updater->output( " secondary tables for " . count( $targets ) . " ZObjects of type " .
1041                $zType . "\n" );
1042        }
1043
1044        $offset = 0;
1045        $queryLimit = 10;
1046        do {
1047            $contents = $zObjectStore->fetchBatchZObjects( array_slice( $targets, $offset,
1048                $queryLimit ) );
1049            $offset += $queryLimit;
1050
1051            foreach ( $contents as $zid => $persistentObject ) {
1052                if ( $verbose ) {
1053                    $updater->output( "  $zid" );
1054                }
1055                if ( $dryRun ) {
1056                    continue;
1057                }
1058                $title = Title::newFromText( $zid, NS_MAIN );
1059                $data = json_encode( $persistentObject->getSerialized() );
1060                $content = $handler::makeContent( $data, $title );
1061                $update = new ZObjectSecondaryDataUpdate(
1062                    $title,
1063                    $content,
1064                    $zObjectStore,
1065                    $zObjectCache,
1066                    // Not trying to update the orchestrator cache here, as we're in a maintenance script
1067                    null
1068                );
1069                DeferredUpdates::addUpdate( $update );
1070            }
1071            if ( $verbose ) {
1072                $updater->output( "\n" );
1073            }
1074
1075        } while ( count( $targets ) - $offset > 0 );
1076    }
1077
1078    /**
1079     * Checks for the existence of WikiLambdaZObjectStore in $services, and creates it
1080     * if needed.
1081     *
1082     * @param MediaWikiServices $services
1083     */
1084    private static function ensureZObjectStoreIsPresent( $services ) {
1085        // If we're in the installer, it won't have registered our extension's services yet.
1086        try {
1087            $services->get( 'WikiLambdaZObjectStore' );
1088        } catch ( NoSuchServiceException ) {
1089            $zObjectStore = WikiLambdaServices::buildZObjectStore( $services );
1090            $services->defineService(
1091                'WikiLambdaZObjectStore',
1092                static function () use ( $zObjectStore ) {
1093                    return $zObjectStore;
1094                }
1095            );
1096        }
1097
1098        try {
1099            $services->get( 'WikiLambdaMemcachedWrapper' );
1100        } catch ( NoSuchServiceException ) {
1101            $memcachedWrapper = WikiLambdaServices::buildMemcachedWrapper( $services );
1102            $services->defineService(
1103                'WikiLambdaMemcachedWrapper',
1104                static function () use ( $memcachedWrapper ) {
1105                    return $memcachedWrapper;
1106                }
1107            );
1108        }
1109    }
1110}