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