PageRenderTime 29ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/installer/Installer.php

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