Merge "Set namespaces for dtp"
[mediawiki.git] / includes / installer / LocalSettingsGenerator.php
blob0e03298409c22e2ede941cda15630ce1fd0ff933
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 namespace MediaWiki\Installer;
23 use InvalidArgumentException;
25 /**
26 * Generate the LocalSettings.php file.
28 * @ingroup Installer
29 * @since 1.17
31 class LocalSettingsGenerator {
33 /** @var string[] */
34 protected $extensions = [];
35 /** @var string[] */
36 protected $skins = [];
37 /** @var string[] */
38 protected $values = [];
39 /** @var bool[][] */
40 protected $groupPermissions = [];
41 /** @var string */
42 protected $dbSettings = '';
43 /** @var string */
44 protected $IP;
46 /**
47 * @var Installer
49 protected $installer;
51 /**
52 * @param Installer $installer
54 public function __construct( Installer $installer ) {
55 $this->installer = $installer;
57 $this->extensions = $installer->getVar( '_Extensions' );
58 $this->skins = $installer->getVar( '_Skins' );
59 $this->IP = $installer->getVar( 'IP' );
61 $db = $installer->getDBInstaller( $installer->getVar( 'wgDBtype' ) );
63 $confItems = array_merge(
65 'wgServer', 'wgScriptPath',
66 'wgPasswordSender', 'wgImageMagickConvertCommand',
67 'wgLanguageCode', 'wgLocaltimezone', 'wgEnableEmail', 'wgEnableUserEmail',
68 'wgDiff3', 'wgEnotifUserTalk', 'wgEnotifWatchlist', 'wgEmailAuthentication',
69 'wgDBtype', 'wgSecretKey', 'wgRightsUrl', 'wgSitename', 'wgRightsIcon',
70 'wgRightsText', '_MainCacheType', 'wgEnableUploads',
71 '_MemCachedServers', 'wgDBserver', 'wgDBuser',
72 'wgDBpassword', 'wgUseInstantCommons', 'wgUpgradeKey', 'wgDefaultSkin',
73 'wgMetaNamespace', 'wgAuthenticationTokenVersion', 'wgPingback',
74 '_Logo1x', '_LogoTagline', '_LogoWordmark', '_LogoIcon',
75 '_LogoWordmarkWidth', '_LogoWordmarkHeight',
76 '_LogoTaglineWidth', '_LogoTaglineHeight', '_WithDevelopmentSettings'
78 $db->getGlobalNames()
81 // The WebInstaller form field for "Logo" contains a literal "$wgResourceBasePath",
82 // and site admins are told in the help text that they can use $wgStylePath and $wgScriptPath
83 // within their input, such treat this as raw PHP for now.
84 $unescaped = [ 'wgRightsIcon', '_Caches',
85 '_Logo1x', '_LogoWordmark', '_LogoTagline', '_LogoIcon',
87 $boolItems = [
88 'wgEnableEmail', 'wgEnableUserEmail', 'wgEnotifUserTalk',
89 'wgEnotifWatchlist', 'wgEmailAuthentication', 'wgEnableUploads', 'wgUseInstantCommons',
90 'wgPingback',
93 foreach ( $confItems as $c ) {
94 $val = $installer->getVar( $c );
96 if ( in_array( $c, $boolItems ) ) {
97 $val = wfBoolToStr( $val );
100 if ( !in_array( $c, $unescaped ) && $val !== null ) {
101 $val = self::escapePhpString( $val );
104 $this->values[$c] = $val;
107 $this->dbSettings = $db->getLocalSettings();
108 $this->values['wgEmergencyContact'] = $this->values['wgPasswordSender'];
112 * For $wgGroupPermissions, set a given ['group']['permission'] value.
113 * @param string $group Group name
114 * @param array $rightsArr An array of permissions, in the form of:
115 * [ 'right' => true, 'right2' => false ]
117 public function setGroupRights( $group, $rightsArr ) {
118 $this->groupPermissions[$group] = $rightsArr;
122 * Returns the escaped version of a string of php code.
124 * @param string $string
126 * @return string|false
128 public static function escapePhpString( $string ) {
129 if ( is_array( $string ) || is_object( $string ) ) {
130 return false;
133 return strtr(
134 $string,
136 "\n" => "\\n",
137 "\r" => "\\r",
138 "\t" => "\\t",
139 "\\" => "\\\\",
140 "\$" => "\\\$",
141 "\"" => "\\\""
147 * Return the full text of the generated LocalSettings.php file,
148 * including the extensions and skins.
150 * @return string
152 public function getText() {
153 $localSettings = $this->getDefaultText();
155 if ( count( $this->skins ) ) {
156 $localSettings .= "
157 # Enabled skins.
158 # The following skins were automatically enabled:\n";
160 foreach ( $this->skins as $skinName ) {
161 $localSettings .= $this->generateExtEnableLine( 'skins', $skinName );
164 $localSettings .= "\n";
167 if ( count( $this->extensions ) ) {
168 $localSettings .= "
169 # Enabled extensions. Most of the extensions are enabled by adding
170 # wfLoadExtension( 'ExtensionName' );
171 # to LocalSettings.php. Check specific extension documentation for more details.
172 # The following extensions were automatically enabled:\n";
174 foreach ( $this->extensions as $extName ) {
175 $localSettings .= $this->generateExtEnableLine( 'extensions', $extName );
178 $localSettings .= "\n";
181 $localSettings .= "
182 # End of automatically generated settings.
183 # Add more configuration options below.\n\n";
185 return $localSettings;
189 * Generate the appropriate line to enable the given extension or skin
191 * @param string $dir Either "extensions" or "skins"
192 * @param string $name Name of extension/skin
193 * @return string
195 private function generateExtEnableLine( $dir, $name ) {
196 if ( $dir === 'extensions' ) {
197 $jsonFile = 'extension.json';
198 $function = 'wfLoadExtension';
199 } elseif ( $dir === 'skins' ) {
200 $jsonFile = 'skin.json';
201 $function = 'wfLoadSkin';
202 } else {
203 throw new InvalidArgumentException( '$dir was not "extensions" or "skins"' );
206 $encName = self::escapePhpString( $name );
208 if ( file_exists( "{$this->IP}/$dir/$encName/$jsonFile" ) ) {
209 return "$function( '$encName' );\n";
210 } else {
211 return "require_once \"\$IP/$dir/$encName/$encName.php\";\n";
216 * Write the generated LocalSettings to a file
218 * @param string $fileName Full path to filename to write to
220 public function writeFile( $fileName ) {
221 file_put_contents( $fileName, $this->getText() );
225 * @return string
227 protected function buildMemcachedServerList() {
228 $servers = $this->values['_MemCachedServers'];
230 if ( !$servers ) {
231 return '[]';
232 } else {
233 $ret = '[ ';
234 $servers = explode( ',', $servers );
236 foreach ( $servers as $srv ) {
237 $srv = trim( $srv );
238 $ret .= "'$srv', ";
241 return rtrim( $ret, ', ' ) . ' ]';
246 * @return string
248 protected function getDefaultText() {
249 if ( !$this->values['wgImageMagickConvertCommand'] ) {
250 $this->values['wgImageMagickConvertCommand'] = '/usr/bin/convert';
251 $magic = '#';
252 } else {
253 $magic = '';
256 $metaNamespace = '';
257 if ( $this->values['wgMetaNamespace'] !== $this->values['wgSitename'] ) {
258 $metaNamespace = "\$wgMetaNamespace = \"{$this->values['wgMetaNamespace']}\";\n";
261 $groupRights = '';
262 $noFollow = '';
263 if ( $this->groupPermissions ) {
264 $groupRights .= "# The following permissions were set based on your choice in the installer\n";
265 foreach ( $this->groupPermissions as $group => $rightArr ) {
266 $group = self::escapePhpString( $group );
267 foreach ( $rightArr as $right => $perm ) {
268 $right = self::escapePhpString( $right );
269 $groupRights .= "\$wgGroupPermissions[\"$group\"][\"$right\"] = " .
270 wfBoolToStr( $perm ) . ";\n";
273 $groupRights .= "\n";
275 if ( ( isset( $this->groupPermissions['*']['edit'] ) &&
276 $this->groupPermissions['*']['edit'] === false )
277 && ( isset( $this->groupPermissions['*']['createaccount'] ) &&
278 $this->groupPermissions['*']['createaccount'] === false )
279 && ( isset( $this->groupPermissions['*']['read'] ) &&
280 $this->groupPermissions['*']['read'] !== false )
282 $noFollow = "# Set \$wgNoFollowLinks to true if you open up your wiki to editing by\n"
283 . "# the general public and wish to apply nofollow to external links as a\n"
284 . "# deterrent to spammers. Nofollow is not a comprehensive anti-spam solution\n"
285 . "# and open wikis will generally require other anti-spam measures; for more\n"
286 . "# information, see https://www.mediawiki.org/wiki/Manual:Combating_spam\n"
287 . "\$wgNoFollowLinks = false;\n\n";
291 $serverSetting = "";
292 if ( array_key_exists( 'wgServer', $this->values ) && $this->values['wgServer'] !== null ) {
293 $serverSetting = "\n## The protocol and server name to use in fully-qualified URLs\n";
294 $serverSetting .= "\$wgServer = \"{$this->values['wgServer']}\";";
297 switch ( $this->values['_MainCacheType'] ) {
298 case 'anything':
299 case 'db':
300 case 'memcached':
301 case 'accel':
302 $cacheType = 'CACHE_' . strtoupper( $this->values['_MainCacheType'] );
303 break;
304 case 'none':
305 default:
306 $cacheType = 'CACHE_NONE';
309 $mcservers = $this->buildMemcachedServerList();
310 if ( file_exists( dirname( __DIR__ ) . '/PlatformSettings.php' ) ) {
311 $platformSettings = "\n## Include platform/distribution defaults";
312 $platformSettings .= "\nrequire_once \"\$IP/includes/PlatformSettings.php\";";
313 } else {
314 $platformSettings = '';
317 $developmentSettings = '';
318 if ( isset( $this->values['_WithDevelopmentSettings'] ) && $this->values['_WithDevelopmentSettings'] ) {
319 $developmentSettings = "\n## Include DevelopmentSettings.php";
320 $developmentSettings .= "\nrequire_once \"\$IP/includes/DevelopmentSettings.php\";";
323 $this->values['taglineConfig'] = $this->values['_LogoTagline'] ? "\n\t'tagline' => [
324 \"src\" => \"{$this->values['_LogoTagline']}\",
325 \"width\" => {$this->values['_LogoTaglineWidth']},
326 \"height\" => {$this->values['_LogoTaglineHeight']}
327 ]," : "";
329 $this->values['wordmarkConfig'] = $this->values['_LogoWordmark'] ? "\n\t'wordmark' => [
330 \"src\" => \"{$this->values['_LogoWordmark']}\",
331 \"width\" => {$this->values['_LogoWordmarkWidth']},
332 \"height\" => {$this->values['_LogoWordmarkHeight']},
333 ]," : "";
335 $this->values['sidebarLogo'] = $this->values['_Logo1x'] ?: $this->values['_LogoIcon'];
337 $version = MW_VERSION;
338 return "<?php
339 # This file was automatically generated by the MediaWiki {$version}
340 # installer. If you make manual changes, please keep track in case you
341 # need to recreate them later.
343 # See includes/MainConfigSchema.php for all configurable settings
344 # and their default values, but don't forget to make changes in _this_
345 # file, not there.
347 # Further documentation for configuration settings may be found at:
348 # https://www.mediawiki.org/wiki/Manual:Configuration_settings
350 # Protect against web entry
351 if ( !defined( 'MEDIAWIKI' ) ) {
352 exit;
354 {$developmentSettings}
356 {$platformSettings}
358 ## Uncomment this to disable output compression
359 # \$wgDisableOutputCompression = true;
361 \$wgSitename = \"{$this->values['wgSitename']}\";
362 {$metaNamespace}
363 ## The URL base path to the directory containing the wiki;
364 ## defaults for all runtime URL paths are based off of this.
365 ## For more information on customizing the URLs
366 ## (like /w/index.php/Page_title to /wiki/Page_title) please see:
367 ## https://www.mediawiki.org/wiki/Manual:Short_URL
368 \$wgScriptPath = \"{$this->values['wgScriptPath']}\";
369 {$serverSetting}
371 ## The URL path to static resources (images, scripts, etc.)
372 \$wgResourceBasePath = \$wgScriptPath;
374 ## The URL paths to the logo. Make sure you change this from the default,
375 ## or else you'll overwrite your logo when you upgrade!
376 \$wgLogos = [
377 '1x' => \"{$this->values['sidebarLogo']}\",{$this->values['wordmarkConfig']}{$this->values['taglineConfig']}
378 'icon' => \"{$this->values['_LogoIcon']}\",
381 ## UPO means: this is also a user preference option
383 \$wgEnableEmail = {$this->values['wgEnableEmail']};
384 \$wgEnableUserEmail = {$this->values['wgEnableUserEmail']}; # UPO
386 \$wgEmergencyContact = \"{$this->values['wgEmergencyContact']}\";
387 \$wgPasswordSender = \"{$this->values['wgPasswordSender']}\";
389 \$wgEnotifUserTalk = {$this->values['wgEnotifUserTalk']}; # UPO
390 \$wgEnotifWatchlist = {$this->values['wgEnotifWatchlist']}; # UPO
391 \$wgEmailAuthentication = {$this->values['wgEmailAuthentication']};
393 ## Database settings
394 \$wgDBtype = \"{$this->values['wgDBtype']}\";
395 \$wgDBserver = \"{$this->values['wgDBserver']}\";
396 \$wgDBname = \"{$this->values['wgDBname']}\";
397 \$wgDBuser = \"{$this->values['wgDBuser']}\";
398 \$wgDBpassword = \"{$this->values['wgDBpassword']}\";
400 {$this->dbSettings}
402 # Shared database table
403 # This has no effect unless \$wgSharedDB is also set.
404 \$wgSharedTables[] = \"actor\";
406 ## Shared memory settings
407 \$wgMainCacheType = $cacheType;
408 \$wgMemCachedServers = $mcservers;
410 ## To enable image uploads, make sure the 'images' directory
411 ## is writable, then set this to true:
412 \$wgEnableUploads = {$this->values['wgEnableUploads']};
413 {$magic}\$wgUseImageMagick = true;
414 {$magic}\$wgImageMagickConvertCommand = \"{$this->values['wgImageMagickConvertCommand']}\";
416 # InstantCommons allows wiki to use images from https://commons.wikimedia.org
417 \$wgUseInstantCommons = {$this->values['wgUseInstantCommons']};
419 # Periodically send a pingback to https://www.mediawiki.org/ with basic data
420 # about this MediaWiki instance. The Wikimedia Foundation shares this data
421 # with MediaWiki developers to help guide future development efforts.
422 \$wgPingback = {$this->values['wgPingback']};
424 # Site language code, should be one of the list in ./includes/languages/data/Names.php
425 \$wgLanguageCode = \"{$this->values['wgLanguageCode']}\";
427 # Time zone
428 \$wgLocaltimezone = \"{$this->values['wgLocaltimezone']}\";
430 ## Set \$wgCacheDirectory to a writable directory on the web server
431 ## to make your wiki go slightly faster. The directory should not
432 ## be publicly accessible from the web.
433 #\$wgCacheDirectory = \"\$IP/cache\";
435 \$wgSecretKey = \"{$this->values['wgSecretKey']}\";
437 # Changing this will log out all existing sessions.
438 \$wgAuthenticationTokenVersion = \"{$this->values['wgAuthenticationTokenVersion']}\";
440 # Site upgrade key. Must be set to a string (default provided) to turn on the
441 # web installer while LocalSettings.php is in place
442 \$wgUpgradeKey = \"{$this->values['wgUpgradeKey']}\";
444 ## For attaching licensing metadata to pages, and displaying an
445 ## appropriate copyright notice / icon. GNU Free Documentation
446 ## License and Creative Commons licenses are supported so far.
447 \$wgRightsPage = \"\"; # Set to the title of a wiki page that describes your license/copyright
448 \$wgRightsUrl = \"{$this->values['wgRightsUrl']}\";
449 \$wgRightsText = \"{$this->values['wgRightsText']}\";
450 \$wgRightsIcon = \"{$this->values['wgRightsIcon']}\";
452 # Path to the GNU diff3 utility. Used for conflict resolution.
453 \$wgDiff3 = \"{$this->values['wgDiff3']}\";
455 {$groupRights}{$noFollow}## Default skin: you can change the default skin. Use the internal symbolic
456 ## names, e.g. 'vector' or 'monobook':
457 \$wgDefaultSkin = \"{$this->values['wgDefaultSkin']}\";