Move ILoadBalancer to Rdbms namespace
[mediawiki.git] / includes / SiteConfiguration.php
blob8d9256b81145a5fd2e4deecf10fefe17586f549d
1 <?php
2 /**
3 * Configuration holder, particularly for multi-wiki sites.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * This is a class for holding configuration settings, particularly for
25 * multi-wiki sites.
27 * A basic synopsis:
29 * Consider a wikifarm having three sites: two production sites, one in English
30 * and one in German, and one testing site. You can assign them easy-to-remember
31 * identifiers - ISO 639 codes 'en' and 'de' for language wikis, and 'beta' for
32 * the testing wiki.
34 * You would thus initialize the site configuration by specifying the wiki
35 * identifiers:
37 * @code
38 * $conf = new SiteConfiguration;
39 * $conf->wikis = [ 'de', 'en', 'beta' ];
40 * @endcode
42 * When configuring the MediaWiki global settings (the $wg variables),
43 * the identifiers will be available to specify settings on a per wiki basis.
45 * @code
46 * $conf->settings = [
47 * 'wgSomeSetting' => [
49 * # production:
50 * 'de' => false,
51 * 'en' => false,
53 * # test:
54 * 'beta => true,
55 * ],
56 * ];
57 * @endcode
59 * With three wikis, that is easy to manage. But what about a farm with
60 * hundreds of wikis? Site configuration provides a special keyword named
61 * 'default' which is the value used when a wiki is not found. Hence
62 * the above code could be written:
64 * @code
65 * $conf->settings = [
66 * 'wgSomeSetting' => [
68 * 'default' => false,
70 * # Enable feature on test
71 * 'beta' => true,
72 * ],
73 * ];
74 * @endcode
77 * Since settings can contain arrays, site configuration provides a way
78 * to merge an array with the default. This is very useful to avoid
79 * repeating settings again and again while still maintaining specific changes
80 * on a per wiki basis.
82 * @code
83 * $conf->settings = [
84 * 'wgMergeSetting' = [
85 * # Value that will be shared among all wikis:
86 * 'default' => [ NS_USER => true ],
88 * # Leading '+' means merging the array of value with the defaults
89 * '+beta' => [ NS_HELP => true ],
90 * ],
91 * ];
93 * # Get configuration for the German site:
94 * $conf->get( 'wgMergeSetting', 'de' );
95 * // --> [ NS_USER => true ];
97 * # Get configuration for the testing site:
98 * $conf->get( 'wgMergeSetting', 'beta' );
99 * // --> [ NS_USER => true, NS_HELP => true ];
100 * @endcode
102 * Finally, to load all configuration settings, extract them in global context:
104 * @code
105 * # Name / identifier of the wiki as set in $conf->wikis
106 * $wikiID = 'beta';
107 * $globals = $conf->getAll( $wikiID );
108 * extract( $globals );
109 * @endcode
111 * @note For WikiMap to function, the configuration must define string values for
112 * $wgServer (or $wgCanonicalServer) and $wgArticlePath, even if these are the
113 * same for all wikis or can be correctly determined by the logic in
114 * Setup.php.
116 * @todo Give examples for,
117 * suffixes:
118 * $conf->suffixes = [ 'wiki' ];
119 * localVHosts
120 * callbacks!
122 class SiteConfiguration {
125 * Array of suffixes, for self::siteFromDB()
127 public $suffixes = [];
130 * Array of wikis, should be the same as $wgLocalDatabases
132 public $wikis = [];
135 * The whole array of settings
137 public $settings = [];
140 * Array of domains that are local and can be handled by the same server
142 * @deprecated since 1.25; use $wgLocalVirtualHosts instead.
144 public $localVHosts = [];
147 * Optional callback to load full configuration data.
148 * @var string|array
150 public $fullLoadCallback = null;
152 /** Whether or not all data has been loaded */
153 public $fullLoadDone = false;
156 * A callback function that returns an array with the following keys (all
157 * optional):
158 * - suffix: site's suffix
159 * - lang: site's lang
160 * - tags: array of wiki tags
161 * - params: array of parameters to be replaced
162 * The function will receive the SiteConfiguration instance in the first
163 * argument and the wiki in the second one.
164 * if suffix and lang are passed they will be used for the return value of
165 * self::siteFromDB() and self::$suffixes will be ignored
167 * @var string|array
169 public $siteParamsCallback = null;
172 * Configuration cache for getConfig()
173 * @var array
175 protected $cfgCache = [];
178 * Retrieves a configuration setting for a given wiki.
179 * @param string $settingName ID of the setting name to retrieve
180 * @param string $wiki Wiki ID of the wiki in question.
181 * @param string $suffix The suffix of the wiki in question.
182 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
183 * @param array $wikiTags The tags assigned to the wiki.
184 * @return mixed The value of the setting requested.
186 public function get( $settingName, $wiki, $suffix = null, $params = [],
187 $wikiTags = []
189 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
190 return $this->getSetting( $settingName, $wiki, $params );
194 * Really retrieves a configuration setting for a given wiki.
196 * @param string $settingName ID of the setting name to retrieve.
197 * @param string $wiki Wiki ID of the wiki in question.
198 * @param array $params Array of parameters.
199 * @return mixed The value of the setting requested.
201 protected function getSetting( $settingName, $wiki, array $params ) {
202 $retval = null;
203 if ( array_key_exists( $settingName, $this->settings ) ) {
204 $thisSetting =& $this->settings[$settingName];
205 do {
206 // Do individual wiki settings
207 if ( array_key_exists( $wiki, $thisSetting ) ) {
208 $retval = $thisSetting[$wiki];
209 break;
210 } elseif ( array_key_exists( "+$wiki", $thisSetting ) && is_array( $thisSetting["+$wiki"] ) ) {
211 $retval = $thisSetting["+$wiki"];
214 // Do tag settings
215 foreach ( $params['tags'] as $tag ) {
216 if ( array_key_exists( $tag, $thisSetting ) ) {
217 if ( is_array( $retval ) && is_array( $thisSetting[$tag] ) ) {
218 $retval = self::arrayMerge( $retval, $thisSetting[$tag] );
219 } else {
220 $retval = $thisSetting[$tag];
222 break 2;
223 } elseif ( array_key_exists( "+$tag", $thisSetting ) && is_array( $thisSetting["+$tag"] ) ) {
224 if ( $retval === null ) {
225 $retval = [];
227 $retval = self::arrayMerge( $retval, $thisSetting["+$tag"] );
230 // Do suffix settings
231 $suffix = $params['suffix'];
232 if ( !is_null( $suffix ) ) {
233 if ( array_key_exists( $suffix, $thisSetting ) ) {
234 if ( is_array( $retval ) && is_array( $thisSetting[$suffix] ) ) {
235 $retval = self::arrayMerge( $retval, $thisSetting[$suffix] );
236 } else {
237 $retval = $thisSetting[$suffix];
239 break;
240 } elseif ( array_key_exists( "+$suffix", $thisSetting )
241 && is_array( $thisSetting["+$suffix"] )
243 if ( $retval === null ) {
244 $retval = [];
246 $retval = self::arrayMerge( $retval, $thisSetting["+$suffix"] );
250 // Fall back to default.
251 if ( array_key_exists( 'default', $thisSetting ) ) {
252 if ( is_array( $retval ) && is_array( $thisSetting['default'] ) ) {
253 $retval = self::arrayMerge( $retval, $thisSetting['default'] );
254 } else {
255 $retval = $thisSetting['default'];
257 break;
259 } while ( false );
262 if ( !is_null( $retval ) && count( $params['params'] ) ) {
263 foreach ( $params['params'] as $key => $value ) {
264 $retval = $this->doReplace( '$' . $key, $value, $retval );
267 return $retval;
271 * Type-safe string replace; won't do replacements on non-strings
272 * private?
274 * @param string $from
275 * @param string $to
276 * @param string|array $in
277 * @return string|array
279 function doReplace( $from, $to, $in ) {
280 if ( is_string( $in ) ) {
281 return str_replace( $from, $to, $in );
282 } elseif ( is_array( $in ) ) {
283 foreach ( $in as $key => $val ) {
284 $in[$key] = $this->doReplace( $from, $to, $val );
286 return $in;
287 } else {
288 return $in;
293 * Gets all settings for a wiki
294 * @param string $wiki Wiki ID of the wiki in question.
295 * @param string $suffix The suffix of the wiki in question.
296 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
297 * @param array $wikiTags The tags assigned to the wiki.
298 * @return array Array of settings requested.
300 public function getAll( $wiki, $suffix = null, $params = [], $wikiTags = [] ) {
301 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
302 $localSettings = [];
303 foreach ( $this->settings as $varname => $stuff ) {
304 $append = false;
305 $var = $varname;
306 if ( substr( $varname, 0, 1 ) == '+' ) {
307 $append = true;
308 $var = substr( $varname, 1 );
311 $value = $this->getSetting( $varname, $wiki, $params );
312 if ( $append && is_array( $value ) && is_array( $GLOBALS[$var] ) ) {
313 $value = self::arrayMerge( $value, $GLOBALS[$var] );
315 if ( !is_null( $value ) ) {
316 $localSettings[$var] = $value;
319 return $localSettings;
323 * Retrieves a configuration setting for a given wiki, forced to a boolean.
324 * @param string $setting ID of the setting name to retrieve
325 * @param string $wiki Wiki ID of the wiki in question.
326 * @param string $suffix The suffix of the wiki in question.
327 * @param array $wikiTags The tags assigned to the wiki.
328 * @return bool The value of the setting requested.
330 public function getBool( $setting, $wiki, $suffix = null, $wikiTags = [] ) {
331 return (bool)$this->get( $setting, $wiki, $suffix, [], $wikiTags );
335 * Retrieves an array of local databases
337 * @return array
339 function &getLocalDatabases() {
340 return $this->wikis;
344 * Retrieves the value of a given setting, and places it in a variable passed by reference.
345 * @param string $setting ID of the setting name to retrieve
346 * @param string $wiki Wiki ID of the wiki in question.
347 * @param string $suffix The suffix of the wiki in question.
348 * @param array $var Reference The variable to insert the value into.
349 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
350 * @param array $wikiTags The tags assigned to the wiki.
352 public function extractVar( $setting, $wiki, $suffix, &$var,
353 $params = [], $wikiTags = []
355 $value = $this->get( $setting, $wiki, $suffix, $params, $wikiTags );
356 if ( !is_null( $value ) ) {
357 $var = $value;
362 * Retrieves the value of a given setting, and places it in its corresponding global variable.
363 * @param string $setting ID of the setting name to retrieve
364 * @param string $wiki Wiki ID of the wiki in question.
365 * @param string $suffix The suffix of the wiki in question.
366 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
367 * @param array $wikiTags The tags assigned to the wiki.
369 public function extractGlobal( $setting, $wiki, $suffix = null,
370 $params = [], $wikiTags = []
372 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
373 $this->extractGlobalSetting( $setting, $wiki, $params );
377 * @param string $setting
378 * @param string $wiki
379 * @param array $params
381 public function extractGlobalSetting( $setting, $wiki, $params ) {
382 $value = $this->getSetting( $setting, $wiki, $params );
383 if ( !is_null( $value ) ) {
384 if ( substr( $setting, 0, 1 ) == '+' && is_array( $value ) ) {
385 $setting = substr( $setting, 1 );
386 if ( is_array( $GLOBALS[$setting] ) ) {
387 $GLOBALS[$setting] = self::arrayMerge( $GLOBALS[$setting], $value );
388 } else {
389 $GLOBALS[$setting] = $value;
391 } else {
392 $GLOBALS[$setting] = $value;
398 * Retrieves the values of all settings, and places them in their corresponding global variables.
399 * @param string $wiki Wiki ID of the wiki in question.
400 * @param string $suffix The suffix of the wiki in question.
401 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
402 * @param array $wikiTags The tags assigned to the wiki.
404 public function extractAllGlobals( $wiki, $suffix = null, $params = [],
405 $wikiTags = []
407 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
408 foreach ( $this->settings as $varName => $setting ) {
409 $this->extractGlobalSetting( $varName, $wiki, $params );
414 * Return specific settings for $wiki
415 * See the documentation of self::$siteParamsCallback for more in-depth
416 * documentation about this function
418 * @param string $wiki
419 * @return array
421 protected function getWikiParams( $wiki ) {
422 static $default = [
423 'suffix' => null,
424 'lang' => null,
425 'tags' => [],
426 'params' => [],
429 if ( !is_callable( $this->siteParamsCallback ) ) {
430 return $default;
433 $ret = call_user_func_array( $this->siteParamsCallback, [ $this, $wiki ] );
434 # Validate the returned value
435 if ( !is_array( $ret ) ) {
436 return $default;
439 foreach ( $default as $name => $def ) {
440 if ( !isset( $ret[$name] ) || ( is_array( $default[$name] ) && !is_array( $ret[$name] ) ) ) {
441 $ret[$name] = $default[$name];
445 return $ret;
449 * Merge params between the ones passed to the function and the ones given
450 * by self::$siteParamsCallback for backward compatibility
451 * Values returned by self::getWikiParams() have the priority.
453 * @param string $wiki Wiki ID of the wiki in question.
454 * @param string $suffix The suffix of the wiki in question.
455 * @param array $params List of parameters. $.'key' is replaced by $value in
456 * all returned data.
457 * @param array $wikiTags The tags assigned to the wiki.
458 * @return array
460 protected function mergeParams( $wiki, $suffix, array $params, array $wikiTags ) {
461 $ret = $this->getWikiParams( $wiki );
463 if ( is_null( $ret['suffix'] ) ) {
464 $ret['suffix'] = $suffix;
467 $ret['tags'] = array_unique( array_merge( $ret['tags'], $wikiTags ) );
469 $ret['params'] += $params;
471 // Automatically fill that ones if needed
472 if ( !isset( $ret['params']['lang'] ) && !is_null( $ret['lang'] ) ) {
473 $ret['params']['lang'] = $ret['lang'];
475 if ( !isset( $ret['params']['site'] ) && !is_null( $ret['suffix'] ) ) {
476 $ret['params']['site'] = $ret['suffix'];
479 return $ret;
483 * Work out the site and language name from a database name
484 * @param string $db
486 * @return array
488 public function siteFromDB( $db ) {
489 // Allow override
490 $def = $this->getWikiParams( $db );
491 if ( !is_null( $def['suffix'] ) && !is_null( $def['lang'] ) ) {
492 return [ $def['suffix'], $def['lang'] ];
495 $site = null;
496 $lang = null;
497 foreach ( $this->suffixes as $altSite => $suffix ) {
498 if ( $suffix === '' ) {
499 $site = '';
500 $lang = $db;
501 break;
502 } elseif ( substr( $db, -strlen( $suffix ) ) == $suffix ) {
503 $site = is_numeric( $altSite ) ? $suffix : $altSite;
504 $lang = substr( $db, 0, strlen( $db ) - strlen( $suffix ) );
505 break;
508 $lang = str_replace( '_', '-', $lang );
509 return [ $site, $lang ];
513 * Get the resolved (post-setup) configuration of a potentially foreign wiki.
514 * For foreign wikis, this is expensive, and only works if maintenance
515 * scripts are setup to handle the --wiki parameter such as in wiki farms.
517 * @param string $wiki
518 * @param array|string $settings A setting name or array of setting names
519 * @return mixed|mixed[] Array if $settings is an array, otherwise the value
520 * @throws MWException
521 * @since 1.21
523 public function getConfig( $wiki, $settings ) {
524 global $IP;
526 $multi = is_array( $settings );
527 $settings = (array)$settings;
528 if ( $wiki === wfWikiID() ) { // $wiki is this wiki
529 $res = [];
530 foreach ( $settings as $name ) {
531 if ( !preg_match( '/^wg[A-Z]/', $name ) ) {
532 throw new MWException( "Variable '$name' does start with 'wg'." );
533 } elseif ( !isset( $GLOBALS[$name] ) ) {
534 throw new MWException( "Variable '$name' is not set." );
536 $res[$name] = $GLOBALS[$name];
538 } else { // $wiki is a foreign wiki
539 if ( isset( $this->cfgCache[$wiki] ) ) {
540 $res = array_intersect_key( $this->cfgCache[$wiki], array_flip( $settings ) );
541 if ( count( $res ) == count( $settings ) ) {
542 return $multi ? $res : current( $res ); // cache hit
544 } elseif ( !in_array( $wiki, $this->wikis ) ) {
545 throw new MWException( "No such wiki '$wiki'." );
546 } else {
547 $this->cfgCache[$wiki] = [];
549 $retVal = 1;
550 $cmd = wfShellWikiCmd(
551 "$IP/maintenance/getConfiguration.php",
553 '--wiki', $wiki,
554 '--settings', implode( ' ', $settings ),
555 '--format', 'PHP'
558 // ulimit5.sh breaks this call
559 $data = trim( wfShellExec( $cmd, $retVal, [], [ 'memory' => 0 ] ) );
560 if ( $retVal != 0 || !strlen( $data ) ) {
561 throw new MWException( "Failed to run getConfiguration.php." );
563 $res = unserialize( $data );
564 if ( !is_array( $res ) ) {
565 throw new MWException( "Failed to unserialize configuration array." );
567 $this->cfgCache[$wiki] = $this->cfgCache[$wiki] + $res;
570 return $multi ? $res : current( $res );
574 * Merge multiple arrays together.
575 * On encountering duplicate keys, merge the two, but ONLY if they're arrays.
576 * PHP's array_merge_recursive() merges ANY duplicate values into arrays,
577 * which is not fun
579 * @param array $array1
581 * @return array
583 static function arrayMerge( $array1/* ... */ ) {
584 $out = $array1;
585 $argsCount = func_num_args();
586 for ( $i = 1; $i < $argsCount; $i++ ) {
587 foreach ( func_get_arg( $i ) as $key => $value ) {
588 if ( isset( $out[$key] ) && is_array( $out[$key] ) && is_array( $value ) ) {
589 $out[$key] = self::arrayMerge( $out[$key], $value );
590 } elseif ( !isset( $out[$key] ) || !$out[$key] && !is_numeric( $key ) ) {
591 // Values that evaluate to true given precedence, for the
592 // primary purpose of merging permissions arrays.
593 $out[$key] = $value;
594 } elseif ( is_numeric( $key ) ) {
595 $out[] = $value;
600 return $out;
603 public function loadFullData() {
604 if ( $this->fullLoadCallback && !$this->fullLoadDone ) {
605 call_user_func( $this->fullLoadCallback, $this );
606 $this->fullLoadDone = true;