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