new-installer: Use `` instead of wfShellExec() like the old installer
[lhc/web/wiklou.git] / includes / installer / Installer.php
1 <?php
2
3 /**
4 * Base installer class
5 * Handles everything that is independent of user interface
6 */
7 abstract class Installer {
8 var $settings, $output;
9
10 /**
11 * MediaWiki configuration globals that will eventually be passed through
12 * to LocalSettings.php. The names only are given here, the defaults
13 * typically come from DefaultSettings.php.
14 * @protected
15 */
16 var $defaultVarNames = array(
17 'wgSitename',
18 'wgPasswordSender',
19 'wgLanguageCode',
20 'wgRightsIcon',
21 'wgRightsText',
22 'wgRightsUrl',
23 'wgMainCacheType',
24 'wgEnableEmail',
25 'wgEnableUserEmail',
26 'wgEnotifUserTalk',
27 'wgEnotifWatchlist',
28 'wgEmailAuthentication',
29 'wgDBtype',
30 'wgDiff3',
31 'wgImageMagickConvertCommand',
32 'IP',
33 'wgScriptPath',
34 'wgScriptExtension',
35 'wgMetaNamespace',
36 // 'wgDeletedDirectory',
37 'wgEnableUploads',
38 'wgLogo',
39 'wgShellLocale',
40 'wgSecretKey',
41 );
42
43 /**
44 * Variables that are stored alongside globals, and are used for any
45 * configuration of the installation process aside from the MediaWiki
46 * configuration. Map of names to defaults.
47 * @protected
48 */
49 var $internalDefaults = array(
50 '_UserLang' => 'en',
51 '_Environment' => false,
52 '_CompiledDBs' => array(),
53 '_SafeMode' => false,
54 '_RaiseMemory' => false,
55 '_UpgradeDone' => false,
56 '_Caches' => array(),
57 '_InstallUser' => 'root',
58 '_InstallPassword' => '',
59 '_SameAccount' => true,
60 '_CreateDBAccount' => false,
61 '_NamespaceType' => 'site-name',
62 '_AdminName' => null, // will be set later, when the user selects language
63 '_AdminPassword' => '',
64 '_AdminPassword2' => '',
65 '_AdminEmail' => '',
66 '_Subscribe' => false,
67 '_SkipOptional' => 'continue',
68 '_RightsProfile' => 'wiki',
69 '_LicenseCode' => 'none',
70 '_CCDone' => false,
71 '_Extensions' => array(),
72 '_MemCachedServers' => '',
73 );
74
75 /**
76 * Known database types. These correspond to the class names <type>Installer,
77 * and are also MediaWiki database types valid for $wgDBtype.
78 *
79 * To add a new type, create a <type>Installer class and a Database<type>
80 * class, and add a config-type-<type> message to MessagesEn.php.
81 * @private
82 */
83 var $dbTypes = array(
84 'mysql',
85 'postgres',
86 'sqlite',
87 'oracle'
88 );
89
90 /**
91 * Minimum memory size in MB
92 */
93 private $minMemorySize = 50;
94
95 /**
96 * Cached DB installer instances, access using getDBInstaller()
97 * @private
98 */
99 var $dbInstallers = array();
100
101 /**
102 * A list of environment check methods called by doEnvironmentChecks().
103 * These may output warnings using showMessage(), and/or abort the
104 * installation process by returning false.
105 * @protected
106 */
107 var $envChecks = array(
108 'envLatestVersion',
109 'envCheckDB',
110 'envCheckRegisterGlobals',
111 'envCheckMagicQuotes',
112 'envCheckMagicSybase',
113 'envCheckMbstring',
114 'envCheckZE1',
115 'envCheckSafeMode',
116 'envCheckXML',
117 'envCheckPCRE',
118 'envCheckMemory',
119 'envCheckCache',
120 'envCheckDiff3',
121 'envCheckGraphics',
122 'envCheckPath',
123 'envCheckWriteableDir',
124 'envCheckExtension',
125 'envCheckShellLocale',
126 'envCheckUploadsDirectory',
127 );
128
129 var $installSteps = array(
130 'database',
131 'user',
132 'tables',
133 'interwiki',
134 'secretkey',
135 'sysop',
136 'localsettings',
137 );
138
139 /**
140 * Known object cache types and the functions used to test for their existence
141 * @protected
142 */
143 var $objectCaches = array(
144 'xcache' => 'xcache_get',
145 'apc' => 'apc_fetch',
146 'eaccel' => 'eaccelerator_get',
147 'wincache' => 'wincache_ucache_get'
148 );
149
150 /**
151 * User rights profiles
152 */
153 var $rightsProfiles = array(
154 'wiki' => array(),
155 'no-anon' => array(
156 '*' => array( 'edit' => false )
157 ),
158 'fishbowl' => array(
159 '*' => array(
160 'createaccount' => false,
161 'edit' => false,
162 ),
163 ),
164 'private' => array(
165 '*' => array(
166 'createaccount' => false,
167 'edit' => false,
168 'read' => false,
169 ),
170 ),
171 );
172
173 /**
174 * License types
175 */
176 var $licenses = array(
177 'none' => array(
178 'url' => '',
179 'icon' => '',
180 'text' => ''
181 ),
182 'cc-by-sa' => array(
183 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
184 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
185 ),
186 'cc-by-nc-sa' => array(
187 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
188 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
189 ),
190 'pd' => array(
191 'url' => 'http://creativecommons.org/licenses/publicdomain/',
192 'icon' => '{$wgStylePath}/common/images/public-domain.png',
193 ),
194 'gfdl-old' => array(
195 'url' => 'http://www.gnu.org/licenses/old-licenses/fdl-1.2.html',
196 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
197 ),
198 'gfdl-current' => array(
199 'url' => 'http://www.gnu.org/copyleft/fdl.html',
200 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
201 ),
202 'cc-choose' => array(
203 // details will be filled in by the selector
204 'url' => '',
205 'icon' => '',
206 'text' => '',
207 ),
208 );
209 /**
210 * Cached Title and ParserOptions used by parse()
211 * @private
212 */
213 var $parserTitle, $parserOptions;
214
215 /**
216 * Constructor, always call this from child classes
217 */
218 function __construct() {
219 // Disable the i18n cache and LoadBalancer
220 Language::getLocalisationCache()->disableBackend();
221 LBFactory::disableBackend();
222
223 // Load the installer's i18n file
224 global $wgExtensionMessagesFiles;
225 $wgExtensionMessagesFiles['MediawikiInstaller'] =
226 './includes/installer/Installer.i18n.php';
227
228 global $wgUser;
229 $wgUser = User::newFromId( 0 );
230 // Having a user with id = 0 safeguards us from DB access via User::loadOptions()
231
232 // Set our custom <doclink> hook
233 global $wgHooks;
234 $wgHooks['ParserFirstCallInit'][] = array( $this, 'registerDocLink' );
235
236 $this->settings = $this->internalDefaults;
237 foreach ( $this->defaultVarNames as $var ) {
238 $this->settings[$var] = $GLOBALS[$var];
239 }
240 foreach ( $this->dbTypes as $type ) {
241 $installer = $this->getDBInstaller( $type );
242 if ( !$installer->isCompiled() ) {
243 continue;
244 }
245 $defaults = $installer->getGlobalDefaults();
246 foreach ( $installer->getGlobalNames() as $var ) {
247 if ( isset( $defaults[$var] ) ) {
248 $this->settings[$var] = $defaults[$var];
249 } else {
250 $this->settings[$var] = $GLOBALS[$var];
251 }
252 }
253 }
254
255 $this->parserTitle = Title::newFromText( 'Installer' );
256 $this->parserOptions = new ParserOptions;
257 $this->parserOptions->setEditSection( false );
258 }
259
260 /**
261 * UI interface for displaying a short message
262 * The parameters are like parameters to wfMsg().
263 * The messages will be in wikitext format, which will be converted to an
264 * output format such as HTML or text before being sent to the user.
265 */
266 abstract function showMessage( $msg /*, ... */ );
267
268 abstract function showStatusMessage( $status );
269
270 /**
271 * Get a list of known DB types
272 */
273 function getDBTypes() {
274 return $this->dbTypes;
275 }
276
277 /**
278 * Get an instance of InstallerDBType for the specified DB type
279 * @param $type Mixed: DB installer for which is needed, false to use default
280 */
281 function getDBInstaller( $type = false ) {
282 if ( !$type ) {
283 $type = $this->getVar( 'wgDBtype' );
284 }
285 if ( !isset( $this->dbInstallers[$type] ) ) {
286 $class = ucfirst( $type ). 'Installer';
287 $this->dbInstallers[$type] = new $class( $this );
288 }
289 return $this->dbInstallers[$type];
290 }
291
292 /**
293 * Do initial checks of the PHP environment. Set variables according to
294 * the observed environment.
295 *
296 * It's possible that this may be called under the CLI SAPI, not the SAPI
297 * that the wiki will primarily run under. In that case, the subclass should
298 * initialise variables such as wgScriptPath, before calling this function.
299 *
300 * Under the web subclass, it can already be assumed that PHP 5+ is in use
301 * and that sessions are working.
302 */
303 function doEnvironmentChecks() {
304 $this->showMessage( 'config-env-php', phpversion() );
305
306 $good = true;
307 foreach ( $this->envChecks as $check ) {
308 $status = $this->$check();
309 if ( $status === false ) {
310 $good = false;
311 }
312 }
313 $this->setVar( '_Environment', $good );
314 if ( $good ) {
315 $this->showMessage( 'config-env-good' );
316 } else {
317 $this->showMessage( 'config-env-bad' );
318 }
319 return $good;
320 }
321
322 /**
323 * Get an MW configuration variable, or internal installer configuration variable.
324 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
325 * Installer variables are typically prefixed by an underscore.
326 */
327 function getVar( $name, $default = null ) {
328 if ( !isset( $this->settings[$name] ) ) {
329 return $default;
330 } else {
331 return $this->settings[$name];
332 }
333 }
334
335 /**
336 * Set a MW configuration variable, or internal installer configuration variable.
337 */
338 function setVar( $name, $value ) {
339 $this->settings[$name] = $value;
340 }
341
342 /**
343 * Exports all wg* variables stored by the installer into global scope
344 */
345 function exportVars() {
346 foreach ( $this->settings as $name => $value ) {
347 if ( substr( $name, 0, 2 ) == 'wg' ) {
348 $GLOBALS[$name] = $value;
349 }
350 }
351 }
352
353 /**
354 * Get a fake password for sending back to the user in HTML.
355 * This is a security mechanism to avoid compromise of the password in the
356 * event of session ID compromise.
357 */
358 function getFakePassword( $realPassword ) {
359 return str_repeat( '*', strlen( $realPassword ) );
360 }
361
362 /**
363 * Set a variable which stores a password, except if the new value is a
364 * fake password in which case leave it as it is.
365 */
366 function setPassword( $name, $value ) {
367 if ( !preg_match( '/^\*+$/', $value ) ) {
368 $this->setVar( $name, $value );
369 }
370 }
371
372 /** Check if we're installing the latest version */
373 function envLatestVersion() {
374 global $wgVersion;
375 $latestInfoUrl = 'http://www.mediawiki.org/w/api.php?action=mwreleases&format=json';
376 $latestInfo = Http::get( $latestInfoUrl );
377 if( !$latestInfo ) {
378 $this->showMessage( 'config-env-latest-can-not-check', $latestInfoUrl );
379 return;
380 }
381 $latestInfo = FormatJson::decode($latestInfo);
382 if ($latestInfo === false || !isset( $latestInfo->mwreleases ) ) {
383 # For when the request is successful but there's e.g. some silly man in
384 # the middle firewall blocking us, e.g. one of those annoying airport ones
385 $this->showMessage( 'config-env-latest-data-invalid', $latestInfoUrl );
386 return;
387 }
388 foreach( $latestInfo->mwreleases as $rel ) {
389 if( isset( $rel->current ) )
390 $currentVersion = $rel->version;
391 }
392 if( version_compare( $wgVersion, $currentVersion, '<' ) ) {
393 $this->showMessage( 'config-env-latest-old' );
394 $this->showHelpBox( 'config-env-latest-help', $wgVersion, $currentVersion );
395 } elseif( version_compare( $wgVersion, $currentVersion, '>' ) ) {
396 $this->showMessage( 'config-env-latest-new' );
397 }
398 $this->showMessage( 'config-env-latest-ok' );
399 }
400
401 /** Environment check for DB types */
402 function envCheckDB() {
403 $compiledDBs = array();
404 $goodNames = array();
405 $allNames = array();
406 foreach ( $this->dbTypes as $name ) {
407 $db = $this->getDBInstaller( $name );
408 $readableName = wfMsg( 'config-type-' . $name );
409 if ( $db->isCompiled() ) {
410 $compiledDBs[] = $name;
411 $goodNames[] = $readableName;
412 }
413 $allNames[] = $readableName;
414 }
415 $this->setVar( '_CompiledDBs', $compiledDBs );
416
417 global $wgLang;
418 if ( !$compiledDBs ) {
419 $this->showMessage( 'config-no-db' );
420 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
421 return false;
422 }
423 $this->showMessage( 'config-have-db', $wgLang->commaList( $goodNames ) );
424 }
425
426 /** Environment check for register_globals */
427 function envCheckRegisterGlobals() {
428 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
429 $this->showMessage( 'config-register-globals' );
430 }
431 }
432
433 /** Environment check for magic_quotes_runtime */
434 function envCheckMagicQuotes() {
435 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
436 $this->showMessage( 'config-magic-quotes-runtime' );
437 return false;
438 }
439 }
440
441 /** Environment check for magic_quotes_sybase */
442 function envCheckMagicSybase() {
443 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
444 $this->showMessage( 'config-magic-quotes-sybase' );
445 return false;
446 }
447 }
448
449 /* Environment check for mbstring.func_overload */
450 function envCheckMbstring() {
451 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
452 $this->showMessage( 'config-mbstring' );
453 return false;
454 }
455 }
456
457 /** Environment check for zend.ze1_compatibility_mode */
458 function envCheckZE1() {
459 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
460 $this->showMessage( 'config-ze1' );
461 return false;
462 }
463 }
464
465 /** Environment check for safe_mode */
466 function envCheckSafeMode() {
467 if ( wfIniGetBool( 'safe_mode' ) ) {
468 $this->setVar( '_SafeMode', true );
469 $this->showMessage( 'config-safe-mode' );
470 }
471 }
472
473 /** Environment check for the XML module */
474 function envCheckXML() {
475 if ( !function_exists( "utf8_encode" ) ) {
476 $this->showMessage( 'config-xml-bad' );
477 return false;
478 }
479 $this->showMessage( 'config-xml-good' );
480 }
481
482 /** Environment check for the PCRE module */
483 function envCheckPCRE() {
484 if ( !function_exists( 'preg_match' ) ) {
485 $this->showMessage( 'config-pcre' );
486 return false;
487 }
488 }
489
490 /** Environment check for available memory */
491 function envCheckMemory() {
492 $limit = ini_get( 'memory_limit' );
493 if ( !$limit || $limit == -1 ) {
494 $this->showMessage( 'config-memory-none' );
495 return true;
496 }
497 $n = intval( $limit );
498 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
499 $n = intval( $m[1] * (1024*1024) );
500 }
501 if( $n < $this->minMemorySize*1024*1024 ) {
502 $newLimit = "{$this->minMemorySize}M";
503 if( false === ini_set( "memory_limit", $newLimit ) ) {
504 $this->showMessage( 'config-memory-bad', $limit );
505 } else {
506 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
507 $this->setVar( '_RaiseMemory', true );
508 }
509 } else {
510 $this->showMessage( 'config-memory-ok', $limit );
511 }
512 }
513
514 /** Environment check for compiled object cache types */
515 function envCheckCache() {
516 $caches = array();
517 foreach ( $this->objectCaches as $name => $function ) {
518 if ( function_exists( $function ) ) {
519 $caches[$name] = true;
520 $this->showMessage( 'config-' . $name );
521 }
522 }
523 if ( !$caches ) {
524 $this->showMessage( 'config-no-cache' );
525 }
526 $this->setVar( '_Caches', $caches );
527 }
528
529 /** Search for GNU diff3 */
530 function envCheckDiff3() {
531 $paths = array_merge(
532 array(
533 "/usr/bin",
534 "/usr/local/bin",
535 "/opt/csw/bin",
536 "/usr/gnu/bin",
537 "/usr/sfw/bin" ),
538 explode( PATH_SEPARATOR, getenv( "PATH" ) ) );
539 $names = array( "gdiff3", "diff3", "diff3.exe" );
540
541 $versionInfo = array( '$1 --version 2>&1', 'diff3 (GNU diffutils)' );
542 $haveDiff3 = false;
543 foreach ( $paths as $path ) {
544 $exe = $this->locateExecutable( $path, $names, $versionInfo );
545 if ($exe !== false) {
546 $this->setVar( 'wgDiff3', $exe );
547 $haveDiff3 = true;
548 break;
549 }
550 }
551 if ( $haveDiff3 ) {
552 $this->showMessage( 'config-diff3-good', $exe );
553 } else {
554 $this->setVar( 'wgDiff3', false );
555 $this->showMessage( 'config-diff3-bad' );
556 }
557 }
558
559 /**
560 * Search a path for any of the given executable names. Returns the
561 * executable name if found. Also checks the version string returned
562 * by each executable
563 *
564 * @param $path String: path to search
565 * @param $names Array of executable names
566 * @param $versionInfo Boolean false or array with two members:
567 * 0 => Command to run for version check, with $1 for the path
568 * 1 => String to compare the output with
569 *
570 * If $versionInfo is not false, only executables with a version
571 * matching $versionInfo[1] will be returned.
572 */
573 function locateExecutable( $path, $names, $versionInfo = false ) {
574 if (!is_array($names))
575 $names = array($names);
576
577 foreach ($names as $name) {
578 $command = "$path/$name";
579 if ( @file_exists( $command ) ) {
580 if ( !$versionInfo )
581 return $command;
582
583 $file = str_replace( '$1', $command, $versionInfo[0] );
584 # Should maybe be wfShellExec( $file), but runs into a ulimit, see
585 # http://www.mediawiki.org/w/index.php?title=New-installer_issues&diff=prev&oldid=335456
586 if ( strstr( `$file`, $versionInfo[1]) !== false )
587 return $command;
588 }
589 }
590 return false;
591 }
592
593 /** Environment check for ImageMagick and GD */
594 function envCheckGraphics() {
595 $imcheck = array( "/usr/bin", "/opt/csw/bin", "/usr/local/bin", "/sw/bin", "/opt/local/bin" );
596 foreach( $imcheck as $dir ) {
597 $im = "$dir/convert";
598 if( @file_exists( $im ) ) {
599 $this->showMessage( 'config-imagemagick', $im );
600 $this->setVar( 'wgImageMagickConvertCommand', $im );
601 return true;
602 }
603 }
604 if ( function_exists( 'imagejpeg' ) ) {
605 $this->showMessage( 'config-gd' );
606 return true;
607 }
608 $this->showMessage( 'no-scaling' );
609 }
610
611 /** Environment check for setting $IP and $wgScriptPath */
612 function envCheckPath() {
613 $IP = dirname( dirname( dirname( __FILE__ ) ) );
614 $this->setVar( 'IP', $IP );
615 $this->showMessage( 'config-dir', $IP );
616
617 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
618 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
619 // to get the path to the current script... hopefully it's reliable. SIGH
620 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
621 $path = $_SERVER['PHP_SELF'];
622 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
623 $path = $_SERVER['SCRIPT_NAME'];
624 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
625 // Some kind soul has set it for us already (e.g. debconf)
626 return true;
627 } else {
628 $this->showMessage( 'config-no-uri' );
629 return false;
630 }
631 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
632 $this->setVar( 'wgScriptPath', $uri );
633 $this->showMessage( 'config-uri', $uri );
634 }
635
636 /** Environment check for writable config/ directory */
637 function envCheckWriteableDir() {
638 $ipDir = $this->getVar( 'IP' );
639 $configDir = $ipDir . '/config';
640 if( !is_writeable( $configDir ) ) {
641 $webserverGroup = self::maybeGetWebserverPrimaryGroup();
642 if ( $webserverGroup !== null ) {
643 $this->showMessage( 'config-dir-not-writable-group', $ipDir, $webserverGroup );
644 } else {
645 $this->showMessage( 'config-dir-not-writable-nogroup', $ipDir, $webserverGroup );
646 }
647 return false;
648 }
649 }
650
651 /** Environment check for setting the preferred PHP file extension */
652 function envCheckExtension() {
653 // FIXME: detect this properly
654 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
655 $ext = 'php5';
656 } else {
657 $ext = 'php';
658 }
659 $this->setVar( 'wgScriptExtension', ".$ext" );
660 $this->showMessage( 'config-file-extension', $ext );
661 }
662
663 function envCheckShellLocale() {
664 # Give up now if we're in safe mode or open_basedir
665 # It's theoretically possible but tricky to work with
666 if ( wfIniGetBool( "safe_mode" ) || ini_get( 'open_basedir' ) || !function_exists( 'exec' ) ) {
667 return true;
668 }
669
670 $os = php_uname( 's' );
671 $supported = array( 'Linux', 'SunOS', 'HP-UX' ); # Tested these
672 if ( !in_array( $os, $supported ) ) {
673 return true;
674 }
675
676 # Get a list of available locales
677 $lines = $ret = false;
678 exec( '/usr/bin/locale -a', $lines, $ret );
679 if ( $ret ) {
680 return true;
681 }
682
683 $lines = wfArrayMap( 'trim', $lines );
684 $candidatesByLocale = array();
685 $candidatesByLang = array();
686 foreach ( $lines as $line ) {
687 if ( $line === '' ) {
688 continue;
689 }
690 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
691 continue;
692 }
693 list( $all, $lang, $territory, $charset, $modifier ) = $m;
694 $candidatesByLocale[$m[0]] = $m;
695 $candidatesByLang[$lang][] = $m;
696 }
697
698 # Try the current value of LANG
699 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
700 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
701 $this->showMessage( 'config-shell-locale', getenv( 'LANG' ) );
702 return true;
703 }
704
705 # Try the most common ones
706 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
707 foreach ( $commonLocales as $commonLocale ) {
708 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
709 $this->setVar( 'wgShellLocale', $commonLocale );
710 $this->showMessage( 'config-shell-locale', $commonLocale );
711 return true;
712 }
713 }
714
715 # Is there an available locale in the Wiki's language?
716 $wikiLang = $this->getVar( 'wgLanguageCode' );
717 if ( isset( $candidatesByLang[$wikiLang] ) ) {
718 $m = reset( $candidatesByLang[$wikiLang] );
719 $this->setVar( 'wgShellLocale', $m[0] );
720 $this->showMessage( 'config-shell-locale', $m[0] );
721 return true;
722 }
723
724 # Are there any at all?
725 if ( count( $candidatesByLocale ) ) {
726 $m = reset( $candidatesByLocale );
727 $this->setVar( 'wgShellLocale', $m[0] );
728 $this->showMessage( 'config-shell-locale', $m[0] );
729 return true;
730 }
731
732 # Give up
733 return true;
734 }
735
736 function envCheckUploadsDirectory() {
737 global $IP, $wgServer;
738 $dir = $IP . '/images/';
739 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
740 $safe = !$this->dirIsExecutable( $dir, $url );
741 if ( $safe ) {
742 $this->showMessage( 'config-uploads-safe' );
743 } else {
744 $this->showMessage( 'config-uploads-not-safe', $dir );
745 }
746 }
747
748 /**
749 * Checks if scripts located in the given directory can be executed via the given URL
750 */
751 function dirIsExecutable( $dir, $url ) {
752 $scriptTypes = array(
753 'php' => array(
754 "<?php echo 'ex' . 'ec';",
755 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
756 ),
757 );
758 // it would be good to check other popular languages here, but it'll be slow
759
760 wfSuppressWarnings();
761 foreach ( $scriptTypes as $ext => $contents ) {
762 foreach ( $contents as $source ) {
763 $file = 'exectest.' . $ext;
764 if ( !file_put_contents( $dir . $file, $source ) ) {
765 break;
766 }
767 $text = Http::get( $url . $file );
768 unlink( $dir . $file );
769 if ( $text == 'exec' ) {
770 wfRestoreWarnings();
771 return $ext;
772 }
773 }
774 }
775 wfRestoreWarnings();
776 return false;
777 }
778
779 /**
780 * Convert wikitext $text to HTML.
781 *
782 * This is potentially error prone since many parser features require a complete
783 * installed MW database. The solution is to just not use those features when you
784 * write your messages. This appears to work well enough. Basic formatting and
785 * external links work just fine.
786 *
787 * But in case a translator decides to throw in a #ifexist or internal link or
788 * whatever, this function is guarded to catch attempted DB access and to present
789 * some fallback text.
790 *
791 * @param $text String
792 * @param $lineStart Boolean
793 * @return String
794 */
795 function parse( $text, $lineStart = false ) {
796 global $wgParser;
797 try {
798 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
799 $html = $out->getText();
800 } catch ( DBAccessError $e ) {
801 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
802 if ( !empty( $this->debug ) ) {
803 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
804 }
805 }
806 return $html;
807 }
808
809 /**
810 * Register tag hook below
811 */
812 function registerDocLink( &$parser ) {
813 $parser->setHook( 'doclink', array( $this, 'docLink' ) );
814 return true;
815 }
816
817 /**
818 * Extension tag hook for a documentation link
819 */
820 function docLink( $linkText, $attribs, $parser ) {
821 $url = $this->getDocUrl( $attribs['href'] );
822 return '<a href="' . htmlspecialchars( $url ) . '">' .
823 htmlspecialchars( $linkText ) .
824 '</a>';
825 }
826
827 /**
828 * Overridden by WebInstaller to provide lastPage parameters
829 */
830 protected function getDocUrl( $page ) {
831 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $attribs['href'] );
832 }
833
834 public function findExtensions() {
835 if( $this->getVar( 'IP' ) === null ) {
836 return false;
837 }
838 $exts = array();
839 $dir = $this->getVar( 'IP' ) . '/extensions';
840 $dh = opendir( $dir );
841 while ( ( $file = readdir( $dh ) ) !== false ) {
842 if( file_exists( "$dir/$file/$file.php" ) ) {
843 $exts[] = $file;
844 }
845 }
846 $this->setVar( '_Extensions', $exts );
847 return $exts;
848 }
849
850 public function getInstallSteps() {
851 if( $this->getVar( '_UpgradeDone' ) ) {
852 $this->installSteps = array( 'localsettings' );
853 }
854 if( count( $this->getVar( '_Extensions' ) ) ) {
855 array_unshift( $this->installSteps, 'extensions' );
856 }
857 return $this->installSteps;
858 }
859
860 public function installExtensions() {
861 global $wgHooks, $wgAutoloadClasses;
862 $exts = $this->getVar( '_Extensions' );
863 $path = $this->getVar( 'IP' ) . '/extensions';
864 foreach( $exts as $e ) {
865 require( "$path/$e/$e.php" );
866 }
867 return Status::newGood();
868 }
869
870 public function installDatabase() {
871 $installer = $this->getDBInstaller( $this->getVar( 'wgDBtype' ) );
872 $status = $installer->setupDatabase();
873 return $status;
874 }
875
876 public function installUser() {
877 $installer = $this->getDBInstaller( $this->getVar( 'wgDBtype' ) );
878 $status = $installer->setupUser();
879 return $status;
880 }
881
882 public function installTables() {
883 $installer = $this->getDBInstaller();
884 $status = $installer->createTables();
885 if( $status->isOK() ) {
886 LBFactory::enableBackend();
887 }
888 return $status;
889 }
890
891 public function installInterwiki() {
892 $installer = $this->getDBInstaller();
893 return $installer->populateInterwikiTable();
894 }
895
896 public function installSecretKey() {
897 if ( wfIsWindows() ) {
898 $file = null;
899 } else {
900 wfSuppressWarnings();
901 $file = fopen( "/dev/urandom", "r" );
902 wfRestoreWarnings();
903 }
904
905 $status = Status::newGood();
906
907 if ( $file ) {
908 $secretKey = bin2hex( fread( $file, 32 ) );
909 fclose( $file );
910 } else {
911 $secretKey = "";
912 for ( $i=0; $i<8; $i++ ) {
913 $secretKey .= dechex(mt_rand(0, 0x7fffffff));
914 }
915 $status->warning( 'config-insecure-secretkey' );
916 }
917 $this->setVar( 'wgSecretKey', $secretKey );
918
919 return $status;
920 }
921
922 public function installSysop() {
923 $name = $this->getVar( '_AdminName' );
924 $user = User::newFromName( $name );
925 if ( !$user ) {
926 // we should've validated this earlier anyway!
927 return Status::newFatal( 'config-admin-error-user', $name );
928 }
929 if ( $user->idForName() == 0 ) {
930 $user->addToDatabase();
931 try {
932 $user->setPassword( $this->getVar( '_AdminPassword' ) );
933 } catch( PasswordError $pwe ) {
934 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
935 }
936 $user->addGroup( 'sysop' );
937 $user->addGroup( 'bureaucrat' );
938 $user->saveSettings();
939 }
940 return Status::newGood();
941 }
942
943 public function installLocalsettings() {
944 $localSettings = new LocalSettingsGenerator( $this );
945 return $localSettings->writeLocalSettings();
946 }
947
948 /**
949 * Determine if LocalSettings exists. If it does, return an appropriate
950 * status for whether we should can upgrade or not
951 * @return Status
952 */
953 function getLocalSettingsStatus() {
954 global $IP;
955
956 $status = Status::newGood();
957
958 wfSuppressWarnings();
959 $ls = file_exists( "$IP/LocalSettings.php" );
960 wfRestoreWarnings();
961
962 if( $ls ) {
963 if( $this->parent->getDBInstaller()->needsUpgrade() ) {
964 $status->warning( 'config-localsettings-upgrade' );
965 }
966 else {
967 $status->fatal( 'config-localsettings-noupgrade' );
968 }
969 }
970 return $status;
971 }
972
973 /**
974 * On POSIX systems return the primary group of the webserver we're running under.
975 * On other systems just returns null.
976 *
977 * This is used to advice the user that he should chgrp his config/data/images directory as the
978 * webserver user before he can install.
979 *
980 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
981 *
982 * @return String
983 */
984 public static function maybeGetWebserverPrimaryGroup() {
985 if ( ! function_exists('posix_getegid') || ! function_exists('posix_getpwuid') ) {
986 # I don't know this, this isn't UNIX
987 return null;
988 }
989
990 # posix_getegid() *not* getmygid() because we want the group of the webserver,
991 # not whoever owns the current script
992 $gid = posix_getegid();
993 $getpwuid = posix_getpwuid( $gid );
994 $group = $getpwuid["name"];
995
996 return $group;
997 }
998
999 /**
1000 * Override the necessary bits of the config to run an installation
1001 */
1002 public static function overrideConfig() {
1003 define( 'MW_NO_SESSION', 1 );
1004
1005 // Don't access the database
1006 $GLOBALS['wgUseDatabaseMessages'] = false;
1007 // Debug-friendly
1008 $GLOBALS['wgShowExceptionDetails'] = true;
1009 // Don't break forms
1010 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1011
1012 // Extended debugging. Maybe disable before release?
1013 $GLOBALS['wgShowSQLErrors'] = true;
1014 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1015 }
1016 }