Merge "Http::getProxy() method to get proxy configuration"
[lhc/web/wiklou.git] / includes / SiteConfiguration.php
1 <?php
2 /**
3 * Configuration holder, particularly for multi-wiki sites.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * This is a class for holding configuration settings, particularly for
25 * multi-wiki sites.
26 *
27 * A basic synopsis:
28 *
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.
33 *
34 * You would thus initialize the site configuration by specifying the wiki
35 * identifiers:
36 *
37 * @code
38 * $conf = new SiteConfiguration;
39 * $conf->wikis = array( 'de', 'en', 'beta' );
40 * @endcode
41 *
42 * When configuring the MediaWiki global settings (the $wg variables),
43 * the identifiers will be available to specify settings on a per wiki basis.
44 *
45 * @code
46 * $conf->settings = array(
47 * 'wgSomeSetting' => array(
48 *
49 * # production:
50 * 'de' => false,
51 * 'en' => false,
52 *
53 * # test:
54 * 'beta => true,
55 * ),
56 * );
57 * @endcode
58 *
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:
63 *
64 * @code
65 * $conf->settings = array(
66 * 'wgSomeSetting' => array(
67 *
68 * 'default' => false,
69 *
70 * # Enable feature on test
71 * 'beta' => true,
72 * ),
73 * );
74 * @endcode
75 *
76 *
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.
81 *
82 * @code
83 * $conf->settings = array(
84 * 'wgMergeSetting' = array(
85 * # Value that will be shared among all wikis:
86 * 'default' => array( NS_USER => true ),
87 *
88 * # Leading '+' means merging the array of value with the defaults
89 * '+beta' => array( NS_HELP => true ),
90 * ),
91 * );
92 *
93 * # Get configuration for the German site:
94 * $conf->get( 'wgMergeSetting', 'de' );
95 * // --> array( NS_USER => true );
96 *
97 * # Get configuration for the testing site:
98 * $conf->get( 'wgMergeSetting', 'beta' );
99 * // --> array( NS_USER => true, NS_HELP => true );
100 * @endcode
101 *
102 * Finally, to load all configuration settings, extract them in global context:
103 *
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
110 *
111 * @todo Give examples for,
112 * suffixes:
113 * $conf->suffixes = array( 'wiki' );
114 * localVHosts
115 * callbacks!
116 */
117 class SiteConfiguration {
118
119 /**
120 * Array of suffixes, for self::siteFromDB()
121 */
122 public $suffixes = [];
123
124 /**
125 * Array of wikis, should be the same as $wgLocalDatabases
126 */
127 public $wikis = [];
128
129 /**
130 * The whole array of settings
131 */
132 public $settings = [];
133
134 /**
135 * Array of domains that are local and can be handled by the same server
136 *
137 * @deprecated since 1.25; use $wgLocalVirtualHosts instead.
138 */
139 public $localVHosts = [];
140
141 /**
142 * Optional callback to load full configuration data.
143 * @var string|array
144 */
145 public $fullLoadCallback = null;
146
147 /** Whether or not all data has been loaded */
148 public $fullLoadDone = false;
149
150 /**
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
161 *
162 * @var string|array
163 */
164 public $siteParamsCallback = null;
165
166 /**
167 * Configuration cache for getConfig()
168 * @var array
169 */
170 protected $cfgCache = [];
171
172 /**
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.
180 */
181 public function get( $settingName, $wiki, $suffix = null, $params = [],
182 $wikiTags = []
183 ) {
184 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
185 return $this->getSetting( $settingName, $wiki, $params );
186 }
187
188 /**
189 * Really retrieves a configuration setting for a given wiki.
190 *
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.
195 */
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"];
207 }
208
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];
216 }
217 break 2;
218 } elseif ( array_key_exists( "+$tag", $thisSetting ) && is_array( $thisSetting["+$tag"] ) ) {
219 if ( $retval === null ) {
220 $retval = [];
221 }
222 $retval = self::arrayMerge( $retval, $thisSetting["+$tag"] );
223 }
224 }
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];
233 }
234 break;
235 } elseif ( array_key_exists( "+$suffix", $thisSetting )
236 && is_array( $thisSetting["+$suffix"] )
237 ) {
238 if ( $retval === null ) {
239 $retval = [];
240 }
241 $retval = self::arrayMerge( $retval, $thisSetting["+$suffix"] );
242 }
243 }
244
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'];
251 }
252 break;
253 }
254 } while ( false );
255 }
256
257 if ( !is_null( $retval ) && count( $params['params'] ) ) {
258 foreach ( $params['params'] as $key => $value ) {
259 $retval = $this->doReplace( '$' . $key, $value, $retval );
260 }
261 }
262 return $retval;
263 }
264
265 /**
266 * Type-safe string replace; won't do replacements on non-strings
267 * private?
268 *
269 * @param string $from
270 * @param string $to
271 * @param string|array $in
272 * @return string
273 */
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 );
280 }
281 return $in;
282 } else {
283 return $in;
284 }
285 }
286
287 /**
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.
294 */
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 );
304 }
305
306 $value = $this->getSetting( $varname, $wiki, $params );
307 if ( $append && is_array( $value ) && is_array( $GLOBALS[$var] ) ) {
308 $value = self::arrayMerge( $value, $GLOBALS[$var] );
309 }
310 if ( !is_null( $value ) ) {
311 $localSettings[$var] = $value;
312 }
313 }
314 return $localSettings;
315 }
316
317 /**
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.
324 */
325 public function getBool( $setting, $wiki, $suffix = null, $wikiTags = [] ) {
326 return (bool)$this->get( $setting, $wiki, $suffix, [], $wikiTags );
327 }
328
329 /**
330 * Retrieves an array of local databases
331 *
332 * @return array
333 */
334 function &getLocalDatabases() {
335 return $this->wikis;
336 }
337
338 /**
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.
346 */
347 public function extractVar( $setting, $wiki, $suffix, &$var,
348 $params = [], $wikiTags = []
349 ) {
350 $value = $this->get( $setting, $wiki, $suffix, $params, $wikiTags );
351 if ( !is_null( $value ) ) {
352 $var = $value;
353 }
354 }
355
356 /**
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.
363 */
364 public function extractGlobal( $setting, $wiki, $suffix = null,
365 $params = [], $wikiTags = []
366 ) {
367 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
368 $this->extractGlobalSetting( $setting, $wiki, $params );
369 }
370
371 /**
372 * @param string $setting
373 * @param string $wiki
374 * @param array $params
375 */
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;
385 }
386 } else {
387 $GLOBALS[$setting] = $value;
388 }
389 }
390 }
391
392 /**
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.
398 */
399 public function extractAllGlobals( $wiki, $suffix = null, $params = [],
400 $wikiTags = []
401 ) {
402 $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
403 foreach ( $this->settings as $varName => $setting ) {
404 $this->extractGlobalSetting( $varName, $wiki, $params );
405 }
406 }
407
408 /**
409 * Return specific settings for $wiki
410 * See the documentation of self::$siteParamsCallback for more in-depth
411 * documentation about this function
412 *
413 * @param string $wiki
414 * @return array
415 */
416 protected function getWikiParams( $wiki ) {
417 static $default = [
418 'suffix' => null,
419 'lang' => null,
420 'tags' => [],
421 'params' => [],
422 ];
423
424 if ( !is_callable( $this->siteParamsCallback ) ) {
425 return $default;
426 }
427
428 $ret = call_user_func_array( $this->siteParamsCallback, [ $this, $wiki ] );
429 # Validate the returned value
430 if ( !is_array( $ret ) ) {
431 return $default;
432 }
433
434 foreach ( $default as $name => $def ) {
435 if ( !isset( $ret[$name] ) || ( is_array( $default[$name] ) && !is_array( $ret[$name] ) ) ) {
436 $ret[$name] = $default[$name];
437 }
438 }
439
440 return $ret;
441 }
442
443 /**
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.
447 *
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
454 */
455 protected function mergeParams( $wiki, $suffix, array $params, array $wikiTags ) {
456 $ret = $this->getWikiParams( $wiki );
457
458 if ( is_null( $ret['suffix'] ) ) {
459 $ret['suffix'] = $suffix;
460 }
461
462 $ret['tags'] = array_unique( array_merge( $ret['tags'], $wikiTags ) );
463
464 $ret['params'] += $params;
465
466 // Automatically fill that ones if needed
467 if ( !isset( $ret['params']['lang'] ) && !is_null( $ret['lang'] ) ) {
468 $ret['params']['lang'] = $ret['lang'];
469 }
470 if ( !isset( $ret['params']['site'] ) && !is_null( $ret['suffix'] ) ) {
471 $ret['params']['site'] = $ret['suffix'];
472 }
473
474 return $ret;
475 }
476
477 /**
478 * Work out the site and language name from a database name
479 * @param string $db
480 *
481 * @return array
482 */
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'] ];
488 }
489
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;
501 }
502 }
503 $lang = str_replace( '_', '-', $lang );
504 return [ $site, $lang ];
505 }
506
507 /**
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.
511 *
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
517 */
518 public function getConfig( $wiki, $settings ) {
519 global $IP;
520
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." );
530 }
531 $res[$name] = $GLOBALS[$name];
532 }
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
538 }
539 } elseif ( !in_array( $wiki, $this->wikis ) ) {
540 throw new MWException( "No such wiki '$wiki'." );
541 } else {
542 $this->cfgCache[$wiki] = [];
543 }
544 $retVal = 1;
545 $cmd = wfShellWikiCmd(
546 "$IP/maintenance/getConfiguration.php",
547 [
548 '--wiki', $wiki,
549 '--settings', implode( ' ', $settings ),
550 '--format', 'PHP'
551 ]
552 );
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." );
557 }
558 $res = unserialize( $data );
559 if ( !is_array( $res ) ) {
560 throw new MWException( "Failed to unserialize configuration array." );
561 }
562 $this->cfgCache[$wiki] = $this->cfgCache[$wiki] + $res;
563 }
564
565 return $multi ? $res : current( $res );
566 }
567
568 /**
569 * Returns true if the given vhost is handled locally.
570 *
571 * @deprecated since 1.25; check if the host is in $wgLocalVirtualHosts instead.
572 * @param string $vhost
573 * @return bool
574 */
575 public function isLocalVHost( $vhost ) {
576 return in_array( $vhost, $this->localVHosts );
577 }
578
579 /**
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
584 *
585 * @param array $array1
586 *
587 * @return array
588 */
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;
602 }
603 }
604 }
605
606 return $out;
607 }
608
609 public function loadFullData() {
610 if ( $this->fullLoadCallback && !$this->fullLoadDone ) {
611 call_user_func( $this->fullLoadCallback, $this );
612 $this->fullLoadDone = true;
613 }
614 }
615 }