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