Moved constant values from initialiseFromUser() to class definition
[lhc/web/wiklou.git] / includes / installer / CoreInstaller.php
1 <?php
2 /**
3 * Base core installer.
4 *
5 * @file
6 * @ingroup Deployment
7 */
8
9 /**
10 * Base core installer class.
11 * Handles everything that is independent of user interface.
12 *
13 * @ingroup Deployment
14 * @since 1.17
15 */
16 abstract class CoreInstaller extends Installer {
17
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.
22 *
23 * @var array
24 */
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',
53 );
54
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.
59 *
60 * @var array
61 */
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,
89 );
90
91 /**
92 * Extra steps for installation, for things like DatabaseInstallers to modify
93 *
94 * @var array
95 */
96 protected $extraInstallSteps = array();
97
98 /**
99 * Known object cache types and the functions used to test for their existence.
100 *
101 * @var array
102 */
103 protected $objectCaches = array(
104 'xcache' => 'xcache_get',
105 'apc' => 'apc_fetch',
106 'eaccel' => 'eaccelerator_get',
107 'wincache' => 'wincache_ucache_get'
108 );
109
110 /**
111 * User rights profiles.
112 *
113 * @var array
114 */
115 public $rightsProfiles = array(
116 'wiki' => array(),
117 'no-anon' => array(
118 '*' => array( 'edit' => false )
119 ),
120 'fishbowl' => array(
121 '*' => array(
122 'createaccount' => false,
123 'edit' => false,
124 ),
125 ),
126 'private' => array(
127 '*' => array(
128 'createaccount' => false,
129 'edit' => false,
130 'read' => false,
131 ),
132 ),
133 );
134
135 /**
136 * License types.
137 *
138 * @var array
139 */
140 public $licenses = array(
141 'cc-by-sa' => array(
142 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
143 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
144 ),
145 'cc-by-nc-sa' => array(
146 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
147 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
148 ),
149 'pd' => array(
150 'url' => 'http://creativecommons.org/licenses/publicdomain/',
151 'icon' => '{$wgStylePath}/common/images/public-domain.png',
152 ),
153 'gfdl-old' => array(
154 'url' => 'http://www.gnu.org/licenses/old-licenses/fdl-1.2.html',
155 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
156 ),
157 'gfdl-current' => array(
158 'url' => 'http://www.gnu.org/copyleft/fdl.html',
159 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
160 ),
161 'none' => array(
162 'url' => '',
163 'icon' => '',
164 'text' => ''
165 ),
166 'cc-choose' => array(
167 // Details will be filled in by the selector.
168 'url' => '',
169 'icon' => '',
170 'text' => '',
171 ),
172 );
173
174 /**
175 * TODO: document
176 *
177 * @param $status Status
178 */
179 public abstract function showStatusMessage( Status $status );
180
181
182 /**
183 * Constructor, always call this from child classes.
184 */
185 public function __construct() {
186 parent::__construct();
187
188 global $wgExtensionMessagesFiles, $wgUser, $wgHooks;
189
190 // Load the installer's i18n file.
191 $wgExtensionMessagesFiles['MediawikiInstaller'] =
192 dirname( __FILE__ ) . '/Installer.i18n.php';
193
194 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
195 $wgUser = User::newFromId( 0 );
196
197 // Set our custom <doclink> hook.
198 $wgHooks['ParserFirstCallInit'][] = array( $this, 'registerDocLink' );
199
200 $this->settings = $this->internalDefaults;
201
202 foreach ( $this->defaultVarNames as $var ) {
203 $this->settings[$var] = $GLOBALS[$var];
204 }
205
206 foreach ( self::getDBTypes() as $type ) {
207 $installer = $this->getDBInstaller( $type );
208
209 if ( !$installer->isCompiled() ) {
210 continue;
211 }
212
213 $defaults = $installer->getGlobalDefaults();
214
215 foreach ( $installer->getGlobalNames() as $var ) {
216 if ( isset( $defaults[$var] ) ) {
217 $this->settings[$var] = $defaults[$var];
218 } else {
219 $this->settings[$var] = $GLOBALS[$var];
220 }
221 }
222 }
223
224 $this->parserTitle = Title::newFromText( 'Installer' );
225 $this->parserOptions = new ParserOptions;
226 $this->parserOptions->setEditSection( false );
227 }
228
229 /**
230 * Register tag hook below.
231 *
232 * @todo Move this to WebInstaller with the two things below?
233 *
234 * @param $parser Parser
235 */
236 public function registerDocLink( Parser &$parser ) {
237 $parser->setHook( 'doclink', array( $this, 'docLink' ) );
238 return true;
239 }
240
241 /**
242 * Extension tag hook for a documentation link.
243 */
244 public function docLink( $linkText, $attribs, $parser ) {
245 $url = $this->getDocUrl( $attribs['href'] );
246 return '<a href="' . htmlspecialchars( $url ) . '">' .
247 htmlspecialchars( $linkText ) .
248 '</a>';
249 }
250
251 /**
252 * Overridden by WebInstaller to provide lastPage parameters.
253 */
254 protected function getDocUrl( $page ) {
255 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $attribs['href'] );
256 }
257
258 /**
259 * Finds extensions that follow the format /extensions/Name/Name.php,
260 * and returns an array containing the value for 'Name' for each found extension.
261 *
262 * @return array
263 */
264 public function findExtensions() {
265 if( $this->getVar( 'IP' ) === null ) {
266 return false;
267 }
268
269 $exts = array();
270 $dir = $this->getVar( 'IP' ) . '/extensions';
271 $dh = opendir( $dir );
272
273 while ( ( $file = readdir( $dh ) ) !== false ) {
274 if( file_exists( "$dir/$file/$file.php" ) ) {
275 $exts[] = $file;
276 }
277 }
278
279 return $exts;
280 }
281
282 /**
283 * Installs the auto-detected extensions.
284 *
285 * @return Status
286 */
287 protected function includeExtensions() {
288 $exts = $this->getVar( '_Extensions' );
289 $path = $this->getVar( 'IP' ) . '/extensions';
290
291 foreach( $exts as $e ) {
292 require( "$path/$e/$e.php" );
293 }
294
295 return Status::newGood();
296 }
297
298 /**
299 * Get an array of install steps. These could be a plain key like the defaults
300 * in $installSteps, or could be an array with a name and a specific callback
301 * There must be a config-install-$step message defined per step, which will
302 * be shown on install.
303 *
304 * @param $installer DatabaseInstaller so we can make callbacks
305 * @return array
306 */
307 protected function getInstallSteps( DatabaseInstaller &$installer ) {
308 $installSteps = array(
309 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
310 array( 'name' => 'tables', 'callback' => array( $this, 'installTables' ) ),
311 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
312 array( 'name' => 'secretkey', 'callback' => array( $this, 'generateSecretKey' ) ),
313 array( 'name' => 'upgradekey', 'callback' => array( $this, 'generateUpgradeKey' ) ),
314 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
315 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
316 );
317 if( count( $this->getVar( '_Extensions' ) ) ) {
318 array_unshift( $installSteps,
319 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
320 );
321 }
322 foreach( $installSteps as $idx => $stepObj ) {
323 if( isset( $this->extraInstallSteps[ $stepObj['name'] ] ) ) {
324 $tmp = array_slice( $installSteps, 0, $idx );
325 $tmp[] = $this->extraInstallSteps[ $stepObj['name'] ];
326 $installSteps = array_merge( $tmp, array_slice( $installSteps, $idx ) );
327 }
328 }
329 return $installSteps;
330 }
331
332 /**
333 * Actually perform the installation.
334 *
335 * @param $startCB A callback array for the beginning of each step
336 * @param $endCB A callback array for the end of each step
337 *
338 * @return Array of Status objects
339 */
340 public function performInstallation( $startCB, $endCB ) {
341 $installResults = array();
342 $installer = $this->getDBInstaller();
343 $installer->preInstall();
344 $steps = $this->getInstallSteps( $installer );
345 foreach( $steps as $stepObj ) {
346 $name = $stepObj['name'];
347 call_user_func_array( $startCB, array( $name ) );
348
349 // Perform the callback step
350 $status = call_user_func_array( $stepObj['callback'], array( &$installer ) );
351
352 // Output and save the results
353 call_user_func_array( $endCB, array( $name, $status ) );
354 $installResults[$name] = $status;
355
356 // If we've hit some sort of fatal, we need to bail.
357 // Callback already had a chance to do output above.
358 if( !$status->isOk() ) {
359 break;
360 }
361 }
362 if( $status->isOk() ) {
363 $this->setVar( '_InstallDone', true );
364 }
365 return $installResults;
366 }
367
368 /**
369 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
370 * /dev/urandom
371 *
372 * @return Status
373 */
374 protected function generateSecretKey() {
375 return $this->generateSecret( 'wgSecretKey' );
376 }
377
378 /**
379 * Generate a secret value for a variable using either
380 * /dev/urandom or mt_rand() Produce a warning in the later case.
381 *
382 * @return Status
383 */
384 protected function generateSecret( $secretName, $length = 64 ) {
385 if ( wfIsWindows() ) {
386 $file = null;
387 } else {
388 wfSuppressWarnings();
389 $file = fopen( "/dev/urandom", "r" );
390 wfRestoreWarnings();
391 }
392
393 $status = Status::newGood();
394
395 if ( $file ) {
396 $secretKey = bin2hex( fread( $file, $length / 2 ) );
397 fclose( $file );
398 } else {
399 $secretKey = '';
400
401 for ( $i = 0; $i < $length / 8; $i++ ) {
402 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
403 }
404
405 $status->warning( 'config-insecure-secret', '$' . $secretName );
406 }
407
408 $this->setVar( $secretName, $secretKey );
409
410 return $status;
411 }
412
413 /**
414 * Generate a default $wgUpgradeKey. Will warn if we had to use
415 * mt_rand() instead of /dev/urandom
416 *
417 * @return Status
418 */
419 public function generateUpgradeKey() {
420 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
421 return $this->generateSecret( 'wgUpgradeKey', 16 );
422 }
423 }
424
425 /**
426 * Create the first user account, grant it sysop and bureaucrat rights
427 *
428 * @return Status
429 */
430 protected function createSysop() {
431 $name = $this->getVar( '_AdminName' );
432 $user = User::newFromName( $name );
433
434 if ( !$user ) {
435 // We should've validated this earlier anyway!
436 return Status::newFatal( 'config-admin-error-user', $name );
437 }
438
439 if ( $user->idForName() == 0 ) {
440 $user->addToDatabase();
441
442 try {
443 $user->setPassword( $this->getVar( '_AdminPassword' ) );
444 } catch( PasswordError $pwe ) {
445 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
446 }
447
448 $user->addGroup( 'sysop' );
449 $user->addGroup( 'bureaucrat' );
450 $user->saveSettings();
451 }
452
453 return Status::newGood();
454 }
455
456 /**
457 * Insert Main Page with default content.
458 *
459 * @return Status
460 */
461 protected function createMainpage( DatabaseInstaller &$installer ) {
462 $status = Status::newGood();
463 try {
464 $article = new Article( Title::newMainPage() );
465 $article->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
466 wfMsgForContent( 'mainpagedocfooter' ),
467 '',
468 EDIT_NEW,
469 false,
470 User::newFromName( 'MediaWiki Default' ) );
471 } catch (MWException $e) {
472 //using raw, because $wgShowExceptionDetails can not be set yet
473 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
474 }
475
476 return $status;
477 }
478
479 /**
480 * Override the necessary bits of the config to run an installation.
481 */
482 public static function overrideConfig() {
483 define( 'MW_NO_SESSION', 1 );
484
485 // Don't access the database
486 $GLOBALS['wgUseDatabaseMessages'] = false;
487 // Debug-friendly
488 $GLOBALS['wgShowExceptionDetails'] = true;
489 // Don't break forms
490 $GLOBALS['wgExternalLinkTarget'] = '_blank';
491
492 // Extended debugging
493 $GLOBALS['wgShowSQLErrors'] = true;
494 $GLOBALS['wgShowDBErrorBacktrace'] = true;
495
496 // Allow multiple ob_flush() calls
497 $GLOBALS['wgDisableOutputCompression'] = true;
498
499 // Use a sensible cookie prefix (not my_wiki)
500 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
501
502 // Some of the environment checks make shell requests, remove limits
503 $GLOBALS['wgMaxShellMemory'] = 0;
504 }
505
506 /**
507 * Add an installation step following the given step.
508 *
509 * @param $findStep String the step to find. Use NULL to put the step at the beginning.
510 * @param $callback array A valid callback array, with name and callback given
511 */
512 public function addInstallStepFollowing( $findStep, $callback ) {
513 $this->extraInstallSteps[$findStep] = $callback;
514 }
515 }