HomeController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin\Controllers;
  4. use PhpMyAdmin\Charsets;
  5. use PhpMyAdmin\CheckUserPrivileges;
  6. use PhpMyAdmin\Config;
  7. use PhpMyAdmin\ConfigStorage\Relation;
  8. use PhpMyAdmin\DatabaseInterface;
  9. use PhpMyAdmin\Git;
  10. use PhpMyAdmin\Html\Generator;
  11. use PhpMyAdmin\LanguageManager;
  12. use PhpMyAdmin\Message;
  13. use PhpMyAdmin\RecentFavoriteTable;
  14. use PhpMyAdmin\ResponseRenderer;
  15. use PhpMyAdmin\Server\Select;
  16. use PhpMyAdmin\Template;
  17. use PhpMyAdmin\ThemeManager;
  18. use PhpMyAdmin\Url;
  19. use PhpMyAdmin\Util;
  20. use PhpMyAdmin\Version;
  21. use function __;
  22. use function count;
  23. use function extension_loaded;
  24. use function file_exists;
  25. use function ini_get;
  26. use function is_string;
  27. use function mb_strlen;
  28. use function preg_match;
  29. use function sprintf;
  30. use const PHP_VERSION;
  31. use const SODIUM_CRYPTO_SECRETBOX_KEYBYTES;
  32. class HomeController extends AbstractController
  33. {
  34. /** @var Config */
  35. private $config;
  36. /** @var ThemeManager */
  37. private $themeManager;
  38. /** @var DatabaseInterface */
  39. private $dbi;
  40. /**
  41. * @var array<int, array<string, string>>
  42. * @psalm-var list<array{message: string, severity: 'warning'|'notice'}>
  43. */
  44. private $errors = [];
  45. public function __construct(
  46. ResponseRenderer $response,
  47. Template $template,
  48. Config $config,
  49. ThemeManager $themeManager,
  50. DatabaseInterface $dbi
  51. ) {
  52. parent::__construct($response, $template);
  53. $this->config = $config;
  54. $this->themeManager = $themeManager;
  55. $this->dbi = $dbi;
  56. }
  57. public function __invoke(): void
  58. {
  59. global $cfg, $server, $collation_connection, $message, $show_query, $db, $table, $errorUrl;
  60. if ($this->response->isAjax() && ! empty($_REQUEST['access_time'])) {
  61. return;
  62. }
  63. $this->addScriptFiles(['home.js']);
  64. // This is for $cfg['ShowDatabasesNavigationAsTree'] = false;
  65. // See: https://github.com/phpmyadmin/phpmyadmin/issues/16520
  66. // The DB is defined here and sent to the JS front-end to refresh the DB tree
  67. $db = $_POST['db'] ?? '';
  68. $table = '';
  69. $show_query = '1';
  70. $errorUrl = Url::getFromRoute('/');
  71. if ($server > 0 && $this->dbi->isSuperUser()) {
  72. $this->dbi->selectDb('mysql');
  73. }
  74. $languageManager = LanguageManager::getInstance();
  75. if (! empty($message)) {
  76. $displayMessage = Generator::getMessage($message);
  77. unset($message);
  78. }
  79. if (isset($_SESSION['partial_logout'])) {
  80. $partialLogout = Message::success(__(
  81. 'You were logged out from one server, to logout completely '
  82. . 'from phpMyAdmin, you need to logout from all servers.'
  83. ))->getDisplay();
  84. unset($_SESSION['partial_logout']);
  85. }
  86. $syncFavoriteTables = RecentFavoriteTable::getInstance('favorite')
  87. ->getHtmlSyncFavoriteTables();
  88. $hasServer = $server > 0 || count($cfg['Servers']) > 1;
  89. if ($hasServer) {
  90. $hasServerSelection = $cfg['ServerDefault'] == 0
  91. || (
  92. $cfg['NavigationDisplayServers']
  93. && (
  94. count($cfg['Servers']) > 1
  95. || ($server == 0 && count($cfg['Servers']) === 1)
  96. )
  97. );
  98. if ($hasServerSelection) {
  99. $serverSelection = Select::render(true, true);
  100. }
  101. if ($server > 0) {
  102. $checkUserPrivileges = new CheckUserPrivileges($this->dbi);
  103. $checkUserPrivileges->getPrivileges();
  104. $charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']);
  105. $collations = Charsets::getCollations($this->dbi, $cfg['Server']['DisableIS']);
  106. $charsetsList = [];
  107. foreach ($charsets as $charset) {
  108. $collationsList = [];
  109. foreach ($collations[$charset->getName()] as $collation) {
  110. $collationsList[] = [
  111. 'name' => $collation->getName(),
  112. 'description' => $collation->getDescription(),
  113. 'is_selected' => $collation_connection === $collation->getName(),
  114. ];
  115. }
  116. $charsetsList[] = [
  117. 'name' => $charset->getName(),
  118. 'description' => $charset->getDescription(),
  119. 'collations' => $collationsList,
  120. ];
  121. }
  122. }
  123. }
  124. $availableLanguages = [];
  125. if (empty($cfg['Lang']) && $languageManager->hasChoice()) {
  126. $availableLanguages = $languageManager->sortedLanguages();
  127. }
  128. $databaseServer = [];
  129. if ($server > 0 && $cfg['ShowServerInfo']) {
  130. $hostInfo = '';
  131. if (! empty($cfg['Server']['verbose'])) {
  132. $hostInfo .= $cfg['Server']['verbose'];
  133. $hostInfo .= ' (';
  134. }
  135. $hostInfo .= $this->dbi->getHostInfo();
  136. if (! empty($cfg['Server']['verbose'])) {
  137. $hostInfo .= ')';
  138. }
  139. $serverCharset = Charsets::getServerCharset($this->dbi, $cfg['Server']['DisableIS']);
  140. $databaseServer = [
  141. 'host' => $hostInfo,
  142. 'type' => Util::getServerType(),
  143. 'connection' => Generator::getServerSSL(),
  144. 'version' => $this->dbi->getVersionString() . ' - ' . $this->dbi->getVersionComment(),
  145. 'protocol' => $this->dbi->getProtoInfo(),
  146. 'user' => $this->dbi->fetchValue('SELECT USER();'),
  147. 'charset' => $serverCharset->getDescription() . ' (' . $serverCharset->getName() . ')',
  148. ];
  149. }
  150. $webServer = [];
  151. if ($cfg['ShowServerInfo']) {
  152. $webServer['software'] = $_SERVER['SERVER_SOFTWARE'] ?? null;
  153. if ($server > 0) {
  154. $clientVersion = $this->dbi->getClientInfo();
  155. if (preg_match('#\d+\.\d+\.\d+#', $clientVersion)) {
  156. $clientVersion = 'libmysql - ' . $clientVersion;
  157. }
  158. $webServer['database'] = $clientVersion;
  159. $webServer['php_extensions'] = Util::listPHPExtensions();
  160. $webServer['php_version'] = PHP_VERSION;
  161. }
  162. }
  163. $relation = new Relation($this->dbi);
  164. if ($server > 0 && $relation->arePmadbTablesAllDisabled() === false) {
  165. $relationParameters = $relation->getRelationParameters();
  166. if (! $relationParameters->hasAllFeatures() && $cfg['PmaNoRelation_DisableWarning'] == false) {
  167. $messageText = __(
  168. 'The phpMyAdmin configuration storage is not completely '
  169. . 'configured, some extended features have been deactivated. '
  170. . '%sFind out why%s. '
  171. );
  172. if ($cfg['ZeroConf'] == true) {
  173. $messageText .= '<br>' .
  174. __('Or alternately go to \'Operations\' tab of any database to set it up there.');
  175. }
  176. $messageInstance = Message::notice($messageText);
  177. $messageInstance->addParamHtml(
  178. '<a href="' . Url::getFromRoute('/check-relations')
  179. . '" data-post="' . Url::getCommon() . '">'
  180. );
  181. $messageInstance->addParamHtml('</a>');
  182. /* Show error if user has configured something, notice elsewhere */
  183. if (! empty($cfg['Servers'][$server]['pmadb'])) {
  184. $messageInstance->isError(true);
  185. }
  186. $configStorageMessage = $messageInstance->getDisplay();
  187. }
  188. }
  189. $this->checkRequirements();
  190. $git = new Git($this->config->get('ShowGitRevision') ?? true);
  191. $this->render('home/index', [
  192. 'db' => $db,
  193. 'table' => $table,
  194. 'message' => $displayMessage ?? '',
  195. 'partial_logout' => $partialLogout ?? '',
  196. 'is_git_revision' => $git->isGitRevision(),
  197. 'server' => $server,
  198. 'sync_favorite_tables' => $syncFavoriteTables,
  199. 'has_server' => $hasServer,
  200. 'is_demo' => $cfg['DBG']['demo'],
  201. 'has_server_selection' => $hasServerSelection ?? false,
  202. 'server_selection' => $serverSelection ?? '',
  203. 'has_change_password_link' => ($cfg['Server']['auth_type'] ?? '') !== 'config' && $cfg['ShowChgPassword'],
  204. 'charsets' => $charsetsList ?? [],
  205. 'available_languages' => $availableLanguages,
  206. 'database_server' => $databaseServer,
  207. 'web_server' => $webServer,
  208. 'show_php_info' => $cfg['ShowPhpInfo'],
  209. 'is_version_checked' => $cfg['VersionCheck'],
  210. 'phpmyadmin_version' => Version::VERSION,
  211. 'phpmyadmin_major_version' => Version::SERIES,
  212. 'config_storage_message' => $configStorageMessage ?? '',
  213. 'has_theme_manager' => $cfg['ThemeManager'],
  214. 'themes' => $this->themeManager->getThemesArray(),
  215. 'errors' => $this->errors,
  216. ]);
  217. }
  218. private function checkRequirements(): void
  219. {
  220. global $cfg, $server;
  221. $this->checkPhpExtensionsRequirements();
  222. if ($cfg['LoginCookieValidityDisableWarning'] == false) {
  223. /**
  224. * Check whether session.gc_maxlifetime limits session validity.
  225. */
  226. $gc_time = (int) ini_get('session.gc_maxlifetime');
  227. if ($gc_time < $cfg['LoginCookieValidity']) {
  228. $this->errors[] = [
  229. 'message' => __(
  230. 'Your PHP parameter [a@https://www.php.net/manual/en/session.' .
  231. 'configuration.php#ini.session.gc-maxlifetime@_blank]session.' .
  232. 'gc_maxlifetime[/a] is lower than cookie validity configured ' .
  233. 'in phpMyAdmin, because of this, your login might expire sooner ' .
  234. 'than configured in phpMyAdmin.'
  235. ),
  236. 'severity' => 'warning',
  237. ];
  238. }
  239. }
  240. /**
  241. * Check whether LoginCookieValidity is limited by LoginCookieStore.
  242. */
  243. if ($cfg['LoginCookieStore'] != 0 && $cfg['LoginCookieStore'] < $cfg['LoginCookieValidity']) {
  244. $this->errors[] = [
  245. 'message' => __(
  246. 'Login cookie store is lower than cookie validity configured in ' .
  247. 'phpMyAdmin, because of this, your login will expire sooner than ' .
  248. 'configured in phpMyAdmin.'
  249. ),
  250. 'severity' => 'warning',
  251. ];
  252. }
  253. /**
  254. * Warning if using the default MySQL controluser account
  255. */
  256. if (
  257. isset($cfg['Server']['controluser'], $cfg['Server']['controlpass'])
  258. && $server != 0
  259. && $cfg['Server']['controluser'] === 'pma'
  260. && $cfg['Server']['controlpass'] === 'pmapass'
  261. ) {
  262. $this->errors[] = [
  263. 'message' => __(
  264. 'Your server is running with default values for the ' .
  265. 'controluser and password (controlpass) and is open to ' .
  266. 'intrusion; you really should fix this security weakness' .
  267. ' by changing the password for controluser \'pma\'.'
  268. ),
  269. 'severity' => 'warning',
  270. ];
  271. }
  272. /**
  273. * Check if user does not have defined blowfish secret and it is being used.
  274. */
  275. if (! empty($_SESSION['encryption_key'])) {
  276. $encryptionKeyLength = 0;
  277. // This can happen if the user did use getenv() to set blowfish_secret
  278. if (is_string($cfg['blowfish_secret'])) {
  279. $encryptionKeyLength = mb_strlen($cfg['blowfish_secret'], '8bit');
  280. }
  281. if ($encryptionKeyLength < SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
  282. $this->errors[] = [
  283. 'message' => __(
  284. 'The configuration file needs a valid key for cookie encryption.'
  285. . ' A temporary key was automatically generated for you.'
  286. . ' Please refer to the [doc@cfg_blowfish_secret]documentation[/doc].'
  287. ),
  288. 'severity' => 'warning',
  289. ];
  290. } elseif ($encryptionKeyLength > SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
  291. $this->errors[] = [
  292. 'message' => sprintf(
  293. __(
  294. 'The cookie encryption key in the configuration file is longer than necessary.'
  295. . ' It should only be %d bytes long.'
  296. . ' Please refer to the [doc@cfg_blowfish_secret]documentation[/doc].'
  297. ),
  298. SODIUM_CRYPTO_SECRETBOX_KEYBYTES
  299. ),
  300. 'severity' => 'warning',
  301. ];
  302. }
  303. }
  304. /**
  305. * Check for existence of config directory which should not exist in
  306. * production environment.
  307. */
  308. if (@file_exists(ROOT_PATH . 'config')) {
  309. $this->errors[] = [
  310. 'message' => __(
  311. 'Directory [code]config[/code], which is used by the setup script, ' .
  312. 'still exists in your phpMyAdmin directory. It is strongly ' .
  313. 'recommended to remove it once phpMyAdmin has been configured. ' .
  314. 'Otherwise the security of your server may be compromised by ' .
  315. 'unauthorized people downloading your configuration.'
  316. ),
  317. 'severity' => 'warning',
  318. ];
  319. }
  320. /**
  321. * Warning about Suhosin only if its simulation mode is not enabled
  322. */
  323. if (
  324. $cfg['SuhosinDisableWarning'] == false
  325. && ini_get('suhosin.request.max_value_length')
  326. && ini_get('suhosin.simulation') == '0'
  327. ) {
  328. $this->errors[] = [
  329. 'message' => sprintf(
  330. __(
  331. 'Server running with Suhosin. Please refer to %sdocumentation%s for possible issues.'
  332. ),
  333. '[doc@faq1-38]',
  334. '[/doc]'
  335. ),
  336. 'severity' => 'warning',
  337. ];
  338. }
  339. /* Missing template cache */
  340. if ($this->config->getTempDir('twig') === null) {
  341. $this->errors[] = [
  342. 'message' => sprintf(
  343. __(
  344. 'The $cfg[\'TempDir\'] (%s) is not accessible. ' .
  345. 'phpMyAdmin is not able to cache templates and will ' .
  346. 'be slow because of this.'
  347. ),
  348. $this->config->get('TempDir')
  349. ),
  350. 'severity' => 'warning',
  351. ];
  352. }
  353. $this->checkLanguageStats();
  354. }
  355. private function checkLanguageStats(): void
  356. {
  357. global $cfg, $lang;
  358. /**
  359. * Warning about incomplete translations.
  360. *
  361. * The data file is created while creating release by ./scripts/remove-incomplete-mo
  362. */
  363. if (! @file_exists(ROOT_PATH . 'libraries/language_stats.inc.php')) {
  364. return;
  365. }
  366. /** @psalm-suppress MissingFile */
  367. include ROOT_PATH . 'libraries/language_stats.inc.php';
  368. /*
  369. * This message is intentionally not translated, because we're
  370. * handling incomplete translations here and focus on english
  371. * speaking users.
  372. */
  373. if (
  374. ! isset($GLOBALS['language_stats'][$lang])
  375. || $GLOBALS['language_stats'][$lang] >= $cfg['TranslationWarningThreshold']
  376. ) {
  377. return;
  378. }
  379. $this->errors[] = [
  380. 'message' => 'You are using an incomplete translation, please help to make it '
  381. . 'better by [a@https://www.phpmyadmin.net/translate/'
  382. . '@_blank]contributing[/a].',
  383. 'severity' => 'notice',
  384. ];
  385. }
  386. private function checkPhpExtensionsRequirements(): void
  387. {
  388. /**
  389. * mbstring is used for handling multibytes inside parser, so it is good
  390. * to tell user something might be broken without it, see bug #1063149.
  391. */
  392. if (! extension_loaded('mbstring')) {
  393. $this->errors[] = [
  394. 'message' => __(
  395. 'The mbstring PHP extension was not found and you seem to be using'
  396. . ' a multibyte charset. Without the mbstring extension phpMyAdmin'
  397. . ' is unable to split strings correctly and it may result in'
  398. . ' unexpected results.'
  399. ),
  400. 'severity' => 'warning',
  401. ];
  402. }
  403. /**
  404. * Missing functionality
  405. */
  406. if (extension_loaded('curl') || ini_get('allow_url_fopen')) {
  407. return;
  408. }
  409. $this->errors[] = [
  410. 'message' => __(
  411. 'The curl extension was not found and allow_url_fopen is '
  412. . 'disabled. Due to this some features such as error reporting '
  413. . 'or version check are disabled.'
  414. ),
  415. 'severity' => 'notice',
  416. ];
  417. }
  418. }