Follwup r75575, honour table prefixes. Bad Roan ;)
[mediawiki.git] / includes / installer / CoreInstaller.php
blob2300d5792f9a043ef3a445bceb377ba89a42ce39
1 <?php
2 /**
3 * Base core installer.
5 * @file
6 * @ingroup Deployment
7 */
9 /**
10 * Base core installer class.
11 * Handles everything that is independent of user interface.
13 * @ingroup Deployment
14 * @since 1.17
16 abstract class CoreInstaller extends Installer {
18 /**
19 * MediaWiki configuration globals that will eventually be passed through
20 * to LocalSettings.php. The names only are given here, the defaults
21 * typically come from DefaultSettings.php.
23 * @var array
25 protected $defaultVarNames = array(
26 'wgSitename',
27 'wgPasswordSender',
28 'wgLanguageCode',
29 'wgRightsIcon',
30 'wgRightsText',
31 'wgRightsUrl',
32 'wgMainCacheType',
33 'wgEnableEmail',
34 'wgEnableUserEmail',
35 'wgEnotifUserTalk',
36 'wgEnotifWatchlist',
37 'wgEmailAuthentication',
38 'wgDBtype',
39 'wgDiff3',
40 'wgImageMagickConvertCommand',
41 'IP',
42 'wgScriptPath',
43 'wgScriptExtension',
44 'wgMetaNamespace',
45 'wgDeletedDirectory',
46 'wgEnableUploads',
47 'wgLogo',
48 'wgShellLocale',
49 'wgSecretKey',
50 'wgUseInstantCommons',
51 'wgUpgradeKey',
52 'wgDefaultSkin',
55 /**
56 * Variables that are stored alongside globals, and are used for any
57 * configuration of the installation process aside from the MediaWiki
58 * configuration. Map of names to defaults.
60 * @var array
62 protected $internalDefaults = array(
63 '_UserLang' => 'en',
64 '_Environment' => false,
65 '_CompiledDBs' => array(),
66 '_SafeMode' => false,
67 '_RaiseMemory' => false,
68 '_UpgradeDone' => false,
69 '_InstallDone' => false,
70 '_Caches' => array(),
71 '_InstallUser' => 'root',
72 '_InstallPassword' => '',
73 '_SameAccount' => true,
74 '_CreateDBAccount' => false,
75 '_NamespaceType' => 'site-name',
76 '_AdminName' => '', // will be set later, when the user selects language
77 '_AdminPassword' => '',
78 '_AdminPassword2' => '',
79 '_AdminEmail' => '',
80 '_Subscribe' => false,
81 '_SkipOptional' => 'continue',
82 '_RightsProfile' => 'wiki',
83 '_LicenseCode' => 'none',
84 '_CCDone' => false,
85 '_Extensions' => array(),
86 '_MemCachedServers' => '',
87 '_UpgradeKeySupplied' => false,
88 '_ExistingDBSettings' => false,
91 /**
92 * The actual list of installation steps. This will be initialized by getInstallSteps()
94 * @var array
96 private $installSteps = array();
98 /**
99 * Extra steps for installation, for things like DatabaseInstallers to modify
101 * @var array
103 protected $extraInstallSteps = array();
106 * Known object cache types and the functions used to test for their existence.
108 * @var array
110 protected $objectCaches = array(
111 'xcache' => 'xcache_get',
112 'apc' => 'apc_fetch',
113 'eaccel' => 'eaccelerator_get',
114 'wincache' => 'wincache_ucache_get'
118 * User rights profiles.
120 * @var array
122 public $rightsProfiles = array(
123 'wiki' => array(),
124 'no-anon' => array(
125 '*' => array( 'edit' => false )
127 'fishbowl' => array(
128 '*' => array(
129 'createaccount' => false,
130 'edit' => false,
133 'private' => array(
134 '*' => array(
135 'createaccount' => false,
136 'edit' => false,
137 'read' => false,
143 * License types.
145 * @var array
147 public $licenses = array(
148 'cc-by-sa' => array(
149 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
150 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
152 'cc-by-nc-sa' => array(
153 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
154 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
156 'pd' => array(
157 'url' => 'http://creativecommons.org/licenses/publicdomain/',
158 'icon' => '{$wgStylePath}/common/images/public-domain.png',
160 'gfdl-old' => array(
161 'url' => 'http://www.gnu.org/licenses/old-licenses/fdl-1.2.html',
162 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
164 'gfdl-current' => array(
165 'url' => 'http://www.gnu.org/copyleft/fdl.html',
166 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
168 'none' => array(
169 'url' => '',
170 'icon' => '',
171 'text' => ''
173 'cc-choose' => array(
174 // Details will be filled in by the selector.
175 'url' => '',
176 'icon' => '',
177 'text' => '',
182 * URL to mediawiki-announce subscription
184 protected $mediaWikiAnnounceUrl = 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
187 * Supported language codes for Mailman
189 protected $mediaWikiAnnounceLanguages = array(
190 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
191 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
192 'sl', 'sr', 'sv', 'tr', 'uk'
196 * TODO: document
198 * @param $status Status
200 public abstract function showStatusMessage( Status $status );
203 * Constructor, always call this from child classes.
205 public function __construct() {
206 parent::__construct();
208 global $wgExtensionMessagesFiles, $wgUser, $wgHooks;
210 // Load the installer's i18n file.
211 $wgExtensionMessagesFiles['MediawikiInstaller'] =
212 dirname( __FILE__ ) . '/Installer.i18n.php';
214 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
215 $wgUser = User::newFromId( 0 );
217 // Set our custom <doclink> hook.
218 $wgHooks['ParserFirstCallInit'][] = array( $this, 'registerDocLink' );
220 $this->settings = $this->internalDefaults;
222 foreach ( $this->defaultVarNames as $var ) {
223 $this->settings[$var] = $GLOBALS[$var];
226 foreach ( self::getDBTypes() as $type ) {
227 $installer = $this->getDBInstaller( $type );
229 if ( !$installer->isCompiled() ) {
230 continue;
233 $defaults = $installer->getGlobalDefaults();
235 foreach ( $installer->getGlobalNames() as $var ) {
236 if ( isset( $defaults[$var] ) ) {
237 $this->settings[$var] = $defaults[$var];
238 } else {
239 $this->settings[$var] = $GLOBALS[$var];
244 $this->parserTitle = Title::newFromText( 'Installer' );
245 $this->parserOptions = new ParserOptions; // language will be wrong :(
246 $this->parserOptions->setEditSection( false );
250 * Register tag hook below.
252 * @todo Move this to WebInstaller with the two things below?
254 * @param $parser Parser
256 public function registerDocLink( Parser &$parser ) {
257 $parser->setHook( 'doclink', array( $this, 'docLink' ) );
258 return true;
262 * ParserOptions are constructed before we determined the language, so fix it
264 public function setParserLanguage( $lang ) {
265 $this->parserOptions->setTargetLanguage( $lang );
266 $this->parserOptions->setUserLang( $lang );
270 * Extension tag hook for a documentation link.
272 public function docLink( $linkText, $attribs, $parser ) {
273 $url = $this->getDocUrl( $attribs['href'] );
274 return '<a href="' . htmlspecialchars( $url ) . '">' .
275 htmlspecialchars( $linkText ) .
276 '</a>';
280 * Overridden by WebInstaller to provide lastPage parameters.
282 protected function getDocUrl( $page ) {
283 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
287 * Finds extensions that follow the format /extensions/Name/Name.php,
288 * and returns an array containing the value for 'Name' for each found extension.
290 * @return array
292 public function findExtensions() {
293 if( $this->getVar( 'IP' ) === null ) {
294 return false;
297 $exts = array();
298 $dir = $this->getVar( 'IP' ) . '/extensions';
299 $dh = opendir( $dir );
301 while ( ( $file = readdir( $dh ) ) !== false ) {
302 if( file_exists( "$dir/$file/$file.php" ) ) {
303 $exts[] = $file;
307 return $exts;
311 * Installs the auto-detected extensions.
313 * @return Status
315 protected function includeExtensions() {
316 $exts = $this->getVar( '_Extensions' );
317 $path = $this->getVar( 'IP' ) . '/extensions';
319 foreach( $exts as $e ) {
320 require( "$path/$e/$e.php" );
323 return Status::newGood();
327 * Get an array of install steps. Should always be in the format of
328 * array(
329 * 'name' => 'someuniquename',
330 * 'callback' => array( $obj, 'method' ),
332 * There must be a config-install-$name message defined per step, which will
333 * be shown on install.
335 * @param $installer DatabaseInstaller so we can make callbacks
336 * @return array
338 protected function getInstallSteps( DatabaseInstaller &$installer ) {
339 $coreInstallSteps = array(
340 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
341 array( 'name' => 'tables', 'callback' => array( $this, 'installTables' ) ),
342 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
343 array( 'name' => 'secretkey', 'callback' => array( $this, 'generateSecretKey' ) ),
344 array( 'name' => 'upgradekey', 'callback' => array( $this, 'generateUpgradeKey' ) ),
345 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
346 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
349 // Build the array of install steps starting from the core install list,
350 // then adding any callbacks that wanted to attach after a given step
351 foreach( $coreInstallSteps as $step ) {
352 $this->installSteps[] = $step;
353 if( isset( $this->extraInstallSteps[ $step['name'] ] ) ) {
354 $this->installSteps = array_merge(
355 $this->installSteps,
356 $this->extraInstallSteps[ $step['name'] ]
361 // Prepend any steps that want to be at the beginning
362 if( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
363 $this->installSteps = array_merge(
364 $this->extraInstallSteps['BEGINNING'],
365 $this->installSteps
369 // Extensions should always go first, chance to tie into hooks and such
370 if( count( $this->getVar( '_Extensions' ) ) ) {
371 array_unshift( $this->installSteps,
372 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
375 return $this->installSteps;
379 * Actually perform the installation.
381 * @param $startCB A callback array for the beginning of each step
382 * @param $endCB A callback array for the end of each step
384 * @return Array of Status objects
386 public function performInstallation( $startCB, $endCB ) {
387 $installResults = array();
388 $installer = $this->getDBInstaller();
389 $installer->preInstall();
390 $steps = $this->getInstallSteps( $installer );
391 foreach( $steps as $stepObj ) {
392 $name = $stepObj['name'];
393 call_user_func_array( $startCB, array( $name ) );
395 // Perform the callback step
396 $status = call_user_func_array( $stepObj['callback'], array( &$installer ) );
398 // Output and save the results
399 call_user_func_array( $endCB, array( $name, $status ) );
400 $installResults[$name] = $status;
402 // If we've hit some sort of fatal, we need to bail.
403 // Callback already had a chance to do output above.
404 if( !$status->isOk() ) {
405 break;
408 if( $status->isOk() ) {
409 $this->setVar( '_InstallDone', true );
411 return $installResults;
415 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
416 * /dev/urandom
418 * @return Status
420 protected function generateSecretKey() {
421 return $this->generateSecret( 'wgSecretKey' );
425 * Generate a secret value for a variable using either
426 * /dev/urandom or mt_rand() Produce a warning in the later case.
428 * @return Status
430 protected function generateSecret( $secretName, $length = 64 ) {
431 if ( wfIsWindows() ) {
432 $file = null;
433 } else {
434 wfSuppressWarnings();
435 $file = fopen( "/dev/urandom", "r" );
436 wfRestoreWarnings();
439 $status = Status::newGood();
441 if ( $file ) {
442 $secretKey = bin2hex( fread( $file, $length / 2 ) );
443 fclose( $file );
444 } else {
445 $secretKey = '';
447 for ( $i = 0; $i < $length / 8; $i++ ) {
448 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
451 $status->warning( 'config-insecure-secret', '$' . $secretName );
454 $this->setVar( $secretName, $secretKey );
456 return $status;
460 * Generate a default $wgUpgradeKey. Will warn if we had to use
461 * mt_rand() instead of /dev/urandom
463 * @return Status
465 public function generateUpgradeKey() {
466 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
467 return $this->generateSecret( 'wgUpgradeKey', 16 );
472 * Create the first user account, grant it sysop and bureaucrat rights
474 * @return Status
476 protected function createSysop() {
477 $name = $this->getVar( '_AdminName' );
478 $user = User::newFromName( $name );
480 if ( !$user ) {
481 // We should've validated this earlier anyway!
482 return Status::newFatal( 'config-admin-error-user', $name );
485 if ( $user->idForName() == 0 ) {
486 $user->addToDatabase();
488 try {
489 $user->setPassword( $this->getVar( '_AdminPassword' ) );
490 } catch( PasswordError $pwe ) {
491 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
494 $user->addGroup( 'sysop' );
495 $user->addGroup( 'bureaucrat' );
496 if( $this->getVar( '_AdminEmail' ) ) {
497 $user->setEmail( $this->getVar( '_AdminEmail' ) );
499 $user->saveSettings();
501 $status = Status::newGood();
503 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
504 $this->subscribeToMediaWikiAnnounce( $status );
507 return $status;
510 private function subscribeToMediaWikiAnnounce( Status $s ) {
511 $params = array(
512 'email' => $this->getVar( '_AdminEmail' ),
513 'language' => 'en',
514 'digest' => 0
517 // Mailman doesn't support as many languages as we do, so check to make
518 // sure their selected language is available
519 $myLang = $this->getVar( '_UserLang' );
520 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
521 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
522 $params['language'] = $myLang;
525 $res = Http::post( $this->mediaWikiAnnounceUrl, array( 'postData' => $params ) );
526 if( !$res ) {
527 $s->warning( 'config-install-subscribe-fail' );
532 * Insert Main Page with default content.
534 * @return Status
536 protected function createMainpage( DatabaseInstaller &$installer ) {
537 $status = Status::newGood();
538 try {
539 $article = new Article( Title::newMainPage() );
540 $article->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
541 wfMsgForContent( 'mainpagedocfooter' ),
543 EDIT_NEW,
544 false,
545 User::newFromName( 'MediaWiki Default' ) );
546 } catch (MWException $e) {
547 //using raw, because $wgShowExceptionDetails can not be set yet
548 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
551 return $status;
555 * Override the necessary bits of the config to run an installation.
557 public static function overrideConfig() {
558 define( 'MW_NO_SESSION', 1 );
560 // Don't access the database
561 $GLOBALS['wgUseDatabaseMessages'] = false;
562 // Debug-friendly
563 $GLOBALS['wgShowExceptionDetails'] = true;
564 // Don't break forms
565 $GLOBALS['wgExternalLinkTarget'] = '_blank';
567 // Extended debugging
568 $GLOBALS['wgShowSQLErrors'] = true;
569 $GLOBALS['wgShowDBErrorBacktrace'] = true;
571 // Allow multiple ob_flush() calls
572 $GLOBALS['wgDisableOutputCompression'] = true;
574 // Use a sensible cookie prefix (not my_wiki)
575 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
577 // Some of the environment checks make shell requests, remove limits
578 $GLOBALS['wgMaxShellMemory'] = 0;
582 * Add an installation step following the given step.
584 * @param $callback Array A valid installation callback array, in this form:
585 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
586 * @param $findStep String the step to find. Omit to put the step at the beginning
588 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
589 $this->extraInstallSteps[$findStep][] = $callback;