Only store currently-existing categories in the categories table
[mediawiki.git] / includes / SiteConfiguration.php
blob1a92fb236ad7c156873e67d50f8132aa1f986a7f
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 = array( '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 = array(
47 * 'wgSomeSetting' => array(
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 = array(
66 * 'wgSomeSetting' => array(
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 = array(
84 * 'wgMergeSetting' = array(
85 * # Value that will be shared among all wikis:
86 * 'default' => array( NS_USER => true ),
88 * # Leading '+' means merging the array of value with the defaults
89 * '+beta' => array( NS_HELP => true ),
90 * ),
91 * );
93 * # Get configuration for the German site:
94 * $conf->get( 'wgMergeSetting', 'de' );
95 * // --> array( NS_USER => true );
97 * # Get configuration for the testing site:
98 * $conf->get( 'wgMergeSetting', 'beta' );
99 * // --> array( 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 * @todo Give examples for,
112 * suffixes:
113 * $conf->suffixes = array( 'wiki' );
114 * localVHosts
115 * callbacks!
117 class SiteConfiguration {
120 * Array of suffixes, for self::siteFromDB()
122 public $suffixes = [];
125 * Array of wikis, should be the same as $wgLocalDatabases
127 public $wikis = [];
130 * The whole array of settings
132 public $settings = [];
135 * Array of domains that are local and can be handled by the same server
137 * @deprecated since 1.25; use $wgLocalVirtualHosts instead.
139 public $localVHosts = [];
142 * Optional callback to load full configuration data.
143 * @var string|array
145 public $fullLoadCallback = null;
147 /** Whether or not all data has been loaded */
148 public $fullLoadDone = false;
151 * A callback function that returns an array with the following keys (all
152 * optional):
153 * - suffix: site's suffix
154 * - lang: site's lang
155 * - tags: array of wiki tags
156 * - params: array of parameters to be replaced
157 * The function will receive the SiteConfiguration instance in the first
158 * argument and the wiki in the second one.
159 * if suffix and lang are passed they will be used for the return value of
160 * self::siteFromDB() and self::$suffixes will be ignored
162 * @var string|array
164 public $siteParamsCallback = null;
167 * Configuration cache for getConfig()
168 * @var array
170 protected $cfgCache = [];
173 * Retrieves a configuration setting for a given wiki.
174 * @param string $settingName ID of the setting name to retrieve
175 * @param string $wiki Wiki ID of the wiki in question.
176 * @param string $suffix The suffix of the wiki in question.
177 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
178 * @param array $wikiTags The tags assigned to the wiki.
179 * @return mixed The value of the setting requested.
181 public function get( $settingName, $wiki, $suffix = null, $params = [],
182 $wikiTags = []
184 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
185 return $this->getSetting( $settingName, $wiki, $params );
189 * Really retrieves a configuration setting for a given wiki.
191 * @param string $settingName ID of the setting name to retrieve.
192 * @param string $wiki Wiki ID of the wiki in question.
193 * @param array $params Array of parameters.
194 * @return mixed The value of the setting requested.
196 protected function getSetting( $settingName, $wiki, array $params ) {
197 $retval = null;
198 if ( array_key_exists( $settingName, $this->settings ) ) {
199 $thisSetting =& $this->settings[$settingName];
200 do {
201 // Do individual wiki settings
202 if ( array_key_exists( $wiki, $thisSetting ) ) {
203 $retval = $thisSetting[$wiki];
204 break;
205 } elseif ( array_key_exists( "+$wiki", $thisSetting ) && is_array( $thisSetting["+$wiki"] ) ) {
206 $retval = $thisSetting["+$wiki"];
209 // Do tag settings
210 foreach ( $params['tags'] as $tag ) {
211 if ( array_key_exists( $tag, $thisSetting ) ) {
212 if ( is_array( $retval ) && is_array( $thisSetting[$tag] ) ) {
213 $retval = self::arrayMerge( $retval, $thisSetting[$tag] );
214 } else {
215 $retval = $thisSetting[$tag];
217 break 2;
218 } elseif ( array_key_exists( "+$tag", $thisSetting ) && is_array( $thisSetting["+$tag"] ) ) {
219 if ( $retval === null ) {
220 $retval = [];
222 $retval = self::arrayMerge( $retval, $thisSetting["+$tag"] );
225 // Do suffix settings
226 $suffix = $params['suffix'];
227 if ( !is_null( $suffix ) ) {
228 if ( array_key_exists( $suffix, $thisSetting ) ) {
229 if ( is_array( $retval ) && is_array( $thisSetting[$suffix] ) ) {
230 $retval = self::arrayMerge( $retval, $thisSetting[$suffix] );
231 } else {
232 $retval = $thisSetting[$suffix];
234 break;
235 } elseif ( array_key_exists( "+$suffix", $thisSetting )
236 && is_array( $thisSetting["+$suffix"] )
238 if ( $retval === null ) {
239 $retval = [];
241 $retval = self::arrayMerge( $retval, $thisSetting["+$suffix"] );
245 // Fall back to default.
246 if ( array_key_exists( 'default', $thisSetting ) ) {
247 if ( is_array( $retval ) && is_array( $thisSetting['default'] ) ) {
248 $retval = self::arrayMerge( $retval, $thisSetting['default'] );
249 } else {
250 $retval = $thisSetting['default'];
252 break;
254 } while ( false );
257 if ( !is_null( $retval ) && count( $params['params'] ) ) {
258 foreach ( $params['params'] as $key => $value ) {
259 $retval = $this->doReplace( '$' . $key, $value, $retval );
262 return $retval;
266 * Type-safe string replace; won't do replacements on non-strings
267 * private?
269 * @param string $from
270 * @param string $to
271 * @param string|array $in
272 * @return string
274 function doReplace( $from, $to, $in ) {
275 if ( is_string( $in ) ) {
276 return str_replace( $from, $to, $in );
277 } elseif ( is_array( $in ) ) {
278 foreach ( $in as $key => $val ) {
279 $in[$key] = $this->doReplace( $from, $to, $val );
281 return $in;
282 } else {
283 return $in;
288 * Gets all settings for a wiki
289 * @param string $wiki Wiki ID of the wiki in question.
290 * @param string $suffix The suffix of the wiki in question.
291 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
292 * @param array $wikiTags The tags assigned to the wiki.
293 * @return array Array of settings requested.
295 public function getAll( $wiki, $suffix = null, $params = [], $wikiTags = [] ) {
296 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
297 $localSettings = [];
298 foreach ( $this->settings as $varname => $stuff ) {
299 $append = false;
300 $var = $varname;
301 if ( substr( $varname, 0, 1 ) == '+' ) {
302 $append = true;
303 $var = substr( $varname, 1 );
306 $value = $this->getSetting( $varname, $wiki, $params );
307 if ( $append && is_array( $value ) && is_array( $GLOBALS[$var] ) ) {
308 $value = self::arrayMerge( $value, $GLOBALS[$var] );
310 if ( !is_null( $value ) ) {
311 $localSettings[$var] = $value;
314 return $localSettings;
318 * Retrieves a configuration setting for a given wiki, forced to a boolean.
319 * @param string $setting ID of the setting name to retrieve
320 * @param string $wiki Wiki ID of the wiki in question.
321 * @param string $suffix The suffix of the wiki in question.
322 * @param array $wikiTags The tags assigned to the wiki.
323 * @return bool The value of the setting requested.
325 public function getBool( $setting, $wiki, $suffix = null, $wikiTags = [] ) {
326 return (bool)$this->get( $setting, $wiki, $suffix, [], $wikiTags );
330 * Retrieves an array of local databases
332 * @return array
334 function &getLocalDatabases() {
335 return $this->wikis;
339 * Retrieves the value of a given setting, and places it in a variable passed by reference.
340 * @param string $setting ID of the setting name to retrieve
341 * @param string $wiki Wiki ID of the wiki in question.
342 * @param string $suffix The suffix of the wiki in question.
343 * @param array $var Reference The variable to insert the value into.
344 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
345 * @param array $wikiTags The tags assigned to the wiki.
347 public function extractVar( $setting, $wiki, $suffix, &$var,
348 $params = [], $wikiTags = []
350 $value = $this->get( $setting, $wiki, $suffix, $params, $wikiTags );
351 if ( !is_null( $value ) ) {
352 $var = $value;
357 * Retrieves the value of a given setting, and places it in its corresponding global variable.
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 $suffix The suffix of the wiki in question.
361 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
362 * @param array $wikiTags The tags assigned to the wiki.
364 public function extractGlobal( $setting, $wiki, $suffix = null,
365 $params = [], $wikiTags = []
367 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
368 $this->extractGlobalSetting( $setting, $wiki, $params );
372 * @param string $setting
373 * @param string $wiki
374 * @param array $params
376 public function extractGlobalSetting( $setting, $wiki, $params ) {
377 $value = $this->getSetting( $setting, $wiki, $params );
378 if ( !is_null( $value ) ) {
379 if ( substr( $setting, 0, 1 ) == '+' && is_array( $value ) ) {
380 $setting = substr( $setting, 1 );
381 if ( is_array( $GLOBALS[$setting] ) ) {
382 $GLOBALS[$setting] = self::arrayMerge( $GLOBALS[$setting], $value );
383 } else {
384 $GLOBALS[$setting] = $value;
386 } else {
387 $GLOBALS[$setting] = $value;
393 * Retrieves the values of all settings, and places them in their corresponding global variables.
394 * @param string $wiki Wiki ID of the wiki in question.
395 * @param string $suffix The suffix of the wiki in question.
396 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
397 * @param array $wikiTags The tags assigned to the wiki.
399 public function extractAllGlobals( $wiki, $suffix = null, $params = [],
400 $wikiTags = []
402 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
403 foreach ( $this->settings as $varName => $setting ) {
404 $this->extractGlobalSetting( $varName, $wiki, $params );
409 * Return specific settings for $wiki
410 * See the documentation of self::$siteParamsCallback for more in-depth
411 * documentation about this function
413 * @param string $wiki
414 * @return array
416 protected function getWikiParams( $wiki ) {
417 static $default = [
418 'suffix' => null,
419 'lang' => null,
420 'tags' => [],
421 'params' => [],
424 if ( !is_callable( $this->siteParamsCallback ) ) {
425 return $default;
428 $ret = call_user_func_array( $this->siteParamsCallback, [ $this, $wiki ] );
429 # Validate the returned value
430 if ( !is_array( $ret ) ) {
431 return $default;
434 foreach ( $default as $name => $def ) {
435 if ( !isset( $ret[$name] ) || ( is_array( $default[$name] ) && !is_array( $ret[$name] ) ) ) {
436 $ret[$name] = $default[$name];
440 return $ret;
444 * Merge params between the ones passed to the function and the ones given
445 * by self::$siteParamsCallback for backward compatibility
446 * Values returned by self::getWikiParams() have the priority.
448 * @param string $wiki Wiki ID of the wiki in question.
449 * @param string $suffix The suffix of the wiki in question.
450 * @param array $params List of parameters. $.'key' is replaced by $value in
451 * all returned data.
452 * @param array $wikiTags The tags assigned to the wiki.
453 * @return array
455 protected function mergeParams( $wiki, $suffix, array $params, array $wikiTags ) {
456 $ret = $this->getWikiParams( $wiki );
458 if ( is_null( $ret['suffix'] ) ) {
459 $ret['suffix'] = $suffix;
462 $ret['tags'] = array_unique( array_merge( $ret['tags'], $wikiTags ) );
464 $ret['params'] += $params;
466 // Automatically fill that ones if needed
467 if ( !isset( $ret['params']['lang'] ) && !is_null( $ret['lang'] ) ) {
468 $ret['params']['lang'] = $ret['lang'];
470 if ( !isset( $ret['params']['site'] ) && !is_null( $ret['suffix'] ) ) {
471 $ret['params']['site'] = $ret['suffix'];
474 return $ret;
478 * Work out the site and language name from a database name
479 * @param string $db
481 * @return array
483 public function siteFromDB( $db ) {
484 // Allow override
485 $def = $this->getWikiParams( $db );
486 if ( !is_null( $def['suffix'] ) && !is_null( $def['lang'] ) ) {
487 return [ $def['suffix'], $def['lang'] ];
490 $site = null;
491 $lang = null;
492 foreach ( $this->suffixes as $altSite => $suffix ) {
493 if ( $suffix === '' ) {
494 $site = '';
495 $lang = $db;
496 break;
497 } elseif ( substr( $db, -strlen( $suffix ) ) == $suffix ) {
498 $site = is_numeric( $altSite ) ? $suffix : $altSite;
499 $lang = substr( $db, 0, strlen( $db ) - strlen( $suffix ) );
500 break;
503 $lang = str_replace( '_', '-', $lang );
504 return [ $site, $lang ];
508 * Get the resolved (post-setup) configuration of a potentially foreign wiki.
509 * For foreign wikis, this is expensive, and only works if maintenance
510 * scripts are setup to handle the --wiki parameter such as in wiki farms.
512 * @param string $wiki
513 * @param array|string $settings A setting name or array of setting names
514 * @return mixed|mixed[] Array if $settings is an array, otherwise the value
515 * @throws MWException
516 * @since 1.21
518 public function getConfig( $wiki, $settings ) {
519 global $IP;
521 $multi = is_array( $settings );
522 $settings = (array)$settings;
523 if ( $wiki === wfWikiID() ) { // $wiki is this wiki
524 $res = [];
525 foreach ( $settings as $name ) {
526 if ( !preg_match( '/^wg[A-Z]/', $name ) ) {
527 throw new MWException( "Variable '$name' does start with 'wg'." );
528 } elseif ( !isset( $GLOBALS[$name] ) ) {
529 throw new MWException( "Variable '$name' is not set." );
531 $res[$name] = $GLOBALS[$name];
533 } else { // $wiki is a foreign wiki
534 if ( isset( $this->cfgCache[$wiki] ) ) {
535 $res = array_intersect_key( $this->cfgCache[$wiki], array_flip( $settings ) );
536 if ( count( $res ) == count( $settings ) ) {
537 return $multi ? $res : current( $res ); // cache hit
539 } elseif ( !in_array( $wiki, $this->wikis ) ) {
540 throw new MWException( "No such wiki '$wiki'." );
541 } else {
542 $this->cfgCache[$wiki] = [];
544 $retVal = 1;
545 $cmd = wfShellWikiCmd(
546 "$IP/maintenance/getConfiguration.php",
548 '--wiki', $wiki,
549 '--settings', implode( ' ', $settings ),
550 '--format', 'PHP'
553 // ulimit5.sh breaks this call
554 $data = trim( wfShellExec( $cmd, $retVal, [], [ 'memory' => 0 ] ) );
555 if ( $retVal != 0 || !strlen( $data ) ) {
556 throw new MWException( "Failed to run getConfiguration.php." );
558 $res = unserialize( $data );
559 if ( !is_array( $res ) ) {
560 throw new MWException( "Failed to unserialize configuration array." );
562 $this->cfgCache[$wiki] = $this->cfgCache[$wiki] + $res;
565 return $multi ? $res : current( $res );
569 * Returns true if the given vhost is handled locally.
571 * @deprecated since 1.25; check if the host is in $wgLocalVirtualHosts instead.
572 * @param string $vhost
573 * @return bool
575 public function isLocalVHost( $vhost ) {
576 return in_array( $vhost, $this->localVHosts );
580 * Merge multiple arrays together.
581 * On encountering duplicate keys, merge the two, but ONLY if they're arrays.
582 * PHP's array_merge_recursive() merges ANY duplicate values into arrays,
583 * which is not fun
585 * @param array $array1
587 * @return array
589 static function arrayMerge( $array1/* ... */ ) {
590 $out = $array1;
591 $argsCount = func_num_args();
592 for ( $i = 1; $i < $argsCount; $i++ ) {
593 foreach ( func_get_arg( $i ) as $key => $value ) {
594 if ( isset( $out[$key] ) && is_array( $out[$key] ) && is_array( $value ) ) {
595 $out[$key] = self::arrayMerge( $out[$key], $value );
596 } elseif ( !isset( $out[$key] ) || !$out[$key] && !is_numeric( $key ) ) {
597 // Values that evaluate to true given precedence, for the
598 // primary purpose of merging permissions arrays.
599 $out[$key] = $value;
600 } elseif ( is_numeric( $key ) ) {
601 $out[] = $value;
606 return $out;
609 public function loadFullData() {
610 if ( $this->fullLoadCallback && !$this->fullLoadDone ) {
611 call_user_func( $this->fullLoadCallback, $this );
612 $this->fullLoadDone = true;