SiteConfiguration.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. use MediaWiki\Shell\Shell;
  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 = [ '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 = [
  47. * 'wgSomeSetting' => [
  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 = [
  66. * 'wgSomeSetting' => [
  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 = [
  84. * 'wgMergeSetting' = [
  85. * # Value that will be shared among all wikis:
  86. * 'default' => [ NS_USER => true ],
  87. *
  88. * # Leading '+' means merging the array of value with the defaults
  89. * '+beta' => [ NS_HELP => true ],
  90. * ],
  91. * ];
  92. *
  93. * # Get configuration for the German site:
  94. * $conf->get( 'wgMergeSetting', 'de' );
  95. * // --> [ NS_USER => true ];
  96. *
  97. * # Get configuration for the testing site:
  98. * $conf->get( 'wgMergeSetting', 'beta' );
  99. * // --> [ 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. * @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.
  115. *
  116. * @todo Give examples for,
  117. * suffixes:
  118. * $conf->suffixes = [ 'wiki' ];
  119. * localVHosts
  120. * callbacks!
  121. */
  122. class SiteConfiguration {
  123. /**
  124. * Array of suffixes, for self::siteFromDB()
  125. */
  126. public $suffixes = [];
  127. /**
  128. * Array of wikis, should be the same as $wgLocalDatabases
  129. */
  130. public $wikis = [];
  131. /**
  132. * The whole array of settings
  133. */
  134. public $settings = [];
  135. /**
  136. * Array of domains that are local and can be handled by the same server
  137. *
  138. * @deprecated since 1.25; use $wgLocalVirtualHosts instead.
  139. */
  140. public $localVHosts = [];
  141. /**
  142. * Optional callback to load full configuration data.
  143. * @var string|array
  144. */
  145. public $fullLoadCallback = null;
  146. /** Whether or not all data has been loaded */
  147. public $fullLoadDone = false;
  148. /**
  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
  159. *
  160. * @var string|array
  161. */
  162. public $siteParamsCallback = null;
  163. /**
  164. * Configuration cache for getConfig()
  165. * @var array
  166. */
  167. protected $cfgCache = [];
  168. /**
  169. * Retrieves a configuration setting for a given wiki.
  170. * @param string $settingName ID of the setting name to retrieve
  171. * @param string $wiki Wiki ID of the wiki in question.
  172. * @param string|null $suffix The suffix of the wiki in question.
  173. * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
  174. * @param array $wikiTags The tags assigned to the wiki.
  175. * @return mixed The value of the setting requested.
  176. */
  177. public function get( $settingName, $wiki, $suffix = null, $params = [],
  178. $wikiTags = []
  179. ) {
  180. $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
  181. return $this->getSetting( $settingName, $wiki, $params );
  182. }
  183. /**
  184. * Really retrieves a configuration setting for a given wiki.
  185. *
  186. * @param string $settingName ID of the setting name to retrieve.
  187. * @param string $wiki Wiki ID of the wiki in question.
  188. * @param array $params Array of parameters.
  189. * @return mixed The value of the setting requested.
  190. */
  191. protected function getSetting( $settingName, $wiki, array $params ) {
  192. $retval = null;
  193. if ( array_key_exists( $settingName, $this->settings ) ) {
  194. $thisSetting =& $this->settings[$settingName];
  195. do {
  196. // Do individual wiki settings
  197. if ( array_key_exists( $wiki, $thisSetting ) ) {
  198. $retval = $thisSetting[$wiki];
  199. break;
  200. } elseif ( array_key_exists( "+$wiki", $thisSetting ) && is_array( $thisSetting["+$wiki"] ) ) {
  201. $retval = $thisSetting["+$wiki"];
  202. }
  203. // Do tag settings
  204. foreach ( $params['tags'] as $tag ) {
  205. if ( array_key_exists( $tag, $thisSetting ) ) {
  206. if ( is_array( $retval ) && is_array( $thisSetting[$tag] ) ) {
  207. $retval = self::arrayMerge( $retval, $thisSetting[$tag] );
  208. } else {
  209. $retval = $thisSetting[$tag];
  210. }
  211. break 2;
  212. } elseif ( array_key_exists( "+$tag", $thisSetting ) && is_array( $thisSetting["+$tag"] ) ) {
  213. if ( $retval === null ) {
  214. $retval = [];
  215. }
  216. $retval = self::arrayMerge( $retval, $thisSetting["+$tag"] );
  217. }
  218. }
  219. // Do suffix settings
  220. $suffix = $params['suffix'];
  221. if ( !is_null( $suffix ) ) {
  222. if ( array_key_exists( $suffix, $thisSetting ) ) {
  223. if ( is_array( $retval ) && is_array( $thisSetting[$suffix] ) ) {
  224. $retval = self::arrayMerge( $retval, $thisSetting[$suffix] );
  225. } else {
  226. $retval = $thisSetting[$suffix];
  227. }
  228. break;
  229. } elseif ( array_key_exists( "+$suffix", $thisSetting )
  230. && is_array( $thisSetting["+$suffix"] )
  231. ) {
  232. if ( $retval === null ) {
  233. $retval = [];
  234. }
  235. $retval = self::arrayMerge( $retval, $thisSetting["+$suffix"] );
  236. }
  237. }
  238. // Fall back to default.
  239. if ( array_key_exists( 'default', $thisSetting ) ) {
  240. if ( is_array( $retval ) && is_array( $thisSetting['default'] ) ) {
  241. $retval = self::arrayMerge( $retval, $thisSetting['default'] );
  242. } else {
  243. $retval = $thisSetting['default'];
  244. }
  245. break;
  246. }
  247. } while ( false );
  248. }
  249. if ( !is_null( $retval ) && count( $params['params'] ) ) {
  250. foreach ( $params['params'] as $key => $value ) {
  251. $retval = $this->doReplace( '$' . $key, $value, $retval );
  252. }
  253. }
  254. return $retval;
  255. }
  256. /**
  257. * Type-safe string replace; won't do replacements on non-strings
  258. * private?
  259. *
  260. * @param string $from
  261. * @param string $to
  262. * @param string|array $in
  263. * @return string|array
  264. */
  265. function doReplace( $from, $to, $in ) {
  266. if ( is_string( $in ) ) {
  267. return str_replace( $from, $to, $in );
  268. } elseif ( is_array( $in ) ) {
  269. foreach ( $in as $key => $val ) {
  270. $in[$key] = $this->doReplace( $from, $to, $val );
  271. }
  272. return $in;
  273. } else {
  274. return $in;
  275. }
  276. }
  277. /**
  278. * Gets all settings for a wiki
  279. * @param string $wiki Wiki ID of the wiki in question.
  280. * @param string|null $suffix The suffix of the wiki in question.
  281. * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
  282. * @param array $wikiTags The tags assigned to the wiki.
  283. * @return array Array of settings requested.
  284. */
  285. public function getAll( $wiki, $suffix = null, $params = [], $wikiTags = [] ) {
  286. $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
  287. $localSettings = [];
  288. foreach ( $this->settings as $varname => $stuff ) {
  289. $append = false;
  290. $var = $varname;
  291. if ( substr( $varname, 0, 1 ) == '+' ) {
  292. $append = true;
  293. $var = substr( $varname, 1 );
  294. }
  295. $value = $this->getSetting( $varname, $wiki, $params );
  296. if ( $append && is_array( $value ) && is_array( $GLOBALS[$var] ) ) {
  297. $value = self::arrayMerge( $value, $GLOBALS[$var] );
  298. }
  299. if ( !is_null( $value ) ) {
  300. $localSettings[$var] = $value;
  301. }
  302. }
  303. return $localSettings;
  304. }
  305. /**
  306. * Retrieves a configuration setting for a given wiki, forced to a boolean.
  307. * @param string $setting ID of the setting name to retrieve
  308. * @param string $wiki Wiki ID of the wiki in question.
  309. * @param string|null $suffix The suffix of the wiki in question.
  310. * @param array $wikiTags The tags assigned to the wiki.
  311. * @return bool The value of the setting requested.
  312. */
  313. public function getBool( $setting, $wiki, $suffix = null, $wikiTags = [] ) {
  314. return (bool)$this->get( $setting, $wiki, $suffix, [], $wikiTags );
  315. }
  316. /**
  317. * Retrieves an array of local databases
  318. *
  319. * @return array
  320. */
  321. function &getLocalDatabases() {
  322. return $this->wikis;
  323. }
  324. /**
  325. * Retrieves the value of a given setting, and places it in a variable passed by reference.
  326. * @param string $setting ID of the setting name to retrieve
  327. * @param string $wiki Wiki ID of the wiki in question.
  328. * @param string $suffix The suffix of the wiki in question.
  329. * @param array &$var Reference The variable to insert the value into.
  330. * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
  331. * @param array $wikiTags The tags assigned to the wiki.
  332. */
  333. public function extractVar( $setting, $wiki, $suffix, &$var,
  334. $params = [], $wikiTags = []
  335. ) {
  336. $value = $this->get( $setting, $wiki, $suffix, $params, $wikiTags );
  337. if ( !is_null( $value ) ) {
  338. $var = $value;
  339. }
  340. }
  341. /**
  342. * Retrieves the value of a given setting, and places it in its corresponding global variable.
  343. * @param string $setting ID of the setting name to retrieve
  344. * @param string $wiki Wiki ID of the wiki in question.
  345. * @param string|null $suffix The suffix of the wiki in question.
  346. * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
  347. * @param array $wikiTags The tags assigned to the wiki.
  348. */
  349. public function extractGlobal( $setting, $wiki, $suffix = null,
  350. $params = [], $wikiTags = []
  351. ) {
  352. $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
  353. $this->extractGlobalSetting( $setting, $wiki, $params );
  354. }
  355. /**
  356. * @param string $setting
  357. * @param string $wiki
  358. * @param array $params
  359. */
  360. public function extractGlobalSetting( $setting, $wiki, $params ) {
  361. $value = $this->getSetting( $setting, $wiki, $params );
  362. if ( !is_null( $value ) ) {
  363. if ( substr( $setting, 0, 1 ) == '+' && is_array( $value ) ) {
  364. $setting = substr( $setting, 1 );
  365. if ( is_array( $GLOBALS[$setting] ) ) {
  366. $GLOBALS[$setting] = self::arrayMerge( $GLOBALS[$setting], $value );
  367. } else {
  368. $GLOBALS[$setting] = $value;
  369. }
  370. } else {
  371. $GLOBALS[$setting] = $value;
  372. }
  373. }
  374. }
  375. /**
  376. * Retrieves the values of all settings, and places them in their corresponding global variables.
  377. * @param string $wiki Wiki ID of the wiki in question.
  378. * @param string|null $suffix The suffix of the wiki in question.
  379. * @param array $params List of parameters. $.'key' is replaced by $value in all returned data.
  380. * @param array $wikiTags The tags assigned to the wiki.
  381. */
  382. public function extractAllGlobals( $wiki, $suffix = null, $params = [],
  383. $wikiTags = []
  384. ) {
  385. $params = $this->mergeParams( $wiki, $suffix, $params, $wikiTags );
  386. foreach ( $this->settings as $varName => $setting ) {
  387. $this->extractGlobalSetting( $varName, $wiki, $params );
  388. }
  389. }
  390. /**
  391. * Return specific settings for $wiki
  392. * See the documentation of self::$siteParamsCallback for more in-depth
  393. * documentation about this function
  394. *
  395. * @param string $wiki
  396. * @return array
  397. */
  398. protected function getWikiParams( $wiki ) {
  399. static $default = [
  400. 'suffix' => null,
  401. 'lang' => null,
  402. 'tags' => [],
  403. 'params' => [],
  404. ];
  405. if ( !is_callable( $this->siteParamsCallback ) ) {
  406. return $default;
  407. }
  408. $ret = ( $this->siteParamsCallback )( $this, $wiki );
  409. # Validate the returned value
  410. if ( !is_array( $ret ) ) {
  411. return $default;
  412. }
  413. foreach ( $default as $name => $def ) {
  414. if ( !isset( $ret[$name] ) || ( is_array( $default[$name] ) && !is_array( $ret[$name] ) ) ) {
  415. $ret[$name] = $default[$name];
  416. }
  417. }
  418. return $ret;
  419. }
  420. /**
  421. * Merge params between the ones passed to the function and the ones given
  422. * by self::$siteParamsCallback for backward compatibility
  423. * Values returned by self::getWikiParams() have the priority.
  424. *
  425. * @param string $wiki Wiki ID of the wiki in question.
  426. * @param string $suffix The suffix of the wiki in question.
  427. * @param array $params List of parameters. $.'key' is replaced by $value in
  428. * all returned data.
  429. * @param array $wikiTags The tags assigned to the wiki.
  430. * @return array
  431. */
  432. protected function mergeParams( $wiki, $suffix, array $params, array $wikiTags ) {
  433. $ret = $this->getWikiParams( $wiki );
  434. if ( is_null( $ret['suffix'] ) ) {
  435. $ret['suffix'] = $suffix;
  436. }
  437. $ret['tags'] = array_unique( array_merge( $ret['tags'], $wikiTags ) );
  438. $ret['params'] += $params;
  439. // Automatically fill that ones if needed
  440. if ( !isset( $ret['params']['lang'] ) && !is_null( $ret['lang'] ) ) {
  441. $ret['params']['lang'] = $ret['lang'];
  442. }
  443. if ( !isset( $ret['params']['site'] ) && !is_null( $ret['suffix'] ) ) {
  444. $ret['params']['site'] = $ret['suffix'];
  445. }
  446. return $ret;
  447. }
  448. /**
  449. * Work out the site and language name from a database name
  450. * @param string $wiki Wiki ID
  451. *
  452. * @return array
  453. */
  454. public function siteFromDB( $wiki ) {
  455. // Allow override
  456. $def = $this->getWikiParams( $wiki );
  457. if ( !is_null( $def['suffix'] ) && !is_null( $def['lang'] ) ) {
  458. return [ $def['suffix'], $def['lang'] ];
  459. }
  460. $site = null;
  461. $lang = null;
  462. foreach ( $this->suffixes as $altSite => $suffix ) {
  463. if ( $suffix === '' ) {
  464. $site = '';
  465. $lang = $wiki;
  466. break;
  467. } elseif ( substr( $wiki, -strlen( $suffix ) ) == $suffix ) {
  468. $site = is_numeric( $altSite ) ? $suffix : $altSite;
  469. $lang = substr( $wiki, 0, strlen( $wiki ) - strlen( $suffix ) );
  470. break;
  471. }
  472. }
  473. $lang = str_replace( '_', '-', $lang );
  474. return [ $site, $lang ];
  475. }
  476. /**
  477. * Get the resolved (post-setup) configuration of a potentially foreign wiki.
  478. * For foreign wikis, this is expensive, and only works if maintenance
  479. * scripts are setup to handle the --wiki parameter such as in wiki farms.
  480. *
  481. * @param string $wiki
  482. * @param array|string $settings A setting name or array of setting names
  483. * @return mixed|mixed[] Array if $settings is an array, otherwise the value
  484. * @throws MWException
  485. * @since 1.21
  486. */
  487. public function getConfig( $wiki, $settings ) {
  488. global $IP;
  489. $multi = is_array( $settings );
  490. $settings = (array)$settings;
  491. if ( WikiMap::isCurrentWikiId( $wiki ) ) { // $wiki is this wiki
  492. $res = [];
  493. foreach ( $settings as $name ) {
  494. if ( !preg_match( '/^wg[A-Z]/', $name ) ) {
  495. throw new MWException( "Variable '$name' does start with 'wg'." );
  496. } elseif ( !isset( $GLOBALS[$name] ) ) {
  497. throw new MWException( "Variable '$name' is not set." );
  498. }
  499. $res[$name] = $GLOBALS[$name];
  500. }
  501. } else { // $wiki is a foreign wiki
  502. if ( isset( $this->cfgCache[$wiki] ) ) {
  503. $res = array_intersect_key( $this->cfgCache[$wiki], array_flip( $settings ) );
  504. if ( count( $res ) == count( $settings ) ) {
  505. return $multi ? $res : current( $res ); // cache hit
  506. }
  507. } elseif ( !in_array( $wiki, $this->wikis ) ) {
  508. throw new MWException( "No such wiki '$wiki'." );
  509. } else {
  510. $this->cfgCache[$wiki] = [];
  511. }
  512. $result = Shell::makeScriptCommand(
  513. "$IP/maintenance/getConfiguration.php",
  514. [
  515. '--wiki', $wiki,
  516. '--settings', implode( ' ', $settings ),
  517. '--format', 'PHP',
  518. ]
  519. )
  520. // limit.sh breaks this call
  521. ->limits( [ 'memory' => 0, 'filesize' => 0 ] )
  522. ->execute();
  523. $data = trim( $result->getStdout() );
  524. if ( $result->getExitCode() || $data === '' ) {
  525. throw new MWException( "Failed to run getConfiguration.php: {$result->getStdout()}" );
  526. }
  527. $res = unserialize( $data );
  528. if ( !is_array( $res ) ) {
  529. throw new MWException( "Failed to unserialize configuration array." );
  530. }
  531. $this->cfgCache[$wiki] = $this->cfgCache[$wiki] + $res;
  532. }
  533. return $multi ? $res : current( $res );
  534. }
  535. /**
  536. * Merge multiple arrays together.
  537. * On encountering duplicate keys, merge the two, but ONLY if they're arrays.
  538. * PHP's array_merge_recursive() merges ANY duplicate values into arrays,
  539. * which is not fun
  540. *
  541. * @param array $array1
  542. * @param array ...$arrays
  543. *
  544. * @return array
  545. */
  546. static function arrayMerge( array $array1, ...$arrays ) {
  547. $out = $array1;
  548. foreach ( $arrays as $array ) {
  549. foreach ( $array as $key => $value ) {
  550. if ( isset( $out[$key] ) && is_array( $out[$key] ) && is_array( $value ) ) {
  551. $out[$key] = self::arrayMerge( $out[$key], $value );
  552. } elseif ( !isset( $out[$key] ) || !$out[$key] && !is_numeric( $key ) ) {
  553. // Values that evaluate to true given precedence, for the
  554. // primary purpose of merging permissions arrays.
  555. $out[$key] = $value;
  556. } elseif ( is_numeric( $key ) ) {
  557. $out[] = $value;
  558. }
  559. }
  560. }
  561. return $out;
  562. }
  563. public function loadFullData() {
  564. if ( $this->fullLoadCallback && !$this->fullLoadDone ) {
  565. ( $this->fullLoadCallback )( $this );
  566. $this->fullLoadDone = true;
  567. }
  568. }
  569. }