Installer.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  1. <?php
  2. /**
  3. * Base code for MediaWiki installer.
  4. *
  5. * DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
  6. * See mw-config/overrides/README for details.
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. * http://www.gnu.org/copyleft/gpl.html
  22. *
  23. * @file
  24. * @ingroup Deployment
  25. */
  26. use MediaWiki\Interwiki\NullInterwikiLookup;
  27. use MediaWiki\MediaWikiServices;
  28. use MediaWiki\Shell\Shell;
  29. /**
  30. * This documentation group collects source code files with deployment functionality.
  31. *
  32. * @defgroup Deployment Deployment
  33. */
  34. /**
  35. * Base installer class.
  36. *
  37. * This class provides the base for installation and update functionality
  38. * for both MediaWiki core and extensions.
  39. *
  40. * @ingroup Deployment
  41. * @since 1.17
  42. */
  43. abstract class Installer {
  44. /**
  45. * The oldest version of PCRE we can support.
  46. *
  47. * Defining this is necessary because PHP may be linked with a system version
  48. * of PCRE, which may be older than that bundled with the minimum PHP version.
  49. */
  50. const MINIMUM_PCRE_VERSION = '7.2';
  51. /**
  52. * @var array
  53. */
  54. protected $settings;
  55. /**
  56. * List of detected DBs, access using getCompiledDBs().
  57. *
  58. * @var array
  59. */
  60. protected $compiledDBs;
  61. /**
  62. * Cached DB installer instances, access using getDBInstaller().
  63. *
  64. * @var array
  65. */
  66. protected $dbInstallers = [];
  67. /**
  68. * Minimum memory size in MB.
  69. *
  70. * @var int
  71. */
  72. protected $minMemorySize = 50;
  73. /**
  74. * Cached Title, used by parse().
  75. *
  76. * @var Title
  77. */
  78. protected $parserTitle;
  79. /**
  80. * Cached ParserOptions, used by parse().
  81. *
  82. * @var ParserOptions
  83. */
  84. protected $parserOptions;
  85. /**
  86. * Known database types. These correspond to the class names <type>Installer,
  87. * and are also MediaWiki database types valid for $wgDBtype.
  88. *
  89. * To add a new type, create a <type>Installer class and a Database<type>
  90. * class, and add a config-type-<type> message to MessagesEn.php.
  91. *
  92. * @var array
  93. */
  94. protected static $dbTypes = [
  95. 'mysql',
  96. 'postgres',
  97. 'sqlite',
  98. ];
  99. /**
  100. * A list of environment check methods called by doEnvironmentChecks().
  101. * These may output warnings using showMessage(), and/or abort the
  102. * installation process by returning false.
  103. *
  104. * For the WebInstaller these are only called on the Welcome page,
  105. * if these methods have side-effects that should affect later page loads
  106. * (as well as the generated stylesheet), use envPreps instead.
  107. *
  108. * @var array
  109. */
  110. protected $envChecks = [
  111. 'envCheckDB',
  112. 'envCheckBrokenXML',
  113. 'envCheckPCRE',
  114. 'envCheckMemory',
  115. 'envCheckCache',
  116. 'envCheckModSecurity',
  117. 'envCheckDiff3',
  118. 'envCheckGraphics',
  119. 'envCheckGit',
  120. 'envCheckServer',
  121. 'envCheckPath',
  122. 'envCheckShellLocale',
  123. 'envCheckUploadsDirectory',
  124. 'envCheckLibicu',
  125. 'envCheckSuhosinMaxValueLength',
  126. 'envCheck64Bit',
  127. ];
  128. /**
  129. * A list of environment preparation methods called by doEnvironmentPreps().
  130. *
  131. * @var array
  132. */
  133. protected $envPreps = [
  134. 'envPrepServer',
  135. 'envPrepPath',
  136. ];
  137. /**
  138. * MediaWiki configuration globals that will eventually be passed through
  139. * to LocalSettings.php. The names only are given here, the defaults
  140. * typically come from DefaultSettings.php.
  141. *
  142. * @var array
  143. */
  144. protected $defaultVarNames = [
  145. 'wgSitename',
  146. 'wgPasswordSender',
  147. 'wgLanguageCode',
  148. 'wgRightsIcon',
  149. 'wgRightsText',
  150. 'wgRightsUrl',
  151. 'wgEnableEmail',
  152. 'wgEnableUserEmail',
  153. 'wgEnotifUserTalk',
  154. 'wgEnotifWatchlist',
  155. 'wgEmailAuthentication',
  156. 'wgDBname',
  157. 'wgDBtype',
  158. 'wgDiff3',
  159. 'wgImageMagickConvertCommand',
  160. 'wgGitBin',
  161. 'IP',
  162. 'wgScriptPath',
  163. 'wgMetaNamespace',
  164. 'wgDeletedDirectory',
  165. 'wgEnableUploads',
  166. 'wgShellLocale',
  167. 'wgSecretKey',
  168. 'wgUseInstantCommons',
  169. 'wgUpgradeKey',
  170. 'wgDefaultSkin',
  171. 'wgPingback',
  172. ];
  173. /**
  174. * Variables that are stored alongside globals, and are used for any
  175. * configuration of the installation process aside from the MediaWiki
  176. * configuration. Map of names to defaults.
  177. *
  178. * @var array
  179. */
  180. protected $internalDefaults = [
  181. '_UserLang' => 'en',
  182. '_Environment' => false,
  183. '_RaiseMemory' => false,
  184. '_UpgradeDone' => false,
  185. '_InstallDone' => false,
  186. '_Caches' => [],
  187. '_InstallPassword' => '',
  188. '_SameAccount' => true,
  189. '_CreateDBAccount' => false,
  190. '_NamespaceType' => 'site-name',
  191. '_AdminName' => '', // will be set later, when the user selects language
  192. '_AdminPassword' => '',
  193. '_AdminPasswordConfirm' => '',
  194. '_AdminEmail' => '',
  195. '_Subscribe' => false,
  196. '_SkipOptional' => 'continue',
  197. '_RightsProfile' => 'wiki',
  198. '_LicenseCode' => 'none',
  199. '_CCDone' => false,
  200. '_Extensions' => [],
  201. '_Skins' => [],
  202. '_MemCachedServers' => '',
  203. '_UpgradeKeySupplied' => false,
  204. '_ExistingDBSettings' => false,
  205. // $wgLogo is probably wrong (T50084); set something that will work.
  206. // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
  207. 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
  208. 'wgAuthenticationTokenVersion' => 1,
  209. ];
  210. /**
  211. * The actual list of installation steps. This will be initialized by getInstallSteps()
  212. *
  213. * @var array
  214. */
  215. private $installSteps = [];
  216. /**
  217. * Extra steps for installation, for things like DatabaseInstallers to modify
  218. *
  219. * @var array
  220. */
  221. protected $extraInstallSteps = [];
  222. /**
  223. * Known object cache types and the functions used to test for their existence.
  224. *
  225. * @var array
  226. */
  227. protected $objectCaches = [
  228. 'apc' => 'apc_fetch',
  229. 'apcu' => 'apcu_fetch',
  230. 'wincache' => 'wincache_ucache_get'
  231. ];
  232. /**
  233. * User rights profiles.
  234. *
  235. * @var array
  236. */
  237. public $rightsProfiles = [
  238. 'wiki' => [],
  239. 'no-anon' => [
  240. '*' => [ 'edit' => false ]
  241. ],
  242. 'fishbowl' => [
  243. '*' => [
  244. 'createaccount' => false,
  245. 'edit' => false,
  246. ],
  247. ],
  248. 'private' => [
  249. '*' => [
  250. 'createaccount' => false,
  251. 'edit' => false,
  252. 'read' => false,
  253. ],
  254. ],
  255. ];
  256. /**
  257. * License types.
  258. *
  259. * @var array
  260. */
  261. public $licenses = [
  262. 'cc-by' => [
  263. 'url' => 'https://creativecommons.org/licenses/by/4.0/',
  264. 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
  265. ],
  266. 'cc-by-sa' => [
  267. 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
  268. 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
  269. ],
  270. 'cc-by-nc-sa' => [
  271. 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
  272. 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
  273. ],
  274. 'cc-0' => [
  275. 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
  276. 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
  277. ],
  278. 'gfdl' => [
  279. 'url' => 'https://www.gnu.org/copyleft/fdl.html',
  280. 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
  281. ],
  282. 'none' => [
  283. 'url' => '',
  284. 'icon' => '',
  285. 'text' => ''
  286. ],
  287. 'cc-choose' => [
  288. // Details will be filled in by the selector.
  289. 'url' => '',
  290. 'icon' => '',
  291. 'text' => '',
  292. ],
  293. ];
  294. /**
  295. * URL to mediawiki-announce subscription
  296. */
  297. protected $mediaWikiAnnounceUrl =
  298. 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
  299. /**
  300. * Supported language codes for Mailman
  301. */
  302. protected $mediaWikiAnnounceLanguages = [
  303. 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
  304. 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
  305. 'sl', 'sr', 'sv', 'tr', 'uk'
  306. ];
  307. /**
  308. * UI interface for displaying a short message
  309. * The parameters are like parameters to wfMessage().
  310. * The messages will be in wikitext format, which will be converted to an
  311. * output format such as HTML or text before being sent to the user.
  312. * @param string $msg
  313. * @param mixed ...$params
  314. */
  315. abstract public function showMessage( $msg, ...$params );
  316. /**
  317. * Same as showMessage(), but for displaying errors
  318. * @param string $msg
  319. * @param mixed ...$params
  320. */
  321. abstract public function showError( $msg, ...$params );
  322. /**
  323. * Show a message to the installing user by using a Status object
  324. * @param Status $status
  325. */
  326. abstract public function showStatusMessage( Status $status );
  327. /**
  328. * Constructs a Config object that contains configuration settings that should be
  329. * overwritten for the installation process.
  330. *
  331. * @since 1.27
  332. *
  333. * @param Config $baseConfig
  334. *
  335. * @return Config The config to use during installation.
  336. */
  337. public static function getInstallerConfig( Config $baseConfig ) {
  338. $configOverrides = new HashConfig();
  339. // disable (problematic) object cache types explicitly, preserving all other (working) ones
  340. // bug T113843
  341. $emptyCache = [ 'class' => EmptyBagOStuff::class ];
  342. $objectCaches = [
  343. CACHE_NONE => $emptyCache,
  344. CACHE_DB => $emptyCache,
  345. CACHE_ANYTHING => $emptyCache,
  346. CACHE_MEMCACHED => $emptyCache,
  347. ] + $baseConfig->get( 'ObjectCaches' );
  348. $configOverrides->set( 'ObjectCaches', $objectCaches );
  349. // Load the installer's i18n.
  350. $messageDirs = $baseConfig->get( 'MessagesDirs' );
  351. $messageDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
  352. $configOverrides->set( 'MessagesDirs', $messageDirs );
  353. $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
  354. // make sure we use the installer config as the main config
  355. $configRegistry = $baseConfig->get( 'ConfigRegistry' );
  356. $configRegistry['main'] = function () use ( $installerConfig ) {
  357. return $installerConfig;
  358. };
  359. $configOverrides->set( 'ConfigRegistry', $configRegistry );
  360. return $installerConfig;
  361. }
  362. /**
  363. * Constructor, always call this from child classes.
  364. */
  365. public function __construct() {
  366. global $wgMemc, $wgUser, $wgObjectCaches;
  367. $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
  368. $installerConfig = self::getInstallerConfig( $defaultConfig );
  369. // Reset all services and inject config overrides
  370. MediaWikiServices::resetGlobalInstance( $installerConfig );
  371. // Don't attempt to load user language options (T126177)
  372. // This will be overridden in the web installer with the user-specified language
  373. RequestContext::getMain()->setLanguage( 'en' );
  374. // Disable all global services, since we don't have any configuration yet!
  375. MediaWikiServices::disableStorageBackend();
  376. $mwServices = MediaWikiServices::getInstance();
  377. // Disable i18n cache
  378. $mwServices->getLocalisationCache()->disableBackend();
  379. // Clear language cache so the old i18n cache doesn't sneak back in
  380. Language::clearCaches();
  381. // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
  382. // SqlBagOStuff will then throw since we just disabled wfGetDB)
  383. $wgObjectCaches = $mwServices->getMainConfig()->get( 'ObjectCaches' );
  384. $wgMemc = ObjectCache::getInstance( CACHE_NONE );
  385. // Disable interwiki lookup, to avoid database access during parses
  386. $mwServices->redefineService( 'InterwikiLookup', function () {
  387. return new NullInterwikiLookup();
  388. } );
  389. // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
  390. $wgUser = User::newFromId( 0 );
  391. RequestContext::getMain()->setUser( $wgUser );
  392. $this->settings = $this->internalDefaults;
  393. foreach ( $this->defaultVarNames as $var ) {
  394. $this->settings[$var] = $GLOBALS[$var];
  395. }
  396. $this->doEnvironmentPreps();
  397. $this->compiledDBs = [];
  398. foreach ( self::getDBTypes() as $type ) {
  399. $installer = $this->getDBInstaller( $type );
  400. if ( !$installer->isCompiled() ) {
  401. continue;
  402. }
  403. $this->compiledDBs[] = $type;
  404. }
  405. $this->parserTitle = Title::newFromText( 'Installer' );
  406. $this->parserOptions = new ParserOptions( $wgUser ); // language will be wrong :(
  407. $this->parserOptions->setTidy( true );
  408. // Don't try to access DB before user language is initialised
  409. $this->setParserLanguage( Language::factory( 'en' ) );
  410. }
  411. /**
  412. * Get a list of known DB types.
  413. *
  414. * @return array
  415. */
  416. public static function getDBTypes() {
  417. return self::$dbTypes;
  418. }
  419. /**
  420. * Do initial checks of the PHP environment. Set variables according to
  421. * the observed environment.
  422. *
  423. * It's possible that this may be called under the CLI SAPI, not the SAPI
  424. * that the wiki will primarily run under. In that case, the subclass should
  425. * initialise variables such as wgScriptPath, before calling this function.
  426. *
  427. * Under the web subclass, it can already be assumed that PHP 5+ is in use
  428. * and that sessions are working.
  429. *
  430. * @return Status
  431. */
  432. public function doEnvironmentChecks() {
  433. // Php version has already been checked by entry scripts
  434. // Show message here for information purposes
  435. if ( wfIsHHVM() ) {
  436. $this->showMessage( 'config-env-hhvm', HHVM_VERSION );
  437. } else {
  438. $this->showMessage( 'config-env-php', PHP_VERSION );
  439. }
  440. $good = true;
  441. // Must go here because an old version of PCRE can prevent other checks from completing
  442. $pcreVersion = explode( ' ', PCRE_VERSION, 2 )[0];
  443. if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
  444. $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
  445. $good = false;
  446. } else {
  447. foreach ( $this->envChecks as $check ) {
  448. $status = $this->$check();
  449. if ( $status === false ) {
  450. $good = false;
  451. }
  452. }
  453. }
  454. $this->setVar( '_Environment', $good );
  455. return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
  456. }
  457. public function doEnvironmentPreps() {
  458. foreach ( $this->envPreps as $prep ) {
  459. $this->$prep();
  460. }
  461. }
  462. /**
  463. * Set a MW configuration variable, or internal installer configuration variable.
  464. *
  465. * @param string $name
  466. * @param mixed $value
  467. */
  468. public function setVar( $name, $value ) {
  469. $this->settings[$name] = $value;
  470. }
  471. /**
  472. * Get an MW configuration variable, or internal installer configuration variable.
  473. * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
  474. * Installer variables are typically prefixed by an underscore.
  475. *
  476. * @param string $name
  477. * @param mixed|null $default
  478. *
  479. * @return mixed
  480. */
  481. public function getVar( $name, $default = null ) {
  482. return $this->settings[$name] ?? $default;
  483. }
  484. /**
  485. * Get a list of DBs supported by current PHP setup
  486. *
  487. * @return array
  488. */
  489. public function getCompiledDBs() {
  490. return $this->compiledDBs;
  491. }
  492. /**
  493. * Get the DatabaseInstaller class name for this type
  494. *
  495. * @param string $type database type ($wgDBtype)
  496. * @return string Class name
  497. * @since 1.30
  498. */
  499. public static function getDBInstallerClass( $type ) {
  500. return ucfirst( $type ) . 'Installer';
  501. }
  502. /**
  503. * Get an instance of DatabaseInstaller for the specified DB type.
  504. *
  505. * @param mixed $type DB installer for which is needed, false to use default.
  506. *
  507. * @return DatabaseInstaller
  508. */
  509. public function getDBInstaller( $type = false ) {
  510. if ( !$type ) {
  511. $type = $this->getVar( 'wgDBtype' );
  512. }
  513. $type = strtolower( $type );
  514. if ( !isset( $this->dbInstallers[$type] ) ) {
  515. $class = self::getDBInstallerClass( $type );
  516. $this->dbInstallers[$type] = new $class( $this );
  517. }
  518. return $this->dbInstallers[$type];
  519. }
  520. /**
  521. * Determine if LocalSettings.php exists. If it does, return its variables.
  522. *
  523. * @return array|false
  524. */
  525. public static function getExistingLocalSettings() {
  526. global $IP;
  527. // You might be wondering why this is here. Well if you don't do this
  528. // then some poorly-formed extensions try to call their own classes
  529. // after immediately registering them. We really need to get extension
  530. // registration out of the global scope and into a real format.
  531. // @see https://phabricator.wikimedia.org/T69440
  532. global $wgAutoloadClasses;
  533. $wgAutoloadClasses = [];
  534. // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
  535. // Define the required globals here, to ensure, the functions can do it work correctly.
  536. // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
  537. global $wgExtensionDirectory, $wgStyleDirectory;
  538. Wikimedia\suppressWarnings();
  539. $_lsExists = file_exists( "$IP/LocalSettings.php" );
  540. Wikimedia\restoreWarnings();
  541. if ( !$_lsExists ) {
  542. return false;
  543. }
  544. unset( $_lsExists );
  545. require "$IP/includes/DefaultSettings.php";
  546. require "$IP/LocalSettings.php";
  547. return get_defined_vars();
  548. }
  549. /**
  550. * Get a fake password for sending back to the user in HTML.
  551. * This is a security mechanism to avoid compromise of the password in the
  552. * event of session ID compromise.
  553. *
  554. * @param string $realPassword
  555. *
  556. * @return string
  557. */
  558. public function getFakePassword( $realPassword ) {
  559. return str_repeat( '*', strlen( $realPassword ) );
  560. }
  561. /**
  562. * Set a variable which stores a password, except if the new value is a
  563. * fake password in which case leave it as it is.
  564. *
  565. * @param string $name
  566. * @param mixed $value
  567. */
  568. public function setPassword( $name, $value ) {
  569. if ( !preg_match( '/^\*+$/', $value ) ) {
  570. $this->setVar( $name, $value );
  571. }
  572. }
  573. /**
  574. * On POSIX systems return the primary group of the webserver we're running under.
  575. * On other systems just returns null.
  576. *
  577. * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
  578. * webserver user before he can install.
  579. *
  580. * Public because SqliteInstaller needs it, and doesn't subclass Installer.
  581. *
  582. * @return mixed
  583. */
  584. public static function maybeGetWebserverPrimaryGroup() {
  585. if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
  586. # I don't know this, this isn't UNIX.
  587. return null;
  588. }
  589. # posix_getegid() *not* getmygid() because we want the group of the webserver,
  590. # not whoever owns the current script.
  591. $gid = posix_getegid();
  592. $group = posix_getpwuid( $gid )['name'];
  593. return $group;
  594. }
  595. /**
  596. * Convert wikitext $text to HTML.
  597. *
  598. * This is potentially error prone since many parser features require a complete
  599. * installed MW database. The solution is to just not use those features when you
  600. * write your messages. This appears to work well enough. Basic formatting and
  601. * external links work just fine.
  602. *
  603. * But in case a translator decides to throw in a "#ifexist" or internal link or
  604. * whatever, this function is guarded to catch the attempted DB access and to present
  605. * some fallback text.
  606. *
  607. * @param string $text
  608. * @param bool $lineStart
  609. * @return string
  610. */
  611. public function parse( $text, $lineStart = false ) {
  612. $parser = MediaWikiServices::getInstance()->getParser();
  613. try {
  614. $out = $parser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
  615. $html = $out->getText( [
  616. 'enableSectionEditLinks' => false,
  617. 'unwrap' => true,
  618. ] );
  619. $html = Parser::stripOuterParagraph( $html );
  620. } catch ( Wikimedia\Services\ServiceDisabledException $e ) {
  621. $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
  622. }
  623. return $html;
  624. }
  625. /**
  626. * @return ParserOptions
  627. */
  628. public function getParserOptions() {
  629. return $this->parserOptions;
  630. }
  631. public function disableLinkPopups() {
  632. $this->parserOptions->setExternalLinkTarget( false );
  633. }
  634. public function restoreLinkPopups() {
  635. global $wgExternalLinkTarget;
  636. $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
  637. }
  638. /**
  639. * Install step which adds a row to the site_stats table with appropriate
  640. * initial values.
  641. *
  642. * @param DatabaseInstaller $installer
  643. *
  644. * @return Status
  645. */
  646. public function populateSiteStats( DatabaseInstaller $installer ) {
  647. $status = $installer->getConnection();
  648. if ( !$status->isOK() ) {
  649. return $status;
  650. }
  651. // @phan-suppress-next-line PhanUndeclaredMethod
  652. $status->value->insert(
  653. 'site_stats',
  654. [
  655. 'ss_row_id' => 1,
  656. 'ss_total_edits' => 0,
  657. 'ss_good_articles' => 0,
  658. 'ss_total_pages' => 0,
  659. 'ss_users' => 0,
  660. 'ss_active_users' => 0,
  661. 'ss_images' => 0
  662. ],
  663. __METHOD__, 'IGNORE'
  664. );
  665. return Status::newGood();
  666. }
  667. /**
  668. * Environment check for DB types.
  669. * @return bool
  670. */
  671. protected function envCheckDB() {
  672. global $wgLang;
  673. /** @var string|null $dbType The user-specified database type */
  674. $dbType = $this->getVar( 'wgDBtype' );
  675. $allNames = [];
  676. // Messages: config-type-mysql, config-type-postgres, config-type-sqlite
  677. foreach ( self::getDBTypes() as $name ) {
  678. $allNames[] = wfMessage( "config-type-$name" )->text();
  679. }
  680. $databases = $this->getCompiledDBs();
  681. $databases = array_flip( $databases );
  682. $ok = true;
  683. foreach ( array_keys( $databases ) as $db ) {
  684. $installer = $this->getDBInstaller( $db );
  685. $status = $installer->checkPrerequisites();
  686. if ( !$status->isGood() ) {
  687. if ( !$this instanceof WebInstaller && $db === $dbType ) {
  688. // Strictly check the key database type instead of just outputting message
  689. // Note: No perform this check run from the web installer, since this method always called by
  690. // the welcome page under web installation, so $dbType will always be 'mysql'
  691. $ok = false;
  692. }
  693. $this->showStatusMessage( $status );
  694. unset( $databases[$db] );
  695. }
  696. }
  697. $databases = array_flip( $databases );
  698. if ( !$databases ) {
  699. $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
  700. return false;
  701. }
  702. return $ok;
  703. }
  704. /**
  705. * Some versions of libxml+PHP break < and > encoding horribly
  706. * @return bool
  707. */
  708. protected function envCheckBrokenXML() {
  709. $test = new PhpXmlBugTester();
  710. if ( !$test->ok ) {
  711. $this->showError( 'config-brokenlibxml' );
  712. return false;
  713. }
  714. return true;
  715. }
  716. /**
  717. * Environment check for the PCRE module.
  718. *
  719. * @note If this check were to fail, the parser would
  720. * probably throw an exception before the result
  721. * of this check is shown to the user.
  722. * @return bool
  723. */
  724. protected function envCheckPCRE() {
  725. Wikimedia\suppressWarnings();
  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', '', "-\u{3000}-" );
  732. Wikimedia\restoreWarnings();
  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 = [];
  765. foreach ( $this->objectCaches as $name => $function ) {
  766. if ( function_exists( $function ) ) {
  767. $caches[$name] = true;
  768. }
  769. }
  770. if ( !$caches ) {
  771. $this->showMessage( 'config-no-cache-apcu' );
  772. }
  773. $this->setVar( '_Caches', $caches );
  774. }
  775. /**
  776. * Scare user to death if they have mod_security or mod_security2
  777. * @return bool
  778. */
  779. protected function envCheckModSecurity() {
  780. if ( self::apacheModulePresent( 'mod_security' )
  781. || self::apacheModulePresent( 'mod_security2' ) ) {
  782. $this->showMessage( 'config-mod-security' );
  783. }
  784. return true;
  785. }
  786. /**
  787. * Search for GNU diff3.
  788. * @return bool
  789. */
  790. protected function envCheckDiff3() {
  791. $names = [ "gdiff3", "diff3" ];
  792. if ( wfIsWindows() ) {
  793. $names[] = 'diff3.exe';
  794. }
  795. $versionInfo = [ '--version', 'GNU diffutils' ];
  796. $diff3 = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
  797. if ( $diff3 ) {
  798. $this->setVar( 'wgDiff3', $diff3 );
  799. } else {
  800. $this->setVar( 'wgDiff3', false );
  801. $this->showMessage( 'config-diff3-bad' );
  802. }
  803. return true;
  804. }
  805. /**
  806. * Environment check for ImageMagick and GD.
  807. * @return bool
  808. */
  809. protected function envCheckGraphics() {
  810. $names = wfIsWindows() ? 'convert.exe' : 'convert';
  811. $versionInfo = [ '-version', 'ImageMagick' ];
  812. $convert = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
  813. $this->setVar( 'wgImageMagickConvertCommand', '' );
  814. if ( $convert ) {
  815. $this->setVar( 'wgImageMagickConvertCommand', $convert );
  816. $this->showMessage( 'config-imagemagick', $convert );
  817. return true;
  818. } elseif ( function_exists( 'imagejpeg' ) ) {
  819. $this->showMessage( 'config-gd' );
  820. } else {
  821. $this->showMessage( 'config-no-scaling' );
  822. }
  823. return true;
  824. }
  825. /**
  826. * Search for git.
  827. *
  828. * @since 1.22
  829. * @return bool
  830. */
  831. protected function envCheckGit() {
  832. $names = wfIsWindows() ? 'git.exe' : 'git';
  833. $versionInfo = [ '--version', 'git version' ];
  834. $git = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
  835. if ( $git ) {
  836. $this->setVar( 'wgGitBin', $git );
  837. $this->showMessage( 'config-git', $git );
  838. } else {
  839. $this->setVar( 'wgGitBin', false );
  840. $this->showMessage( 'config-git-bad' );
  841. }
  842. return true;
  843. }
  844. /**
  845. * Environment check to inform user which server we've assumed.
  846. *
  847. * @return bool
  848. */
  849. protected function envCheckServer() {
  850. $server = $this->envGetDefaultServer();
  851. if ( $server !== null ) {
  852. $this->showMessage( 'config-using-server', $server );
  853. }
  854. return true;
  855. }
  856. /**
  857. * Environment check to inform user which paths we've assumed.
  858. *
  859. * @return bool
  860. */
  861. protected function envCheckPath() {
  862. $this->showMessage(
  863. 'config-using-uri',
  864. $this->getVar( 'wgServer' ),
  865. $this->getVar( 'wgScriptPath' )
  866. );
  867. return true;
  868. }
  869. /**
  870. * Environment check for preferred locale in shell
  871. * @return bool
  872. */
  873. protected function envCheckShellLocale() {
  874. $os = php_uname( 's' );
  875. $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
  876. if ( !in_array( $os, $supported ) ) {
  877. return true;
  878. }
  879. if ( Shell::isDisabled() ) {
  880. return true;
  881. }
  882. # Get a list of available locales.
  883. $result = Shell::command( '/usr/bin/locale', '-a' )
  884. ->execute();
  885. if ( $result->getExitCode() != 0 ) {
  886. return true;
  887. }
  888. $lines = $result->getStdout();
  889. $lines = array_map( 'trim', explode( "\n", $lines ) );
  890. $candidatesByLocale = [];
  891. $candidatesByLang = [];
  892. foreach ( $lines as $line ) {
  893. if ( $line === '' ) {
  894. continue;
  895. }
  896. if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
  897. continue;
  898. }
  899. list( , $lang, , , ) = $m;
  900. $candidatesByLocale[$m[0]] = $m;
  901. $candidatesByLang[$lang][] = $m;
  902. }
  903. # Try the current value of LANG.
  904. if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
  905. $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
  906. return true;
  907. }
  908. # Try the most common ones.
  909. $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
  910. foreach ( $commonLocales as $commonLocale ) {
  911. if ( isset( $candidatesByLocale[$commonLocale] ) ) {
  912. $this->setVar( 'wgShellLocale', $commonLocale );
  913. return true;
  914. }
  915. }
  916. # Is there an available locale in the Wiki's language?
  917. $wikiLang = $this->getVar( 'wgLanguageCode' );
  918. if ( isset( $candidatesByLang[$wikiLang] ) ) {
  919. $m = reset( $candidatesByLang[$wikiLang] );
  920. $this->setVar( 'wgShellLocale', $m[0] );
  921. return true;
  922. }
  923. # Are there any at all?
  924. if ( count( $candidatesByLocale ) ) {
  925. $m = reset( $candidatesByLocale );
  926. $this->setVar( 'wgShellLocale', $m[0] );
  927. return true;
  928. }
  929. # Give up.
  930. return true;
  931. }
  932. /**
  933. * Environment check for the permissions of the uploads directory
  934. * @return bool
  935. */
  936. protected function envCheckUploadsDirectory() {
  937. global $IP;
  938. $dir = $IP . '/images/';
  939. $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
  940. $safe = !$this->dirIsExecutable( $dir, $url );
  941. if ( !$safe ) {
  942. $this->showMessage( 'config-uploads-not-safe', $dir );
  943. }
  944. return true;
  945. }
  946. /**
  947. * Checks if suhosin.get.max_value_length is set, and if so generate
  948. * a warning because it is incompatible with ResourceLoader.
  949. * @return bool
  950. */
  951. protected function envCheckSuhosinMaxValueLength() {
  952. $currentValue = ini_get( 'suhosin.get.max_value_length' );
  953. $minRequired = 2000;
  954. $recommended = 5000;
  955. if ( $currentValue > 0 && $currentValue < $minRequired ) {
  956. $this->showError( 'config-suhosin-max-value-length', $currentValue, $minRequired, $recommended );
  957. return false;
  958. }
  959. return true;
  960. }
  961. /**
  962. * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
  963. * hard to support, so let's at least warn people.
  964. *
  965. * @return bool
  966. */
  967. protected function envCheck64Bit() {
  968. if ( PHP_INT_SIZE == 4 ) {
  969. $this->showMessage( 'config-using-32bit' );
  970. }
  971. return true;
  972. }
  973. /**
  974. * Check the libicu version
  975. */
  976. protected function envCheckLibicu() {
  977. /**
  978. * This needs to be updated something that the latest libicu
  979. * will properly normalize. This normalization was found at
  980. * https://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
  981. * Note that we use the hex representation to create the code
  982. * points in order to avoid any Unicode-destroying during transit.
  983. */
  984. $not_normal_c = "\u{FA6C}";
  985. $normal_c = "\u{242EE}";
  986. $useNormalizer = 'php';
  987. $needsUpdate = false;
  988. if ( function_exists( 'normalizer_normalize' ) ) {
  989. $useNormalizer = 'intl';
  990. $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
  991. if ( $intl !== $normal_c ) {
  992. $needsUpdate = true;
  993. }
  994. }
  995. // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
  996. if ( $useNormalizer === 'php' ) {
  997. $this->showMessage( 'config-unicode-pure-php-warning' );
  998. } else {
  999. $this->showMessage( 'config-unicode-using-' . $useNormalizer );
  1000. if ( $needsUpdate ) {
  1001. $this->showMessage( 'config-unicode-update-warning' );
  1002. }
  1003. }
  1004. }
  1005. /**
  1006. * Environment prep for the server hostname.
  1007. */
  1008. protected function envPrepServer() {
  1009. $server = $this->envGetDefaultServer();
  1010. if ( $server !== null ) {
  1011. $this->setVar( 'wgServer', $server );
  1012. }
  1013. }
  1014. /**
  1015. * Helper function to be called from envPrepServer()
  1016. * @return string
  1017. */
  1018. abstract protected function envGetDefaultServer();
  1019. /**
  1020. * Environment prep for setting $IP and $wgScriptPath.
  1021. */
  1022. protected function envPrepPath() {
  1023. global $IP;
  1024. $IP = dirname( dirname( __DIR__ ) );
  1025. $this->setVar( 'IP', $IP );
  1026. }
  1027. /**
  1028. * Checks if scripts located in the given directory can be executed via the given URL.
  1029. *
  1030. * Used only by environment checks.
  1031. * @param string $dir
  1032. * @param string $url
  1033. * @return bool|int|string
  1034. */
  1035. public function dirIsExecutable( $dir, $url ) {
  1036. $scriptTypes = [
  1037. 'php' => [
  1038. "<?php echo 'exec';",
  1039. "#!/var/env php\n<?php echo 'exec';",
  1040. ],
  1041. ];
  1042. // it would be good to check other popular languages here, but it'll be slow.
  1043. Wikimedia\suppressWarnings();
  1044. foreach ( $scriptTypes as $ext => $contents ) {
  1045. foreach ( $contents as $source ) {
  1046. $file = 'exectest.' . $ext;
  1047. if ( !file_put_contents( $dir . $file, $source ) ) {
  1048. break;
  1049. }
  1050. try {
  1051. $text = MediaWikiServices::getInstance()->getHttpRequestFactory()->
  1052. get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
  1053. } catch ( Exception $e ) {
  1054. // HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
  1055. // extension.
  1056. $text = null;
  1057. }
  1058. unlink( $dir . $file );
  1059. if ( $text == 'exec' ) {
  1060. Wikimedia\restoreWarnings();
  1061. return $ext;
  1062. }
  1063. }
  1064. }
  1065. Wikimedia\restoreWarnings();
  1066. return false;
  1067. }
  1068. /**
  1069. * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
  1070. *
  1071. * @param string $moduleName Name of module to check.
  1072. * @return bool
  1073. */
  1074. public static function apacheModulePresent( $moduleName ) {
  1075. if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
  1076. return true;
  1077. }
  1078. // try it the hard way
  1079. ob_start();
  1080. phpinfo( INFO_MODULES );
  1081. $info = ob_get_clean();
  1082. return strpos( $info, $moduleName ) !== false;
  1083. }
  1084. /**
  1085. * ParserOptions are constructed before we determined the language, so fix it
  1086. *
  1087. * @param Language $lang
  1088. */
  1089. public function setParserLanguage( $lang ) {
  1090. $this->parserOptions->setTargetLanguage( $lang );
  1091. $this->parserOptions->setUserLang( $lang );
  1092. }
  1093. /**
  1094. * Overridden by WebInstaller to provide lastPage parameters.
  1095. * @param string $page
  1096. * @return string
  1097. */
  1098. protected function getDocUrl( $page ) {
  1099. return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
  1100. }
  1101. /**
  1102. * Find extensions or skins in a subdirectory of $IP.
  1103. * Returns an array containing the value for 'Name' for each found extension.
  1104. *
  1105. * @param string $directory Directory to search in, relative to $IP, must be either "extensions"
  1106. * or "skins"
  1107. * @return Status An object containing an error list. If there were no errors, an associative
  1108. * array of information about the extension can be found in $status->value.
  1109. */
  1110. public function findExtensions( $directory = 'extensions' ) {
  1111. switch ( $directory ) {
  1112. case 'extensions':
  1113. return $this->findExtensionsByType( 'extension', 'extensions' );
  1114. case 'skins':
  1115. return $this->findExtensionsByType( 'skin', 'skins' );
  1116. default:
  1117. throw new InvalidArgumentException( "Invalid extension type" );
  1118. }
  1119. }
  1120. /**
  1121. * Find extensions or skins, and return an array containing the value for 'Name' for each found
  1122. * extension.
  1123. *
  1124. * @param string $type Either "extension" or "skin"
  1125. * @param string $directory Directory to search in, relative to $IP
  1126. * @return Status An object containing an error list. If there were no errors, an associative
  1127. * array of information about the extension can be found in $status->value.
  1128. */
  1129. protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
  1130. if ( $this->getVar( 'IP' ) === null ) {
  1131. return Status::newGood( [] );
  1132. }
  1133. $extDir = $this->getVar( 'IP' ) . '/' . $directory;
  1134. if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
  1135. return Status::newGood( [] );
  1136. }
  1137. $dh = opendir( $extDir );
  1138. $exts = [];
  1139. $status = new Status;
  1140. while ( ( $file = readdir( $dh ) ) !== false ) {
  1141. // skip non-dirs and hidden directories
  1142. if ( !is_dir( "$extDir/$file" ) || $file[0] === '.' ) {
  1143. continue;
  1144. }
  1145. $extStatus = $this->getExtensionInfo( $type, $directory, $file );
  1146. if ( $extStatus->isOK() ) {
  1147. $exts[$file] = $extStatus->value;
  1148. } elseif ( $extStatus->hasMessage( 'config-extension-not-found' ) ) {
  1149. // (T225512) The directory is not actually an extension. Downgrade to warning.
  1150. $status->warning( 'config-extension-not-found', $file );
  1151. } else {
  1152. $status->merge( $extStatus );
  1153. }
  1154. }
  1155. closedir( $dh );
  1156. uksort( $exts, 'strnatcasecmp' );
  1157. $status->value = $exts;
  1158. return $status;
  1159. }
  1160. /**
  1161. * @param string $type Either "extension" or "skin"
  1162. * @param string $parentRelPath The parent directory relative to $IP
  1163. * @param string $name The extension or skin name
  1164. * @return Status An object containing an error list. If there were no errors, an associative
  1165. * array of information about the extension can be found in $status->value.
  1166. */
  1167. protected function getExtensionInfo( $type, $parentRelPath, $name ) {
  1168. if ( $this->getVar( 'IP' ) === null ) {
  1169. throw new Exception( 'Cannot find extensions since the IP variable is not yet set' );
  1170. }
  1171. if ( $type !== 'extension' && $type !== 'skin' ) {
  1172. throw new InvalidArgumentException( "Invalid extension type" );
  1173. }
  1174. $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
  1175. $relDir = "../$parentRelPath/$name";
  1176. if ( !is_dir( $absDir ) ) {
  1177. return Status::newFatal( 'config-extension-not-found', $name );
  1178. }
  1179. $jsonFile = $type . '.json';
  1180. $fullJsonFile = "$absDir/$jsonFile";
  1181. $isJson = file_exists( $fullJsonFile );
  1182. $isPhp = false;
  1183. if ( !$isJson ) {
  1184. // Only fallback to PHP file if JSON doesn't exist
  1185. $fullPhpFile = "$absDir/$name.php";
  1186. $isPhp = file_exists( $fullPhpFile );
  1187. }
  1188. if ( !$isJson && !$isPhp ) {
  1189. return Status::newFatal( 'config-extension-not-found', $name );
  1190. }
  1191. // Extension exists. Now see if there are screenshots
  1192. $info = [];
  1193. if ( is_dir( "$absDir/screenshots" ) ) {
  1194. $paths = glob( "$absDir/screenshots/*.png" );
  1195. foreach ( $paths as $path ) {
  1196. $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
  1197. }
  1198. }
  1199. if ( $isJson ) {
  1200. $jsonStatus = $this->readExtension( $fullJsonFile );
  1201. if ( !$jsonStatus->isOK() ) {
  1202. return $jsonStatus;
  1203. }
  1204. $info += $jsonStatus->value;
  1205. }
  1206. return Status::newGood( $info );
  1207. }
  1208. /**
  1209. * @param string $fullJsonFile
  1210. * @param array $extDeps
  1211. * @param array $skinDeps
  1212. *
  1213. * @return Status On success, an array of extension information is in $status->value. On
  1214. * failure, the Status object will have an error list.
  1215. */
  1216. private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
  1217. $load = [
  1218. $fullJsonFile => 1
  1219. ];
  1220. if ( $extDeps ) {
  1221. $extDir = $this->getVar( 'IP' ) . '/extensions';
  1222. foreach ( $extDeps as $dep ) {
  1223. $fname = "$extDir/$dep/extension.json";
  1224. if ( !file_exists( $fname ) ) {
  1225. return Status::newFatal( 'config-extension-not-found', $dep );
  1226. }
  1227. $load[$fname] = 1;
  1228. }
  1229. }
  1230. if ( $skinDeps ) {
  1231. $skinDir = $this->getVar( 'IP' ) . '/skins';
  1232. foreach ( $skinDeps as $dep ) {
  1233. $fname = "$skinDir/$dep/skin.json";
  1234. if ( !file_exists( $fname ) ) {
  1235. return Status::newFatal( 'config-extension-not-found', $dep );
  1236. }
  1237. $load[$fname] = 1;
  1238. }
  1239. }
  1240. $registry = new ExtensionRegistry();
  1241. try {
  1242. $info = $registry->readFromQueue( $load );
  1243. } catch ( ExtensionDependencyError $e ) {
  1244. if ( $e->incompatibleCore || $e->incompatibleSkins
  1245. || $e->incompatibleExtensions
  1246. ) {
  1247. // If something is incompatible with a dependency, we have no real
  1248. // option besides skipping it
  1249. return Status::newFatal( 'config-extension-dependency',
  1250. basename( dirname( $fullJsonFile ) ), $e->getMessage() );
  1251. } elseif ( $e->missingExtensions || $e->missingSkins ) {
  1252. // There's an extension missing in the dependency tree,
  1253. // so add those to the dependency list and try again
  1254. $status = $this->readExtension(
  1255. $fullJsonFile,
  1256. array_merge( $extDeps, $e->missingExtensions ),
  1257. array_merge( $skinDeps, $e->missingSkins )
  1258. );
  1259. if ( !$status->isOK() && !$status->hasMessage( 'config-extension-dependency' ) ) {
  1260. $status = Status::newFatal( 'config-extension-dependency',
  1261. basename( dirname( $fullJsonFile ) ), $status->getMessage() );
  1262. }
  1263. return $status;
  1264. }
  1265. // Some other kind of dependency error?
  1266. return Status::newFatal( 'config-extension-dependency',
  1267. basename( dirname( $fullJsonFile ) ), $e->getMessage() );
  1268. }
  1269. $ret = [];
  1270. // The order of credits will be the order of $load,
  1271. // so the first extension is the one we want to load,
  1272. // everything else is a dependency
  1273. $i = 0;
  1274. foreach ( $info['credits'] as $name => $credit ) {
  1275. $i++;
  1276. if ( $i == 1 ) {
  1277. // Extension we want to load
  1278. continue;
  1279. }
  1280. $type = basename( $credit['path'] ) === 'skin.json' ? 'skins' : 'extensions';
  1281. $ret['requires'][$type][] = $credit['name'];
  1282. }
  1283. $credits = array_values( $info['credits'] )[0];
  1284. if ( isset( $credits['url'] ) ) {
  1285. $ret['url'] = $credits['url'];
  1286. }
  1287. $ret['type'] = $credits['type'];
  1288. return Status::newGood( $ret );
  1289. }
  1290. /**
  1291. * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
  1292. * but will fall back to another if the default skin is missing and some other one is present
  1293. * instead.
  1294. *
  1295. * @param string[] $skinNames Names of installed skins.
  1296. * @return string
  1297. */
  1298. public function getDefaultSkin( array $skinNames ) {
  1299. $defaultSkin = $GLOBALS['wgDefaultSkin'];
  1300. if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
  1301. return $defaultSkin;
  1302. } else {
  1303. return $skinNames[0];
  1304. }
  1305. }
  1306. /**
  1307. * Installs the auto-detected extensions.
  1308. *
  1309. * @suppress SecurityCheck-OTHER It thinks $exts/$IP is user controlled but they are not.
  1310. * @return Status
  1311. */
  1312. protected function includeExtensions() {
  1313. global $IP;
  1314. $exts = $this->getVar( '_Extensions' );
  1315. $IP = $this->getVar( 'IP' );
  1316. // Marker for DatabaseUpdater::loadExtensions so we don't
  1317. // double load extensions
  1318. define( 'MW_EXTENSIONS_LOADED', true );
  1319. /**
  1320. * We need to include DefaultSettings before including extensions to avoid
  1321. * warnings about unset variables. However, the only thing we really
  1322. * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
  1323. * if the extension has hidden hook registration in $wgExtensionFunctions,
  1324. * but we're not opening that can of worms
  1325. * @see https://phabricator.wikimedia.org/T28857
  1326. */
  1327. global $wgAutoloadClasses;
  1328. $wgAutoloadClasses = [];
  1329. $queue = [];
  1330. require "$IP/includes/DefaultSettings.php";
  1331. foreach ( $exts as $e ) {
  1332. if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
  1333. $queue["$IP/extensions/$e/extension.json"] = 1;
  1334. } else {
  1335. require_once "$IP/extensions/$e/$e.php";
  1336. }
  1337. }
  1338. $registry = new ExtensionRegistry();
  1339. $data = $registry->readFromQueue( $queue );
  1340. $wgAutoloadClasses += $data['autoload'];
  1341. // @phan-suppress-next-line PhanUndeclaredVariable $wgHooks is set by DefaultSettings
  1342. $hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ?? [];
  1343. if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
  1344. $hooksWeWant = array_merge_recursive(
  1345. $hooksWeWant,
  1346. $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
  1347. );
  1348. }
  1349. // Unset everyone else's hooks. Lord knows what someone might be doing
  1350. // in ParserFirstCallInit (see T29171)
  1351. $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
  1352. return Status::newGood();
  1353. }
  1354. /**
  1355. * Get an array of install steps. Should always be in the format of
  1356. * [
  1357. * 'name' => 'someuniquename',
  1358. * 'callback' => [ $obj, 'method' ],
  1359. * ]
  1360. * There must be a config-install-$name message defined per step, which will
  1361. * be shown on install.
  1362. *
  1363. * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
  1364. * @return array
  1365. */
  1366. protected function getInstallSteps( DatabaseInstaller $installer ) {
  1367. $coreInstallSteps = [
  1368. [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
  1369. [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
  1370. [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
  1371. [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
  1372. [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
  1373. [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
  1374. [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
  1375. [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
  1376. ];
  1377. // Build the array of install steps starting from the core install list,
  1378. // then adding any callbacks that wanted to attach after a given step
  1379. foreach ( $coreInstallSteps as $step ) {
  1380. $this->installSteps[] = $step;
  1381. if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
  1382. $this->installSteps = array_merge(
  1383. $this->installSteps,
  1384. $this->extraInstallSteps[$step['name']]
  1385. );
  1386. }
  1387. }
  1388. // Prepend any steps that want to be at the beginning
  1389. if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
  1390. $this->installSteps = array_merge(
  1391. $this->extraInstallSteps['BEGINNING'],
  1392. $this->installSteps
  1393. );
  1394. }
  1395. // Extensions should always go first, chance to tie into hooks and such
  1396. if ( count( $this->getVar( '_Extensions' ) ) ) {
  1397. array_unshift( $this->installSteps,
  1398. [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
  1399. );
  1400. $this->installSteps[] = [
  1401. 'name' => 'extension-tables',
  1402. 'callback' => [ $installer, 'createExtensionTables' ]
  1403. ];
  1404. }
  1405. return $this->installSteps;
  1406. }
  1407. /**
  1408. * Actually perform the installation.
  1409. *
  1410. * @param callable $startCB A callback array for the beginning of each step
  1411. * @param callable $endCB A callback array for the end of each step
  1412. *
  1413. * @return Status[] Array of Status objects
  1414. */
  1415. public function performInstallation( $startCB, $endCB ) {
  1416. $installResults = [];
  1417. $installer = $this->getDBInstaller();
  1418. $installer->preInstall();
  1419. $steps = $this->getInstallSteps( $installer );
  1420. foreach ( $steps as $stepObj ) {
  1421. $name = $stepObj['name'];
  1422. call_user_func_array( $startCB, [ $name ] );
  1423. // Perform the callback step
  1424. $status = call_user_func( $stepObj['callback'], $installer );
  1425. // Output and save the results
  1426. call_user_func( $endCB, $name, $status );
  1427. $installResults[$name] = $status;
  1428. // If we've hit some sort of fatal, we need to bail.
  1429. // Callback already had a chance to do output above.
  1430. if ( !$status->isOK() ) {
  1431. break;
  1432. }
  1433. }
  1434. if ( $status->isOK() ) {
  1435. $this->showMessage(
  1436. 'config-install-db-success'
  1437. );
  1438. $this->setVar( '_InstallDone', true );
  1439. }
  1440. return $installResults;
  1441. }
  1442. /**
  1443. * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
  1444. *
  1445. * @return Status
  1446. */
  1447. public function generateKeys() {
  1448. $keys = [ 'wgSecretKey' => 64 ];
  1449. if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
  1450. $keys['wgUpgradeKey'] = 16;
  1451. }
  1452. return $this->doGenerateKeys( $keys );
  1453. }
  1454. /**
  1455. * Generate a secret value for variables using a secure generator.
  1456. *
  1457. * @param array $keys
  1458. * @return Status
  1459. */
  1460. protected function doGenerateKeys( $keys ) {
  1461. $status = Status::newGood();
  1462. foreach ( $keys as $name => $length ) {
  1463. $secretKey = MWCryptRand::generateHex( $length );
  1464. $this->setVar( $name, $secretKey );
  1465. }
  1466. return $status;
  1467. }
  1468. /**
  1469. * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
  1470. *
  1471. * @return Status
  1472. */
  1473. protected function createSysop() {
  1474. $name = $this->getVar( '_AdminName' );
  1475. $user = User::newFromName( $name );
  1476. if ( !$user ) {
  1477. // We should've validated this earlier anyway!
  1478. return Status::newFatal( 'config-admin-error-user', $name );
  1479. }
  1480. if ( $user->idForName() == 0 ) {
  1481. $user->addToDatabase();
  1482. try {
  1483. $user->setPassword( $this->getVar( '_AdminPassword' ) );
  1484. } catch ( PasswordError $pwe ) {
  1485. return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
  1486. }
  1487. $user->addGroup( 'sysop' );
  1488. $user->addGroup( 'bureaucrat' );
  1489. $user->addGroup( 'interface-admin' );
  1490. if ( $this->getVar( '_AdminEmail' ) ) {
  1491. $user->setEmail( $this->getVar( '_AdminEmail' ) );
  1492. }
  1493. $user->saveSettings();
  1494. // Update user count
  1495. $ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
  1496. $ssUpdate->doUpdate();
  1497. }
  1498. $status = Status::newGood();
  1499. if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
  1500. $this->subscribeToMediaWikiAnnounce( $status );
  1501. }
  1502. return $status;
  1503. }
  1504. /**
  1505. * @param Status $s
  1506. */
  1507. private function subscribeToMediaWikiAnnounce( Status $s ) {
  1508. $params = [
  1509. 'email' => $this->getVar( '_AdminEmail' ),
  1510. 'language' => 'en',
  1511. 'digest' => 0
  1512. ];
  1513. // Mailman doesn't support as many languages as we do, so check to make
  1514. // sure their selected language is available
  1515. $myLang = $this->getVar( '_UserLang' );
  1516. if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
  1517. $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
  1518. $params['language'] = $myLang;
  1519. }
  1520. if ( MWHttpRequest::canMakeRequests() ) {
  1521. $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
  1522. [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
  1523. if ( !$res->isOK() ) {
  1524. $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
  1525. }
  1526. } else {
  1527. $s->warning( 'config-install-subscribe-notpossible' );
  1528. }
  1529. }
  1530. /**
  1531. * Insert Main Page with default content.
  1532. *
  1533. * @param DatabaseInstaller $installer
  1534. * @return Status
  1535. */
  1536. protected function createMainpage( DatabaseInstaller $installer ) {
  1537. $status = Status::newGood();
  1538. $title = Title::newMainPage();
  1539. if ( $title->exists() ) {
  1540. $status->warning( 'config-install-mainpage-exists' );
  1541. return $status;
  1542. }
  1543. try {
  1544. $page = WikiPage::factory( $title );
  1545. $content = new WikitextContent(
  1546. wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
  1547. wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
  1548. );
  1549. $status = $page->doEditContent( $content,
  1550. '',
  1551. EDIT_NEW,
  1552. false,
  1553. User::newFromName( 'MediaWiki default' )
  1554. );
  1555. } catch ( Exception $e ) {
  1556. // using raw, because $wgShowExceptionDetails can not be set yet
  1557. $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
  1558. }
  1559. return $status;
  1560. }
  1561. /**
  1562. * Override the necessary bits of the config to run an installation.
  1563. */
  1564. public static function overrideConfig() {
  1565. // Use PHP's built-in session handling, since MediaWiki's
  1566. // SessionHandler can't work before we have an object cache set up.
  1567. if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
  1568. define( 'MW_NO_SESSION_HANDLER', 1 );
  1569. }
  1570. // Don't access the database
  1571. $GLOBALS['wgUseDatabaseMessages'] = false;
  1572. // Don't cache langconv tables
  1573. $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
  1574. // Debug-friendly
  1575. $GLOBALS['wgShowExceptionDetails'] = true;
  1576. $GLOBALS['wgShowHostnames'] = true;
  1577. // Don't break forms
  1578. $GLOBALS['wgExternalLinkTarget'] = '_blank';
  1579. // Allow multiple ob_flush() calls
  1580. $GLOBALS['wgDisableOutputCompression'] = true;
  1581. // Use a sensible cookie prefix (not my_wiki)
  1582. $GLOBALS['wgCookiePrefix'] = 'mw_installer';
  1583. // Some of the environment checks make shell requests, remove limits
  1584. $GLOBALS['wgMaxShellMemory'] = 0;
  1585. // Override the default CookieSessionProvider with a dummy
  1586. // implementation that won't stomp on PHP's cookies.
  1587. $GLOBALS['wgSessionProviders'] = [
  1588. [
  1589. 'class' => InstallerSessionProvider::class,
  1590. 'args' => [ [
  1591. 'priority' => 1,
  1592. ] ]
  1593. ]
  1594. ];
  1595. // Don't try to use any object cache for SessionManager either.
  1596. $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
  1597. // Set a dummy $wgServer to bypass the check in Setup.php, the
  1598. // web installer will automatically detect it and not use this value.
  1599. $GLOBALS['wgServer'] = 'https://🌻.invalid';
  1600. }
  1601. /**
  1602. * Add an installation step following the given step.
  1603. *
  1604. * @param array $callback A valid installation callback array, in this form:
  1605. * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
  1606. * @param string $findStep The step to find. Omit to put the step at the beginning
  1607. */
  1608. public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
  1609. $this->extraInstallSteps[$findStep][] = $callback;
  1610. }
  1611. /**
  1612. * Disable the time limit for execution.
  1613. * Some long-running pages (Install, Upgrade) will want to do this
  1614. */
  1615. protected function disableTimeLimit() {
  1616. Wikimedia\suppressWarnings();
  1617. set_time_limit( 0 );
  1618. Wikimedia\restoreWarnings();
  1619. }
  1620. }