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