Debian Codegraph @

includes/config/SiteConfiguration.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Config;
22
23 use function array_key_exists;
24
25 /**
26 * Configuration holder, particularly for multi-wiki sites.
27 *
28 * A basic synopsis:
29 *
30 * Consider a wikifarm having three sites: two production sites, one in English
31 * and one in German, and one testing site. You can assign them easy-to-remember
32 * identifiers - ISO 639 codes 'en' and 'de' for language wikis, and 'beta' for
33 * the testing wiki.
34 *
35 * You would thus initialize the site configuration by specifying the wiki
36 * identifiers:
37 *
38 * @code
39 * $conf = new SiteConfiguration;
40 * $conf->wikis = [ 'de', 'en', 'beta' ];
41 * @endcode
42 *
43 * When configuring the MediaWiki global settings (the $wg variables),
44 * the identifiers will be available to specify settings on a per wiki basis.
45 *
46 * @code
47 * $conf->settings = [
48 * 'wgSomeSetting' => [
49 *
50 * # production:
51 * 'de' => false,
52 * 'en' => false,
53 *
54 * # test:
55 * 'beta => true,
56 * ],
57 * ];
58 * @endcode
59 *
60 * With three wikis, that is easy to manage. But what about a farm with
61 * hundreds of wikis? Site configuration provides a special keyword named
62 * 'default' which is the value used when a wiki is not found. Hence
63 * the above code could be written:
64 *
65 * @code
66 * $conf->settings = [
67 * 'wgSomeSetting' => [
68 *
69 * 'default' => false,
70 *
71 * # Enable feature on test
72 * 'beta' => true,
73 * ],
74 * ];
75 * @endcode
76 *
77 *
78 * Since settings can contain arrays, site configuration provides a way
79 * to merge an array with the default. This is very useful to avoid
80 * repeating settings again and again while still maintaining specific changes
81 * on a per wiki basis.
82 *
83 * @code
84 * $conf->settings = [
85 * 'wgMergeSetting' = [
86 * # Value that will be shared among all wikis:
87 * 'default' => [ NS_USER => true ],
88 *
89 * # Leading '+' means merging the array of value with the defaults
90 * '+beta' => [ NS_HELP => true ],
91 * ],
92 * ];
93 *
94 * # Get configuration for the German site:
95 * $conf->get( 'wgMergeSetting', 'de' );
96 * // --> [ NS_USER => true ];
97 *
98 * # Get configuration for the testing site:
99 * $conf->get( 'wgMergeSetting', 'beta' );
100 * // --> [ NS_USER => true, NS_HELP => true ];
101 * @endcode
102 *
103 * Finally, to load all configuration settings, extract them in global context:
104 *
105 * @code
106 * # Name / identifier of the wiki as set in $conf->wikis
107 * $wikiID = 'beta';
108 * $globals = $conf->getAll( $wikiID );
109 * extract( $globals );
110 * @endcode
111 *
112 * Simple suffix system where "pt_brwiki" becomes lang="pt-br", site="wiki":
113 *
114 * @code
115 * $conf->suffixes[] = 'wiki';
116 * @endcode
117 *
118 * Suffix is resolved as an alias, so "dewiki" becomes lang="de", site="wikipedia":
119 * @code
120 * $conf->suffixes['wikipedia'] = 'wiki';
121 * @endcode
122 *
123 * @note For WikiMap to function, the configuration must define string values for
124 * $wgServer (or $wgCanonicalServer) and $wgArticlePath, even if these are the
125 * same for all wikis or can be correctly determined by the logic in
126 * Setup.php.
127 */
128 class SiteConfiguration {
129
130 /**
131 * Array of suffixes, for self::siteFromDB()
132 * @var string[]
133 */
134 public $suffixes = [];
135
136 /**
137 * Array of wikis, should be the same as $wgLocalDatabases
138 * @var string[]
139 */
140 public $wikis = [];
141
142 /**
143 * The whole array of settings.
144 *
145 * If the key "@replaceableSettings" exists, it contains a list of setting
146 * names that are subject to string replacement of $params.
147 * @var array
148 */
149 public $settings = [];
150
151 /**
152 * Optional callback to load full configuration data.
153 * @var string|array
154 */
155 public $fullLoadCallback = null;
156
157 /** @var bool Whether or not all data has been loaded */
158 public $fullLoadDone = false;
159
160 /**
161 * A callback function that returns an array with the following keys (all
162 * optional):
163 * - suffix: site's suffix
164 * - lang: site's lang
165 * - tags: array of wiki tags
166 * - params: array of parameters to be replaced
167 * The function will receive the SiteConfiguration instance in the first
168 * argument and the wiki in the second one.
169 * if suffix and lang are passed they will be used for the return value of
170 * self::siteFromDB() and self::$suffixes will be ignored
171 *
172 * @var callable|null
173 */
174 public $siteParamsCallback = null;
175
176 /**
177 * Retrieves a configuration setting for a given wiki.
178 * @param string $settingName ID of the setting name to retrieve
179 * @param string $wiki Wiki ID of the wiki in question.
180 * @param string|null $site The site from ::siteFromDB(), or db suffix.
181 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
182 * @param array $wikiTags The tags assigned to the wiki.
183 * @return mixed The value of the setting requested.
184 */
185 public function get(
186 $settingName,
187 $wiki,
188 $site = null,
189 $params = [],
190 $wikiTags = []
191 ) {
192 $params = $this->mergeParams( $wiki, $site, $params, $wikiTags );
193 $overrides = $this->settings[$settingName] ?? null;
194 $value = $overrides ? $this->processSetting( $overrides, $wiki, $params['tags'] ) : null;
195 if ( !array_key_exists( '@replaceableSettings', $this->settings )
196 || in_array( $settingName, $this->settings['@replaceableSettings'] )
197 ) {
198 $this->doReplacements( $value, $params['replacements'] );
199 }
200 return $value;
201 }
202
203 /**
204 * Retrieve the configuration setting for a given wiki, based on an overrides array.
205 *
206 * General order of precedence:
207 *
208 * 1. Wiki ID, an override specific to the given wiki.
209 * 2. Tag, an override specific to a group of wikis (e.g. wiki family, or db
210 * shard). It is unsupported for the same setting to be set for multiple
211 * tags of which the wiki groups overlap. In that case, whichever is
212 * iterated and matched first wins, where the tag iteration order
213 * is NOT guaranteed.
214 * 3. Default, the default value for all wikis in this wiki farm.
215 *
216 * If the "+" operator is used, with any of these, then the merges will follow the
217 * following order (earlier entries have precedence on clashing sub keys):
218 *
219 * 1. "+wiki"
220 * 2. "tag"
221 * Only one may match here. And upon match, the merge cascade stops.
222 * 3. "+tag"
223 * These are only considered if there was no "tag" match.
224 * Multiple matches are allowed here, although the array values from
225 * multiple tags that contain the same wiki must not overlap, as it is
226 * undocumented how key conflicts among them would be handled.
227 * 4. "default"
228 *
229 * @param array $thisSetting An array of overrides for a given setting.
230 * @param string $wiki Wiki ID of the wiki in question.
231 * @param string[] $tags Array of tags.
232 * @return mixed The value of the setting requested.
233 */
234 private function processSetting( $thisSetting, $wiki, $tags ) {
235 // Optimization: Avoid native type hint on private method called by hot getAll()
236 // <https://gerrit.wikimedia.org/r/c/mediawiki/core/+/820244>
237
238 // Optimization: Fast path for when there is only a default value and no overrides
239 // <https://gerrit.wikimedia.org/r/c/mediawiki/core/+/1220661>
240 if ( count( $thisSetting ) === 1 && array_key_exists( 'default', $thisSetting ) ) {
241 return $thisSetting['default'];
242 }
243
244 $retval = null;
245
246 if ( array_key_exists( $wiki, $thisSetting ) ) {
247 // Found override by Wiki ID.
248 $retval = $thisSetting[$wiki];
249 } else {
250 if ( array_key_exists( "+$wiki", $thisSetting ) ) {
251 // Found mergable override by Wiki ID.
252 // We continue to look for more merge candidates.
253 $retval = $thisSetting["+$wiki"];
254 }
255
256 foreach ( $tags as $tag ) {
257 if ( array_key_exists( $tag, $thisSetting ) ) {
258 if ( is_array( $retval ) && is_array( $thisSetting[$tag] ) ) {
259 // Found a mergable override by Tag, without "+" operator.
260 // Merge it with any "+wiki" match from before, and stop the cascade.
261 $retval = self::arrayMerge( $retval, $thisSetting[$tag] );
262 } else {
263 // Found a non-mergable override by Tag.
264 // This could in theory replace a "+wiki" match, but it should never happen
265 // that a setting uses both mergable array values and non-array values.
266 $retval = $thisSetting[$tag];
267 }
268 return $retval;
269 } elseif ( array_key_exists( "+$tag", $thisSetting ) ) {
270 // Found a mergable override by Tag with "+" operator.
271 // Merge it with any "+wiki" or "+tag" matches from before,
272 // and keep looking for more merge candidates.
273 $retval = self::arrayMerge( $retval ?? [], $thisSetting["+$tag"] );
274 }
275 }
276
277 if ( array_key_exists( 'default', $thisSetting ) ) {
278 if ( is_array( $retval ) && is_array( $thisSetting['default'] ) ) {
279 // Found a mergable default
280 // Merge it with any "+wiki" or "+tag" matches from before.
281 $retval = self::arrayMerge( $retval, $thisSetting['default'] );
282 } else {
283 // Found a default
284 // If any array-based values were built up via "+wiki" or "+tag" matches,
285 // these are thrown away here. We don't support merging array values into
286 // non-array values, and the fallback here is to use the default.
287 $retval = $thisSetting['default'];
288 }
289 }
290 }
291 return $retval;
292 }
293
294 /**
295 * Do string replacements
296 *
297 * @param string &$value
298 * @param array $replacements
299 */
300 private function doReplacements( &$value, $replacements ) {
301 // Optimization: Avoid native type hint on private method called by hot getAll()
302 // <https://gerrit.wikimedia.org/r/c/mediawiki/core/+/820244>
303
304 if ( is_string( $value ) ) {
305 $value = strtr( $value, $replacements );
306 } elseif ( is_array( $value ) ) {
307 foreach ( $value as &$val ) {
308 if ( is_string( $val ) ) {
309 $val = strtr( $val, $replacements );
310 }
311 }
312 }
313 }
314
315 /**
316 * Gets all settings for a wiki
317 * @param string $wiki Wiki ID of the wiki in question.
318 * @param string|null $site The site from ::siteFromDB(), or db suffix.
319 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
320 * @param array $wikiTags The tags assigned to the wiki.
321 * @return array Array of settings requested.
322 */
323 public function getAll( $wiki, $site = null, $params = [], $wikiTags = [] ) {
324 $params = $this->mergeParams( $wiki, $site, $params, $wikiTags );
325 $tags = $params['tags'];
326 $localSettings = [];
327 foreach ( $this->settings as $varname => $overrides ) {
328 $value = $this->processSetting( $overrides, $wiki, $tags );
329 if ( $varname[0] === '+' ) {
330 $varname = substr( $varname, 1 );
331 if ( is_array( $value ) && is_array( $GLOBALS[$varname] ) ) {
332 $value = self::arrayMerge( $value, $GLOBALS[$varname] );
333 }
334 }
335 if ( $value !== null ) {
336 $localSettings[$varname] = $value;
337 }
338 }
339
340 $replacements = $params['replacements'];
341 if ( array_key_exists( '@replaceableSettings', $this->settings ) ) {
342 foreach ( $this->settings['@replaceableSettings'] as $varname ) {
343 if ( array_key_exists( $varname, $localSettings ) ) {
344 $this->doReplacements( $localSettings[$varname], $replacements );
345 }
346 }
347 } else {
348 foreach ( $localSettings as &$value ) {
349 $this->doReplacements( $value, $replacements );
350 }
351 }
352 return $localSettings;
353 }
354
355 /**
356 * Retrieves a configuration setting for a given wiki, forced to a boolean.
357 *
358 * @param string $setting ID of the setting name to retrieve
359 * @param string $wiki Wiki ID of the wiki in question.
360 * @param string|null $site The site from ::siteFromDB(), or db suffix.
361 * @param array $wikiTags The tags assigned to the wiki.
362 * @return bool The value of the setting requested.
363 */
364 public function getBool( $setting, $wiki, $site = null, $wikiTags = [] ) {
365 return (bool)$this->get( $setting, $wiki, $site, [], $wikiTags );
366 }
367
368 /**
369 * Retrieves an array of local databases
370 *
371 * @return array
372 */
373 public function getLocalDatabases() {
374 return $this->wikis;
375 }
376
377 /**
378 * @param string $setting
379 * @param string $wiki
380 * @param array $params
381 */
382 public function extractGlobalSetting( $setting, $wiki, $params ) {
383 $overrides = $this->settings[$setting] ?? null;
384 $value = $overrides ? $this->processSetting( $overrides, $wiki, $params['tags'] ) : null;
385 if ( !array_key_exists( '@replaceableSettings', $this->settings )
386 || in_array( $setting, $this->settings['@replaceableSettings'] )
387 ) {
388 $this->doReplacements( $value, $params['replacements'] );
389 }
390 if ( $value !== null ) {
391 if ( substr( $setting, 0, 1 ) == '+' && is_array( $value ) ) {
392 $setting = substr( $setting, 1 );
393 if ( is_array( $GLOBALS[$setting] ) ) {
394 $GLOBALS[$setting] = self::arrayMerge( $GLOBALS[$setting], $value );
395 } else {
396 $GLOBALS[$setting] = $value;
397 }
398 } else {
399 $GLOBALS[$setting] = $value;
400 }
401 }
402 }
403
404 /**
405 * Retrieves the values of all settings, and places them in their corresponding global variables.
406 * @param string $wiki Wiki ID of the wiki in question.
407 * @param string|null $site The site from ::siteFromDB(), or db suffix.
408 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
409 * @param array $wikiTags The tags assigned to the wiki.
410 */
411 public function extractAllGlobals(
412 $wiki,
413 $site = null,
414 $params = [],
415 $wikiTags = []
416 ) {
417 $params = $this->mergeParams( $wiki, $site, $params, $wikiTags );
418 foreach ( $this->settings as $varName => $setting ) {
419 $this->extractGlobalSetting( $varName, $wiki, $params );
420 }
421 }
422
423 /**
424 * Return specific settings for $wiki
425 * See the documentation of self::$siteParamsCallback for more in-depth
426 * documentation about this function
427 *
428 * @param string $wiki
429 * @return array
430 */
431 protected function getWikiParams( $wiki ) {
432 static $default = [
433 'suffix' => null,
434 'lang' => null,
435 'tags' => [],
436 'params' => [],
437 ];
438
439 if ( !is_callable( $this->siteParamsCallback ) ) {
440 return $default;
441 }
442
443 $ret = ( $this->siteParamsCallback )( $this, $wiki );
444 # Validate the returned value
445 if ( !is_array( $ret ) ) {
446 return $default;
447 }
448
449 foreach ( $default as $name => $def ) {
450 if ( !isset( $ret[$name] ) || ( is_array( $def ) && !is_array( $ret[$name] ) ) ) {
451 $ret[$name] = $def;
452 }
453 }
454
455 return $ret;
456 }
457
458 /**
459 * Merge params between the ones passed to the function and the ones given
460 * by self::$siteParamsCallback for backward compatibility
461 * Values returned by self::getWikiParams() have the priority.
462 *
463 * @param string $wiki Wiki ID of the wiki in question.
464 * @param string|null $site The site from ::siteFromDB(), or db suffix.
465 * @param array $params List of parameters. $.'key' is replaced by $value in
466 * all returned data.
467 * @param array $wikiTags The tags assigned to the wiki.
468 * @return array
469 */
470 protected function mergeParams( $wiki, $site, array $params, array $wikiTags ) {
471 $ret = $this->getWikiParams( $wiki );
472
473 $ret['suffix'] ??= $site;
474
475 // Make tags based on the db suffix (e.g. wiki family) automatically
476 // available for use in wgConf. The user does not have to maintain
477 // wiki tag lookups (e.g. dblists at WMF) for the wiki family.
478 $wikiTags[] = $ret['suffix'];
479
480 $ret['tags'] = array_unique( array_merge( $ret['tags'], $wikiTags ) );
481
482 $ret['params'] += $params;
483
484 // Make the $lang and $site parameters automatically available if they
485 // were provided by `siteParamsCallback` via getWikiParams()
486 if ( !isset( $ret['params']['lang'] ) && $ret['lang'] !== null ) {
487 $ret['params']['lang'] = $ret['lang'];
488 }
489 if ( !isset( $ret['params']['site'] ) && $ret['suffix'] !== null ) {
490 $ret['params']['site'] = $ret['suffix'];
491 }
492
493 // Optimization: For hot getAll() code path, precompute replacements to re-use
494 // over hundreds of processSetting() calls.
495 $ret['replacements'] = [];
496 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
497 foreach ( $ret['params'] as $key => $value ) {
498 $ret['replacements']['$' . $key] = $value;
499 }
500
501 return $ret;
502 }
503
504 /**
505 * Work out the site and language name from a database name
506 *
507 * @param string $wiki Wiki ID
508 * @return array [ string|null $site, string|null $languageCode ]
509 */
510 public function siteFromDB( $wiki ) {
511 // Allow override
512 $def = $this->getWikiParams( $wiki );
513 if ( $def['suffix'] !== null && $def['lang'] !== null ) {
514 return [ $def['suffix'], $def['lang'] ];
515 }
516
517 $languageCode = str_replace( '_', '-', $wiki );
518 foreach ( $this->suffixes as $altSite => $suffix ) {
519 if ( $suffix === '' ) {
520 return [ '', $languageCode ];
521 } elseif ( str_ends_with( $wiki, $suffix ) ) {
522 $site = is_string( $altSite ) ? $altSite : $suffix;
523 $languageCode = substr( $languageCode, 0, -strlen( $suffix ) );
524 return [ $site, $languageCode ];
525 }
526 }
527
528 return [ null, null ];
529 }
530
531 /**
532 * Merge multiple arrays together.
533 * On encountering duplicate keys, merge the two, but ONLY if they're arrays.
534 * PHP's array_merge_recursive() merges ANY duplicate values into arrays,
535 * which is not fun
536 *
537 * @param array $array1
538 * @param array $array2
539 * @return array
540 */
541 private static function arrayMerge( array $array1, array $array2 ) {
542 $out = $array1;
543 foreach ( $array2 as $key => $value ) {
544 if ( isset( $out[$key] ) ) {
545 if ( is_array( $out[$key] ) && is_array( $value ) ) {
546 // Merge the new array into the existing one
547 $out[$key] = self::arrayMerge( $out[$key], $value );
548 } elseif ( is_numeric( $key ) ) {
549 // A numerical key is taken, append the value at the end instead.
550 // It is important that we generally preserve numerical keys and only
551 // fallback to appending values if there are conflicts. This is needed
552 // by configuration variables that hold associative arrays with
553 // meaningful numerical keys, such as $wgNamespacesWithSubpages,
554 // $wgNamespaceProtection, $wgNamespacesToBeSearchedDefault, etc.
555 $out[] = $value;
556 } elseif ( $out[$key] === false ) {
557 // A non-numerical key is taken and holds a false value,
558 // allow it to be overridden always. This exists mainly for the purpose
559 // merging permissions arrays, such as $wgGroupPermissions.
560 $out[$key] = $value;
561 }
562 // Else: The key is already taken and we keep the current value
563
564 } else {
565 // Add a new key.
566 $out[$key] = $value;
567 }
568 }
569
570 return $out;
571 }
572
573 public function loadFullData() {
574 if ( $this->fullLoadCallback && !$this->fullLoadDone ) {
575 ( $this->fullLoadCallback )( $this );
576 $this->fullLoadDone = true;
577 }
578 }
579 }
580
581 /** @deprecated class alias since 1.41 */
582 class_alias( SiteConfiguration::class, 'SiteConfiguration' );