Merge "Revert API part of "Add page_props table access class""
[lhc/web/wiklou.git] / includes / installer / Installer.php
1 <?php
2 /**
3 * Base code for MediaWiki installer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Deployment
22 */
23
24 /**
25 * This documentation group collects source code files with deployment functionality.
26 *
27 * @defgroup Deployment Deployment
28 */
29
30 /**
31 * Base installer class.
32 *
33 * This class provides the base for installation and update functionality
34 * for both MediaWiki core and extensions.
35 *
36 * @ingroup Deployment
37 * @since 1.17
38 */
39 abstract class Installer {
40
41 /**
42 * The oldest version of PCRE we can support.
43 *
44 * Defining this is necessary because PHP may be linked with a system version
45 * of PCRE, which may be older than that bundled with the minimum PHP version.
46 */
47 const MINIMUM_PCRE_VERSION = '7.2';
48
49 /**
50 * @var array
51 */
52 protected $settings;
53
54 /**
55 * List of detected DBs, access using getCompiledDBs().
56 *
57 * @var array
58 */
59 protected $compiledDBs;
60
61 /**
62 * Cached DB installer instances, access using getDBInstaller().
63 *
64 * @var array
65 */
66 protected $dbInstallers = array();
67
68 /**
69 * Minimum memory size in MB.
70 *
71 * @var int
72 */
73 protected $minMemorySize = 50;
74
75 /**
76 * Cached Title, used by parse().
77 *
78 * @var Title
79 */
80 protected $parserTitle;
81
82 /**
83 * Cached ParserOptions, used by parse().
84 *
85 * @var ParserOptions
86 */
87 protected $parserOptions;
88
89 /**
90 * Known database types. These correspond to the class names <type>Installer,
91 * and are also MediaWiki database types valid for $wgDBtype.
92 *
93 * To add a new type, create a <type>Installer class and a Database<type>
94 * class, and add a config-type-<type> message to MessagesEn.php.
95 *
96 * @var array
97 */
98 protected static $dbTypes = array(
99 'mysql',
100 'postgres',
101 'oracle',
102 'mssql',
103 'sqlite',
104 );
105
106 /**
107 * A list of environment check methods called by doEnvironmentChecks().
108 * These may output warnings using showMessage(), and/or abort the
109 * installation process by returning false.
110 *
111 * For the WebInstaller these are only called on the Welcome page,
112 * if these methods have side-effects that should affect later page loads
113 * (as well as the generated stylesheet), use envPreps instead.
114 *
115 * @var array
116 */
117 protected $envChecks = array(
118 'envCheckDB',
119 'envCheckRegisterGlobals',
120 'envCheckBrokenXML',
121 'envCheckMagicQuotes',
122 'envCheckMbstring',
123 'envCheckSafeMode',
124 'envCheckXML',
125 'envCheckPCRE',
126 'envCheckMemory',
127 'envCheckCache',
128 'envCheckModSecurity',
129 'envCheckDiff3',
130 'envCheckGraphics',
131 'envCheckGit',
132 'envCheckServer',
133 'envCheckPath',
134 'envCheckShellLocale',
135 'envCheckUploadsDirectory',
136 'envCheckLibicu',
137 'envCheckSuhosinMaxValueLength',
138 'envCheckCtype',
139 'envCheckIconv',
140 'envCheckJSON',
141 );
142
143 /**
144 * A list of environment preparation methods called by doEnvironmentPreps().
145 *
146 * @var array
147 */
148 protected $envPreps = array(
149 'envPrepServer',
150 'envPrepPath',
151 );
152
153 /**
154 * MediaWiki configuration globals that will eventually be passed through
155 * to LocalSettings.php. The names only are given here, the defaults
156 * typically come from DefaultSettings.php.
157 *
158 * @var array
159 */
160 protected $defaultVarNames = array(
161 'wgSitename',
162 'wgPasswordSender',
163 'wgLanguageCode',
164 'wgRightsIcon',
165 'wgRightsText',
166 'wgRightsUrl',
167 'wgEnableEmail',
168 'wgEnableUserEmail',
169 'wgEnotifUserTalk',
170 'wgEnotifWatchlist',
171 'wgEmailAuthentication',
172 'wgDBname',
173 'wgDBtype',
174 'wgDiff3',
175 'wgImageMagickConvertCommand',
176 'wgGitBin',
177 'IP',
178 'wgScriptPath',
179 'wgMetaNamespace',
180 'wgDeletedDirectory',
181 'wgEnableUploads',
182 'wgShellLocale',
183 'wgSecretKey',
184 'wgUseInstantCommons',
185 'wgUpgradeKey',
186 'wgDefaultSkin',
187 );
188
189 /**
190 * Variables that are stored alongside globals, and are used for any
191 * configuration of the installation process aside from the MediaWiki
192 * configuration. Map of names to defaults.
193 *
194 * @var array
195 */
196 protected $internalDefaults = array(
197 '_UserLang' => 'en',
198 '_Environment' => false,
199 '_SafeMode' => false,
200 '_RaiseMemory' => false,
201 '_UpgradeDone' => false,
202 '_InstallDone' => false,
203 '_Caches' => array(),
204 '_InstallPassword' => '',
205 '_SameAccount' => true,
206 '_CreateDBAccount' => false,
207 '_NamespaceType' => 'site-name',
208 '_AdminName' => '', // will be set later, when the user selects language
209 '_AdminPassword' => '',
210 '_AdminPasswordConfirm' => '',
211 '_AdminEmail' => '',
212 '_Subscribe' => false,
213 '_SkipOptional' => 'continue',
214 '_RightsProfile' => 'wiki',
215 '_LicenseCode' => 'none',
216 '_CCDone' => false,
217 '_Extensions' => array(),
218 '_Skins' => array(),
219 '_MemCachedServers' => '',
220 '_UpgradeKeySupplied' => false,
221 '_ExistingDBSettings' => false,
222
223 // $wgLogo is probably wrong (bug 48084); set something that will work.
224 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
225 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
226 );
227
228 /**
229 * The actual list of installation steps. This will be initialized by getInstallSteps()
230 *
231 * @var array
232 */
233 private $installSteps = array();
234
235 /**
236 * Extra steps for installation, for things like DatabaseInstallers to modify
237 *
238 * @var array
239 */
240 protected $extraInstallSteps = array();
241
242 /**
243 * Known object cache types and the functions used to test for their existence.
244 *
245 * @var array
246 */
247 protected $objectCaches = array(
248 'xcache' => 'xcache_get',
249 'apc' => 'apc_fetch',
250 'wincache' => 'wincache_ucache_get'
251 );
252
253 /**
254 * User rights profiles.
255 *
256 * @var array
257 */
258 public $rightsProfiles = array(
259 'wiki' => array(),
260 'no-anon' => array(
261 '*' => array( 'edit' => false )
262 ),
263 'fishbowl' => array(
264 '*' => array(
265 'createaccount' => false,
266 'edit' => false,
267 ),
268 ),
269 'private' => array(
270 '*' => array(
271 'createaccount' => false,
272 'edit' => false,
273 'read' => false,
274 ),
275 ),
276 );
277
278 /**
279 * License types.
280 *
281 * @var array
282 */
283 public $licenses = array(
284 'cc-by' => array(
285 'url' => 'https://creativecommons.org/licenses/by/4.0/',
286 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
287 ),
288 'cc-by-sa' => array(
289 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
290 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
291 ),
292 'cc-by-nc-sa' => array(
293 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
294 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
295 ),
296 'cc-0' => array(
297 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
298 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
299 ),
300 'pd' => array(
301 'url' => '',
302 'icon' => '$wgResourceBasePath/resources/assets/licenses/public-domain.png',
303 ),
304 'gfdl' => array(
305 'url' => 'https://www.gnu.org/copyleft/fdl.html',
306 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
307 ),
308 'none' => array(
309 'url' => '',
310 'icon' => '',
311 'text' => ''
312 ),
313 'cc-choose' => array(
314 // Details will be filled in by the selector.
315 'url' => '',
316 'icon' => '',
317 'text' => '',
318 ),
319 );
320
321 /**
322 * URL to mediawiki-announce subscription
323 */
324 protected $mediaWikiAnnounceUrl =
325 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
326
327 /**
328 * Supported language codes for Mailman
329 */
330 protected $mediaWikiAnnounceLanguages = array(
331 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
332 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
333 'sl', 'sr', 'sv', 'tr', 'uk'
334 );
335
336 /**
337 * UI interface for displaying a short message
338 * The parameters are like parameters to wfMessage().
339 * The messages will be in wikitext format, which will be converted to an
340 * output format such as HTML or text before being sent to the user.
341 * @param string $msg
342 */
343 abstract public function showMessage( $msg /*, ... */ );
344
345 /**
346 * Same as showMessage(), but for displaying errors
347 * @param string $msg
348 */
349 abstract public function showError( $msg /*, ... */ );
350
351 /**
352 * Show a message to the installing user by using a Status object
353 * @param Status $status
354 */
355 abstract public function showStatusMessage( Status $status );
356
357 /**
358 * Constructor, always call this from child classes.
359 */
360 public function __construct() {
361 global $wgMessagesDirs, $wgUser;
362
363 // Disable the i18n cache
364 Language::getLocalisationCache()->disableBackend();
365 // Disable LoadBalancer and wfGetDB etc.
366 LBFactory::disableBackend();
367
368 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
369 // SqlBagOStuff will then throw since we just disabled wfGetDB)
370 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
371 ObjectCache::clear();
372 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
373 // disable (problematic) object cache types explicitly, preserving all other (working) ones
374 // bug T113843
375 $GLOBALS['wgObjectCaches'] = array(
376 CACHE_NONE => $emptyCache,
377 CACHE_DB => $emptyCache,
378 CACHE_ANYTHING => $emptyCache,
379 CACHE_MEMCACHED => $emptyCache,
380 ) + $GLOBALS['wgObjectCaches'];
381
382 // Load the installer's i18n.
383 $wgMessagesDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
384
385 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
386 $wgUser = User::newFromId( 0 );
387
388 $this->settings = $this->internalDefaults;
389
390 foreach ( $this->defaultVarNames as $var ) {
391 $this->settings[$var] = $GLOBALS[$var];
392 }
393
394 $this->doEnvironmentPreps();
395
396 $this->compiledDBs = array();
397 foreach ( self::getDBTypes() as $type ) {
398 $installer = $this->getDBInstaller( $type );
399
400 if ( !$installer->isCompiled() ) {
401 continue;
402 }
403 $this->compiledDBs[] = $type;
404 }
405
406 $this->parserTitle = Title::newFromText( 'Installer' );
407 $this->parserOptions = new ParserOptions; // language will be wrong :(
408 $this->parserOptions->setEditSection( false );
409 }
410
411 /**
412 * Get a list of known DB types.
413 *
414 * @return array
415 */
416 public static function getDBTypes() {
417 return self::$dbTypes;
418 }
419
420 /**
421 * Do initial checks of the PHP environment. Set variables according to
422 * the observed environment.
423 *
424 * It's possible that this may be called under the CLI SAPI, not the SAPI
425 * that the wiki will primarily run under. In that case, the subclass should
426 * initialise variables such as wgScriptPath, before calling this function.
427 *
428 * Under the web subclass, it can already be assumed that PHP 5+ is in use
429 * and that sessions are working.
430 *
431 * @return Status
432 */
433 public function doEnvironmentChecks() {
434 // Php version has already been checked by entry scripts
435 // Show message here for information purposes
436 if ( wfIsHHVM() ) {
437 $this->showMessage( 'config-env-hhvm', HHVM_VERSION );
438 } else {
439 $this->showMessage( 'config-env-php', PHP_VERSION );
440 }
441
442 $good = true;
443 // Must go here because an old version of PCRE can prevent other checks from completing
444 list( $pcreVersion ) = explode( ' ', PCRE_VERSION, 2 );
445 if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
446 $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
447 $good = false;
448 } else {
449 foreach ( $this->envChecks as $check ) {
450 $status = $this->$check();
451 if ( $status === false ) {
452 $good = false;
453 }
454 }
455 }
456
457 $this->setVar( '_Environment', $good );
458
459 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
460 }
461
462 public function doEnvironmentPreps() {
463 foreach ( $this->envPreps as $prep ) {
464 $this->$prep();
465 }
466 }
467
468 /**
469 * Set a MW configuration variable, or internal installer configuration variable.
470 *
471 * @param string $name
472 * @param mixed $value
473 */
474 public function setVar( $name, $value ) {
475 $this->settings[$name] = $value;
476 }
477
478 /**
479 * Get an MW configuration variable, or internal installer configuration variable.
480 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
481 * Installer variables are typically prefixed by an underscore.
482 *
483 * @param string $name
484 * @param mixed $default
485 *
486 * @return mixed
487 */
488 public function getVar( $name, $default = null ) {
489 if ( !isset( $this->settings[$name] ) ) {
490 return $default;
491 } else {
492 return $this->settings[$name];
493 }
494 }
495
496 /**
497 * Get a list of DBs supported by current PHP setup
498 *
499 * @return array
500 */
501 public function getCompiledDBs() {
502 return $this->compiledDBs;
503 }
504
505 /**
506 * Get an instance of DatabaseInstaller for the specified DB type.
507 *
508 * @param mixed $type DB installer for which is needed, false to use default.
509 *
510 * @return DatabaseInstaller
511 */
512 public function getDBInstaller( $type = false ) {
513 if ( !$type ) {
514 $type = $this->getVar( 'wgDBtype' );
515 }
516
517 $type = strtolower( $type );
518
519 if ( !isset( $this->dbInstallers[$type] ) ) {
520 $class = ucfirst( $type ) . 'Installer';
521 $this->dbInstallers[$type] = new $class( $this );
522 }
523
524 return $this->dbInstallers[$type];
525 }
526
527 /**
528 * Determine if LocalSettings.php exists. If it does, return its variables.
529 *
530 * @return array
531 */
532 public static function getExistingLocalSettings() {
533 global $IP;
534
535 // You might be wondering why this is here. Well if you don't do this
536 // then some poorly-formed extensions try to call their own classes
537 // after immediately registering them. We really need to get extension
538 // registration out of the global scope and into a real format.
539 // @see https://phabricator.wikimedia.org/T69440
540 global $wgAutoloadClasses;
541 $wgAutoloadClasses = array();
542
543 // @codingStandardsIgnoreStart
544 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
545 // Define the required globals here, to ensure, the functions can do it work correctly.
546 global $wgExtensionDirectory, $wgStyleDirectory;
547 // @codingStandardsIgnoreEnd
548
549 MediaWiki\suppressWarnings();
550 $_lsExists = file_exists( "$IP/LocalSettings.php" );
551 MediaWiki\restoreWarnings();
552
553 if ( !$_lsExists ) {
554 return false;
555 }
556 unset( $_lsExists );
557
558 require "$IP/includes/DefaultSettings.php";
559 require "$IP/LocalSettings.php";
560
561 return get_defined_vars();
562 }
563
564 /**
565 * Get a fake password for sending back to the user in HTML.
566 * This is a security mechanism to avoid compromise of the password in the
567 * event of session ID compromise.
568 *
569 * @param string $realPassword
570 *
571 * @return string
572 */
573 public function getFakePassword( $realPassword ) {
574 return str_repeat( '*', strlen( $realPassword ) );
575 }
576
577 /**
578 * Set a variable which stores a password, except if the new value is a
579 * fake password in which case leave it as it is.
580 *
581 * @param string $name
582 * @param mixed $value
583 */
584 public function setPassword( $name, $value ) {
585 if ( !preg_match( '/^\*+$/', $value ) ) {
586 $this->setVar( $name, $value );
587 }
588 }
589
590 /**
591 * On POSIX systems return the primary group of the webserver we're running under.
592 * On other systems just returns null.
593 *
594 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
595 * webserver user before he can install.
596 *
597 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
598 *
599 * @return mixed
600 */
601 public static function maybeGetWebserverPrimaryGroup() {
602 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
603 # I don't know this, this isn't UNIX.
604 return null;
605 }
606
607 # posix_getegid() *not* getmygid() because we want the group of the webserver,
608 # not whoever owns the current script.
609 $gid = posix_getegid();
610 $getpwuid = posix_getpwuid( $gid );
611 $group = $getpwuid['name'];
612
613 return $group;
614 }
615
616 /**
617 * Convert wikitext $text to HTML.
618 *
619 * This is potentially error prone since many parser features require a complete
620 * installed MW database. The solution is to just not use those features when you
621 * write your messages. This appears to work well enough. Basic formatting and
622 * external links work just fine.
623 *
624 * But in case a translator decides to throw in a "#ifexist" or internal link or
625 * whatever, this function is guarded to catch the attempted DB access and to present
626 * some fallback text.
627 *
628 * @param string $text
629 * @param bool $lineStart
630 * @return string
631 */
632 public function parse( $text, $lineStart = false ) {
633 global $wgParser;
634
635 try {
636 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
637 $html = $out->getText();
638 } catch ( DBAccessError $e ) {
639 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
640
641 if ( !empty( $this->debug ) ) {
642 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
643 }
644 }
645
646 return $html;
647 }
648
649 /**
650 * @return ParserOptions
651 */
652 public function getParserOptions() {
653 return $this->parserOptions;
654 }
655
656 public function disableLinkPopups() {
657 $this->parserOptions->setExternalLinkTarget( false );
658 }
659
660 public function restoreLinkPopups() {
661 global $wgExternalLinkTarget;
662 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
663 }
664
665 /**
666 * Install step which adds a row to the site_stats table with appropriate
667 * initial values.
668 *
669 * @param DatabaseInstaller $installer
670 *
671 * @return Status
672 */
673 public function populateSiteStats( DatabaseInstaller $installer ) {
674 $status = $installer->getConnection();
675 if ( !$status->isOK() ) {
676 return $status;
677 }
678 $status->value->insert(
679 'site_stats',
680 array(
681 'ss_row_id' => 1,
682 'ss_total_edits' => 0,
683 'ss_good_articles' => 0,
684 'ss_total_pages' => 0,
685 'ss_users' => 0,
686 'ss_images' => 0
687 ),
688 __METHOD__, 'IGNORE'
689 );
690
691 return Status::newGood();
692 }
693
694 /**
695 * Environment check for DB types.
696 * @return bool
697 */
698 protected function envCheckDB() {
699 global $wgLang;
700
701 $allNames = array();
702
703 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
704 // config-type-sqlite
705 foreach ( self::getDBTypes() as $name ) {
706 $allNames[] = wfMessage( "config-type-$name" )->text();
707 }
708
709 $databases = $this->getCompiledDBs();
710
711 $databases = array_flip( $databases );
712 foreach ( array_keys( $databases ) as $db ) {
713 $installer = $this->getDBInstaller( $db );
714 $status = $installer->checkPrerequisites();
715 if ( !$status->isGood() ) {
716 $this->showStatusMessage( $status );
717 }
718 if ( !$status->isOK() ) {
719 unset( $databases[$db] );
720 }
721 }
722 $databases = array_flip( $databases );
723 if ( !$databases ) {
724 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
725
726 // @todo FIXME: This only works for the web installer!
727 return false;
728 }
729
730 return true;
731 }
732
733 /**
734 * Environment check for register_globals.
735 * Prevent installation if enabled
736 * @return bool
737 */
738 protected function envCheckRegisterGlobals() {
739 if ( wfIniGetBool( 'register_globals' ) ) {
740 $this->showMessage( 'config-register-globals-error' );
741 return false;
742 }
743
744 return true;
745 }
746
747 /**
748 * Some versions of libxml+PHP break < and > encoding horribly
749 * @return bool
750 */
751 protected function envCheckBrokenXML() {
752 $test = new PhpXmlBugTester();
753 if ( !$test->ok ) {
754 $this->showError( 'config-brokenlibxml' );
755
756 return false;
757 }
758
759 return true;
760 }
761
762 /**
763 * Environment check for magic_quotes_(gpc|runtime|sybase).
764 * @return bool
765 */
766 protected function envCheckMagicQuotes() {
767 $status = true;
768 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
769 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
770 $this->showError( "config-magic-quotes-$magicJunk" );
771 $status = false;
772 }
773 }
774
775 return $status;
776 }
777
778 /**
779 * Environment check for mbstring.func_overload.
780 * @return bool
781 */
782 protected function envCheckMbstring() {
783 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
784 $this->showError( 'config-mbstring' );
785
786 return false;
787 }
788
789 return true;
790 }
791
792 /**
793 * Environment check for safe_mode.
794 * @return bool
795 */
796 protected function envCheckSafeMode() {
797 if ( wfIniGetBool( 'safe_mode' ) ) {
798 $this->setVar( '_SafeMode', true );
799 $this->showMessage( 'config-safe-mode' );
800 }
801
802 return true;
803 }
804
805 /**
806 * Environment check for the XML module.
807 * @return bool
808 */
809 protected function envCheckXML() {
810 if ( !function_exists( "utf8_encode" ) ) {
811 $this->showError( 'config-xml-bad' );
812
813 return false;
814 }
815
816 return true;
817 }
818
819 /**
820 * Environment check for the PCRE module.
821 *
822 * @note If this check were to fail, the parser would
823 * probably throw an exception before the result
824 * of this check is shown to the user.
825 * @return bool
826 */
827 protected function envCheckPCRE() {
828 MediaWiki\suppressWarnings();
829 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
830 // Need to check for \p support too, as PCRE can be compiled
831 // with utf8 support, but not unicode property support.
832 // check that \p{Zs} (space separators) matches
833 // U+3000 (Ideographic space)
834 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
835 MediaWiki\restoreWarnings();
836 if ( $regexd != '--' || $regexprop != '--' ) {
837 $this->showError( 'config-pcre-no-utf8' );
838
839 return false;
840 }
841
842 return true;
843 }
844
845 /**
846 * Environment check for available memory.
847 * @return bool
848 */
849 protected function envCheckMemory() {
850 $limit = ini_get( 'memory_limit' );
851
852 if ( !$limit || $limit == -1 ) {
853 return true;
854 }
855
856 $n = wfShorthandToInteger( $limit );
857
858 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
859 $newLimit = "{$this->minMemorySize}M";
860
861 if ( ini_set( "memory_limit", $newLimit ) === false ) {
862 $this->showMessage( 'config-memory-bad', $limit );
863 } else {
864 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
865 $this->setVar( '_RaiseMemory', true );
866 }
867 }
868
869 return true;
870 }
871
872 /**
873 * Environment check for compiled object cache types.
874 */
875 protected function envCheckCache() {
876 $caches = array();
877 foreach ( $this->objectCaches as $name => $function ) {
878 if ( function_exists( $function ) ) {
879 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
880 continue;
881 }
882 $caches[$name] = true;
883 }
884 }
885
886 if ( !$caches ) {
887 $key = 'config-no-cache';
888 // PHP >=5.5 is called APCu, earlier versions use APC (T61998).
889 if ( !wfIsHHVM() && version_compare( PHP_VERSION, '5.5', '>=' ) ) {
890 // config-no-cache-apcu
891 $key .= '-apcu';
892 }
893 $this->showMessage( $key );
894 }
895
896 $this->setVar( '_Caches', $caches );
897 }
898
899 /**
900 * Scare user to death if they have mod_security or mod_security2
901 * @return bool
902 */
903 protected function envCheckModSecurity() {
904 if ( self::apacheModulePresent( 'mod_security' )
905 || self::apacheModulePresent( 'mod_security2' ) ) {
906 $this->showMessage( 'config-mod-security' );
907 }
908
909 return true;
910 }
911
912 /**
913 * Search for GNU diff3.
914 * @return bool
915 */
916 protected function envCheckDiff3() {
917 $names = array( "gdiff3", "diff3", "diff3.exe" );
918 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
919
920 $diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
921
922 if ( $diff3 ) {
923 $this->setVar( 'wgDiff3', $diff3 );
924 } else {
925 $this->setVar( 'wgDiff3', false );
926 $this->showMessage( 'config-diff3-bad' );
927 }
928
929 return true;
930 }
931
932 /**
933 * Environment check for ImageMagick and GD.
934 * @return bool
935 */
936 protected function envCheckGraphics() {
937 $names = array( wfIsWindows() ? 'convert.exe' : 'convert' );
938 $versionInfo = array( '$1 -version', 'ImageMagick' );
939 $convert = self::locateExecutableInDefaultPaths( $names, $versionInfo );
940
941 $this->setVar( 'wgImageMagickConvertCommand', '' );
942 if ( $convert ) {
943 $this->setVar( 'wgImageMagickConvertCommand', $convert );
944 $this->showMessage( 'config-imagemagick', $convert );
945
946 return true;
947 } elseif ( function_exists( 'imagejpeg' ) ) {
948 $this->showMessage( 'config-gd' );
949 } else {
950 $this->showMessage( 'config-no-scaling' );
951 }
952
953 return true;
954 }
955
956 /**
957 * Search for git.
958 *
959 * @since 1.22
960 * @return bool
961 */
962 protected function envCheckGit() {
963 $names = array( wfIsWindows() ? 'git.exe' : 'git' );
964 $versionInfo = array( '$1 --version', 'git version' );
965
966 $git = self::locateExecutableInDefaultPaths( $names, $versionInfo );
967
968 if ( $git ) {
969 $this->setVar( 'wgGitBin', $git );
970 $this->showMessage( 'config-git', $git );
971 } else {
972 $this->setVar( 'wgGitBin', false );
973 $this->showMessage( 'config-git-bad' );
974 }
975
976 return true;
977 }
978
979 /**
980 * Environment check to inform user which server we've assumed.
981 *
982 * @return bool
983 */
984 protected function envCheckServer() {
985 $server = $this->envGetDefaultServer();
986 if ( $server !== null ) {
987 $this->showMessage( 'config-using-server', $server );
988 }
989 return true;
990 }
991
992 /**
993 * Environment check to inform user which paths we've assumed.
994 *
995 * @return bool
996 */
997 protected function envCheckPath() {
998 $this->showMessage(
999 'config-using-uri',
1000 $this->getVar( 'wgServer' ),
1001 $this->getVar( 'wgScriptPath' )
1002 );
1003 return true;
1004 }
1005
1006 /**
1007 * Environment check for preferred locale in shell
1008 * @return bool
1009 */
1010 protected function envCheckShellLocale() {
1011 $os = php_uname( 's' );
1012 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1013
1014 if ( !in_array( $os, $supported ) ) {
1015 return true;
1016 }
1017
1018 # Get a list of available locales.
1019 $ret = false;
1020 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1021
1022 if ( $ret ) {
1023 return true;
1024 }
1025
1026 $lines = array_map( 'trim', explode( "\n", $lines ) );
1027 $candidatesByLocale = array();
1028 $candidatesByLang = array();
1029
1030 foreach ( $lines as $line ) {
1031 if ( $line === '' ) {
1032 continue;
1033 }
1034
1035 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1036 continue;
1037 }
1038
1039 list( , $lang, , , ) = $m;
1040
1041 $candidatesByLocale[$m[0]] = $m;
1042 $candidatesByLang[$lang][] = $m;
1043 }
1044
1045 # Try the current value of LANG.
1046 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1047 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1048
1049 return true;
1050 }
1051
1052 # Try the most common ones.
1053 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1054 foreach ( $commonLocales as $commonLocale ) {
1055 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1056 $this->setVar( 'wgShellLocale', $commonLocale );
1057
1058 return true;
1059 }
1060 }
1061
1062 # Is there an available locale in the Wiki's language?
1063 $wikiLang = $this->getVar( 'wgLanguageCode' );
1064
1065 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1066 $m = reset( $candidatesByLang[$wikiLang] );
1067 $this->setVar( 'wgShellLocale', $m[0] );
1068
1069 return true;
1070 }
1071
1072 # Are there any at all?
1073 if ( count( $candidatesByLocale ) ) {
1074 $m = reset( $candidatesByLocale );
1075 $this->setVar( 'wgShellLocale', $m[0] );
1076
1077 return true;
1078 }
1079
1080 # Give up.
1081 return true;
1082 }
1083
1084 /**
1085 * Environment check for the permissions of the uploads directory
1086 * @return bool
1087 */
1088 protected function envCheckUploadsDirectory() {
1089 global $IP;
1090
1091 $dir = $IP . '/images/';
1092 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1093 $safe = !$this->dirIsExecutable( $dir, $url );
1094
1095 if ( !$safe ) {
1096 $this->showMessage( 'config-uploads-not-safe', $dir );
1097 }
1098
1099 return true;
1100 }
1101
1102 /**
1103 * Checks if suhosin.get.max_value_length is set, and if so generate
1104 * a warning because it decreases ResourceLoader performance.
1105 * @return bool
1106 */
1107 protected function envCheckSuhosinMaxValueLength() {
1108 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1109 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1110 // Only warn if the value is below the sane 1024
1111 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1112 }
1113
1114 return true;
1115 }
1116
1117 /**
1118 * Convert a hex string representing a Unicode code point to that code point.
1119 * @param string $c
1120 * @return string
1121 */
1122 protected function unicodeChar( $c ) {
1123 $c = hexdec( $c );
1124 if ( $c <= 0x7F ) {
1125 return chr( $c );
1126 } elseif ( $c <= 0x7FF ) {
1127 return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1128 } elseif ( $c <= 0xFFFF ) {
1129 return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F ) .
1130 chr( 0x80 | $c & 0x3F );
1131 } elseif ( $c <= 0x10FFFF ) {
1132 return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F ) .
1133 chr( 0x80 | $c >> 6 & 0x3F ) .
1134 chr( 0x80 | $c & 0x3F );
1135 } else {
1136 return false;
1137 }
1138 }
1139
1140 /**
1141 * Check the libicu version
1142 */
1143 protected function envCheckLibicu() {
1144 /**
1145 * This needs to be updated something that the latest libicu
1146 * will properly normalize. This normalization was found at
1147 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1148 * Note that we use the hex representation to create the code
1149 * points in order to avoid any Unicode-destroying during transit.
1150 */
1151 $not_normal_c = $this->unicodeChar( "FA6C" );
1152 $normal_c = $this->unicodeChar( "242EE" );
1153
1154 $useNormalizer = 'php';
1155 $needsUpdate = false;
1156
1157 if ( function_exists( 'normalizer_normalize' ) ) {
1158 $useNormalizer = 'intl';
1159 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1160 if ( $intl !== $normal_c ) {
1161 $needsUpdate = true;
1162 }
1163 }
1164
1165 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1166 if ( $useNormalizer === 'php' ) {
1167 $this->showMessage( 'config-unicode-pure-php-warning' );
1168 } else {
1169 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1170 if ( $needsUpdate ) {
1171 $this->showMessage( 'config-unicode-update-warning' );
1172 }
1173 }
1174 }
1175
1176 /**
1177 * @return bool
1178 */
1179 protected function envCheckCtype() {
1180 if ( !function_exists( 'ctype_digit' ) ) {
1181 $this->showError( 'config-ctype' );
1182
1183 return false;
1184 }
1185
1186 return true;
1187 }
1188
1189 /**
1190 * @return bool
1191 */
1192 protected function envCheckIconv() {
1193 if ( !function_exists( 'iconv' ) ) {
1194 $this->showError( 'config-iconv' );
1195
1196 return false;
1197 }
1198
1199 return true;
1200 }
1201
1202 /**
1203 * @return bool
1204 */
1205 protected function envCheckJSON() {
1206 if ( !function_exists( 'json_decode' ) ) {
1207 $this->showError( 'config-json' );
1208
1209 return false;
1210 }
1211
1212 return true;
1213 }
1214
1215 /**
1216 * Environment prep for the server hostname.
1217 */
1218 protected function envPrepServer() {
1219 $server = $this->envGetDefaultServer();
1220 if ( $server !== null ) {
1221 $this->setVar( 'wgServer', $server );
1222 }
1223 }
1224
1225 /**
1226 * Helper function to be called from envPrepServer()
1227 * @return string
1228 */
1229 abstract protected function envGetDefaultServer();
1230
1231 /**
1232 * Environment prep for setting $IP and $wgScriptPath.
1233 */
1234 protected function envPrepPath() {
1235 global $IP;
1236 $IP = dirname( dirname( __DIR__ ) );
1237 $this->setVar( 'IP', $IP );
1238 }
1239
1240 /**
1241 * Get an array of likely places we can find executables. Check a bunch
1242 * of known Unix-like defaults, as well as the PATH environment variable
1243 * (which should maybe make it work for Windows?)
1244 *
1245 * @return array
1246 */
1247 protected static function getPossibleBinPaths() {
1248 return array_merge(
1249 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1250 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1251 explode( PATH_SEPARATOR, getenv( 'PATH' ) )
1252 );
1253 }
1254
1255 /**
1256 * Search a path for any of the given executable names. Returns the
1257 * executable name if found. Also checks the version string returned
1258 * by each executable.
1259 *
1260 * Used only by environment checks.
1261 *
1262 * @param string $path Path to search
1263 * @param array $names Array of executable names
1264 * @param array|bool $versionInfo False or array with two members:
1265 * 0 => Command to run for version check, with $1 for the full executable name
1266 * 1 => String to compare the output with
1267 *
1268 * If $versionInfo is not false, only executables with a version
1269 * matching $versionInfo[1] will be returned.
1270 * @return bool|string
1271 */
1272 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1273 if ( !is_array( $names ) ) {
1274 $names = array( $names );
1275 }
1276
1277 foreach ( $names as $name ) {
1278 $command = $path . DIRECTORY_SEPARATOR . $name;
1279
1280 MediaWiki\suppressWarnings();
1281 $file_exists = file_exists( $command );
1282 MediaWiki\restoreWarnings();
1283
1284 if ( $file_exists ) {
1285 if ( !$versionInfo ) {
1286 return $command;
1287 }
1288
1289 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1290 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1291 return $command;
1292 }
1293 }
1294 }
1295
1296 return false;
1297 }
1298
1299 /**
1300 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1301 * @see locateExecutable()
1302 * @param array $names Array of possible names.
1303 * @param array|bool $versionInfo Default: false or array with two members:
1304 * 0 => Command to run for version check, with $1 for the full executable name
1305 * 1 => String to compare the output with
1306 *
1307 * If $versionInfo is not false, only executables with a version
1308 * matching $versionInfo[1] will be returned.
1309 * @return bool|string
1310 */
1311 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1312 foreach ( self::getPossibleBinPaths() as $path ) {
1313 $exe = self::locateExecutable( $path, $names, $versionInfo );
1314 if ( $exe !== false ) {
1315 return $exe;
1316 }
1317 }
1318
1319 return false;
1320 }
1321
1322 /**
1323 * Checks if scripts located in the given directory can be executed via the given URL.
1324 *
1325 * Used only by environment checks.
1326 * @param string $dir
1327 * @param string $url
1328 * @return bool|int|string
1329 */
1330 public function dirIsExecutable( $dir, $url ) {
1331 $scriptTypes = array(
1332 'php' => array(
1333 "<?php echo 'ex' . 'ec';",
1334 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1335 ),
1336 );
1337
1338 // it would be good to check other popular languages here, but it'll be slow.
1339
1340 MediaWiki\suppressWarnings();
1341
1342 foreach ( $scriptTypes as $ext => $contents ) {
1343 foreach ( $contents as $source ) {
1344 $file = 'exectest.' . $ext;
1345
1346 if ( !file_put_contents( $dir . $file, $source ) ) {
1347 break;
1348 }
1349
1350 try {
1351 $text = Http::get( $url . $file, array( 'timeout' => 3 ), __METHOD__ );
1352 } catch ( Exception $e ) {
1353 // Http::get throws with allow_url_fopen = false and no curl extension.
1354 $text = null;
1355 }
1356 unlink( $dir . $file );
1357
1358 if ( $text == 'exec' ) {
1359 MediaWiki\restoreWarnings();
1360
1361 return $ext;
1362 }
1363 }
1364 }
1365
1366 MediaWiki\restoreWarnings();
1367
1368 return false;
1369 }
1370
1371 /**
1372 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1373 *
1374 * @param string $moduleName Name of module to check.
1375 * @return bool
1376 */
1377 public static function apacheModulePresent( $moduleName ) {
1378 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1379 return true;
1380 }
1381 // try it the hard way
1382 ob_start();
1383 phpinfo( INFO_MODULES );
1384 $info = ob_get_clean();
1385
1386 return strpos( $info, $moduleName ) !== false;
1387 }
1388
1389 /**
1390 * ParserOptions are constructed before we determined the language, so fix it
1391 *
1392 * @param Language $lang
1393 */
1394 public function setParserLanguage( $lang ) {
1395 $this->parserOptions->setTargetLanguage( $lang );
1396 $this->parserOptions->setUserLang( $lang );
1397 }
1398
1399 /**
1400 * Overridden by WebInstaller to provide lastPage parameters.
1401 * @param string $page
1402 * @return string
1403 */
1404 protected function getDocUrl( $page ) {
1405 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1406 }
1407
1408 /**
1409 * Finds extensions that follow the format /$directory/Name/Name.php,
1410 * and returns an array containing the value for 'Name' for each found extension.
1411 *
1412 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1413 *
1414 * @param string $directory Directory to search in
1415 * @return array
1416 */
1417 public function findExtensions( $directory = 'extensions' ) {
1418 if ( $this->getVar( 'IP' ) === null ) {
1419 return array();
1420 }
1421
1422 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1423 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1424 return array();
1425 }
1426
1427 // extensions -> extension.json, skins -> skin.json
1428 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1429
1430 $dh = opendir( $extDir );
1431 $exts = array();
1432 while ( ( $file = readdir( $dh ) ) !== false ) {
1433 if ( !is_dir( "$extDir/$file" ) ) {
1434 continue;
1435 }
1436 if ( file_exists( "$extDir/$file/$jsonFile" ) || file_exists( "$extDir/$file/$file.php" ) ) {
1437 $exts[] = $file;
1438 }
1439 }
1440 closedir( $dh );
1441 natcasesort( $exts );
1442
1443 return $exts;
1444 }
1445
1446 /**
1447 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1448 * but will fall back to another if the default skin is missing and some other one is present
1449 * instead.
1450 *
1451 * @param string[] $skinNames Names of installed skins.
1452 * @return string
1453 */
1454 public function getDefaultSkin( array $skinNames ) {
1455 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1456 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1457 return $defaultSkin;
1458 } else {
1459 return $skinNames[0];
1460 }
1461 }
1462
1463 /**
1464 * Installs the auto-detected extensions.
1465 *
1466 * @return Status
1467 */
1468 protected function includeExtensions() {
1469 global $IP;
1470 $exts = $this->getVar( '_Extensions' );
1471 $IP = $this->getVar( 'IP' );
1472
1473 /**
1474 * We need to include DefaultSettings before including extensions to avoid
1475 * warnings about unset variables. However, the only thing we really
1476 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1477 * if the extension has hidden hook registration in $wgExtensionFunctions,
1478 * but we're not opening that can of worms
1479 * @see https://phabricator.wikimedia.org/T28857
1480 */
1481 global $wgAutoloadClasses;
1482 $wgAutoloadClasses = array();
1483 $queue = array();
1484
1485 require "$IP/includes/DefaultSettings.php";
1486
1487 foreach ( $exts as $e ) {
1488 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1489 $queue["$IP/extensions/$e/extension.json"] = 1;
1490 } else {
1491 require_once "$IP/extensions/$e/$e.php";
1492 }
1493 }
1494
1495 $registry = new ExtensionRegistry();
1496 $data = $registry->readFromQueue( $queue );
1497 $wgAutoloadClasses += $data['autoload'];
1498
1499 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1500 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1501
1502 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1503 $hooksWeWant = array_merge_recursive(
1504 $hooksWeWant,
1505 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1506 );
1507 }
1508 // Unset everyone else's hooks. Lord knows what someone might be doing
1509 // in ParserFirstCallInit (see bug 27171)
1510 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1511
1512 return Status::newGood();
1513 }
1514
1515 /**
1516 * Get an array of install steps. Should always be in the format of
1517 * array(
1518 * 'name' => 'someuniquename',
1519 * 'callback' => array( $obj, 'method' ),
1520 * )
1521 * There must be a config-install-$name message defined per step, which will
1522 * be shown on install.
1523 *
1524 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1525 * @return array
1526 */
1527 protected function getInstallSteps( DatabaseInstaller $installer ) {
1528 $coreInstallSteps = array(
1529 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1530 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1531 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1532 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1533 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1534 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1535 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1536 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1537 );
1538
1539 // Build the array of install steps starting from the core install list,
1540 // then adding any callbacks that wanted to attach after a given step
1541 foreach ( $coreInstallSteps as $step ) {
1542 $this->installSteps[] = $step;
1543 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1544 $this->installSteps = array_merge(
1545 $this->installSteps,
1546 $this->extraInstallSteps[$step['name']]
1547 );
1548 }
1549 }
1550
1551 // Prepend any steps that want to be at the beginning
1552 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1553 $this->installSteps = array_merge(
1554 $this->extraInstallSteps['BEGINNING'],
1555 $this->installSteps
1556 );
1557 }
1558
1559 // Extensions should always go first, chance to tie into hooks and such
1560 if ( count( $this->getVar( '_Extensions' ) ) ) {
1561 array_unshift( $this->installSteps,
1562 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1563 );
1564 $this->installSteps[] = array(
1565 'name' => 'extension-tables',
1566 'callback' => array( $installer, 'createExtensionTables' )
1567 );
1568 }
1569
1570 return $this->installSteps;
1571 }
1572
1573 /**
1574 * Actually perform the installation.
1575 *
1576 * @param callable $startCB A callback array for the beginning of each step
1577 * @param callable $endCB A callback array for the end of each step
1578 *
1579 * @return array Array of Status objects
1580 */
1581 public function performInstallation( $startCB, $endCB ) {
1582 $installResults = array();
1583 $installer = $this->getDBInstaller();
1584 $installer->preInstall();
1585 $steps = $this->getInstallSteps( $installer );
1586 foreach ( $steps as $stepObj ) {
1587 $name = $stepObj['name'];
1588 call_user_func_array( $startCB, array( $name ) );
1589
1590 // Perform the callback step
1591 $status = call_user_func( $stepObj['callback'], $installer );
1592
1593 // Output and save the results
1594 call_user_func( $endCB, $name, $status );
1595 $installResults[$name] = $status;
1596
1597 // If we've hit some sort of fatal, we need to bail.
1598 // Callback already had a chance to do output above.
1599 if ( !$status->isOk() ) {
1600 break;
1601 }
1602 }
1603 if ( $status->isOk() ) {
1604 $this->setVar( '_InstallDone', true );
1605 }
1606
1607 return $installResults;
1608 }
1609
1610 /**
1611 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1612 *
1613 * @return Status
1614 */
1615 public function generateKeys() {
1616 $keys = array( 'wgSecretKey' => 64 );
1617 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1618 $keys['wgUpgradeKey'] = 16;
1619 }
1620
1621 return $this->doGenerateKeys( $keys );
1622 }
1623
1624 /**
1625 * Generate a secret value for variables using our CryptRand generator.
1626 * Produce a warning if the random source was insecure.
1627 *
1628 * @param array $keys
1629 * @return Status
1630 */
1631 protected function doGenerateKeys( $keys ) {
1632 $status = Status::newGood();
1633
1634 $strong = true;
1635 foreach ( $keys as $name => $length ) {
1636 $secretKey = MWCryptRand::generateHex( $length, true );
1637 if ( !MWCryptRand::wasStrong() ) {
1638 $strong = false;
1639 }
1640
1641 $this->setVar( $name, $secretKey );
1642 }
1643
1644 if ( !$strong ) {
1645 $names = array_keys( $keys );
1646 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1647 global $wgLang;
1648 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1649 }
1650
1651 return $status;
1652 }
1653
1654 /**
1655 * Create the first user account, grant it sysop and bureaucrat rights
1656 *
1657 * @return Status
1658 */
1659 protected function createSysop() {
1660 $name = $this->getVar( '_AdminName' );
1661 $user = User::newFromName( $name );
1662
1663 if ( !$user ) {
1664 // We should've validated this earlier anyway!
1665 return Status::newFatal( 'config-admin-error-user', $name );
1666 }
1667
1668 if ( $user->idForName() == 0 ) {
1669 $user->addToDatabase();
1670
1671 try {
1672 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1673 } catch ( PasswordError $pwe ) {
1674 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1675 }
1676
1677 $user->addGroup( 'sysop' );
1678 $user->addGroup( 'bureaucrat' );
1679 if ( $this->getVar( '_AdminEmail' ) ) {
1680 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1681 }
1682 $user->saveSettings();
1683
1684 // Update user count
1685 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1686 $ssUpdate->doUpdate();
1687 }
1688 $status = Status::newGood();
1689
1690 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1691 $this->subscribeToMediaWikiAnnounce( $status );
1692 }
1693
1694 return $status;
1695 }
1696
1697 /**
1698 * @param Status $s
1699 */
1700 private function subscribeToMediaWikiAnnounce( Status $s ) {
1701 $params = array(
1702 'email' => $this->getVar( '_AdminEmail' ),
1703 'language' => 'en',
1704 'digest' => 0
1705 );
1706
1707 // Mailman doesn't support as many languages as we do, so check to make
1708 // sure their selected language is available
1709 $myLang = $this->getVar( '_UserLang' );
1710 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1711 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1712 $params['language'] = $myLang;
1713 }
1714
1715 if ( MWHttpRequest::canMakeRequests() ) {
1716 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1717 array( 'method' => 'POST', 'postData' => $params ), __METHOD__ )->execute();
1718 if ( !$res->isOK() ) {
1719 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1720 }
1721 } else {
1722 $s->warning( 'config-install-subscribe-notpossible' );
1723 }
1724 }
1725
1726 /**
1727 * Insert Main Page with default content.
1728 *
1729 * @param DatabaseInstaller $installer
1730 * @return Status
1731 */
1732 protected function createMainpage( DatabaseInstaller $installer ) {
1733 $status = Status::newGood();
1734 try {
1735 $page = WikiPage::factory( Title::newMainPage() );
1736 $content = new WikitextContent(
1737 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1738 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1739 );
1740
1741 $page->doEditContent( $content,
1742 '',
1743 EDIT_NEW,
1744 false,
1745 User::newFromName( 'MediaWiki default' )
1746 );
1747 } catch ( Exception $e ) {
1748 // using raw, because $wgShowExceptionDetails can not be set yet
1749 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1750 }
1751
1752 return $status;
1753 }
1754
1755 /**
1756 * Override the necessary bits of the config to run an installation.
1757 */
1758 public static function overrideConfig() {
1759 define( 'MW_NO_SESSION', 1 );
1760
1761 // Don't access the database
1762 $GLOBALS['wgUseDatabaseMessages'] = false;
1763 // Don't cache langconv tables
1764 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1765 // Debug-friendly
1766 $GLOBALS['wgShowExceptionDetails'] = true;
1767 // Don't break forms
1768 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1769
1770 // Extended debugging
1771 $GLOBALS['wgShowSQLErrors'] = true;
1772 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1773
1774 // Allow multiple ob_flush() calls
1775 $GLOBALS['wgDisableOutputCompression'] = true;
1776
1777 // Use a sensible cookie prefix (not my_wiki)
1778 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1779
1780 // Some of the environment checks make shell requests, remove limits
1781 $GLOBALS['wgMaxShellMemory'] = 0;
1782 }
1783
1784 /**
1785 * Add an installation step following the given step.
1786 *
1787 * @param callable $callback A valid installation callback array, in this form:
1788 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1789 * @param string $findStep The step to find. Omit to put the step at the beginning
1790 */
1791 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1792 $this->extraInstallSteps[$findStep][] = $callback;
1793 }
1794
1795 /**
1796 * Disable the time limit for execution.
1797 * Some long-running pages (Install, Upgrade) will want to do this
1798 */
1799 protected function disableTimeLimit() {
1800 MediaWiki\suppressWarnings();
1801 set_time_limit( 0 );
1802 MediaWiki\restoreWarnings();
1803 }
1804 }