Merge "Combine JavaScript and JSON encoding logic"
[mediawiki.git] / includes / SiteConfiguration.php
blob2d250dfbea96a28fce38b5717c4ec5b42dc65abe
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 = array();
125 * Array of wikis, should be the same as $wgLocalDatabases
127 public $wikis = array();
130 * The whole array of settings
132 public $settings = array();
135 * Array of domains that are local and can be handled by the same server
137 public $localVHosts = array();
140 * Optional callback to load full configuration data.
141 * @var string|array
143 public $fullLoadCallback = null;
145 /** Whether or not all data has been loaded */
146 public $fullLoadDone = false;
149 * A callback function that returns an array with the following keys (all
150 * optional):
151 * - suffix: site's suffix
152 * - lang: site's lang
153 * - tags: array of wiki tags
154 * - params: array of parameters to be replaced
155 * The function will receive the SiteConfiguration instance in the first
156 * argument and the wiki in the second one.
157 * if suffix and lang are passed they will be used for the return value of
158 * self::siteFromDB() and self::$suffixes will be ignored
160 * @var string|array
162 public $siteParamsCallback = null;
165 * Configuration cache for getConfig()
166 * @var array
168 protected $cfgCache = array();
171 * Retrieves a configuration setting for a given wiki.
172 * @param string $settingName ID of the setting name to retrieve
173 * @param string $wiki Wiki ID of the wiki in question.
174 * @param string $suffix The suffix of the wiki in question.
175 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
176 * @param array $wikiTags The tags assigned to the wiki.
177 * @return Mixed the value of the setting requested.
179 public function get( $settingName, $wiki, $suffix = null, $params = array(), $wikiTags = array() ) {
180 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
181 return $this->getSetting( $settingName, $wiki, $params );
185 * Really retrieves a configuration setting for a given wiki.
187 * @param string $settingName ID of the setting name to retrieve.
188 * @param string $wiki Wiki ID of the wiki in question.
189 * @param array $params array of parameters.
190 * @return Mixed the value of the setting requested.
192 protected function getSetting( $settingName, $wiki, /*array*/ $params ) {
193 $retval = null;
194 if( array_key_exists( $settingName, $this->settings ) ) {
195 $thisSetting =& $this->settings[$settingName];
196 do {
197 // Do individual wiki settings
198 if( array_key_exists( $wiki, $thisSetting ) ) {
199 $retval = $thisSetting[$wiki];
200 break;
201 } elseif ( array_key_exists( "+$wiki", $thisSetting ) && is_array( $thisSetting["+$wiki"] ) ) {
202 $retval = $thisSetting["+$wiki"];
205 // Do tag settings
206 foreach( $params['tags'] as $tag ) {
207 if( array_key_exists( $tag, $thisSetting ) ) {
208 if ( isset( $retval ) && is_array( $retval ) && is_array( $thisSetting[$tag] ) ) {
209 $retval = self::arrayMerge( $retval, $thisSetting[$tag] );
210 } else {
211 $retval = $thisSetting[$tag];
213 break 2;
214 } elseif( array_key_exists( "+$tag", $thisSetting ) && is_array( $thisSetting["+$tag"] ) ) {
215 if( !isset( $retval ) ) {
216 $retval = array();
218 $retval = self::arrayMerge( $retval, $thisSetting["+$tag"] );
221 // Do suffix settings
222 $suffix = $params['suffix'];
223 if( !is_null( $suffix ) ) {
224 if( array_key_exists( $suffix, $thisSetting ) ) {
225 if ( isset( $retval ) && is_array( $retval ) && is_array( $thisSetting[$suffix] ) ) {
226 $retval = self::arrayMerge( $retval, $thisSetting[$suffix] );
227 } else {
228 $retval = $thisSetting[$suffix];
230 break;
231 } elseif ( array_key_exists( "+$suffix", $thisSetting ) && is_array( $thisSetting["+$suffix"] ) ) {
232 if ( !isset( $retval ) ) {
233 $retval = array();
235 $retval = self::arrayMerge( $retval, $thisSetting["+$suffix"] );
239 // Fall back to default.
240 if( array_key_exists( 'default', $thisSetting ) ) {
241 if( is_array( $retval ) && is_array( $thisSetting['default'] ) ) {
242 $retval = self::arrayMerge( $retval, $thisSetting['default'] );
243 } else {
244 $retval = $thisSetting['default'];
246 break;
248 } while ( false );
251 if( !is_null( $retval ) && count( $params['params'] ) ) {
252 foreach ( $params['params'] as $key => $value ) {
253 $retval = $this->doReplace( '$' . $key, $value, $retval );
256 return $retval;
260 * Type-safe string replace; won't do replacements on non-strings
261 * private?
263 * @param $from
264 * @param $to
265 * @param $in
266 * @return string
268 function doReplace( $from, $to, $in ) {
269 if( is_string( $in ) ) {
270 return str_replace( $from, $to, $in );
271 } elseif( is_array( $in ) ) {
272 foreach( $in as $key => $val ) {
273 $in[$key] = $this->doReplace( $from, $to, $val );
275 return $in;
276 } else {
277 return $in;
282 * Gets all settings for a wiki
283 * @param string $wiki Wiki ID of the wiki in question.
284 * @param string $suffix The suffix of the wiki in question.
285 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
286 * @param array $wikiTags The tags assigned to the wiki.
287 * @return Array Array of settings requested.
289 public function getAll( $wiki, $suffix = null, $params = array(), $wikiTags = array() ) {
290 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
291 $localSettings = array();
292 foreach( $this->settings as $varname => $stuff ) {
293 $append = false;
294 $var = $varname;
295 if ( substr( $varname, 0, 1 ) == '+' ) {
296 $append = true;
297 $var = substr( $varname, 1 );
300 $value = $this->getSetting( $varname, $wiki, $params );
301 if ( $append && is_array( $value ) && is_array( $GLOBALS[$var] ) ) {
302 $value = self::arrayMerge( $value, $GLOBALS[$var] );
304 if ( !is_null( $value ) ) {
305 $localSettings[$var] = $value;
308 return $localSettings;
312 * Retrieves a configuration setting for a given wiki, forced to a boolean.
313 * @param string $setting ID of the setting name to retrieve
314 * @param string $wiki Wiki ID of the wiki in question.
315 * @param string $suffix The suffix of the wiki in question.
316 * @param array $wikiTags The tags assigned to the wiki.
317 * @return bool The value of the setting requested.
319 public function getBool( $setting, $wiki, $suffix = null, $wikiTags = array() ) {
320 return (bool)($this->get( $setting, $wiki, $suffix, array(), $wikiTags ) );
324 * Retrieves an array of local databases
326 * @return array
328 function &getLocalDatabases() {
329 return $this->wikis;
333 * Retrieves the value of a given setting, and places it in a variable passed by reference.
334 * @param string $setting ID of the setting name to retrieve
335 * @param string $wiki Wiki ID of the wiki in question.
336 * @param string $suffix The suffix of the wiki in question.
337 * @param array $var Reference The variable to insert the value into.
338 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
339 * @param array $wikiTags The tags assigned to the wiki.
341 public function extractVar( $setting, $wiki, $suffix, &$var, $params = array(), $wikiTags = array() ) {
342 $value = $this->get( $setting, $wiki, $suffix, $params, $wikiTags );
343 if ( !is_null( $value ) ) {
344 $var = $value;
349 * Retrieves the value of a given setting, and places it in its corresponding global variable.
350 * @param string $setting ID of the setting name to retrieve
351 * @param string $wiki Wiki ID of the wiki in question.
352 * @param string $suffix The suffix of the wiki in question.
353 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
354 * @param array $wikiTags The tags assigned to the wiki.
356 public function extractGlobal( $setting, $wiki, $suffix = null, $params = array(), $wikiTags = array() ) {
357 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
358 $this->extractGlobalSetting( $setting, $wiki, $params );
362 * @param $setting string
363 * @param $wiki string
364 * @param $params array
366 public function extractGlobalSetting( $setting, $wiki, $params ) {
367 $value = $this->getSetting( $setting, $wiki, $params );
368 if ( !is_null( $value ) ) {
369 if ( substr( $setting, 0, 1 ) == '+' && is_array( $value ) ) {
370 $setting = substr( $setting, 1 );
371 if ( is_array( $GLOBALS[$setting] ) ) {
372 $GLOBALS[$setting] = self::arrayMerge( $GLOBALS[$setting], $value );
373 } else {
374 $GLOBALS[$setting] = $value;
376 } else {
377 $GLOBALS[$setting] = $value;
383 * Retrieves the values of all settings, and places them in their corresponding global variables.
384 * @param string $wiki Wiki ID of the wiki in question.
385 * @param string $suffix The suffix of the wiki in question.
386 * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
387 * @param array $wikiTags The tags assigned to the wiki.
389 public function extractAllGlobals( $wiki, $suffix = null, $params = array(), $wikiTags = array() ) {
390 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
391 foreach ( $this->settings as $varName => $setting ) {
392 $this->extractGlobalSetting( $varName, $wiki, $params );
397 * Return specific settings for $wiki
398 * See the documentation of self::$siteParamsCallback for more in-depth
399 * documentation about this function
401 * @param $wiki String
402 * @return array
404 protected function getWikiParams( $wiki ) {
405 static $default = array(
406 'suffix' => null,
407 'lang' => null,
408 'tags' => array(),
409 'params' => array(),
412 if( !is_callable( $this->siteParamsCallback ) ) {
413 return $default;
416 $ret = call_user_func_array( $this->siteParamsCallback, array( $this, $wiki ) );
417 # Validate the returned value
418 if( !is_array( $ret ) ) {
419 return $default;
422 foreach( $default as $name => $def ) {
423 if( !isset( $ret[$name] ) || ( is_array( $default[$name] ) && !is_array( $ret[$name] ) ) ) {
424 $ret[$name] = $default[$name];
428 return $ret;
432 * Merge params between the ones passed to the function and the ones given
433 * by self::$siteParamsCallback for backward compatibility
434 * Values returned by self::getWikiParams() have the priority.
436 * @param string $wiki Wiki ID of the wiki in question.
437 * @param string $suffix The suffix of the wiki in question.
438 * @param array $params List of parameters. $.'key' is replaced by $value in
439 * all returned data.
440 * @param array $wikiTags The tags assigned to the wiki.
441 * @return array
443 protected function mergeParams( $wiki, $suffix, /*array*/ $params, /*array*/ $wikiTags ) {
444 $ret = $this->getWikiParams( $wiki );
446 if( is_null( $ret['suffix'] ) ) {
447 $ret['suffix'] = $suffix;
450 $ret['tags'] = array_unique( array_merge( $ret['tags'], $wikiTags ) );
452 $ret['params'] += $params;
454 // Automatically fill that ones if needed
455 if( !isset( $ret['params']['lang'] ) && !is_null( $ret['lang'] ) ) {
456 $ret['params']['lang'] = $ret['lang'];
458 if( !isset( $ret['params']['site'] ) && !is_null( $ret['suffix'] ) ) {
459 $ret['params']['site'] = $ret['suffix'];
462 return $ret;
466 * Work out the site and language name from a database name
467 * @param $db
469 * @return array
471 public function siteFromDB( $db ) {
472 // Allow override
473 $def = $this->getWikiParams( $db );
474 if( !is_null( $def['suffix'] ) && !is_null( $def['lang'] ) ) {
475 return array( $def['suffix'], $def['lang'] );
478 $site = null;
479 $lang = null;
480 foreach ( $this->suffixes as $suffix ) {
481 if ( $suffix === '' ) {
482 $site = '';
483 $lang = $db;
484 break;
485 } elseif ( substr( $db, -strlen( $suffix ) ) == $suffix ) {
486 $site = $suffix == 'wiki' ? 'wikipedia' : $suffix;
487 $lang = substr( $db, 0, strlen( $db ) - strlen( $suffix ) );
488 break;
491 $lang = str_replace( '_', '-', $lang );
492 return array( $site, $lang );
496 * Get the resolved (post-setup) configuration of a potentially foreign wiki.
497 * For foreign wikis, this is expensive, and only works if maintenance
498 * scripts are setup to handle the --wiki parameter such as in wiki farms.
500 * @param string $wiki
501 * @param array|string $settings A setting name or array of setting names
502 * @return Array|mixed Array if $settings is an array, otherwise the value
503 * @throws MWException
504 * @since 1.21
506 public function getConfig( $wiki, $settings ) {
507 global $IP;
509 $multi = is_array( $settings );
510 $settings = (array)$settings;
511 if ( $wiki === wfWikiID() ) { // $wiki is this wiki
512 $res = array();
513 foreach ( $settings as $name ) {
514 if ( !preg_match( '/^wg[A-Z]/', $name ) ) {
515 throw new MWException( "Variable '$name' does start with 'wg'." );
516 } elseif ( !isset( $GLOBALS[$name] ) ) {
517 throw new MWException( "Variable '$name' is not set." );
519 $res[$name] = $GLOBALS[$name];
521 } else { // $wiki is a foreign wiki
522 if ( isset( $this->cfgCache[$wiki] ) ) {
523 $res = array_intersect_key( $this->cfgCache[$wiki], array_flip( $settings ) );
524 if ( count( $res ) == count( $settings ) ) {
525 return $res; // cache hit
527 } elseif ( !in_array( $wiki, $this->wikis ) ) {
528 throw new MWException( "No such wiki '$wiki'." );
529 } else {
530 $this->cfgCache[$wiki] = array();
532 $retVal = 1;
533 $cmd = wfShellWikiCmd(
534 "$IP/maintenance/getConfiguration.php",
535 array(
536 '--wiki', $wiki,
537 '--settings', implode( ' ', $settings ),
538 '--format', 'PHP'
541 // ulimit5.sh breaks this call
542 $data = trim( wfShellExec( $cmd, $retVal, array(), array( 'memory' => 0 ) ) );
543 if ( $retVal != 0 || !strlen( $data ) ) {
544 throw new MWException( "Failed to run getConfiguration.php." );
546 $res = unserialize( $data );
547 if ( !is_array( $res ) ) {
548 throw new MWException( "Failed to unserialize configuration array." );
550 $this->cfgCache[$wiki] = $this->cfgCache[$wiki] + $res;
553 return $multi ? $res : current( $res );
557 * Returns true if the given vhost is handled locally.
558 * @param $vhost String
559 * @return bool
561 public function isLocalVHost( $vhost ) {
562 return in_array( $vhost, $this->localVHosts );
566 * Merge multiple arrays together.
567 * On encountering duplicate keys, merge the two, but ONLY if they're arrays.
568 * PHP's array_merge_recursive() merges ANY duplicate values into arrays,
569 * which is not fun
571 * @param $array1 array
573 * @return array
575 static function arrayMerge( $array1/* ... */ ) {
576 $out = $array1;
577 for( $i = 1; $i < func_num_args(); $i++ ) {
578 foreach( func_get_arg( $i ) as $key => $value ) {
579 if ( isset( $out[$key] ) && is_array( $out[$key] ) && is_array( $value ) ) {
580 $out[$key] = self::arrayMerge( $out[$key], $value );
581 } elseif ( !isset( $out[$key] ) || !$out[$key] && !is_numeric( $key ) ) {
582 // Values that evaluate to true given precedence, for the primary purpose of merging permissions arrays.
583 $out[$key] = $value;
584 } elseif ( is_numeric( $key ) ) {
585 $out[] = $value;
590 return $out;
593 public function loadFullData() {
594 if ( $this->fullLoadCallback && !$this->fullLoadDone ) {
595 call_user_func( $this->fullLoadCallback, $this );
596 $this->fullLoadDone = true;