Merge "RCFilters: Don't allow underscore in filter or group names"
[lhc/web/wiklou.git] / includes / installer / LocalSettingsGenerator.php
1 <?php
2 /**
3 * Generator for LocalSettings.php file.
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 * @ingroup Deployment
22 */
23
24 /**
25 * Class for generating LocalSettings.php file.
26 *
27 * @ingroup Deployment
28 * @since 1.17
29 */
30 class LocalSettingsGenerator {
31
32 protected $extensions = [];
33 protected $values = [];
34 protected $groupPermissions = [];
35 protected $dbSettings = '';
36 protected $IP;
37
38 /**
39 * @var Installer
40 */
41 protected $installer;
42
43 /**
44 * Constructor.
45 *
46 * @param Installer $installer
47 */
48 public function __construct( Installer $installer ) {
49 $this->installer = $installer;
50
51 $this->extensions = $installer->getVar( '_Extensions' );
52 $this->skins = $installer->getVar( '_Skins' );
53 $this->IP = $installer->getVar( 'IP' );
54
55 $db = $installer->getDBInstaller( $installer->getVar( 'wgDBtype' ) );
56
57 $confItems = array_merge(
58 [
59 'wgServer', 'wgScriptPath',
60 'wgPasswordSender', 'wgImageMagickConvertCommand', 'wgShellLocale',
61 'wgLanguageCode', 'wgEnableEmail', 'wgEnableUserEmail', 'wgDiff3',
62 'wgEnotifUserTalk', 'wgEnotifWatchlist', 'wgEmailAuthentication',
63 'wgDBtype', 'wgSecretKey', 'wgRightsUrl', 'wgSitename', 'wgRightsIcon',
64 'wgRightsText', '_MainCacheType', 'wgEnableUploads',
65 '_MemCachedServers', 'wgDBserver', 'wgDBuser',
66 'wgDBpassword', 'wgUseInstantCommons', 'wgUpgradeKey', 'wgDefaultSkin',
67 'wgMetaNamespace', 'wgLogo', 'wgAuthenticationTokenVersion', 'wgPingback',
68 '_Caches',
69 ],
70 $db->getGlobalNames()
71 );
72
73 $unescaped = [ 'wgRightsIcon', 'wgLogo' ];
74 $boolItems = [
75 'wgEnableEmail', 'wgEnableUserEmail', 'wgEnotifUserTalk',
76 'wgEnotifWatchlist', 'wgEmailAuthentication', 'wgEnableUploads', 'wgUseInstantCommons',
77 'wgPingback',
78 ];
79
80 foreach ( $confItems as $c ) {
81 $val = $installer->getVar( $c );
82
83 if ( in_array( $c, $boolItems ) ) {
84 $val = wfBoolToStr( $val );
85 }
86
87 if ( !in_array( $c, $unescaped ) && $val !== null ) {
88 $val = self::escapePhpString( $val );
89 }
90
91 $this->values[$c] = $val;
92 }
93
94 $this->dbSettings = $db->getLocalSettings();
95 $this->values['wgEmergencyContact'] = $this->values['wgPasswordSender'];
96 }
97
98 /**
99 * For $wgGroupPermissions, set a given ['group']['permission'] value.
100 * @param string $group Group name
101 * @param array $rightsArr An array of permissions, in the form of:
102 * [ 'right' => true, 'right2' => false ]
103 */
104 public function setGroupRights( $group, $rightsArr ) {
105 $this->groupPermissions[$group] = $rightsArr;
106 }
107
108 /**
109 * Returns the escaped version of a string of php code.
110 *
111 * @param string $string
112 *
113 * @return string|false
114 */
115 public static function escapePhpString( $string ) {
116 if ( is_array( $string ) || is_object( $string ) ) {
117 return false;
118 }
119
120 return strtr(
121 $string,
122 [
123 "\n" => "\\n",
124 "\r" => "\\r",
125 "\t" => "\\t",
126 "\\" => "\\\\",
127 "\$" => "\\\$",
128 "\"" => "\\\""
129 ]
130 );
131 }
132
133 /**
134 * Return the full text of the generated LocalSettings.php file,
135 * including the extensions and skins.
136 *
137 * @return string
138 */
139 public function getText() {
140 $localSettings = $this->getDefaultText();
141
142 if ( count( $this->skins ) ) {
143 $localSettings .= "
144 # Enabled skins.
145 # The following skins were automatically enabled:\n";
146
147 foreach ( $this->skins as $skinName ) {
148 $localSettings .= $this->generateExtEnableLine( 'skins', $skinName );
149 }
150
151 $localSettings .= "\n";
152 }
153
154 if ( count( $this->extensions ) ) {
155 $localSettings .= "
156 # Enabled extensions. Most of the extensions are enabled by adding
157 # wfLoadExtensions('ExtensionName');
158 # to LocalSettings.php. Check specific extension documentation for more details.
159 # The following extensions were automatically enabled:\n";
160
161 foreach ( $this->extensions as $extName ) {
162 $localSettings .= $this->generateExtEnableLine( 'extensions', $extName );
163 }
164
165 $localSettings .= "\n";
166 }
167
168 $localSettings .= "
169 # End of automatically generated settings.
170 # Add more configuration options below.\n\n";
171
172 return $localSettings;
173 }
174
175 /**
176 * Generate the appropriate line to enable the given extension or skin
177 *
178 * @param string $dir Either "extensions" or "skins"
179 * @param string $name Name of extension/skin
180 * @throws InvalidArgumentException
181 * @return string
182 */
183 private function generateExtEnableLine( $dir, $name ) {
184 if ( $dir === 'extensions' ) {
185 $jsonFile = 'extension.json';
186 $function = 'wfLoadExtension';
187 } elseif ( $dir === 'skins' ) {
188 $jsonFile = 'skin.json';
189 $function = 'wfLoadSkin';
190 } else {
191 throw new InvalidArgumentException( '$dir was not "extensions" or "skins' );
192 }
193
194 $encName = self::escapePhpString( $name );
195
196 if ( file_exists( "{$this->IP}/$dir/$encName/$jsonFile" ) ) {
197 return "$function( '$encName' );\n";
198 } else {
199 return "require_once \"\$IP/$dir/$encName/$encName.php\";\n";
200 }
201 }
202
203 /**
204 * Write the generated LocalSettings to a file
205 *
206 * @param string $fileName Full path to filename to write to
207 */
208 public function writeFile( $fileName ) {
209 file_put_contents( $fileName, $this->getText() );
210 }
211
212 /**
213 * @return string
214 */
215 protected function buildMemcachedServerList() {
216 $servers = $this->values['_MemCachedServers'];
217
218 if ( !$servers ) {
219 return '[]';
220 } else {
221 $ret = '[ ';
222 $servers = explode( ',', $servers );
223
224 foreach ( $servers as $srv ) {
225 $srv = trim( $srv );
226 $ret .= "'$srv', ";
227 }
228
229 return rtrim( $ret, ', ' ) . ' ]';
230 }
231 }
232
233 /**
234 * @return string
235 */
236 protected function getDefaultText() {
237 if ( !$this->values['wgImageMagickConvertCommand'] ) {
238 $this->values['wgImageMagickConvertCommand'] = '/usr/bin/convert';
239 $magic = '#';
240 } else {
241 $magic = '';
242 }
243
244 if ( !$this->values['wgShellLocale'] ) {
245 $this->values['wgShellLocale'] = 'en_US.UTF-8';
246 $locale = '#';
247 } else {
248 $locale = '';
249 }
250
251 $metaNamespace = '';
252 if ( $this->values['wgMetaNamespace'] !== $this->values['wgSitename'] ) {
253 $metaNamespace = "\$wgMetaNamespace = \"{$this->values['wgMetaNamespace']}\";\n";
254 }
255
256 $groupRights = '';
257 $noFollow = '';
258 if ( $this->groupPermissions ) {
259 $groupRights .= "# The following permissions were set based on your choice in the installer\n";
260 foreach ( $this->groupPermissions as $group => $rightArr ) {
261 $group = self::escapePhpString( $group );
262 foreach ( $rightArr as $right => $perm ) {
263 $right = self::escapePhpString( $right );
264 $groupRights .= "\$wgGroupPermissions['$group']['$right'] = " .
265 wfBoolToStr( $perm ) . ";\n";
266 }
267 }
268 $groupRights .= "\n";
269
270 if ( ( isset( $this->groupPermissions['*']['edit'] ) &&
271 $this->groupPermissions['*']['edit'] === false )
272 && ( isset( $this->groupPermissions['*']['createaccount'] ) &&
273 $this->groupPermissions['*']['createaccount'] === false )
274 && ( isset( $this->groupPermissions['*']['read'] ) &&
275 $this->groupPermissions['*']['read'] !== false )
276 ) {
277 $noFollow = "# Set \$wgNoFollowLinks to true if you open up your wiki to editing by\n"
278 . "# the general public and wish to apply nofollow to external links as a\n"
279 . "# deterrent to spammers. Nofollow is not a comprehensive anti-spam solution\n"
280 . "# and open wikis will generally require other anti-spam measures; for more\n"
281 . "# information, see https://www.mediawiki.org/wiki/Manual:Combating_spam\n"
282 . "\$wgNoFollowLinks = false;\n\n";
283 }
284 }
285
286 $serverSetting = "";
287 if ( array_key_exists( 'wgServer', $this->values ) && $this->values['wgServer'] !== null ) {
288 $serverSetting = "\n## The protocol and server name to use in fully-qualified URLs\n";
289 $serverSetting .= "\$wgServer = \"{$this->values['wgServer']}\";";
290 }
291
292 switch ( $this->values['_MainCacheType'] ) {
293 case 'anything':
294 case 'db':
295 case 'memcached':
296 case 'accel':
297 case 'none':
298 $cacheType = 'CACHE_' . strtoupper( $this->values['_MainCacheType'] );
299 break;
300 default:
301 // If the user skipped the options page,
302 // default to CACHE_ACCEL if available
303 if ( count( $this->values['_Caches'] ) ) {
304 $cacheType = 'CACHE_ACCEL';
305 } else {
306 $cacheType = 'CACHE_NONE';
307 }
308 }
309
310 $mcservers = $this->buildMemcachedServerList();
311
312 return "<?php
313 # This file was automatically generated by the MediaWiki {$GLOBALS['wgVersion']}
314 # installer. If you make manual changes, please keep track in case you
315 # need to recreate them later.
316 #
317 # See includes/DefaultSettings.php for all configurable settings
318 # and their default values, but don't forget to make changes in _this_
319 # file, not there.
320 #
321 # Further documentation for configuration settings may be found at:
322 # https://www.mediawiki.org/wiki/Manual:Configuration_settings
323
324 # Protect against web entry
325 if ( !defined( 'MEDIAWIKI' ) ) {
326 exit;
327 }
328
329 ## Uncomment this to disable output compression
330 # \$wgDisableOutputCompression = true;
331
332 \$wgSitename = \"{$this->values['wgSitename']}\";
333 {$metaNamespace}
334 ## The URL base path to the directory containing the wiki;
335 ## defaults for all runtime URL paths are based off of this.
336 ## For more information on customizing the URLs
337 ## (like /w/index.php/Page_title to /wiki/Page_title) please see:
338 ## https://www.mediawiki.org/wiki/Manual:Short_URL
339 \$wgScriptPath = \"{$this->values['wgScriptPath']}\";
340 ${serverSetting}
341
342 ## The URL path to static resources (images, scripts, etc.)
343 \$wgResourceBasePath = \$wgScriptPath;
344
345 ## The URL path to the logo. Make sure you change this from the default,
346 ## or else you'll overwrite your logo when you upgrade!
347 \$wgLogo = \"{$this->values['wgLogo']}\";
348
349 ## UPO means: this is also a user preference option
350
351 \$wgEnableEmail = {$this->values['wgEnableEmail']};
352 \$wgEnableUserEmail = {$this->values['wgEnableUserEmail']}; # UPO
353
354 \$wgEmergencyContact = \"{$this->values['wgEmergencyContact']}\";
355 \$wgPasswordSender = \"{$this->values['wgPasswordSender']}\";
356
357 \$wgEnotifUserTalk = {$this->values['wgEnotifUserTalk']}; # UPO
358 \$wgEnotifWatchlist = {$this->values['wgEnotifWatchlist']}; # UPO
359 \$wgEmailAuthentication = {$this->values['wgEmailAuthentication']};
360
361 ## Database settings
362 \$wgDBtype = \"{$this->values['wgDBtype']}\";
363 \$wgDBserver = \"{$this->values['wgDBserver']}\";
364 \$wgDBname = \"{$this->values['wgDBname']}\";
365 \$wgDBuser = \"{$this->values['wgDBuser']}\";
366 \$wgDBpassword = \"{$this->values['wgDBpassword']}\";
367
368 {$this->dbSettings}
369
370 ## Shared memory settings
371 \$wgMainCacheType = $cacheType;
372 \$wgMemCachedServers = $mcservers;
373
374 ## To enable image uploads, make sure the 'images' directory
375 ## is writable, then set this to true:
376 \$wgEnableUploads = {$this->values['wgEnableUploads']};
377 {$magic}\$wgUseImageMagick = true;
378 {$magic}\$wgImageMagickConvertCommand = \"{$this->values['wgImageMagickConvertCommand']}\";
379
380 # InstantCommons allows wiki to use images from https://commons.wikimedia.org
381 \$wgUseInstantCommons = {$this->values['wgUseInstantCommons']};
382
383 # Periodically send a pingback to https://www.mediawiki.org/ with basic data
384 # about this MediaWiki instance. The Wikimedia Foundation shares this data
385 # with MediaWiki developers to help guide future development efforts.
386 \$wgPingback = {$this->values['wgPingback']};
387
388 ## If you use ImageMagick (or any other shell command) on a
389 ## Linux server, this will need to be set to the name of an
390 ## available UTF-8 locale
391 {$locale}\$wgShellLocale = \"{$this->values['wgShellLocale']}\";
392
393 ## Set \$wgCacheDirectory to a writable directory on the web server
394 ## to make your wiki go slightly faster. The directory should not
395 ## be publically accessible from the web.
396 #\$wgCacheDirectory = \"\$IP/cache\";
397
398 # Site language code, should be one of the list in ./languages/data/Names.php
399 \$wgLanguageCode = \"{$this->values['wgLanguageCode']}\";
400
401 \$wgSecretKey = \"{$this->values['wgSecretKey']}\";
402
403 # Changing this will log out all existing sessions.
404 \$wgAuthenticationTokenVersion = \"{$this->values['wgAuthenticationTokenVersion']}\";
405
406 # Site upgrade key. Must be set to a string (default provided) to turn on the
407 # web installer while LocalSettings.php is in place
408 \$wgUpgradeKey = \"{$this->values['wgUpgradeKey']}\";
409
410 ## For attaching licensing metadata to pages, and displaying an
411 ## appropriate copyright notice / icon. GNU Free Documentation
412 ## License and Creative Commons licenses are supported so far.
413 \$wgRightsPage = \"\"; # Set to the title of a wiki page that describes your license/copyright
414 \$wgRightsUrl = \"{$this->values['wgRightsUrl']}\";
415 \$wgRightsText = \"{$this->values['wgRightsText']}\";
416 \$wgRightsIcon = \"{$this->values['wgRightsIcon']}\";
417
418 # Path to the GNU diff3 utility. Used for conflict resolution.
419 \$wgDiff3 = \"{$this->values['wgDiff3']}\";
420
421 {$groupRights}{$noFollow}## Default skin: you can change the default skin. Use the internal symbolic
422 ## names, ie 'vector', 'monobook':
423 \$wgDefaultSkin = \"{$this->values['wgDefaultSkin']}\";
424 ";
425 }
426 }