1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
|
<?php
/**
* Base code for MediaWiki installer.
*
* DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
* See mw-config/overrides/README for details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Installer
*/
namespace MediaWiki\Installer;
use AutoLoader;
use Exception;
use ExecutableFinder;
use GuzzleHttp\Psr7\Header;
use IntlChar;
use InvalidArgumentException;
use LogicException;
use MediaWiki\Config\Config;
use MediaWiki\Config\GlobalVarConfig;
use MediaWiki\Config\HashConfig;
use MediaWiki\Config\MultiConfig;
use MediaWiki\Content\WikitextContent;
use MediaWiki\Context\RequestContext;
use MediaWiki\Deferred\SiteStatsUpdate;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\HookContainer\StaticHookRegistry;
use MediaWiki\Interwiki\NullInterwikiLookup;
use MediaWiki\Language\Language;
use MediaWiki\MainConfigNames;
use MediaWiki\MainConfigSchema;
use MediaWiki\MediaWikiServices;
use MediaWiki\Parser\Parser;
use MediaWiki\Parser\ParserOptions;
use MediaWiki\Registration\ExtensionDependencyError;
use MediaWiki\Registration\ExtensionProcessor;
use MediaWiki\Registration\ExtensionRegistry;
use MediaWiki\Settings\SettingsBuilder;
use MediaWiki\Status\Status;
use MediaWiki\StubObject\StubGlobalUser;
use MediaWiki\Title\Title;
use MediaWiki\User\Options\StaticUserOptionsLookup;
use MediaWiki\User\User;
use MediaWiki\Utils\UrlUtils;
use MWCryptRand;
use MWLBFactory;
use RuntimeException;
use Wikimedia\AtEase\AtEase;
use Wikimedia\Message\MessageSpecifier;
use Wikimedia\ObjectCache\EmptyBagOStuff;
use Wikimedia\Rdbms\LBFactorySingle;
use Wikimedia\Services\ServiceDisabledException;
/**
* The Installer helps admins create or upgrade their wiki.
*
* The installer classes are exposed through these human interfaces:
*
* - The `maintenance/install.php` script, backed by CliInstaller.
* - The `maintenance/update.php` script, backed by DatabaseUpdater.
* - The `mw-config/index.php` web entry point, backed by WebInstaller.
*
* @defgroup Installer Installer
*/
/**
* Base installer class.
*
* This class provides the base for installation and update functionality
* for both MediaWiki core and extensions.
*
* @ingroup Installer
* @since 1.17
*/
abstract class Installer {
/**
* URL to mediawiki-announce list summary page
*/
private const MEDIAWIKI_ANNOUNCE_URL =
'https://lists.wikimedia.org/postorius/lists/mediawiki-announce.lists.wikimedia.org/';
/**
* @var array
*/
protected $settings;
/**
* List of detected DBs, access using getCompiledDBs().
*
* @var array
*/
protected $compiledDBs;
/**
* Cached DB installer instances, access using getDBInstaller().
*
* @var array
*/
protected $dbInstallers = [];
/**
* Minimum memory size in MiB.
*
* @var int
*/
protected $minMemorySize = 50;
/**
* Cached Title, used by parse().
*
* @var Title
*/
protected $parserTitle;
/**
* Cached ParserOptions, used by parse().
*
* @var ParserOptions
*/
protected $parserOptions;
/**
* Known database types. These correspond to the class names <type>Installer,
* and are also MediaWiki database types valid for $wgDBtype.
*
* To add a new type, create a <type>Installer class and a Database<type>
* class, and add a config-type-<type> message to MessagesEn.php.
*
* @var array
*/
protected static $dbTypes = [
'mysql',
'postgres',
'sqlite',
];
/**
* A list of environment check methods called by doEnvironmentChecks().
* These may output warnings using showMessage(), and/or abort the
* installation process by returning false.
*
* For the WebInstaller these are only called on the Welcome page,
* if these methods have side-effects that should affect later page loads
* (as well as the generated stylesheet), use envPreps instead.
*
* @var array
*/
protected $envChecks = [
'envCheckLibicu',
'envCheckDB',
'envCheckPCRE',
'envCheckMemory',
'envCheckCache',
'envCheckModSecurity',
'envCheckDiff3',
'envCheckGraphics',
'envCheckGit',
'envCheckServer',
'envCheckPath',
'envCheckUploadsDirectory',
'envCheckUploadsServerResponse',
'envCheck64Bit',
];
/**
* A list of environment preparation methods called by doEnvironmentPreps().
*
* @var array
*/
protected $envPreps = [
'envPrepServer',
'envPrepPath',
];
/**
* MediaWiki configuration globals that will eventually be passed through
* to LocalSettings.php. The names only are given here, the defaults
* typically come from config-schema.yaml.
*/
private const DEFAULT_VAR_NAMES = [
MainConfigNames::Sitename,
MainConfigNames::PasswordSender,
MainConfigNames::LanguageCode,
MainConfigNames::Localtimezone,
MainConfigNames::RightsIcon,
MainConfigNames::RightsText,
MainConfigNames::RightsUrl,
MainConfigNames::EnableEmail,
MainConfigNames::EnableUserEmail,
MainConfigNames::EnotifUserTalk,
MainConfigNames::EnotifWatchlist,
MainConfigNames::EmailAuthentication,
MainConfigNames::DBname,
MainConfigNames::DBtype,
MainConfigNames::Diff3,
MainConfigNames::ImageMagickConvertCommand,
MainConfigNames::GitBin,
MainConfigNames::ScriptPath,
MainConfigNames::MetaNamespace,
MainConfigNames::DeletedDirectory,
MainConfigNames::EnableUploads,
MainConfigNames::SecretKey,
MainConfigNames::UseInstantCommons,
MainConfigNames::UpgradeKey,
MainConfigNames::DefaultSkin,
MainConfigNames::Pingback,
];
/**
* Variables that are stored alongside globals, and are used for any
* configuration of the installation process aside from the MediaWiki
* configuration. Map of names to defaults.
*
* @var array
*/
protected $internalDefaults = [
'_UserLang' => 'en',
'_Environment' => false,
'_RaiseMemory' => false,
'_UpgradeDone' => false,
'_InstallDone' => false,
'_Caches' => [],
'_InstallPassword' => '',
'_SameAccount' => true,
'_CreateDBAccount' => false,
'_NamespaceType' => 'site-name',
'_AdminName' => '', // will be set later, when the user selects language
'_AdminPassword' => '',
'_AdminPasswordConfirm' => '',
'_AdminEmail' => '',
'_Subscribe' => false,
'_SkipOptional' => 'continue',
'_RightsProfile' => 'wiki',
'_LicenseCode' => 'none',
'_CCDone' => false,
'_Extensions' => [],
'_Skins' => [],
'_MemCachedServers' => '',
'_UpgradeKeySupplied' => false,
'_ExistingDBSettings' => false,
'_LogoWordmark' => '',
'_LogoWordmarkWidth' => 119,
'_LogoWordmarkHeight' => 18,
// Single quotes are intentional, LocalSettingsGenerator must output this unescaped.
'_Logo1x' => '$wgResourceBasePath/resources/assets/change-your-logo.svg',
'_LogoIcon' => '$wgResourceBasePath/resources/assets/change-your-logo-icon.svg',
'_LogoTagline' => '',
'_LogoTaglineWidth' => 117,
'_LogoTaglineHeight' => 13,
'_WithDevelopmentSettings' => false,
'wgAuthenticationTokenVersion' => 1,
];
/**
* The actual list of installation steps. This will be initialized by getInstallSteps()
*
* @var array[]
* @phan-var array<int,array{name:string,callback:array{0:object,1:string}}>
*/
private $installSteps = [];
/**
* Extra steps for installation, for things like DatabaseInstallers to modify
*
* @var array
*/
protected $extraInstallSteps = [];
/**
* Known object cache types and the functions used to test for their existence.
*
* @var array
*/
protected $objectCaches = [
'apcu' => 'apcu_fetch',
];
/**
* User rights profiles.
*
* @var array
*/
public $rightsProfiles = [
'wiki' => [],
'no-anon' => [
'*' => [ 'edit' => false ]
],
'fishbowl' => [
'*' => [
'createaccount' => false,
'edit' => false,
],
],
'private' => [
'*' => [
'createaccount' => false,
'edit' => false,
'read' => false,
],
],
];
/**
* License types.
*
* @var array
*/
public $licenses = [
'cc-by' => [
'url' => 'https://creativecommons.org/licenses/by/4.0/',
'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
],
'cc-by-sa' => [
'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
],
'cc-by-nc-sa' => [
'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
],
'cc-0' => [
'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
],
'gfdl' => [
'url' => 'https://www.gnu.org/copyleft/fdl.html',
'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
],
'none' => [
'url' => '',
'icon' => '',
'text' => ''
],
];
/**
* @var HookContainer|null
*/
protected $autoExtensionHookContainer;
protected array $virtualDomains = [];
/**
* Display a short neutral message
*
* @param string|MessageSpecifier $msg String of wikitext that will be converted
* to HTML, or interface message that will be parsed.
* @param mixed ...$params
*/
abstract public function showMessage( $msg, ...$params );
/**
* Display a success message
*
* @param string|MessageSpecifier $msg String of wikitext that will be converted
* to HTML, or interface message that will be parsed.
* @param string|int|float ...$params Message parameters, same as wfMessage().
*/
abstract public function showSuccess( $msg, ...$params );
/**
* Display a warning message
*
* @param string|MessageSpecifier $msg String of wikitext that will be converted
* to HTML, or interface message that will be parsed.
* @param string|int|float ...$params Message parameters, same as wfMessage().
*/
abstract public function showWarning( $msg, ...$params );
/**
* Display an error message
*
* Avoid error fatigue in the installer. Use this only if something the
* user expects has failed and requires intervention to continue.
* If something non-essential failed that can be continued past with
* no action, use a warning instead.
*
* @param string|MessageSpecifier $msg
* @param mixed ...$params
*/
abstract public function showError( $msg, ...$params );
/**
* Show a message to the installing user by using a Status object
* @param Status $status
*/
abstract public function showStatusMessage( Status $status );
/**
* Constructs a Config object that contains configuration settings that should be
* overwritten for the installation process.
*
* @since 1.27
*
* @param Config $baseConfig
*
* @return Config The config to use during installation.
*/
public static function getInstallerConfig( Config $baseConfig ) {
$configOverrides = new HashConfig();
// disable (problematic) object cache types explicitly, preserving all other (working) ones
// bug T113843
$emptyCache = [ 'class' => EmptyBagOStuff::class ];
$objectCaches = [
CACHE_NONE => $emptyCache,
CACHE_DB => $emptyCache,
CACHE_ANYTHING => $emptyCache,
CACHE_MEMCACHED => $emptyCache,
] + $baseConfig->get( MainConfigNames::ObjectCaches );
$configOverrides->set( MainConfigNames::ObjectCaches, $objectCaches );
// Load the installer's i18n.
$messageDirs = $baseConfig->get( MainConfigNames::MessagesDirs );
$messageDirs['MediaWikiInstaller'] = __DIR__ . '/i18n';
$configOverrides->set( MainConfigNames::MessagesDirs, $messageDirs );
$installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
// make sure we use the installer config as the main config
$configRegistry = $baseConfig->get( MainConfigNames::ConfigRegistry );
$configRegistry['main'] = static function () use ( $installerConfig ) {
return $installerConfig;
};
$configOverrides->set( MainConfigNames::ConfigRegistry, $configRegistry );
return $installerConfig;
}
/**
* Constructor, always call this from child classes.
*/
public function __construct() {
$defaultConfig = new GlobalVarConfig(); // all the defaults from config-schema.yaml.
$installerConfig = self::getInstallerConfig( $defaultConfig );
// Disable all storage services, since we don't have any configuration yet!
$this->resetMediaWikiServices( $installerConfig, [], true );
$this->settings = $this->getDefaultSettings();
$this->doEnvironmentPreps();
$this->compiledDBs = [];
foreach ( self::getDBTypes() as $type ) {
$installer = $this->getDBInstaller( $type );
if ( !$installer->isCompiled() ) {
continue;
}
$this->compiledDBs[] = $type;
}
$this->parserTitle = Title::newFromText( 'Installer' );
}
/**
* @return array
*/
private function getDefaultSettings(): array {
global $wgLocaltimezone;
$ret = $this->internalDefaults;
foreach ( self::DEFAULT_VAR_NAMES as $name ) {
$var = "wg{$name}";
$ret[$var] = MainConfigSchema::getDefaultValue( $name );
}
// Set $wgLocaltimezone to the value of the global, which SetupDynamicConfig.php will have
// set to something that is a valid timezone.
$ret['wgLocaltimezone'] = $wgLocaltimezone;
return $ret;
}
/**
* Reset the global service container and associated global state
* to accommodate different stages of the installation.
* @since 1.35
*
* @param Config|null $installerConfig Config override. If null, the previous
* config will be inherited.
* @param array $serviceOverrides Service definition overrides. Values can be null to
* disable specific overrides that would be applied by default, namely
* 'InterwikiLookup' and 'UserOptionsLookup'.
* @param bool $disableStorage Whether MediaWikiServices::disableStorage() should be called.
*
* @return MediaWikiServices
*/
public function resetMediaWikiServices(
?Config $installerConfig = null,
$serviceOverrides = [],
bool $disableStorage = false
) {
global $wgObjectCaches, $wgLang;
// Reset all services and inject config overrides.
// NOTE: This will reset existing instances, but not previous wiring overrides!
MediaWikiServices::resetGlobalInstance( $installerConfig );
$mwServices = MediaWikiServices::getInstance();
if ( $disableStorage ) {
$mwServices->disableStorage();
} else {
// Default to partially disabling services.
$serviceOverrides += [
// Disable interwiki lookup, to avoid database access during parses
'InterwikiLookup' => static function () {
return new NullInterwikiLookup();
},
// Disable user options database fetching, only rely on default options.
'UserOptionsLookup' => static function ( MediaWikiServices $services ) {
return new StaticUserOptionsLookup(
[],
$services->getMainConfig()->get( MainConfigNames::DefaultUserOptions )
);
},
// Restore to default wiring, in case it was overwritten by disableStorage()
'DBLoadBalancer' => static function ( MediaWikiServices $services ) {
return $services->getDBLoadBalancerFactory()->getMainLB();
},
];
}
$lang = $this->getVar( '_UserLang', 'en' );
foreach ( $serviceOverrides as $name => $callback ) {
// Skip if the caller set $callback to null
// to suppress default overrides.
if ( $callback ) {
$mwServices->redefineService( $name, $callback );
}
}
// Disable i18n cache
$mwServices->getLocalisationCache()->disableBackend();
// Set a fake user.
// Note that this will reset the context's language,
// so set the user before setting the language.
$user = User::newFromId( 0 );
StubGlobalUser::setUser( $user );
RequestContext::getMain()->setUser( $user );
// Don't attempt to load user language options (T126177)
// This will be overridden in the web installer with the user-specified language
// Ensure $wgLang does not have a reference to a stale LocalisationCache instance
// (T241638, T261081)
RequestContext::getMain()->setLanguage( $lang );
$wgLang = RequestContext::getMain()->getLanguage();
// Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
// SqlBagOStuff will then throw since we just disabled wfGetDB)
$wgObjectCaches = $mwServices->getMainConfig()->get( MainConfigNames::ObjectCaches );
$this->parserOptions = new ParserOptions( $user ); // language will be wrong :(
// Don't try to access DB before user language is initialised
$this->setParserLanguage( $mwServices->getLanguageFactory()->getLanguage( 'en' ) );
return $mwServices;
}
/**
* Get a list of known DB types.
*
* @return array
*/
public static function getDBTypes() {
return self::$dbTypes;
}
/**
* Do initial checks of the PHP environment. Set variables according to
* the observed environment.
*
* It's possible that this may be called under the CLI SAPI, not the SAPI
* that the wiki will primarily run under. In that case, the subclass should
* initialise variables such as wgScriptPath, before calling this function.
*
* It can already be assumed that a supported PHP version is in use. Under
* the web subclass, it can also be assumed that sessions are working.
*
* @return Status
*/
public function doEnvironmentChecks() {
// PHP version has already been checked by entry scripts
// Show message here for information purposes
$this->showMessage( 'config-env-php', PHP_VERSION );
$good = true;
foreach ( $this->envChecks as $check ) {
$status = $this->$check();
if ( $status === false ) {
$good = false;
}
}
$this->setVar( '_Environment', $good );
return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
}
public function doEnvironmentPreps() {
foreach ( $this->envPreps as $prep ) {
$this->$prep();
}
}
/**
* Set a MW configuration variable, or internal installer configuration variable.
*
* @param string $name
* @param mixed $value
*/
public function setVar( $name, $value ) {
$this->settings[$name] = $value;
}
/**
* Get an MW configuration variable, or internal installer configuration variable.
* The defaults come from MainConfigSchema.
* Installer variables are typically prefixed by an underscore.
*
* @param string $name
* @param mixed|null $default
*
* @return mixed
*/
public function getVar( $name, $default = null ) {
return $this->settings[$name] ?? $default;
}
/**
* Get a list of DBs supported by current PHP setup
*
* @return array
*/
public function getCompiledDBs() {
return $this->compiledDBs;
}
/**
* Get the DatabaseInstaller class name for this type
*
* @param string $type database type ($wgDBtype)
* @return string Class name
* @since 1.30
*/
public static function getDBInstallerClass( $type ) {
return '\\MediaWiki\\Installer\\' . ucfirst( $type ) . 'Installer';
}
/**
* Get an instance of DatabaseInstaller for the specified DB type.
*
* @param mixed $type DB installer for which is needed, false to use default.
*
* @return DatabaseInstaller
*/
public function getDBInstaller( $type = false ) {
if ( !$type ) {
$type = $this->getVar( 'wgDBtype' );
}
$type = strtolower( $type );
if ( !isset( $this->dbInstallers[$type] ) ) {
$class = self::getDBInstallerClass( $type );
$this->dbInstallers[$type] = new $class( $this );
}
return $this->dbInstallers[$type];
}
/**
* Determine if LocalSettings.php exists. If it does, return its variables.
*
* @return array|false
*/
public static function getExistingLocalSettings() {
$IP = wfDetectInstallPath();
// You might be wondering why this is here. Well if you don't do this
// then some poorly-formed extensions try to call their own classes
// after immediately registering them. We really need to get extension
// registration out of the global scope and into a real format.
// @see https://phabricator.wikimedia.org/T69440
global $wgAutoloadClasses;
$wgAutoloadClasses = [];
// LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
// Define the required globals here, to ensure, the functions can do it work correctly.
// phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
global $wgExtensionDirectory, $wgStyleDirectory;
// This will also define MW_CONFIG_FILE
$lsFile = wfDetectLocalSettingsFile( $IP );
// phpcs:ignore Generic.PHP.NoSilencedErrors
$lsExists = @file_exists( $lsFile );
if ( !$lsExists ) {
return false;
}
if ( !str_ends_with( $lsFile, '.php' ) ) {
throw new RuntimeException(
'The installer cannot yet handle non-php settings files: ' . $lsFile . '. ' .
'Use `php maintenance/run.php update` to update an existing installation.'
);
}
unset( $lsExists );
// Extract the defaults into the current scope
foreach ( MainConfigSchema::listDefaultValues( 'wg' ) as $var => $value ) {
$$var = $value;
}
$wgExtensionDirectory = "$IP/extensions";
$wgStyleDirectory = "$IP/skins";
// NOTE: To support YAML settings files, this needs to start using SettingsBuilder.
// However, as of 1.38, YAML settings files are still experimental and
// SettingsBuilder is still unstable. For now, the installer will fail if
// the existing settings file is not PHP. The updater should still work though.
// NOTE: When adding support for YAML settings file, all references to LocalSettings.php
// in localisation messages need to be replaced.
// NOTE: This assumes simple variable assignments. More complex setups may involve
// settings coming from sub-required and/or functions that assign globals
// directly. This is fine here because this isn't used as the "real" include.
// It is only used for reading out a small set of variables that the installer
// validates and/or displays.
require $lsFile;
return get_defined_vars();
}
/**
* Get a fake password for sending back to the user in HTML.
* This is a security mechanism to avoid compromise of the password in the
* event of session ID compromise.
*
* @param string $realPassword
*
* @return string
*/
public function getFakePassword( $realPassword ) {
return str_repeat( '*', strlen( $realPassword ) );
}
/**
* Set a variable which stores a password, except if the new value is a
* fake password in which case leave it as it is.
*
* @param string $name
* @param mixed $value
*/
public function setPassword( $name, $value ) {
if ( !preg_match( '/^\*+$/', $value ) ) {
$this->setVar( $name, $value );
}
}
/**
* On POSIX systems return the primary group of the webserver we're running under.
* On other systems just returns null.
*
* This is used to advice the user that he should chgrp his mw-config/data/images directory as the
* webserver user before he can install.
*
* Public because SqliteInstaller needs it, and doesn't subclass Installer.
*
* @return mixed
*/
public static function maybeGetWebserverPrimaryGroup() {
if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
# I don't know this, this isn't UNIX.
return null;
}
# posix_getegid() *not* getmygid() because we want the group of the webserver,
# not whoever owns the current script.
$gid = posix_getegid();
return posix_getpwuid( $gid )['name'] ?? null;
}
/**
* Convert wikitext $text to HTML.
*
* This is potentially error prone since many parser features require a complete
* installed MW database. The solution is to just not use those features when you
* write your messages. This appears to work well enough. Basic formatting and
* external links work just fine.
*
* But in case a translator decides to throw in a "#ifexist" or internal link or
* whatever, this function is guarded to catch the attempted DB access and to present
* some fallback text.
*
* @param string $text
* @param bool $lineStart
* @return string
*/
public function parse( $text, $lineStart = false ) {
$parser = MediaWikiServices::getInstance()->getParser();
try {
$out = $parser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
$pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
// TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
$html = $pipeline->run( $out, $this->parserOptions, [
'enableSectionEditLinks' => false,
'unwrap' => true,
] )->getContentHolderText();
$html = Parser::stripOuterParagraph( $html );
} catch ( ServiceDisabledException $e ) {
$html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
}
return $html;
}
/**
* @return ParserOptions
*/
public function getParserOptions() {
return $this->parserOptions;
}
public function disableLinkPopups() {
// T317647: This ParserOptions method is deprecated; we should be
// updating ExternalLinkTarget in the Configuration instead.
$this->parserOptions->setExternalLinkTarget( false );
}
public function restoreLinkPopups() {
// T317647: This ParserOptions method is deprecated; we should be
// updating ExternalLinkTarget in the Configuration instead.
global $wgExternalLinkTarget;
$this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
}
/**
* Install step which adds a row to the site_stats table with appropriate
* initial values.
*
* @param DatabaseInstaller $installer
*
* @return Status
*/
public function populateSiteStats( DatabaseInstaller $installer ) {
$status = $installer->getConnection( DatabaseInstaller::CONN_CREATE_TABLES );
if ( !$status->isOK() ) {
return $status;
}
$status->getDB()->newInsertQueryBuilder()
->insertInto( 'site_stats' )
->ignore()
->row( [
'ss_row_id' => 1,
'ss_total_edits' => 0,
'ss_good_articles' => 0,
'ss_total_pages' => 0,
'ss_users' => 0,
'ss_active_users' => 0,
'ss_images' => 0
] )
->caller( __METHOD__ )
->execute();
return Status::newGood();
}
/**
* Environment check for DB types.
* @return bool
*/
protected function envCheckDB() {
global $wgLang;
/** @var string|null $dbType The user-specified database type */
$dbType = $this->getVar( 'wgDBtype' );
$allNames = [];
// Messages: config-type-mysql, config-type-postgres, config-type-sqlite
foreach ( self::getDBTypes() as $name ) {
$allNames[] = wfMessage( "config-type-$name" )->text();
}
$databases = $this->getCompiledDBs();
$databases = array_flip( $databases );
$ok = true;
foreach ( $databases as $db => $_ ) {
$installer = $this->getDBInstaller( $db );
$status = $installer->checkPrerequisites();
if ( !$status->isGood() ) {
if ( !$this instanceof WebInstaller && $db === $dbType ) {
// Strictly check the key database type instead of just outputting message
// Note: No perform this check run from the web installer, since this method always called by
// the welcome page under web installation, so $dbType will always be 'mysql'
$ok = false;
}
$this->showStatusMessage( $status );
unset( $databases[$db] );
}
}
$databases = array_flip( $databases );
if ( !$databases ) {
$this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
return false;
}
return $ok;
}
/**
* Check for known PCRE-related compatibility issues.
*
* @note We don't bother checking for Unicode support here. If it were
* missing, the parser would probably throw an exception before the
* result of this check is shown to the user.
*
* @return bool
*/
protected function envCheckPCRE() {
// PCRE2 must be compiled using NEWLINE_DEFAULT other than 4 (ANY);
// otherwise, it will misidentify UTF-8 trailing byte value 0x85
// as a line ending character when in non-UTF mode.
if ( preg_match( '/^b.*c$/', 'bÄ…c' ) === 0 ) {
$this->showError( 'config-pcre-invalid-newline' );
return false;
}
return true;
}
/**
* Environment check for available memory.
* @return bool
*/
protected function envCheckMemory() {
$limit = ini_get( 'memory_limit' );
if ( !$limit || $limit == -1 ) {
return true;
}
$n = wfShorthandToInteger( $limit );
if ( $n < $this->minMemorySize * 1024 * 1024 ) {
$newLimit = "{$this->minMemorySize}M";
if ( ini_set( "memory_limit", $newLimit ) === false ) {
$this->showMessage( 'config-memory-bad', $limit );
} else {
$this->showMessage( 'config-memory-raised', $limit, $newLimit );
$this->setVar( '_RaiseMemory', true );
}
}
return true;
}
/**
* Environment check for compiled object cache types.
*/
protected function envCheckCache() {
$caches = [];
foreach ( $this->objectCaches as $name => $function ) {
if ( function_exists( $function ) ) {
$caches[$name] = true;
}
}
if ( !$caches ) {
$this->showMessage( 'config-no-cache-apcu' );
}
$this->setVar( '_Caches', $caches );
}
/**
* Scare user to death if they have mod_security or mod_security2
* @return bool
*/
protected function envCheckModSecurity() {
if ( self::apacheModulePresent( 'mod_security' )
|| self::apacheModulePresent( 'mod_security2' ) ) {
$this->showMessage( 'config-mod-security' );
}
return true;
}
/**
* Search for GNU diff3.
* @return bool
*/
protected function envCheckDiff3() {
$names = [ "gdiff3", "diff3" ];
if ( wfIsWindows() ) {
$names[] = 'diff3.exe';
}
$versionInfo = [ '--version', 'GNU diffutils' ];
$diff3 = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
if ( $diff3 ) {
$this->setVar( 'wgDiff3', $diff3 );
} else {
$this->setVar( 'wgDiff3', false );
$this->showMessage( 'config-diff3-bad' );
}
return true;
}
/**
* Environment check for ImageMagick and GD.
* @return bool
*/
protected function envCheckGraphics() {
$names = wfIsWindows() ? 'convert.exe' : 'convert';
$versionInfo = [ '-version', 'ImageMagick' ];
$convert = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
$this->setVar( 'wgImageMagickConvertCommand', '' );
if ( $convert ) {
$this->setVar( 'wgImageMagickConvertCommand', $convert );
$this->showMessage( 'config-imagemagick', $convert );
} elseif ( function_exists( 'imagejpeg' ) ) {
$this->showMessage( 'config-gd' );
} else {
$this->showMessage( 'config-no-scaling' );
}
return true;
}
/**
* Search for git.
*
* @since 1.22
* @return bool
*/
protected function envCheckGit() {
$names = wfIsWindows() ? 'git.exe' : 'git';
$versionInfo = [ '--version', 'git version' ];
$git = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
if ( $git ) {
$this->setVar( 'wgGitBin', $git );
$this->showMessage( 'config-git', $git );
} else {
$this->setVar( 'wgGitBin', false );
$this->showMessage( 'config-git-bad' );
}
return true;
}
/**
* Environment check to inform user which server we've assumed.
*
* @return bool
*/
protected function envCheckServer() {
$server = $this->envGetDefaultServer();
if ( $server !== null ) {
$this->showMessage( 'config-using-server', $server );
}
return true;
}
/**
* Environment check to inform user which paths we've assumed.
*
* @return bool
*/
protected function envCheckPath() {
$this->showMessage(
'config-using-uri',
$this->getVar( 'wgServer' ),
$this->getVar( 'wgScriptPath' )
);
return true;
}
/**
* Environment check for the permissions of the uploads directory
* @return bool
*/
protected function envCheckUploadsDirectory() {
global $IP;
$dir = $IP . '/images/';
$url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
$safe = !$this->dirIsExecutable( $dir, $url );
if ( !$safe ) {
$this->showWarning( 'config-uploads-not-safe', $dir );
}
return true;
}
protected function envCheckUploadsServerResponse() {
$url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/README';
$httpRequestFactory = MediaWikiServices::getInstance()->getHttpRequestFactory();
$status = null;
$req = $httpRequestFactory->create(
$url,
[
'method' => 'GET',
'timeout' => 3,
'followRedirects' => true
],
__METHOD__
);
try {
$status = $req->execute();
} catch ( Exception $e ) {
// HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
// extension.
}
if ( !$status || !$status->isGood() ) {
$this->showWarning( 'config-uploads-security-requesterror', 'X-Content-Type-Options: nosniff' );
return true;
}
$headerValue = $req->getResponseHeader( 'X-Content-Type-Options' ) ?? '';
$responseList = Header::splitList( $headerValue );
if ( !in_array( 'nosniff', $responseList, true ) ) {
$this->showWarning( 'config-uploads-security-headers', 'X-Content-Type-Options: nosniff' );
}
return true;
}
/**
* Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
* hard to support, so let's at least warn people.
*
* @return bool
*/
protected function envCheck64Bit() {
if ( PHP_INT_SIZE == 4 ) {
$this->showMessage( 'config-using-32bit' );
}
return true;
}
/**
* Check and display the libicu and Unicode versions
*/
protected function envCheckLibicu() {
$unicodeVersion = implode( '.', array_slice( IntlChar::getUnicodeVersion(), 0, 3 ) );
$this->showMessage( 'config-env-icu', INTL_ICU_VERSION, $unicodeVersion );
}
/**
* Environment prep for the server hostname.
*/
protected function envPrepServer() {
$server = $this->envGetDefaultServer();
if ( $server !== null ) {
$this->setVar( 'wgServer', $server );
}
}
/**
* Helper function to be called from envPrepServer()
* @return string
*/
abstract protected function envGetDefaultServer();
/**
* Environment prep for setting $IP and $wgScriptPath.
*/
protected function envPrepPath() {
global $IP;
$IP = dirname( dirname( __DIR__ ) );
$this->setVar( 'IP', $IP );
}
/**
* Checks if scripts located in the given directory can be executed via the given URL.
*
* Used only by environment checks.
* @param string $dir
* @param string $url
* @return bool|int|string
*/
public function dirIsExecutable( $dir, $url ) {
$scriptTypes = [
'php' => [
"<?php echo 'exec';",
"#!/var/env php\n<?php echo 'exec';",
],
];
// it would be good to check other popular languages here, but it'll be slow.
// TODO no need to have a loop if there is going to only be one script type
$httpRequestFactory = MediaWikiServices::getInstance()->getHttpRequestFactory();
AtEase::suppressWarnings();
foreach ( $scriptTypes as $ext => $contents ) {
foreach ( $contents as $source ) {
$file = 'exectest.' . $ext;
if ( !file_put_contents( $dir . $file, $source ) ) {
break;
}
try {
$text = $httpRequestFactory->get(
$url . $file,
[ 'timeout' => 3 ],
__METHOD__
);
} catch ( Exception $e ) {
// HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
// extension.
$text = null;
}
unlink( $dir . $file );
if ( $text == 'exec' ) {
AtEase::restoreWarnings();
return $ext;
}
}
}
AtEase::restoreWarnings();
return false;
}
/**
* Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
*
* @param string $moduleName Name of module to check.
* @return bool
*/
public static function apacheModulePresent( $moduleName ) {
if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
return true;
}
// try it the hard way
ob_start();
phpinfo( INFO_MODULES );
$info = ob_get_clean();
return strpos( $info, $moduleName ) !== false;
}
/**
* ParserOptions are constructed before we determined the language, so fix it
*
* @param Language $lang
*/
public function setParserLanguage( $lang ) {
$this->parserOptions->setTargetLanguage( $lang );
$this->parserOptions->setUserLang( $lang );
}
/**
* Overridden by WebInstaller to provide lastPage parameters.
* @param string $page
* @return string
*/
protected function getDocUrl( $page ) {
return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
}
/**
* Find extensions or skins in a subdirectory of $IP.
* Returns an array containing the value for 'Name' for each found extension.
*
* @param string $directory Directory to search in, relative to $IP, must be either "extensions"
* or "skins"
* @return Status An object containing an error list. If there were no errors, an associative
* array of information about the extension can be found in $status->value.
*/
public function findExtensions( $directory = 'extensions' ) {
switch ( $directory ) {
case 'extensions':
return $this->findExtensionsByType( 'extension', 'extensions' );
case 'skins':
return $this->findExtensionsByType( 'skin', 'skins' );
default:
throw new InvalidArgumentException( "Invalid extension type" );
}
}
/**
* Find extensions or skins, and return an array containing the value for 'Name' for each found
* extension.
*
* @param string $type Either "extension" or "skin"
* @param string $directory Directory to search in, relative to $IP
* @return Status An object containing an error list. If there were no errors, an associative
* array of information about the extension can be found in $status->value.
*/
protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
if ( $this->getVar( 'IP' ) === null ) {
return Status::newGood( [] );
}
$extDir = $this->getVar( 'IP' ) . '/' . $directory;
if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
return Status::newGood( [] );
}
$dh = opendir( $extDir );
$exts = [];
$status = new Status;
// phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
while ( ( $file = readdir( $dh ) ) !== false ) {
// skip non-dirs and hidden directories
if ( !is_dir( "$extDir/$file" ) || $file[0] === '.' ) {
continue;
}
$extStatus = $this->getExtensionInfo( $type, $directory, $file );
if ( $extStatus->isOK() ) {
$exts[$file] = $extStatus->value;
} elseif ( $extStatus->hasMessage( 'config-extension-not-found' ) ) {
// (T225512) The directory is not actually an extension. Downgrade to warning.
$status->warning( 'config-extension-not-found', $file );
} else {
$status->merge( $extStatus );
}
}
closedir( $dh );
uksort( $exts, 'strnatcasecmp' );
$status->value = $exts;
return $status;
}
/**
* @param string $type Either "extension" or "skin"
* @param string $parentRelPath The parent directory relative to $IP
* @param string $name The extension or skin name
* @return Status An object containing an error list. If there were no errors, an associative
* array of information about the extension can be found in $status->value.
*/
protected function getExtensionInfo( $type, $parentRelPath, $name ) {
if ( $this->getVar( 'IP' ) === null ) {
throw new RuntimeException( 'Cannot find extensions since the IP variable is not yet set' );
}
if ( $type !== 'extension' && $type !== 'skin' ) {
throw new InvalidArgumentException( "Invalid extension type" );
}
$absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
$relDir = "../$parentRelPath/$name";
if ( !is_dir( $absDir ) ) {
return Status::newFatal( 'config-extension-not-found', $name );
}
$jsonFile = $type . '.json';
$fullJsonFile = "$absDir/$jsonFile";
$isJson = file_exists( $fullJsonFile );
$isPhp = false;
if ( !$isJson ) {
// Only fallback to PHP file if JSON doesn't exist
$fullPhpFile = "$absDir/$name.php";
$isPhp = file_exists( $fullPhpFile );
}
if ( !$isJson && !$isPhp ) {
return Status::newFatal( 'config-extension-not-found', $name );
}
// Extension exists. Now see if there are screenshots
$info = [];
if ( is_dir( "$absDir/screenshots" ) ) {
$paths = glob( "$absDir/screenshots/*.png" );
foreach ( $paths as $path ) {
$info['screenshots'][] = str_replace( $absDir, $relDir, $path );
}
}
if ( $isJson ) {
$jsonStatus = $this->readExtension( $fullJsonFile );
if ( !$jsonStatus->isOK() ) {
return $jsonStatus;
}
$info += $jsonStatus->value;
}
return Status::newGood( $info );
}
/**
* @param string $fullJsonFile
* @param array $extDeps
* @param array $skinDeps
*
* @return Status On success, an array of extension information is in $status->value. On
* failure, the Status object will have an error list.
*/
private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
$load = [
$fullJsonFile => 1
];
if ( $extDeps ) {
$extDir = $this->getVar( 'IP' ) . '/extensions';
foreach ( $extDeps as $dep ) {
$fname = "$extDir/$dep/extension.json";
if ( !file_exists( $fname ) ) {
return Status::newFatal( 'config-extension-not-found', $dep );
}
$load[$fname] = 1;
}
}
if ( $skinDeps ) {
$skinDir = $this->getVar( 'IP' ) . '/skins';
foreach ( $skinDeps as $dep ) {
$fname = "$skinDir/$dep/skin.json";
if ( !file_exists( $fname ) ) {
return Status::newFatal( 'config-extension-not-found', $dep );
}
$load[$fname] = 1;
}
}
$registry = new ExtensionRegistry();
try {
$info = $registry->readFromQueue( $load );
} catch ( ExtensionDependencyError $e ) {
if ( $e->incompatibleCore || $e->incompatibleSkins
|| $e->incompatibleExtensions
) {
// If something is incompatible with a dependency, we have no real
// option besides skipping it
return Status::newFatal( 'config-extension-dependency',
basename( dirname( $fullJsonFile ) ), $e->getMessage() );
} elseif ( $e->missingExtensions || $e->missingSkins ) {
// There's an extension missing in the dependency tree,
// so add those to the dependency list and try again
$status = $this->readExtension(
$fullJsonFile,
array_merge( $extDeps, $e->missingExtensions ),
array_merge( $skinDeps, $e->missingSkins )
);
if ( !$status->isOK() && !$status->hasMessage( 'config-extension-dependency' ) ) {
$status = Status::newFatal( 'config-extension-dependency',
basename( dirname( $fullJsonFile ) ), $status->getMessage() );
}
return $status;
}
// Some other kind of dependency error?
return Status::newFatal( 'config-extension-dependency',
basename( dirname( $fullJsonFile ) ), $e->getMessage() );
}
$ret = [];
// The order of credits will be the order of $load,
// so the first extension is the one we want to load,
// everything else is a dependency
$i = 0;
foreach ( $info['credits'] as $credit ) {
$i++;
if ( $i == 1 ) {
// Extension we want to load
continue;
}
$type = basename( $credit['path'] ) === 'skin.json' ? 'skins' : 'extensions';
$ret['requires'][$type][] = $credit['name'];
}
$credits = array_values( $info['credits'] )[0];
if ( isset( $credits['url'] ) ) {
$ret['url'] = $credits['url'];
}
$ret['type'] = $credits['type'];
return Status::newGood( $ret );
}
/**
* Returns a default value to be used for $wgDefaultSkin: normally the DefaultSkin from
* config-schema.yaml, but will fall back to another if the default skin is missing
* and some other one is present instead.
*
* @param string[] $skinNames Names of installed skins.
* @return string
*/
public function getDefaultSkin( array $skinNames ) {
$defaultSkin = $GLOBALS['wgDefaultSkin'];
if ( in_array( 'vector', $skinNames ) ) {
$skinNames[] = 'vector-2022';
}
// T346332: Minerva skin uses different name from its directory name
if ( in_array( 'minervaneue', $skinNames ) ) {
$minervaNeue = array_search( 'minervaneue', $skinNames );
$skinNames[$minervaNeue] = 'minerva';
}
if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
return $defaultSkin;
} else {
return $skinNames[0];
}
}
/**
* Installs the auto-detected extensions.
*
* @return Status
*/
protected function includeExtensions() {
// Marker for DatabaseUpdater::loadExtensions so we don't
// double load extensions
define( 'MW_EXTENSIONS_LOADED', true );
$legacySchemaHooks = $this->getAutoExtensionLegacyHooks();
$data = $this->getAutoExtensionData();
if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
$legacySchemaHooks = array_merge( $legacySchemaHooks,
$data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] );
}
$extDeprecatedHooks = $data['attributes']['DeprecatedHooks'] ?? [];
$this->autoExtensionHookContainer = new HookContainer(
new StaticHookRegistry(
[ 'LoadExtensionSchemaUpdates' => $legacySchemaHooks ],
$data['attributes']['Hooks'] ?? [],
$extDeprecatedHooks
),
MediaWikiServices::getInstance()->getObjectFactory()
);
$this->virtualDomains = $data['attributes']['DatabaseVirtualDomains'] ?? [];
return Status::newGood();
}
/**
* Auto-detect extensions with an old style .php registration file, load
* the extensions, and return the merged $wgHooks array.
*
* @suppress SecurityCheck-PathTraversal It thinks $exts/$IP is user controlled but they are not.
* @return array
*/
protected function getAutoExtensionLegacyHooks() {
$exts = $this->getVar( '_Extensions' );
$installPath = $this->getVar( 'IP' );
$files = [];
foreach ( $exts as $e ) {
if ( file_exists( "$installPath/extensions/$e/$e.php" ) ) {
$files[] = "$installPath/extensions/$e/$e.php";
}
}
if ( $files ) {
return $this->includeExtensionFiles( $files );
} else {
return [];
}
}
/**
* Include the specified extension PHP files. Populate $wgAutoloadClasses
* and return the LoadExtensionSchemaUpdates hooks.
*
* @param string[] $files
* @return array LoadExtensionSchemaUpdates legacy hooks
*/
protected function includeExtensionFiles( $files ) {
global $IP;
$IP = $this->getVar( 'IP' );
/**
* We need to define the $wgXyz variables before including extensions to avoid
* warnings about unset variables. However, the only thing we really
* want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
* if the extension has hidden hook registration in $wgExtensionFunctions,
* but we're not opening that can of worms
* @see https://phabricator.wikimedia.org/T28857
*/
// Extract the defaults into the current scope
foreach ( MainConfigSchema::listDefaultValues( 'wg' ) as $var => $value ) {
$$var = $value;
}
// phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
global $wgAutoloadClasses, $wgExtensionDirectory, $wgStyleDirectory;
$wgExtensionDirectory = "$IP/extensions";
$wgStyleDirectory = "$IP/skins";
foreach ( $files as $file ) {
require_once $file;
}
// @phpcs:disable MediaWiki.VariableAnalysis.MisleadingGlobalNames.Misleading$wgHooks
// @phpcs:ignore Generic.Files.LineLength.TooLong
// @phan-suppress-next-line PhanUndeclaredVariable,PhanCoalescingAlwaysNull $wgHooks is defined by MainConfigSchema
$hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ?? [];
// @phpcs:enable MediaWiki.VariableAnalysis.MisleadingGlobalNames.Misleading$wgHooks
// Ignore everyone else's hooks. Lord knows what someone might be doing
// in ParserFirstCallInit (see T29171)
return [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
}
/**
* Auto-detect extensions with an extension.json file. Load the extensions,
* register classes with the autoloader and return the merged registry data.
*
* @return array
*/
protected function getAutoExtensionData() {
$exts = $this->getVar( '_Extensions' );
$installPath = $this->getVar( 'IP' );
$extensionProcessor = new ExtensionProcessor();
foreach ( $exts as $e ) {
$jsonPath = "$installPath/extensions/$e/extension.json";
if ( file_exists( $jsonPath ) ) {
$extensionProcessor->extractInfoFromFile( $jsonPath );
}
}
$autoload = $extensionProcessor->getExtractedAutoloadInfo();
AutoLoader::loadFiles( $autoload['files'] );
AutoLoader::registerClasses( $autoload['classes'] );
AutoLoader::registerNamespaces( $autoload['namespaces'] );
return $extensionProcessor->getExtractedInfo();
}
/**
* Get the hook container previously populated by includeExtensions().
*
* @internal For use by DatabaseInstaller
* @since 1.36
* @return HookContainer
*/
public function getAutoExtensionHookContainer() {
if ( !$this->autoExtensionHookContainer ) {
throw new LogicException( __METHOD__ .
': includeExtensions() has not been called' );
}
return $this->autoExtensionHookContainer;
}
/**
* Get the virtual domains
*
* @internal For use by DatabaseInstaller
* @since 1.42
* @return array
*/
public function getVirtualDomains(): array {
return $this->virtualDomains;
}
/**
* Get an array of install steps. Should always be in the format of
* [
* 'name' => 'someuniquename',
* 'callback' => [ $obj, 'method' ],
* ]
* There must be a config-install-$name message defined per step, which will
* be shown on install.
*
* @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
* @return array[]
* @phan-return array<int,array{name:string,callback:array{0:object,1:string}}>
*/
protected function getInstallSteps( DatabaseInstaller $installer ) {
$coreInstallSteps = [
[ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
[ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
[ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
[ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
[ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
[ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
[ 'name' => 'restore-services', 'callback' => [ $this, 'restoreServices' ] ],
[ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
[ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
];
// Build the array of install steps starting from the core install list,
// then adding any callbacks that wanted to attach after a given step
foreach ( $coreInstallSteps as $step ) {
$this->installSteps[] = $step;
if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
$this->installSteps = array_merge(
$this->installSteps,
$this->extraInstallSteps[$step['name']]
);
}
}
// Prepend any steps that want to be at the beginning
if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
$this->installSteps = array_merge(
$this->extraInstallSteps['BEGINNING'],
$this->installSteps
);
}
// Extensions should always go first, chance to tie into hooks and such
if ( count( $this->getVar( '_Extensions' ) ) ) {
array_unshift( $this->installSteps,
[ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
);
$this->installSteps[] = [
'name' => 'extension-tables',
'callback' => [ $installer, 'createExtensionTables' ]
];
}
return $this->installSteps;
}
/**
* Actually perform the installation.
*
* @param callable $startCB A callback array for the beginning of each step
* @param callable $endCB A callback array for the end of each step
*
* @return Status[]
*/
public function performInstallation( $startCB, $endCB ) {
$installResults = [];
$installer = $this->getDBInstaller();
$installer->preInstall();
$steps = $this->getInstallSteps( $installer );
foreach ( $steps as $stepObj ) {
$name = $stepObj['name'];
call_user_func_array( $startCB, [ $name ] );
// Perform the callback step
$status = call_user_func( $stepObj['callback'], $installer );
// Output and save the results
call_user_func( $endCB, $name, $status );
$installResults[$name] = $status;
// If we've hit some sort of fatal, we need to bail.
// Callback already had a chance to do output above.
if ( !$status->isOK() ) {
break;
}
}
// @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
// $steps has at least one element and that defines $status
if ( $status->isOK() ) {
$this->showSuccess(
'config-install-db-success'
);
$this->setVar( '_InstallDone', true );
}
return $installResults;
}
/**
* Generate $wgSecretKey. Will warn if we had to use an insecure random source.
*
* @return Status
*/
public function generateKeys() {
$keys = [ 'wgSecretKey' => 64 ];
if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
$keys['wgUpgradeKey'] = 16;
}
return $this->doGenerateKeys( $keys );
}
/**
* Restore services that have been redefined in the early stage of installation
* @return Status
*/
public function restoreServices() {
// Apply wgServer, so it's available for database initialization hooks.
$urlOptions = [
UrlUtils::SERVER => $GLOBALS['wgServer'],
];
$connection = $this->getDBInstaller()
->definitelyGetConnection( DatabaseInstaller::CONN_CREATE_TABLES );
$virtualDomains = array_merge(
$this->getVirtualDomains(),
MWLBFactory::CORE_VIRTUAL_DOMAINS
);
$this->resetMediaWikiServices( null, [
'DBLoadBalancerFactory' => static function () use ( $virtualDomains, $connection ) {
return LBFactorySingle::newFromConnection(
$connection,
[ 'virtualDomains' => $virtualDomains ]
);
},
'UrlUtils' => static function ( MediaWikiServices $services ) use ( $urlOptions ) {
return new UrlUtils( $urlOptions );
},
'UserOptionsLookup' => static function ( MediaWikiServices $services ) {
return $services->get( 'UserOptionsManager' );
},
] );
return Status::newGood();
}
/**
* Generate a secret value for variables using a secure generator.
*
* @param array $keys
* @return Status
*/
protected function doGenerateKeys( $keys ) {
foreach ( $keys as $name => $length ) {
$secretKey = MWCryptRand::generateHex( $length );
$this->setVar( $name, $secretKey );
}
return Status::newGood();
}
/**
* Create the first user account, grant it sysop, bureaucrat and interface-admin rights
*
* @return Status
*/
protected function createSysop() {
$name = $this->getVar( '_AdminName' );
$user = User::newFromName( $name );
if ( !$user ) {
// We should've validated this earlier anyway!
return Status::newFatal( 'config-admin-error-user', $name );
}
if ( $user->idForName() == 0 ) {
$user->addToDatabase();
$password = $this->getVar( '_AdminPassword' );
$status = $user->changeAuthenticationData( [
'username' => $user->getName(),
'password' => $password,
'retype' => $password,
] );
if ( !$status->isGood() ) {
return Status::newFatal( 'config-admin-error-password',
$name, $status->getWikiText( false, false, $this->getVar( '_UserLang' ) ) );
}
$userGroupManager = MediaWikiServices::getInstance()->getUserGroupManager();
$userGroupManager->addUserToGroup( $user, 'sysop' );
$userGroupManager->addUserToGroup( $user, 'bureaucrat' );
$userGroupManager->addUserToGroup( $user, 'interface-admin' );
if ( $this->getVar( '_AdminEmail' ) ) {
$user->setEmail( $this->getVar( '_AdminEmail' ) );
}
$user->saveSettings();
// Update user count
$ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
$ssUpdate->doUpdate();
}
if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
return $this->subscribeToMediaWikiAnnounce();
}
return Status::newGood();
}
/**
* @return Status
*/
private function subscribeToMediaWikiAnnounce() {
$status = Status::newGood();
$http = MediaWikiServices::getInstance()->getHttpRequestFactory();
if ( !$http->canMakeRequests() ) {
$status->warning( 'config-install-subscribe-fail',
wfMessage( 'config-install-subscribe-notpossible' ) );
return $status;
}
// Create subscription request
$params = [ 'email' => $this->getVar( '_AdminEmail' ) ];
$req = $http->create( self::MEDIAWIKI_ANNOUNCE_URL . 'anonymous_subscribe',
[ 'method' => 'POST', 'postData' => $params ], __METHOD__ );
// Add headers needed to pass Django's CSRF checks
$token = str_repeat( 'a', 64 );
$req->setHeader( 'Referer', self::MEDIAWIKI_ANNOUNCE_URL );
$req->setHeader( 'Cookie', "csrftoken=$token" );
$req->setHeader( 'X-CSRFToken', $token );
// Send subscription request
$reqStatus = $req->execute();
if ( !$reqStatus->isOK() ) {
$status->warning( 'config-install-subscribe-fail',
Status::wrap( $reqStatus )->getMessage() );
return $status;
}
// Was the request submitted successfully?
// The status message is displayed after a redirect, using Django's messages
// framework, so load the list summary page and look for the expected text.
// (Though parsing the cookie set by the framework may be possible, it isn't
// simple, since the format of the cookie has changed between versions.)
$checkReq = $http->create( self::MEDIAWIKI_ANNOUNCE_URL, [], __METHOD__ );
$checkReq->setCookieJar( $req->getCookieJar() );
if ( !$checkReq->execute()->isOK() ) {
$status->warning( 'config-install-subscribe-possiblefail' );
return $status;
}
$html = $checkReq->getContent();
if ( strpos( $html, 'Please check your inbox for further instructions' ) !== false ) {
// Success
} elseif ( strpos( $html, 'Member already subscribed' ) !== false ) {
$status->warning( 'config-install-subscribe-alreadysubscribed' );
} elseif ( strpos( $html, 'Subscription request already pending' ) !== false ) {
$status->warning( 'config-install-subscribe-alreadypending' );
} else {
$status->warning( 'config-install-subscribe-possiblefail' );
}
return $status;
}
/**
* Insert Main Page with default content.
*
* @param DatabaseInstaller $installer
* @return Status
*/
protected function createMainpage( DatabaseInstaller $installer ) {
$status = Status::newGood();
$title = Title::newMainPage();
if ( $title->exists() ) {
$status->warning( 'config-install-mainpage-exists' );
return $status;
}
try {
$page = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $title );
$content = new WikitextContent(
wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
);
$status = $page->doUserEditContent(
$content,
User::newSystemUser( 'MediaWiki default' ),
'',
EDIT_NEW
);
} catch ( Exception $e ) {
// using raw, because $wgShowExceptionDetails can not be set yet
$status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
}
return $status;
}
/**
* Override the necessary bits of the config to run an installation.
*
* @param SettingsBuilder $settings
*/
public static function overrideConfig( SettingsBuilder $settings ) {
// Use PHP's built-in session handling, since MediaWiki's
// SessionHandler can't work before we have an object cache set up.
if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
define( 'MW_NO_SESSION_HANDLER', 1 );
}
$settings->overrideConfigValues( [
// Don't access the database
MainConfigNames::UseDatabaseMessages => false,
// Don't cache langconv tables
MainConfigNames::LanguageConverterCacheType => CACHE_NONE,
// Don't try to cache ResourceLoader dependencies in the database
MainConfigNames::ResourceLoaderUseObjectCacheForDeps => true,
// Debug-friendly
MainConfigNames::ShowExceptionDetails => true,
MainConfigNames::ShowHostnames => true,
// Don't break forms
MainConfigNames::ExternalLinkTarget => '_blank',
// Allow multiple ob_flush() calls
MainConfigNames::DisableOutputCompression => true,
// Use a sensible cookie prefix (not my_wiki)
MainConfigNames::CookiePrefix => 'mw_installer',
// Some of the environment checks make shell requests, remove limits
MainConfigNames::MaxShellMemory => 0,
// Override the default CookieSessionProvider with a dummy
// implementation that won't stomp on PHP's cookies.
MainConfigNames::SessionProviders => [
[
'class' => InstallerSessionProvider::class,
'args' => [ [
'priority' => 1,
] ]
]
],
// Don't use the DB as the main stash
MainConfigNames::MainStash => CACHE_NONE,
// Don't try to use any object cache for SessionManager either.
MainConfigNames::SessionCacheType => CACHE_NONE,
// Set a dummy $wgServer to bypass the check in Setup.php, the
// web installer will automatically detect it and not use this value.
MainConfigNames::Server => 'https://🌻.invalid',
] );
}
/**
* Add an installation step following the given step.
*
* @param array $callback A valid installation callback array, in this form:
* [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
* @param string $findStep The step to find. Omit to put the step at the beginning
*/
public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
$this->extraInstallSteps[$findStep][] = $callback;
}
/**
* Disable the time limit for execution.
* Some long-running pages (Install, Upgrade) will want to do this
*/
protected function disableTimeLimit() {
AtEase::suppressWarnings();
set_time_limit( 0 );
AtEase::restoreWarnings();
}
}
|