Completed
Branch master (246348)
by
unknown
22:34
created

Installer::envCheckIconv()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * Base code for MediaWiki installer.
4
 *
5
 * DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
6
 * See mw-config/overrides/README for details.
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 2 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License along
19
 * with this program; if not, write to the Free Software Foundation, Inc.,
20
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
 * http://www.gnu.org/copyleft/gpl.html
22
 *
23
 * @file
24
 * @ingroup Deployment
25
 */
26
use MediaWiki\MediaWikiServices;
27
28
/**
29
 * This documentation group collects source code files with deployment functionality.
30
 *
31
 * @defgroup Deployment Deployment
32
 */
33
34
/**
35
 * Base installer class.
36
 *
37
 * This class provides the base for installation and update functionality
38
 * for both MediaWiki core and extensions.
39
 *
40
 * @ingroup Deployment
41
 * @since 1.17
42
 */
43
abstract class Installer {
44
45
	/**
46
	 * The oldest version of PCRE we can support.
47
	 *
48
	 * Defining this is necessary because PHP may be linked with a system version
49
	 * of PCRE, which may be older than that bundled with the minimum PHP version.
50
	 */
51
	const MINIMUM_PCRE_VERSION = '7.2';
52
53
	/**
54
	 * @var array
55
	 */
56
	protected $settings;
57
58
	/**
59
	 * List of detected DBs, access using getCompiledDBs().
60
	 *
61
	 * @var array
62
	 */
63
	protected $compiledDBs;
64
65
	/**
66
	 * Cached DB installer instances, access using getDBInstaller().
67
	 *
68
	 * @var array
69
	 */
70
	protected $dbInstallers = [];
71
72
	/**
73
	 * Minimum memory size in MB.
74
	 *
75
	 * @var int
76
	 */
77
	protected $minMemorySize = 50;
78
79
	/**
80
	 * Cached Title, used by parse().
81
	 *
82
	 * @var Title
83
	 */
84
	protected $parserTitle;
85
86
	/**
87
	 * Cached ParserOptions, used by parse().
88
	 *
89
	 * @var ParserOptions
90
	 */
91
	protected $parserOptions;
92
93
	/**
94
	 * Known database types. These correspond to the class names <type>Installer,
95
	 * and are also MediaWiki database types valid for $wgDBtype.
96
	 *
97
	 * To add a new type, create a <type>Installer class and a Database<type>
98
	 * class, and add a config-type-<type> message to MessagesEn.php.
99
	 *
100
	 * @var array
101
	 */
102
	protected static $dbTypes = [
103
		'mysql',
104
		'postgres',
105
		'oracle',
106
		'mssql',
107
		'sqlite',
108
	];
109
110
	/**
111
	 * A list of environment check methods called by doEnvironmentChecks().
112
	 * These may output warnings using showMessage(), and/or abort the
113
	 * installation process by returning false.
114
	 *
115
	 * For the WebInstaller these are only called on the Welcome page,
116
	 * if these methods have side-effects that should affect later page loads
117
	 * (as well as the generated stylesheet), use envPreps instead.
118
	 *
119
	 * @var array
120
	 */
121
	protected $envChecks = [
122
		'envCheckDB',
123
		'envCheckBrokenXML',
124
		'envCheckPCRE',
125
		'envCheckMemory',
126
		'envCheckCache',
127
		'envCheckModSecurity',
128
		'envCheckDiff3',
129
		'envCheckGraphics',
130
		'envCheckGit',
131
		'envCheckServer',
132
		'envCheckPath',
133
		'envCheckShellLocale',
134
		'envCheckUploadsDirectory',
135
		'envCheckLibicu',
136
		'envCheckSuhosinMaxValueLength',
137
	];
138
139
	/**
140
	 * A list of environment preparation methods called by doEnvironmentPreps().
141
	 *
142
	 * @var array
143
	 */
144
	protected $envPreps = [
145
		'envPrepServer',
146
		'envPrepPath',
147
	];
148
149
	/**
150
	 * MediaWiki configuration globals that will eventually be passed through
151
	 * to LocalSettings.php. The names only are given here, the defaults
152
	 * typically come from DefaultSettings.php.
153
	 *
154
	 * @var array
155
	 */
156
	protected $defaultVarNames = [
157
		'wgSitename',
158
		'wgPasswordSender',
159
		'wgLanguageCode',
160
		'wgRightsIcon',
161
		'wgRightsText',
162
		'wgRightsUrl',
163
		'wgEnableEmail',
164
		'wgEnableUserEmail',
165
		'wgEnotifUserTalk',
166
		'wgEnotifWatchlist',
167
		'wgEmailAuthentication',
168
		'wgDBname',
169
		'wgDBtype',
170
		'wgDiff3',
171
		'wgImageMagickConvertCommand',
172
		'wgGitBin',
173
		'IP',
174
		'wgScriptPath',
175
		'wgMetaNamespace',
176
		'wgDeletedDirectory',
177
		'wgEnableUploads',
178
		'wgShellLocale',
179
		'wgSecretKey',
180
		'wgUseInstantCommons',
181
		'wgUpgradeKey',
182
		'wgDefaultSkin',
183
	];
184
185
	/**
186
	 * Variables that are stored alongside globals, and are used for any
187
	 * configuration of the installation process aside from the MediaWiki
188
	 * configuration. Map of names to defaults.
189
	 *
190
	 * @var array
191
	 */
192
	protected $internalDefaults = [
193
		'_UserLang' => 'en',
194
		'_Environment' => false,
195
		'_RaiseMemory' => false,
196
		'_UpgradeDone' => false,
197
		'_InstallDone' => false,
198
		'_Caches' => [],
199
		'_InstallPassword' => '',
200
		'_SameAccount' => true,
201
		'_CreateDBAccount' => false,
202
		'_NamespaceType' => 'site-name',
203
		'_AdminName' => '', // will be set later, when the user selects language
204
		'_AdminPassword' => '',
205
		'_AdminPasswordConfirm' => '',
206
		'_AdminEmail' => '',
207
		'_Subscribe' => false,
208
		'_SkipOptional' => 'continue',
209
		'_RightsProfile' => 'wiki',
210
		'_LicenseCode' => 'none',
211
		'_CCDone' => false,
212
		'_Extensions' => [],
213
		'_Skins' => [],
214
		'_MemCachedServers' => '',
215
		'_UpgradeKeySupplied' => false,
216
		'_ExistingDBSettings' => false,
217
218
		// $wgLogo is probably wrong (bug 48084); set something that will work.
219
		// Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
220
		'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
221
		'wgAuthenticationTokenVersion' => 1,
222
	];
223
224
	/**
225
	 * The actual list of installation steps. This will be initialized by getInstallSteps()
226
	 *
227
	 * @var array
228
	 */
229
	private $installSteps = [];
230
231
	/**
232
	 * Extra steps for installation, for things like DatabaseInstallers to modify
233
	 *
234
	 * @var array
235
	 */
236
	protected $extraInstallSteps = [];
237
238
	/**
239
	 * Known object cache types and the functions used to test for their existence.
240
	 *
241
	 * @var array
242
	 */
243
	protected $objectCaches = [
244
		'xcache' => 'xcache_get',
245
		'apc' => 'apc_fetch',
246
		'wincache' => 'wincache_ucache_get'
247
	];
248
249
	/**
250
	 * User rights profiles.
251
	 *
252
	 * @var array
253
	 */
254
	public $rightsProfiles = [
255
		'wiki' => [],
256
		'no-anon' => [
257
			'*' => [ 'edit' => false ]
258
		],
259
		'fishbowl' => [
260
			'*' => [
261
				'createaccount' => false,
262
				'edit' => false,
263
			],
264
		],
265
		'private' => [
266
			'*' => [
267
				'createaccount' => false,
268
				'edit' => false,
269
				'read' => false,
270
			],
271
		],
272
	];
273
274
	/**
275
	 * License types.
276
	 *
277
	 * @var array
278
	 */
279
	public $licenses = [
280
		'cc-by' => [
281
			'url' => 'https://creativecommons.org/licenses/by/4.0/',
282
			'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
283
		],
284
		'cc-by-sa' => [
285
			'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
286
			'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
287
		],
288
		'cc-by-nc-sa' => [
289
			'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
290
			'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
291
		],
292
		'cc-0' => [
293
			'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
294
			'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
295
		],
296
		'pd' => [
297
			'url' => '',
298
			'icon' => '$wgResourceBasePath/resources/assets/licenses/public-domain.png',
299
		],
300
		'gfdl' => [
301
			'url' => 'https://www.gnu.org/copyleft/fdl.html',
302
			'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
303
		],
304
		'none' => [
305
			'url' => '',
306
			'icon' => '',
307
			'text' => ''
308
		],
309
		'cc-choose' => [
310
			// Details will be filled in by the selector.
311
			'url' => '',
312
			'icon' => '',
313
			'text' => '',
314
		],
315
	];
316
317
	/**
318
	 * URL to mediawiki-announce subscription
319
	 */
320
	protected $mediaWikiAnnounceUrl =
321
		'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
322
323
	/**
324
	 * Supported language codes for Mailman
325
	 */
326
	protected $mediaWikiAnnounceLanguages = [
327
		'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
328
		'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
329
		'sl', 'sr', 'sv', 'tr', 'uk'
330
	];
331
332
	/**
333
	 * UI interface for displaying a short message
334
	 * The parameters are like parameters to wfMessage().
335
	 * The messages will be in wikitext format, which will be converted to an
336
	 * output format such as HTML or text before being sent to the user.
337
	 * @param string $msg
338
	 */
339
	abstract public function showMessage( $msg /*, ... */ );
340
341
	/**
342
	 * Same as showMessage(), but for displaying errors
343
	 * @param string $msg
344
	 */
345
	abstract public function showError( $msg /*, ... */ );
346
347
	/**
348
	 * Show a message to the installing user by using a Status object
349
	 * @param Status $status
350
	 */
351
	abstract public function showStatusMessage( Status $status );
352
353
	/**
354
	 * Constructs a Config object that contains configuration settings that should be
355
	 * overwritten for the installation process.
356
	 *
357
	 * @since 1.27
358
	 *
359
	 * @param Config $baseConfig
360
	 *
361
	 * @return Config The config to use during installation.
362
	 */
363
	public static function getInstallerConfig( Config $baseConfig ) {
364
		$configOverrides = new HashConfig();
365
366
		// disable (problematic) object cache types explicitly, preserving all other (working) ones
367
		// bug T113843
368
		$emptyCache = [ 'class' => 'EmptyBagOStuff' ];
369
370
		$objectCaches = [
371
				CACHE_NONE => $emptyCache,
372
				CACHE_DB => $emptyCache,
373
				CACHE_ANYTHING => $emptyCache,
374
				CACHE_MEMCACHED => $emptyCache,
375
			] + $baseConfig->get( 'ObjectCaches' );
376
377
		$configOverrides->set( 'ObjectCaches', $objectCaches );
378
379
		// Load the installer's i18n.
380
		$messageDirs = $baseConfig->get( 'MessagesDirs' );
381
		$messageDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
382
383
		$configOverrides->set( 'MessagesDirs', $messageDirs );
384
385
		$installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
386
387
		// make sure we use the installer config as the main config
388
		$configRegistry = $baseConfig->get( 'ConfigRegistry' );
389
		$configRegistry['main'] = function() use ( $installerConfig ) {
390
			return $installerConfig;
391
		};
392
393
		$configOverrides->set( 'ConfigRegistry', $configRegistry );
394
395
		return $installerConfig;
396
	}
397
398
	/**
399
	 * Constructor, always call this from child classes.
400
	 */
401
	public function __construct() {
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
402
		global $wgMemc, $wgUser, $wgObjectCaches;
403
404
		$defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
405
		$installerConfig = self::getInstallerConfig( $defaultConfig );
406
407
		// Reset all services and inject config overrides
408
		MediaWiki\MediaWikiServices::resetGlobalInstance( $installerConfig );
409
410
		// Don't attempt to load user language options (T126177)
411
		// This will be overridden in the web installer with the user-specified language
412
		RequestContext::getMain()->setLanguage( 'en' );
413
414
		// Disable the i18n cache
415
		// TODO: manage LocalisationCache singleton in MediaWikiServices
416
		Language::getLocalisationCache()->disableBackend();
417
418
		// Disable all global services, since we don't have any configuration yet!
419
		MediaWiki\MediaWikiServices::disableStorageBackend();
420
421
		// Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
422
		// SqlBagOStuff will then throw since we just disabled wfGetDB)
423
		$wgObjectCaches = MediaWikiServices::getInstance()->getMainConfig()->get( 'ObjectCaches' );
424
		$wgMemc = ObjectCache::getInstance( CACHE_NONE );
425
426
		// Having a user with id = 0 safeguards us from DB access via User::loadOptions().
427
		$wgUser = User::newFromId( 0 );
428
		RequestContext::getMain()->setUser( $wgUser );
429
430
		$this->settings = $this->internalDefaults;
431
432
		foreach ( $this->defaultVarNames as $var ) {
433
			$this->settings[$var] = $GLOBALS[$var];
434
		}
435
436
		$this->doEnvironmentPreps();
437
438
		$this->compiledDBs = [];
439
		foreach ( self::getDBTypes() as $type ) {
440
			$installer = $this->getDBInstaller( $type );
441
442
			if ( !$installer->isCompiled() ) {
443
				continue;
444
			}
445
			$this->compiledDBs[] = $type;
446
		}
447
448
		$this->parserTitle = Title::newFromText( 'Installer' );
449
		$this->parserOptions = new ParserOptions( $wgUser ); // language will be wrong :(
450
		$this->parserOptions->setEditSection( false );
451
	}
452
453
	/**
454
	 * Get a list of known DB types.
455
	 *
456
	 * @return array
457
	 */
458
	public static function getDBTypes() {
459
		return self::$dbTypes;
460
	}
461
462
	/**
463
	 * Do initial checks of the PHP environment. Set variables according to
464
	 * the observed environment.
465
	 *
466
	 * It's possible that this may be called under the CLI SAPI, not the SAPI
467
	 * that the wiki will primarily run under. In that case, the subclass should
468
	 * initialise variables such as wgScriptPath, before calling this function.
469
	 *
470
	 * Under the web subclass, it can already be assumed that PHP 5+ is in use
471
	 * and that sessions are working.
472
	 *
473
	 * @return Status
474
	 */
475
	public function doEnvironmentChecks() {
476
		// Php version has already been checked by entry scripts
477
		// Show message here for information purposes
478
		if ( wfIsHHVM() ) {
479
			$this->showMessage( 'config-env-hhvm', HHVM_VERSION );
480
		} else {
481
			$this->showMessage( 'config-env-php', PHP_VERSION );
482
		}
483
484
		$good = true;
485
		// Must go here because an old version of PCRE can prevent other checks from completing
486
		list( $pcreVersion ) = explode( ' ', PCRE_VERSION, 2 );
487
		if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
488
			$this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
489
			$good = false;
490
		} else {
491
			foreach ( $this->envChecks as $check ) {
492
				$status = $this->$check();
493
				if ( $status === false ) {
494
					$good = false;
495
				}
496
			}
497
		}
498
499
		$this->setVar( '_Environment', $good );
500
501
		return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
502
	}
503
504
	public function doEnvironmentPreps() {
505
		foreach ( $this->envPreps as $prep ) {
506
			$this->$prep();
507
		}
508
	}
509
510
	/**
511
	 * Set a MW configuration variable, or internal installer configuration variable.
512
	 *
513
	 * @param string $name
514
	 * @param mixed $value
515
	 */
516
	public function setVar( $name, $value ) {
517
		$this->settings[$name] = $value;
518
	}
519
520
	/**
521
	 * Get an MW configuration variable, or internal installer configuration variable.
522
	 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
523
	 * Installer variables are typically prefixed by an underscore.
524
	 *
525
	 * @param string $name
526
	 * @param mixed $default
527
	 *
528
	 * @return mixed
529
	 */
530 View Code Duplication
	public function getVar( $name, $default = null ) {
531
		if ( !isset( $this->settings[$name] ) ) {
532
			return $default;
533
		} else {
534
			return $this->settings[$name];
535
		}
536
	}
537
538
	/**
539
	 * Get a list of DBs supported by current PHP setup
540
	 *
541
	 * @return array
542
	 */
543
	public function getCompiledDBs() {
544
		return $this->compiledDBs;
545
	}
546
547
	/**
548
	 * Get an instance of DatabaseInstaller for the specified DB type.
549
	 *
550
	 * @param mixed $type DB installer for which is needed, false to use default.
551
	 *
552
	 * @return DatabaseInstaller
553
	 */
554
	public function getDBInstaller( $type = false ) {
555
		if ( !$type ) {
556
			$type = $this->getVar( 'wgDBtype' );
557
		}
558
559
		$type = strtolower( $type );
560
561
		if ( !isset( $this->dbInstallers[$type] ) ) {
562
			$class = ucfirst( $type ) . 'Installer';
563
			$this->dbInstallers[$type] = new $class( $this );
564
		}
565
566
		return $this->dbInstallers[$type];
567
	}
568
569
	/**
570
	 * Determine if LocalSettings.php exists. If it does, return its variables.
571
	 *
572
	 * @return array
573
	 */
574
	public static function getExistingLocalSettings() {
575
		global $IP;
576
577
		// You might be wondering why this is here. Well if you don't do this
578
		// then some poorly-formed extensions try to call their own classes
579
		// after immediately registering them. We really need to get extension
580
		// registration out of the global scope and into a real format.
581
		// @see https://phabricator.wikimedia.org/T69440
582
		global $wgAutoloadClasses;
583
		$wgAutoloadClasses = [];
584
585
		// @codingStandardsIgnoreStart
586
		// LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
587
		// Define the required globals here, to ensure, the functions can do it work correctly.
588
		global $wgExtensionDirectory, $wgStyleDirectory;
589
		// @codingStandardsIgnoreEnd
590
591
		MediaWiki\suppressWarnings();
592
		$_lsExists = file_exists( "$IP/LocalSettings.php" );
593
		MediaWiki\restoreWarnings();
594
595
		if ( !$_lsExists ) {
596
			return false;
597
		}
598
		unset( $_lsExists );
599
600
		require "$IP/includes/DefaultSettings.php";
601
		require "$IP/LocalSettings.php";
602
603
		return get_defined_vars();
604
	}
605
606
	/**
607
	 * Get a fake password for sending back to the user in HTML.
608
	 * This is a security mechanism to avoid compromise of the password in the
609
	 * event of session ID compromise.
610
	 *
611
	 * @param string $realPassword
612
	 *
613
	 * @return string
614
	 */
615
	public function getFakePassword( $realPassword ) {
616
		return str_repeat( '*', strlen( $realPassword ) );
617
	}
618
619
	/**
620
	 * Set a variable which stores a password, except if the new value is a
621
	 * fake password in which case leave it as it is.
622
	 *
623
	 * @param string $name
624
	 * @param mixed $value
625
	 */
626
	public function setPassword( $name, $value ) {
627
		if ( !preg_match( '/^\*+$/', $value ) ) {
628
			$this->setVar( $name, $value );
629
		}
630
	}
631
632
	/**
633
	 * On POSIX systems return the primary group of the webserver we're running under.
634
	 * On other systems just returns null.
635
	 *
636
	 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
637
	 * webserver user before he can install.
638
	 *
639
	 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
640
	 *
641
	 * @return mixed
642
	 */
643
	public static function maybeGetWebserverPrimaryGroup() {
644
		if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
645
			# I don't know this, this isn't UNIX.
646
			return null;
647
		}
648
649
		# posix_getegid() *not* getmygid() because we want the group of the webserver,
650
		# not whoever owns the current script.
651
		$gid = posix_getegid();
652
		$group = posix_getpwuid( $gid )['name'];
653
654
		return $group;
655
	}
656
657
	/**
658
	 * Convert wikitext $text to HTML.
659
	 *
660
	 * This is potentially error prone since many parser features require a complete
661
	 * installed MW database. The solution is to just not use those features when you
662
	 * write your messages. This appears to work well enough. Basic formatting and
663
	 * external links work just fine.
664
	 *
665
	 * But in case a translator decides to throw in a "#ifexist" or internal link or
666
	 * whatever, this function is guarded to catch the attempted DB access and to present
667
	 * some fallback text.
668
	 *
669
	 * @param string $text
670
	 * @param bool $lineStart
671
	 * @return string
672
	 */
673
	public function parse( $text, $lineStart = false ) {
674
		global $wgParser;
675
676
		try {
677
			$out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
678
			$html = $out->getText();
679
		} catch ( DBAccessError $e ) {
680
			$html = '<!--DB access attempted during parse-->  ' . htmlspecialchars( $text );
681
682
			if ( !empty( $this->debug ) ) {
0 ignored issues
show
Bug introduced by
The property debug does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
683
				$html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
684
			}
685
		}
686
687
		return $html;
688
	}
689
690
	/**
691
	 * @return ParserOptions
692
	 */
693
	public function getParserOptions() {
694
		return $this->parserOptions;
695
	}
696
697
	public function disableLinkPopups() {
698
		$this->parserOptions->setExternalLinkTarget( false );
699
	}
700
701
	public function restoreLinkPopups() {
702
		global $wgExternalLinkTarget;
703
		$this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
704
	}
705
706
	/**
707
	 * Install step which adds a row to the site_stats table with appropriate
708
	 * initial values.
709
	 *
710
	 * @param DatabaseInstaller $installer
711
	 *
712
	 * @return Status
713
	 */
714
	public function populateSiteStats( DatabaseInstaller $installer ) {
715
		$status = $installer->getConnection();
716
		if ( !$status->isOK() ) {
717
			return $status;
718
		}
719
		$status->value->insert(
720
			'site_stats',
721
			[
722
				'ss_row_id' => 1,
723
				'ss_total_edits' => 0,
724
				'ss_good_articles' => 0,
725
				'ss_total_pages' => 0,
726
				'ss_users' => 0,
727
				'ss_images' => 0
728
			],
729
			__METHOD__, 'IGNORE'
730
		);
731
732
		return Status::newGood();
733
	}
734
735
	/**
736
	 * Environment check for DB types.
737
	 * @return bool
738
	 */
739
	protected function envCheckDB() {
740
		global $wgLang;
741
742
		$allNames = [];
743
744
		// Messages: config-type-mysql, config-type-postgres, config-type-oracle,
745
		// config-type-sqlite
746
		foreach ( self::getDBTypes() as $name ) {
747
			$allNames[] = wfMessage( "config-type-$name" )->text();
748
		}
749
750
		$databases = $this->getCompiledDBs();
751
752
		$databases = array_flip( $databases );
753
		foreach ( array_keys( $databases ) as $db ) {
754
			$installer = $this->getDBInstaller( $db );
755
			$status = $installer->checkPrerequisites();
756
			if ( !$status->isGood() ) {
757
				$this->showStatusMessage( $status );
758
			}
759
			if ( !$status->isOK() ) {
760
				unset( $databases[$db] );
761
			}
762
		}
763
		$databases = array_flip( $databases );
764
		if ( !$databases ) {
765
			$this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
766
767
			// @todo FIXME: This only works for the web installer!
768
			return false;
769
		}
770
771
		return true;
772
	}
773
774
	/**
775
	 * Some versions of libxml+PHP break < and > encoding horribly
776
	 * @return bool
777
	 */
778
	protected function envCheckBrokenXML() {
779
		$test = new PhpXmlBugTester();
780
		if ( !$test->ok ) {
781
			$this->showError( 'config-brokenlibxml' );
782
783
			return false;
784
		}
785
786
		return true;
787
	}
788
789
	/**
790
	 * Environment check for the PCRE module.
791
	 *
792
	 * @note If this check were to fail, the parser would
793
	 *   probably throw an exception before the result
794
	 *   of this check is shown to the user.
795
	 * @return bool
796
	 */
797
	protected function envCheckPCRE() {
798
		MediaWiki\suppressWarnings();
799
		$regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
800
		// Need to check for \p support too, as PCRE can be compiled
801
		// with utf8 support, but not unicode property support.
802
		// check that \p{Zs} (space separators) matches
803
		// U+3000 (Ideographic space)
804
		$regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
805
		MediaWiki\restoreWarnings();
806
		if ( $regexd != '--' || $regexprop != '--' ) {
807
			$this->showError( 'config-pcre-no-utf8' );
808
809
			return false;
810
		}
811
812
		return true;
813
	}
814
815
	/**
816
	 * Environment check for available memory.
817
	 * @return bool
818
	 */
819
	protected function envCheckMemory() {
820
		$limit = ini_get( 'memory_limit' );
821
822
		if ( !$limit || $limit == -1 ) {
823
			return true;
824
		}
825
826
		$n = wfShorthandToInteger( $limit );
827
828
		if ( $n < $this->minMemorySize * 1024 * 1024 ) {
829
			$newLimit = "{$this->minMemorySize}M";
830
831
			if ( ini_set( "memory_limit", $newLimit ) === false ) {
832
				$this->showMessage( 'config-memory-bad', $limit );
833
			} else {
834
				$this->showMessage( 'config-memory-raised', $limit, $newLimit );
835
				$this->setVar( '_RaiseMemory', true );
836
			}
837
		}
838
839
		return true;
840
	}
841
842
	/**
843
	 * Environment check for compiled object cache types.
844
	 */
845
	protected function envCheckCache() {
846
		$caches = [];
847
		foreach ( $this->objectCaches as $name => $function ) {
848
			if ( function_exists( $function ) ) {
849
				if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
850
					continue;
851
				}
852
				$caches[$name] = true;
853
			}
854
		}
855
856
		if ( !$caches ) {
857
			$key = 'config-no-cache-apcu';
858
			$this->showMessage( $key );
859
		}
860
861
		$this->setVar( '_Caches', $caches );
862
	}
863
864
	/**
865
	 * Scare user to death if they have mod_security or mod_security2
866
	 * @return bool
867
	 */
868
	protected function envCheckModSecurity() {
869
		if ( self::apacheModulePresent( 'mod_security' )
870
			|| self::apacheModulePresent( 'mod_security2' ) ) {
871
			$this->showMessage( 'config-mod-security' );
872
		}
873
874
		return true;
875
	}
876
877
	/**
878
	 * Search for GNU diff3.
879
	 * @return bool
880
	 */
881
	protected function envCheckDiff3() {
882
		$names = [ "gdiff3", "diff3", "diff3.exe" ];
883
		$versionInfo = [ '$1 --version 2>&1', 'GNU diffutils' ];
884
885
		$diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
886
887
		if ( $diff3 ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $diff3 of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
888
			$this->setVar( 'wgDiff3', $diff3 );
889
		} else {
890
			$this->setVar( 'wgDiff3', false );
891
			$this->showMessage( 'config-diff3-bad' );
892
		}
893
894
		return true;
895
	}
896
897
	/**
898
	 * Environment check for ImageMagick and GD.
899
	 * @return bool
900
	 */
901
	protected function envCheckGraphics() {
902
		$names = [ wfIsWindows() ? 'convert.exe' : 'convert' ];
903
		$versionInfo = [ '$1 -version', 'ImageMagick' ];
904
		$convert = self::locateExecutableInDefaultPaths( $names, $versionInfo );
905
906
		$this->setVar( 'wgImageMagickConvertCommand', '' );
907
		if ( $convert ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $convert of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
908
			$this->setVar( 'wgImageMagickConvertCommand', $convert );
909
			$this->showMessage( 'config-imagemagick', $convert );
910
911
			return true;
912
		} elseif ( function_exists( 'imagejpeg' ) ) {
913
			$this->showMessage( 'config-gd' );
914
		} else {
915
			$this->showMessage( 'config-no-scaling' );
916
		}
917
918
		return true;
919
	}
920
921
	/**
922
	 * Search for git.
923
	 *
924
	 * @since 1.22
925
	 * @return bool
926
	 */
927
	protected function envCheckGit() {
928
		$names = [ wfIsWindows() ? 'git.exe' : 'git' ];
929
		$versionInfo = [ '$1 --version', 'git version' ];
930
931
		$git = self::locateExecutableInDefaultPaths( $names, $versionInfo );
932
933
		if ( $git ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $git of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
934
			$this->setVar( 'wgGitBin', $git );
935
			$this->showMessage( 'config-git', $git );
936
		} else {
937
			$this->setVar( 'wgGitBin', false );
938
			$this->showMessage( 'config-git-bad' );
939
		}
940
941
		return true;
942
	}
943
944
	/**
945
	 * Environment check to inform user which server we've assumed.
946
	 *
947
	 * @return bool
948
	 */
949
	protected function envCheckServer() {
950
		$server = $this->envGetDefaultServer();
951
		if ( $server !== null ) {
952
			$this->showMessage( 'config-using-server', $server );
953
		}
954
		return true;
955
	}
956
957
	/**
958
	 * Environment check to inform user which paths we've assumed.
959
	 *
960
	 * @return bool
961
	 */
962
	protected function envCheckPath() {
963
		$this->showMessage(
964
			'config-using-uri',
965
			$this->getVar( 'wgServer' ),
966
			$this->getVar( 'wgScriptPath' )
967
		);
968
		return true;
969
	}
970
971
	/**
972
	 * Environment check for preferred locale in shell
973
	 * @return bool
974
	 */
975
	protected function envCheckShellLocale() {
976
		$os = php_uname( 's' );
977
		$supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
978
979
		if ( !in_array( $os, $supported ) ) {
980
			return true;
981
		}
982
983
		# Get a list of available locales.
984
		$ret = false;
985
		$lines = wfShellExec( '/usr/bin/locale -a', $ret );
986
987
		if ( $ret ) {
988
			return true;
989
		}
990
991
		$lines = array_map( 'trim', explode( "\n", $lines ) );
992
		$candidatesByLocale = [];
993
		$candidatesByLang = [];
994
995
		foreach ( $lines as $line ) {
996
			if ( $line === '' ) {
997
				continue;
998
			}
999
1000
			if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1001
				continue;
1002
			}
1003
1004
			list( , $lang, , , ) = $m;
1005
1006
			$candidatesByLocale[$m[0]] = $m;
1007
			$candidatesByLang[$lang][] = $m;
1008
		}
1009
1010
		# Try the current value of LANG.
1011
		if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1012
			$this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1013
1014
			return true;
1015
		}
1016
1017
		# Try the most common ones.
1018
		$commonLocales = [ 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1019
		foreach ( $commonLocales as $commonLocale ) {
1020
			if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1021
				$this->setVar( 'wgShellLocale', $commonLocale );
1022
1023
				return true;
1024
			}
1025
		}
1026
1027
		# Is there an available locale in the Wiki's language?
1028
		$wikiLang = $this->getVar( 'wgLanguageCode' );
1029
1030
		if ( isset( $candidatesByLang[$wikiLang] ) ) {
1031
			$m = reset( $candidatesByLang[$wikiLang] );
1032
			$this->setVar( 'wgShellLocale', $m[0] );
1033
1034
			return true;
1035
		}
1036
1037
		# Are there any at all?
1038
		if ( count( $candidatesByLocale ) ) {
1039
			$m = reset( $candidatesByLocale );
1040
			$this->setVar( 'wgShellLocale', $m[0] );
1041
1042
			return true;
1043
		}
1044
1045
		# Give up.
1046
		return true;
1047
	}
1048
1049
	/**
1050
	 * Environment check for the permissions of the uploads directory
1051
	 * @return bool
1052
	 */
1053
	protected function envCheckUploadsDirectory() {
1054
		global $IP;
1055
1056
		$dir = $IP . '/images/';
1057
		$url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1058
		$safe = !$this->dirIsExecutable( $dir, $url );
1059
1060
		if ( !$safe ) {
1061
			$this->showMessage( 'config-uploads-not-safe', $dir );
1062
		}
1063
1064
		return true;
1065
	}
1066
1067
	/**
1068
	 * Checks if suhosin.get.max_value_length is set, and if so generate
1069
	 * a warning because it decreases ResourceLoader performance.
1070
	 * @return bool
1071
	 */
1072
	protected function envCheckSuhosinMaxValueLength() {
1073
		$maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1074
		if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1075
			// Only warn if the value is below the sane 1024
1076
			$this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1077
		}
1078
1079
		return true;
1080
	}
1081
1082
	/**
1083
	 * Convert a hex string representing a Unicode code point to that code point.
1084
	 * @param string $c
1085
	 * @return string
1086
	 */
1087
	protected function unicodeChar( $c ) {
1088
		$c = hexdec( $c );
1089
		if ( $c <= 0x7F ) {
1090
			return chr( $c );
1091
		} elseif ( $c <= 0x7FF ) {
1092
			return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1093
		} elseif ( $c <= 0xFFFF ) {
1094
			return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F ) .
1095
				chr( 0x80 | $c & 0x3F );
1096
		} elseif ( $c <= 0x10FFFF ) {
1097
			return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F ) .
1098
				chr( 0x80 | $c >> 6 & 0x3F ) .
1099
				chr( 0x80 | $c & 0x3F );
1100
		} else {
1101
			return false;
1102
		}
1103
	}
1104
1105
	/**
1106
	 * Check the libicu version
1107
	 */
1108
	protected function envCheckLibicu() {
1109
		/**
1110
		 * This needs to be updated something that the latest libicu
1111
		 * will properly normalize.  This normalization was found at
1112
		 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1113
		 * Note that we use the hex representation to create the code
1114
		 * points in order to avoid any Unicode-destroying during transit.
1115
		 */
1116
		$not_normal_c = $this->unicodeChar( "FA6C" );
1117
		$normal_c = $this->unicodeChar( "242EE" );
1118
1119
		$useNormalizer = 'php';
1120
		$needsUpdate = false;
1121
1122
		if ( function_exists( 'normalizer_normalize' ) ) {
1123
			$useNormalizer = 'intl';
1124
			$intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1125
			if ( $intl !== $normal_c ) {
1126
				$needsUpdate = true;
1127
			}
1128
		}
1129
1130
		// Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1131
		if ( $useNormalizer === 'php' ) {
1132
			$this->showMessage( 'config-unicode-pure-php-warning' );
1133
		} else {
1134
			$this->showMessage( 'config-unicode-using-' . $useNormalizer );
1135
			if ( $needsUpdate ) {
1136
				$this->showMessage( 'config-unicode-update-warning' );
1137
			}
1138
		}
1139
	}
1140
1141
	/**
1142
	 * Environment prep for the server hostname.
1143
	 */
1144
	protected function envPrepServer() {
1145
		$server = $this->envGetDefaultServer();
1146
		if ( $server !== null ) {
1147
			$this->setVar( 'wgServer', $server );
1148
		}
1149
	}
1150
1151
	/**
1152
	 * Helper function to be called from envPrepServer()
1153
	 * @return string
1154
	 */
1155
	abstract protected function envGetDefaultServer();
1156
1157
	/**
1158
	 * Environment prep for setting $IP and $wgScriptPath.
1159
	 */
1160
	protected function envPrepPath() {
1161
		global $IP;
1162
		$IP = dirname( dirname( __DIR__ ) );
1163
		$this->setVar( 'IP', $IP );
1164
	}
1165
1166
	/**
1167
	 * Get an array of likely places we can find executables. Check a bunch
1168
	 * of known Unix-like defaults, as well as the PATH environment variable
1169
	 * (which should maybe make it work for Windows?)
1170
	 *
1171
	 * @return array
1172
	 */
1173
	protected static function getPossibleBinPaths() {
1174
		return array_merge(
1175
			[ '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1176
				'/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ],
1177
			explode( PATH_SEPARATOR, getenv( 'PATH' ) )
1178
		);
1179
	}
1180
1181
	/**
1182
	 * Search a path for any of the given executable names. Returns the
1183
	 * executable name if found. Also checks the version string returned
1184
	 * by each executable.
1185
	 *
1186
	 * Used only by environment checks.
1187
	 *
1188
	 * @param string $path Path to search
1189
	 * @param array $names Array of executable names
1190
	 * @param array|bool $versionInfo False or array with two members:
1191
	 *   0 => Command to run for version check, with $1 for the full executable name
1192
	 *   1 => String to compare the output with
1193
	 *
1194
	 * If $versionInfo is not false, only executables with a version
1195
	 * matching $versionInfo[1] will be returned.
1196
	 * @return bool|string
1197
	 */
1198
	public static function locateExecutable( $path, $names, $versionInfo = false ) {
1199
		if ( !is_array( $names ) ) {
1200
			$names = [ $names ];
1201
		}
1202
1203
		foreach ( $names as $name ) {
1204
			$command = $path . DIRECTORY_SEPARATOR . $name;
1205
1206
			MediaWiki\suppressWarnings();
1207
			$file_exists = is_executable( $command );
1208
			MediaWiki\restoreWarnings();
1209
1210
			if ( $file_exists ) {
1211
				if ( !$versionInfo ) {
1212
					return $command;
1213
				}
1214
1215
				$file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1216
				if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1217
					return $command;
1218
				}
1219
			}
1220
		}
1221
1222
		return false;
1223
	}
1224
1225
	/**
1226
	 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1227
	 * @see locateExecutable()
1228
	 * @param array $names Array of possible names.
1229
	 * @param array|bool $versionInfo Default: false or array with two members:
1230
	 *   0 => Command to run for version check, with $1 for the full executable name
1231
	 *   1 => String to compare the output with
1232
	 *
1233
	 * If $versionInfo is not false, only executables with a version
1234
	 * matching $versionInfo[1] will be returned.
1235
	 * @return bool|string
1236
	 */
1237
	public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1238
		foreach ( self::getPossibleBinPaths() as $path ) {
1239
			$exe = self::locateExecutable( $path, $names, $versionInfo );
1240
			if ( $exe !== false ) {
1241
				return $exe;
1242
			}
1243
		}
1244
1245
		return false;
1246
	}
1247
1248
	/**
1249
	 * Checks if scripts located in the given directory can be executed via the given URL.
1250
	 *
1251
	 * Used only by environment checks.
1252
	 * @param string $dir
1253
	 * @param string $url
1254
	 * @return bool|int|string
1255
	 */
1256
	public function dirIsExecutable( $dir, $url ) {
1257
		$scriptTypes = [
1258
			'php' => [
1259
				"<?php echo 'ex' . 'ec';",
1260
				"#!/var/env php5\n<?php echo 'ex' . 'ec';",
1261
			],
1262
		];
1263
1264
		// it would be good to check other popular languages here, but it'll be slow.
1265
1266
		MediaWiki\suppressWarnings();
1267
1268
		foreach ( $scriptTypes as $ext => $contents ) {
1269
			foreach ( $contents as $source ) {
1270
				$file = 'exectest.' . $ext;
1271
1272
				if ( !file_put_contents( $dir . $file, $source ) ) {
1273
					break;
1274
				}
1275
1276
				try {
1277
					$text = Http::get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1278
				} catch ( Exception $e ) {
1279
					// Http::get throws with allow_url_fopen = false and no curl extension.
1280
					$text = null;
1281
				}
1282
				unlink( $dir . $file );
1283
1284
				if ( $text == 'exec' ) {
1285
					MediaWiki\restoreWarnings();
1286
1287
					return $ext;
1288
				}
1289
			}
1290
		}
1291
1292
		MediaWiki\restoreWarnings();
1293
1294
		return false;
1295
	}
1296
1297
	/**
1298
	 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1299
	 *
1300
	 * @param string $moduleName Name of module to check.
1301
	 * @return bool
1302
	 */
1303
	public static function apacheModulePresent( $moduleName ) {
1304
		if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1305
			return true;
1306
		}
1307
		// try it the hard way
1308
		ob_start();
1309
		phpinfo( INFO_MODULES );
1310
		$info = ob_get_clean();
1311
1312
		return strpos( $info, $moduleName ) !== false;
1313
	}
1314
1315
	/**
1316
	 * ParserOptions are constructed before we determined the language, so fix it
1317
	 *
1318
	 * @param Language $lang
1319
	 */
1320
	public function setParserLanguage( $lang ) {
1321
		$this->parserOptions->setTargetLanguage( $lang );
1322
		$this->parserOptions->setUserLang( $lang );
1323
	}
1324
1325
	/**
1326
	 * Overridden by WebInstaller to provide lastPage parameters.
1327
	 * @param string $page
1328
	 * @return string
1329
	 */
1330
	protected function getDocUrl( $page ) {
0 ignored issues
show
Coding Style introduced by
getDocUrl uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1331
		return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1332
	}
1333
1334
	/**
1335
	 * Finds extensions that follow the format /$directory/Name/Name.php,
1336
	 * and returns an array containing the value for 'Name' for each found extension.
1337
	 *
1338
	 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1339
	 *
1340
	 * @param string $directory Directory to search in
1341
	 * @return array
1342
	 */
1343
	public function findExtensions( $directory = 'extensions' ) {
1344
		if ( $this->getVar( 'IP' ) === null ) {
1345
			return [];
1346
		}
1347
1348
		$extDir = $this->getVar( 'IP' ) . '/' . $directory;
1349
		if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1350
			return [];
1351
		}
1352
1353
		// extensions -> extension.json, skins -> skin.json
1354
		$jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1355
1356
		$dh = opendir( $extDir );
1357
		$exts = [];
1358
		while ( ( $file = readdir( $dh ) ) !== false ) {
1359
			if ( !is_dir( "$extDir/$file" ) ) {
1360
				continue;
1361
			}
1362
			if ( file_exists( "$extDir/$file/$jsonFile" ) || file_exists( "$extDir/$file/$file.php" ) ) {
1363
				$exts[] = $file;
1364
			}
1365
		}
1366
		closedir( $dh );
1367
		natcasesort( $exts );
1368
1369
		return $exts;
1370
	}
1371
1372
	/**
1373
	 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1374
	 * but will fall back to another if the default skin is missing and some other one is present
1375
	 * instead.
1376
	 *
1377
	 * @param string[] $skinNames Names of installed skins.
1378
	 * @return string
1379
	 */
1380
	public function getDefaultSkin( array $skinNames ) {
0 ignored issues
show
Coding Style introduced by
getDefaultSkin uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1381
		$defaultSkin = $GLOBALS['wgDefaultSkin'];
1382
		if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1383
			return $defaultSkin;
1384
		} else {
1385
			return $skinNames[0];
1386
		}
1387
	}
1388
1389
	/**
1390
	 * Installs the auto-detected extensions.
1391
	 *
1392
	 * @return Status
1393
	 */
1394
	protected function includeExtensions() {
0 ignored issues
show
Coding Style introduced by
includeExtensions uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1395
		global $IP;
1396
		$exts = $this->getVar( '_Extensions' );
1397
		$IP = $this->getVar( 'IP' );
1398
1399
		/**
1400
		 * We need to include DefaultSettings before including extensions to avoid
1401
		 * warnings about unset variables. However, the only thing we really
1402
		 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1403
		 * if the extension has hidden hook registration in $wgExtensionFunctions,
1404
		 * but we're not opening that can of worms
1405
		 * @see https://phabricator.wikimedia.org/T28857
1406
		 */
1407
		global $wgAutoloadClasses;
1408
		$wgAutoloadClasses = [];
1409
		$queue = [];
1410
1411
		require "$IP/includes/DefaultSettings.php";
1412
1413
		foreach ( $exts as $e ) {
1414
			if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1415
				$queue["$IP/extensions/$e/extension.json"] = 1;
1416
			} else {
1417
				require_once "$IP/extensions/$e/$e.php";
1418
			}
1419
		}
1420
1421
		$registry = new ExtensionRegistry();
1422
		$data = $registry->readFromQueue( $queue );
1423
		$wgAutoloadClasses += $data['autoload'];
1424
1425
		$hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
0 ignored issues
show
Bug introduced by
The variable $wgHooks seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
1426
			$wgHooks['LoadExtensionSchemaUpdates'] : [];
1427
1428 View Code Duplication
		if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1429
			$hooksWeWant = array_merge_recursive(
1430
				$hooksWeWant,
1431
				$data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1432
			);
1433
		}
1434
		// Unset everyone else's hooks. Lord knows what someone might be doing
1435
		// in ParserFirstCallInit (see bug 27171)
1436
		$GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1437
1438
		return Status::newGood();
1439
	}
1440
1441
	/**
1442
	 * Get an array of install steps. Should always be in the format of
1443
	 * array(
1444
	 *   'name'     => 'someuniquename',
1445
	 *   'callback' => array( $obj, 'method' ),
1446
	 * )
1447
	 * There must be a config-install-$name message defined per step, which will
1448
	 * be shown on install.
1449
	 *
1450
	 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1451
	 * @return array
1452
	 */
1453
	protected function getInstallSteps( DatabaseInstaller $installer ) {
1454
		$coreInstallSteps = [
1455
			[ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1456
			[ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1457
			[ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1458
			[ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1459
			[ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1460
			[ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1461
			[ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1462
			[ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1463
		];
1464
1465
		// Build the array of install steps starting from the core install list,
1466
		// then adding any callbacks that wanted to attach after a given step
1467
		foreach ( $coreInstallSteps as $step ) {
1468
			$this->installSteps[] = $step;
1469 View Code Duplication
			if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1470
				$this->installSteps = array_merge(
1471
					$this->installSteps,
1472
					$this->extraInstallSteps[$step['name']]
1473
				);
1474
			}
1475
		}
1476
1477
		// Prepend any steps that want to be at the beginning
1478 View Code Duplication
		if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1479
			$this->installSteps = array_merge(
1480
				$this->extraInstallSteps['BEGINNING'],
1481
				$this->installSteps
1482
			);
1483
		}
1484
1485
		// Extensions should always go first, chance to tie into hooks and such
1486
		if ( count( $this->getVar( '_Extensions' ) ) ) {
1487
			array_unshift( $this->installSteps,
1488
				[ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1489
			);
1490
			$this->installSteps[] = [
1491
				'name' => 'extension-tables',
1492
				'callback' => [ $installer, 'createExtensionTables' ]
1493
			];
1494
		}
1495
1496
		return $this->installSteps;
1497
	}
1498
1499
	/**
1500
	 * Actually perform the installation.
1501
	 *
1502
	 * @param callable $startCB A callback array for the beginning of each step
1503
	 * @param callable $endCB A callback array for the end of each step
1504
	 *
1505
	 * @return array Array of Status objects
1506
	 */
1507
	public function performInstallation( $startCB, $endCB ) {
1508
		$installResults = [];
1509
		$installer = $this->getDBInstaller();
1510
		$installer->preInstall();
1511
		$steps = $this->getInstallSteps( $installer );
1512
		foreach ( $steps as $stepObj ) {
1513
			$name = $stepObj['name'];
1514
			call_user_func_array( $startCB, [ $name ] );
1515
1516
			// Perform the callback step
1517
			$status = call_user_func( $stepObj['callback'], $installer );
1518
1519
			// Output and save the results
1520
			call_user_func( $endCB, $name, $status );
1521
			$installResults[$name] = $status;
1522
1523
			// If we've hit some sort of fatal, we need to bail.
1524
			// Callback already had a chance to do output above.
1525
			if ( !$status->isOk() ) {
1526
				break;
1527
			}
1528
		}
1529
		if ( $status->isOk() ) {
0 ignored issues
show
Bug introduced by
The variable $status does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1530
			$this->setVar( '_InstallDone', true );
1531
		}
1532
1533
		return $installResults;
1534
	}
1535
1536
	/**
1537
	 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1538
	 *
1539
	 * @return Status
1540
	 */
1541
	public function generateKeys() {
1542
		$keys = [ 'wgSecretKey' => 64 ];
1543
		if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1544
			$keys['wgUpgradeKey'] = 16;
1545
		}
1546
1547
		return $this->doGenerateKeys( $keys );
1548
	}
1549
1550
	/**
1551
	 * Generate a secret value for variables using our CryptRand generator.
1552
	 * Produce a warning if the random source was insecure.
1553
	 *
1554
	 * @param array $keys
1555
	 * @return Status
1556
	 */
1557
	protected function doGenerateKeys( $keys ) {
1558
		$status = Status::newGood();
1559
1560
		$strong = true;
1561
		foreach ( $keys as $name => $length ) {
1562
			$secretKey = MWCryptRand::generateHex( $length, true );
1563
			if ( !MWCryptRand::wasStrong() ) {
1564
				$strong = false;
1565
			}
1566
1567
			$this->setVar( $name, $secretKey );
1568
		}
1569
1570
		if ( !$strong ) {
1571
			$names = array_keys( $keys );
1572
			$names = preg_replace( '/^(.*)$/', '\$$1', $names );
1573
			global $wgLang;
1574
			$status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1575
		}
1576
1577
		return $status;
1578
	}
1579
1580
	/**
1581
	 * Create the first user account, grant it sysop and bureaucrat rights
1582
	 *
1583
	 * @return Status
1584
	 */
1585
	protected function createSysop() {
1586
		$name = $this->getVar( '_AdminName' );
1587
		$user = User::newFromName( $name );
1588
1589
		if ( !$user ) {
1590
			// We should've validated this earlier anyway!
1591
			return Status::newFatal( 'config-admin-error-user', $name );
1592
		}
1593
1594
		if ( $user->idForName() == 0 ) {
1595
			$user->addToDatabase();
1596
1597
			try {
1598
				$user->setPassword( $this->getVar( '_AdminPassword' ) );
0 ignored issues
show
Deprecated Code introduced by
The method User::setPassword() has been deprecated with message: since 1.27, use AuthManager instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1599
			} catch ( PasswordError $pwe ) {
1600
				return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1601
			}
1602
1603
			$user->addGroup( 'sysop' );
1604
			$user->addGroup( 'bureaucrat' );
1605
			if ( $this->getVar( '_AdminEmail' ) ) {
1606
				$user->setEmail( $this->getVar( '_AdminEmail' ) );
1607
			}
1608
			$user->saveSettings();
1609
1610
			// Update user count
1611
			$ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1612
			$ssUpdate->doUpdate();
1613
		}
1614
		$status = Status::newGood();
1615
1616
		if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1617
			$this->subscribeToMediaWikiAnnounce( $status );
1618
		}
1619
1620
		return $status;
1621
	}
1622
1623
	/**
1624
	 * @param Status $s
1625
	 */
1626
	private function subscribeToMediaWikiAnnounce( Status $s ) {
1627
		$params = [
1628
			'email' => $this->getVar( '_AdminEmail' ),
1629
			'language' => 'en',
1630
			'digest' => 0
1631
		];
1632
1633
		// Mailman doesn't support as many languages as we do, so check to make
1634
		// sure their selected language is available
1635
		$myLang = $this->getVar( '_UserLang' );
1636
		if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1637
			$myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1638
			$params['language'] = $myLang;
1639
		}
1640
1641
		if ( MWHttpRequest::canMakeRequests() ) {
1642
			$res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1643
				[ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1644
			if ( !$res->isOK() ) {
1645
				$s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1646
			}
1647
		} else {
1648
			$s->warning( 'config-install-subscribe-notpossible' );
1649
		}
1650
	}
1651
1652
	/**
1653
	 * Insert Main Page with default content.
1654
	 *
1655
	 * @param DatabaseInstaller $installer
1656
	 * @return Status
1657
	 */
1658
	protected function createMainpage( DatabaseInstaller $installer ) {
1659
		$status = Status::newGood();
1660
		try {
1661
			$page = WikiPage::factory( Title::newMainPage() );
0 ignored issues
show
Bug introduced by
It seems like \Title::newMainPage() can be null; however, factory() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1662
			$content = new WikitextContent(
1663
				wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1664
				wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1665
			);
1666
1667
			$status = $page->doEditContent( $content,
1668
				'',
1669
				EDIT_NEW,
1670
				false,
1671
				User::newFromName( 'MediaWiki default' )
0 ignored issues
show
Security Bug introduced by
It seems like \User::newFromName('MediaWiki default') targeting User::newFromName() can also be of type false; however, WikiPage::doEditContent() does only seem to accept null|object<User>, did you maybe forget to handle an error condition?
Loading history...
1672
			);
1673
		} catch ( Exception $e ) {
1674
			// using raw, because $wgShowExceptionDetails can not be set yet
1675
			$status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1676
		}
1677
1678
		return $status;
1679
	}
1680
1681
	/**
1682
	 * Override the necessary bits of the config to run an installation.
1683
	 */
1684
	public static function overrideConfig() {
0 ignored issues
show
Coding Style introduced by
overrideConfig uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1685
		// Use PHP's built-in session handling, since MediaWiki's
1686
		// SessionHandler can't work before we have an object cache set up.
1687
		define( 'MW_NO_SESSION_HANDLER', 1 );
1688
1689
		// Don't access the database
1690
		$GLOBALS['wgUseDatabaseMessages'] = false;
1691
		// Don't cache langconv tables
1692
		$GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1693
		// Debug-friendly
1694
		$GLOBALS['wgShowExceptionDetails'] = true;
1695
		// Don't break forms
1696
		$GLOBALS['wgExternalLinkTarget'] = '_blank';
1697
1698
		// Extended debugging
1699
		$GLOBALS['wgShowSQLErrors'] = true;
1700
		$GLOBALS['wgShowDBErrorBacktrace'] = true;
1701
1702
		// Allow multiple ob_flush() calls
1703
		$GLOBALS['wgDisableOutputCompression'] = true;
1704
1705
		// Use a sensible cookie prefix (not my_wiki)
1706
		$GLOBALS['wgCookiePrefix'] = 'mw_installer';
1707
1708
		// Some of the environment checks make shell requests, remove limits
1709
		$GLOBALS['wgMaxShellMemory'] = 0;
1710
1711
		// Override the default CookieSessionProvider with a dummy
1712
		// implementation that won't stomp on PHP's cookies.
1713
		$GLOBALS['wgSessionProviders'] = [
1714
			[
1715
				'class' => 'InstallerSessionProvider',
1716
				'args' => [ [
1717
					'priority' => 1,
1718
				] ]
1719
			]
1720
		];
1721
1722
		// Don't try to use any object cache for SessionManager either.
1723
		$GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1724
	}
1725
1726
	/**
1727
	 * Add an installation step following the given step.
1728
	 *
1729
	 * @param callable $callback A valid installation callback array, in this form:
1730
	 *    array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1731
	 * @param string $findStep The step to find. Omit to put the step at the beginning
1732
	 */
1733
	public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1734
		$this->extraInstallSteps[$findStep][] = $callback;
1735
	}
1736
1737
	/**
1738
	 * Disable the time limit for execution.
1739
	 * Some long-running pages (Install, Upgrade) will want to do this
1740
	 */
1741
	protected function disableTimeLimit() {
1742
		MediaWiki\suppressWarnings();
1743
		set_time_limit( 0 );
1744
		MediaWiki\restoreWarnings();
1745
	}
1746
}
1747