Welcome to mirror list, hosted at ThFree Co, Russian Federation.

HomeController.php « Controllers « classes « libraries - github.com/phpmyadmin/phpmyadmin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 998cc3b4ce33d63ee65b4c05665b8bf328ab22f7 (plain)
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
<?php

declare(strict_types=1);

namespace PhpMyAdmin\Controllers;

use PhpMyAdmin\Charsets;
use PhpMyAdmin\CheckUserPrivileges;
use PhpMyAdmin\Config;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Git;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\LanguageManager;
use PhpMyAdmin\Message;
use PhpMyAdmin\RecentFavoriteTable;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Server\Select;
use PhpMyAdmin\Template;
use PhpMyAdmin\ThemeManager;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use PhpMyAdmin\Version;

use function __;
use function count;
use function extension_loaded;
use function file_exists;
use function ini_get;
use function mb_strlen;
use function preg_match;
use function sprintf;

use const PHP_VERSION;
use const SODIUM_CRYPTO_SECRETBOX_KEYBYTES;

class HomeController extends AbstractController
{
    /** @var Config */
    private $config;

    /** @var ThemeManager */
    private $themeManager;

    /** @var DatabaseInterface */
    private $dbi;

    /**
     * @var array<int, array<string, string>>
     * @psalm-var list<array{message: string, severity: 'warning'|'notice'}>
     */
    private $errors = [];

    public function __construct(
        ResponseRenderer $response,
        Template $template,
        Config $config,
        ThemeManager $themeManager,
        DatabaseInterface $dbi
    ) {
        parent::__construct($response, $template);
        $this->config = $config;
        $this->themeManager = $themeManager;
        $this->dbi = $dbi;
    }

    public function __invoke(): void
    {
        global $cfg, $server, $collation_connection, $message, $show_query, $db, $table, $errorUrl;

        if ($this->response->isAjax() && ! empty($_REQUEST['access_time'])) {
            return;
        }

        $this->addScriptFiles(['home.js']);

        // This is for $cfg['ShowDatabasesNavigationAsTree'] = false;
        // See: https://github.com/phpmyadmin/phpmyadmin/issues/16520
        // The DB is defined here and sent to the JS front-end to refresh the DB tree
        $db = $_POST['db'] ?? '';
        $table = '';
        $show_query = '1';
        $errorUrl = Url::getFromRoute('/');

        if ($server > 0 && $this->dbi->isSuperUser()) {
            $this->dbi->selectDb('mysql');
        }

        $languageManager = LanguageManager::getInstance();

        if (! empty($message)) {
            $displayMessage = Generator::getMessage($message);
            unset($message);
        }

        if (isset($_SESSION['partial_logout'])) {
            $partialLogout = Message::success(__(
                'You were logged out from one server, to logout completely '
                . 'from phpMyAdmin, you need to logout from all servers.'
            ))->getDisplay();
            unset($_SESSION['partial_logout']);
        }

        $syncFavoriteTables = RecentFavoriteTable::getInstance('favorite')
            ->getHtmlSyncFavoriteTables();

        $hasServer = $server > 0 || count($cfg['Servers']) > 1;
        if ($hasServer) {
            $hasServerSelection = $cfg['ServerDefault'] == 0
                || (! $cfg['NavigationDisplayServers']
                && (count($cfg['Servers']) > 1
                || ($server == 0 && count($cfg['Servers']) === 1)));
            if ($hasServerSelection) {
                $serverSelection = Select::render(true, true);
            }

            if ($server > 0) {
                $checkUserPrivileges = new CheckUserPrivileges($this->dbi);
                $checkUserPrivileges->getPrivileges();

                $charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']);
                $collations = Charsets::getCollations($this->dbi, $cfg['Server']['DisableIS']);
                $charsetsList = [];
                foreach ($charsets as $charset) {
                    $collationsList = [];
                    foreach ($collations[$charset->getName()] as $collation) {
                        $collationsList[] = [
                            'name' => $collation->getName(),
                            'description' => $collation->getDescription(),
                            'is_selected' => $collation_connection === $collation->getName(),
                        ];
                    }

                    $charsetsList[] = [
                        'name' => $charset->getName(),
                        'description' => $charset->getDescription(),
                        'collations' => $collationsList,
                    ];
                }
            }
        }

        $availableLanguages = [];
        if (empty($cfg['Lang']) && $languageManager->hasChoice()) {
            $availableLanguages = $languageManager->sortedLanguages();
        }

        $databaseServer = [];
        if ($server > 0 && $cfg['ShowServerInfo']) {
            $hostInfo = '';
            if (! empty($cfg['Server']['verbose'])) {
                $hostInfo .= $cfg['Server']['verbose'];
                $hostInfo .= ' (';
            }

            $hostInfo .= $this->dbi->getHostInfo();

            if (! empty($cfg['Server']['verbose'])) {
                $hostInfo .= ')';
            }

            $serverCharset = Charsets::getServerCharset($this->dbi, $cfg['Server']['DisableIS']);
            $databaseServer = [
                'host' => $hostInfo,
                'type' => Util::getServerType(),
                'connection' => Generator::getServerSSL(),
                'version' => $this->dbi->getVersionString() . ' - ' . $this->dbi->getVersionComment(),
                'protocol' => $this->dbi->getProtoInfo(),
                'user' => $this->dbi->fetchValue('SELECT USER();'),
                'charset' => $serverCharset->getDescription() . ' (' . $serverCharset->getName() . ')',
            ];
        }

        $webServer = [];
        if ($cfg['ShowServerInfo']) {
            $webServer['software'] = $_SERVER['SERVER_SOFTWARE'] ?? null;

            if ($server > 0) {
                $clientVersion = $this->dbi->getClientInfo();
                if (preg_match('#\d+\.\d+\.\d+#', $clientVersion)) {
                    $clientVersion = 'libmysql - ' . $clientVersion;
                }

                $webServer['database'] = $clientVersion;
                $webServer['php_extensions'] = Util::listPHPExtensions();
                $webServer['php_version'] = PHP_VERSION;
            }
        }

        $relation = new Relation($this->dbi);
        if ($server > 0) {
            $relationParameters = $relation->getRelationParameters();
            if (! $relationParameters->hasAllFeatures() && $cfg['PmaNoRelation_DisableWarning'] == false) {
                $messageText = __(
                    'The phpMyAdmin configuration storage is not completely '
                    . 'configured, some extended features have been deactivated. '
                    . '%sFind out why%s. '
                );
                if ($cfg['ZeroConf'] == true) {
                    $messageText .= '<br>' .
                        __('Or alternately go to \'Operations\' tab of any database to set it up there.');
                }

                $messageInstance = Message::notice($messageText);
                $messageInstance->addParamHtml(
                    '<a href="' . Url::getFromRoute('/check-relations')
                    . '" data-post="' . Url::getCommon() . '">'
                );
                $messageInstance->addParamHtml('</a>');
                /* Show error if user has configured something, notice elsewhere */
                if (! empty($cfg['Servers'][$server]['pmadb'])) {
                    $messageInstance->isError(true);
                }

                $configStorageMessage = $messageInstance->getDisplay();
            }
        }

        $this->checkRequirements();

        $git = new Git($this->config->get('ShowGitRevision') ?? true);

        $this->render('home/index', [
            'db' => $db,
            'table' => $table,
            'message' => $displayMessage ?? '',
            'partial_logout' => $partialLogout ?? '',
            'is_git_revision' => $git->isGitRevision(),
            'server' => $server,
            'sync_favorite_tables' => $syncFavoriteTables,
            'has_server' => $hasServer,
            'is_demo' => $cfg['DBG']['demo'],
            'has_server_selection' => $hasServerSelection ?? false,
            'server_selection' => $serverSelection ?? '',
            'has_change_password_link' => $cfg['Server']['auth_type'] !== 'config' && $cfg['ShowChgPassword'],
            'charsets' => $charsetsList ?? [],
            'available_languages' => $availableLanguages,
            'database_server' => $databaseServer,
            'web_server' => $webServer,
            'show_php_info' => $cfg['ShowPhpInfo'],
            'is_version_checked' => $cfg['VersionCheck'],
            'phpmyadmin_version' => Version::VERSION,
            'phpmyadmin_major_version' => Version::SERIES,
            'config_storage_message' => $configStorageMessage ?? '',
            'has_theme_manager' => $cfg['ThemeManager'],
            'themes' => $this->themeManager->getThemesArray(),
            'errors' => $this->errors,
        ]);
    }

    private function checkRequirements(): void
    {
        global $cfg, $server;

        $this->checkPhpExtensionsRequirements();

        if ($cfg['LoginCookieValidityDisableWarning'] == false) {
            /**
             * Check whether session.gc_maxlifetime limits session validity.
             */
            $gc_time = (int) ini_get('session.gc_maxlifetime');
            if ($gc_time < $cfg['LoginCookieValidity']) {
                $this->errors[] = [
                    'message' => __(
                        'Your PHP parameter [a@https://www.php.net/manual/en/session.' .
                        'configuration.php#ini.session.gc-maxlifetime@_blank]session.' .
                        'gc_maxlifetime[/a] is lower than cookie validity configured ' .
                        'in phpMyAdmin, because of this, your login might expire sooner ' .
                        'than configured in phpMyAdmin.'
                    ),
                    'severity' => 'warning',
                ];
            }
        }

        /**
         * Check whether LoginCookieValidity is limited by LoginCookieStore.
         */
        if ($cfg['LoginCookieStore'] != 0 && $cfg['LoginCookieStore'] < $cfg['LoginCookieValidity']) {
            $this->errors[] = [
                'message' => __(
                    'Login cookie store is lower than cookie validity configured in ' .
                    'phpMyAdmin, because of this, your login will expire sooner than ' .
                    'configured in phpMyAdmin.'
                ),
                'severity' => 'warning',
            ];
        }

        /**
         * Warning if using the default MySQL controluser account
         */
        if (
            isset($cfg['Server']['controluser'], $cfg['Server']['controlpass'])
            && $server != 0
            && $cfg['Server']['controluser'] === 'pma'
            && $cfg['Server']['controlpass'] === 'pmapass'
        ) {
            $this->errors[] = [
                'message' => __(
                    'Your server is running with default values for the ' .
                    'controluser and password (controlpass) and is open to ' .
                    'intrusion; you really should fix this security weakness' .
                    ' by changing the password for controluser \'pma\'.'
                ),
                'severity' => 'warning',
            ];
        }

        /**
         * Check if user does not have defined blowfish secret and it is being used.
         */
        if (! empty($_SESSION['encryption_key'])) {
            if (empty($cfg['blowfish_secret'])) {
                $this->errors[] = [
                    'message' => __(
                        'The configuration file now needs a secret passphrase (blowfish_secret).'
                    ),
                    'severity' => 'warning',
                ];
            } elseif (mb_strlen($cfg['blowfish_secret'], '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
                $this->errors[] = [
                    'message' => sprintf(
                        __(
                            'The secret passphrase in configuration (blowfish_secret) is not the correct length.'
                            . ' It should be %d bytes long.'
                        ),
                        SODIUM_CRYPTO_SECRETBOX_KEYBYTES
                    ),
                    'severity' => 'warning',
                ];
            }
        }

        /**
         * Check for existence of config directory which should not exist in
         * production environment.
         */
        if (@file_exists(ROOT_PATH . 'config')) {
            $this->errors[] = [
                'message' => __(
                    'Directory [code]config[/code], which is used by the setup script, ' .
                    'still exists in your phpMyAdmin directory. It is strongly ' .
                    'recommended to remove it once phpMyAdmin has been configured. ' .
                    'Otherwise the security of your server may be compromised by ' .
                    'unauthorized people downloading your configuration.'
                ),
                'severity' => 'warning',
            ];
        }

        /**
         * Warning about Suhosin only if its simulation mode is not enabled
         */
        if (
            $cfg['SuhosinDisableWarning'] == false
            && ini_get('suhosin.request.max_value_length')
            && ini_get('suhosin.simulation') == '0'
        ) {
            $this->errors[] = [
                'message' => sprintf(
                    __(
                        'Server running with Suhosin. Please refer to %sdocumentation%s for possible issues.'
                    ),
                    '[doc@faq1-38]',
                    '[/doc]'
                ),
                'severity' => 'warning',
            ];
        }

        /* Missing template cache */
        if ($this->config->getTempDir('twig') === null) {
            $this->errors[] = [
                'message' => sprintf(
                    __(
                        'The $cfg[\'TempDir\'] (%s) is not accessible. ' .
                        'phpMyAdmin is not able to cache templates and will ' .
                        'be slow because of this.'
                    ),
                    $this->config->get('TempDir')
                ),
                'severity' => 'warning',
            ];
        }

        $this->checkLanguageStats();
    }

    private function checkLanguageStats(): void
    {
        global $cfg, $lang;

        /**
         * Warning about incomplete translations.
         *
         * The data file is created while creating release by ./scripts/remove-incomplete-mo
         */
        if (! @file_exists(ROOT_PATH . 'libraries/language_stats.inc.php')) {
            return;
        }

        /** @psalm-suppress MissingFile */
        include ROOT_PATH . 'libraries/language_stats.inc.php';
        /*
         * This message is intentionally not translated, because we're
         * handling incomplete translations here and focus on english
         * speaking users.
         */
        if (
            ! isset($GLOBALS['language_stats'][$lang])
            || $GLOBALS['language_stats'][$lang] >= $cfg['TranslationWarningThreshold']
        ) {
            return;
        }

        $this->errors[] = [
            'message' => 'You are using an incomplete translation, please help to make it '
                . 'better by [a@https://www.phpmyadmin.net/translate/'
                . '@_blank]contributing[/a].',
            'severity' => 'notice',
        ];
    }

    private function checkPhpExtensionsRequirements(): void
    {
        /**
         * mbstring is used for handling multibytes inside parser, so it is good
         * to tell user something might be broken without it, see bug #1063149.
         */
        if (! extension_loaded('mbstring')) {
            $this->errors[] = [
                'message' => __(
                    'The mbstring PHP extension was not found and you seem to be using'
                    . ' a multibyte charset. Without the mbstring extension phpMyAdmin'
                    . ' is unable to split strings correctly and it may result in'
                    . ' unexpected results.'
                ),
                'severity' => 'warning',
            ];
        }

        /**
         * Missing functionality
         */
        if (extension_loaded('curl') || ini_get('allow_url_fopen')) {
            return;
        }

        $this->errors[] = [
            'message' =>  __(
                'The curl extension was not found and allow_url_fopen is '
                . 'disabled. Due to this some features such as error reporting '
                . 'or version check are disabled.'
            ),
            'severity' => 'notice',
        ];
    }
}