diff --git a/index.php b/index.php index 8c5eaf5cf9..9ce7de8b88 100644 --- a/index.php +++ b/index.php @@ -35,9 +35,11 @@ if (! @is_readable(AUTOLOAD_FILE)) { require AUTOLOAD_FILE; -global $containerBuilder; - Common::run(); -$dispatcher = Routing::getDispatcher(); -Routing::callControllerForRoute(Common::getRequest(), Routing::getCurrentRoute(), $dispatcher, $containerBuilder); +Routing::callControllerForRoute( + Common::getRequest(), + Routing::getCurrentRoute(), + Routing::getDispatcher(), + $GLOBALS['containerBuilder'] +); diff --git a/js/messages.php b/js/messages.php index 927226b2e8..2844458935 100644 --- a/js/messages.php +++ b/js/messages.php @@ -6,9 +6,6 @@ use PhpMyAdmin\Common; use PhpMyAdmin\Controllers\JavaScriptMessagesController; use PhpMyAdmin\OutputBuffering; -/** @psalm-suppress InvalidGlobal */ -global $containerBuilder; - if (! defined('ROOT_PATH')) { // phpcs:disable PSR1.Files.SideEffects define('ROOT_PATH', dirname(__DIR__) . DIRECTORY_SEPARATOR); @@ -47,7 +44,7 @@ header('Content-Type: text/javascript; charset=UTF-8'); // Cache output in client - the nocache query parameter makes sure that this file is reloaded when config changes. header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT'); -$isMinimumCommon = true; +$GLOBALS['isMinimumCommon'] = true; // phpcs:disable PSR1.Files.SideEffects define('PMA_PATH_TO_BASEDIR', '../'); define('PMA_NO_SESSION', true); @@ -63,5 +60,5 @@ register_shutdown_function(static function (): void { }); /** @var JavaScriptMessagesController $controller */ -$controller = $containerBuilder->get(JavaScriptMessagesController::class); +$controller = $GLOBALS['containerBuilder']->get(JavaScriptMessagesController::class); $controller(); diff --git a/libraries/classes/BrowseForeigners.php b/libraries/classes/BrowseForeigners.php index d6184f913c..6b16af1231 100644 --- a/libraries/classes/BrowseForeigners.php +++ b/libraries/classes/BrowseForeigners.php @@ -39,14 +39,12 @@ class BrowseForeigners */ public function __construct(Template $template) { - global $cfg; - $this->template = $template; - $this->limitChars = (int) $cfg['LimitChars']; - $this->maxRows = (int) $cfg['MaxRows']; - $this->repeatCells = (int) $cfg['RepeatCells']; - $this->showAll = (bool) $cfg['ShowAll']; + $this->limitChars = (int) $GLOBALS['cfg']['LimitChars']; + $this->maxRows = (int) $GLOBALS['cfg']['MaxRows']; + $this->repeatCells = (int) $GLOBALS['cfg']['RepeatCells']; + $this->showAll = (bool) $GLOBALS['cfg']['ShowAll']; } /** @@ -71,8 +69,6 @@ class BrowseForeigners int $indexByDescription, string $currentValue ): array { - global $theme; - $horizontalCount++; $output = ''; @@ -126,7 +122,7 @@ class BrowseForeigners ]); $output .= ''; $output .= $this->template->render('table/browse_foreigners/column_element', [ diff --git a/libraries/classes/Command/CacheWarmupCommand.php b/libraries/classes/Command/CacheWarmupCommand.php index c090ee27e9..e6516ae399 100644 --- a/libraries/classes/Command/CacheWarmupCommand.php +++ b/libraries/classes/Command/CacheWarmupCommand.php @@ -118,13 +118,11 @@ final class CacheWarmupCommand extends Command string $environment, bool $writeReplacements ): int { - global $cfg, $config, $dbi; - $output->writeln('Warming up the twig cache', OutputInterface::VERBOSITY_VERBOSE); - $config = new Config(CONFIG_FILE); - $cfg['environment'] = $environment; - $config->set('environment', $cfg['environment']); - $dbi = new DatabaseInterface(new DbiDummy()); + $GLOBALS['config'] = new Config(CONFIG_FILE); + $GLOBALS['cfg']['environment'] = $environment; + $GLOBALS['config']->set('environment', $GLOBALS['cfg']['environment']); + $GLOBALS['dbi'] = new DatabaseInterface(new DbiDummy()); $tmpDir = ROOT_PATH . 'twig-templates'; $twig = Template::getTwigEnvironment($tmpDir); diff --git a/libraries/classes/Common.php b/libraries/classes/Common.php index 7c73885e3b..b7ee7cee98 100644 --- a/libraries/classes/Common.php +++ b/libraries/classes/Common.php @@ -81,22 +81,17 @@ final class Common */ public static function run(): void { - global $containerBuilder, $errorHandler, $config, $server, $dbi; - global $lang, $cfg, $isConfigLoading, $auth_plugin, $theme; - global $urlParams, $isMinimumCommon, $sql_query, $token_mismatch; - $request = self::getRequest(); $route = Routing::getCurrentRoute(); if ($route === '/import-status') { - $isMinimumCommon = true; + $GLOBALS['isMinimumCommon'] = true; } - $containerBuilder = Core::getContainerBuilder(); + $GLOBALS['containerBuilder'] = Core::getContainerBuilder(); - /** @var ErrorHandler $errorHandler */ - $errorHandler = $containerBuilder->get('error_handler'); + $GLOBALS['errorHandler'] = $GLOBALS['containerBuilder']->get('error_handler'); self::checkRequiredPhpExtensions(); self::configurePhpSettings(); @@ -104,24 +99,22 @@ final class Common /* parsing configuration file LABEL_parsing_config_file */ - /** @var bool $isConfigLoading Indication for the error handler */ - $isConfigLoading = false; + /** Indication for the error handler */ + $GLOBALS['isConfigLoading'] = false; register_shutdown_function([Config::class, 'fatalErrorHandler']); /** * Force reading of config file, because we removed sensitive values * in the previous iteration. - * - * @var Config $config */ - $config = $containerBuilder->get('config'); + $GLOBALS['config'] = $GLOBALS['containerBuilder']->get('config'); /** * include session handling after the globals, to prevent overwriting */ if (! defined('PMA_NO_SESSION')) { - Session::setUp($config, $errorHandler); + Session::setUp($GLOBALS['config'], $GLOBALS['errorHandler']); } $request = Core::populateRequestWithEncryptedQueryParams($request); @@ -135,27 +128,27 @@ final class Common * * @global array $urlParams */ - $urlParams = []; - $containerBuilder->setParameter('url_params', $urlParams); + $GLOBALS['urlParams'] = []; + $GLOBALS['containerBuilder']->setParameter('url_params', $GLOBALS['urlParams']); - self::setGotoAndBackGlobals($containerBuilder, $config); + self::setGotoAndBackGlobals($GLOBALS['containerBuilder'], $GLOBALS['config']); self::checkTokenRequestParam(); - self::setDatabaseAndTableFromRequest($containerBuilder, $request); + self::setDatabaseAndTableFromRequest($GLOBALS['containerBuilder'], $request); /** * SQL query to be executed * * @global string $sql_query */ - $sql_query = ''; + $GLOBALS['sql_query'] = ''; if ($request->isPost()) { - $sql_query = $request->getParsedBodyParam('sql_query'); - if (! is_string($sql_query)) { - $sql_query = ''; + $GLOBALS['sql_query'] = $request->getParsedBodyParam('sql_query'); + if (! is_string($GLOBALS['sql_query'])) { + $GLOBALS['sql_query'] = ''; } } - $containerBuilder->setParameter('sql_query', $sql_query); + $GLOBALS['containerBuilder']->setParameter('sql_query', $GLOBALS['sql_query']); //$_REQUEST['set_theme'] // checked later in this file LABEL_theme_setup //$_REQUEST['server']; // checked later in this file @@ -173,38 +166,37 @@ final class Common * check for errors occurred while loading configuration * this check is done here after loading language files to present errors in locale */ - $config->checkPermissions(); - $config->checkErrors(); + $GLOBALS['config']->checkPermissions(); + $GLOBALS['config']->checkErrors(); self::checkServerConfiguration(); self::checkRequest(); /* setup servers LABEL_setup_servers */ - $config->checkServers(); + $GLOBALS['config']->checkServers(); /** * current server * * @global integer $server */ - $server = $config->selectServer(); - $urlParams['server'] = $server; - $containerBuilder->setParameter('server', $server); - $containerBuilder->setParameter('url_params', $urlParams); + $GLOBALS['server'] = $GLOBALS['config']->selectServer(); + $GLOBALS['urlParams']['server'] = $GLOBALS['server']; + $GLOBALS['containerBuilder']->setParameter('server', $GLOBALS['server']); + $GLOBALS['containerBuilder']->setParameter('url_params', $GLOBALS['urlParams']); - $cfg = $config->settings; + $GLOBALS['cfg'] = $GLOBALS['config']->settings; /* setup themes LABEL_theme_setup */ - $theme = ThemeManager::initializeTheme(); + $GLOBALS['theme'] = ThemeManager::initializeTheme(); - /** @var DatabaseInterface $dbi */ - $dbi = null; + $GLOBALS['dbi'] = null; - if (isset($isMinimumCommon)) { - $config->loadUserPreferences(); - $containerBuilder->set('theme_manager', ThemeManager::getInstance()); + if (isset($GLOBALS['isMinimumCommon'])) { + $GLOBALS['config']->loadUserPreferences(); + $GLOBALS['containerBuilder']->set('theme_manager', ThemeManager::getInstance()); Tracker::enable(); return; @@ -215,19 +207,19 @@ final class Common * * @todo should be done in PhpMyAdmin\Config */ - $config->setCookie('pma_lang', (string) $lang); + $GLOBALS['config']->setCookie('pma_lang', (string) $GLOBALS['lang']); ThemeManager::getInstance()->setThemeCookie(); - $dbi = DatabaseInterface::load(); - $containerBuilder->set(DatabaseInterface::class, $dbi); - $containerBuilder->setAlias('dbi', DatabaseInterface::class); + $GLOBALS['dbi'] = DatabaseInterface::load(); + $GLOBALS['containerBuilder']->set(DatabaseInterface::class, $GLOBALS['dbi']); + $GLOBALS['containerBuilder']->setAlias('dbi', DatabaseInterface::class); - if (! empty($cfg['Server'])) { - $config->getLoginCookieValidityFromCache($server); + if (! empty($GLOBALS['cfg']['Server'])) { + $GLOBALS['config']->getLoginCookieValidityFromCache($GLOBALS['server']); - $auth_plugin = Plugins::getAuthPlugin(); - $auth_plugin->authenticate(); + $GLOBALS['auth_plugin'] = Plugins::getAuthPlugin(); + $GLOBALS['auth_plugin']->authenticate(); /* Enable LOAD DATA LOCAL INFILE for LDI plugin */ if ($route === '/import' && ($_POST['format'] ?? '') === 'ldi') { @@ -237,21 +229,21 @@ final class Common // phpcs:enable } - self::connectToDatabaseServer($dbi, $auth_plugin); + self::connectToDatabaseServer($GLOBALS['dbi'], $GLOBALS['auth_plugin']); - $auth_plugin->rememberCredentials(); + $GLOBALS['auth_plugin']->rememberCredentials(); - $auth_plugin->checkTwoFactor(); + $GLOBALS['auth_plugin']->checkTwoFactor(); /* Log success */ - Logging::logUser($cfg['Server']['user']); + Logging::logUser($GLOBALS['cfg']['Server']['user']); - if ($dbi->getVersion() < $cfg['MysqlMinVersion']['internal']) { + if ($GLOBALS['dbi']->getVersion() < $GLOBALS['cfg']['MysqlMinVersion']['internal']) { Core::fatalError( __('You should upgrade to %s %s or later.'), [ 'MySQL', - $cfg['MysqlMinVersion']['human'], + $GLOBALS['cfg']['MysqlMinVersion']['human'], ] ); } @@ -276,7 +268,7 @@ final class Common * There is no point in even attempting to process * an ajax request if there is a token mismatch */ - if ($response->isAjax() && $request->isPost() && $token_mismatch) { + if ($response->isAjax() && $request->isPost() && $GLOBALS['token_mismatch']) { $response->setRequestStatus(false); $response->addJSON( 'message', @@ -285,25 +277,25 @@ final class Common exit; } - Profiling::check($dbi, $response); + Profiling::check($GLOBALS['dbi'], $response); - $containerBuilder->set('response', ResponseRenderer::getInstance()); + $GLOBALS['containerBuilder']->set('response', ResponseRenderer::getInstance()); // load user preferences - $config->loadUserPreferences(); + $GLOBALS['config']->loadUserPreferences(); - $containerBuilder->set('theme_manager', ThemeManager::getInstance()); + $GLOBALS['containerBuilder']->set('theme_manager', ThemeManager::getInstance()); /* Tell tracker that it can actually work */ Tracker::enable(); - if (empty($server) || ! isset($cfg['ZeroConf']) || $cfg['ZeroConf'] !== true) { + if (empty($GLOBALS['server']) || ! isset($GLOBALS['cfg']['ZeroConf']) || $GLOBALS['cfg']['ZeroConf'] !== true) { return; } /** @var Relation $relation */ - $relation = $containerBuilder->get('relation'); - $dbi->postConnectControl($relation); + $relation = $GLOBALS['containerBuilder']->get('relation'); + $GLOBALS['dbi']->postConnectControl($relation); } /** @@ -381,31 +373,29 @@ final class Common */ public static function cleanupPathInfo(): void { - global $PMA_PHP_SELF; - - $PMA_PHP_SELF = Core::getenv('PHP_SELF'); - if (empty($PMA_PHP_SELF)) { - $PMA_PHP_SELF = urldecode(Core::getenv('REQUEST_URI')); + $GLOBALS['PMA_PHP_SELF'] = Core::getenv('PHP_SELF'); + if (empty($GLOBALS['PMA_PHP_SELF'])) { + $GLOBALS['PMA_PHP_SELF'] = urldecode(Core::getenv('REQUEST_URI')); } $_PATH_INFO = Core::getenv('PATH_INFO'); - if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) { - $question_pos = mb_strpos($PMA_PHP_SELF, '?'); + if (! empty($_PATH_INFO) && ! empty($GLOBALS['PMA_PHP_SELF'])) { + $question_pos = mb_strpos($GLOBALS['PMA_PHP_SELF'], '?'); if ($question_pos != false) { - $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $question_pos); + $GLOBALS['PMA_PHP_SELF'] = mb_substr($GLOBALS['PMA_PHP_SELF'], 0, $question_pos); } - $path_info_pos = mb_strrpos($PMA_PHP_SELF, $_PATH_INFO); + $path_info_pos = mb_strrpos($GLOBALS['PMA_PHP_SELF'], $_PATH_INFO); if ($path_info_pos !== false) { - $path_info_part = mb_substr($PMA_PHP_SELF, $path_info_pos, mb_strlen($_PATH_INFO)); + $path_info_part = mb_substr($GLOBALS['PMA_PHP_SELF'], $path_info_pos, mb_strlen($_PATH_INFO)); if ($path_info_part == $_PATH_INFO) { - $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $path_info_pos); + $GLOBALS['PMA_PHP_SELF'] = mb_substr($GLOBALS['PMA_PHP_SELF'], 0, $path_info_pos); } } } $path = []; - foreach (explode('/', $PMA_PHP_SELF) as $part) { + foreach (explode('/', $GLOBALS['PMA_PHP_SELF']) as $part) { // ignore parts that have no value if (empty($part) || $part === '.') { continue; @@ -423,22 +413,20 @@ final class Common // as there is nothing sane to do } - $PMA_PHP_SELF = htmlspecialchars('/' . implode('/', $path)); + $GLOBALS['PMA_PHP_SELF'] = htmlspecialchars('/' . implode('/', $path)); } private static function setGotoAndBackGlobals(ContainerInterface $container, Config $config): void { - global $goto, $back, $urlParams; - // Holds page that should be displayed. - $goto = ''; - $container->setParameter('goto', $goto); + $GLOBALS['goto'] = ''; + $container->setParameter('goto', $GLOBALS['goto']); if (isset($_REQUEST['goto']) && Core::checkPageValidity($_REQUEST['goto'])) { - $goto = $_REQUEST['goto']; - $urlParams['goto'] = $goto; - $container->setParameter('goto', $goto); - $container->setParameter('url_params', $urlParams); + $GLOBALS['goto'] = $_REQUEST['goto']; + $GLOBALS['urlParams']['goto'] = $GLOBALS['goto']; + $container->setParameter('goto', $GLOBALS['goto']); + $container->setParameter('url_params', $GLOBALS['urlParams']); } else { if ($config->issetCookie('goto')) { $config->removeCookie('goto'); @@ -449,8 +437,8 @@ final class Common if (isset($_REQUEST['back']) && Core::checkPageValidity($_REQUEST['back'])) { // Returning page. - $back = $_REQUEST['back']; - $container->setParameter('back', $back); + $GLOBALS['back'] = $_REQUEST['back']; + $container->setParameter('back', $GLOBALS['back']); return; } @@ -472,21 +460,19 @@ final class Common */ public static function checkTokenRequestParam(): void { - global $token_mismatch, $token_provided; - - $token_mismatch = true; - $token_provided = false; + $GLOBALS['token_mismatch'] = true; + $GLOBALS['token_provided'] = false; if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { return; } if (isset($_POST['token']) && is_scalar($_POST['token']) && strlen((string) $_POST['token']) > 0) { - $token_provided = true; - $token_mismatch = ! @hash_equals($_SESSION[' PMA_token '], (string) $_POST['token']); + $GLOBALS['token_provided'] = true; + $GLOBALS['token_mismatch'] = ! @hash_equals($_SESSION[' PMA_token '], (string) $_POST['token']); } - if (! $token_mismatch) { + if (! $GLOBALS['token_mismatch']) { return; } @@ -512,28 +498,26 @@ final class Common ContainerInterface $containerBuilder, ServerRequest $request ): void { - global $db, $table, $urlParams; - try { - $db = DatabaseName::fromValue($request->getParam('db'))->getName(); + $GLOBALS['db'] = DatabaseName::fromValue($request->getParam('db'))->getName(); } catch (InvalidArgumentException $exception) { - $db = ''; + $GLOBALS['db'] = ''; } try { - Assert::stringNotEmpty($db); - $table = TableName::fromValue($request->getParam('table'))->getName(); + Assert::stringNotEmpty($GLOBALS['db']); + $GLOBALS['table'] = TableName::fromValue($request->getParam('table'))->getName(); } catch (InvalidArgumentException $exception) { - $table = ''; + $GLOBALS['table'] = ''; } - if (! is_array($urlParams)) { - $urlParams = []; + if (! is_array($GLOBALS['urlParams'])) { + $GLOBALS['urlParams'] = []; } - $urlParams['db'] = $db; - $urlParams['table'] = $table; - $containerBuilder->setParameter('url_params', $urlParams); + $GLOBALS['urlParams']['db'] = $GLOBALS['db']; + $GLOBALS['urlParams']['table'] = $GLOBALS['table']; + $containerBuilder->setParameter('url_params', $GLOBALS['urlParams']); } /** @@ -594,14 +578,12 @@ final class Common private static function connectToDatabaseServer(DatabaseInterface $dbi, AuthenticationPlugin $auth): void { - global $cfg; - /** * Try to connect MySQL with the control user profile (will be used to get the privileges list for the current * user but the true user link must be open after this one so it would be default one for all the scripts). */ $controlLink = false; - if ($cfg['Server']['controluser'] !== '') { + if ($GLOBALS['cfg']['Server']['controluser'] !== '') { $controlLink = $dbi->connect(DatabaseInterface::CONNECT_CONTROL); } diff --git a/libraries/classes/Config.php b/libraries/classes/Config.php index c7f3c4f734..9fc9b7cef2 100644 --- a/libraries/classes/Config.php +++ b/libraries/classes/Config.php @@ -344,8 +344,6 @@ class Config */ public function load(?string $source = null): bool { - global $isConfigLoading; - $this->loadDefaults(); if ($source !== null) { @@ -369,10 +367,10 @@ class Config } ob_start(); - $isConfigLoading = true; + $GLOBALS['isConfigLoading'] = true; /** @psalm-suppress UnresolvableInclude */ $eval_result = include $this->getSource(); - $isConfigLoading = false; + $GLOBALS['isConfigLoading'] = false; ob_end_clean(); if ($canUseErrorReporting) { @@ -415,14 +413,12 @@ class Config */ private function setConnectionCollation(): void { - global $dbi; - $collation_connection = $this->get('DefaultConnectionCollation'); if (empty($collation_connection) || $collation_connection == $GLOBALS['collation_connection']) { return; } - $dbi->setCollation($collation_connection); + $GLOBALS['dbi']->setCollation($collation_connection); } /** @@ -431,15 +427,13 @@ class Config */ public function loadUserPreferences(): void { - global $isMinimumCommon; - // index.php should load these settings, so that phpmyadmin.css.php // will have everything available in session cache $server = $GLOBALS['server'] ?? (! empty($GLOBALS['cfg']['ServerDefault']) ? $GLOBALS['cfg']['ServerDefault'] : 0); $cache_key = 'server_' . $server; - if ($server > 0 && ! isset($isMinimumCommon)) { + if ($server > 0 && ! isset($GLOBALS['isMinimumCommon'])) { // cache user preferences, use database only when needed if ( ! isset($_SESSION['cache'][$cache_key]['userprefs']) @@ -467,7 +461,7 @@ class Config $this->settings = array_replace_recursive($this->settings, $config_data); $GLOBALS['cfg'] = array_replace_recursive($GLOBALS['cfg'], $config_data); - if (isset($isMinimumCommon)) { + if (isset($GLOBALS['isMinimumCommon'])) { return; } @@ -1036,9 +1030,7 @@ class Config */ public static function fatalErrorHandler(): void { - global $isConfigLoading; - - if (! isset($isConfigLoading) || ! $isConfigLoading) { + if (! isset($GLOBALS['isConfigLoading']) || ! $GLOBALS['isConfigLoading']) { return; } @@ -1258,31 +1250,29 @@ class Config */ public static function getConnectionParams(int $mode, ?array $server = null): array { - global $cfg; - $user = null; $password = null; if ($mode == DatabaseInterface::CONNECT_USER) { - $user = $cfg['Server']['user']; - $password = $cfg['Server']['password']; - $server = $cfg['Server']; + $user = $GLOBALS['cfg']['Server']['user']; + $password = $GLOBALS['cfg']['Server']['password']; + $server = $GLOBALS['cfg']['Server']; } elseif ($mode == DatabaseInterface::CONNECT_CONTROL) { - $user = $cfg['Server']['controluser']; - $password = $cfg['Server']['controlpass']; + $user = $GLOBALS['cfg']['Server']['controluser']; + $password = $GLOBALS['cfg']['Server']['controlpass']; $server = []; - $server['hide_connection_errors'] = $cfg['Server']['hide_connection_errors']; + $server['hide_connection_errors'] = $GLOBALS['cfg']['Server']['hide_connection_errors']; - if (! empty($cfg['Server']['controlhost'])) { - $server['host'] = $cfg['Server']['controlhost']; + if (! empty($GLOBALS['cfg']['Server']['controlhost'])) { + $server['host'] = $GLOBALS['cfg']['Server']['controlhost']; } else { - $server['host'] = $cfg['Server']['host']; + $server['host'] = $GLOBALS['cfg']['Server']['host']; } // Share the settings if the host is same - if ($server['host'] == $cfg['Server']['host']) { + if ($server['host'] == $GLOBALS['cfg']['Server']['host']) { $shared = [ 'port', 'socket', @@ -1296,21 +1286,21 @@ class Config 'ssl_verify', ]; foreach ($shared as $item) { - if (! isset($cfg['Server'][$item])) { + if (! isset($GLOBALS['cfg']['Server'][$item])) { continue; } - $server[$item] = $cfg['Server'][$item]; + $server[$item] = $GLOBALS['cfg']['Server'][$item]; } } // Set configured port - if (! empty($cfg['Server']['controlport'])) { - $server['port'] = $cfg['Server']['controlport']; + if (! empty($GLOBALS['cfg']['Server']['controlport'])) { + $server['port'] = $GLOBALS['cfg']['Server']['controlport']; } // Set any configuration with control_ prefix - foreach ($cfg['Server'] as $key => $val) { + foreach ($GLOBALS['cfg']['Server'] as $key => $val) { if (substr($key, 0, 8) !== 'control_') { continue; } @@ -1375,8 +1365,6 @@ class Config */ public function getLoginCookieValidityFromCache(int $server): void { - global $cfg; - $cacheKey = 'server_' . $server; if (! isset($_SESSION['cache'][$cacheKey]['userprefs']['LoginCookieValidity'])) { @@ -1385,6 +1373,6 @@ class Config $value = $_SESSION['cache'][$cacheKey]['userprefs']['LoginCookieValidity']; $this->set('LoginCookieValidity', $value); - $cfg['LoginCookieValidity'] = $value; + $GLOBALS['cfg']['LoginCookieValidity'] = $value; } } diff --git a/libraries/classes/Config/SpecialSchemaLinks.php b/libraries/classes/Config/SpecialSchemaLinks.php index 1a3c93ba15..b273fbaf0c 100644 --- a/libraries/classes/Config/SpecialSchemaLinks.php +++ b/libraries/classes/Config/SpecialSchemaLinks.php @@ -64,9 +64,7 @@ class SpecialSchemaLinks */ public static function get(): array { - global $cfg; - - $defaultPage = './' . Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); + $defaultPage = './' . Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); return [ 'mysql' => [ diff --git a/libraries/classes/ConfigStorage/Relation.php b/libraries/classes/ConfigStorage/Relation.php index 38e21d6182..29bc0f79de 100644 --- a/libraries/classes/ConfigStorage/Relation.php +++ b/libraries/classes/ConfigStorage/Relation.php @@ -1778,9 +1778,7 @@ class Relation public function getConfigurationStorageDbName(): string { - global $cfg; - - $cfgStorageDbName = $cfg['Server']['pmadb'] ?? ''; + $cfgStorageDbName = $GLOBALS['cfg']['Server']['pmadb'] ?? ''; // Use "phpmyadmin" as a default database name to check to keep the behavior consistent return empty($cfgStorageDbName) ? 'phpmyadmin' : $cfgStorageDbName; diff --git a/libraries/classes/ConfigStorage/UserGroups.php b/libraries/classes/ConfigStorage/UserGroups.php index 9763f57a1b..14c629f7fd 100644 --- a/libraries/classes/ConfigStorage/UserGroups.php +++ b/libraries/classes/ConfigStorage/UserGroups.php @@ -37,8 +37,6 @@ class UserGroups ConfigurableMenusFeature $configurableMenusFeature, string $userGroup ): string { - global $dbi; - $users = []; $numRows = 0; @@ -46,9 +44,9 @@ class UserGroups $usersTable = Util::backquote($configurableMenusFeature->database) . '.' . Util::backquote($configurableMenusFeature->users); $sql_query = 'SELECT `username` FROM ' . $usersTable - . " WHERE `usergroup`='" . $dbi->escapeString($userGroup) + . " WHERE `usergroup`='" . $GLOBALS['dbi']->escapeString($userGroup) . "'"; - $result = $dbi->tryQueryAsControlUser($sql_query); + $result = $GLOBALS['dbi']->tryQueryAsControlUser($sql_query); if ($result) { $i = 0; while ($row = $result->fetchRow()) { @@ -75,12 +73,10 @@ class UserGroups */ public static function getHtmlForUserGroupsTable(ConfigurableMenusFeature $configurableMenusFeature): string { - global $dbi; - $groupTable = Util::backquote($configurableMenusFeature->database) . '.' . Util::backquote($configurableMenusFeature->userGroups); $sql_query = 'SELECT * FROM ' . $groupTable . ' ORDER BY `usergroup` ASC'; - $result = $dbi->tryQueryAsControlUser($sql_query); + $result = $GLOBALS['dbi']->tryQueryAsControlUser($sql_query); $userGroups = []; $userGroupsValues = []; $action = Url::getFromRoute('/server/privileges'); @@ -171,20 +167,18 @@ class UserGroups */ public static function delete(ConfigurableMenusFeature $configurableMenusFeature, string $userGroup): void { - global $dbi; - $userTable = Util::backquote($configurableMenusFeature->database) . '.' . Util::backquote($configurableMenusFeature->users); $groupTable = Util::backquote($configurableMenusFeature->database) . '.' . Util::backquote($configurableMenusFeature->userGroups); $sql_query = 'DELETE FROM ' . $userTable - . " WHERE `usergroup`='" . $dbi->escapeString($userGroup) + . " WHERE `usergroup`='" . $GLOBALS['dbi']->escapeString($userGroup) . "'"; - $dbi->queryAsControlUser($sql_query); + $GLOBALS['dbi']->queryAsControlUser($sql_query); $sql_query = 'DELETE FROM ' . $groupTable - . " WHERE `usergroup`='" . $dbi->escapeString($userGroup) + . " WHERE `usergroup`='" . $GLOBALS['dbi']->escapeString($userGroup) . "'"; - $dbi->queryAsControlUser($sql_query); + $GLOBALS['dbi']->queryAsControlUser($sql_query); } /** @@ -198,8 +192,6 @@ class UserGroups ConfigurableMenusFeature $configurableMenusFeature, ?string $userGroup = null ): string { - global $dbi; - $urlParams = []; $editUserGroupSpecialChars = ''; @@ -223,9 +215,9 @@ class UserGroups $groupTable = Util::backquote($configurableMenusFeature->database) . '.' . Util::backquote($configurableMenusFeature->userGroups); $sql_query = 'SELECT * FROM ' . $groupTable - . " WHERE `usergroup`='" . $dbi->escapeString($userGroup) + . " WHERE `usergroup`='" . $GLOBALS['dbi']->escapeString($userGroup) . "'"; - $result = $dbi->tryQueryAsControlUser($sql_query); + $result = $GLOBALS['dbi']->tryQueryAsControlUser($sql_query); if ($result) { foreach ($result as $row) { $key = $row['tab']; @@ -312,17 +304,15 @@ class UserGroups string $userGroup, bool $new = false ): void { - global $dbi; - $tabs = Util::getMenuTabList(); $groupTable = Util::backquote($configurableMenusFeature->database) . '.' . Util::backquote($configurableMenusFeature->userGroups); if (! $new) { $sql_query = 'DELETE FROM ' . $groupTable - . " WHERE `usergroup`='" . $dbi->escapeString($userGroup) + . " WHERE `usergroup`='" . $GLOBALS['dbi']->escapeString($userGroup) . "';"; - $dbi->queryAsControlUser($sql_query); + $GLOBALS['dbi']->queryAsControlUser($sql_query); } $sql_query = 'INSERT INTO ' . $groupTable @@ -338,13 +328,13 @@ class UserGroups $tabName = $tabGroupName . '_' . $tab; $allowed = isset($_POST[$tabName]) && $_POST[$tabName] === 'Y'; - $sql_query .= "('" . $dbi->escapeString($userGroup) . "', '" . $tabName . "', '" + $sql_query .= "('" . $GLOBALS['dbi']->escapeString($userGroup) . "', '" . $tabName . "', '" . ($allowed ? 'Y' : 'N') . "')"; $first = false; } } $sql_query .= ';'; - $dbi->queryAsControlUser($sql_query); + $GLOBALS['dbi']->queryAsControlUser($sql_query); } } diff --git a/libraries/classes/Console.php b/libraries/classes/Console.php index c416355939..556009c3b8 100644 --- a/libraries/classes/Console.php +++ b/libraries/classes/Console.php @@ -44,10 +44,8 @@ class Console */ public function __construct() { - global $dbi; - $this->isEnabled = true; - $this->relation = new Relation($dbi); + $this->relation = new Relation($GLOBALS['dbi']); $this->template = new Template(); } @@ -75,16 +73,14 @@ class Console */ public static function getBookmarkContent(): string { - global $dbi; - $template = new Template(); - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $bookmarkFeature = $relation->getRelationParameters()->bookmarkFeature; if ($bookmarkFeature === null) { return ''; } - $bookmarks = Bookmark::getList($bookmarkFeature, $dbi, $GLOBALS['cfg']['Server']['user']); + $bookmarks = Bookmark::getList($bookmarkFeature, $GLOBALS['dbi'], $GLOBALS['cfg']['Server']['user']); $count_bookmarks = count($bookmarks); if ($count_bookmarks > 0) { $welcomeMessage = sprintf( diff --git a/libraries/classes/Controllers/AbstractController.php b/libraries/classes/Controllers/AbstractController.php index 3fe4167d36..8b3cf58189 100644 --- a/libraries/classes/Controllers/AbstractController.php +++ b/libraries/classes/Controllers/AbstractController.php @@ -48,25 +48,23 @@ abstract class AbstractController protected function hasDatabase(): bool { - global $db, $is_db, $errno, $dbi, $message; - - if (isset($is_db) && $is_db) { + if (isset($GLOBALS['is_db']) && $GLOBALS['is_db']) { return true; } - $is_db = false; - if (strlen($db) > 0) { - $is_db = $dbi->selectDb($db); + $GLOBALS['is_db'] = false; + if (strlen($GLOBALS['db']) > 0) { + $GLOBALS['is_db'] = $GLOBALS['dbi']->selectDb($GLOBALS['db']); // This "Command out of sync" 2014 error may happen, for example // after calling a MySQL procedure; at this point we can't select // the db but it's not necessarily wrong - if ($dbi->getError() && $errno == 2014) { - $is_db = true; - unset($errno); + if ($GLOBALS['dbi']->getError() && $GLOBALS['errno'] == 2014) { + $GLOBALS['is_db'] = true; + unset($GLOBALS['errno']); } } - if (strlen($db) === 0 || ! $is_db) { + if (strlen($GLOBALS['db']) === 0 || ! $GLOBALS['is_db']) { if ($this->response->isAjax()) { $this->response->setRequestStatus(false); $this->response->addJSON( @@ -79,8 +77,8 @@ abstract class AbstractController // Not a valid db name -> back to the welcome page $params = ['reload' => '1']; - if (isset($message)) { - $params['message'] = $message; + if (isset($GLOBALS['message'])) { + $params['message'] = $GLOBALS['message']; } $this->redirect('/', $params); @@ -88,7 +86,7 @@ abstract class AbstractController return false; } - return $is_db; + return $GLOBALS['is_db']; } /** diff --git a/libraries/classes/Controllers/CheckRelationsController.php b/libraries/classes/Controllers/CheckRelationsController.php index 7ffe56c8e2..968c07a8e7 100644 --- a/libraries/classes/Controllers/CheckRelationsController.php +++ b/libraries/classes/Controllers/CheckRelationsController.php @@ -27,8 +27,6 @@ class CheckRelationsController extends AbstractController public function __invoke(ServerRequest $request): void { - global $db, $cfg; - /** @var string|null $createPmaDb */ $createPmaDb = $request->getParsedBodyParam('create_pmadb'); /** @var string|null $fixAllPmaDb */ @@ -45,7 +43,7 @@ class CheckRelationsController extends AbstractController // If request for creating all PMA tables. if (isset($fixAllPmaDb)) { - $this->relation->fixPmaTables($db); + $this->relation->fixPmaTables($GLOBALS['db']); } // If request for creating missing PMA tables. @@ -58,8 +56,8 @@ class CheckRelationsController extends AbstractController $relationParameters = $this->relation->getRelationParameters(); $this->render('relation/check_relations', [ - 'db' => $db, - 'zero_conf' => $cfg['ZeroConf'], + 'db' => $GLOBALS['db'], + 'zero_conf' => $GLOBALS['cfg']['ZeroConf'], 'relation_parameters' => $relationParameters->toArray(), 'sql_dir' => SQL_DIR, 'config_storage_database_name' => $cfgStorageDbName, diff --git a/libraries/classes/Controllers/Database/CentralColumnsController.php b/libraries/classes/Controllers/Database/CentralColumnsController.php index e703dc86a4..4c7c3f0feb 100644 --- a/libraries/classes/Controllers/Database/CentralColumnsController.php +++ b/libraries/classes/Controllers/Database/CentralColumnsController.php @@ -35,8 +35,6 @@ class CentralColumnsController extends AbstractController public function __invoke(): void { - global $cfg, $db, $message, $pos, $num_cols; - if (isset($_POST['edit_save'])) { echo $this->editSave([ 'col_name' => $_POST['col_name'] ?? null, @@ -99,7 +97,7 @@ class CentralColumnsController extends AbstractController } if (isset($_POST['multi_edit_central_column_save'])) { - $message = $this->updateMultipleColumn([ + $GLOBALS['message'] = $this->updateMultipleColumn([ 'db' => $_POST['db'] ?? null, 'orig_col_name' => $_POST['orig_col_name'] ?? null, 'field_name' => $_POST['field_name'] ?? null, @@ -112,9 +110,9 @@ class CentralColumnsController extends AbstractController 'field_null' => $_POST['field_null'] ?? null, 'col_extra' => $_POST['col_extra'] ?? null, ]); - if (! is_bool($message)) { + if (! is_bool($GLOBALS['message'])) { $this->response->setRequestStatus(false); - $this->response->addJSON('message', $message); + $this->response->addJSON('message', $GLOBALS['message']); } } @@ -130,20 +128,24 @@ class CentralColumnsController extends AbstractController 'total_rows' => $_POST['total_rows'] ?? null, ]); - $pos = 0; + $GLOBALS['pos'] = 0; if (isset($_POST['pos']) && is_numeric($_POST['pos'])) { - $pos = (int) $_POST['pos']; + $GLOBALS['pos'] = (int) $_POST['pos']; } - $num_cols = $this->centralColumns->getColumnsCount($db, $pos, (int) $cfg['MaxRows']); - $message = Message::success( - sprintf(__('Showing rows %1$s - %2$s.'), $pos + 1, $pos + $num_cols) + $GLOBALS['num_cols'] = $this->centralColumns->getColumnsCount( + $GLOBALS['db'], + $GLOBALS['pos'], + (int) $GLOBALS['cfg']['MaxRows'] + ); + $GLOBALS['message'] = Message::success( + sprintf(__('Showing rows %1$s - %2$s.'), $GLOBALS['pos'] + 1, $GLOBALS['pos'] + $GLOBALS['num_cols']) ); if (! isset($tmp_msg) || $tmp_msg === true) { return; } - $message = $tmp_msg; + $GLOBALS['message'] = $tmp_msg; } /** @@ -151,8 +153,6 @@ class CentralColumnsController extends AbstractController */ public function main(array $params): void { - global $text_dir; - if (! empty($params['total_rows']) && is_numeric($params['total_rows'])) { $totalRows = (int) $params['total_rows']; } else { @@ -164,7 +164,12 @@ class CentralColumnsController extends AbstractController $pos = (int) $params['pos']; } - $variables = $this->centralColumns->getTemplateVariablesForMain($GLOBALS['db'], $totalRows, $pos, $text_dir); + $variables = $this->centralColumns->getTemplateVariablesForMain( + $GLOBALS['db'], + $totalRows, + $pos, + $GLOBALS['text_dir'] + ); $this->render('database/central_columns/main', $variables); } diff --git a/libraries/classes/Controllers/Database/DesignerController.php b/libraries/classes/Controllers/Database/DesignerController.php index 19d2156c45..7d7688d9f7 100644 --- a/libraries/classes/Controllers/Database/DesignerController.php +++ b/libraries/classes/Controllers/Database/DesignerController.php @@ -38,11 +38,6 @@ class DesignerController extends AbstractController public function __invoke(): void { - global $db, $script_display_field, $tab_column, $tables_all_keys, $tables_pk_or_unique_keys; - global $success, $page, $message, $display_page, $selected_page, $tab_pos, $fullTableNames, $script_tables; - global $script_contr, $params, $tables, $num_tables, $total_num_tables, $sub_part; - global $tooltip_truename, $tooltip_aliasname, $pos, $classes_side_menu, $cfg, $errorUrl; - if (isset($_POST['dialog'])) { if ($_POST['dialog'] === 'edit') { $html = $this->databaseDesigner->getHtmlForEditOrDeletePages($_POST['db'], 'editPage'); @@ -54,19 +49,21 @@ class DesignerController extends AbstractController $html = $this->databaseDesigner->getHtmlForSchemaExport($_POST['db'], $_POST['selected_page']); } elseif ($_POST['dialog'] === 'add_table') { // Pass the db and table to the getTablesInfo so we only have the table we asked for - $script_display_field = $this->designerCommon->getTablesInfo($_POST['db'], $_POST['table']); - $tab_column = $this->designerCommon->getColumnsInfo($script_display_field); - $tables_all_keys = $this->designerCommon->getAllKeys($script_display_field); - $tables_pk_or_unique_keys = $this->designerCommon->getPkOrUniqueKeys($script_display_field); + $GLOBALS['script_display_field'] = $this->designerCommon->getTablesInfo($_POST['db'], $_POST['table']); + $GLOBALS['tab_column'] = $this->designerCommon->getColumnsInfo($GLOBALS['script_display_field']); + $GLOBALS['tables_all_keys'] = $this->designerCommon->getAllKeys($GLOBALS['script_display_field']); + $GLOBALS['tables_pk_or_unique_keys'] = $this->designerCommon->getPkOrUniqueKeys( + $GLOBALS['script_display_field'] + ); $html = $this->databaseDesigner->getDatabaseTables( $_POST['db'], - $script_display_field, + $GLOBALS['script_display_field'], [], -1, - $tab_column, - $tables_all_keys, - $tables_pk_or_unique_keys + $GLOBALS['tab_column'], + $GLOBALS['tables_all_keys'], + $GLOBALS['tables_pk_or_unique_keys'] ); } @@ -79,11 +76,11 @@ class DesignerController extends AbstractController if (isset($_POST['operation'])) { if ($_POST['operation'] === 'deletePage') { - $success = $this->designerCommon->deletePage($_POST['selected_page']); - $this->response->setRequestStatus($success); + $GLOBALS['success'] = $this->designerCommon->deletePage($_POST['selected_page']); + $this->response->setRequestStatus($GLOBALS['success']); } elseif ($_POST['operation'] === 'savePage') { if ($_POST['save_page'] === 'same') { - $page = $_POST['selected_page']; + $GLOBALS['page'] = $_POST['selected_page']; } elseif ($this->designerCommon->getPageExists($_POST['selected_value'])) { $this->response->addJSON( 'message', @@ -99,21 +96,21 @@ class DesignerController extends AbstractController return; } else { - $page = $this->designerCommon->createNewPage($_POST['selected_value'], $_POST['db']); - $this->response->addJSON('id', $page); + $GLOBALS['page'] = $this->designerCommon->createNewPage($_POST['selected_value'], $_POST['db']); + $this->response->addJSON('id', $GLOBALS['page']); } - $success = $this->designerCommon->saveTablePositions($page); - $this->response->setRequestStatus($success); + $GLOBALS['success'] = $this->designerCommon->saveTablePositions($GLOBALS['page']); + $this->response->setRequestStatus($GLOBALS['success']); } elseif ($_POST['operation'] === 'setDisplayField') { [ - $success, - $message, + $GLOBALS['success'], + $GLOBALS['message'], ] = $this->designerCommon->saveDisplayField($_POST['db'], $_POST['table'], $_POST['field']); - $this->response->setRequestStatus($success); - $this->response->addJSON('message', $message); + $this->response->setRequestStatus($GLOBALS['success']); + $this->response->addJSON('message', $GLOBALS['message']); } elseif ($_POST['operation'] === 'addNewRelation') { - [$success, $message] = $this->designerCommon->addNewRelation( + [$GLOBALS['success'], $GLOBALS['message']] = $this->designerCommon->addNewRelation( $_POST['db'], $_POST['T1'], $_POST['F1'], @@ -124,20 +121,20 @@ class DesignerController extends AbstractController $_POST['DB1'], $_POST['DB2'] ); - $this->response->setRequestStatus($success); - $this->response->addJSON('message', $message); + $this->response->setRequestStatus($GLOBALS['success']); + $this->response->addJSON('message', $GLOBALS['message']); } elseif ($_POST['operation'] === 'removeRelation') { - [$success, $message] = $this->designerCommon->removeRelation( + [$GLOBALS['success'], $GLOBALS['message']] = $this->designerCommon->removeRelation( $_POST['T1'], $_POST['F1'], $_POST['T2'], $_POST['F2'] ); - $this->response->setRequestStatus($success); - $this->response->addJSON('message', $message); + $this->response->setRequestStatus($GLOBALS['success']); + $this->response->addJSON('message', $GLOBALS['message']); } elseif ($_POST['operation'] === 'save_setting_value') { - $success = $this->designerCommon->saveSetting($_POST['index'], $_POST['value']); - $this->response->setRequestStatus($success); + $GLOBALS['success'] = $this->designerCommon->saveSetting($_POST['index'], $_POST['value']); + $this->response->setRequestStatus($GLOBALS['success']); } return; @@ -145,62 +142,64 @@ class DesignerController extends AbstractController Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } - $script_display_field = $this->designerCommon->getTablesInfo(); + $GLOBALS['script_display_field'] = $this->designerCommon->getTablesInfo(); - $display_page = -1; - $selected_page = null; + $GLOBALS['display_page'] = -1; + $GLOBALS['selected_page'] = null; $visualBuilderMode = isset($_GET['query']); if ($visualBuilderMode) { - $display_page = $this->designerCommon->getDefaultPage($_GET['db']); + $GLOBALS['display_page'] = $this->designerCommon->getDefaultPage($_GET['db']); } elseif (! empty($_GET['page'])) { - $display_page = $_GET['page']; + $GLOBALS['display_page'] = $_GET['page']; } else { - $display_page = $this->designerCommon->getLoadingPage($_GET['db']); + $GLOBALS['display_page'] = $this->designerCommon->getLoadingPage($_GET['db']); } - if ($display_page != -1) { - $selected_page = $this->designerCommon->getPageName($display_page); + if ($GLOBALS['display_page'] != -1) { + $GLOBALS['selected_page'] = $this->designerCommon->getPageName($GLOBALS['display_page']); } - $tab_pos = $this->designerCommon->getTablePositions($display_page); + $GLOBALS['tab_pos'] = $this->designerCommon->getTablePositions($GLOBALS['display_page']); - $fullTableNames = []; + $GLOBALS['fullTableNames'] = []; - foreach ($script_display_field as $designerTable) { - $fullTableNames[] = $designerTable->getDbTableString(); + foreach ($GLOBALS['script_display_field'] as $designerTable) { + $GLOBALS['fullTableNames'][] = $designerTable->getDbTableString(); } - foreach ($tab_pos as $position) { - if (in_array($position['dbName'] . '.' . $position['tableName'], $fullTableNames)) { + foreach ($GLOBALS['tab_pos'] as $position) { + if (in_array($position['dbName'] . '.' . $position['tableName'], $GLOBALS['fullTableNames'])) { continue; } $designerTables = $this->designerCommon->getTablesInfo($position['dbName'], $position['tableName']); foreach ($designerTables as $designerTable) { - $script_display_field[] = $designerTable; + $GLOBALS['script_display_field'][] = $designerTable; } } - $tab_column = $this->designerCommon->getColumnsInfo($script_display_field); - $script_tables = $this->designerCommon->getScriptTabs($script_display_field); - $tables_pk_or_unique_keys = $this->designerCommon->getPkOrUniqueKeys($script_display_field); - $tables_all_keys = $this->designerCommon->getAllKeys($script_display_field); - $classes_side_menu = $this->databaseDesigner->returnClassNamesFromMenuButtons(); + $GLOBALS['tab_column'] = $this->designerCommon->getColumnsInfo($GLOBALS['script_display_field']); + $GLOBALS['script_tables'] = $this->designerCommon->getScriptTabs($GLOBALS['script_display_field']); + $GLOBALS['tables_pk_or_unique_keys'] = $this->designerCommon->getPkOrUniqueKeys( + $GLOBALS['script_display_field'] + ); + $GLOBALS['tables_all_keys'] = $this->designerCommon->getAllKeys($GLOBALS['script_display_field']); + $GLOBALS['classes_side_menu'] = $this->databaseDesigner->returnClassNamesFromMenuButtons(); - $script_contr = $this->designerCommon->getScriptContr($script_display_field); + $GLOBALS['script_contr'] = $this->designerCommon->getScriptContr($GLOBALS['script_display_field']); - $params = ['lang' => $GLOBALS['lang']]; + $GLOBALS['params'] = ['lang' => $GLOBALS['lang']]; if (isset($_GET['db'])) { - $params['db'] = $_GET['db']; + $GLOBALS['params']['db'] = $_GET['db']; } $this->response->getFooter()->setMinimal(); @@ -217,33 +216,33 @@ class DesignerController extends AbstractController ]); [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part ?? ''); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part'] ?? ''); // Embed some data into HTML, later it will be read // by designer/init.js and converted to JS variables. $this->response->addHTML( $this->databaseDesigner->getHtmlForMain( - $db, + $GLOBALS['db'], $_GET['db'], - $script_display_field, - $script_tables, - $script_contr, - $script_display_field, - $display_page, + $GLOBALS['script_display_field'], + $GLOBALS['script_tables'], + $GLOBALS['script_contr'], + $GLOBALS['script_display_field'], + $GLOBALS['display_page'], $visualBuilderMode, - $selected_page, - $classes_side_menu, - $tab_pos, - $tab_column, - $tables_all_keys, - $tables_pk_or_unique_keys + $GLOBALS['selected_page'], + $GLOBALS['classes_side_menu'], + $GLOBALS['tab_pos'], + $GLOBALS['tab_column'], + $GLOBALS['tables_all_keys'], + $GLOBALS['tables_pk_or_unique_keys'] ) ); diff --git a/libraries/classes/Controllers/Database/EventsController.php b/libraries/classes/Controllers/Database/EventsController.php index 139d5ba5de..1ed8da239b 100644 --- a/libraries/classes/Controllers/Database/EventsController.php +++ b/libraries/classes/Controllers/Database/EventsController.php @@ -35,51 +35,48 @@ final class EventsController extends AbstractController public function __invoke(): void { - global $db, $tables, $num_tables, $total_num_tables, $sub_part, $errors, $text_dir; - global $tooltip_truename, $tooltip_aliasname, $pos, $cfg, $errorUrl; - $this->addScriptFiles(['database/events.js']); if (! $this->response->isAjax()) { Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part ?? ''); - } elseif (strlen($db) > 0) { - $this->dbi->selectDb($db); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part'] ?? ''); + } elseif (strlen($GLOBALS['db']) > 0) { + $this->dbi->selectDb($GLOBALS['db']); } /** * Keep a list of errors that occurred while * processing an 'Add' or 'Edit' operation. */ - $errors = []; + $GLOBALS['errors'] = []; $this->events->handleEditor(); $this->events->export(); - $items = $this->dbi->getEvents($db); + $items = $this->dbi->getEvents($GLOBALS['db']); $this->render('database/events/index', [ - 'db' => $db, + 'db' => $GLOBALS['db'], 'items' => $items, - 'has_privilege' => Util::currentUserHasPrivilege('EVENT', $db), + 'has_privilege' => Util::currentUserHasPrivilege('EVENT', $GLOBALS['db']), 'scheduler_state' => $this->events->getEventSchedulerStatus(), - 'text_dir' => $text_dir, + 'text_dir' => $GLOBALS['text_dir'], 'is_ajax' => $this->response->isAjax() && empty($_REQUEST['ajax_page_request']), ]); } diff --git a/libraries/classes/Controllers/Database/ExportController.php b/libraries/classes/Controllers/Database/ExportController.php index ee09b5ea63..f9fbe56224 100644 --- a/libraries/classes/Controllers/Database/ExportController.php +++ b/libraries/classes/Controllers/Database/ExportController.php @@ -40,10 +40,6 @@ final class ExportController extends AbstractController public function __invoke(): void { - global $db, $table, $sub_part, $urlParams, $sql_query; - global $tables, $num_tables, $total_num_tables, $tooltip_truename; - global $tooltip_aliasname, $pos, $table_select, $unlim_num_rows, $cfg, $errorUrl; - $pageSettings = new PageSettings('Export'); $pageSettingsErrorHtml = $pageSettings->getErrorHTML(); $pageSettingsHtml = $pageSettings->getHTML(); @@ -52,31 +48,31 @@ final class ExportController extends AbstractController // $sub_part is used in Util::getDbInfo() to see if we are coming from // /database/export, in which case we don't obey $cfg['MaxTableList'] - $sub_part = '_export'; + $GLOBALS['sub_part'] = '_export'; Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } - $urlParams['goto'] = Url::getFromRoute('/database/export'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/database/export'); [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part']); // exit if no tables in db found - if ($num_tables < 1) { + if ($GLOBALS['num_tables'] < 1) { $this->response->addHTML( Message::error(__('No tables found in database.'))->getDisplay() ); @@ -84,17 +80,17 @@ final class ExportController extends AbstractController return; } - if (! empty($_POST['selected_tbl']) && empty($table_select)) { - $table_select = $_POST['selected_tbl']; + if (! empty($_POST['selected_tbl']) && empty($GLOBALS['table_select'])) { + $GLOBALS['table_select'] = $_POST['selected_tbl']; } $tablesForMultiValues = []; - foreach ($tables as $each_table) { + foreach ($GLOBALS['tables'] as $each_table) { if (isset($_POST['table_select']) && is_array($_POST['table_select'])) { $is_checked = $this->export->getCheckedClause($each_table['Name'], $_POST['table_select']); - } elseif (isset($table_select)) { - $is_checked = $this->export->getCheckedClause($each_table['Name'], $table_select); + } elseif (isset($GLOBALS['table_select'])) { + $is_checked = $this->export->getCheckedClause($each_table['Name'], $GLOBALS['table_select']); } else { $is_checked = true; } @@ -119,12 +115,12 @@ final class ExportController extends AbstractController ]; } - if (! isset($sql_query)) { - $sql_query = ''; + if (! isset($GLOBALS['sql_query'])) { + $GLOBALS['sql_query'] = ''; } - if (! isset($unlim_num_rows)) { - $unlim_num_rows = 0; + if (! isset($GLOBALS['unlim_num_rows'])) { + $GLOBALS['unlim_num_rows'] = 0; } $isReturnBackFromRawExport = isset($_POST['export_type']) && $_POST['export_type'] === 'raw'; @@ -148,11 +144,11 @@ final class ExportController extends AbstractController $options = $this->exportOptions->getOptions( $export_type, - $db, - $table, - $sql_query, - $num_tables, - $unlim_num_rows, + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['sql_query'], + $GLOBALS['num_tables'], + $GLOBALS['unlim_num_rows'], $exportList ); diff --git a/libraries/classes/Controllers/Database/ImportController.php b/libraries/classes/Controllers/Database/ImportController.php index 716a22e3e4..5e6da2daa1 100644 --- a/libraries/classes/Controllers/Database/ImportController.php +++ b/libraries/classes/Controllers/Database/ImportController.php @@ -36,9 +36,6 @@ final class ImportController extends AbstractController public function __invoke(): void { - global $db, $table, $tables, $num_tables, $total_num_tables, $cfg; - global $tooltip_truename, $tooltip_aliasname, $pos, $sub_part, $SESSION_KEY, $errorUrl; - $pageSettings = new PageSettings('Import'); $pageSettingsErrorHtml = $pageSettings->getErrorHTML(); $pageSettingsHtml = $pageSettings->getHTML(); @@ -47,24 +44,24 @@ final class ImportController extends AbstractController Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part ?? ''); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part'] ?? ''); - [$SESSION_KEY, $uploadId] = Ajax::uploadProgressSetup(); + [$GLOBALS['SESSION_KEY'], $uploadId] = Ajax::uploadProgressSetup(); $importList = Plugins::getImport('database'); @@ -85,13 +82,13 @@ final class ImportController extends AbstractController $localImportFile = $_REQUEST['local_import_file'] ?? null; $compressions = Import::getCompressions(); - $charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']); + $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); - $idKey = $_SESSION[$SESSION_KEY]['handler']::getIdKey(); + $idKey = $_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getIdKey(); $hiddenInputs = [ $idKey => $uploadId, 'import_type' => 'database', - 'db' => $db, + 'db' => $GLOBALS['db'], ]; $default = isset($_GET['format']) ? (string) $_GET['format'] : Plugins::getDefault('Import', 'format'); @@ -105,10 +102,10 @@ final class ImportController extends AbstractController 'page_settings_error_html' => $pageSettingsErrorHtml, 'page_settings_html' => $pageSettingsHtml, 'upload_id' => $uploadId, - 'handler' => $_SESSION[$SESSION_KEY]['handler'], + 'handler' => $_SESSION[$GLOBALS['SESSION_KEY']]['handler'], 'hidden_inputs' => $hiddenInputs, - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'max_upload_size' => $maxUploadSize, 'formatted_maximum_upload_size' => Util::getFormattedMaximumUploadSize($maxUploadSize), 'plugins_choice' => $choice, @@ -117,18 +114,18 @@ final class ImportController extends AbstractController 'is_allow_interrupt_checked' => $isAllowInterruptChecked, 'local_import_file' => $localImportFile, 'is_upload' => $GLOBALS['config']->get('enable_upload'), - 'upload_dir' => $cfg['UploadDir'] ?? null, + 'upload_dir' => $GLOBALS['cfg']['UploadDir'] ?? null, 'timeout_passed_global' => $GLOBALS['timeout_passed'] ?? null, 'compressions' => $compressions, 'is_encoding_supported' => Encoding::isSupported(), 'encodings' => Encoding::listEncodings(), - 'import_charset' => $cfg['Import']['charset'] ?? null, + 'import_charset' => $GLOBALS['cfg']['Import']['charset'] ?? null, 'timeout_passed' => $timeoutPassed, 'offset' => $offset, 'can_convert_kanji' => Encoding::canConvertKanji(), 'charsets' => $charsets, 'is_foreign_key_check' => ForeignKey::isCheckEnabled(), - 'user_upload_dir' => Util::userDir((string) ($cfg['UploadDir'] ?? '')), + 'user_upload_dir' => Util::userDir((string) ($GLOBALS['cfg']['UploadDir'] ?? '')), 'local_files' => Import::getLocalFiles($importList), ]); } diff --git a/libraries/classes/Controllers/Database/Operations/CollationController.php b/libraries/classes/Controllers/Database/Operations/CollationController.php index 50a361a974..07a8335546 100644 --- a/libraries/classes/Controllers/Database/Operations/CollationController.php +++ b/libraries/classes/Controllers/Database/Operations/CollationController.php @@ -36,8 +36,6 @@ final class CollationController extends AbstractController public function __invoke(): void { - global $db, $cfg, $errorUrl; - if (! $this->response->isAjax()) { return; } @@ -51,14 +49,14 @@ final class CollationController extends AbstractController Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } - $sql_query = 'ALTER DATABASE ' . Util::backquote($db) + $sql_query = 'ALTER DATABASE ' . Util::backquote($GLOBALS['db']) . ' DEFAULT' . Util::getCharsetQueryPart($_POST['db_collation'] ?? ''); $this->dbi->query($sql_query); $message = Message::success(); @@ -67,16 +65,16 @@ final class CollationController extends AbstractController * Changes tables charset if requested by the user */ if (isset($_POST['change_all_tables_collations']) && $_POST['change_all_tables_collations'] === 'on') { - [$tables] = Util::getDbInfo($db, ''); + [$tables] = Util::getDbInfo($GLOBALS['db'], ''); foreach ($tables as ['Name' => $tableName]) { - if ($this->dbi->getTable($db, $tableName)->isView()) { + if ($this->dbi->getTable($GLOBALS['db'], $tableName)->isView()) { // Skip views, we can not change the collation of a view. // issue #15283 continue; } $sql_query = 'ALTER TABLE ' - . Util::backquote($db) + . Util::backquote($GLOBALS['db']) . '.' . Util::backquote($tableName) . ' DEFAULT ' @@ -93,7 +91,7 @@ final class CollationController extends AbstractController continue; } - $this->operations->changeAllColumnsCollation($db, $tableName, $_POST['db_collation']); + $this->operations->changeAllColumnsCollation($GLOBALS['db'], $tableName, $_POST['db_collation']); } } diff --git a/libraries/classes/Controllers/Database/OperationsController.php b/libraries/classes/Controllers/Database/OperationsController.php index e785a79819..acb123b0cf 100644 --- a/libraries/classes/Controllers/Database/OperationsController.php +++ b/libraries/classes/Controllers/Database/OperationsController.php @@ -14,7 +14,6 @@ use PhpMyAdmin\Html\Generator; use PhpMyAdmin\Message; use PhpMyAdmin\Operations; use PhpMyAdmin\Plugins; -use PhpMyAdmin\Plugins\Export\ExportSql; use PhpMyAdmin\Query\Utilities; use PhpMyAdmin\ResponseRenderer; use PhpMyAdmin\Template; @@ -65,29 +64,24 @@ class OperationsController extends AbstractController public function __invoke(): void { - global $cfg, $db, $server, $sql_query, $move, $message, $tables_full, $errorUrl; - global $export_sql_plugin, $views, $sqlConstratints, $local_query, $reload, $urlParams, $tables; - global $total_num_tables, $sub_part, $tooltip_truename; - global $db_collation, $tooltip_aliasname, $pos, $is_information_schema, $single_table, $num_tables; - $this->checkUserPrivileges->getPrivileges(); $this->addScriptFiles(['database/operations.js']); - $sql_query = ''; + $GLOBALS['sql_query'] = ''; /** * Rename/move or copy database */ - if (strlen($db) > 0 && (! empty($_POST['db_rename']) || ! empty($_POST['db_copy']))) { + if (strlen($GLOBALS['db']) > 0 && (! empty($_POST['db_rename']) || ! empty($_POST['db_copy']))) { if (! empty($_POST['db_rename'])) { - $move = true; + $GLOBALS['move'] = true; } else { - $move = false; + $GLOBALS['move'] = false; } if (! isset($_POST['newname']) || strlen($_POST['newname']) === 0) { - $message = Message::error(__('The database name is empty!')); + $GLOBALS['message'] = Message::error(__('The database name is empty!')); } else { // lower_case_table_names=1 `DB` becomes `db` if ($this->dbi->getLowerCaseNames() === '1') { @@ -95,12 +89,12 @@ class OperationsController extends AbstractController } if ($_POST['newname'] === $_REQUEST['db']) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __('Cannot copy database to the same name. Change the name and try again.') ); } else { $_error = false; - if ($move || ! empty($_POST['create_database_before_copying'])) { + if ($GLOBALS['move'] || ! empty($_POST['create_database_before_copying'])) { $this->operations->createDbBeforeCopy(); } @@ -110,97 +104,104 @@ class OperationsController extends AbstractController // to avoid selecting alternatively the current and new db // we would need to modify the CREATE definitions to qualify // the db name - $this->operations->runProcedureAndFunctionDefinitions($db); + $this->operations->runProcedureAndFunctionDefinitions($GLOBALS['db']); // go back to current db, just in case - $this->dbi->selectDb($db); + $this->dbi->selectDb($GLOBALS['db']); - $tables_full = $this->dbi->getTablesFull($db); + $GLOBALS['tables_full'] = $this->dbi->getTablesFull($GLOBALS['db']); // remove all foreign key constraints, otherwise we can get errors - /** @var ExportSql $export_sql_plugin */ - $export_sql_plugin = Plugins::getPlugin('export', 'sql', [ + $GLOBALS['export_sql_plugin'] = Plugins::getPlugin('export', 'sql', [ 'export_type' => 'database', - 'single_table' => isset($single_table), + 'single_table' => isset($GLOBALS['single_table']), ]); // create stand-in tables for views - $views = $this->operations->getViewsAndCreateSqlViewStandIn($tables_full, $export_sql_plugin, $db); + $GLOBALS['views'] = $this->operations->getViewsAndCreateSqlViewStandIn( + $GLOBALS['tables_full'], + $GLOBALS['export_sql_plugin'], + $GLOBALS['db'] + ); // copy tables - $sqlConstratints = $this->operations->copyTables($tables_full, $move, $db); + $GLOBALS['sqlConstratints'] = $this->operations->copyTables( + $GLOBALS['tables_full'], + $GLOBALS['move'], + $GLOBALS['db'] + ); // handle the views if (! $_error) { - $this->operations->handleTheViews($views, $move, $db); + $this->operations->handleTheViews($GLOBALS['views'], $GLOBALS['move'], $GLOBALS['db']); } - unset($views); + unset($GLOBALS['views']); // now that all tables exist, create all the accumulated constraints - if (! $_error && count($sqlConstratints) > 0) { - $this->operations->createAllAccumulatedConstraints($sqlConstratints); + if (! $_error && count($GLOBALS['sqlConstratints']) > 0) { + $this->operations->createAllAccumulatedConstraints($GLOBALS['sqlConstratints']); } - unset($sqlConstratints); + unset($GLOBALS['sqlConstratints']); if ($this->dbi->getVersion() >= 50100) { // here DELIMITER is not used because it's not part of the // language; each statement is sent one by one - $this->operations->runEventDefinitionsForDb($db); + $this->operations->runEventDefinitionsForDb($GLOBALS['db']); } // go back to current db, just in case - $this->dbi->selectDb($db); + $this->dbi->selectDb($GLOBALS['db']); // Duplicate the bookmarks for this db (done once for each db) - $this->operations->duplicateBookmarks($_error, $db); + $this->operations->duplicateBookmarks($_error, $GLOBALS['db']); - if (! $_error && $move) { + if (! $_error && $GLOBALS['move']) { if (isset($_POST['adjust_privileges']) && ! empty($_POST['adjust_privileges'])) { - $this->operations->adjustPrivilegesMoveDb($db, $_POST['newname']); + $this->operations->adjustPrivilegesMoveDb($GLOBALS['db'], $_POST['newname']); } /** * cleanup pmadb stuff for this db */ - $this->relationCleanup->database($db); + $this->relationCleanup->database($GLOBALS['db']); // if someday the RENAME DATABASE reappears, do not DROP - $local_query = 'DROP DATABASE ' - . Util::backquote($db) . ';'; - $sql_query .= "\n" . $local_query; - $this->dbi->query($local_query); + $GLOBALS['local_query'] = 'DROP DATABASE ' + . Util::backquote($GLOBALS['db']) . ';'; + $GLOBALS['sql_query'] .= "\n" . $GLOBALS['local_query']; + $this->dbi->query($GLOBALS['local_query']); - $message = Message::success( + $GLOBALS['message'] = Message::success( __('Database %1$s has been renamed to %2$s.') ); - $message->addParam($db); - $message->addParam($_POST['newname']); + $GLOBALS['message']->addParam($GLOBALS['db']); + $GLOBALS['message']->addParam($_POST['newname']); } elseif (! $_error) { if (isset($_POST['adjust_privileges']) && ! empty($_POST['adjust_privileges'])) { - $this->operations->adjustPrivilegesCopyDb($db, $_POST['newname']); + $this->operations->adjustPrivilegesCopyDb($GLOBALS['db'], $_POST['newname']); } - $message = Message::success( + $GLOBALS['message'] = Message::success( __('Database %1$s has been copied to %2$s.') ); - $message->addParam($db); - $message->addParam($_POST['newname']); + $GLOBALS['message']->addParam($GLOBALS['db']); + $GLOBALS['message']->addParam($_POST['newname']); } else { - $message = Message::error(); + $GLOBALS['message'] = Message::error(); } - $reload = true; + $GLOBALS['reload'] = true; /* Change database to be used */ - if (! $_error && $move) { - $db = $_POST['newname']; + if (! $_error && $GLOBALS['move']) { + $GLOBALS['db'] = $_POST['newname']; } elseif (! $_error) { if (isset($_POST['switch_to_new']) && $_POST['switch_to_new'] === 'true') { $_SESSION['pma_switch_to_new'] = true; - $db = $_POST['newname']; + $GLOBALS['db'] = $_POST['newname']; } else { $_SESSION['pma_switch_to_new'] = false; } @@ -213,14 +214,14 @@ class OperationsController extends AbstractController * generate the output with {@link ResponseRenderer} and exit */ if ($this->response->isAjax()) { - $this->response->setRequestStatus($message->isSuccess()); - $this->response->addJSON('message', $message); + $this->response->setRequestStatus($GLOBALS['message']->isSuccess()); + $this->response->addJSON('message', $GLOBALS['message']); $this->response->addJSON('newname', $_POST['newname']); $this->response->addJSON( 'sql_query', - Generator::getMessage('', $sql_query) + Generator::getMessage('', $GLOBALS['sql_query']) ); - $this->response->addJSON('db', $db); + $this->response->addJSON('db', $GLOBALS['db']); return; } @@ -233,86 +234,86 @@ class OperationsController extends AbstractController * (must be done before displaying the menu tabs) */ if (isset($_POST['comment'])) { - $this->relation->setDbComment($db, $_POST['comment']); + $this->relation->setDbComment($GLOBALS['db'], $_POST['comment']); } Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } - $urlParams['goto'] = Url::getFromRoute('/database/operations'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/database/operations'); // Gets the database structure - $sub_part = '_structure'; + $GLOBALS['sub_part'] = '_structure'; [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,, + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],, $isSystemSchema, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part); + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part']); $oldMessage = ''; - if (isset($message)) { - $oldMessage = Generator::getMessage($message, $sql_query); - unset($message); + if (isset($GLOBALS['message'])) { + $oldMessage = Generator::getMessage($GLOBALS['message'], $GLOBALS['sql_query']); + unset($GLOBALS['message']); } - $db_collation = $this->dbi->getDbCollation($db); - $is_information_schema = Utilities::isSystemSchema($db); + $GLOBALS['db_collation'] = $this->dbi->getDbCollation($GLOBALS['db']); + $GLOBALS['is_information_schema'] = Utilities::isSystemSchema($GLOBALS['db']); - if ($is_information_schema) { + if ($GLOBALS['is_information_schema']) { return; } $databaseComment = ''; if ($relationParameters->columnCommentsFeature !== null) { - $databaseComment = $this->relation->getDbComment($db); + $databaseComment = $this->relation->getDbComment($GLOBALS['db']); } $hasAdjustPrivileges = $GLOBALS['db_priv'] && $GLOBALS['table_priv'] && $GLOBALS['col_priv'] && $GLOBALS['proc_priv'] && $GLOBALS['is_reload_priv']; - $isDropDatabaseAllowed = ($this->dbi->isSuperUser() || $cfg['AllowUserDropDatabase']) - && ! $isSystemSchema && $db !== 'mysql'; + $isDropDatabaseAllowed = ($this->dbi->isSuperUser() || $GLOBALS['cfg']['AllowUserDropDatabase']) + && ! $isSystemSchema && $GLOBALS['db'] !== 'mysql'; $switchToNew = isset($_SESSION['pma_switch_to_new']) && $_SESSION['pma_switch_to_new']; $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); $collations = Charsets::getCollations($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); - if (! $relationParameters->hasAllFeatures() && $cfg['PmaNoRelation_DisableWarning'] == false) { - $message = Message::notice( + if (! $relationParameters->hasAllFeatures() && $GLOBALS['cfg']['PmaNoRelation_DisableWarning'] == false) { + $GLOBALS['message'] = Message::notice( __( 'The phpMyAdmin configuration storage has been deactivated. %sFind out why%s.' ) ); - $message->addParamHtml( + $GLOBALS['message']->addParamHtml( '' + . '" data-post="' . Url::getCommon(['db' => $GLOBALS['db']]) . '">' ); - $message->addParamHtml(''); + $GLOBALS['message']->addParamHtml(''); /* Show error if user has configured something, notice elsewhere */ - if (! empty($cfg['Servers'][$server]['pmadb'])) { - $message->isError(true); + if (! empty($GLOBALS['cfg']['Servers'][$GLOBALS['server']]['pmadb'])) { + $GLOBALS['message']->isError(true); } } $this->render('database/operations/index', [ 'message' => $oldMessage, - 'db' => $db, + 'db' => $GLOBALS['db'], 'has_comment' => $relationParameters->columnCommentsFeature !== null, 'db_comment' => $databaseComment, - 'db_collation' => $db_collation, + 'db_collation' => $GLOBALS['db_collation'], 'has_adjust_privileges' => $hasAdjustPrivileges, 'is_drop_database_allowed' => $isDropDatabaseAllowed, 'switch_to_new' => $switchToNew, diff --git a/libraries/classes/Controllers/Database/PrivilegesController.php b/libraries/classes/Controllers/Database/PrivilegesController.php index 8e82f264ad..9b97d8081c 100644 --- a/libraries/classes/Controllers/Database/PrivilegesController.php +++ b/libraries/classes/Controllers/Database/PrivilegesController.php @@ -41,9 +41,7 @@ class PrivilegesController extends AbstractController */ public function __invoke(array $params): string { - global $cfg, $text_dir; - - $scriptName = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); + $scriptName = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); $privileges = []; if ($this->dbi->isSuperUser()) { @@ -54,7 +52,7 @@ class PrivilegesController extends AbstractController 'is_superuser' => $this->dbi->isSuperUser(), 'db' => $params['checkprivsdb'], 'database_url' => $scriptName, - 'text_dir' => $text_dir, + 'text_dir' => $GLOBALS['text_dir'], 'is_createuser' => $this->dbi->isCreateUser(), 'is_grantuser' => $this->dbi->isGrantUser(), 'privileges' => $privileges, diff --git a/libraries/classes/Controllers/Database/QueryByExampleController.php b/libraries/classes/Controllers/Database/QueryByExampleController.php index ce441d61bd..9757b490b0 100644 --- a/libraries/classes/Controllers/Database/QueryByExampleController.php +++ b/libraries/classes/Controllers/Database/QueryByExampleController.php @@ -41,70 +41,66 @@ class QueryByExampleController extends AbstractController public function __invoke(): void { - global $db, $savedSearchList, $savedSearch, $currentSearchId; - global $sql_query, $goto, $sub_part, $tables, $num_tables, $total_num_tables; - global $tooltip_truename, $tooltip_aliasname, $pos, $urlParams, $cfg, $errorUrl; - $savedQbeSearchesFeature = $this->relation->getRelationParameters()->savedQueryByExampleSearchesFeature; - $savedSearchList = []; - $savedSearch = null; - $currentSearchId = null; + $GLOBALS['savedSearchList'] = []; + $GLOBALS['savedSearch'] = null; + $GLOBALS['currentSearchId'] = null; $this->addScriptFiles(['database/qbe.js']); if ($savedQbeSearchesFeature !== null) { //Get saved search list. - $savedSearch = new SavedSearches(); - $savedSearch->setUsername($GLOBALS['cfg']['Server']['user']) - ->setDbname($db); + $GLOBALS['savedSearch'] = new SavedSearches(); + $GLOBALS['savedSearch']->setUsername($GLOBALS['cfg']['Server']['user']) + ->setDbname($GLOBALS['db']); if (! empty($_POST['searchId'])) { - $savedSearch->setId($_POST['searchId']); + $GLOBALS['savedSearch']->setId($_POST['searchId']); } //Action field is sent. if (isset($_POST['action'])) { - $savedSearch->setSearchName($_POST['searchName']); + $GLOBALS['savedSearch']->setSearchName($_POST['searchName']); if ($_POST['action'] === 'create') { - $savedSearch->setId(null) + $GLOBALS['savedSearch']->setId(null) ->setCriterias($_POST) ->save($savedQbeSearchesFeature); } elseif ($_POST['action'] === 'update') { - $savedSearch->setCriterias($_POST) + $GLOBALS['savedSearch']->setCriterias($_POST) ->save($savedQbeSearchesFeature); } elseif ($_POST['action'] === 'delete') { - $savedSearch->delete($savedQbeSearchesFeature); + $GLOBALS['savedSearch']->delete($savedQbeSearchesFeature); //After deletion, reset search. - $savedSearch = new SavedSearches(); - $savedSearch->setUsername($GLOBALS['cfg']['Server']['user']) - ->setDbname($db); + $GLOBALS['savedSearch'] = new SavedSearches(); + $GLOBALS['savedSearch']->setUsername($GLOBALS['cfg']['Server']['user']) + ->setDbname($GLOBALS['db']); $_POST = []; } elseif ($_POST['action'] === 'load') { if (empty($_POST['searchId'])) { //when not loading a search, reset the object. - $savedSearch = new SavedSearches(); - $savedSearch->setUsername($GLOBALS['cfg']['Server']['user']) - ->setDbname($db); + $GLOBALS['savedSearch'] = new SavedSearches(); + $GLOBALS['savedSearch']->setUsername($GLOBALS['cfg']['Server']['user']) + ->setDbname($GLOBALS['db']); $_POST = []; } else { - $savedSearch->load($savedQbeSearchesFeature); + $GLOBALS['savedSearch']->load($savedQbeSearchesFeature); } } //Else, it's an "update query" } - $savedSearchList = $savedSearch->getList($savedQbeSearchesFeature); - $currentSearchId = $savedSearch->getId(); + $GLOBALS['savedSearchList'] = $GLOBALS['savedSearch']->getList($savedQbeSearchesFeature); + $GLOBALS['currentSearchId'] = $GLOBALS['savedSearch']->getId(); } /** * A query has been submitted -> (maybe) execute it */ $hasMessageToDisplay = false; - if (isset($_POST['submit_sql']) && ! empty($sql_query)) { - if (stripos($sql_query, 'SELECT') !== 0) { + if (isset($_POST['submit_sql']) && ! empty($GLOBALS['sql_query'])) { + if (stripos($GLOBALS['sql_query'], 'SELECT') !== 0) { $hasMessageToDisplay = true; } else { - $goto = Url::getFromRoute('/database/sql'); + $GLOBALS['goto'] = Url::getFromRoute('/database/sql'); $sql = new Sql( $this->dbi, @@ -125,42 +121,49 @@ class QueryByExampleController extends AbstractController null, // extra_data null, // message_to_show null, // sql_data - $goto, // goto + $GLOBALS['goto'], // goto null, // disp_query null, // disp_message - $sql_query, // sql_query + $GLOBALS['sql_query'], // sql_query null // complete_query )); } } - $sub_part = '_qbe'; + $GLOBALS['sub_part'] = '_qbe'; Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } - $urlParams['goto'] = Url::getFromRoute('/database/qbe'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/database/qbe'); [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part']); - $databaseQbe = new Qbe($this->relation, $this->template, $this->dbi, $db, $savedSearchList, $savedSearch); + $databaseQbe = new Qbe( + $this->relation, + $this->template, + $this->dbi, + $GLOBALS['db'], + $GLOBALS['savedSearchList'], + $GLOBALS['savedSearch'] + ); $this->render('database/qbe/index', [ - 'url_params' => $urlParams, + 'url_params' => $GLOBALS['urlParams'], 'has_message_to_display' => $hasMessageToDisplay, 'selection_form_html' => $databaseQbe->getSelectionForm(), ]); diff --git a/libraries/classes/Controllers/Database/RoutinesController.php b/libraries/classes/Controllers/Database/RoutinesController.php index 73c94f544c..1f862fca14 100644 --- a/libraries/classes/Controllers/Database/RoutinesController.php +++ b/libraries/classes/Controllers/Database/RoutinesController.php @@ -41,10 +41,6 @@ class RoutinesController extends AbstractController public function __invoke(): void { - global $db, $table, $tables, $num_tables, $total_num_tables, $sub_part; - global $tooltip_truename, $tooltip_aliasname, $pos; - global $errors, $errorUrl, $urlParams, $cfg; - $this->addScriptFiles(['database/routines.js']); $type = $_REQUEST['type'] ?? null; @@ -55,45 +51,45 @@ class RoutinesController extends AbstractController /** * Displays the header and tabs */ - if (! empty($table) && in_array($table, $this->dbi->getTables($db))) { + if (! empty($GLOBALS['table']) && in_array($GLOBALS['table'], $this->dbi->getTables($GLOBALS['db']))) { Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); } else { - $table = ''; + $GLOBALS['table'] = ''; Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part ?? ''); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part'] ?? ''); } - } elseif (strlen($db) > 0) { - $this->dbi->selectDb($db); + } elseif (strlen($GLOBALS['db']) > 0) { + $this->dbi->selectDb($GLOBALS['db']); } /** * Keep a list of errors that occurred while * processing an 'Add' or 'Edit' operation. */ - $errors = []; + $GLOBALS['errors'] = []; $routines = new Routines($this->dbi, $this->template, $this->response); @@ -105,7 +101,7 @@ class RoutinesController extends AbstractController $type = null; } - $items = $this->dbi->getRoutines($db, $type); + $items = $this->dbi->getRoutines($GLOBALS['db'], $type); $isAjax = $this->response->isAjax() && empty($_REQUEST['ajax_page_request']); $rows = ''; @@ -114,11 +110,11 @@ class RoutinesController extends AbstractController } $this->render('database/routines/index', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'items' => $items, 'rows' => $rows, - 'has_privilege' => Util::currentUserHasPrivilege('CREATE ROUTINE', $db, $table), + 'has_privilege' => Util::currentUserHasPrivilege('CREATE ROUTINE', $GLOBALS['db'], $GLOBALS['table']), ]); } } diff --git a/libraries/classes/Controllers/Database/SearchController.php b/libraries/classes/Controllers/Database/SearchController.php index 61c1a8538f..42b94e08e1 100644 --- a/libraries/classes/Controllers/Database/SearchController.php +++ b/libraries/classes/Controllers/Database/SearchController.php @@ -28,9 +28,6 @@ class SearchController extends AbstractController public function __invoke(): void { - global $cfg, $db, $errorUrl, $urlParams, $tables, $num_tables, $total_num_tables, $sub_part; - global $tooltip_truename, $tooltip_aliasname, $pos; - $this->addScriptFiles([ 'database/search.js', 'vendor/stickyfill.min.js', @@ -40,39 +37,39 @@ class SearchController extends AbstractController Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } // If config variable $cfg['UseDbSearch'] is on false : exit. - if (! $cfg['UseDbSearch']) { + if (! $GLOBALS['cfg']['UseDbSearch']) { Generator::mysqlDie( __('Access denied!'), '', false, - $errorUrl + $GLOBALS['errorUrl'] ); } - $urlParams['goto'] = Url::getFromRoute('/database/search'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/database/search'); // Create a database search instance - $databaseSearch = new Search($this->dbi, $db, $this->template); + $databaseSearch = new Search($this->dbi, $GLOBALS['db'], $this->template); // Display top links if we are not in an Ajax request if (! $this->response->isAjax()) { [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part ?? ''); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part'] ?? ''); } // Main search form has been submitted, get results diff --git a/libraries/classes/Controllers/Database/SqlAutoCompleteController.php b/libraries/classes/Controllers/Database/SqlAutoCompleteController.php index 64fcb146ca..f7fab89a75 100644 --- a/libraries/classes/Controllers/Database/SqlAutoCompleteController.php +++ b/libraries/classes/Controllers/Database/SqlAutoCompleteController.php @@ -27,20 +27,18 @@ class SqlAutoCompleteController extends AbstractController public function __invoke(): void { - global $cfg, $db, $sql_autocomplete; - - $sql_autocomplete = true; - if ($cfg['EnableAutocompleteForTablesAndColumns']) { - $db = $_POST['db'] ?? $db; - $sql_autocomplete = []; - if ($db) { - $tableNames = $this->dbi->getTables($db); + $GLOBALS['sql_autocomplete'] = true; + if ($GLOBALS['cfg']['EnableAutocompleteForTablesAndColumns']) { + $GLOBALS['db'] = $_POST['db'] ?? $GLOBALS['db']; + $GLOBALS['sql_autocomplete'] = []; + if ($GLOBALS['db']) { + $tableNames = $this->dbi->getTables($GLOBALS['db']); foreach ($tableNames as $tableName) { - $sql_autocomplete[$tableName] = $this->dbi->getColumns($db, $tableName); + $GLOBALS['sql_autocomplete'][$tableName] = $this->dbi->getColumns($GLOBALS['db'], $tableName); } } } - $this->response->addJSON(['tables' => json_encode($sql_autocomplete)]); + $this->response->addJSON(['tables' => json_encode($GLOBALS['sql_autocomplete'])]); } } diff --git a/libraries/classes/Controllers/Database/SqlController.php b/libraries/classes/Controllers/Database/SqlController.php index d6418a6937..15a47b805f 100644 --- a/libraries/classes/Controllers/Database/SqlController.php +++ b/libraries/classes/Controllers/Database/SqlController.php @@ -30,8 +30,6 @@ class SqlController extends AbstractController public function __invoke(): void { - global $goto, $back, $db, $cfg, $errorUrl; - $this->addScriptFiles([ 'makegrid.js', 'vendor/jquery/jquery.uitablefilter.js', @@ -45,8 +43,8 @@ class SqlController extends AbstractController Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; @@ -56,11 +54,11 @@ class SqlController extends AbstractController * After a syntax error, we return to this script * with the typed query in the textarea. */ - $goto = Url::getFromRoute('/database/sql'); - $back = $goto; + $GLOBALS['goto'] = Url::getFromRoute('/database/sql'); + $GLOBALS['back'] = $GLOBALS['goto']; $this->response->addHTML($this->sqlQueryForm->getHtml( - $db, + $GLOBALS['db'], '', true, false, diff --git a/libraries/classes/Controllers/Database/Structure/AddPrefixController.php b/libraries/classes/Controllers/Database/Structure/AddPrefixController.php index 9108dfb781..d46765faaf 100644 --- a/libraries/classes/Controllers/Database/Structure/AddPrefixController.php +++ b/libraries/classes/Controllers/Database/Structure/AddPrefixController.php @@ -12,8 +12,6 @@ final class AddPrefixController extends AbstractController { public function __invoke(): void { - global $db; - $selected = $_POST['selected_tbl'] ?? []; if (empty($selected)) { @@ -23,7 +21,7 @@ final class AddPrefixController extends AbstractController return; } - $params = ['db' => $db]; + $params = ['db' => $GLOBALS['db']]; foreach ($selected as $selectedValue) { $params['selected'][] = $selectedValue; } diff --git a/libraries/classes/Controllers/Database/Structure/AddPrefixTableController.php b/libraries/classes/Controllers/Database/Structure/AddPrefixTableController.php index 012b4d3148..134eeb24a0 100644 --- a/libraries/classes/Controllers/Database/Structure/AddPrefixTableController.php +++ b/libraries/classes/Controllers/Database/Structure/AddPrefixTableController.php @@ -35,11 +35,9 @@ final class AddPrefixTableController extends AbstractController public function __invoke(): void { - global $db, $message, $sql_query; - $selected = $_POST['selected'] ?? []; - $sql_query = ''; + $GLOBALS['sql_query'] = ''; $selectedCount = count($selected); for ($i = 0; $i < $selectedCount; $i++) { @@ -47,15 +45,15 @@ final class AddPrefixTableController extends AbstractController $aQuery = 'ALTER TABLE ' . Util::backquote($selected[$i]) . ' RENAME ' . Util::backquote($newTableName); - $sql_query .= $aQuery . ';' . "\n"; - $this->dbi->selectDb($db); + $GLOBALS['sql_query'] .= $aQuery . ';' . "\n"; + $this->dbi->selectDb($GLOBALS['db']); $this->dbi->query($aQuery); } - $message = Message::success(); + $GLOBALS['message'] = Message::success(); if (empty($_POST['message'])) { - $_POST['message'] = $message; + $_POST['message'] = $GLOBALS['message']; } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Database/Structure/CentralColumns/AddController.php b/libraries/classes/Controllers/Database/Structure/CentralColumns/AddController.php index fc91ab858b..fd79280f94 100644 --- a/libraries/classes/Controllers/Database/Structure/CentralColumns/AddController.php +++ b/libraries/classes/Controllers/Database/Structure/CentralColumns/AddController.php @@ -35,8 +35,6 @@ final class AddController extends AbstractController public function __invoke(): void { - global $message; - $selected = $_POST['selected_tbl'] ?? []; if (empty($selected)) { @@ -49,7 +47,7 @@ final class AddController extends AbstractController $centralColumns = new CentralColumns($this->dbi); $error = $centralColumns->syncUniqueColumns($selected); - $message = $error instanceof Message ? $error : Message::success(__('Success!')); + $GLOBALS['message'] = $error instanceof Message ? $error : Message::success(__('Success!')); unset($_POST['submit_mult']); diff --git a/libraries/classes/Controllers/Database/Structure/CentralColumns/MakeConsistentController.php b/libraries/classes/Controllers/Database/Structure/CentralColumns/MakeConsistentController.php index f95ad2ba94..23fa23cc9f 100644 --- a/libraries/classes/Controllers/Database/Structure/CentralColumns/MakeConsistentController.php +++ b/libraries/classes/Controllers/Database/Structure/CentralColumns/MakeConsistentController.php @@ -35,8 +35,6 @@ final class MakeConsistentController extends AbstractController public function __invoke(): void { - global $db, $message; - $selected = $_POST['selected_tbl'] ?? []; if (empty($selected)) { @@ -47,9 +45,9 @@ final class MakeConsistentController extends AbstractController } $centralColumns = new CentralColumns($this->dbi); - $error = $centralColumns->makeConsistentWithList($db, $selected); + $error = $centralColumns->makeConsistentWithList($GLOBALS['db'], $selected); - $message = $error instanceof Message ? $error : Message::success(__('Success!')); + $GLOBALS['message'] = $error instanceof Message ? $error : Message::success(__('Success!')); unset($_POST['submit_mult']); diff --git a/libraries/classes/Controllers/Database/Structure/CentralColumns/RemoveController.php b/libraries/classes/Controllers/Database/Structure/CentralColumns/RemoveController.php index 7f113240f9..e21606fd38 100644 --- a/libraries/classes/Controllers/Database/Structure/CentralColumns/RemoveController.php +++ b/libraries/classes/Controllers/Database/Structure/CentralColumns/RemoveController.php @@ -35,8 +35,6 @@ final class RemoveController extends AbstractController public function __invoke(): void { - global $message; - $selected = $_POST['selected_tbl'] ?? []; if (empty($selected)) { @@ -49,7 +47,7 @@ final class RemoveController extends AbstractController $centralColumns = new CentralColumns($this->dbi); $error = $centralColumns->deleteColumnsFromList($_POST['db'], $selected); - $message = $error instanceof Message ? $error : Message::success(__('Success!')); + $GLOBALS['message'] = $error instanceof Message ? $error : Message::success(__('Success!')); unset($_POST['submit_mult']); diff --git a/libraries/classes/Controllers/Database/Structure/ChangePrefixFormController.php b/libraries/classes/Controllers/Database/Structure/ChangePrefixFormController.php index 54d7692708..4ea01e9171 100644 --- a/libraries/classes/Controllers/Database/Structure/ChangePrefixFormController.php +++ b/libraries/classes/Controllers/Database/Structure/ChangePrefixFormController.php @@ -12,8 +12,6 @@ final class ChangePrefixFormController extends AbstractController { public function __invoke(): void { - global $db; - $selected = $_POST['selected_tbl'] ?? []; $submitMult = $_POST['submit_mult'] ?? ''; @@ -29,7 +27,7 @@ final class ChangePrefixFormController extends AbstractController $route = '/database/structure/copy-table-with-prefix'; } - $urlParams = ['db' => $db]; + $urlParams = ['db' => $GLOBALS['db']]; foreach ($selected as $selectedValue) { $urlParams['selected'][] = $selectedValue; } diff --git a/libraries/classes/Controllers/Database/Structure/CopyFormController.php b/libraries/classes/Controllers/Database/Structure/CopyFormController.php index ce4c2e8dd5..0d376e83a7 100644 --- a/libraries/classes/Controllers/Database/Structure/CopyFormController.php +++ b/libraries/classes/Controllers/Database/Structure/CopyFormController.php @@ -12,8 +12,6 @@ final class CopyFormController extends AbstractController { public function __invoke(): void { - global $db, $dblist; - $selected = $_POST['selected_tbl'] ?? []; if (empty($selected)) { @@ -23,14 +21,14 @@ final class CopyFormController extends AbstractController return; } - $urlParams = ['db' => $db]; + $urlParams = ['db' => $GLOBALS['db']]; foreach ($selected as $selectedValue) { $urlParams['selected'][] = $selectedValue; } - $databasesList = $dblist->databases; + $databasesList = $GLOBALS['dblist']->databases; foreach ($databasesList as $key => $databaseName) { - if ($databaseName == $db) { + if ($databaseName == $GLOBALS['db']) { $databasesList->offsetUnset($key); break; } diff --git a/libraries/classes/Controllers/Database/Structure/CopyTableController.php b/libraries/classes/Controllers/Database/Structure/CopyTableController.php index 36dd957c08..d7d3ee9d39 100644 --- a/libraries/classes/Controllers/Database/Structure/CopyTableController.php +++ b/libraries/classes/Controllers/Database/Structure/CopyTableController.php @@ -35,15 +35,13 @@ final class CopyTableController extends AbstractController public function __invoke(): void { - global $db, $message; - $selected = $_POST['selected'] ?? []; $targetDb = $_POST['target_db'] ?? null; $selectedCount = count($selected); for ($i = 0; $i < $selectedCount; $i++) { Table::moveCopy( - $db, + $GLOBALS['db'], $selected[$i], $targetDb, $selected[$i], @@ -57,13 +55,13 @@ final class CopyTableController extends AbstractController continue; } - $this->operations->adjustPrivilegesCopyTable($db, $selected[$i], $targetDb, $selected[$i]); + $this->operations->adjustPrivilegesCopyTable($GLOBALS['db'], $selected[$i], $targetDb, $selected[$i]); } - $message = Message::success(); + $GLOBALS['message'] = Message::success(); if (empty($_POST['message'])) { - $_POST['message'] = $message; + $_POST['message'] = $GLOBALS['message']; } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Database/Structure/CopyTableWithPrefixController.php b/libraries/classes/Controllers/Database/Structure/CopyTableWithPrefixController.php index 8915287972..97974449cb 100644 --- a/libraries/classes/Controllers/Database/Structure/CopyTableWithPrefixController.php +++ b/libraries/classes/Controllers/Database/Structure/CopyTableWithPrefixController.php @@ -31,8 +31,6 @@ final class CopyTableWithPrefixController extends AbstractController public function __invoke(): void { - global $db, $message; - $selected = $_POST['selected'] ?? []; $fromPrefix = $_POST['from_prefix'] ?? null; $toPrefix = $_POST['to_prefix'] ?? null; @@ -44,9 +42,9 @@ final class CopyTableWithPrefixController extends AbstractController $newTableName = $toPrefix . mb_substr($current, mb_strlen((string) $fromPrefix)); Table::moveCopy( - $db, + $GLOBALS['db'], $current, - $db, + $GLOBALS['db'], $newTableName, 'data', false, @@ -55,10 +53,10 @@ final class CopyTableWithPrefixController extends AbstractController ); } - $message = Message::success(); + $GLOBALS['message'] = Message::success(); if (empty($_POST['message'])) { - $_POST['message'] = $message; + $_POST['message'] = $GLOBALS['message']; } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Database/Structure/DropFormController.php b/libraries/classes/Controllers/Database/Structure/DropFormController.php index 033ccbf15a..1cd46ee229 100644 --- a/libraries/classes/Controllers/Database/Structure/DropFormController.php +++ b/libraries/classes/Controllers/Database/Structure/DropFormController.php @@ -28,8 +28,6 @@ final class DropFormController extends AbstractController public function __invoke(): void { - global $db; - $selected = $_POST['selected_tbl'] ?? []; if (empty($selected)) { @@ -39,7 +37,7 @@ final class DropFormController extends AbstractController return; } - $views = $this->dbi->getVirtualTables($db); + $views = $this->dbi->getVirtualTables($GLOBALS['db']); $fullQueryViews = ''; $fullQuery = ''; @@ -63,7 +61,7 @@ final class DropFormController extends AbstractController $fullQuery .= $fullQueryViews . ';
' . "\n"; } - $urlParams = ['db' => $db]; + $urlParams = ['db' => $GLOBALS['db']]; foreach ($selected as $selectedValue) { $urlParams['selected'][] = $selectedValue; } diff --git a/libraries/classes/Controllers/Database/Structure/DropTableController.php b/libraries/classes/Controllers/Database/Structure/DropTableController.php index 96290eb7c5..108a2fba8b 100644 --- a/libraries/classes/Controllers/Database/Structure/DropTableController.php +++ b/libraries/classes/Controllers/Database/Structure/DropTableController.php @@ -44,16 +44,14 @@ final class DropTableController extends AbstractController public function __invoke(): void { - global $db, $message, $reload, $sql_query; - - $reload = $_POST['reload'] ?? $reload ?? null; + $GLOBALS['reload'] = $_POST['reload'] ?? $GLOBALS['reload'] ?? null; $multBtn = $_POST['mult_btn'] ?? ''; $selected = $_POST['selected'] ?? []; - $views = $this->dbi->getVirtualTables($db); + $views = $this->dbi->getVirtualTables($GLOBALS['db']); if ($multBtn !== __('Yes')) { - $message = Message::success(__('No change')); + $GLOBALS['message'] = Message::success(__('No change')); if (empty($_POST['message'])) { $_POST['message'] = Message::success(); @@ -67,27 +65,28 @@ final class DropTableController extends AbstractController } $defaultFkCheckValue = ForeignKey::handleDisableCheckInit(); - $sql_query = ''; + $GLOBALS['sql_query'] = ''; $sqlQueryViews = ''; $selectedCount = count($selected); for ($i = 0; $i < $selectedCount; $i++) { - $this->relationCleanup->table($db, $selected[$i]); + $this->relationCleanup->table($GLOBALS['db'], $selected[$i]); $current = $selected[$i]; if (! empty($views) && in_array($current, $views)) { $sqlQueryViews .= (empty($sqlQueryViews) ? 'DROP VIEW ' : ', ') . Util::backquote($current); } else { - $sql_query .= (empty($sql_query) ? 'DROP TABLE ' : ', ') . Util::backquote($current); + $GLOBALS['sql_query'] .= (empty($GLOBALS['sql_query']) ? 'DROP TABLE ' : ', ') + . Util::backquote($current); } - $reload = 1; + $GLOBALS['reload'] = 1; } - if (! empty($sql_query)) { - $sql_query .= ';'; + if (! empty($GLOBALS['sql_query'])) { + $GLOBALS['sql_query'] .= ';'; } elseif (! empty($sqlQueryViews)) { - $sql_query = $sqlQueryViews . ';'; + $GLOBALS['sql_query'] = $sqlQueryViews . ';'; unset($sqlQueryViews); } @@ -102,25 +101,25 @@ final class DropTableController extends AbstractController } } - $this->dbi->selectDb($db); - $result = $this->dbi->tryQuery($sql_query); + $this->dbi->selectDb($GLOBALS['db']); + $result = $this->dbi->tryQuery($GLOBALS['sql_query']); if ($result && ! empty($sqlQueryViews)) { - $sql_query .= ' ' . $sqlQueryViews . ';'; + $GLOBALS['sql_query'] .= ' ' . $sqlQueryViews . ';'; $result = $this->dbi->tryQuery($sqlQueryViews); unset($sqlQueryViews); } if (! $result) { - $message = Message::error($this->dbi->getError()); + $GLOBALS['message'] = Message::error($this->dbi->getError()); } ForeignKey::handleDisableCheckCleanup($defaultFkCheckValue); - $message = Message::success(); + $GLOBALS['message'] = Message::success(); if (empty($_POST['message'])) { - $_POST['message'] = $message; + $_POST['message'] = $GLOBALS['message']; } unset($_POST['mult_btn']); diff --git a/libraries/classes/Controllers/Database/Structure/EmptyFormController.php b/libraries/classes/Controllers/Database/Structure/EmptyFormController.php index 1f039a836b..8609b5935c 100644 --- a/libraries/classes/Controllers/Database/Structure/EmptyFormController.php +++ b/libraries/classes/Controllers/Database/Structure/EmptyFormController.php @@ -15,8 +15,6 @@ final class EmptyFormController extends AbstractController { public function __invoke(): void { - global $db; - $selected = $_POST['selected_tbl'] ?? []; if (empty($selected)) { @@ -27,7 +25,7 @@ final class EmptyFormController extends AbstractController } $fullQuery = ''; - $urlParams = ['db' => $db]; + $urlParams = ['db' => $GLOBALS['db']]; foreach ($selected as $selectedValue) { $fullQuery .= 'TRUNCATE '; diff --git a/libraries/classes/Controllers/Database/Structure/EmptyTableController.php b/libraries/classes/Controllers/Database/Structure/EmptyTableController.php index f050224a03..9acc32c8f9 100644 --- a/libraries/classes/Controllers/Database/Structure/EmptyTableController.php +++ b/libraries/classes/Controllers/Database/Structure/EmptyTableController.php @@ -63,29 +63,27 @@ final class EmptyTableController extends AbstractController public function __invoke(): void { - global $db, $table, $message, $sql_query; - $multBtn = $_POST['mult_btn'] ?? ''; $selected = $_POST['selected'] ?? []; if ($multBtn !== __('Yes')) { $this->flash->addMessage('success', __('No change')); - $this->redirect('/database/structure', ['db' => $db]); + $this->redirect('/database/structure', ['db' => $GLOBALS['db']]); return; } $defaultFkCheckValue = ForeignKey::handleDisableCheckInit(); - $sql_query = ''; + $GLOBALS['sql_query'] = ''; $selectedCount = count($selected); for ($i = 0; $i < $selectedCount; $i++) { $aQuery = 'TRUNCATE '; $aQuery .= Util::backquote($selected[$i]); - $sql_query .= $aQuery . ';' . "\n"; - $this->dbi->selectDb($db); + $GLOBALS['sql_query'] .= $aQuery . ';' . "\n"; + $this->dbi->selectDb($GLOBALS['db']); $this->dbi->query($aQuery); } @@ -99,15 +97,15 @@ final class EmptyTableController extends AbstractController $this->template ); - $_REQUEST['pos'] = $sql->calculatePosForLastPage($db, $table, $_REQUEST['pos']); + $_REQUEST['pos'] = $sql->calculatePosForLastPage($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['pos']); } ForeignKey::handleDisableCheckCleanup($defaultFkCheckValue); - $message = Message::success(); + $GLOBALS['message'] = Message::success(); if (empty($_POST['message'])) { - $_POST['message'] = $message; + $_POST['message'] = $GLOBALS['message']; } unset($_POST['mult_btn']); diff --git a/libraries/classes/Controllers/Database/Structure/FavoriteTableController.php b/libraries/classes/Controllers/Database/Structure/FavoriteTableController.php index 12326498b6..040d0eb005 100644 --- a/libraries/classes/Controllers/Database/Structure/FavoriteTableController.php +++ b/libraries/classes/Controllers/Database/Structure/FavoriteTableController.php @@ -32,8 +32,6 @@ final class FavoriteTableController extends AbstractController public function __invoke(): void { - global $cfg, $db, $errorUrl; - $parameters = [ 'favorite_table' => $_REQUEST['favorite_table'] ?? null, 'favoriteTables' => $_REQUEST['favoriteTables'] ?? null, @@ -42,8 +40,8 @@ final class FavoriteTableController extends AbstractController Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase() || ! $this->response->isAjax()) { return; @@ -57,7 +55,7 @@ final class FavoriteTableController extends AbstractController } // Required to keep each user's preferences separate. - $user = sha1($cfg['Server']['user']); + $user = sha1($GLOBALS['cfg']['Server']['user']); // Request for Synchronization of favorite tables. if (isset($parameters['sync_favorite_tables'])) { @@ -86,7 +84,7 @@ final class FavoriteTableController extends AbstractController } elseif (isset($_REQUEST['add_favorite'])) { if (! $alreadyFavorite) { $numTables = count($favoriteInstance->getTables()); - if ($numTables == $cfg['NumFavoriteTables']) { + if ($numTables == $GLOBALS['cfg']['NumFavoriteTables']) { $changes = false; } else { // Otherwise add to favorite list. diff --git a/libraries/classes/Controllers/Database/Structure/RealRowCountController.php b/libraries/classes/Controllers/Database/Structure/RealRowCountController.php index 3535b18d7b..40c0a876e4 100644 --- a/libraries/classes/Controllers/Database/Structure/RealRowCountController.php +++ b/libraries/classes/Controllers/Database/Structure/RealRowCountController.php @@ -29,8 +29,6 @@ final class RealRowCountController extends AbstractController public function __invoke(): void { - global $cfg, $db, $errorUrl; - $parameters = [ 'real_row_count_all' => $_REQUEST['real_row_count_all'] ?? null, 'table' => $_REQUEST['table'] ?? null, @@ -38,8 +36,8 @@ final class RealRowCountController extends AbstractController Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase() || ! $this->response->isAjax()) { return; diff --git a/libraries/classes/Controllers/Database/Structure/ReplacePrefixController.php b/libraries/classes/Controllers/Database/Structure/ReplacePrefixController.php index 42d054b4ab..c6a06c0d39 100644 --- a/libraries/classes/Controllers/Database/Structure/ReplacePrefixController.php +++ b/libraries/classes/Controllers/Database/Structure/ReplacePrefixController.php @@ -37,13 +37,11 @@ final class ReplacePrefixController extends AbstractController public function __invoke(): void { - global $db, $message, $sql_query; - $selected = $_POST['selected'] ?? []; $fromPrefix = $_POST['from_prefix'] ?? ''; $toPrefix = $_POST['to_prefix'] ?? ''; - $sql_query = ''; + $GLOBALS['sql_query'] = ''; $selectedCount = count($selected); for ($i = 0; $i < $selectedCount; $i++) { @@ -59,15 +57,15 @@ final class ReplacePrefixController extends AbstractController $aQuery = 'ALTER TABLE ' . Util::backquote($selected[$i]) . ' RENAME ' . Util::backquote($newTableName); - $sql_query .= $aQuery . ';' . "\n"; - $this->dbi->selectDb($db); + $GLOBALS['sql_query'] .= $aQuery . ';' . "\n"; + $this->dbi->selectDb($GLOBALS['db']); $this->dbi->query($aQuery); } - $message = Message::success(); + $GLOBALS['message'] = Message::success(); if (empty($_POST['message'])) { - $_POST['message'] = $message; + $_POST['message'] = $GLOBALS['message']; } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Database/StructureController.php b/libraries/classes/Controllers/Database/StructureController.php index 1ea1072ea7..76188b64f1 100644 --- a/libraries/classes/Controllers/Database/StructureController.php +++ b/libraries/classes/Controllers/Database/StructureController.php @@ -135,8 +135,6 @@ class StructureController extends AbstractController public function __invoke(): void { - global $cfg, $db, $errorUrl; - $parameters = [ 'sort' => $_REQUEST['sort'] ?? null, 'sort_order' => $_REQUEST['sort_order'] ?? null, @@ -144,8 +142,8 @@ class StructureController extends AbstractController Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; @@ -162,7 +160,7 @@ class StructureController extends AbstractController if ($this->totalNumTables > 0 && $this->position > $this->totalNumTables) { $this->redirect('/database/structure', [ 'db' => $GLOBALS['db'], - 'pos' => max(0, $this->totalNumTables - $cfg['MaxTableList']), + 'pos' => max(0, $this->totalNumTables - $GLOBALS['cfg']['MaxTableList']), 'reload' => 1, ]); } @@ -193,7 +191,7 @@ class StructureController extends AbstractController $urlParams, Url::getFromRoute('/database/structure'), 'frame_content', - $cfg['MaxTableList'] + $GLOBALS['cfg']['MaxTableList'] ); $tableList = $this->displayTableList($replicaInfo); diff --git a/libraries/classes/Controllers/Database/TrackingController.php b/libraries/classes/Controllers/Database/TrackingController.php index 47ed9d42e7..e4e6e6fe8c 100644 --- a/libraries/classes/Controllers/Database/TrackingController.php +++ b/libraries/classes/Controllers/Database/TrackingController.php @@ -45,45 +45,41 @@ class TrackingController extends AbstractController public function __invoke(): void { - global $db, $text_dir, $urlParams, $tables, $num_tables; - global $total_num_tables, $sub_part, $pos, $data, $cfg; - global $tooltip_truename, $tooltip_aliasname, $errorUrl; - $this->addScriptFiles(['vendor/jquery/jquery.tablesorter.js', 'database/tracking.js']); Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } - $urlParams['goto'] = Url::getFromRoute('/table/tracking'); - $urlParams['back'] = Url::getFromRoute('/database/tracking'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/table/tracking'); + $GLOBALS['urlParams']['back'] = Url::getFromRoute('/database/tracking'); // Get the database structure - $sub_part = '_structure'; + $GLOBALS['sub_part'] = '_structure'; [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,, + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],, $isSystemSchema, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part); + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part']); if (isset($_POST['delete_tracking'], $_POST['table'])) { - Tracker::deleteTracking($db, $_POST['table']); + Tracker::deleteTracking($GLOBALS['db'], $_POST['table']); echo Message::success( __('Tracking data deleted successfully.') )->getDisplay(); } elseif (isset($_POST['submit_create_version'])) { - $this->tracking->createTrackingForMultipleTables($db, $_POST['selected']); + $this->tracking->createTrackingForMultipleTables($GLOBALS['db'], $_POST['selected']); echo Message::success( sprintf( __( @@ -96,7 +92,7 @@ class TrackingController extends AbstractController if (! empty($_POST['selected_tbl'])) { if ($_POST['submit_mult'] === 'delete_tracking') { foreach ($_POST['selected_tbl'] as $table) { - Tracker::deleteTracking($db, $table); + Tracker::deleteTracking($GLOBALS['db'], $table); } echo Message::success( @@ -105,12 +101,12 @@ class TrackingController extends AbstractController } elseif ($_POST['submit_mult'] === 'track') { echo $this->template->render('create_tracking_version', [ 'route' => '/database/tracking', - 'url_params' => $urlParams, + 'url_params' => $GLOBALS['urlParams'], 'last_version' => 0, - 'db' => $db, + 'db' => $GLOBALS['db'], 'selected' => $_POST['selected_tbl'], 'type' => 'both', - 'default_statements' => $cfg['Server']['tracking_default_statements'], + 'default_statements' => $GLOBALS['cfg']['Server']['tracking_default_statements'], ]); return; @@ -123,31 +119,31 @@ class TrackingController extends AbstractController } // Get tracked data about the database - $data = Tracker::getTrackedData($db, '', '1'); + $GLOBALS['data'] = Tracker::getTrackedData($GLOBALS['db'], '', '1'); // No tables present and no log exist - if ($num_tables == 0 && count($data['ddlog']) === 0) { + if ($GLOBALS['num_tables'] == 0 && count($GLOBALS['data']['ddlog']) === 0) { echo '

' , __('No tables found in database.') , '

' , "\n"; if (empty($isSystemSchema)) { $checkUserPrivileges = new CheckUserPrivileges($this->dbi); $checkUserPrivileges->getPrivileges(); - echo $this->template->render('database/create_table', ['db' => $db]); + echo $this->template->render('database/create_table', ['db' => $GLOBALS['db']]); } return; } - echo $this->tracking->getHtmlForDbTrackingTables($db, $urlParams, $text_dir); + echo $this->tracking->getHtmlForDbTrackingTables($GLOBALS['db'], $GLOBALS['urlParams'], $GLOBALS['text_dir']); // If available print out database log - if (count($data['ddlog']) <= 0) { + if (count($GLOBALS['data']['ddlog']) <= 0) { return; } $log = ''; - foreach ($data['ddlog'] as $entry) { + foreach ($GLOBALS['data']['ddlog'] as $entry) { $log .= '# ' . $entry['date'] . ' ' . $entry['username'] . "\n" . $entry['statement'] . "\n"; } diff --git a/libraries/classes/Controllers/Database/TriggersController.php b/libraries/classes/Controllers/Database/TriggersController.php index a291fcc6eb..fce9c86333 100644 --- a/libraries/classes/Controllers/Database/TriggersController.php +++ b/libraries/classes/Controllers/Database/TriggersController.php @@ -32,55 +32,51 @@ class TriggersController extends AbstractController public function __invoke(): void { - global $db, $table, $tables, $num_tables, $total_num_tables, $sub_part; - global $tooltip_truename, $tooltip_aliasname, $pos; - global $errors, $urlParams, $errorUrl, $cfg; - $this->addScriptFiles(['database/triggers.js']); if (! $this->response->isAjax()) { /** * Displays the header and tabs */ - if (! empty($table) && in_array($table, $this->dbi->getTables($db))) { + if (! empty($GLOBALS['table']) && in_array($GLOBALS['table'], $this->dbi->getTables($GLOBALS['db']))) { Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); } else { - $table = ''; + $GLOBALS['table'] = ''; Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part ?? ''); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part'] ?? ''); } - } elseif (strlen($db) > 0) { - $this->dbi->selectDb($db); + } elseif (strlen($GLOBALS['db']) > 0) { + $this->dbi->selectDb($GLOBALS['db']); } /** * Keep a list of errors that occurred while * processing an 'Add' or 'Edit' operation. */ - $errors = []; + $GLOBALS['errors'] = []; $triggers = new Triggers($this->dbi, $this->template, $this->response); $triggers->main(); diff --git a/libraries/classes/Controllers/DatabaseController.php b/libraries/classes/Controllers/DatabaseController.php index 573dfaa917..ed737024cf 100644 --- a/libraries/classes/Controllers/DatabaseController.php +++ b/libraries/classes/Controllers/DatabaseController.php @@ -8,8 +8,6 @@ final class DatabaseController extends AbstractController { public function __invoke(): void { - global $dblist; - - $this->response->addJSON(['databases' => $dblist->databases]); + $this->response->addJSON(['databases' => $GLOBALS['dblist']->databases]); } } diff --git a/libraries/classes/Controllers/ErrorReportController.php b/libraries/classes/Controllers/ErrorReportController.php index d263a840c2..4166846295 100644 --- a/libraries/classes/Controllers/ErrorReportController.php +++ b/libraries/classes/Controllers/ErrorReportController.php @@ -46,8 +46,6 @@ class ErrorReportController extends AbstractController public function __invoke(ServerRequest $request): void { - global $cfg; - /** @var string $exceptionType */ $exceptionType = $request->getParsedBodyParam('exception_type', ''); /** @var string|null $sendErrorReport */ @@ -101,7 +99,7 @@ class ErrorReportController extends AbstractController /* Message to show to the user */ if ($success) { - if ($automatic === 'true' || $cfg['SendErrorReports'] === 'always') { + if ($automatic === 'true' || $GLOBALS['cfg']['SendErrorReports'] === 'always') { $msg = __( 'An error has been detected and an error report has been ' . 'automatically submitted based on your settings.' @@ -152,7 +150,7 @@ class ErrorReportController extends AbstractController } } } elseif ($getSettings) { - $this->response->addJSON('report_setting', $cfg['SendErrorReports']); + $this->response->addJSON('report_setting', $GLOBALS['cfg']['SendErrorReports']); } elseif ($exceptionType === 'js') { $this->response->addJSON('report_modal', $this->errorReport->getEmptyModal()); $this->response->addHTML($this->errorReport->getForm()); diff --git a/libraries/classes/Controllers/Export/ExportController.php b/libraries/classes/Controllers/Export/ExportController.php index 24f7a7f31e..8b99b1fa61 100644 --- a/libraries/classes/Controllers/Export/ExportController.php +++ b/libraries/classes/Controllers/Export/ExportController.php @@ -13,7 +13,6 @@ use PhpMyAdmin\Export; use PhpMyAdmin\Http\ServerRequest; use PhpMyAdmin\Message; use PhpMyAdmin\Plugins; -use PhpMyAdmin\Plugins\ExportPlugin; use PhpMyAdmin\ResponseRenderer; use PhpMyAdmin\Sanitize; use PhpMyAdmin\SqlParser\Parser; @@ -51,15 +50,6 @@ final class ExportController extends AbstractController public function __invoke(ServerRequest $request): void { - global $containerBuilder, $db, $export_type, $filename_template, $sql_query, $errorUrl, $message; - global $compression, $crlf, $asfile, $buffer_needed, $save_on_server, $file_handle, $separate_files; - global $output_charset_conversion, $output_kanji_conversion, $table, $what, $export_plugin, $single_table; - global $compression_methods, $onserver, $back_button, $refreshButton, $save_filename, $filename; - global $quick_export, $cfg, $tables, $table_select, $aliases; - global $time_start, $charset, $remember_template, $mime_type, $num_tables; - global $active_page, $do_relation, $do_comments, $do_mime, $do_dates, $whatStrucOrData, $db_select; - global $table_structure, $table_data, $lock_tables, $allrows, $limit_to, $limit_from; - /** @var array $postParams */ $postParams = $request->getParsedBody(); @@ -225,76 +215,75 @@ final class ExportController extends AbstractController Util::checkParameters(['what', 'export_type']); // sanitize this parameter which will be used below in a file inclusion - $what = Core::securePath($whatParam); + $GLOBALS['what'] = Core::securePath($whatParam); // export class instance, not array of properties, as before - /** @var ExportPlugin $export_plugin */ - $export_plugin = Plugins::getPlugin('export', $what, [ - 'export_type' => (string) $export_type, - 'single_table' => isset($single_table), + $GLOBALS['export_plugin'] = Plugins::getPlugin('export', $GLOBALS['what'], [ + 'export_type' => (string) $GLOBALS['export_type'], + 'single_table' => isset($GLOBALS['single_table']), ]); // Check export type - if (empty($export_plugin)) { + if (empty($GLOBALS['export_plugin'])) { Core::fatalError(__('Bad type!')); } /** * valid compression methods */ - $compression_methods = []; + $GLOBALS['compression_methods'] = []; if ($GLOBALS['cfg']['ZipDump'] && function_exists('gzcompress')) { - $compression_methods[] = 'zip'; + $GLOBALS['compression_methods'][] = 'zip'; } if ($GLOBALS['cfg']['GZipDump'] && function_exists('gzencode')) { - $compression_methods[] = 'gzip'; + $GLOBALS['compression_methods'][] = 'gzip'; } /** * init and variable checking */ - $compression = ''; - $onserver = false; - $save_on_server = false; - $buffer_needed = false; - $back_button = ''; - $refreshButton = ''; - $save_filename = ''; - $file_handle = ''; - $errorUrl = ''; - $filename = ''; - $separate_files = ''; + $GLOBALS['compression'] = ''; + $GLOBALS['onserver'] = false; + $GLOBALS['save_on_server'] = false; + $GLOBALS['buffer_needed'] = false; + $GLOBALS['back_button'] = ''; + $GLOBALS['refreshButton'] = ''; + $GLOBALS['save_filename'] = ''; + $GLOBALS['file_handle'] = ''; + $GLOBALS['errorUrl'] = ''; + $GLOBALS['filename'] = ''; + $GLOBALS['separate_files'] = ''; // Is it a quick or custom export? if ($quickOrCustom === 'quick') { - $quick_export = true; + $GLOBALS['quick_export'] = true; } else { - $quick_export = false; + $GLOBALS['quick_export'] = false; } if ($outputFormat === 'astext') { - $asfile = false; + $GLOBALS['asfile'] = false; } else { - $asfile = true; + $GLOBALS['asfile'] = true; if ($asSeparateFiles && $compressionParam === 'zip') { - $separate_files = $asSeparateFiles; + $GLOBALS['separate_files'] = $asSeparateFiles; } - if (in_array($compressionParam, $compression_methods)) { - $compression = $compressionParam; - $buffer_needed = true; + if (in_array($compressionParam, $GLOBALS['compression_methods'])) { + $GLOBALS['compression'] = $compressionParam; + $GLOBALS['buffer_needed'] = true; } - if (($quick_export && $quickExportOnServer) || (! $quick_export && $onServerParam)) { - if ($quick_export) { - $onserver = $quickExportOnServer; + if (($GLOBALS['quick_export'] && $quickExportOnServer) || (! $GLOBALS['quick_export'] && $onServerParam)) { + if ($GLOBALS['quick_export']) { + $GLOBALS['onserver'] = $quickExportOnServer; } else { - $onserver = $onServerParam; + $GLOBALS['onserver'] = $onServerParam; } // Will we save dump on server? - $save_on_server = ! empty($cfg['SaveDir']); + $GLOBALS['save_on_server'] = ! empty($GLOBALS['cfg']['SaveDir']); } } @@ -302,7 +291,7 @@ final class ExportController extends AbstractController * If we are sending the export file (as opposed to just displaying it * as text), we have to bypass the usual PhpMyAdmin\Response mechanism */ - if ($outputFormat === 'sendit' && ! $save_on_server) { + if ($outputFormat === 'sendit' && ! $GLOBALS['save_on_server']) { $this->response->disable(); //Disable all active buffers (see: ob_get_status(true) at this point) do { @@ -314,21 +303,21 @@ final class ExportController extends AbstractController } while ($hasBuffer); } - $tables = []; + $GLOBALS['tables'] = []; // Generate error url and check for needed variables - if ($export_type === 'server') { - $errorUrl = Url::getFromRoute('/server/export'); - } elseif ($export_type === 'database' && strlen($db) > 0) { - $errorUrl = Url::getFromRoute('/database/export', ['db' => $db]); + if ($GLOBALS['export_type'] === 'server') { + $GLOBALS['errorUrl'] = Url::getFromRoute('/server/export'); + } elseif ($GLOBALS['export_type'] === 'database' && strlen($GLOBALS['db']) > 0) { + $GLOBALS['errorUrl'] = Url::getFromRoute('/database/export', ['db' => $GLOBALS['db']]); // Check if we have something to export - $tables = $table_select ?? []; - } elseif ($export_type === 'table' && strlen($db) > 0 && strlen($table) > 0) { - $errorUrl = Url::getFromRoute('/table/export', [ - 'db' => $db, - 'table' => $table, + $GLOBALS['tables'] = $GLOBALS['table_select'] ?? []; + } elseif ($GLOBALS['export_type'] === 'table' && strlen($GLOBALS['db']) > 0 && strlen($GLOBALS['table']) > 0) { + $GLOBALS['errorUrl'] = Url::getFromRoute('/table/export', [ + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], ]); - } elseif ($export_type === 'raw') { - $errorUrl = Url::getFromRoute('/server/export', ['sql_query' => $sql_query]); + } elseif ($GLOBALS['export_type'] === 'raw') { + $GLOBALS['errorUrl'] = Url::getFromRoute('/server/export', ['sql_query' => $GLOBALS['sql_query']]); } else { Core::fatalError(__('Bad parameters!')); } @@ -336,14 +325,14 @@ final class ExportController extends AbstractController // Merge SQL Query aliases with Export aliases from // export page, Export page aliases are given more // preference over SQL Query aliases. - $parser = new Parser($sql_query); - $aliases = []; + $parser = new Parser($GLOBALS['sql_query']); + $GLOBALS['aliases'] = []; if (! empty($parser->statements[0]) && ($parser->statements[0] instanceof SelectStatement)) { - $aliases = Misc::getAliases($parser->statements[0], $db); + $GLOBALS['aliases'] = Misc::getAliases($parser->statements[0], $GLOBALS['db']); } if (! empty($aliasesParam)) { - $aliases = $this->export->mergeAliases($aliases, $aliasesParam); + $GLOBALS['aliases'] = $this->export->mergeAliases($GLOBALS['aliases'], $aliasesParam); $_SESSION['tmpval']['aliases'] = $aliasesParam; } @@ -351,8 +340,8 @@ final class ExportController extends AbstractController * Increase time limit for script execution and initializes some variables */ Util::setTimeLimit(); - if (! empty($cfg['MemoryLimit'])) { - ini_set('memory_limit', $cfg['MemoryLimit']); + if (! empty($GLOBALS['cfg']['MemoryLimit'])) { + ini_set('memory_limit', $GLOBALS['cfg']['MemoryLimit']); } register_shutdown_function([$this->export, 'shutdown']); @@ -364,59 +353,67 @@ final class ExportController extends AbstractController $this->export->dumpBufferObjects = []; // We send fake headers to avoid browser timeout when buffering - $time_start = time(); + $GLOBALS['time_start'] = time(); // Defines the default format. // For SQL always use \n as MySQL wants this on all platforms. - if ($what === 'sql') { - $crlf = "\n"; + if ($GLOBALS['what'] === 'sql') { + $GLOBALS['crlf'] = "\n"; } else { - $crlf = PHP_EOL; + $GLOBALS['crlf'] = PHP_EOL; } - $output_kanji_conversion = Encoding::canConvertKanji(); + $GLOBALS['output_kanji_conversion'] = Encoding::canConvertKanji(); // Do we need to convert charset? - $output_charset_conversion = $asfile + $GLOBALS['output_charset_conversion'] = $GLOBALS['asfile'] && Encoding::isSupported() - && isset($charset) && $charset !== 'utf-8'; + && isset($GLOBALS['charset']) && $GLOBALS['charset'] !== 'utf-8'; // Use on the fly compression? $GLOBALS['onfly_compression'] = $GLOBALS['cfg']['CompressOnFly'] - && $compression === 'gzip'; + && $GLOBALS['compression'] === 'gzip'; if ($GLOBALS['onfly_compression']) { $GLOBALS['memory_limit'] = $this->export->getMemoryLimit(); } // Generate filename and mime type if needed - if ($asfile) { - if (empty($remember_template)) { - $remember_template = ''; + if ($GLOBALS['asfile']) { + if (empty($GLOBALS['remember_template'])) { + $GLOBALS['remember_template'] = ''; } - [$filename, $mime_type] = $this->export->getFilenameAndMimetype( - $export_type, - $remember_template, - $export_plugin, - $compression, - $filename_template + [$GLOBALS['filename'], $GLOBALS['mime_type']] = $this->export->getFilenameAndMimetype( + $GLOBALS['export_type'], + $GLOBALS['remember_template'], + $GLOBALS['export_plugin'], + $GLOBALS['compression'], + $GLOBALS['filename_template'] ); } else { - $mime_type = ''; + $GLOBALS['mime_type'] = ''; } // For raw query export, filename will be export.extension - if ($export_type === 'raw') { - [$filename] = $this->export->getFinalFilenameAndMimetypeForFilename($export_plugin, $compression, 'export'); + if ($GLOBALS['export_type'] === 'raw') { + [$GLOBALS['filename']] = $this->export->getFinalFilenameAndMimetypeForFilename( + $GLOBALS['export_plugin'], + $GLOBALS['compression'], + 'export' + ); } // Open file on server if needed - if ($save_on_server) { - [$save_filename, $message, $file_handle] = $this->export->openFile($filename, $quick_export); + if ($GLOBALS['save_on_server']) { + [ + $GLOBALS['save_filename'], + $GLOBALS['message'], + $GLOBALS['file_handle'], + ] = $this->export->openFile($GLOBALS['filename'], $GLOBALS['quick_export']); // problem opening export file on server? - if (! empty($message)) { - $this->export->showPage($export_type); + if (! empty($GLOBALS['message'])) { + $this->export->showPage($GLOBALS['export_type']); return; } @@ -425,34 +422,38 @@ final class ExportController extends AbstractController * Send headers depending on whether the user chose to download a dump file * or not */ - if ($asfile) { + if ($GLOBALS['asfile']) { // Download // (avoid rewriting data containing HTML with anchors and forms; // this was reported to happen under Plesk) ini_set('url_rewriter.tags', ''); - $filename = Sanitize::sanitizeFilename($filename); + $GLOBALS['filename'] = Sanitize::sanitizeFilename($GLOBALS['filename']); - Core::downloadHeader($filename, $mime_type); + Core::downloadHeader($GLOBALS['filename'], $GLOBALS['mime_type']); } else { // HTML - if ($export_type === 'database') { - $num_tables = count($tables); - if ($num_tables === 0) { - $message = Message::error( + if ($GLOBALS['export_type'] === 'database') { + $GLOBALS['num_tables'] = count($GLOBALS['tables']); + if ($GLOBALS['num_tables'] === 0) { + $GLOBALS['message'] = Message::error( __('No tables found in database.') ); - $active_page = Url::getFromRoute('/database/export'); + $GLOBALS['active_page'] = Url::getFromRoute('/database/export'); /** @var DatabaseExportController $controller */ - $controller = $containerBuilder->get(DatabaseExportController::class); + $controller = $GLOBALS['containerBuilder']->get(DatabaseExportController::class); $controller(); exit; } } - [$html, $back_button, $refreshButton] = $this->export->getHtmlForDisplayedExportHeader( - $export_type, - $db, - $table + [ + $html, + $GLOBALS['back_button'], + $GLOBALS['refreshButton'], + ] = $this->export->getHtmlForDisplayedExportHeader( + $GLOBALS['export_type'], + $GLOBALS['db'], + $GLOBALS['table'] ); echo $html; unset($html); @@ -465,175 +466,182 @@ final class ExportController extends AbstractController $this->export->dumpBufferLength = 0; // Add possibly some comments to export - if (! $export_plugin->exportHeader()) { + if (! $GLOBALS['export_plugin']->exportHeader()) { throw new ExportException('Failure during header export.'); } // Will we need relation & co. setup? - $do_relation = isset($GLOBALS[$what . '_relation']); - $do_comments = isset($GLOBALS[$what . '_include_comments']) - || isset($GLOBALS[$what . '_comments']); - $do_mime = isset($GLOBALS[$what . '_mime']); + $GLOBALS['do_relation'] = isset($GLOBALS[$GLOBALS['what'] . '_relation']); + $GLOBALS['do_comments'] = isset($GLOBALS[$GLOBALS['what'] . '_include_comments']) + || isset($GLOBALS[$GLOBALS['what'] . '_comments']); + $GLOBALS['do_mime'] = isset($GLOBALS[$GLOBALS['what'] . '_mime']); // Include dates in export? - $do_dates = isset($GLOBALS[$what . '_dates']); + $GLOBALS['do_dates'] = isset($GLOBALS[$GLOBALS['what'] . '_dates']); - $whatStrucOrData = $GLOBALS[$what . '_structure_or_data']; + $GLOBALS['whatStrucOrData'] = $GLOBALS[$GLOBALS['what'] . '_structure_or_data']; - if ($export_type === 'raw') { - $whatStrucOrData = 'raw'; + if ($GLOBALS['export_type'] === 'raw') { + $GLOBALS['whatStrucOrData'] = 'raw'; } /** * Builds the dump */ - if ($export_type === 'server') { - if (! isset($db_select)) { - $db_select = ''; + if ($GLOBALS['export_type'] === 'server') { + if (! isset($GLOBALS['db_select'])) { + $GLOBALS['db_select'] = ''; } $this->export->exportServer( - $db_select, - $whatStrucOrData, - $export_plugin, - $crlf, - $errorUrl, - $export_type, - $do_relation, - $do_comments, - $do_mime, - $do_dates, - $aliases, - $separate_files + $GLOBALS['db_select'], + $GLOBALS['whatStrucOrData'], + $GLOBALS['export_plugin'], + $GLOBALS['crlf'], + $GLOBALS['errorUrl'], + $GLOBALS['export_type'], + $GLOBALS['do_relation'], + $GLOBALS['do_comments'], + $GLOBALS['do_mime'], + $GLOBALS['do_dates'], + $GLOBALS['aliases'], + $GLOBALS['separate_files'] ); - } elseif ($export_type === 'database') { - if (! isset($table_structure) || ! is_array($table_structure)) { - $table_structure = []; + } elseif ($GLOBALS['export_type'] === 'database') { + if (! isset($GLOBALS['table_structure']) || ! is_array($GLOBALS['table_structure'])) { + $GLOBALS['table_structure'] = []; } - if (! isset($table_data) || ! is_array($table_data)) { - $table_data = []; + if (! isset($GLOBALS['table_data']) || ! is_array($GLOBALS['table_data'])) { + $GLOBALS['table_data'] = []; } if ($structureOrDataForced) { - $table_structure = $tables; - $table_data = $tables; + $GLOBALS['table_structure'] = $GLOBALS['tables']; + $GLOBALS['table_data'] = $GLOBALS['tables']; } - if (isset($lock_tables)) { - $this->export->lockTables($db, $tables, 'READ'); + if (isset($GLOBALS['lock_tables'])) { + $this->export->lockTables($GLOBALS['db'], $GLOBALS['tables'], 'READ'); try { $this->export->exportDatabase( - $db, - $tables, - $whatStrucOrData, - $table_structure, - $table_data, - $export_plugin, - $crlf, - $errorUrl, - $export_type, - $do_relation, - $do_comments, - $do_mime, - $do_dates, - $aliases, - $separate_files + $GLOBALS['db'], + $GLOBALS['tables'], + $GLOBALS['whatStrucOrData'], + $GLOBALS['table_structure'], + $GLOBALS['table_data'], + $GLOBALS['export_plugin'], + $GLOBALS['crlf'], + $GLOBALS['errorUrl'], + $GLOBALS['export_type'], + $GLOBALS['do_relation'], + $GLOBALS['do_comments'], + $GLOBALS['do_mime'], + $GLOBALS['do_dates'], + $GLOBALS['aliases'], + $GLOBALS['separate_files'] ); } finally { $this->export->unlockTables(); } } else { $this->export->exportDatabase( - $db, - $tables, - $whatStrucOrData, - $table_structure, - $table_data, - $export_plugin, - $crlf, - $errorUrl, - $export_type, - $do_relation, - $do_comments, - $do_mime, - $do_dates, - $aliases, - $separate_files + $GLOBALS['db'], + $GLOBALS['tables'], + $GLOBALS['whatStrucOrData'], + $GLOBALS['table_structure'], + $GLOBALS['table_data'], + $GLOBALS['export_plugin'], + $GLOBALS['crlf'], + $GLOBALS['errorUrl'], + $GLOBALS['export_type'], + $GLOBALS['do_relation'], + $GLOBALS['do_comments'], + $GLOBALS['do_mime'], + $GLOBALS['do_dates'], + $GLOBALS['aliases'], + $GLOBALS['separate_files'] ); } - } elseif ($export_type === 'raw') { - Export::exportRaw($whatStrucOrData, $export_plugin, $crlf, $errorUrl, $sql_query, $export_type); + } elseif ($GLOBALS['export_type'] === 'raw') { + Export::exportRaw( + $GLOBALS['whatStrucOrData'], + $GLOBALS['export_plugin'], + $GLOBALS['crlf'], + $GLOBALS['errorUrl'], + $GLOBALS['sql_query'], + $GLOBALS['export_type'] + ); } else { // We export just one table // $allrows comes from the form when "Dump all rows" has been selected - if (! isset($allrows)) { - $allrows = ''; + if (! isset($GLOBALS['allrows'])) { + $GLOBALS['allrows'] = ''; } - if (! isset($limit_to)) { - $limit_to = '0'; + if (! isset($GLOBALS['limit_to'])) { + $GLOBALS['limit_to'] = '0'; } - if (! isset($limit_from)) { - $limit_from = '0'; + if (! isset($GLOBALS['limit_from'])) { + $GLOBALS['limit_from'] = '0'; } - if (isset($lock_tables)) { + if (isset($GLOBALS['lock_tables'])) { try { - $this->export->lockTables($db, [$table], 'READ'); + $this->export->lockTables($GLOBALS['db'], [$GLOBALS['table']], 'READ'); $this->export->exportTable( - $db, - $table, - $whatStrucOrData, - $export_plugin, - $crlf, - $errorUrl, - $export_type, - $do_relation, - $do_comments, - $do_mime, - $do_dates, - $allrows, - $limit_to, - $limit_from, - $sql_query, - $aliases + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['whatStrucOrData'], + $GLOBALS['export_plugin'], + $GLOBALS['crlf'], + $GLOBALS['errorUrl'], + $GLOBALS['export_type'], + $GLOBALS['do_relation'], + $GLOBALS['do_comments'], + $GLOBALS['do_mime'], + $GLOBALS['do_dates'], + $GLOBALS['allrows'], + $GLOBALS['limit_to'], + $GLOBALS['limit_from'], + $GLOBALS['sql_query'], + $GLOBALS['aliases'] ); } finally { $this->export->unlockTables(); } } else { $this->export->exportTable( - $db, - $table, - $whatStrucOrData, - $export_plugin, - $crlf, - $errorUrl, - $export_type, - $do_relation, - $do_comments, - $do_mime, - $do_dates, - $allrows, - $limit_to, - $limit_from, - $sql_query, - $aliases + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['whatStrucOrData'], + $GLOBALS['export_plugin'], + $GLOBALS['crlf'], + $GLOBALS['errorUrl'], + $GLOBALS['export_type'], + $GLOBALS['do_relation'], + $GLOBALS['do_comments'], + $GLOBALS['do_mime'], + $GLOBALS['do_dates'], + $GLOBALS['allrows'], + $GLOBALS['limit_to'], + $GLOBALS['limit_from'], + $GLOBALS['sql_query'], + $GLOBALS['aliases'] ); } } - if (! $export_plugin->exportFooter()) { + if (! $GLOBALS['export_plugin']->exportFooter()) { throw new ExportException('Failure during footer export.'); } } catch (ExportException $e) { // Ignore } - if ($save_on_server && ! empty($message)) { - $this->export->showPage($export_type); + if ($GLOBALS['save_on_server'] && ! empty($GLOBALS['message'])) { + $this->export->showPage($GLOBALS['export_type']); return; } @@ -641,14 +649,14 @@ final class ExportController extends AbstractController /** * Send the dump as a file... */ - if (empty($asfile)) { - echo $this->export->getHtmlForDisplayedExportFooter($back_button, $refreshButton); + if (empty($GLOBALS['asfile'])) { + echo $this->export->getHtmlForDisplayedExportFooter($GLOBALS['back_button'], $GLOBALS['refreshButton']); return; } // Convert the charset if required. - if ($output_charset_conversion) { + if ($GLOBALS['output_charset_conversion']) { $this->export->dumpBuffer = Encoding::convertString( 'utf-8', $GLOBALS['charset'], @@ -657,22 +665,30 @@ final class ExportController extends AbstractController } // Compression needed? - if ($compression) { - if (! empty($separate_files)) { + if ($GLOBALS['compression']) { + if (! empty($GLOBALS['separate_files'])) { $this->export->dumpBuffer = $this->export->compress( $this->export->dumpBufferObjects, - $compression, - $filename + $GLOBALS['compression'], + $GLOBALS['filename'] ); } else { - $this->export->dumpBuffer = $this->export->compress($this->export->dumpBuffer, $compression, $filename); + $this->export->dumpBuffer = $this->export->compress( + $this->export->dumpBuffer, + $GLOBALS['compression'], + $GLOBALS['filename'] + ); } } /* If we saved on server, we have to close file now */ - if ($save_on_server) { - $message = $this->export->closeFile($file_handle, $this->export->dumpBuffer, $save_filename); - $this->export->showPage($export_type); + if ($GLOBALS['save_on_server']) { + $GLOBALS['message'] = $this->export->closeFile( + $GLOBALS['file_handle'], + $this->export->dumpBuffer, + $GLOBALS['save_filename'] + ); + $this->export->showPage($GLOBALS['export_type']); return; } diff --git a/libraries/classes/Controllers/Export/Template/CreateController.php b/libraries/classes/Controllers/Export/Template/CreateController.php index 91abb1beca..932aa351c5 100644 --- a/libraries/classes/Controllers/Export/Template/CreateController.php +++ b/libraries/classes/Controllers/Export/Template/CreateController.php @@ -35,8 +35,6 @@ final class CreateController extends AbstractController public function __invoke(ServerRequest $request): void { - global $cfg; - /** @var string $exportType */ $exportType = $request->getParsedBodyParam('exportType', ''); /** @var string $templateName */ @@ -52,7 +50,7 @@ final class CreateController extends AbstractController } $template = ExportTemplate::fromArray([ - 'username' => $cfg['Server']['user'], + 'username' => $GLOBALS['cfg']['Server']['user'], 'exportType' => $exportType, 'name' => $templateName, 'data' => $templateData, diff --git a/libraries/classes/Controllers/Export/Template/DeleteController.php b/libraries/classes/Controllers/Export/Template/DeleteController.php index f83c7960b3..29a7628e86 100644 --- a/libraries/classes/Controllers/Export/Template/DeleteController.php +++ b/libraries/classes/Controllers/Export/Template/DeleteController.php @@ -32,8 +32,6 @@ final class DeleteController extends AbstractController public function __invoke(ServerRequest $request): void { - global $cfg; - $templateId = (int) $request->getParsedBodyParam('templateId'); $exportTemplatesFeature = $this->relation->getRelationParameters()->exportTemplatesFeature; @@ -44,7 +42,7 @@ final class DeleteController extends AbstractController $result = $this->model->delete( $exportTemplatesFeature->database, $exportTemplatesFeature->exportTemplates, - $cfg['Server']['user'], + $GLOBALS['cfg']['Server']['user'], $templateId ); diff --git a/libraries/classes/Controllers/Export/Template/LoadController.php b/libraries/classes/Controllers/Export/Template/LoadController.php index 56a8e649ac..03bd33503c 100644 --- a/libraries/classes/Controllers/Export/Template/LoadController.php +++ b/libraries/classes/Controllers/Export/Template/LoadController.php @@ -33,8 +33,6 @@ final class LoadController extends AbstractController public function __invoke(ServerRequest $request): void { - global $cfg; - $templateId = (int) $request->getParsedBodyParam('templateId'); $exportTemplatesFeature = $this->relation->getRelationParameters()->exportTemplatesFeature; @@ -45,7 +43,7 @@ final class LoadController extends AbstractController $template = $this->model->load( $exportTemplatesFeature->database, $exportTemplatesFeature->exportTemplates, - $cfg['Server']['user'], + $GLOBALS['cfg']['Server']['user'], $templateId ); diff --git a/libraries/classes/Controllers/Export/Template/UpdateController.php b/libraries/classes/Controllers/Export/Template/UpdateController.php index 09d7981ad7..eb407c47af 100644 --- a/libraries/classes/Controllers/Export/Template/UpdateController.php +++ b/libraries/classes/Controllers/Export/Template/UpdateController.php @@ -33,8 +33,6 @@ final class UpdateController extends AbstractController public function __invoke(ServerRequest $request): void { - global $cfg; - $templateId = (int) $request->getParsedBodyParam('templateId'); /** @var string $templateData */ $templateData = $request->getParsedBodyParam('templateData', ''); @@ -46,7 +44,7 @@ final class UpdateController extends AbstractController $template = ExportTemplate::fromArray([ 'id' => $templateId, - 'username' => $cfg['Server']['user'], + 'username' => $GLOBALS['cfg']['Server']['user'], 'data' => $templateData, ]); $result = $this->model->update( diff --git a/libraries/classes/Controllers/GisDataEditorController.php b/libraries/classes/Controllers/GisDataEditorController.php index 565e012ece..07b224ba07 100644 --- a/libraries/classes/Controllers/GisDataEditorController.php +++ b/libraries/classes/Controllers/GisDataEditorController.php @@ -28,9 +28,6 @@ class GisDataEditorController extends AbstractController { public function __invoke(ServerRequest $request): void { - global $gis_data, $gis_types, $start, $geom_type, $gis_obj, $srid, $wkt, $wkt_with_zero; - global $result, $visualizationSettings, $data, $visualization, $open_layers, $geom_count, $dbi; - /** @var string|null $field */ $field = $request->getParsedBodyParam('field'); /** @var array|null $gisDataParam */ @@ -49,12 +46,12 @@ class GisDataEditorController extends AbstractController } // Get data if any posted - $gis_data = []; + $GLOBALS['gis_data'] = []; if (is_array($gisDataParam)) { - $gis_data = $gisDataParam; + $GLOBALS['gis_data'] = $gisDataParam; } - $gis_types = [ + $GLOBALS['gis_types'] = [ 'POINT', 'MULTIPOINT', 'LINESTRING', @@ -66,95 +63,103 @@ class GisDataEditorController extends AbstractController // Extract type from the initial call and make sure that it's a valid one. // Extract from field's values if available, if not use the column type passed. - if (! isset($gis_data['gis_type'])) { + if (! isset($GLOBALS['gis_data']['gis_type'])) { if ($type !== '') { - $gis_data['gis_type'] = mb_strtoupper($type); + $GLOBALS['gis_data']['gis_type'] = mb_strtoupper($type); } if (isset($value) && trim($value) !== '') { - $start = substr($value, 0, 1) == "'" ? 1 : 0; - $gis_data['gis_type'] = mb_substr($value, $start, (int) mb_strpos($value, '(') - $start); + $GLOBALS['start'] = substr($value, 0, 1) == "'" ? 1 : 0; + $GLOBALS['gis_data']['gis_type'] = mb_substr( + $value, + $GLOBALS['start'], + (int) mb_strpos($value, '(') - $GLOBALS['start'] + ); } - if (! isset($gis_data['gis_type']) || (! in_array($gis_data['gis_type'], $gis_types))) { - $gis_data['gis_type'] = $gis_types[0]; + if ( + ! isset($GLOBALS['gis_data']['gis_type']) + || (! in_array($GLOBALS['gis_data']['gis_type'], $GLOBALS['gis_types'])) + ) { + $GLOBALS['gis_data']['gis_type'] = $GLOBALS['gis_types'][0]; } } - $geom_type = $gis_data['gis_type']; + $GLOBALS['geom_type'] = $GLOBALS['gis_data']['gis_type']; // Generate parameters from value passed. - $gis_obj = GisFactory::factory($geom_type); - if ($gis_obj === false) { + $GLOBALS['gis_obj'] = GisFactory::factory($GLOBALS['geom_type']); + if ($GLOBALS['gis_obj'] === false) { return; } if (isset($value)) { - $gis_data = array_merge( - $gis_data, - $gis_obj->generateParams($value) + $GLOBALS['gis_data'] = array_merge( + $GLOBALS['gis_data'], + $GLOBALS['gis_obj']->generateParams($value) ); } // Generate Well Known Text - $srid = isset($gis_data['srid']) && $gis_data['srid'] != '' ? (int) $gis_data['srid'] : 0; - $wkt = $gis_obj->generateWkt($gis_data, 0); - $wkt_with_zero = $gis_obj->generateWkt($gis_data, 0, '0'); - $result = "'" . $wkt . "'," . $srid; + $GLOBALS['srid'] = isset($GLOBALS['gis_data']['srid']) && $GLOBALS['gis_data']['srid'] != '' + ? (int) $GLOBALS['gis_data']['srid'] : 0; + $GLOBALS['wkt'] = $GLOBALS['gis_obj']->generateWkt($GLOBALS['gis_data'], 0); + $GLOBALS['wkt_with_zero'] = $GLOBALS['gis_obj']->generateWkt($GLOBALS['gis_data'], 0, '0'); + $GLOBALS['result'] = "'" . $GLOBALS['wkt'] . "'," . $GLOBALS['srid']; // Generate SVG based visualization - $visualizationSettings = [ + $GLOBALS['visualizationSettings'] = [ 'width' => 450, 'height' => 300, 'spatialColumn' => 'wkt', - 'mysqlVersion' => $dbi->getVersion(), - 'isMariaDB' => $dbi->isMariaDB(), + 'mysqlVersion' => $GLOBALS['dbi']->getVersion(), + 'isMariaDB' => $GLOBALS['dbi']->isMariaDB(), ]; - $data = [ + $GLOBALS['data'] = [ [ - 'wkt' => $wkt_with_zero, - 'srid' => $srid, + 'wkt' => $GLOBALS['wkt_with_zero'], + 'srid' => $GLOBALS['srid'], ], ]; - $visualization = GisVisualization::getByData($data, $visualizationSettings) + $GLOBALS['visualization'] = GisVisualization::getByData($GLOBALS['data'], $GLOBALS['visualizationSettings']) ->toImage('svg'); - $open_layers = GisVisualization::getByData($data, $visualizationSettings) + $GLOBALS['open_layers'] = GisVisualization::getByData($GLOBALS['data'], $GLOBALS['visualizationSettings']) ->asOl(); // If the call is to update the WKT and visualization make an AJAX response if ($generate) { $this->response->addJSON([ - 'result' => $result, - 'visualization' => $visualization, - 'openLayers' => $open_layers, + 'result' => $GLOBALS['result'], + 'visualization' => $GLOBALS['visualization'], + 'openLayers' => $GLOBALS['open_layers'], ]); return; } - $geom_count = 1; - if ($geom_type === 'GEOMETRYCOLLECTION') { - $geom_count = isset($gis_data[$geom_type]['geom_count']) - ? intval($gis_data[$geom_type]['geom_count']) : 1; - if (isset($gis_data[$geom_type]['add_geom'])) { - $geom_count++; + $GLOBALS['geom_count'] = 1; + if ($GLOBALS['geom_type'] === 'GEOMETRYCOLLECTION') { + $GLOBALS['geom_count'] = isset($GLOBALS['gis_data'][$GLOBALS['geom_type']]['geom_count']) + ? intval($GLOBALS['gis_data'][$GLOBALS['geom_type']]['geom_count']) : 1; + if (isset($GLOBALS['gis_data'][$GLOBALS['geom_type']]['add_geom'])) { + $GLOBALS['geom_count']++; } } $templateOutput = $this->template->render('gis_data_editor_form', [ - 'width' => $visualizationSettings['width'], - 'height' => $visualizationSettings['height'], + 'width' => $GLOBALS['visualizationSettings']['width'], + 'height' => $GLOBALS['visualizationSettings']['height'], 'field' => $field, 'input_name' => $inputName, - 'srid' => $srid, - 'visualization' => $visualization, - 'open_layers' => $open_layers, - 'gis_types' => $gis_types, - 'geom_type' => $geom_type, - 'geom_count' => $geom_count, - 'gis_data' => $gis_data, - 'result' => $result, + 'srid' => $GLOBALS['srid'], + 'visualization' => $GLOBALS['visualization'], + 'open_layers' => $GLOBALS['open_layers'], + 'gis_types' => $GLOBALS['gis_types'], + 'geom_type' => $GLOBALS['geom_type'], + 'geom_count' => $GLOBALS['geom_count'], + 'gis_data' => $GLOBALS['gis_data'], + 'result' => $GLOBALS['result'], ]); $this->response->addJSON(['gis_editor' => $templateOutput]); diff --git a/libraries/classes/Controllers/HomeController.php b/libraries/classes/Controllers/HomeController.php index 2b998682f0..8d7996ba3b 100644 --- a/libraries/classes/Controllers/HomeController.php +++ b/libraries/classes/Controllers/HomeController.php @@ -63,8 +63,6 @@ class HomeController extends AbstractController public function __invoke(): void { - global $cfg, $server, $collation_connection, $message, $show_query, $db, $table, $errorUrl; - if ($this->response->isAjax() && ! empty($_REQUEST['access_time'])) { return; } @@ -74,20 +72,20 @@ class HomeController extends AbstractController // 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('/'); + $GLOBALS['db'] = $_POST['db'] ?? ''; + $GLOBALS['table'] = ''; + $GLOBALS['show_query'] = '1'; + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); - if ($server > 0 && $this->dbi->isSuperUser()) { + if ($GLOBALS['server'] > 0 && $this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); } $languageManager = LanguageManager::getInstance(); - if (! empty($message)) { - $displayMessage = Generator::getMessage($message); - unset($message); + if (! empty($GLOBALS['message'])) { + $displayMessage = Generator::getMessage($GLOBALS['message']); + unset($GLOBALS['message']); } if (isset($_SESSION['partial_logout'])) { @@ -101,22 +99,22 @@ class HomeController extends AbstractController $syncFavoriteTables = RecentFavoriteTable::getInstance('favorite') ->getHtmlSyncFavoriteTables(); - $hasServer = $server > 0 || count($cfg['Servers']) > 1; + $hasServer = $GLOBALS['server'] > 0 || count($GLOBALS['cfg']['Servers']) > 1; if ($hasServer) { - $hasServerSelection = $cfg['ServerDefault'] == 0 - || (! $cfg['NavigationDisplayServers'] - && (count($cfg['Servers']) > 1 - || ($server == 0 && count($cfg['Servers']) === 1))); + $hasServerSelection = $GLOBALS['cfg']['ServerDefault'] == 0 + || (! $GLOBALS['cfg']['NavigationDisplayServers'] + && (count($GLOBALS['cfg']['Servers']) > 1 + || ($GLOBALS['server'] == 0 && count($GLOBALS['cfg']['Servers']) === 1))); if ($hasServerSelection) { $serverSelection = Select::render(true, true); } - if ($server > 0) { + if ($GLOBALS['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']); + $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); + $collations = Charsets::getCollations($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); $charsetsList = []; foreach ($charsets as $charset) { $collationsList = []; @@ -124,7 +122,7 @@ class HomeController extends AbstractController $collationsList[] = [ 'name' => $collation->getName(), 'description' => $collation->getDescription(), - 'is_selected' => $collation_connection === $collation->getName(), + 'is_selected' => $GLOBALS['collation_connection'] === $collation->getName(), ]; } @@ -138,29 +136,29 @@ class HomeController extends AbstractController } $availableLanguages = []; - if (empty($cfg['Lang']) && $languageManager->hasChoice()) { + if (empty($GLOBALS['cfg']['Lang']) && $languageManager->hasChoice()) { $availableLanguages = $languageManager->sortedLanguages(); } $databaseServer = []; - if ($server > 0) { + if ($GLOBALS['server'] > 0) { $hostInfo = ''; - if (! empty($cfg['Server']['verbose'])) { - $hostInfo .= $cfg['Server']['verbose']; - if ($cfg['ShowServerInfo']) { + if (! empty($GLOBALS['cfg']['Server']['verbose'])) { + $hostInfo .= $GLOBALS['cfg']['Server']['verbose']; + if ($GLOBALS['cfg']['ShowServerInfo']) { $hostInfo .= ' ('; } } - if ($cfg['ShowServerInfo'] || empty($cfg['Server']['verbose'])) { + if ($GLOBALS['cfg']['ShowServerInfo'] || empty($GLOBALS['cfg']['Server']['verbose'])) { $hostInfo .= $this->dbi->getHostInfo(); } - if (! empty($cfg['Server']['verbose']) && $cfg['ShowServerInfo']) { + if (! empty($GLOBALS['cfg']['Server']['verbose']) && $GLOBALS['cfg']['ShowServerInfo']) { $hostInfo .= ')'; } - $serverCharset = Charsets::getServerCharset($this->dbi, $cfg['Server']['DisableIS']); + $serverCharset = Charsets::getServerCharset($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); $databaseServer = [ 'host' => $hostInfo, 'type' => Util::getServerType(), @@ -173,10 +171,10 @@ class HomeController extends AbstractController } $webServer = []; - if ($cfg['ShowServerInfo']) { + if ($GLOBALS['cfg']['ShowServerInfo']) { $webServer['software'] = $_SERVER['SERVER_SOFTWARE'] ?? null; - if ($server > 0) { + if ($GLOBALS['server'] > 0) { $clientVersion = $this->dbi->getClientInfo(); if (preg_match('#\d+\.\d+\.\d+#', $clientVersion)) { $clientVersion = 'libmysql - ' . $clientVersion; @@ -189,15 +187,15 @@ class HomeController extends AbstractController } $relation = new Relation($this->dbi); - if ($server > 0) { + if ($GLOBALS['server'] > 0) { $relationParameters = $relation->getRelationParameters(); - if (! $relationParameters->hasAllFeatures() && $cfg['PmaNoRelation_DisableWarning'] == false) { + if (! $relationParameters->hasAllFeatures() && $GLOBALS['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) { + if ($GLOBALS['cfg']['ZeroConf'] == true) { $messageText .= '
' . __('Or alternately go to \'Operations\' tab of any database to set it up there.'); } @@ -209,7 +207,7 @@ class HomeController extends AbstractController ); $messageInstance->addParamHtml(''); /* Show error if user has configured something, notice elsewhere */ - if (! empty($cfg['Servers'][$server]['pmadb'])) { + if (! empty($GLOBALS['cfg']['Servers'][$GLOBALS['server']]['pmadb'])) { $messageInstance->isError(true); } @@ -222,44 +220,43 @@ class HomeController extends AbstractController $git = new Git($this->config->get('ShowGitRevision') ?? true); $this->render('home/index', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'message' => $displayMessage ?? '', 'partial_logout' => $partialLogout ?? '', 'is_git_revision' => $git->isGitRevision(), - 'server' => $server, + 'server' => $GLOBALS['server'], 'sync_favorite_tables' => $syncFavoriteTables, 'has_server' => $hasServer, - 'is_demo' => $cfg['DBG']['demo'], + 'is_demo' => $GLOBALS['cfg']['DBG']['demo'], 'has_server_selection' => $hasServerSelection ?? false, 'server_selection' => $serverSelection ?? '', - 'has_change_password_link' => $cfg['Server']['auth_type'] !== 'config' && $cfg['ShowChgPassword'], + 'has_change_password_link' => $GLOBALS['cfg']['Server']['auth_type'] !== 'config' + && $GLOBALS['cfg']['ShowChgPassword'], 'charsets' => $charsetsList ?? [], 'available_languages' => $availableLanguages, 'database_server' => $databaseServer, 'web_server' => $webServer, - 'show_php_info' => $cfg['ShowPhpInfo'], - 'is_version_checked' => $cfg['VersionCheck'], + 'show_php_info' => $GLOBALS['cfg']['ShowPhpInfo'], + 'is_version_checked' => $GLOBALS['cfg']['VersionCheck'], 'phpmyadmin_version' => Version::VERSION, 'phpmyadmin_major_version' => Version::SERIES, 'config_storage_message' => $configStorageMessage ?? '', - 'has_theme_manager' => $cfg['ThemeManager'], + 'has_theme_manager' => $GLOBALS['cfg']['ThemeManager'], 'themes' => $this->themeManager->getThemesArray(), ]); } private function checkRequirements(): void { - global $cfg, $server; - $this->checkPhpExtensionsRequirements(); - if ($cfg['LoginCookieValidityDisableWarning'] == false) { + if ($GLOBALS['cfg']['LoginCookieValidityDisableWarning'] == false) { /** * Check whether session.gc_maxlifetime limits session validity. */ $gc_time = (int) ini_get('session.gc_maxlifetime'); - if ($gc_time < $cfg['LoginCookieValidity']) { + if ($gc_time < $GLOBALS['cfg']['LoginCookieValidity']) { trigger_error( __( 'Your PHP parameter [a@https://www.php.net/manual/en/session.' . @@ -276,7 +273,10 @@ class HomeController extends AbstractController /** * Check whether LoginCookieValidity is limited by LoginCookieStore. */ - if ($cfg['LoginCookieStore'] != 0 && $cfg['LoginCookieStore'] < $cfg['LoginCookieValidity']) { + if ( + $GLOBALS['cfg']['LoginCookieStore'] != 0 + && $GLOBALS['cfg']['LoginCookieStore'] < $GLOBALS['cfg']['LoginCookieValidity'] + ) { trigger_error( __( 'Login cookie store is lower than cookie validity configured in ' . @@ -291,10 +291,10 @@ class HomeController extends AbstractController * 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' + isset($GLOBALS['cfg']['Server']['controluser'], $GLOBALS['cfg']['Server']['controlpass']) + && $GLOBALS['server'] != 0 + && $GLOBALS['cfg']['Server']['controluser'] === 'pma' + && $GLOBALS['cfg']['Server']['controlpass'] === 'pmapass' ) { trigger_error( __( @@ -311,14 +311,14 @@ class HomeController extends AbstractController * Check if user does not have defined blowfish secret and it is being used. */ if (! empty($_SESSION['encryption_key'])) { - if (empty($cfg['blowfish_secret'])) { + if (empty($GLOBALS['cfg']['blowfish_secret'])) { trigger_error( __( 'The configuration file now needs a secret passphrase (blowfish_secret).' ), E_USER_WARNING ); - } elseif (mb_strlen($cfg['blowfish_secret'], '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { + } elseif (mb_strlen($GLOBALS['cfg']['blowfish_secret'], '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { trigger_error( sprintf( __( @@ -353,7 +353,7 @@ class HomeController extends AbstractController * Warning about Suhosin only if its simulation mode is not enabled */ if ( - $cfg['SuhosinDisableWarning'] == false + $GLOBALS['cfg']['SuhosinDisableWarning'] == false && ini_get('suhosin.request.max_value_length') && ini_get('suhosin.simulation') == '0' ) { @@ -389,8 +389,6 @@ class HomeController extends AbstractController private function checkLanguageStats(): void { - global $cfg, $lang; - /** * Warning about incomplete translations. * @@ -408,8 +406,8 @@ class HomeController extends AbstractController * speaking users. */ if ( - ! isset($GLOBALS['language_stats'][$lang]) - || $GLOBALS['language_stats'][$lang] >= $cfg['TranslationWarningThreshold'] + ! isset($GLOBALS['language_stats'][$GLOBALS['lang']]) + || $GLOBALS['language_stats'][$GLOBALS['lang']] >= $GLOBALS['cfg']['TranslationWarningThreshold'] ) { return; } diff --git a/libraries/classes/Controllers/Import/ImportController.php b/libraries/classes/Controllers/Import/ImportController.php index 5a60baf6c4..1e2fe4753e 100644 --- a/libraries/classes/Controllers/Import/ImportController.php +++ b/libraries/classes/Controllers/Import/ImportController.php @@ -72,25 +72,16 @@ final class ImportController extends AbstractController public function __invoke(): void { - global $cfg, $collation_connection, $db, $import_type, $table, $goto, $display_query; - global $format, $local_import_file, $ajax_reload, $import_text, $sql_query, $message, $errorUrl, $urlParams; - global $memory_limit, $read_limit, $finished, $offset, $charset_conversion, $charset_of_file; - global $timestamp, $maximum_time, $timeout_passed, $import_file, $go_sql, $sql_file, $error, $max_sql_len, $msg; - global $sql_query_disabled, $executed_queries, $run_query, $reset_charset; - global $result, $import_file_name, $sql_data, $import_notice, $read_multiply, $my_die, $active_page; - global $show_as_php, $reload, $charset_connection, $is_js_confirmed, $MAX_FILE_SIZE, $message_to_show; - global $noplugin, $skip_queries; - - $charset_of_file = $_POST['charset_of_file'] ?? null; - $format = $_POST['format'] ?? ''; - $import_type = $_POST['import_type'] ?? null; - $is_js_confirmed = $_POST['is_js_confirmed'] ?? null; - $MAX_FILE_SIZE = $_POST['MAX_FILE_SIZE'] ?? null; - $message_to_show = $_POST['message_to_show'] ?? null; - $noplugin = $_POST['noplugin'] ?? null; - $skip_queries = $_POST['skip_queries'] ?? null; - $local_import_file = $_POST['local_import_file'] ?? null; - $show_as_php = $_POST['show_as_php'] ?? null; + $GLOBALS['charset_of_file'] = $_POST['charset_of_file'] ?? null; + $GLOBALS['format'] = $_POST['format'] ?? ''; + $GLOBALS['import_type'] = $_POST['import_type'] ?? null; + $GLOBALS['is_js_confirmed'] = $_POST['is_js_confirmed'] ?? null; + $GLOBALS['MAX_FILE_SIZE'] = $_POST['MAX_FILE_SIZE'] ?? null; + $GLOBALS['message_to_show'] = $_POST['message_to_show'] ?? null; + $GLOBALS['noplugin'] = $_POST['noplugin'] ?? null; + $GLOBALS['skip_queries'] = $_POST['skip_queries'] ?? null; + $GLOBALS['local_import_file'] = $_POST['local_import_file'] ?? null; + $GLOBALS['show_as_php'] = $_POST['show_as_php'] ?? null; // If it's a refresh console bookmarks request if (isset($_GET['console_bookmark_refresh'])) { @@ -112,7 +103,7 @@ final class ImportController extends AbstractController $bookmarkFields = [ 'bkm_database' => $_POST['db'], - 'bkm_user' => $cfg['Server']['user'], + 'bkm_user' => $GLOBALS['cfg']['Server']['user'], 'bkm_sql_query' => $_POST['bookmark_query'], 'bkm_label' => $_POST['label'], ]; @@ -133,7 +124,7 @@ final class ImportController extends AbstractController $_SESSION['Import_message']['message'] = null; $_SESSION['Import_message']['go_back_url'] = null; // default values - $reload = false; + $GLOBALS['reload'] = false; // Use to identify current cycle is executing // a multiquery statement or stored routine @@ -141,11 +132,11 @@ final class ImportController extends AbstractController $_SESSION['is_multi_query'] = false; } - $ajax_reload = []; - $import_text = ''; + $GLOBALS['ajax_reload'] = []; + $GLOBALS['import_text'] = ''; // Are we just executing plain query or sql file? // (eg. non import, but query box/window run) - if (! empty($sql_query)) { + if (! empty($GLOBALS['sql_query'])) { // apply values for parameters if (! empty($_POST['parameterized']) && ! empty($_POST['parameters']) && is_array($_POST['parameters'])) { $parameters = $_POST['parameters']; @@ -157,76 +148,86 @@ final class ImportController extends AbstractController $quoted = preg_quote($parameter, '/'); // making sure that :param does not apply values to :param1 - $sql_query = preg_replace( + $GLOBALS['sql_query'] = preg_replace( '/' . $quoted . '([^a-zA-Z0-9_])/', $replacementValue . '${1}', - $sql_query + $GLOBALS['sql_query'] ); // for parameters the appear at the end of the string - $sql_query = preg_replace('/' . $quoted . '$/', $replacementValue, $sql_query); + $GLOBALS['sql_query'] = preg_replace( + '/' . $quoted . '$/', + $replacementValue, + $GLOBALS['sql_query'] + ); } } // run SQL query - $import_text = $sql_query; - $import_type = 'query'; - $format = 'sql'; + $GLOBALS['import_text'] = $GLOBALS['sql_query']; + $GLOBALS['import_type'] = 'query'; + $GLOBALS['format'] = 'sql'; $_SESSION['sql_from_query_box'] = true; // If there is a request to ROLLBACK when finished. if (isset($_POST['rollback_query'])) { - $this->import->handleRollbackRequest($import_text); + $this->import->handleRollbackRequest($GLOBALS['import_text']); } // refresh navigation and main panels - if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) { - $reload = true; - $ajax_reload['reload'] = true; + if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $GLOBALS['sql_query'])) { + $GLOBALS['reload'] = true; + $GLOBALS['ajax_reload']['reload'] = true; } // refresh navigation panel only - if (preg_match('/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) { - $ajax_reload['reload'] = true; + if (preg_match('/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $GLOBALS['sql_query'])) { + $GLOBALS['ajax_reload']['reload'] = true; } // do a dynamic reload if table is RENAMED // (by sending the instruction to the AJAX response handler) - if (preg_match('/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i', $sql_query, $rename_table_names)) { - $ajax_reload['reload'] = true; - $ajax_reload['table_name'] = Util::unQuote($rename_table_names[2]); + if ( + preg_match( + '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i', + $GLOBALS['sql_query'], + $rename_table_names + ) + ) { + $GLOBALS['ajax_reload']['reload'] = true; + $GLOBALS['ajax_reload']['table_name'] = Util::unQuote($rename_table_names[2]); } - $sql_query = ''; - } elseif (! empty($sql_file)) { + $GLOBALS['sql_query'] = ''; + } elseif (! empty($GLOBALS['sql_file'])) { // run uploaded SQL file - $import_file = $sql_file; - $import_type = 'queryfile'; - $format = 'sql'; - unset($sql_file); + $GLOBALS['import_file'] = $GLOBALS['sql_file']; + $GLOBALS['import_type'] = 'queryfile'; + $GLOBALS['format'] = 'sql'; + unset($GLOBALS['sql_file']); } elseif (! empty($_POST['id_bookmark'])) { // run bookmark - $import_type = 'query'; - $format = 'sql'; + $GLOBALS['import_type'] = 'query'; + $GLOBALS['format'] = 'sql'; } // If we didn't get any parameters, either user called this directly, or // upload limit has been reached, let's assume the second possibility. if ($_POST == [] && $_GET == []) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __( 'You probably tried to upload a file that is too large. Please refer ' . 'to %sdocumentation%s for a workaround for this limit.' ) ); - $message->addParam('[doc@faq1-16]'); - $message->addParam('[/doc]'); + $GLOBALS['message']->addParam('[doc@faq1-16]'); + $GLOBALS['message']->addParam('[/doc]'); // so we can obtain the message - $_SESSION['Import_message']['message'] = $message->getDisplay(); - $_SESSION['Import_message']['go_back_url'] = $goto; + $_SESSION['Import_message']['message'] = $GLOBALS['message']->getDisplay(); + $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto']; $this->response->setRequestStatus(false); - $this->response->addJSON('message', $message); + $this->response->addJSON('message', $GLOBALS['message']); return; // the footer is displayed automatically } @@ -241,7 +242,7 @@ final class ImportController extends AbstractController * We only need to load the selected plugin */ - if (! in_array($format, ['csv', 'ldi', 'mediawiki', 'ods', 'shp', 'sql', 'xml'])) { + if (! in_array($GLOBALS['format'], ['csv', 'ldi', 'mediawiki', 'ods', 'shp', 'sql', 'xml'])) { // this should not happen for a normal user // but only during an attack Core::fatalError('Incorrect format parameter'); @@ -249,7 +250,7 @@ final class ImportController extends AbstractController $post_patterns = [ '/^force_file_/', - '/^' . $format . '_/', + '/^' . $GLOBALS['format'] . '_/', ]; Core::setPostAsGlobal($post_patterns); @@ -258,73 +259,72 @@ final class ImportController extends AbstractController Util::checkParameters(['import_type', 'format']); // We don't want anything special in format - $format = Core::securePath($format); + $GLOBALS['format'] = Core::securePath($GLOBALS['format']); - if (strlen($table) > 0 && strlen($db) > 0) { - $urlParams = [ - 'db' => $db, - 'table' => $table, + if (strlen($GLOBALS['table']) > 0 && strlen($GLOBALS['db']) > 0) { + $GLOBALS['urlParams'] = [ + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], ]; - } elseif (strlen($db) > 0) { - $urlParams = ['db' => $db]; + } elseif (strlen($GLOBALS['db']) > 0) { + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db']]; } else { - $urlParams = []; + $GLOBALS['urlParams'] = []; } // Create error and goto url - if ($import_type === 'table') { - $goto = Url::getFromRoute('/table/import'); - } elseif ($import_type === 'database') { - $goto = Url::getFromRoute('/database/import'); - } elseif ($import_type === 'server') { - $goto = Url::getFromRoute('/server/import'); - } elseif (empty($goto) || ! preg_match('@^index\.php$@i', $goto)) { - if (strlen($table) > 0 && strlen($db) > 0) { - $goto = Url::getFromRoute('/table/structure'); - } elseif (strlen($db) > 0) { - $goto = Url::getFromRoute('/database/structure'); + if ($GLOBALS['import_type'] === 'table') { + $GLOBALS['goto'] = Url::getFromRoute('/table/import'); + } elseif ($GLOBALS['import_type'] === 'database') { + $GLOBALS['goto'] = Url::getFromRoute('/database/import'); + } elseif ($GLOBALS['import_type'] === 'server') { + $GLOBALS['goto'] = Url::getFromRoute('/server/import'); + } elseif (empty($GLOBALS['goto']) || ! preg_match('@^index\.php$@i', $GLOBALS['goto'])) { + if (strlen($GLOBALS['table']) > 0 && strlen($GLOBALS['db']) > 0) { + $GLOBALS['goto'] = Url::getFromRoute('/table/structure'); + } elseif (strlen($GLOBALS['db']) > 0) { + $GLOBALS['goto'] = Url::getFromRoute('/database/structure'); } else { - $goto = Url::getFromRoute('/server/sql'); + $GLOBALS['goto'] = Url::getFromRoute('/server/sql'); } } - $errorUrl = $goto . Url::getCommon($urlParams, '&'); - $_SESSION['Import_message']['go_back_url'] = $errorUrl; + $GLOBALS['errorUrl'] = $GLOBALS['goto'] . Url::getCommon($GLOBALS['urlParams'], '&'); + $_SESSION['Import_message']['go_back_url'] = $GLOBALS['errorUrl']; - if (strlen($db) > 0) { - $this->dbi->selectDb($db); + if (strlen($GLOBALS['db']) > 0) { + $this->dbi->selectDb($GLOBALS['db']); } Util::setTimeLimit(); - if (! empty($cfg['MemoryLimit'])) { - ini_set('memory_limit', $cfg['MemoryLimit']); + if (! empty($GLOBALS['cfg']['MemoryLimit'])) { + ini_set('memory_limit', $GLOBALS['cfg']['MemoryLimit']); } - $timestamp = time(); + $GLOBALS['timestamp'] = time(); if (isset($_POST['allow_interrupt'])) { - $maximum_time = ini_get('max_execution_time'); + $GLOBALS['maximum_time'] = ini_get('max_execution_time'); } else { - $maximum_time = 0; + $GLOBALS['maximum_time'] = 0; } // set default values - $timeout_passed = false; - $error = false; - $read_multiply = 1; - $finished = false; - $offset = 0; - $max_sql_len = 0; - $sql_query = ''; - $sql_query_disabled = false; - $go_sql = false; - $executed_queries = 0; - $run_query = true; - $charset_conversion = false; - $reset_charset = false; - $msg = 'Sorry an unexpected error happened!'; + $GLOBALS['timeout_passed'] = false; + $GLOBALS['error'] = false; + $GLOBALS['read_multiply'] = 1; + $GLOBALS['finished'] = false; + $GLOBALS['offset'] = 0; + $GLOBALS['max_sql_len'] = 0; + $GLOBALS['sql_query'] = ''; + $GLOBALS['sql_query_disabled'] = false; + $GLOBALS['go_sql'] = false; + $GLOBALS['executed_queries'] = 0; + $GLOBALS['run_query'] = true; + $GLOBALS['charset_conversion'] = false; + $GLOBALS['reset_charset'] = false; + $GLOBALS['msg'] = 'Sorry an unexpected error happened!'; - /** @var bool|mixed $result */ - $result = false; + $GLOBALS['result'] = false; // Bookmark Support: get a query back from bookmark if required if (! empty($_POST['id_bookmark'])) { @@ -333,8 +333,8 @@ final class ImportController extends AbstractController case 0: // bookmarked query that have to be run $bookmark = Bookmark::get( $this->dbi, - $cfg['Server']['user'], - $db, + $GLOBALS['cfg']['Server']['user'], + $GLOBALS['db'], $id_bookmark, 'id', isset($_POST['action_bookmark_all']) @@ -344,63 +344,73 @@ final class ImportController extends AbstractController } if (! empty($_POST['bookmark_variable'])) { - $import_text = $bookmark->applyVariables($_POST['bookmark_variable']); + $GLOBALS['import_text'] = $bookmark->applyVariables($_POST['bookmark_variable']); } else { - $import_text = $bookmark->getQuery(); + $GLOBALS['import_text'] = $bookmark->getQuery(); } // refresh navigation and main panels - if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $import_text)) { - $reload = true; - $ajax_reload['reload'] = true; + if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $GLOBALS['import_text'])) { + $GLOBALS['reload'] = true; + $GLOBALS['ajax_reload']['reload'] = true; } // refresh navigation panel only - if (preg_match('/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $import_text)) { - $ajax_reload['reload'] = true; + if (preg_match('/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $GLOBALS['import_text'])) { + $GLOBALS['ajax_reload']['reload'] = true; } break; case 1: // bookmarked query that have to be displayed - $bookmark = Bookmark::get($this->dbi, $cfg['Server']['user'], $db, $id_bookmark); + $bookmark = Bookmark::get( + $this->dbi, + $GLOBALS['cfg']['Server']['user'], + $GLOBALS['db'], + $id_bookmark + ); if (! $bookmark instanceof Bookmark) { break; } - $import_text = $bookmark->getQuery(); + $GLOBALS['import_text'] = $bookmark->getQuery(); if ($this->response->isAjax()) { - $message = Message::success(__('Showing bookmark')); - $this->response->setRequestStatus($message->isSuccess()); - $this->response->addJSON('message', $message); - $this->response->addJSON('sql_query', $import_text); + $GLOBALS['message'] = Message::success(__('Showing bookmark')); + $this->response->setRequestStatus($GLOBALS['message']->isSuccess()); + $this->response->addJSON('message', $GLOBALS['message']); + $this->response->addJSON('sql_query', $GLOBALS['import_text']); $this->response->addJSON('action_bookmark', $_POST['action_bookmark']); return; } else { - $run_query = false; + $GLOBALS['run_query'] = false; } break; case 2: // bookmarked query that have to be deleted - $bookmark = Bookmark::get($this->dbi, $cfg['Server']['user'], $db, $id_bookmark); + $bookmark = Bookmark::get( + $this->dbi, + $GLOBALS['cfg']['Server']['user'], + $GLOBALS['db'], + $id_bookmark + ); if (! $bookmark instanceof Bookmark) { break; } $bookmark->delete(); if ($this->response->isAjax()) { - $message = Message::success( + $GLOBALS['message'] = Message::success( __('The bookmark has been deleted.') ); - $this->response->setRequestStatus($message->isSuccess()); - $this->response->addJSON('message', $message); + $this->response->setRequestStatus($GLOBALS['message']->isSuccess()); + $this->response->addJSON('message', $GLOBALS['message']); $this->response->addJSON('action_bookmark', $_POST['action_bookmark']); $this->response->addJSON('id_bookmark', $id_bookmark); return; } else { - $run_query = false; - $error = true; // this is kind of hack to skip processing the query + $GLOBALS['run_query'] = false; + $GLOBALS['error'] = true; // this is kind of hack to skip processing the query } break; @@ -408,70 +418,70 @@ final class ImportController extends AbstractController } // Do no run query if we show PHP code - if (isset($show_as_php)) { - $run_query = false; - $go_sql = true; + if (isset($GLOBALS['show_as_php'])) { + $GLOBALS['run_query'] = false; + $GLOBALS['go_sql'] = true; } // We can not read all at once, otherwise we can run out of memory - $memory_limit = trim((string) ini_get('memory_limit')); + $GLOBALS['memory_limit'] = trim((string) ini_get('memory_limit')); // 2 MB as default - if (empty($memory_limit)) { - $memory_limit = 2 * 1024 * 1024; + if (empty($GLOBALS['memory_limit'])) { + $GLOBALS['memory_limit'] = 2 * 1024 * 1024; } // In case no memory limit we work on 10MB chunks - if ($memory_limit === '-1') { - $memory_limit = 10 * 1024 * 1024; + if ($GLOBALS['memory_limit'] === '-1') { + $GLOBALS['memory_limit'] = 10 * 1024 * 1024; } // Calculate value of the limit - $memoryUnit = mb_strtolower(substr((string) $memory_limit, -1)); + $memoryUnit = mb_strtolower(substr((string) $GLOBALS['memory_limit'], -1)); if ($memoryUnit === 'm') { - $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024; + $GLOBALS['memory_limit'] = (int) substr((string) $GLOBALS['memory_limit'], 0, -1) * 1024 * 1024; } elseif ($memoryUnit === 'k') { - $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024; + $GLOBALS['memory_limit'] = (int) substr((string) $GLOBALS['memory_limit'], 0, -1) * 1024; } elseif ($memoryUnit === 'g') { - $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024 * 1024; + $GLOBALS['memory_limit'] = (int) substr((string) $GLOBALS['memory_limit'], 0, -1) * 1024 * 1024 * 1024; } else { - $memory_limit = (int) $memory_limit; + $GLOBALS['memory_limit'] = (int) $GLOBALS['memory_limit']; } // Just to be sure, there might be lot of memory needed for uncompression - $read_limit = $memory_limit / 8; + $GLOBALS['read_limit'] = $GLOBALS['memory_limit'] / 8; // handle filenames if (isset($_FILES['import_file'])) { - $import_file = $_FILES['import_file']['tmp_name']; - $import_file_name = $_FILES['import_file']['name']; + $GLOBALS['import_file'] = $_FILES['import_file']['tmp_name']; + $GLOBALS['import_file_name'] = $_FILES['import_file']['name']; } - if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) { + if (! empty($GLOBALS['local_import_file']) && ! empty($GLOBALS['cfg']['UploadDir'])) { // sanitize $local_import_file as it comes from a POST - $local_import_file = Core::securePath($local_import_file); + $GLOBALS['local_import_file'] = Core::securePath($GLOBALS['local_import_file']); - $import_file = Util::userDir((string) $cfg['UploadDir']) - . $local_import_file; + $GLOBALS['import_file'] = Util::userDir((string) $GLOBALS['cfg']['UploadDir']) + . $GLOBALS['local_import_file']; /* * Do not allow symlinks to avoid security issues * (user can create symlink to file they can not access, * but phpMyAdmin can). */ - if (@is_link($import_file)) { - $import_file = 'none'; + if (@is_link($GLOBALS['import_file'])) { + $GLOBALS['import_file'] = 'none'; } - } elseif (empty($import_file) || ! is_uploaded_file($import_file)) { - $import_file = 'none'; + } elseif (empty($GLOBALS['import_file']) || ! is_uploaded_file($GLOBALS['import_file'])) { + $GLOBALS['import_file'] = 'none'; } // Do we have file to import? - if ($import_file !== 'none' && ! $error) { + if ($GLOBALS['import_file'] !== 'none' && ! $GLOBALS['error']) { /** * Handle file compression */ - $importHandle = new File($import_file); + $importHandle = new File($GLOBALS['import_file']); $importHandle->checkUploadedFile(); if ($importHandle->isError()) { /** @var Message $errorMessage */ @@ -504,8 +514,8 @@ final class ImportController extends AbstractController return; } - } elseif (! $error && (! isset($import_text) || empty($import_text))) { - $message = Message::error( + } elseif (! $GLOBALS['error'] && (! isset($GLOBALS['import_text']) || empty($GLOBALS['import_text']))) { + $GLOBALS['message'] = Message::error( __( 'No data was received to import. Either no file name was ' . 'submitted, or the file size exceeded the maximum size permitted ' . @@ -513,35 +523,38 @@ final class ImportController extends AbstractController ) ); - $_SESSION['Import_message']['message'] = $message->getDisplay(); + $_SESSION['Import_message']['message'] = $GLOBALS['message']->getDisplay(); $this->response->setRequestStatus(false); - $this->response->addJSON('message', $message->getDisplay()); - $this->response->addHTML($message->getDisplay()); + $this->response->addJSON('message', $GLOBALS['message']->getDisplay()); + $this->response->addHTML($GLOBALS['message']->getDisplay()); return; } // Convert the file's charset if necessary - if (Encoding::isSupported() && isset($charset_of_file)) { - if ($charset_of_file !== 'utf-8') { - $charset_conversion = true; + if (Encoding::isSupported() && isset($GLOBALS['charset_of_file'])) { + if ($GLOBALS['charset_of_file'] !== 'utf-8') { + $GLOBALS['charset_conversion'] = true; } - } elseif (isset($charset_of_file) && $charset_of_file !== 'utf-8') { - $this->dbi->query('SET NAMES \'' . $charset_of_file . '\''); + } elseif (isset($GLOBALS['charset_of_file']) && $GLOBALS['charset_of_file'] !== 'utf-8') { + $this->dbi->query('SET NAMES \'' . $GLOBALS['charset_of_file'] . '\''); // We can not show query in this case, it is in different charset - $sql_query_disabled = true; - $reset_charset = true; + $GLOBALS['sql_query_disabled'] = true; + $GLOBALS['reset_charset'] = true; } // Something to skip? (because timeout has passed) - if (! $error && isset($_POST['skip'])) { + if (! $GLOBALS['error'] && isset($_POST['skip'])) { $original_skip = $skip = intval($_POST['skip']); - while ($skip > 0 && ! $finished) { - $this->import->getNextChunk($importHandle ?? null, $skip < $read_limit ? $skip : $read_limit); + while ($skip > 0 && ! $GLOBALS['finished']) { + $this->import->getNextChunk( + $importHandle ?? null, + $skip < $GLOBALS['read_limit'] ? $skip : $GLOBALS['read_limit'] + ); // Disable read progressivity, otherwise we eat all memory! - $read_multiply = 1; - $skip -= $read_limit; + $GLOBALS['read_multiply'] = 1; + $skip -= $GLOBALS['read_limit']; } unset($skip); @@ -549,26 +562,26 @@ final class ImportController extends AbstractController // This array contain the data like number of valid sql queries in the statement // and complete valid sql statement (which affected for rows) - $sql_data = [ + $GLOBALS['sql_data'] = [ 'valid_sql' => [], 'valid_queries' => 0, ]; - if (! $error) { + if (! $GLOBALS['error']) { /** * @var ImportPlugin $import_plugin */ - $import_plugin = Plugins::getPlugin('import', $format, $import_type); + $import_plugin = Plugins::getPlugin('import', $GLOBALS['format'], $GLOBALS['import_type']); if ($import_plugin == null) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __('Could not load import plugins, please check your installation!') ); - $_SESSION['Import_message']['message'] = $message->getDisplay(); + $_SESSION['Import_message']['message'] = $GLOBALS['message']->getDisplay(); $this->response->setRequestStatus(false); - $this->response->addJSON('message', $message->getDisplay()); - $this->response->addHTML($message->getDisplay()); + $this->response->addJSON('message', $GLOBALS['message']->getDisplay()); + $this->response->addHTML($GLOBALS['message']->getDisplay()); return; } @@ -576,7 +589,7 @@ final class ImportController extends AbstractController // Do the real import $default_fk_check = ForeignKey::handleDisableCheckInit(); try { - $import_plugin->doImport($importHandle ?? null, $sql_data); + $import_plugin->doImport($importHandle ?? null, $GLOBALS['sql_data']); ForeignKey::handleDisableCheckCleanup($default_fk_check); } catch (Throwable $e) { ForeignKey::handleDisableCheckCleanup($default_fk_check); @@ -590,66 +603,66 @@ final class ImportController extends AbstractController } // Reset charset back, if we did some changes - if ($reset_charset) { - $this->dbi->query('SET CHARACTER SET ' . $charset_connection); - $this->dbi->setCollation($collation_connection); + if ($GLOBALS['reset_charset']) { + $this->dbi->query('SET CHARACTER SET ' . $GLOBALS['charset_connection']); + $this->dbi->setCollation($GLOBALS['collation_connection']); } // Show correct message if (! empty($id_bookmark) && $_POST['action_bookmark'] == 2) { - $message = Message::success(__('The bookmark has been deleted.')); - $display_query = $import_text; - $error = false; // unset error marker, it was used just to skip processing + $GLOBALS['message'] = Message::success(__('The bookmark has been deleted.')); + $GLOBALS['display_query'] = $GLOBALS['import_text']; + $GLOBALS['error'] = false; // unset error marker, it was used just to skip processing } elseif (! empty($id_bookmark) && $_POST['action_bookmark'] == 1) { - $message = Message::notice(__('Showing bookmark')); - } elseif ($finished && ! $error) { + $GLOBALS['message'] = Message::notice(__('Showing bookmark')); + } elseif ($GLOBALS['finished'] && ! $GLOBALS['error']) { // Do not display the query with message, we do it separately - $display_query = ';'; - if ($import_type !== 'query') { - $message = Message::success( + $GLOBALS['display_query'] = ';'; + if ($GLOBALS['import_type'] !== 'query') { + $GLOBALS['message'] = Message::success( '' . _ngettext( 'Import has been successfully finished, %d query executed.', 'Import has been successfully finished, %d queries executed.', - $executed_queries + $GLOBALS['executed_queries'] ) . '' ); - $message->addParam($executed_queries); + $GLOBALS['message']->addParam($GLOBALS['executed_queries']); - if (! empty($import_notice)) { - $message->addHtml($import_notice); + if (! empty($GLOBALS['import_notice'])) { + $GLOBALS['message']->addHtml($GLOBALS['import_notice']); } - if (! empty($local_import_file)) { - $message->addText('(' . $local_import_file . ')'); + if (! empty($GLOBALS['local_import_file'])) { + $GLOBALS['message']->addText('(' . $GLOBALS['local_import_file'] . ')'); } else { - $message->addText('(' . $_FILES['import_file']['name'] . ')'); + $GLOBALS['message']->addText('(' . $_FILES['import_file']['name'] . ')'); } } } // Did we hit timeout? Tell it user. - if ($timeout_passed) { - $urlParams['timeout_passed'] = '1'; - $urlParams['offset'] = $offset; - if (isset($local_import_file)) { - $urlParams['local_import_file'] = $local_import_file; + if ($GLOBALS['timeout_passed']) { + $GLOBALS['urlParams']['timeout_passed'] = '1'; + $GLOBALS['urlParams']['offset'] = $GLOBALS['offset']; + if (isset($GLOBALS['local_import_file'])) { + $GLOBALS['urlParams']['local_import_file'] = $GLOBALS['local_import_file']; } - $importUrl = $errorUrl = $goto . Url::getCommon($urlParams, '&'); + $importUrl = $GLOBALS['errorUrl'] = $GLOBALS['goto'] . Url::getCommon($GLOBALS['urlParams'], '&'); - $message = Message::error( + $GLOBALS['message'] = Message::error( __( 'Script timeout passed, if you want to finish import,' . ' please %sresubmit the same file%s and import will resume.' ) ); - $message->addParamHtml(''); - $message->addParamHtml(''); + $GLOBALS['message']->addParamHtml(''); + $GLOBALS['message']->addParamHtml(''); - if ($offset == 0 || (isset($original_skip) && $original_skip == $offset)) { - $message->addText( + if ($GLOBALS['offset'] == 0 || (isset($original_skip) && $original_skip == $GLOBALS['offset'])) { + $GLOBALS['message']->addText( __( 'However on last run no data has been parsed,' . ' this usually means phpMyAdmin won\'t be able to' @@ -661,63 +674,63 @@ final class ImportController extends AbstractController // if there is any message, copy it into $_SESSION as well, // so we can obtain it by AJAX call - if (isset($message)) { - $_SESSION['Import_message']['message'] = $message->getDisplay(); + if (isset($GLOBALS['message'])) { + $_SESSION['Import_message']['message'] = $GLOBALS['message']->getDisplay(); } // Parse and analyze the query, for correct db and table name // in case of a query typed in the query window // (but if the query is too large, in case of an imported file, the parser // can choke on it so avoid parsing) - $sqlLength = mb_strlen($sql_query); - if ($sqlLength <= $cfg['MaxCharactersInDisplayedSQL']) { + $sqlLength = mb_strlen($GLOBALS['sql_query']); + if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) { [ $analyzed_sql_results, - $db, + $GLOBALS['db'], $table_from_sql, - ] = ParseAnalyze::sqlQuery($sql_query, $db); + ] = ParseAnalyze::sqlQuery($GLOBALS['sql_query'], $GLOBALS['db']); - $reload = $analyzed_sql_results['reload']; - $offset = $analyzed_sql_results['offset']; + $GLOBALS['reload'] = $analyzed_sql_results['reload']; + $GLOBALS['offset'] = $analyzed_sql_results['offset']; - if ($table != $table_from_sql && ! empty($table_from_sql)) { - $table = $table_from_sql; + if ($GLOBALS['table'] != $table_from_sql && ! empty($table_from_sql)) { + $GLOBALS['table'] = $table_from_sql; } } // There was an error? - if (isset($my_die)) { - foreach ($my_die as $die) { - Generator::mysqlDie($die['error'], $die['sql'], false, $errorUrl, $error); + if (isset($GLOBALS['my_die'])) { + foreach ($GLOBALS['my_die'] as $die) { + Generator::mysqlDie($die['error'], $die['sql'], false, $GLOBALS['errorUrl'], $GLOBALS['error']); } } - if ($go_sql) { - if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) { + if ($GLOBALS['go_sql']) { + if (! empty($GLOBALS['sql_data']) && ($GLOBALS['sql_data']['valid_queries'] > 1)) { $_SESSION['is_multi_query'] = true; - $sql_queries = $sql_data['valid_sql']; + $sql_queries = $GLOBALS['sql_data']['valid_sql']; } else { - $sql_queries = [$sql_query]; + $sql_queries = [$GLOBALS['sql_query']]; } $html_output = ''; - foreach ($sql_queries as $sql_query) { + foreach ($sql_queries as $GLOBALS['sql_query']) { // parse sql query [ $analyzed_sql_results, - $db, + $GLOBALS['db'], $table_from_sql, - ] = ParseAnalyze::sqlQuery($sql_query, $db); + ] = ParseAnalyze::sqlQuery($GLOBALS['sql_query'], $GLOBALS['db']); - $offset = $analyzed_sql_results['offset']; - $reload = $analyzed_sql_results['reload']; + $GLOBALS['offset'] = $analyzed_sql_results['offset']; + $GLOBALS['reload'] = $analyzed_sql_results['reload']; // Check if User is allowed to issue a 'DROP DATABASE' Statement if ( $this->sql->hasNoRightsToDropDatabase( $analyzed_sql_results, - $cfg['AllowUserDropDatabase'], + $GLOBALS['cfg']['AllowUserDropDatabase'], $this->dbi->isSuperUser() ) ) { @@ -731,24 +744,24 @@ final class ImportController extends AbstractController return; } - if ($table != $table_from_sql && ! empty($table_from_sql)) { - $table = $table_from_sql; + if ($GLOBALS['table'] != $table_from_sql && ! empty($table_from_sql)) { + $GLOBALS['table'] = $table_from_sql; } $html_output .= $this->sql->executeQueryAndGetQueryResponse( $analyzed_sql_results, // analyzed_sql_results false, // is_gotofile - $db, // db - $table, // table + $GLOBALS['db'], // db + $GLOBALS['table'], // table null, // find_real_end null, // sql_query_for_bookmark - see below null, // extra_data null, // message_to_show null, // sql_data - $goto, // goto + $GLOBALS['goto'], // goto null, // disp_query null, // disp_message - $sql_query, // sql_query + $GLOBALS['sql_query'], // sql_query null // complete_query ); } @@ -756,34 +769,34 @@ final class ImportController extends AbstractController // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse // since only one bookmark has to be added for all the queries submitted through // the SQL tab - if (! empty($_POST['bkm_label']) && ! empty($import_text)) { + if (! empty($_POST['bkm_label']) && ! empty($GLOBALS['import_text'])) { $relation = new Relation($this->dbi); $this->sql->storeTheQueryAsBookmark( $relation->getRelationParameters()->bookmarkFeature, - $db, - $cfg['Server']['user'], + $GLOBALS['db'], + $GLOBALS['cfg']['Server']['user'], $_POST['sql_query'], $_POST['bkm_label'], isset($_POST['bkm_replace']) ); } - $this->response->addJSON('ajax_reload', $ajax_reload); + $this->response->addJSON('ajax_reload', $GLOBALS['ajax_reload']); $this->response->addHTML($html_output); return; } - if ($result) { + if ($GLOBALS['result']) { // Save a Bookmark with more than one queries (if Bookmark label given). - if (! empty($_POST['bkm_label']) && ! empty($import_text)) { + if (! empty($_POST['bkm_label']) && ! empty($GLOBALS['import_text'])) { $relation = new Relation($this->dbi); $this->sql->storeTheQueryAsBookmark( $relation->getRelationParameters()->bookmarkFeature, - $db, - $cfg['Server']['user'], + $GLOBALS['db'], + $GLOBALS['cfg']['Server']['user'], $_POST['sql_query'], $_POST['bkm_label'], isset($_POST['bkm_replace']) @@ -791,18 +804,18 @@ final class ImportController extends AbstractController } $this->response->setRequestStatus(true); - $this->response->addJSON('message', Message::success($msg)); + $this->response->addJSON('message', Message::success($GLOBALS['msg'])); $this->response->addJSON( 'sql_query', - Generator::getMessage($msg, $sql_query, 'success') + Generator::getMessage($GLOBALS['msg'], $GLOBALS['sql_query'], 'success') ); - } elseif ($result === false) { + } elseif ($GLOBALS['result'] === false) { $this->response->setRequestStatus(false); - $this->response->addJSON('message', Message::error($msg)); + $this->response->addJSON('message', Message::error($GLOBALS['msg'])); } else { - $active_page = $goto; + $GLOBALS['active_page'] = $GLOBALS['goto']; /** @psalm-suppress UnresolvableInclude */ - include ROOT_PATH . $goto; + include ROOT_PATH . $GLOBALS['goto']; } // If there is request for ROLLBACK in the end. diff --git a/libraries/classes/Controllers/Import/StatusController.php b/libraries/classes/Controllers/Import/StatusController.php index 8813e77f68..de7b9ec413 100644 --- a/libraries/classes/Controllers/Import/StatusController.php +++ b/libraries/classes/Controllers/Import/StatusController.php @@ -32,12 +32,10 @@ class StatusController public function __invoke(): void { - global $SESSION_KEY, $upload_id, $plugins, $timestamp; - [ - $SESSION_KEY, - $upload_id, - $plugins, + $GLOBALS['SESSION_KEY'], + $GLOBALS['upload_id'], + $GLOBALS['plugins'], ] = Ajax::uploadProgressSetup(); // $_GET["message"] is used for asking for an import message @@ -51,7 +49,7 @@ class StatusController usleep(300000); $maximumTime = ini_get('max_execution_time'); - $timestamp = time(); + $GLOBALS['timestamp'] = time(); // wait until message is available while (($_SESSION['Import_message']['message'] ?? null) == null) { // close session before sleeping @@ -61,7 +59,7 @@ class StatusController // reopen session session_start(); - if (time() - $timestamp > $maximumTime) { + if (time() - $GLOBALS['timestamp'] > $maximumTime) { $_SESSION['Import_message']['message'] = Message::error( __('Could not load the progress of the import.') )->getDisplay(); diff --git a/libraries/classes/Controllers/LogoutController.php b/libraries/classes/Controllers/LogoutController.php index 5050e42d1b..4bce6b75bc 100644 --- a/libraries/classes/Controllers/LogoutController.php +++ b/libraries/classes/Controllers/LogoutController.php @@ -10,14 +10,12 @@ class LogoutController { public function __invoke(): void { - global $auth_plugin, $token_mismatch; - - if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST' || $token_mismatch) { + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST' || $GLOBALS['token_mismatch']) { Core::sendHeaderLocation('./index.php?route=/'); return; } - $auth_plugin->logOut(); + $GLOBALS['auth_plugin']->logOut(); } } diff --git a/libraries/classes/Controllers/NormalizationController.php b/libraries/classes/Controllers/NormalizationController.php index 07625d661a..eaf109a537 100644 --- a/libraries/classes/Controllers/NormalizationController.php +++ b/libraries/classes/Controllers/NormalizationController.php @@ -34,15 +34,13 @@ class NormalizationController extends AbstractController public function __invoke(): void { - global $db, $table; - if (isset($_POST['getColumns'])) { $html = '' . ''; //get column whose datatype falls under string category $html .= $this->normalization->getHtmlForColumnsList( - $db, - $table, + $GLOBALS['db'], + $GLOBALS['table'], _pgettext('string types', 'String') ); echo $html; @@ -52,8 +50,8 @@ class NormalizationController extends AbstractController if (isset($_POST['splitColumn'])) { $num_fields = min(4096, intval($_POST['numFields'])); - $html = $this->normalization->getHtmlForCreateNewColumn($num_fields, $db, $table); - $html .= Url::getHiddenInputs($db, $table); + $html = $this->normalization->getHtmlForCreateNewColumn($num_fields, $GLOBALS['db'], $GLOBALS['table']); + $html .= Url::getHiddenInputs($GLOBALS['db'], $GLOBALS['table']); echo $html; return; @@ -62,18 +60,23 @@ class NormalizationController extends AbstractController if (isset($_POST['addNewPrimary'])) { $num_fields = 1; $columnMeta = [ - 'Field' => $table . '_id', + 'Field' => $GLOBALS['table'] . '_id', 'Extra' => 'auto_increment', ]; - $html = $this->normalization->getHtmlForCreateNewColumn($num_fields, $db, $table, $columnMeta); - $html .= Url::getHiddenInputs($db, $table); + $html = $this->normalization->getHtmlForCreateNewColumn( + $num_fields, + $GLOBALS['db'], + $GLOBALS['table'], + $columnMeta + ); + $html .= Url::getHiddenInputs($GLOBALS['db'], $GLOBALS['table']); echo $html; return; } if (isset($_POST['findPdl'])) { - $html = $this->normalization->findPartialDependencies($table, $db); + $html = $this->normalization->findPartialDependencies($GLOBALS['table'], $GLOBALS['db']); echo $html; return; @@ -81,7 +84,7 @@ class NormalizationController extends AbstractController if (isset($_POST['getNewTables2NF'])) { $partialDependencies = json_decode($_POST['pd'], true); - $html = $this->normalization->getHtmlForNewTables2NF($partialDependencies, $table); + $html = $this->normalization->getHtmlForNewTables2NF($partialDependencies, $GLOBALS['table']); echo $html; return; @@ -90,7 +93,7 @@ class NormalizationController extends AbstractController if (isset($_POST['getNewTables3NF'])) { $dependencies = json_decode($_POST['pd']); $tables = json_decode($_POST['tables'], true); - $newTables = $this->normalization->getHtmlForNewTables3NF($dependencies, $tables, $db); + $newTables = $this->normalization->getHtmlForNewTables3NF($dependencies, $tables, $GLOBALS['db']); $this->response->disable(); Core::headerJSON(); echo json_encode($newTables); @@ -108,7 +111,12 @@ class NormalizationController extends AbstractController if (isset($_POST['createNewTables2NF'])) { $partialDependencies = json_decode($_POST['pd'], true); $tablesName = json_decode($_POST['newTablesName']); - $res = $this->normalization->createNewTablesFor2NF($partialDependencies, $tablesName, $table, $db); + $res = $this->normalization->createNewTablesFor2NF( + $partialDependencies, + $tablesName, + $GLOBALS['table'], + $GLOBALS['db'] + ); $this->response->addJSON($res); return; @@ -116,7 +124,7 @@ class NormalizationController extends AbstractController if (isset($_POST['createNewTables3NF'])) { $newtables = json_decode($_POST['newTables'], true); - $res = $this->normalization->createNewTablesFor3NF($newtables, $db); + $res = $this->normalization->createNewTablesFor3NF($newtables, $GLOBALS['db']); $this->response->addJSON($res); return; @@ -132,8 +140,8 @@ class NormalizationController extends AbstractController $primary_columns, $newTable, $newColumn, - $table, - $db + $GLOBALS['table'], + $GLOBALS['db'] ); $this->response->addJSON($res); @@ -141,23 +149,23 @@ class NormalizationController extends AbstractController } if (isset($_POST['step1'])) { - $html = $this->normalization->getHtmlFor1NFStep1($db, $table, $normalForm); + $html = $this->normalization->getHtmlFor1NFStep1($GLOBALS['db'], $GLOBALS['table'], $normalForm); $this->response->addHTML($html); } elseif (isset($_POST['step2'])) { - $res = $this->normalization->getHtmlContentsFor1NFStep2($db, $table); + $res = $this->normalization->getHtmlContentsFor1NFStep2($GLOBALS['db'], $GLOBALS['table']); $this->response->addJSON($res); } elseif (isset($_POST['step3'])) { - $res = $this->normalization->getHtmlContentsFor1NFStep3($db, $table); + $res = $this->normalization->getHtmlContentsFor1NFStep3($GLOBALS['db'], $GLOBALS['table']); $this->response->addJSON($res); } elseif (isset($_POST['step4'])) { - $res = $this->normalization->getHtmlContentsFor1NFStep4($db, $table); + $res = $this->normalization->getHtmlContentsFor1NFStep4($GLOBALS['db'], $GLOBALS['table']); $this->response->addJSON($res); } elseif (isset($_POST['step']) && $_POST['step'] == '2.1') { - $res = $this->normalization->getHtmlFor2NFstep1($db, $table); + $res = $this->normalization->getHtmlFor2NFstep1($GLOBALS['db'], $GLOBALS['table']); $this->response->addJSON($res); } elseif (isset($_POST['step']) && $_POST['step'] == '3.1') { $tables = $_POST['tables']; - $res = $this->normalization->getHtmlFor3NFstep1($db, $tables); + $res = $this->normalization->getHtmlFor3NFstep1($GLOBALS['db'], $tables); $this->response->addJSON($res); } else { $this->response->addHTML($this->normalization->getHtmlForNormalizeTable()); diff --git a/libraries/classes/Controllers/PhpInfoController.php b/libraries/classes/Controllers/PhpInfoController.php index b1924c5adc..21cb516921 100644 --- a/libraries/classes/Controllers/PhpInfoController.php +++ b/libraries/classes/Controllers/PhpInfoController.php @@ -20,12 +20,10 @@ class PhpInfoController extends AbstractController { public function __invoke(): void { - global $cfg; - $this->response->disable(); $this->response->getHeader()->sendHttpHeaders(); - if (! $cfg['ShowPhpInfo']) { + if (! $GLOBALS['cfg']['ShowPhpInfo']) { return; } diff --git a/libraries/classes/Controllers/Preferences/ExportController.php b/libraries/classes/Controllers/Preferences/ExportController.php index 313f635012..3b94a82af5 100644 --- a/libraries/classes/Controllers/Preferences/ExportController.php +++ b/libraries/classes/Controllers/Preferences/ExportController.php @@ -45,14 +45,12 @@ class ExportController extends AbstractController public function __invoke(): void { - global $cfg, $cf, $error, $tabHash, $hash, $server; - $route = Routing::getCurrentRoute(); - $cf = new ConfigFile($this->config->baseSettings); - $this->userPreferences->pageInit($cf); + $GLOBALS['cf'] = new ConfigFile($this->config->baseSettings); + $this->userPreferences->pageInit($GLOBALS['cf']); - $formDisplay = new ExportForm($cf, 1); + $formDisplay = new ExportForm($GLOBALS['cf'], 1); if (isset($_POST['revert'])) { // revert erroneous fields to their default values @@ -62,25 +60,25 @@ class ExportController extends AbstractController return; } - $error = null; + $GLOBALS['error'] = null; if ($formDisplay->process(false) && ! $formDisplay->hasErrors()) { // Load 2FA settings - $twoFactor = new TwoFactor($cfg['Server']['user']); + $twoFactor = new TwoFactor($GLOBALS['cfg']['Server']['user']); // save settings - $result = $this->userPreferences->save($cf->getConfigArray()); + $result = $this->userPreferences->save($GLOBALS['cf']->getConfigArray()); // save back the 2FA setting only $twoFactor->save(); if ($result === true) { // reload config $this->config->loadUserPreferences(); - $tabHash = $_POST['tab_hash'] ?? null; - $hash = ltrim($tabHash, '#'); - $this->userPreferences->redirect('index.php?route=/preferences/export', null, $hash); + $GLOBALS['tabHash'] = $_POST['tab_hash'] ?? null; + $GLOBALS['hash'] = ltrim($GLOBALS['tabHash'], '#'); + $this->userPreferences->redirect('index.php?route=/preferences/export', null, $GLOBALS['hash']); return; } - $error = $result; + $GLOBALS['error'] = $result; } $this->addScriptFiles(['config.js']); @@ -98,13 +96,13 @@ class ExportController extends AbstractController } $this->render('preferences/forms/main', [ - 'error' => $error ? $error->getDisplay() : '', + 'error' => $GLOBALS['error'] ? $GLOBALS['error']->getDisplay() : '', 'has_errors' => $formDisplay->hasErrors(), 'errors' => $formErrors ?? null, 'form' => $formDisplay->getDisplay( true, Url::getFromRoute('/preferences/export'), - ['server' => $server] + ['server' => $GLOBALS['server']] ), ]); diff --git a/libraries/classes/Controllers/Preferences/FeaturesController.php b/libraries/classes/Controllers/Preferences/FeaturesController.php index 8d8d986a2d..ad6fd20a20 100644 --- a/libraries/classes/Controllers/Preferences/FeaturesController.php +++ b/libraries/classes/Controllers/Preferences/FeaturesController.php @@ -45,14 +45,12 @@ class FeaturesController extends AbstractController public function __invoke(): void { - global $cfg, $cf, $error, $tabHash, $hash, $server; - $route = Routing::getCurrentRoute(); - $cf = new ConfigFile($this->config->baseSettings); - $this->userPreferences->pageInit($cf); + $GLOBALS['cf'] = new ConfigFile($this->config->baseSettings); + $this->userPreferences->pageInit($GLOBALS['cf']); - $formDisplay = new FeaturesForm($cf, 1); + $formDisplay = new FeaturesForm($GLOBALS['cf'], 1); if (isset($_POST['revert'])) { // revert erroneous fields to their default values @@ -62,25 +60,25 @@ class FeaturesController extends AbstractController return; } - $error = null; + $GLOBALS['error'] = null; if ($formDisplay->process(false) && ! $formDisplay->hasErrors()) { // Load 2FA settings - $twoFactor = new TwoFactor($cfg['Server']['user']); + $twoFactor = new TwoFactor($GLOBALS['cfg']['Server']['user']); // save settings - $result = $this->userPreferences->save($cf->getConfigArray()); + $result = $this->userPreferences->save($GLOBALS['cf']->getConfigArray()); // save back the 2FA setting only $twoFactor->save(); if ($result === true) { // reload config $this->config->loadUserPreferences(); - $tabHash = $_POST['tab_hash'] ?? null; - $hash = ltrim($tabHash, '#'); - $this->userPreferences->redirect('index.php?route=/preferences/features', null, $hash); + $GLOBALS['tabHash'] = $_POST['tab_hash'] ?? null; + $GLOBALS['hash'] = ltrim($GLOBALS['tabHash'], '#'); + $this->userPreferences->redirect('index.php?route=/preferences/features', null, $GLOBALS['hash']); return; } - $error = $result; + $GLOBALS['error'] = $result; } $this->addScriptFiles(['config.js']); @@ -98,13 +96,13 @@ class FeaturesController extends AbstractController } $this->render('preferences/forms/main', [ - 'error' => $error ? $error->getDisplay() : '', + 'error' => $GLOBALS['error'] ? $GLOBALS['error']->getDisplay() : '', 'has_errors' => $formDisplay->hasErrors(), 'errors' => $formErrors ?? null, 'form' => $formDisplay->getDisplay( true, Url::getFromRoute('/preferences/features'), - ['server' => $server] + ['server' => $GLOBALS['server']] ), ]); diff --git a/libraries/classes/Controllers/Preferences/ImportController.php b/libraries/classes/Controllers/Preferences/ImportController.php index 48755f5661..8f0221013a 100644 --- a/libraries/classes/Controllers/Preferences/ImportController.php +++ b/libraries/classes/Controllers/Preferences/ImportController.php @@ -45,14 +45,12 @@ class ImportController extends AbstractController public function __invoke(): void { - global $cfg, $cf, $error, $tabHash, $hash, $server; - $route = Routing::getCurrentRoute(); - $cf = new ConfigFile($this->config->baseSettings); - $this->userPreferences->pageInit($cf); + $GLOBALS['cf'] = new ConfigFile($this->config->baseSettings); + $this->userPreferences->pageInit($GLOBALS['cf']); - $formDisplay = new ImportForm($cf, 1); + $formDisplay = new ImportForm($GLOBALS['cf'], 1); if (isset($_POST['revert'])) { // revert erroneous fields to their default values @@ -62,25 +60,25 @@ class ImportController extends AbstractController return; } - $error = null; + $GLOBALS['error'] = null; if ($formDisplay->process(false) && ! $formDisplay->hasErrors()) { // Load 2FA settings - $twoFactor = new TwoFactor($cfg['Server']['user']); + $twoFactor = new TwoFactor($GLOBALS['cfg']['Server']['user']); // save settings - $result = $this->userPreferences->save($cf->getConfigArray()); + $result = $this->userPreferences->save($GLOBALS['cf']->getConfigArray()); // save back the 2FA setting only $twoFactor->save(); if ($result === true) { // reload config $this->config->loadUserPreferences(); - $tabHash = $_POST['tab_hash'] ?? null; - $hash = ltrim($tabHash, '#'); - $this->userPreferences->redirect('index.php?route=/preferences/import', null, $hash); + $GLOBALS['tabHash'] = $_POST['tab_hash'] ?? null; + $GLOBALS['hash'] = ltrim($GLOBALS['tabHash'], '#'); + $this->userPreferences->redirect('index.php?route=/preferences/import', null, $GLOBALS['hash']); return; } - $error = $result; + $GLOBALS['error'] = $result; } $this->addScriptFiles(['config.js']); @@ -98,13 +96,13 @@ class ImportController extends AbstractController } $this->render('preferences/forms/main', [ - 'error' => $error ? $error->getDisplay() : '', + 'error' => $GLOBALS['error'] ? $GLOBALS['error']->getDisplay() : '', 'has_errors' => $formDisplay->hasErrors(), 'errors' => $formErrors ?? null, 'form' => $formDisplay->getDisplay( true, Url::getFromRoute('/preferences/import'), - ['server' => $server] + ['server' => $GLOBALS['server']] ), ]); diff --git a/libraries/classes/Controllers/Preferences/MainPanelController.php b/libraries/classes/Controllers/Preferences/MainPanelController.php index afdfd4d3ce..a4de9a852d 100644 --- a/libraries/classes/Controllers/Preferences/MainPanelController.php +++ b/libraries/classes/Controllers/Preferences/MainPanelController.php @@ -45,14 +45,12 @@ class MainPanelController extends AbstractController public function __invoke(): void { - global $cfg, $cf, $error, $tabHash, $hash, $server; - $route = Routing::getCurrentRoute(); - $cf = new ConfigFile($this->config->baseSettings); - $this->userPreferences->pageInit($cf); + $GLOBALS['cf'] = new ConfigFile($this->config->baseSettings); + $this->userPreferences->pageInit($GLOBALS['cf']); - $formDisplay = new MainForm($cf, 1); + $formDisplay = new MainForm($GLOBALS['cf'], 1); if (isset($_POST['revert'])) { // revert erroneous fields to their default values @@ -62,25 +60,25 @@ class MainPanelController extends AbstractController return; } - $error = null; + $GLOBALS['error'] = null; if ($formDisplay->process(false) && ! $formDisplay->hasErrors()) { // Load 2FA settings - $twoFactor = new TwoFactor($cfg['Server']['user']); + $twoFactor = new TwoFactor($GLOBALS['cfg']['Server']['user']); // save settings - $result = $this->userPreferences->save($cf->getConfigArray()); + $result = $this->userPreferences->save($GLOBALS['cf']->getConfigArray()); // save back the 2FA setting only $twoFactor->save(); if ($result === true) { // reload config $this->config->loadUserPreferences(); - $tabHash = $_POST['tab_hash'] ?? null; - $hash = ltrim($tabHash, '#'); - $this->userPreferences->redirect('index.php?route=/preferences/main-panel', null, $hash); + $GLOBALS['tabHash'] = $_POST['tab_hash'] ?? null; + $GLOBALS['hash'] = ltrim($GLOBALS['tabHash'], '#'); + $this->userPreferences->redirect('index.php?route=/preferences/main-panel', null, $GLOBALS['hash']); return; } - $error = $result; + $GLOBALS['error'] = $result; } $this->addScriptFiles(['config.js']); @@ -98,13 +96,13 @@ class MainPanelController extends AbstractController } $this->render('preferences/forms/main', [ - 'error' => $error ? $error->getDisplay() : '', + 'error' => $GLOBALS['error'] ? $GLOBALS['error']->getDisplay() : '', 'has_errors' => $formDisplay->hasErrors(), 'errors' => $formErrors ?? null, 'form' => $formDisplay->getDisplay( true, Url::getFromRoute('/preferences/main-panel'), - ['server' => $server] + ['server' => $GLOBALS['server']] ), ]); diff --git a/libraries/classes/Controllers/Preferences/ManageController.php b/libraries/classes/Controllers/Preferences/ManageController.php index e693397a69..cac70ef309 100644 --- a/libraries/classes/Controllers/Preferences/ManageController.php +++ b/libraries/classes/Controllers/Preferences/ManageController.php @@ -67,20 +67,17 @@ class ManageController extends AbstractController public function __invoke(): void { - global $cf, $error, $filename, $json, $lang; - global $new_config, $return_url, $form_display, $all_ok, $params, $query; - $route = Routing::getCurrentRoute(); - $cf = new ConfigFile($this->config->baseSettings); - $this->userPreferences->pageInit($cf); + $GLOBALS['cf'] = new ConfigFile($this->config->baseSettings); + $this->userPreferences->pageInit($GLOBALS['cf']); - $error = ''; + $GLOBALS['error'] = ''; if (isset($_POST['submit_export'], $_POST['export_type']) && $_POST['export_type'] === 'text_file') { // export to JSON file $this->response->disable(); - $filename = 'phpMyAdmin-config-' . urlencode(Core::getenv('HTTP_HOST')) . '.json'; - Core::downloadHeader($filename, 'application/json'); + $GLOBALS['filename'] = 'phpMyAdmin-config-' . urlencode(Core::getenv('HTTP_HOST')) . '.json'; + Core::downloadHeader($GLOBALS['filename'], 'application/json'); $settings = $this->userPreferences->load(); echo json_encode($settings['config_data'], JSON_PRETTY_PRINT); @@ -90,8 +87,8 @@ class ManageController extends AbstractController if (isset($_POST['submit_export'], $_POST['export_type']) && $_POST['export_type'] === 'php_file') { // export to JSON file $this->response->disable(); - $filename = 'phpMyAdmin-config-' . urlencode(Core::getenv('HTTP_HOST')) . '.php'; - Core::downloadHeader($filename, 'application/php'); + $GLOBALS['filename'] = 'phpMyAdmin-config-' . urlencode(Core::getenv('HTTP_HOST')) . '.php'; + Core::downloadHeader($GLOBALS['filename'], 'application/php'); $settings = $this->userPreferences->load(); echo '/* ' . __('phpMyAdmin configuration snippet') . " */\n\n"; echo '/* ' . __('Paste it to your config.inc.php') . " */\n\n"; @@ -113,7 +110,7 @@ class ManageController extends AbstractController if (isset($_POST['submit_import'])) { // load from JSON file - $json = ''; + $GLOBALS['json'] = ''; if ( isset($_POST['import_type'], $_FILES['import_file']) && $_POST['import_type'] === 'text_file' @@ -123,51 +120,51 @@ class ManageController extends AbstractController $importHandle = new File($_FILES['import_file']['tmp_name']); $importHandle->checkUploadedFile(); if ($importHandle->isError()) { - $error = $importHandle->getError(); + $GLOBALS['error'] = $importHandle->getError(); } else { // read JSON from uploaded file - $json = $importHandle->getRawContent(); + $GLOBALS['json'] = $importHandle->getRawContent(); } } else { // read from POST value (json) - $json = $_POST['json'] ?? null; + $GLOBALS['json'] = $_POST['json'] ?? null; } // hide header message $_SESSION['userprefs_autoload'] = true; - $configuration = json_decode($json, true); - $return_url = $_POST['return_url'] ?? null; + $configuration = json_decode($GLOBALS['json'], true); + $GLOBALS['return_url'] = $_POST['return_url'] ?? null; if (! is_array($configuration)) { - if (! isset($error)) { - $error = __('Could not import configuration'); + if (! isset($GLOBALS['error'])) { + $GLOBALS['error'] = __('Could not import configuration'); } } else { // sanitize input values: treat them as though // they came from HTTP POST request - $form_display = new UserFormList($cf); - $new_config = $cf->getFlatDefaultConfig(); + $GLOBALS['form_display'] = new UserFormList($GLOBALS['cf']); + $GLOBALS['new_config'] = $GLOBALS['cf']->getFlatDefaultConfig(); if (! empty($_POST['import_merge'])) { - $new_config = array_merge($new_config, $cf->getConfigArray()); + $GLOBALS['new_config'] = array_merge($GLOBALS['new_config'], $GLOBALS['cf']->getConfigArray()); } - $new_config = array_merge($new_config, $configuration); + $GLOBALS['new_config'] = array_merge($GLOBALS['new_config'], $configuration); $_POST_bak = $_POST; - foreach ($new_config as $k => $v) { + foreach ($GLOBALS['new_config'] as $k => $v) { $_POST[str_replace('/', '-', (string) $k)] = $v; } - $cf->resetConfigData(); - $all_ok = $form_display->process(true, false); - $all_ok = $all_ok && ! $form_display->hasErrors(); + $GLOBALS['cf']->resetConfigData(); + $GLOBALS['all_ok'] = $GLOBALS['form_display']->process(true, false); + $GLOBALS['all_ok'] = $GLOBALS['all_ok'] && ! $GLOBALS['form_display']->hasErrors(); $_POST = $_POST_bak; - if (! $all_ok && isset($_POST['fix_errors'])) { - $form_display->fixErrors(); - $all_ok = true; + if (! $GLOBALS['all_ok'] && isset($_POST['fix_errors'])) { + $GLOBALS['form_display']->fixErrors(); + $GLOBALS['all_ok'] = true; } - if (! $all_ok) { + if (! $GLOBALS['all_ok']) { // mimic original form and post json in a hidden field $relationParameters = $this->relation->getRelationParameters(); @@ -178,17 +175,17 @@ class ManageController extends AbstractController ]); echo $this->template->render('preferences/manage/error', [ - 'form_errors' => $form_display->displayErrors(), - 'json' => $json, + 'form_errors' => $GLOBALS['form_display']->displayErrors(), + 'json' => $GLOBALS['json'], 'import_merge' => $_POST['import_merge'] ?? null, - 'return_url' => $return_url, + 'return_url' => $GLOBALS['return_url'], ]); return; } // check for ThemeDefault - $params = []; + $GLOBALS['params'] = []; $tmanager = ThemeManager::getInstance(); if ( isset($configuration['ThemeDefault']) @@ -199,50 +196,50 @@ class ManageController extends AbstractController $tmanager->setThemeCookie(); } - if (isset($configuration['lang']) && $configuration['lang'] != $lang) { - $params['lang'] = $configuration['lang']; + if (isset($configuration['lang']) && $configuration['lang'] != $GLOBALS['lang']) { + $GLOBALS['params']['lang'] = $configuration['lang']; } // save settings - $result = $this->userPreferences->save($cf->getConfigArray()); + $result = $this->userPreferences->save($GLOBALS['cf']->getConfigArray()); if ($result === true) { - if ($return_url) { - $query = Util::splitURLQuery($return_url); - $return_url = parse_url($return_url, PHP_URL_PATH); + if ($GLOBALS['return_url']) { + $GLOBALS['query'] = Util::splitURLQuery($GLOBALS['return_url']); + $GLOBALS['return_url'] = parse_url($GLOBALS['return_url'], PHP_URL_PATH); - foreach ($query as $q) { + foreach ($GLOBALS['query'] as $q) { $pos = mb_strpos($q, '='); $k = mb_substr($q, 0, (int) $pos); if ($k === 'token') { continue; } - $params[$k] = mb_substr($q, $pos + 1); + $GLOBALS['params'][$k] = mb_substr($q, $pos + 1); } } else { - $return_url = 'index.php?route=/preferences/manage'; + $GLOBALS['return_url'] = 'index.php?route=/preferences/manage'; } // reload config $this->config->loadUserPreferences(); - $this->userPreferences->redirect($return_url ?? '', $params); + $this->userPreferences->redirect($GLOBALS['return_url'] ?? '', $GLOBALS['params']); return; } - $error = $result; + $GLOBALS['error'] = $result; } } elseif (isset($_POST['submit_clear'])) { $result = $this->userPreferences->save([]); if ($result === true) { - $params = []; + $GLOBALS['params'] = []; $this->config->removeCookie('pma_collaction_connection'); $this->config->removeCookie('pma_lang'); - $this->userPreferences->redirect('index.php?route=/preferences/manage', $params); + $this->userPreferences->redirect('index.php?route=/preferences/manage', $GLOBALS['params']); return; } else { - $error = $result; + $GLOBALS['error'] = $result; } return; @@ -258,16 +255,16 @@ class ManageController extends AbstractController 'has_config_storage' => $relationParameters->userPreferencesFeature !== null, ]); - if ($error) { - if (! $error instanceof Message) { - $error = Message::error($error); + if ($GLOBALS['error']) { + if (! $GLOBALS['error'] instanceof Message) { + $GLOBALS['error'] = Message::error($GLOBALS['error']); } - $error->getDisplay(); + $GLOBALS['error']->getDisplay(); } echo $this->template->render('preferences/manage/main', [ - 'error' => $error, + 'error' => $GLOBALS['error'], 'max_upload_size' => $GLOBALS['config']->get('max_upload_size'), 'exists_setup_and_not_exists_config' => @file_exists(ROOT_PATH . 'setup/index.php') && ! @file_exists(CONFIG_FILE), diff --git a/libraries/classes/Controllers/Preferences/NavigationController.php b/libraries/classes/Controllers/Preferences/NavigationController.php index fdce42afb2..a46180e6a9 100644 --- a/libraries/classes/Controllers/Preferences/NavigationController.php +++ b/libraries/classes/Controllers/Preferences/NavigationController.php @@ -45,14 +45,12 @@ class NavigationController extends AbstractController public function __invoke(): void { - global $cfg, $cf, $error, $tabHash, $hash, $server; - $route = Routing::getCurrentRoute(); - $cf = new ConfigFile($this->config->baseSettings); - $this->userPreferences->pageInit($cf); + $GLOBALS['cf'] = new ConfigFile($this->config->baseSettings); + $this->userPreferences->pageInit($GLOBALS['cf']); - $formDisplay = new NaviForm($cf, 1); + $formDisplay = new NaviForm($GLOBALS['cf'], 1); if (isset($_POST['revert'])) { // revert erroneous fields to their default values @@ -62,25 +60,25 @@ class NavigationController extends AbstractController return; } - $error = null; + $GLOBALS['error'] = null; if ($formDisplay->process(false) && ! $formDisplay->hasErrors()) { // Load 2FA settings - $twoFactor = new TwoFactor($cfg['Server']['user']); + $twoFactor = new TwoFactor($GLOBALS['cfg']['Server']['user']); // save settings - $result = $this->userPreferences->save($cf->getConfigArray()); + $result = $this->userPreferences->save($GLOBALS['cf']->getConfigArray()); // save back the 2FA setting only $twoFactor->save(); if ($result === true) { // reload config $this->config->loadUserPreferences(); - $tabHash = $_POST['tab_hash'] ?? null; - $hash = ltrim($tabHash, '#'); - $this->userPreferences->redirect('index.php?route=/preferences/navigation', null, $hash); + $GLOBALS['tabHash'] = $_POST['tab_hash'] ?? null; + $GLOBALS['hash'] = ltrim($GLOBALS['tabHash'], '#'); + $this->userPreferences->redirect('index.php?route=/preferences/navigation', null, $GLOBALS['hash']); return; } - $error = $result; + $GLOBALS['error'] = $result; } $this->addScriptFiles(['config.js']); @@ -98,13 +96,13 @@ class NavigationController extends AbstractController } $this->render('preferences/forms/main', [ - 'error' => $error ? $error->getDisplay() : '', + 'error' => $GLOBALS['error'] ? $GLOBALS['error']->getDisplay() : '', 'has_errors' => $formDisplay->hasErrors(), 'errors' => $formErrors ?? null, 'form' => $formDisplay->getDisplay( true, Url::getFromRoute('/preferences/navigation'), - ['server' => $server] + ['server' => $GLOBALS['server']] ), ]); diff --git a/libraries/classes/Controllers/Preferences/SqlController.php b/libraries/classes/Controllers/Preferences/SqlController.php index 29de30c7db..858a061a59 100644 --- a/libraries/classes/Controllers/Preferences/SqlController.php +++ b/libraries/classes/Controllers/Preferences/SqlController.php @@ -45,14 +45,12 @@ class SqlController extends AbstractController public function __invoke(): void { - global $cfg, $cf, $error, $tabHash, $hash, $server; - $route = Routing::getCurrentRoute(); - $cf = new ConfigFile($this->config->baseSettings); - $this->userPreferences->pageInit($cf); + $GLOBALS['cf'] = new ConfigFile($this->config->baseSettings); + $this->userPreferences->pageInit($GLOBALS['cf']); - $formDisplay = new SqlForm($cf, 1); + $formDisplay = new SqlForm($GLOBALS['cf'], 1); if (isset($_POST['revert'])) { // revert erroneous fields to their default values @@ -62,25 +60,25 @@ class SqlController extends AbstractController return; } - $error = null; + $GLOBALS['error'] = null; if ($formDisplay->process(false) && ! $formDisplay->hasErrors()) { // Load 2FA settings - $twoFactor = new TwoFactor($cfg['Server']['user']); + $twoFactor = new TwoFactor($GLOBALS['cfg']['Server']['user']); // save settings - $result = $this->userPreferences->save($cf->getConfigArray()); + $result = $this->userPreferences->save($GLOBALS['cf']->getConfigArray()); // save back the 2FA setting only $twoFactor->save(); if ($result === true) { // reload config $this->config->loadUserPreferences(); - $tabHash = $_POST['tab_hash'] ?? null; - $hash = ltrim($tabHash, '#'); - $this->userPreferences->redirect('index.php?route=/preferences/sql', null, $hash); + $GLOBALS['tabHash'] = $_POST['tab_hash'] ?? null; + $GLOBALS['hash'] = ltrim($GLOBALS['tabHash'], '#'); + $this->userPreferences->redirect('index.php?route=/preferences/sql', null, $GLOBALS['hash']); return; } - $error = $result; + $GLOBALS['error'] = $result; } $this->addScriptFiles(['config.js']); @@ -98,13 +96,13 @@ class SqlController extends AbstractController } $this->render('preferences/forms/main', [ - 'error' => $error ? $error->getDisplay() : '', + 'error' => $GLOBALS['error'] ? $GLOBALS['error']->getDisplay() : '', 'has_errors' => $formDisplay->hasErrors(), 'errors' => $formErrors ?? null, 'form' => $formDisplay->getDisplay( true, Url::getFromRoute('/preferences/sql'), - ['server' => $server] + ['server' => $GLOBALS['server']] ), ]); diff --git a/libraries/classes/Controllers/Preferences/TwoFactorController.php b/libraries/classes/Controllers/Preferences/TwoFactorController.php index 47d888bc8e..314e423dfe 100644 --- a/libraries/classes/Controllers/Preferences/TwoFactorController.php +++ b/libraries/classes/Controllers/Preferences/TwoFactorController.php @@ -28,8 +28,6 @@ class TwoFactorController extends AbstractController public function __invoke(): void { - global $cfg; - $route = Routing::getCurrentRoute(); $relationParameters = $this->relation->getRelationParameters(); @@ -40,7 +38,7 @@ class TwoFactorController extends AbstractController 'has_config_storage' => $relationParameters->userPreferencesFeature !== null, ]); - $twoFactor = new TwoFactor($cfg['Server']['user']); + $twoFactor = new TwoFactor($GLOBALS['cfg']['Server']['user']); if (isset($_POST['2fa_remove'])) { if (! $twoFactor->check(true)) { diff --git a/libraries/classes/Controllers/Server/BinlogController.php b/libraries/classes/Controllers/Server/BinlogController.php index ae29440a3f..b8346a6809 100644 --- a/libraries/classes/Controllers/Server/BinlogController.php +++ b/libraries/classes/Controllers/Server/BinlogController.php @@ -43,14 +43,12 @@ class BinlogController extends AbstractController public function __invoke(): void { - global $cfg, $errorUrl; - $params = [ 'log' => $_POST['log'] ?? null, 'pos' => $_POST['pos'] ?? null, 'is_full_query' => $_POST['is_full_query'] ?? null, ]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); @@ -69,7 +67,7 @@ class BinlogController extends AbstractController $urlParams['is_full_query'] = 1; } - $sqlQuery = $this->getSqlQuery($params['log'] ?? '', $position, (int) $cfg['MaxRows']); + $sqlQuery = $this->getSqlQuery($params['log'] ?? '', $position, (int) $GLOBALS['cfg']['MaxRows']); $result = $this->dbi->query($sqlQuery); $numRows = $result->numRows(); @@ -79,8 +77,8 @@ class BinlogController extends AbstractController $nextParams = $urlParams; if ($position > 0) { $fullQueriesParams['pos'] = $position; - if ($position > $cfg['MaxRows']) { - $previousParams['pos'] = $position - $cfg['MaxRows']; + if ($position > $GLOBALS['cfg']['MaxRows']) { + $previousParams['pos'] = $position - $GLOBALS['cfg']['MaxRows']; } } @@ -89,8 +87,8 @@ class BinlogController extends AbstractController unset($fullQueriesParams['is_full_query']); } - if ($numRows >= $cfg['MaxRows']) { - $nextParams['pos'] = $position + $cfg['MaxRows']; + if ($numRows >= $GLOBALS['cfg']['MaxRows']) { + $nextParams['pos'] = $position + $GLOBALS['cfg']['MaxRows']; } $values = $result->fetchAllAssoc(); @@ -102,7 +100,7 @@ class BinlogController extends AbstractController 'sql_message' => Generator::getMessage(Message::success(), $sqlQuery), 'values' => $values, 'has_previous' => $position > 0, - 'has_next' => $numRows >= $cfg['MaxRows'], + 'has_next' => $numRows >= $GLOBALS['cfg']['MaxRows'], 'previous_params' => $previousParams, 'full_queries_params' => $fullQueriesParams, 'next_params' => $nextParams, diff --git a/libraries/classes/Controllers/Server/CollationsController.php b/libraries/classes/Controllers/Server/CollationsController.php index 6e99068324..c1b1af4c84 100644 --- a/libraries/classes/Controllers/Server/CollationsController.php +++ b/libraries/classes/Controllers/Server/CollationsController.php @@ -38,20 +38,16 @@ class CollationsController extends AbstractController ?array $charsets = null, ?array $collations = null ) { - global $cfg; - parent::__construct($response, $template); $this->dbi = $dbi; - $this->charsets = $charsets ?? Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']); - $this->collations = $collations ?? Charsets::getCollations($this->dbi, $cfg['Server']['DisableIS']); + $this->charsets = $charsets ?? Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); + $this->collations = $collations ?? Charsets::getCollations($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); } public function __invoke(): void { - global $errorUrl; - - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Databases/CreateController.php b/libraries/classes/Controllers/Server/Databases/CreateController.php index c130e9b00e..90b54163c3 100644 --- a/libraries/classes/Controllers/Server/Databases/CreateController.php +++ b/libraries/classes/Controllers/Server/Databases/CreateController.php @@ -34,8 +34,6 @@ final class CreateController extends AbstractController public function __invoke(): void { - global $cfg, $db; - $params = [ 'new_db' => $_POST['new_db'] ?? null, 'db_collation' => $_POST['db_collation'] ?? null, @@ -58,8 +56,8 @@ final class CreateController extends AbstractController $sqlQuery = 'CREATE DATABASE ' . Util::backquote($params['new_db']); if (! empty($params['db_collation'])) { [$databaseCharset] = explode('_', $params['db_collation']); - $charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']); - $collations = Charsets::getCollations($this->dbi, $cfg['Server']['DisableIS']); + $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); + $collations = Charsets::getCollations($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); if ( array_key_exists($databaseCharset, $charsets) && array_key_exists($params['db_collation'], $collations[$databaseCharset]) @@ -75,19 +73,19 @@ final class CreateController extends AbstractController if (! $result) { // avoid displaying the not-created db name in header or navi panel - $db = ''; + $GLOBALS['db'] = ''; $message = Message::rawError($this->dbi->getError()); $json = ['message' => $message]; $this->response->setRequestStatus(false); } else { - $db = $params['new_db']; + $GLOBALS['db'] = $params['new_db']; $message = Message::success(__('Database %1$s has been created.')); $message->addParam($params['new_db']); - $scriptName = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); + $scriptName = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); $json = [ 'message' => $message, diff --git a/libraries/classes/Controllers/Server/Databases/DestroyController.php b/libraries/classes/Controllers/Server/Databases/DestroyController.php index 915f560031..5e2dfbbb08 100644 --- a/libraries/classes/Controllers/Server/Databases/DestroyController.php +++ b/libraries/classes/Controllers/Server/Databases/DestroyController.php @@ -45,13 +45,11 @@ final class DestroyController extends AbstractController public function __invoke(): void { - global $selected, $errorUrl, $cfg, $dblist, $reload; - $selected_dbs = $_POST['selected_dbs'] ?? null; if ( ! $this->response->isAjax() - || (! $this->dbi->isSuperUser() && ! $cfg['AllowUserDropDatabase']) + || (! $this->dbi->isSuperUser() && ! $GLOBALS['cfg']['AllowUserDropDatabase']) ) { $message = Message::error(); $json = ['message' => $message]; @@ -73,20 +71,20 @@ final class DestroyController extends AbstractController return; } - $errorUrl = Url::getFromRoute('/server/databases'); - $selected = $selected_dbs; + $GLOBALS['errorUrl'] = Url::getFromRoute('/server/databases'); + $GLOBALS['selected'] = $selected_dbs; $numberOfDatabases = count($selected_dbs); foreach ($selected_dbs as $database) { $this->relationCleanup->database($database); $aQuery = 'DROP DATABASE ' . Util::backquote($database); - $reload = true; + $GLOBALS['reload'] = true; $this->dbi->query($aQuery); $this->transformations->clear($database); } - $dblist->databases->build(); + $GLOBALS['dblist']->databases->build(); $message = Message::success( _ngettext( diff --git a/libraries/classes/Controllers/Server/DatabasesController.php b/libraries/classes/Controllers/Server/DatabasesController.php index 96af14b2ed..82ef338c6e 100644 --- a/libraries/classes/Controllers/Server/DatabasesController.php +++ b/libraries/classes/Controllers/Server/DatabasesController.php @@ -76,9 +76,6 @@ class DatabasesController extends AbstractController public function __invoke(): void { - global $cfg, $server, $dblist, $is_create_db_priv; - global $db_to_create, $text_dir, $errorUrl; - $params = [ 'statistics' => $_REQUEST['statistics'] ?? null, 'pos' => $_REQUEST['pos'] ?? null, @@ -87,7 +84,7 @@ class DatabasesController extends AbstractController ]; $this->addScriptFiles(['server/databases.js']); - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); @@ -106,7 +103,7 @@ class DatabasesController extends AbstractController /** * Gets the databases list */ - if ($server > 0) { + if ($GLOBALS['server'] > 0) { $this->databases = $this->dbi->getDatabasesFull( null, $this->hasStatistics, @@ -116,7 +113,7 @@ class DatabasesController extends AbstractController $this->position, true ); - $this->databaseCount = count($dblist->databases); + $this->databaseCount = count($GLOBALS['dblist']->databases); } $urlParams = [ @@ -129,9 +126,9 @@ class DatabasesController extends AbstractController $databases = $this->getDatabases($primaryInfo, $replicaInfo); $charsetsList = []; - if ($cfg['ShowCreateDb'] && $is_create_db_priv) { - $charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']); - $collations = Charsets::getCollations($this->dbi, $cfg['Server']['DisableIS']); + if ($GLOBALS['cfg']['ShowCreateDb'] && $GLOBALS['is_create_db_priv']) { + $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); + $collations = Charsets::getCollations($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); $serverCollation = $this->dbi->getServerCollation(); foreach ($charsets as $charset) { $collationsList = []; @@ -154,10 +151,10 @@ class DatabasesController extends AbstractController $headerStatistics = $this->getStatisticsColumns(); $this->render('server/databases/index', [ - 'is_create_database_shown' => $cfg['ShowCreateDb'], - 'has_create_database_privileges' => $is_create_db_priv, + 'is_create_database_shown' => $GLOBALS['cfg']['ShowCreateDb'], + 'has_create_database_privileges' => $GLOBALS['is_create_db_priv'], 'has_statistics' => $this->hasStatistics, - 'database_to_create' => $db_to_create, + 'database_to_create' => $GLOBALS['db_to_create'], 'databases' => $databases['databases'], 'total_statistics' => $databases['total_statistics'], 'header_statistics' => $headerStatistics, @@ -165,11 +162,11 @@ class DatabasesController extends AbstractController 'database_count' => $this->databaseCount, 'pos' => $this->position, 'url_params' => $urlParams, - 'max_db_list' => $cfg['MaxDbList'], + 'max_db_list' => $GLOBALS['cfg']['MaxDbList'], 'has_primary_replication' => $primaryInfo['status'], 'has_replica_replication' => $replicaInfo['status'], - 'is_drop_allowed' => $this->dbi->isSuperUser() || $cfg['AllowUserDropDatabase'], - 'text_dir' => $text_dir, + 'is_drop_allowed' => $this->dbi->isSuperUser() || $GLOBALS['cfg']['AllowUserDropDatabase'], + 'text_dir' => $GLOBALS['text_dir'], ]); } @@ -216,8 +213,6 @@ class DatabasesController extends AbstractController */ private function getDatabases($primaryInfo, $replicaInfo): array { - global $cfg; - $databases = []; $totalStatistics = $this->getStatisticsColumns(); foreach ($this->databases as $database) { @@ -260,7 +255,7 @@ class DatabasesController extends AbstractController } } - $url = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); + $url = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); $url .= Url::getCommonRaw( ['db' => $database['SCHEMA_NAME']], ! str_contains($url, '?') ? '?' : '&' @@ -271,12 +266,12 @@ class DatabasesController extends AbstractController 'statistics' => $statistics, 'replication' => $replication, 'is_system_schema' => Utilities::isSystemSchema($database['SCHEMA_NAME'], true), - 'is_pmadb' => $database['SCHEMA_NAME'] === ($cfg['Server']['pmadb'] ?? ''), + 'is_pmadb' => $database['SCHEMA_NAME'] === ($GLOBALS['cfg']['Server']['pmadb'] ?? ''), 'url' => $url, ]; $collation = Charsets::findCollationByName( $this->dbi, - $cfg['Server']['DisableIS'], + $GLOBALS['cfg']['Server']['DisableIS'], $database['DEFAULT_COLLATION_NAME'] ); if ($collation === null) { diff --git a/libraries/classes/Controllers/Server/EnginesController.php b/libraries/classes/Controllers/Server/EnginesController.php index e9c90c34f0..b863195ace 100644 --- a/libraries/classes/Controllers/Server/EnginesController.php +++ b/libraries/classes/Controllers/Server/EnginesController.php @@ -27,9 +27,7 @@ class EnginesController extends AbstractController public function __invoke(): void { - global $errorUrl; - - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/ExportController.php b/libraries/classes/Controllers/Server/ExportController.php index fc46eb0dcd..1978371db3 100644 --- a/libraries/classes/Controllers/Server/ExportController.php +++ b/libraries/classes/Controllers/Server/ExportController.php @@ -34,10 +34,7 @@ final class ExportController extends AbstractController public function __invoke(): void { - global $db, $table, $sql_query, $num_tables, $unlim_num_rows; - global $tmp_select, $select_item, $errorUrl; - - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); @@ -49,19 +46,19 @@ final class ExportController extends AbstractController $this->addScriptFiles(['export.js']); - $select_item = $tmp_select ?? ''; - $databases = $this->export->getDatabasesForSelectOptions($select_item); + $GLOBALS['select_item'] = $GLOBALS['tmp_select'] ?? ''; + $databases = $this->export->getDatabasesForSelectOptions($GLOBALS['select_item']); - if (! isset($sql_query)) { - $sql_query = ''; + if (! isset($GLOBALS['sql_query'])) { + $GLOBALS['sql_query'] = ''; } - if (! isset($num_tables)) { - $num_tables = 0; + if (! isset($GLOBALS['num_tables'])) { + $GLOBALS['num_tables'] = 0; } - if (! isset($unlim_num_rows)) { - $unlim_num_rows = 0; + if (! isset($GLOBALS['unlim_num_rows'])) { + $GLOBALS['unlim_num_rows'] = 0; } $GLOBALS['single_table'] = $_POST['single_table'] ?? $_GET['single_table'] ?? $GLOBALS['single_table'] ?? null; @@ -78,11 +75,11 @@ final class ExportController extends AbstractController $options = $this->export->getOptions( 'server', - $db, - $table, - $sql_query, - $num_tables, - $unlim_num_rows, + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['sql_query'], + $GLOBALS['num_tables'], + $GLOBALS['unlim_num_rows'], $exportList ); diff --git a/libraries/classes/Controllers/Server/ImportController.php b/libraries/classes/Controllers/Server/ImportController.php index 9463d60b00..aef374f124 100644 --- a/libraries/classes/Controllers/Server/ImportController.php +++ b/libraries/classes/Controllers/Server/ImportController.php @@ -36,20 +36,18 @@ final class ImportController extends AbstractController public function __invoke(): void { - global $db, $table, $SESSION_KEY, $cfg, $errorUrl; - $pageSettings = new PageSettings('Import'); $pageSettingsErrorHtml = $pageSettings->getErrorHTML(); $pageSettingsHtml = $pageSettings->getHTML(); $this->addScriptFiles(['import.js']); - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); } - [$SESSION_KEY, $uploadId] = Ajax::uploadProgressSetup(); + [$GLOBALS['SESSION_KEY'], $uploadId] = Ajax::uploadProgressSetup(); $importList = Plugins::getImport('server'); @@ -70,9 +68,9 @@ final class ImportController extends AbstractController $localImportFile = $_REQUEST['local_import_file'] ?? null; $compressions = Import::getCompressions(); - $charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']); + $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); - $idKey = $_SESSION[$SESSION_KEY]['handler']::getIdKey(); + $idKey = $_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getIdKey(); $hiddenInputs = [ $idKey => $uploadId, 'import_type' => 'server', @@ -89,10 +87,10 @@ final class ImportController extends AbstractController 'page_settings_error_html' => $pageSettingsErrorHtml, 'page_settings_html' => $pageSettingsHtml, 'upload_id' => $uploadId, - 'handler' => $_SESSION[$SESSION_KEY]['handler'], + 'handler' => $_SESSION[$GLOBALS['SESSION_KEY']]['handler'], 'hidden_inputs' => $hiddenInputs, - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'max_upload_size' => $maxUploadSize, 'formatted_maximum_upload_size' => Util::getFormattedMaximumUploadSize($maxUploadSize), 'plugins_choice' => $choice, @@ -101,18 +99,18 @@ final class ImportController extends AbstractController 'is_allow_interrupt_checked' => $isAllowInterruptChecked, 'local_import_file' => $localImportFile, 'is_upload' => $GLOBALS['config']->get('enable_upload'), - 'upload_dir' => $cfg['UploadDir'] ?? null, + 'upload_dir' => $GLOBALS['cfg']['UploadDir'] ?? null, 'timeout_passed_global' => $GLOBALS['timeout_passed'] ?? null, 'compressions' => $compressions, 'is_encoding_supported' => Encoding::isSupported(), 'encodings' => Encoding::listEncodings(), - 'import_charset' => $cfg['Import']['charset'] ?? null, + 'import_charset' => $GLOBALS['cfg']['Import']['charset'] ?? null, 'timeout_passed' => $timeoutPassed, 'offset' => $offset, 'can_convert_kanji' => Encoding::canConvertKanji(), 'charsets' => $charsets, 'is_foreign_key_check' => ForeignKey::isCheckEnabled(), - 'user_upload_dir' => Util::userDir((string) ($cfg['UploadDir'] ?? '')), + 'user_upload_dir' => Util::userDir((string) ($GLOBALS['cfg']['UploadDir'] ?? '')), 'local_files' => Import::getLocalFiles($importList), ]); } diff --git a/libraries/classes/Controllers/Server/PluginsController.php b/libraries/classes/Controllers/Server/PluginsController.php index bf8b01b94b..3f39b3e400 100644 --- a/libraries/classes/Controllers/Server/PluginsController.php +++ b/libraries/classes/Controllers/Server/PluginsController.php @@ -40,9 +40,7 @@ class PluginsController extends AbstractController public function __invoke(): void { - global $errorUrl; - - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/PrivilegesController.php b/libraries/classes/Controllers/Server/PrivilegesController.php index aa3ca456bc..3471917f91 100644 --- a/libraries/classes/Controllers/Server/PrivilegesController.php +++ b/libraries/classes/Controllers/Server/PrivilegesController.php @@ -56,12 +56,6 @@ class PrivilegesController extends AbstractController public function __invoke(): void { - global $db, $errorUrl, $message, $text_dir, $post_patterns; - global $username, $hostname, $dbname, $tablename, $routinename, $db_and_table, $dbname_is_wildcard; - global $queries, $password, $ret_message, $ret_queries, $queries_for_display, $sql_query, $_add_user_error; - global $itemType, $tables, $num_tables, $total_num_tables, $sub_part; - global $tooltip_truename, $tooltip_aliasname, $pos, $title, $export, $grants, $one_grant, $url_dbname; - $checkUserPrivileges = new CheckUserPrivileges($this->dbi); $checkUserPrivileges->getPrivileges(); @@ -97,32 +91,32 @@ class PrivilegesController extends AbstractController /** * Sets globals from $_POST patterns, for privileges and max_* vars */ - $post_patterns = [ + $GLOBALS['post_patterns'] = [ '/_priv$/i', '/^max_/i', ]; - Core::setPostAsGlobal($post_patterns); + Core::setPostAsGlobal($GLOBALS['post_patterns']); - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); } - $_add_user_error = false; + $GLOBALS['_add_user_error'] = false; /** * Get DB information: username, hostname, dbname, * tablename, db_and_table, dbname_is_wildcard */ [ - $username, - $hostname, - $dbname, - $tablename, - $routinename, - $db_and_table, - $dbname_is_wildcard, + $GLOBALS['username'], + $GLOBALS['hostname'], + $GLOBALS['dbname'], + $GLOBALS['tablename'], + $GLOBALS['routinename'], + $GLOBALS['db_and_table'], + $GLOBALS['dbname_is_wildcard'], ] = $serverPrivileges->getDataForDBInfo(); /** @@ -155,8 +149,8 @@ class PrivilegesController extends AbstractController * only to update the password */ if ( - isset($_POST['change_copy']) && $username == $_POST['old_username'] - && $hostname == $_POST['old_hostname'] + isset($_POST['change_copy']) && $GLOBALS['username'] == $_POST['old_username'] + && $GLOBALS['hostname'] == $_POST['old_hostname'] ) { $this->response->addHTML( Message::error( @@ -175,71 +169,75 @@ class PrivilegesController extends AbstractController /** * Changes / copies a user, part I */ - [$queries, $password] = $serverPrivileges->getDataForChangeOrCopyUser(); + [$GLOBALS['queries'], $GLOBALS['password']] = $serverPrivileges->getDataForChangeOrCopyUser(); /** * Adds a user * (Changes / copies a user, part II) */ [ - $ret_message, - $ret_queries, - $queries_for_display, - $sql_query, - $_add_user_error, + $GLOBALS['ret_message'], + $GLOBALS['ret_queries'], + $GLOBALS['queries_for_display'], + $GLOBALS['sql_query'], + $GLOBALS['_add_user_error'], ] = $serverPrivileges->addUser( - $dbname ?? null, - $username ?? '', - $hostname ?? '', - $password ?? null, + $GLOBALS['dbname'] ?? null, + $GLOBALS['username'] ?? '', + $GLOBALS['hostname'] ?? '', + $GLOBALS['password'] ?? null, $relationParameters->configurableMenusFeature !== null ); //update the old variables - if (isset($ret_queries)) { - $queries = $ret_queries; - unset($ret_queries); + if (isset($GLOBALS['ret_queries'])) { + $GLOBALS['queries'] = $GLOBALS['ret_queries']; + unset($GLOBALS['ret_queries']); } - if (isset($ret_message)) { - $message = $ret_message; - unset($ret_message); + if (isset($GLOBALS['ret_message'])) { + $GLOBALS['message'] = $GLOBALS['ret_message']; + unset($GLOBALS['ret_message']); } /** * Changes / copies a user, part III */ - if (isset($_POST['change_copy']) && $username !== null && $hostname !== null) { - $queries = $serverPrivileges->getDbSpecificPrivsQueriesForChangeOrCopyUser($queries, $username, $hostname); + if (isset($_POST['change_copy']) && $GLOBALS['username'] !== null && $GLOBALS['hostname'] !== null) { + $GLOBALS['queries'] = $serverPrivileges->getDbSpecificPrivsQueriesForChangeOrCopyUser( + $GLOBALS['queries'], + $GLOBALS['username'], + $GLOBALS['hostname'] + ); } - $itemType = ''; - if (! empty($routinename) && is_string($dbname)) { - $itemType = $serverPrivileges->getRoutineType($dbname, $routinename); + $GLOBALS['itemType'] = ''; + if (! empty($GLOBALS['routinename']) && is_string($GLOBALS['dbname'])) { + $GLOBALS['itemType'] = $serverPrivileges->getRoutineType($GLOBALS['dbname'], $GLOBALS['routinename']); } /** * Updates privileges */ if (! empty($_POST['update_privs'])) { - if (is_array($dbname)) { - foreach ($dbname as $key => $db_name) { - [$sql_query[$key], $message] = $serverPrivileges->updatePrivileges( - ($username ?? ''), - ($hostname ?? ''), - ($tablename ?? ($routinename ?? '')), + if (is_array($GLOBALS['dbname'])) { + foreach ($GLOBALS['dbname'] as $key => $db_name) { + [$GLOBALS['sql_query'][$key], $GLOBALS['message']] = $serverPrivileges->updatePrivileges( + ($GLOBALS['username'] ?? ''), + ($GLOBALS['hostname'] ?? ''), + ($GLOBALS['tablename'] ?? ($GLOBALS['routinename'] ?? '')), ($db_name ?? ''), - $itemType + $GLOBALS['itemType'] ); } - $sql_query = implode("\n", $sql_query); + $GLOBALS['sql_query'] = implode("\n", $GLOBALS['sql_query']); } else { - [$sql_query, $message] = $serverPrivileges->updatePrivileges( - ($username ?? ''), - ($hostname ?? ''), - ($tablename ?? ($routinename ?? '')), - ($dbname ?? ''), - $itemType + [$GLOBALS['sql_query'], $GLOBALS['message']] = $serverPrivileges->updatePrivileges( + ($GLOBALS['username'] ?? ''), + ($GLOBALS['hostname'] ?? ''), + ($GLOBALS['tablename'] ?? ($GLOBALS['routinename'] ?? '')), + ($GLOBALS['dbname'] ?? ''), + $GLOBALS['itemType'] ); } } @@ -251,20 +249,20 @@ class PrivilegesController extends AbstractController ! empty($_POST['changeUserGroup']) && $relationParameters->configurableMenusFeature !== null && $this->dbi->isSuperUser() && $this->dbi->isCreateUser() ) { - $serverPrivileges->setUserGroup($username ?? '', $_POST['userGroup']); - $message = Message::success(); + $serverPrivileges->setUserGroup($GLOBALS['username'] ?? '', $_POST['userGroup']); + $GLOBALS['message'] = Message::success(); } /** * Revokes Privileges */ if (isset($_POST['revokeall'])) { - [$message, $sql_query] = $serverPrivileges->getMessageAndSqlQueryForPrivilegesRevoke( - (is_string($dbname) ? $dbname : ''), - ($tablename ?? ($routinename ?? '')), - $username ?? '', - $hostname ?? '', - $itemType + [$GLOBALS['message'], $GLOBALS['sql_query']] = $serverPrivileges->getMessageAndSqlQueryForPrivilegesRevoke( + (is_string($GLOBALS['dbname']) ? $GLOBALS['dbname'] : ''), + ($GLOBALS['tablename'] ?? ($GLOBALS['routinename'] ?? '')), + $GLOBALS['username'] ?? '', + $GLOBALS['hostname'] ?? '', + $GLOBALS['itemType'] ); } @@ -272,7 +270,11 @@ class PrivilegesController extends AbstractController * Updates the password */ if (isset($_POST['change_pw'])) { - $message = $serverPrivileges->updatePassword($errorUrl, $username ?? '', $hostname ?? ''); + $GLOBALS['message'] = $serverPrivileges->updatePassword( + $GLOBALS['errorUrl'], + $GLOBALS['username'] ?? '', + $GLOBALS['hostname'] ?? '' + ); } /** @@ -280,9 +282,9 @@ class PrivilegesController extends AbstractController * (Changes / copies a user, part IV) */ if (isset($_POST['delete']) || (isset($_POST['change_copy']) && $_POST['mode'] < 4)) { - $queries = $serverPrivileges->getDataForDeleteUsers($queries); + $GLOBALS['queries'] = $serverPrivileges->getDataForDeleteUsers($GLOBALS['queries']); if (empty($_POST['change_copy'])) { - [$sql_query, $message] = $serverPrivileges->deleteUser($queries); + [$GLOBALS['sql_query'], $GLOBALS['message']] = $serverPrivileges->deleteUser($GLOBALS['queries']); } } @@ -290,9 +292,12 @@ class PrivilegesController extends AbstractController * Changes / copies a user, part V */ if (isset($_POST['change_copy'])) { - $queries = $serverPrivileges->getDataForQueries($queries, $queries_for_display); - $message = Message::success(); - $sql_query = implode("\n", $queries); + $GLOBALS['queries'] = $serverPrivileges->getDataForQueries( + $GLOBALS['queries'], + $GLOBALS['queries_for_display'] + ); + $GLOBALS['message'] = Message::success(); + $GLOBALS['sql_query'] = implode("\n", $GLOBALS['queries']); } /** @@ -300,7 +305,7 @@ class PrivilegesController extends AbstractController */ $message_ret = $serverPrivileges->updateMessageForReload(); if ($message_ret !== null) { - $message = $message_ret; + $GLOBALS['message'] = $message_ret; unset($message_ret); } @@ -318,15 +323,15 @@ class PrivilegesController extends AbstractController && ! isset($_GET['showall']) ) { $extra_data = $serverPrivileges->getExtraDataForAjaxBehavior( - ($password ?? ''), - ($sql_query ?? ''), - ($hostname ?? ''), - ($username ?? '') + ($GLOBALS['password'] ?? ''), + ($GLOBALS['sql_query'] ?? ''), + ($GLOBALS['hostname'] ?? ''), + ($GLOBALS['username'] ?? '') ); - if (! empty($message) && $message instanceof Message) { - $this->response->setRequestStatus($message->isSuccess()); - $this->response->addJSON('message', $message); + if (! empty($GLOBALS['message']) && $GLOBALS['message'] instanceof Message) { + $this->response->setRequestStatus($GLOBALS['message']->isSuccess()); + $this->response->addJSON('message', $GLOBALS['message']); $this->response->addJSON($extra_data); return; @@ -337,21 +342,21 @@ class PrivilegesController extends AbstractController * Displays the links */ if (isset($_GET['viewing_mode']) && $_GET['viewing_mode'] === 'db') { - $db = $_REQUEST['db'] = $_GET['checkprivsdb']; + $GLOBALS['db'] = $_REQUEST['db'] = $_GET['checkprivsdb']; // Gets the database structure - $sub_part = '_structure'; + $GLOBALS['sub_part'] = '_structure'; ob_start(); [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part']); $content = ob_get_clean(); $this->response->addHTML($content . "\n"); @@ -362,26 +367,29 @@ class PrivilegesController extends AbstractController // export user definition if (isset($_GET['export']) || (isset($_POST['submit_mult']) && $_POST['submit_mult'] === 'export')) { - [$title, $export] = $serverPrivileges->getListForExportUserDefinition($username ?? '', $hostname ?? ''); + [$GLOBALS['title'], $GLOBALS['export']] = $serverPrivileges->getListForExportUserDefinition( + $GLOBALS['username'] ?? '', + $GLOBALS['hostname'] ?? '' + ); - unset($username, $hostname, $grants, $one_grant); + unset($GLOBALS['username'], $GLOBALS['hostname'], $GLOBALS['grants'], $GLOBALS['one_grant']); if ($this->response->isAjax()) { - $this->response->addJSON('message', $export); - $this->response->addJSON('title', $title); + $this->response->addJSON('message', $GLOBALS['export']); + $this->response->addJSON('title', $GLOBALS['title']); return; } - $this->response->addHTML('

' . $title . '

' . $export); + $this->response->addHTML('

' . $GLOBALS['title'] . '

' . $GLOBALS['export']); } // Show back the form if an error occurred - if (isset($_GET['adduser']) || $_add_user_error === true) { + if (isset($_GET['adduser']) || $GLOBALS['_add_user_error'] === true) { // Add user - $this->response->addHTML( - $serverPrivileges->getHtmlForAddUser(Util::escapeMysqlWildcards(is_string($dbname) ? $dbname : '')) - ); + $this->response->addHTML($serverPrivileges->getHtmlForAddUser( + Util::escapeMysqlWildcards(is_string($GLOBALS['dbname']) ? $GLOBALS['dbname'] : '') + )); } elseif (isset($_GET['checkprivsdb'])) { if (isset($_GET['checkprivstable'])) { $this->response->addHTML($tableController([ @@ -390,8 +398,8 @@ class PrivilegesController extends AbstractController ])); $this->render('export_modal'); } elseif ($this->response->isAjax() === true && empty($_REQUEST['ajax_page_request'])) { - $message = Message::success(__('User has been added.')); - $this->response->addJSON('message', $message); + $GLOBALS['message'] = Message::success(__('User has been added.')); + $this->response->addJSON('message', $GLOBALS['message']); return; } else { @@ -399,8 +407,8 @@ class PrivilegesController extends AbstractController $this->render('export_modal'); } } else { - if (isset($dbname) && ! is_array($dbname)) { - $url_dbname = urlencode( + if (isset($GLOBALS['dbname']) && ! is_array($GLOBALS['dbname'])) { + $GLOBALS['url_dbname'] = urlencode( str_replace( [ '\_', @@ -410,24 +418,24 @@ class PrivilegesController extends AbstractController '_', '%', ], - $dbname + $GLOBALS['dbname'] ) ); } - if (! isset($username)) { + if (! isset($GLOBALS['username'])) { // No username is given --> display the overview $this->response->addHTML( - $serverPrivileges->getHtmlForUserOverview($text_dir) + $serverPrivileges->getHtmlForUserOverview($GLOBALS['text_dir']) ); - } elseif (! empty($routinename)) { + } elseif (! empty($GLOBALS['routinename'])) { $this->response->addHTML( $serverPrivileges->getHtmlForRoutineSpecificPrivileges( - $username, - $hostname ?? '', - is_string($dbname) ? $dbname : '', - $routinename, - Util::escapeMysqlWildcards($url_dbname ?? '') + $GLOBALS['username'], + $GLOBALS['hostname'] ?? '', + is_string($GLOBALS['dbname']) ? $GLOBALS['dbname'] : '', + $GLOBALS['routinename'], + Util::escapeMysqlWildcards($GLOBALS['url_dbname'] ?? '') ) ); } else { @@ -439,12 +447,12 @@ class PrivilegesController extends AbstractController $this->response->addHTML( $serverPrivileges->getHtmlForUserProperties( - $dbname_is_wildcard, - Util::escapeMysqlWildcards($url_dbname ?? ''), - $username, - $hostname ?? '', - $dbname ?? '', - $tablename ?? '' + $GLOBALS['dbname_is_wildcard'], + Util::escapeMysqlWildcards($GLOBALS['url_dbname'] ?? ''), + $GLOBALS['username'], + $GLOBALS['hostname'] ?? '', + $GLOBALS['dbname'] ?? '', + $GLOBALS['tablename'] ?? '' ) ); } diff --git a/libraries/classes/Controllers/Server/ReplicationController.php b/libraries/classes/Controllers/Server/ReplicationController.php index 4f974b7a82..f3566567dc 100644 --- a/libraries/classes/Controllers/Server/ReplicationController.php +++ b/libraries/classes/Controllers/Server/ReplicationController.php @@ -41,15 +41,13 @@ class ReplicationController extends AbstractController public function __invoke(): void { - global $urlParams, $errorUrl; - $params = [ 'url_params' => $_POST['url_params'] ?? null, 'primary_configure' => $_POST['primary_configure'] ?? null, 'replica_configure' => $_POST['replica_configure'] ?? null, 'repl_clear_scr' => $_POST['repl_clear_scr'] ?? null, ]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); @@ -64,7 +62,7 @@ class ReplicationController extends AbstractController $this->addScriptFiles(['server/privileges.js', 'replication.js', 'vendor/zxcvbn-ts.js']); if (isset($params['url_params']) && is_array($params['url_params'])) { - $urlParams = $params['url_params']; + $GLOBALS['urlParams'] = $params['url_params']; } if ($this->dbi->isSuperUser()) { @@ -93,7 +91,7 @@ class ReplicationController extends AbstractController } $this->render('server/replication/index', [ - 'url_params' => $urlParams, + 'url_params' => $GLOBALS['urlParams'], 'is_super_user' => $this->dbi->isSuperUser(), 'error_messages' => $errorMessages, 'is_primary' => $primaryInfo['status'], diff --git a/libraries/classes/Controllers/Server/ShowEngineController.php b/libraries/classes/Controllers/Server/ShowEngineController.php index 7e01099337..3aa5c6d421 100644 --- a/libraries/classes/Controllers/Server/ShowEngineController.php +++ b/libraries/classes/Controllers/Server/ShowEngineController.php @@ -32,9 +32,7 @@ final class ShowEngineController extends AbstractController */ public function __invoke(ServerRequest $request, array $params): void { - global $errorUrl; - - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/SqlController.php b/libraries/classes/Controllers/Server/SqlController.php index 20ca5b1339..24545b4177 100644 --- a/libraries/classes/Controllers/Server/SqlController.php +++ b/libraries/classes/Controllers/Server/SqlController.php @@ -36,8 +36,6 @@ class SqlController extends AbstractController public function __invoke(): void { - global $errorUrl; - $this->addScriptFiles([ 'makegrid.js', 'vendor/jquery/jquery.uitablefilter.js', @@ -48,7 +46,7 @@ class SqlController extends AbstractController $pageSettings = new PageSettings('Sql'); $this->response->addHTML($pageSettings->getErrorHTML()); $this->response->addHTML($pageSettings->getHTML()); - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/Monitor/ChartingDataController.php b/libraries/classes/Controllers/Server/Status/Monitor/ChartingDataController.php index dfdfe7739f..bfe90714ab 100644 --- a/libraries/classes/Controllers/Server/Status/Monitor/ChartingDataController.php +++ b/libraries/classes/Controllers/Server/Status/Monitor/ChartingDataController.php @@ -34,10 +34,8 @@ final class ChartingDataController extends AbstractController public function __invoke(): void { - global $errorUrl; - $params = ['requiredData' => $_POST['requiredData'] ?? null]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/Monitor/GeneralLogController.php b/libraries/classes/Controllers/Server/Status/Monitor/GeneralLogController.php index 1fb20be619..a1a5467001 100644 --- a/libraries/classes/Controllers/Server/Status/Monitor/GeneralLogController.php +++ b/libraries/classes/Controllers/Server/Status/Monitor/GeneralLogController.php @@ -34,15 +34,13 @@ final class GeneralLogController extends AbstractController public function __invoke(): void { - global $errorUrl; - $params = [ 'time_start' => $_POST['time_start'] ?? null, 'time_end' => $_POST['time_end'] ?? null, 'limitTypes' => $_POST['limitTypes'] ?? null, 'removeVariables' => $_POST['removeVariables'] ?? null, ]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/Monitor/LogVarsController.php b/libraries/classes/Controllers/Server/Status/Monitor/LogVarsController.php index 8d628996a3..71d0a3b752 100644 --- a/libraries/classes/Controllers/Server/Status/Monitor/LogVarsController.php +++ b/libraries/classes/Controllers/Server/Status/Monitor/LogVarsController.php @@ -34,13 +34,11 @@ final class LogVarsController extends AbstractController public function __invoke(): void { - global $errorUrl; - $params = [ 'varName' => $_POST['varName'] ?? null, 'varValue' => $_POST['varValue'] ?? null, ]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/Monitor/QueryAnalyzerController.php b/libraries/classes/Controllers/Server/Status/Monitor/QueryAnalyzerController.php index 93ae374ec4..3d3c4c1bc0 100644 --- a/libraries/classes/Controllers/Server/Status/Monitor/QueryAnalyzerController.php +++ b/libraries/classes/Controllers/Server/Status/Monitor/QueryAnalyzerController.php @@ -34,13 +34,11 @@ final class QueryAnalyzerController extends AbstractController public function __invoke(): void { - global $errorUrl; - $params = [ 'database' => $_POST['database'] ?? null, 'query' => $_POST['query'] ?? null, ]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/Monitor/SlowLogController.php b/libraries/classes/Controllers/Server/Status/Monitor/SlowLogController.php index f734c66847..bc591eb337 100644 --- a/libraries/classes/Controllers/Server/Status/Monitor/SlowLogController.php +++ b/libraries/classes/Controllers/Server/Status/Monitor/SlowLogController.php @@ -34,13 +34,11 @@ final class SlowLogController extends AbstractController public function __invoke(): void { - global $errorUrl; - $params = [ 'time_start' => $_POST['time_start'] ?? null, 'time_end' => $_POST['time_end'] ?? null, ]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/MonitorController.php b/libraries/classes/Controllers/Server/Status/MonitorController.php index 74ad8a2c85..a2d4210184 100644 --- a/libraries/classes/Controllers/Server/Status/MonitorController.php +++ b/libraries/classes/Controllers/Server/Status/MonitorController.php @@ -27,9 +27,7 @@ class MonitorController extends AbstractController public function __invoke(): void { - global $errorUrl; - - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/ProcessesController.php b/libraries/classes/Controllers/Server/Status/ProcessesController.php index 5ea1a9a959..d4dc4652e4 100644 --- a/libraries/classes/Controllers/Server/Status/ProcessesController.php +++ b/libraries/classes/Controllers/Server/Status/ProcessesController.php @@ -33,8 +33,6 @@ class ProcessesController extends AbstractController public function __invoke(): void { - global $errorUrl; - $params = [ 'showExecuting' => $_POST['showExecuting'] ?? null, 'full' => $_POST['full'] ?? null, @@ -42,7 +40,7 @@ class ProcessesController extends AbstractController 'order_by_field' => $_POST['order_by_field'] ?? null, 'sort_order' => $_POST['sort_order'] ?? null, ]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/QueriesController.php b/libraries/classes/Controllers/Server/Status/QueriesController.php index f74809735f..d2641abdbe 100644 --- a/libraries/classes/Controllers/Server/Status/QueriesController.php +++ b/libraries/classes/Controllers/Server/Status/QueriesController.php @@ -32,9 +32,7 @@ class QueriesController extends AbstractController public function __invoke(): void { - global $errorUrl; - - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/StatusController.php b/libraries/classes/Controllers/Server/Status/StatusController.php index 8841cabdc7..c62b64df59 100644 --- a/libraries/classes/Controllers/Server/Status/StatusController.php +++ b/libraries/classes/Controllers/Server/Status/StatusController.php @@ -40,9 +40,7 @@ class StatusController extends AbstractController public function __invoke(): void { - global $errorUrl; - - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/Status/VariablesController.php b/libraries/classes/Controllers/Server/Status/VariablesController.php index ba67d62799..290e0ad509 100644 --- a/libraries/classes/Controllers/Server/Status/VariablesController.php +++ b/libraries/classes/Controllers/Server/Status/VariablesController.php @@ -32,8 +32,6 @@ class VariablesController extends AbstractController public function __invoke(): void { - global $errorUrl; - $params = [ 'flush' => $_POST['flush'] ?? null, 'filterAlert' => $_POST['filterAlert'] ?? null, @@ -41,7 +39,7 @@ class VariablesController extends AbstractController 'filterCategory' => $_POST['filterCategory'] ?? null, 'dontFormat' => $_POST['dontFormat'] ?? null, ]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Server/VariablesController.php b/libraries/classes/Controllers/Server/VariablesController.php index 657bcb4fd1..e31fbd90d9 100644 --- a/libraries/classes/Controllers/Server/VariablesController.php +++ b/libraries/classes/Controllers/Server/VariablesController.php @@ -36,10 +36,8 @@ class VariablesController extends AbstractController public function __invoke(): void { - global $errorUrl; - $params = ['filter' => $_GET['filter'] ?? null]; - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); diff --git a/libraries/classes/Controllers/Sql/ColumnPreferencesController.php b/libraries/classes/Controllers/Sql/ColumnPreferencesController.php index bd82f79c0f..ad25978bbb 100644 --- a/libraries/classes/Controllers/Sql/ColumnPreferencesController.php +++ b/libraries/classes/Controllers/Sql/ColumnPreferencesController.php @@ -38,11 +38,9 @@ final class ColumnPreferencesController extends AbstractController public function __invoke(): void { - global $db, $table; - $this->checkUserPrivileges->getPrivileges(); - $tableObject = $this->dbi->getTable($db, $table); + $tableObject = $this->dbi->getTable($GLOBALS['db'], $GLOBALS['table']); $status = false; // set column order diff --git a/libraries/classes/Controllers/Sql/EnumValuesController.php b/libraries/classes/Controllers/Sql/EnumValuesController.php index 843d0ca8be..0a58f0691e 100644 --- a/libraries/classes/Controllers/Sql/EnumValuesController.php +++ b/libraries/classes/Controllers/Sql/EnumValuesController.php @@ -39,13 +39,11 @@ final class EnumValuesController extends AbstractController */ public function __invoke(): void { - global $db, $table; - $this->checkUserPrivileges->getPrivileges(); $column = $_POST['column']; $curr_value = $_POST['curr_value']; - $values = $this->sql->getValuesForColumn($db, $table, $column); + $values = $this->sql->getValuesForColumn($GLOBALS['db'], $GLOBALS['table'], $column); if ($values === null) { $this->response->addJSON('message', __('Error in processing request')); diff --git a/libraries/classes/Controllers/Sql/RelationalValuesController.php b/libraries/classes/Controllers/Sql/RelationalValuesController.php index 884f7590e8..4cccc15ce0 100644 --- a/libraries/classes/Controllers/Sql/RelationalValuesController.php +++ b/libraries/classes/Controllers/Sql/RelationalValuesController.php @@ -36,8 +36,6 @@ final class RelationalValuesController extends AbstractController */ public function __invoke(): void { - global $db, $table; - $this->checkUserPrivileges->getPrivileges(); $column = $_POST['column']; @@ -51,7 +49,12 @@ final class RelationalValuesController extends AbstractController $curr_value = $_POST['curr_value']; } - $dropdown = $this->sql->getHtmlForRelationalColumnDropdown($db, $table, $column, $curr_value); + $dropdown = $this->sql->getHtmlForRelationalColumnDropdown( + $GLOBALS['db'], + $GLOBALS['table'], + $column, + $curr_value + ); $this->response->addJSON('dropdown', $dropdown); } } diff --git a/libraries/classes/Controllers/Sql/SetValuesController.php b/libraries/classes/Controllers/Sql/SetValuesController.php index 89989aa6ba..501c828c10 100644 --- a/libraries/classes/Controllers/Sql/SetValuesController.php +++ b/libraries/classes/Controllers/Sql/SetValuesController.php @@ -39,8 +39,6 @@ final class SetValuesController extends AbstractController */ public function __invoke(): void { - global $db, $table; - $this->checkUserPrivileges->getPrivileges(); $column = $_POST['column']; @@ -48,7 +46,7 @@ final class SetValuesController extends AbstractController $fullValues = $_POST['get_full_values'] ?? false; $whereClause = $_POST['where_clause'] ?? null; - $values = $this->sql->getValuesForColumn($db, $table, $column); + $values = $this->sql->getValuesForColumn($GLOBALS['db'], $GLOBALS['table'], $column); if ($values === null) { $this->response->addJSON('message', __('Error in processing request')); @@ -59,7 +57,12 @@ final class SetValuesController extends AbstractController // If the $currentValue was truncated, we should fetch the correct full values from the table. if ($fullValues && ! empty($whereClause)) { - $currentValue = $this->sql->getFullValuesForSetColumn($db, $table, $column, $whereClause); + $currentValue = $this->sql->getFullValuesForSetColumn( + $GLOBALS['db'], + $GLOBALS['table'], + $column, + $whereClause + ); } // Converts characters of $currentValue to HTML entities. diff --git a/libraries/classes/Controllers/Sql/SqlController.php b/libraries/classes/Controllers/Sql/SqlController.php index 5ee59558f7..9826d86fe7 100644 --- a/libraries/classes/Controllers/Sql/SqlController.php +++ b/libraries/classes/Controllers/Sql/SqlController.php @@ -51,11 +51,6 @@ class SqlController extends AbstractController public function __invoke(): void { - global $cfg, $db, $display_query, $sql_query, $table; - global $ajax_reload, $goto, $errorUrl, $find_real_end, $unlim_num_rows, $import_text, $disp_query; - global $extra_data, $message_to_show, $sql_data, $disp_message, $complete_query; - global $is_gotofile, $back, $table_from_sql; - $this->checkUserPrivileges->getPrivileges(); $pageSettings = new PageSettings('Browse'); @@ -74,59 +69,60 @@ class SqlController extends AbstractController /** * Set ajax_reload in the response if it was already set */ - if (isset($ajax_reload) && $ajax_reload['reload'] === true) { - $this->response->addJSON('ajax_reload', $ajax_reload); + if (isset($GLOBALS['ajax_reload']) && $GLOBALS['ajax_reload']['reload'] === true) { + $this->response->addJSON('ajax_reload', $GLOBALS['ajax_reload']); } /** * Defines the url to return to in case of error in a sql statement */ - $is_gotofile = true; - if (empty($goto)) { - if (empty($table)) { - $goto = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); + $GLOBALS['is_gotofile'] = true; + if (empty($GLOBALS['goto'])) { + if (empty($GLOBALS['table'])) { + $GLOBALS['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); } else { - $goto = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); + $GLOBALS['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); } } - if (! isset($errorUrl)) { - $errorUrl = ! empty($back) ? $back : $goto; - $errorUrl .= Url::getCommon( + if (! isset($GLOBALS['errorUrl'])) { + $GLOBALS['errorUrl'] = ! empty($GLOBALS['back']) ? $GLOBALS['back'] : $GLOBALS['goto']; + $GLOBALS['errorUrl'] .= Url::getCommon( ['db' => $GLOBALS['db']], - ! str_contains($errorUrl, '?') ? '?' : '&' + ! str_contains($GLOBALS['errorUrl'], '?') ? '?' : '&' ); if ( - (mb_strpos(' ' . $errorUrl, 'db_') !== 1 || ! str_contains($errorUrl, '?route=/database/')) - && strlen($table) > 0 + (mb_strpos(' ' . $GLOBALS['errorUrl'], 'db_') !== 1 + || ! str_contains($GLOBALS['errorUrl'], '?route=/database/')) + && strlen($GLOBALS['table']) > 0 ) { - $errorUrl .= '&table=' . urlencode($table); + $GLOBALS['errorUrl'] .= '&table=' . urlencode($GLOBALS['table']); } } // Coming from a bookmark dialog if (isset($_POST['bkm_fields']['bkm_sql_query'])) { - $sql_query = $_POST['bkm_fields']['bkm_sql_query']; + $GLOBALS['sql_query'] = $_POST['bkm_fields']['bkm_sql_query']; } elseif (isset($_POST['sql_query'])) { - $sql_query = $_POST['sql_query']; + $GLOBALS['sql_query'] = $_POST['sql_query']; } elseif (isset($_GET['sql_query'], $_GET['sql_signature'])) { if (Core::checkSqlQuerySignature($_GET['sql_query'], $_GET['sql_signature'])) { - $sql_query = $_GET['sql_query']; + $GLOBALS['sql_query'] = $_GET['sql_query']; } } // This one is just to fill $db if (isset($_POST['bkm_fields']['bkm_database'])) { - $db = $_POST['bkm_fields']['bkm_database']; + $GLOBALS['db'] = $_POST['bkm_fields']['bkm_database']; } // Default to browse if no query set and we have table // (needed for browsing from DefaultTabTable) - if (empty($sql_query) && strlen($table) > 0 && strlen($db) > 0) { - $sql_query = $this->sql->getDefaultSqlQueryForBrowse($db, $table); + if (empty($GLOBALS['sql_query']) && strlen($GLOBALS['table']) > 0 && strlen($GLOBALS['db']) > 0) { + $GLOBALS['sql_query'] = $this->sql->getDefaultSqlQueryForBrowse($GLOBALS['db'], $GLOBALS['table']); // set $goto to what will be displayed if query returns 0 rows - $goto = ''; + $GLOBALS['goto'] = ''; } else { // Now we can check the parameters Util::checkParameters(['sql_query']); @@ -137,12 +133,12 @@ class SqlController extends AbstractController */ [ $analyzed_sql_results, - $db, - $table_from_sql, - ] = ParseAnalyze::sqlQuery($sql_query, $db); + $GLOBALS['db'], + $GLOBALS['table_from_sql'], + ] = ParseAnalyze::sqlQuery($GLOBALS['sql_query'], $GLOBALS['db']); - if ($table != $table_from_sql && ! empty($table_from_sql)) { - $table = $table_from_sql; + if ($GLOBALS['table'] != $GLOBALS['table_from_sql'] && ! empty($GLOBALS['table_from_sql'])) { + $GLOBALS['table'] = $GLOBALS['table_from_sql']; } /** @@ -155,7 +151,7 @@ class SqlController extends AbstractController if ( $this->sql->hasNoRightsToDropDatabase( $analyzed_sql_results, - $cfg['AllowUserDropDatabase'], + $GLOBALS['cfg']['AllowUserDropDatabase'], $this->dbi->isSuperUser() ) ) { @@ -163,22 +159,22 @@ class SqlController extends AbstractController __('"DROP DATABASE" statements are disabled.'), '', false, - $errorUrl + $GLOBALS['errorUrl'] ); } /** * Need to find the real end of rows? */ - if (isset($find_real_end) && $find_real_end) { - $unlim_num_rows = $this->sql->findRealEndOfRows($db, $table); + if (isset($GLOBALS['find_real_end']) && $GLOBALS['find_real_end']) { + $GLOBALS['unlim_num_rows'] = $this->sql->findRealEndOfRows($GLOBALS['db'], $GLOBALS['table']); } /** * Bookmark add */ if (isset($_POST['store_bkm'])) { - $this->addBookmark($goto); + $this->addBookmark($GLOBALS['goto']); return; } @@ -186,30 +182,30 @@ class SqlController extends AbstractController /** * Sets or modifies the $goto variable if required */ - if ($goto === Url::getFromRoute('/sql')) { - $is_gotofile = false; - $goto = Url::getFromRoute('/sql', [ - 'db' => $db, - 'table' => $table, - 'sql_query' => $sql_query, + if ($GLOBALS['goto'] === Url::getFromRoute('/sql')) { + $GLOBALS['is_gotofile'] = false; + $GLOBALS['goto'] = Url::getFromRoute('/sql', [ + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], + 'sql_query' => $GLOBALS['sql_query'], ]); } $this->response->addHTML($this->sql->executeQueryAndSendQueryResponse( $analyzed_sql_results, - $is_gotofile, - $db, - $table, - $find_real_end ?? null, - $import_text ?? null, - $extra_data ?? null, - $message_to_show ?? null, - $sql_data ?? null, - $goto, - isset($disp_query) ? $display_query : null, - $disp_message ?? null, - $sql_query, - $complete_query ?? null + $GLOBALS['is_gotofile'], + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['find_real_end'] ?? null, + $GLOBALS['import_text'] ?? null, + $GLOBALS['extra_data'] ?? null, + $GLOBALS['message_to_show'] ?? null, + $GLOBALS['sql_data'] ?? null, + $GLOBALS['goto'], + isset($GLOBALS['disp_query']) ? $GLOBALS['display_query'] : null, + $GLOBALS['disp_message'] ?? null, + $GLOBALS['sql_query'], + $GLOBALS['complete_query'] ?? null )); } diff --git a/libraries/classes/Controllers/Table/AddFieldController.php b/libraries/classes/Controllers/Table/AddFieldController.php index 756432b8b5..1cd41d31ca 100644 --- a/libraries/classes/Controllers/Table/AddFieldController.php +++ b/libraries/classes/Controllers/Table/AddFieldController.php @@ -59,9 +59,6 @@ class AddFieldController extends AbstractController public function __invoke(): void { - global $errorUrl, $message, $active_page, $sql_query; - global $num_fields, $regenerate, $result, $db, $table; - $this->addScriptFiles(['table/structure.js']); // Check parameters @@ -72,9 +69,9 @@ class AddFieldController extends AbstractController /** * Defines the url to return to in case of error in a sql statement */ - $errorUrl = Url::getFromRoute('/table/sql', [ - 'db' => $db, - 'table' => $table, + $GLOBALS['errorUrl'] = Url::getFromRoute('/table/sql', [ + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], ]); // check number of fields to be created @@ -87,15 +84,15 @@ class AddFieldController extends AbstractController $_POST['field_where'] = $_POST['orig_field_where']; } - $num_fields = min( + $GLOBALS['num_fields'] = min( intval($_POST['orig_num_fields']) + intval($_POST['added_fields']), 4096 ); - $regenerate = true; + $GLOBALS['regenerate'] = true; } elseif (isset($_POST['num_fields']) && intval($_POST['num_fields']) > 0) { - $num_fields = min(4096, intval($_POST['num_fields'])); + $GLOBALS['num_fields'] = min(4096, intval($_POST['num_fields'])); } else { - $num_fields = 1; + $GLOBALS['num_fields'] = 1; } if (isset($_POST['do_save_data'])) { @@ -105,19 +102,23 @@ class AddFieldController extends AbstractController $createAddField = new CreateAddField($this->dbi); - $sql_query = $createAddField->getColumnCreationQuery($table); + $GLOBALS['sql_query'] = $createAddField->getColumnCreationQuery($GLOBALS['table']); // If there is a request for SQL previewing. if (isset($_POST['preview_sql'])) { - Core::previewSQL($sql_query); + Core::previewSQL($GLOBALS['sql_query']); return; } - $result = $createAddField->tryColumnCreationQuery($db, $sql_query, $errorUrl); + $GLOBALS['result'] = $createAddField->tryColumnCreationQuery( + $GLOBALS['db'], + $GLOBALS['sql_query'], + $GLOBALS['errorUrl'] + ); - if ($result !== true) { - $error_message_html = Generator::mysqlDie('', '', false, $errorUrl, false); + if ($GLOBALS['result'] !== true) { + $error_message_html = Generator::mysqlDie('', '', false, $GLOBALS['errorUrl'], false); $this->response->addHTML($error_message_html ?? ''); $this->response->setRequestStatus(false); @@ -132,8 +133,8 @@ class AddFieldController extends AbstractController } $this->transformations->setMime( - $db, - $table, + $GLOBALS['db'], + $GLOBALS['table'], $_POST['field_name'][$fieldindex], $mimetype, $_POST['field_transformation'][$fieldindex], @@ -145,21 +146,21 @@ class AddFieldController extends AbstractController } // Go back to the structure sub-page - $message = Message::success( + $GLOBALS['message'] = Message::success( __('Table %1$s has been altered successfully.') ); - $message->addParam($table); + $GLOBALS['message']->addParam($GLOBALS['table']); $this->response->addJSON( 'message', - Generator::getMessage($message, $sql_query, 'success') + Generator::getMessage($GLOBALS['message'], $GLOBALS['sql_query'], 'success') ); // Give an URL to call and use to appends the structure after the success message $this->response->addJSON( 'structure_refresh_route', Url::getFromRoute('/table/structure', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'ajax_request' => '1', ]) ); @@ -167,17 +168,21 @@ class AddFieldController extends AbstractController return; } - $url_params = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($url_params, '&'); + $url_params = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($url_params, '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); - $active_page = Url::getFromRoute('/table/structure'); + $GLOBALS['active_page'] = Url::getFromRoute('/table/structure'); $this->addScriptFiles(['vendor/jquery/jquery.uitablefilter.js', 'indexes.js']); - $templateData = $this->columnsDefinition->displayForm('/table/add-field', $num_fields, $regenerate); + $templateData = $this->columnsDefinition->displayForm( + '/table/add-field', + $GLOBALS['num_fields'], + $GLOBALS['regenerate'] + ); $this->render('columns_definitions/column_definitions_form', $templateData); } diff --git a/libraries/classes/Controllers/Table/ChangeController.php b/libraries/classes/Controllers/Table/ChangeController.php index 5297ac632a..aced16a740 100644 --- a/libraries/classes/Controllers/Table/ChangeController.php +++ b/libraries/classes/Controllers/Table/ChangeController.php @@ -46,35 +46,32 @@ class ChangeController extends AbstractController public function __invoke(): void { - global $cfg, $db, $table, $text_dir, $disp_message, $urlParams; - global $errorUrl, $where_clause, $unsaved_values, $insert_mode, $where_clause_array, $where_clauses; - global $result, $rows, $found_unique_key, $after_insert, $comments_map, $table_columns; - global $chg_evt_handler, $timestamp_seen, $columns_cnt, $tabindex; - global $tabindex_for_value, $o_rows, $biggest_max_file_size, $has_blob_field; - global $jsvkey, $vkey, $current_result, $repopulate, $checked; - $pageSettings = new PageSettings('Edit'); $this->response->addHTML($pageSettings->getErrorHTML()); $this->response->addHTML($pageSettings->getHTML()); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); /** * Determine whether Insert or Edit and set global variables */ [ - $insert_mode, - $where_clause, - $where_clause_array, - $where_clauses, - $result, - $rows, - $found_unique_key, - $after_insert, - ] = $this->insertEdit->determineInsertOrEdit($where_clause ?? null, $db, $table); + $GLOBALS['insert_mode'], + $GLOBALS['where_clause'], + $GLOBALS['where_clause_array'], + $GLOBALS['where_clauses'], + $GLOBALS['result'], + $GLOBALS['rows'], + $GLOBALS['found_unique_key'], + $GLOBALS['after_insert'], + ] = $this->insertEdit->determineInsertOrEdit( + $GLOBALS['where_clause'] ?? null, + $GLOBALS['db'], + $GLOBALS['table'] + ); // Increase number of rows if unsaved rows are more - if (! empty($unsaved_values) && count($rows) < count($unsaved_values)) { - $rows = array_fill(0, count($unsaved_values), false); + if (! empty($GLOBALS['unsaved_values']) && count($GLOBALS['rows']) < count($GLOBALS['unsaved_values'])) { + $GLOBALS['rows'] = array_fill(0, count($GLOBALS['unsaved_values']), false); } /** @@ -82,7 +79,7 @@ class ChangeController extends AbstractController * (at this point, $GLOBALS['goto'] will be set but could be empty) */ if (empty($GLOBALS['goto'])) { - if (strlen($table) > 0) { + if (strlen($GLOBALS['table']) > 0) { // avoid a problem (see bug #2202709) $GLOBALS['goto'] = Url::getFromRoute('/table/sql'); } else { @@ -90,22 +87,22 @@ class ChangeController extends AbstractController } } - $urlParams = [ - 'db' => $db, + $GLOBALS['urlParams'] = [ + 'db' => $GLOBALS['db'], 'sql_query' => $_POST['sql_query'] ?? '', ]; if (strpos($GLOBALS['goto'] ?? '', 'index.php?route=/table') === 0) { - $urlParams['table'] = $table; + $GLOBALS['urlParams']['table'] = $GLOBALS['table']; } - $errorUrl = $GLOBALS['goto'] . Url::getCommon( - $urlParams, + $GLOBALS['errorUrl'] = $GLOBALS['goto'] . Url::getCommon( + $GLOBALS['urlParams'], ! str_contains($GLOBALS['goto'], '?') ? '?' : '&' ); - unset($urlParams); + unset($GLOBALS['urlParams']); - $comments_map = $this->insertEdit->getCommentsMap($db, $table); + $GLOBALS['comments_map'] = $this->insertEdit->getCommentsMap($GLOBALS['db'], $GLOBALS['table']); /** * START REGULAR OUTPUT @@ -125,22 +122,22 @@ class ChangeController extends AbstractController * * $disp_message come from /table/replace */ - if (! empty($disp_message)) { - $this->response->addHTML(Generator::getMessage($disp_message, null)); + if (! empty($GLOBALS['disp_message'])) { + $this->response->addHTML(Generator::getMessage($GLOBALS['disp_message'], null)); } - $table_columns = $this->insertEdit->getTableColumns($db, $table); + $GLOBALS['table_columns'] = $this->insertEdit->getTableColumns($GLOBALS['db'], $GLOBALS['table']); // retrieve keys into foreign fields, if any - $foreigners = $this->relation->getForeigners($db, $table); + $foreigners = $this->relation->getForeigners($GLOBALS['db'], $GLOBALS['table']); // Retrieve form parameters for insert/edit form $_form_params = $this->insertEdit->getFormParametersForInsertForm( - $db, - $table, - $where_clauses, - $where_clause_array, - $errorUrl + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['where_clauses'], + $GLOBALS['where_clause_array'], + $GLOBALS['errorUrl'] ); /** @@ -148,28 +145,31 @@ class ChangeController extends AbstractController */ // autocomplete feature of IE kills the "onchange" event handler and it // must be replaced by the "onpropertychange" one in this case - $chg_evt_handler = 'onchange'; + $GLOBALS['chg_evt_handler'] = 'onchange'; // Had to put the URI because when hosted on an https server, // some browsers send wrongly this form to the http server. $html_output = ''; // Set if we passed the first timestamp field - $timestamp_seen = false; - $columns_cnt = count($table_columns); + $GLOBALS['timestamp_seen'] = false; + $GLOBALS['columns_cnt'] = count($GLOBALS['table_columns']); - $tabindex = 0; - $tabindex_for_value = 0; - $o_rows = 0; - $biggest_max_file_size = 0; + $GLOBALS['tabindex'] = 0; + $GLOBALS['tabindex_for_value'] = 0; + $GLOBALS['o_rows'] = 0; + $GLOBALS['biggest_max_file_size'] = 0; - $urlParams['db'] = $db; - $urlParams['table'] = $table; - $urlParams = $this->insertEdit->urlParamsInEditMode($urlParams, $where_clause_array); + $GLOBALS['urlParams']['db'] = $GLOBALS['db']; + $GLOBALS['urlParams']['table'] = $GLOBALS['table']; + $GLOBALS['urlParams'] = $this->insertEdit->urlParamsInEditMode( + $GLOBALS['urlParams'], + $GLOBALS['where_clause_array'] + ); - $has_blob_field = false; - foreach ($table_columns as $column) { + $GLOBALS['has_blob_field'] = false; + foreach ($GLOBALS['table_columns'] as $column) { if ($this->insertEdit->isColumn($column, ['blob', 'tinyblob', 'mediumblob', 'longblob'])) { - $has_blob_field = true; + $GLOBALS['has_blob_field'] = true; break; } } @@ -177,92 +177,94 @@ class ChangeController extends AbstractController //Insert/Edit form //If table has blob fields we have to disable ajax. $isUpload = $GLOBALS['config']->get('enable_upload'); - $html_output .= $this->insertEdit->getHtmlForInsertEditFormHeader($has_blob_field, $isUpload); + $html_output .= $this->insertEdit->getHtmlForInsertEditFormHeader($GLOBALS['has_blob_field'], $isUpload); $html_output .= Url::getHiddenInputs($_form_params); // user can toggle the display of Function column and column types // (currently does not work for multi-edits) - if (! $cfg['ShowFunctionFields'] || ! $cfg['ShowFieldTypesInDataEditView']) { + if (! $GLOBALS['cfg']['ShowFunctionFields'] || ! $GLOBALS['cfg']['ShowFieldTypesInDataEditView']) { $html_output .= __('Show'); } - if (! $cfg['ShowFunctionFields']) { - $html_output .= $this->insertEdit->showTypeOrFunction('function', $urlParams, false); + if (! $GLOBALS['cfg']['ShowFunctionFields']) { + $html_output .= $this->insertEdit->showTypeOrFunction('function', $GLOBALS['urlParams'], false); } - if (! $cfg['ShowFieldTypesInDataEditView']) { - $html_output .= $this->insertEdit->showTypeOrFunction('type', $urlParams, false); + if (! $GLOBALS['cfg']['ShowFieldTypesInDataEditView']) { + $html_output .= $this->insertEdit->showTypeOrFunction('type', $GLOBALS['urlParams'], false); } $GLOBALS['plugin_scripts'] = []; - foreach ($rows as $row_id => $current_row) { + foreach ($GLOBALS['rows'] as $row_id => $current_row) { if (empty($current_row)) { $current_row = []; } - $jsvkey = $row_id; - $vkey = '[multi_edit][' . $jsvkey . ']'; + $GLOBALS['jsvkey'] = $row_id; + $GLOBALS['vkey'] = '[multi_edit][' . $GLOBALS['jsvkey'] . ']'; - $current_result = (isset($result) && is_array($result) && isset($result[$row_id]) - ? $result[$row_id] - : $result); - $repopulate = []; - $checked = true; - if (isset($unsaved_values[$row_id])) { - $repopulate = $unsaved_values[$row_id]; - $checked = false; + $GLOBALS['current_result'] = (isset($GLOBALS['result']) + && is_array($GLOBALS['result']) && isset($GLOBALS['result'][$row_id]) + ? $GLOBALS['result'][$row_id] + : $GLOBALS['result']); + $GLOBALS['repopulate'] = []; + $GLOBALS['checked'] = true; + if (isset($GLOBALS['unsaved_values'][$row_id])) { + $GLOBALS['repopulate'] = $GLOBALS['unsaved_values'][$row_id]; + $GLOBALS['checked'] = false; } - if ($insert_mode && $row_id > 0) { - $html_output .= $this->insertEdit->getHtmlForIgnoreOption($row_id, $checked); + if ($GLOBALS['insert_mode'] && $row_id > 0) { + $html_output .= $this->insertEdit->getHtmlForIgnoreOption($row_id, $GLOBALS['checked']); } $html_output .= $this->insertEdit->getHtmlForInsertEditRow( - $urlParams, - $table_columns, - $comments_map, - $timestamp_seen, - $current_result, - $chg_evt_handler, - $jsvkey, - $vkey, - $insert_mode, + $GLOBALS['urlParams'], + $GLOBALS['table_columns'], + $GLOBALS['comments_map'], + $GLOBALS['timestamp_seen'], + $GLOBALS['current_result'], + $GLOBALS['chg_evt_handler'], + $GLOBALS['jsvkey'], + $GLOBALS['vkey'], + $GLOBALS['insert_mode'], $current_row, - $o_rows, - $tabindex, - $columns_cnt, + $GLOBALS['o_rows'], + $GLOBALS['tabindex'], + $GLOBALS['columns_cnt'], $isUpload, $foreigners, - $tabindex_for_value, - $table, - $db, + $GLOBALS['tabindex_for_value'], + $GLOBALS['table'], + $GLOBALS['db'], $row_id, - $biggest_max_file_size, - $text_dir, - $repopulate, - $where_clause_array + $GLOBALS['biggest_max_file_size'], + $GLOBALS['text_dir'], + $GLOBALS['repopulate'], + $GLOBALS['where_clause_array'] ); } $this->addScriptFiles($GLOBALS['plugin_scripts']); - unset($unsaved_values, $checked, $repopulate, $GLOBALS['plugin_scripts']); + unset($GLOBALS['unsaved_values'], $GLOBALS['checked'], $GLOBALS['repopulate'], $GLOBALS['plugin_scripts']); - if (! isset($after_insert)) { - $after_insert = 'back'; + if (! isset($GLOBALS['after_insert'])) { + $GLOBALS['after_insert'] = 'back'; } - $isNumeric = InsertEdit::isWhereClauseNumeric($where_clause); + $isNumeric = InsertEdit::isWhereClauseNumeric($GLOBALS['where_clause']); $html_output .= $this->template->render('table/insert/actions_panel', [ - 'where_clause' => $where_clause, - 'after_insert' => $after_insert, - 'found_unique_key' => $found_unique_key, + 'where_clause' => $GLOBALS['where_clause'], + 'after_insert' => $GLOBALS['after_insert'], + 'found_unique_key' => $GLOBALS['found_unique_key'], 'is_numeric' => $isNumeric, ]); - if ($biggest_max_file_size > 0) { - $html_output .= '' . "\n"; + if ($GLOBALS['biggest_max_file_size'] > 0) { + $html_output .= '' . "\n"; } $html_output .= ''; @@ -270,9 +272,14 @@ class ChangeController extends AbstractController $html_output .= $this->insertEdit->getHtmlForGisEditor(); // end Insert/Edit form - if ($insert_mode) { + if ($GLOBALS['insert_mode']) { //Continue insertion form - $html_output .= $this->insertEdit->getContinueInsertionForm($table, $db, $where_clause_array, $errorUrl); + $html_output .= $this->insertEdit->getContinueInsertionForm( + $GLOBALS['table'], + $GLOBALS['db'], + $GLOBALS['where_clause_array'], + $GLOBALS['errorUrl'] + ); } $this->response->addHTML($html_output); diff --git a/libraries/classes/Controllers/Table/ChangeRowsController.php b/libraries/classes/Controllers/Table/ChangeRowsController.php index 66edc220f2..67c1f5cd06 100644 --- a/libraries/classes/Controllers/Table/ChangeRowsController.php +++ b/libraries/classes/Controllers/Table/ChangeRowsController.php @@ -28,8 +28,6 @@ final class ChangeRowsController extends AbstractController public function __invoke(): void { - global $active_page, $where_clause; - if (isset($_POST['goto']) && (! isset($_POST['rows_to_delete']) || ! is_array($_POST['rows_to_delete']))) { $this->response->setRequestStatus(false); $this->response->addJSON('message', __('No row selected.')); @@ -41,14 +39,14 @@ final class ChangeRowsController extends AbstractController // 'rows_to_delete' checkbox, we use the index of it as the // indicating WHERE clause. Then we build the array which is used // for the /table/change script. - $where_clause = []; + $GLOBALS['where_clause'] = []; if (isset($_POST['rows_to_delete']) && is_array($_POST['rows_to_delete'])) { foreach ($_POST['rows_to_delete'] as $i_where_clause) { - $where_clause[] = $i_where_clause; + $GLOBALS['where_clause'][] = $i_where_clause; } } - $active_page = Url::getFromRoute('/table/change'); + $GLOBALS['active_page'] = Url::getFromRoute('/table/change'); ($this->changeController)(); } diff --git a/libraries/classes/Controllers/Table/ChartController.php b/libraries/classes/Controllers/Table/ChartController.php index 39871ebc4f..90a73e447e 100644 --- a/libraries/classes/Controllers/Table/ChartController.php +++ b/libraries/classes/Controllers/Table/ChartController.php @@ -44,8 +44,6 @@ class ChartController extends AbstractController public function __invoke(): void { - global $db, $table, $cfg, $sql_query, $errorUrl; - if (isset($_REQUEST['pos'], $_REQUEST['session_max_rows']) && $this->response->isAjax()) { $this->ajax(); @@ -53,7 +51,7 @@ class ChartController extends AbstractController } // Throw error if no sql query is set - if (! isset($sql_query) || $sql_query == '') { + if (! isset($GLOBALS['sql_query']) || $GLOBALS['sql_query'] == '') { $this->response->setRequestStatus(false); $this->response->addHTML( Message::error(__('No SQL query was set to fetch data.'))->getDisplay() @@ -82,41 +80,41 @@ class ChartController extends AbstractController /** * Runs common work */ - if (strlen($table) > 0) { + if (strlen($GLOBALS['table']) > 0) { Util::checkParameters(['db', 'table']); - $url_params = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($url_params, '&'); + $url_params = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($url_params, '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); - $url_params['goto'] = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); + $url_params['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); $url_params['back'] = Url::getFromRoute('/table/sql'); - $this->dbi->selectDb($db); - } elseif (strlen($db) > 0) { - $url_params['goto'] = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); + $this->dbi->selectDb($GLOBALS['db']); + } elseif (strlen($GLOBALS['db']) > 0) { + $url_params['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); $url_params['back'] = Url::getFromRoute('/sql'); Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } } else { - $url_params['goto'] = Util::getScriptNameForOption($cfg['DefaultTabServer'], 'server'); + $url_params['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabServer'], 'server'); $url_params['back'] = Url::getFromRoute('/sql'); - $errorUrl = Url::getFromRoute('/'); + $GLOBALS['errorUrl'] = Url::getFromRoute('/'); if ($this->dbi->isSuperUser()) { $this->dbi->selectDb('mysql'); } } - $result = $this->dbi->tryQuery($sql_query); + $result = $this->dbi->tryQuery($GLOBALS['sql_query']); $fields_meta = $row = []; if ($result !== false) { $fields_meta = $this->dbi->getFieldsMeta($result); @@ -147,10 +145,10 @@ class ChartController extends AbstractController return; } - $url_params['db'] = $db; + $url_params['db'] = $GLOBALS['db']; $url_params['reload'] = 1; - $startAndNumberOfRowsFieldset = Generator::getStartAndNumberOfRowsFieldsetData($sql_query); + $startAndNumberOfRowsFieldset = Generator::getStartAndNumberOfRowsFieldsetData($GLOBALS['sql_query']); /** * Displays the page @@ -169,19 +167,17 @@ class ChartController extends AbstractController */ public function ajax(): void { - global $db, $table, $sql_query, $urlParams, $errorUrl, $cfg; - - if (strlen($table) > 0 && strlen($db) > 0) { + if (strlen($GLOBALS['table']) > 0 && strlen($GLOBALS['db']) > 0) { Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); } - $parser = new Parser($sql_query); + $parser = new Parser($GLOBALS['sql_query']); /** * @var SelectStatement $statement */ diff --git a/libraries/classes/Controllers/Table/CreateController.php b/libraries/classes/Controllers/Table/CreateController.php index 45025279ef..0ccf154b06 100644 --- a/libraries/classes/Controllers/Table/CreateController.php +++ b/libraries/classes/Controllers/Table/CreateController.php @@ -58,14 +58,12 @@ class CreateController extends AbstractController public function __invoke(): void { - global $num_fields, $sql_query, $result, $db, $table; - Util::checkParameters(['db']); $cfg = $this->config->settings; /* Check if database name is empty */ - if (strlen($db) === 0) { + if (strlen($GLOBALS['db']) === 0) { Generator::mysqlDie( __('The database name is empty!'), '', @@ -77,28 +75,28 @@ class CreateController extends AbstractController /** * Selects the database to work with */ - if (! $this->dbi->selectDb($db)) { + if (! $this->dbi->selectDb($GLOBALS['db'])) { Generator::mysqlDie( - sprintf(__('\'%s\' database does not exist.'), htmlspecialchars($db)), + sprintf(__('\'%s\' database does not exist.'), htmlspecialchars($GLOBALS['db'])), '', false, 'index.php' ); } - if ($this->dbi->getColumns($db, $table)) { + if ($this->dbi->getColumns($GLOBALS['db'], $GLOBALS['table'])) { // table exists already Generator::mysqlDie( - sprintf(__('Table %s already exists!'), htmlspecialchars($table)), + sprintf(__('Table %s already exists!'), htmlspecialchars($GLOBALS['table'])), '', false, - Url::getFromRoute('/database/structure', ['db' => $db]) + Url::getFromRoute('/database/structure', ['db' => $GLOBALS['db']]) ); } $createAddField = new CreateAddField($this->dbi); - $num_fields = $createAddField->getNumberOfFieldsFromRequest(); + $GLOBALS['num_fields'] = $createAddField->getNumberOfFieldsFromRequest(); /** * The form used to define the structure of the table has been submitted @@ -106,23 +104,23 @@ class CreateController extends AbstractController if (isset($_POST['do_save_data'])) { // lower_case_table_names=1 `DB` becomes `db` if ($this->dbi->getLowerCaseNames() === '1') { - $db = mb_strtolower($db); - $table = mb_strtolower($table); + $GLOBALS['db'] = mb_strtolower($GLOBALS['db']); + $GLOBALS['table'] = mb_strtolower($GLOBALS['table']); } - $sql_query = $createAddField->getTableCreationQuery($db, $table); + $GLOBALS['sql_query'] = $createAddField->getTableCreationQuery($GLOBALS['db'], $GLOBALS['table']); // If there is a request for SQL previewing. if (isset($_POST['preview_sql'])) { - Core::previewSQL($sql_query); + Core::previewSQL($GLOBALS['sql_query']); return; } // Executes the query - $result = $this->dbi->tryQuery($sql_query); + $GLOBALS['result'] = $this->dbi->tryQuery($GLOBALS['sql_query']); - if ($result) { + if ($GLOBALS['result']) { // Update comment table for mime types [MIME] if (isset($_POST['field_mimetype']) && is_array($_POST['field_mimetype']) && $cfg['BrowseMIME']) { foreach ($_POST['field_mimetype'] as $fieldindex => $mimetype) { @@ -134,8 +132,8 @@ class CreateController extends AbstractController } $this->transformations->setMime( - $db, - $table, + $GLOBALS['db'], + $GLOBALS['table'], $_POST['field_name'][$fieldindex], $mimetype, $_POST['field_transformation'][$fieldindex], @@ -158,7 +156,7 @@ class CreateController extends AbstractController $this->addScriptFiles(['vendor/jquery/jquery.uitablefilter.js', 'indexes.js']); - $templateData = $this->columnsDefinition->displayForm('/table/create', $num_fields); + $templateData = $this->columnsDefinition->displayForm('/table/create', $GLOBALS['num_fields']); $this->render('columns_definitions/column_definitions_form', $templateData); } diff --git a/libraries/classes/Controllers/Table/DeleteConfirmController.php b/libraries/classes/Controllers/Table/DeleteConfirmController.php index 9b7dda67d7..da751966b4 100644 --- a/libraries/classes/Controllers/Table/DeleteConfirmController.php +++ b/libraries/classes/Controllers/Table/DeleteConfirmController.php @@ -17,8 +17,6 @@ final class DeleteConfirmController extends AbstractController { public function __invoke(): void { - global $db, $table, $sql_query, $urlParams, $errorUrl, $cfg; - $selected = $_POST['rows_to_delete'] ?? null; if (! isset($selected) || ! is_array($selected)) { @@ -30,17 +28,17 @@ final class DeleteConfirmController extends AbstractController Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); $this->render('table/delete/confirm', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'selected' => $selected, - 'sql_query' => $sql_query, + 'sql_query' => $GLOBALS['sql_query'], 'is_foreign_key_check' => ForeignKey::isCheckEnabled(), ]); } diff --git a/libraries/classes/Controllers/Table/DeleteRowsController.php b/libraries/classes/Controllers/Table/DeleteRowsController.php index 73db50de88..55f735b774 100644 --- a/libraries/classes/Controllers/Table/DeleteRowsController.php +++ b/libraries/classes/Controllers/Table/DeleteRowsController.php @@ -36,8 +36,6 @@ final class DeleteRowsController extends AbstractController public function __invoke(): void { - global $db, $goto, $sql_query, $table, $disp_message, $disp_query, $active_page; - $mult_btn = $_POST['mult_btn'] ?? ''; $original_sql_query = $_POST['original_sql_query'] ?? ''; $selected = $_POST['selected'] ?? []; @@ -54,52 +52,52 @@ final class DeleteRowsController extends AbstractController if ($mult_btn === __('Yes')) { $default_fk_check_value = ForeignKey::handleDisableCheckInit(); - $sql_query = ''; + $GLOBALS['sql_query'] = ''; foreach ($selected as $row) { $query = sprintf( 'DELETE FROM %s WHERE %s LIMIT 1;', - Util::backquote($table), + Util::backquote($GLOBALS['table']), $row ); - $sql_query .= $query . "\n"; - $this->dbi->selectDb($db); + $GLOBALS['sql_query'] .= $query . "\n"; + $this->dbi->selectDb($GLOBALS['db']); $this->dbi->query($query); } if (! empty($_REQUEST['pos'])) { - $_REQUEST['pos'] = $sql->calculatePosForLastPage($db, $table, $_REQUEST['pos']); + $_REQUEST['pos'] = $sql->calculatePosForLastPage($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['pos']); } ForeignKey::handleDisableCheckCleanup($default_fk_check_value); - $disp_message = __('Your SQL query has been executed successfully.'); - $disp_query = $sql_query; + $GLOBALS['disp_message'] = __('Your SQL query has been executed successfully.'); + $GLOBALS['disp_query'] = $GLOBALS['sql_query']; } $_url_params = $GLOBALS['urlParams']; $_url_params['goto'] = Url::getFromRoute('/table/sql'); if (isset($original_sql_query)) { - $sql_query = $original_sql_query; + $GLOBALS['sql_query'] = $original_sql_query; } - $active_page = Url::getFromRoute('/sql'); + $GLOBALS['active_page'] = Url::getFromRoute('/sql'); $this->response->addHTML($sql->executeQueryAndSendQueryResponse( null, false, - $db, - $table, + $GLOBALS['db'], + $GLOBALS['table'], null, null, null, null, null, - $goto, - $disp_query ?? null, - $disp_message ?? null, - $sql_query, + $GLOBALS['goto'], + $GLOBALS['disp_query'] ?? null, + $GLOBALS['disp_message'] ?? null, + $GLOBALS['sql_query'], null )); } diff --git a/libraries/classes/Controllers/Table/DropColumnConfirmationController.php b/libraries/classes/Controllers/Table/DropColumnConfirmationController.php index 179e3cac33..8309fa71df 100644 --- a/libraries/classes/Controllers/Table/DropColumnConfirmationController.php +++ b/libraries/classes/Controllers/Table/DropColumnConfirmationController.php @@ -15,8 +15,6 @@ final class DropColumnConfirmationController extends AbstractController { public function __invoke(): void { - global $db, $table, $urlParams, $errorUrl, $cfg; - $selected = $_POST['selected_fld'] ?? null; if (empty($selected)) { @@ -28,11 +26,11 @@ final class DropColumnConfirmationController extends AbstractController Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); $this->render('table/structure/drop_confirm', [ 'db' => $GLOBALS['db'], diff --git a/libraries/classes/Controllers/Table/ExportController.php b/libraries/classes/Controllers/Table/ExportController.php index 649aedc81d..81cb1224b1 100644 --- a/libraries/classes/Controllers/Table/ExportController.php +++ b/libraries/classes/Controllers/Table/ExportController.php @@ -38,9 +38,6 @@ class ExportController extends AbstractController public function __invoke(): void { - global $db, $urlParams, $table, $replaces, $cfg, $errorUrl; - global $sql_query, $where_clause, $num_tables, $unlim_num_rows; - $pageSettings = new PageSettings('Export'); $pageSettingsErrorHtml = $pageSettings->getErrorHTML(); $pageSettingsHtml = $pageSettings->getHTML(); @@ -49,49 +46,53 @@ class ExportController extends AbstractController Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - $urlParams['goto'] = Url::getFromRoute('/table/export'); - $urlParams['back'] = Url::getFromRoute('/table/export'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/table/export'); + $GLOBALS['urlParams']['back'] = Url::getFromRoute('/table/export'); // When we have some query, we need to remove LIMIT from that and possibly // generate WHERE clause (if we are asked to export specific rows) - if (! empty($sql_query)) { - $parser = new Parser($sql_query); + if (! empty($GLOBALS['sql_query'])) { + $parser = new Parser($GLOBALS['sql_query']); if (! empty($parser->statements[0]) && ($parser->statements[0] instanceof SelectStatement)) { // Checking if the WHERE clause has to be replaced. - if (! empty($where_clause) && is_array($where_clause)) { - $replaces[] = [ + if (! empty($GLOBALS['where_clause']) && is_array($GLOBALS['where_clause'])) { + $GLOBALS['replaces'][] = [ 'WHERE', - 'WHERE (' . implode(') OR (', $where_clause) . ')', + 'WHERE (' . implode(') OR (', $GLOBALS['where_clause']) . ')', ]; } // Preparing to remove the LIMIT clause. - $replaces[] = [ + $GLOBALS['replaces'][] = [ 'LIMIT', '', ]; // Replacing the clauses. - $sql_query = Query::replaceClauses($parser->statements[0], $parser->list, $replaces); + $GLOBALS['sql_query'] = Query::replaceClauses( + $parser->statements[0], + $parser->list, + $GLOBALS['replaces'] + ); } } - if (! isset($sql_query)) { - $sql_query = ''; + if (! isset($GLOBALS['sql_query'])) { + $GLOBALS['sql_query'] = ''; } - if (! isset($num_tables)) { - $num_tables = 0; + if (! isset($GLOBALS['num_tables'])) { + $GLOBALS['num_tables'] = 0; } - if (! isset($unlim_num_rows)) { - $unlim_num_rows = 0; + if (! isset($GLOBALS['unlim_num_rows'])) { + $GLOBALS['unlim_num_rows'] = 0; } $GLOBALS['single_table'] = $_POST['single_table'] ?? $_GET['single_table'] ?? $GLOBALS['single_table'] ?? null; @@ -114,11 +115,11 @@ class ExportController extends AbstractController $options = $this->export->getOptions( $exportType, - $db, - $table, - $sql_query, - $num_tables, - $unlim_num_rows, + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['sql_query'], + $GLOBALS['num_tables'], + $GLOBALS['unlim_num_rows'], $exportList ); diff --git a/libraries/classes/Controllers/Table/ExportRowsController.php b/libraries/classes/Controllers/Table/ExportRowsController.php index c0e81e3ca0..c4ad72ceb9 100644 --- a/libraries/classes/Controllers/Table/ExportRowsController.php +++ b/libraries/classes/Controllers/Table/ExportRowsController.php @@ -28,8 +28,6 @@ final class ExportRowsController extends AbstractController public function __invoke(): void { - global $active_page, $single_table, $where_clause; - if (isset($_POST['goto']) && (! isset($_POST['rows_to_delete']) || ! is_array($_POST['rows_to_delete']))) { $this->response->setRequestStatus(false); $this->response->addJSON('message', __('No row selected.')); @@ -38,20 +36,20 @@ final class ExportRowsController extends AbstractController } // Needed to allow SQL export - $single_table = true; + $GLOBALS['single_table'] = true; // As we got the rows to be exported from the // 'rows_to_delete' checkbox, we use the index of it as the // indicating WHERE clause. Then we build the array which is used // for the /table/change script. - $where_clause = []; + $GLOBALS['where_clause'] = []; if (isset($_POST['rows_to_delete']) && is_array($_POST['rows_to_delete'])) { foreach ($_POST['rows_to_delete'] as $i_where_clause) { - $where_clause[] = $i_where_clause; + $GLOBALS['where_clause'][] = $i_where_clause; } } - $active_page = Url::getFromRoute('/table/export'); + $GLOBALS['active_page'] = Url::getFromRoute('/table/export'); ($this->exportController)(); } diff --git a/libraries/classes/Controllers/Table/FindReplaceController.php b/libraries/classes/Controllers/Table/FindReplaceController.php index 98d82cdc20..c49e908710 100644 --- a/libraries/classes/Controllers/Table/FindReplaceController.php +++ b/libraries/classes/Controllers/Table/FindReplaceController.php @@ -60,15 +60,13 @@ class FindReplaceController extends AbstractController public function __invoke(): void { - global $db, $table, $urlParams, $cfg, $errorUrl; - Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); if (isset($_POST['find'])) { $this->findAction(); @@ -127,10 +125,8 @@ class FindReplaceController extends AbstractController */ public function displaySelectionFormAction(): void { - global $goto; - - if (! isset($goto)) { - $goto = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + if (! isset($GLOBALS['goto'])) { + $GLOBALS['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); } $column_names = $this->columnNames; @@ -144,7 +140,7 @@ class FindReplaceController extends AbstractController $this->render('table/find_replace/index', [ 'db' => $GLOBALS['db'], 'table' => $GLOBALS['table'], - 'goto' => $goto, + 'goto' => $GLOBALS['goto'], 'column_names' => $column_names, 'types' => $types, 'sql_types' => $this->dbi->types, diff --git a/libraries/classes/Controllers/Table/GetFieldController.php b/libraries/classes/Controllers/Table/GetFieldController.php index f1c7cdbf7f..c033e18f52 100644 --- a/libraries/classes/Controllers/Table/GetFieldController.php +++ b/libraries/classes/Controllers/Table/GetFieldController.php @@ -38,8 +38,6 @@ class GetFieldController extends AbstractController public function __invoke(): void { - global $db, $table; - $this->response->disable(); /* Check parameters */ @@ -49,16 +47,16 @@ class GetFieldController extends AbstractController ]); /* Select database */ - if (! $this->dbi->selectDb($db)) { + if (! $this->dbi->selectDb($GLOBALS['db'])) { Generator::mysqlDie( - sprintf(__('\'%s\' database does not exist.'), htmlspecialchars($db)), + sprintf(__('\'%s\' database does not exist.'), htmlspecialchars($GLOBALS['db'])), '', false ); } /* Check if table exists */ - if (! $this->dbi->getColumns($db, $table)) { + if (! $this->dbi->getColumns($GLOBALS['db'], $GLOBALS['table'])) { Generator::mysqlDie(__('Invalid table name')); } @@ -75,7 +73,7 @@ class GetFieldController extends AbstractController /* Grab data */ $sql = 'SELECT ' . Util::backquote($_GET['transform_key']) - . ' FROM ' . Util::backquote($table) + . ' FROM ' . Util::backquote($GLOBALS['table']) . ' WHERE ' . $_GET['where_clause'] . ';'; $result = $this->dbi->fetchValue($sql); @@ -93,7 +91,7 @@ class GetFieldController extends AbstractController ini_set('url_rewriter.tags', ''); Core::downloadHeader( - $table . '-' . $_GET['transform_key'] . '.bin', + $GLOBALS['table'] . '-' . $_GET['transform_key'] . '.bin', Mime::detect($result), mb_strlen($result, '8bit') ); diff --git a/libraries/classes/Controllers/Table/GisVisualizationController.php b/libraries/classes/Controllers/Table/GisVisualizationController.php index 0fecc2f5bb..82ea067946 100644 --- a/libraries/classes/Controllers/Table/GisVisualizationController.php +++ b/libraries/classes/Controllers/Table/GisVisualizationController.php @@ -41,12 +41,10 @@ final class GisVisualizationController extends AbstractController public function __invoke(): void { - global $cfg, $urlParams, $db, $errorUrl; - Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; @@ -163,12 +161,12 @@ final class GisVisualizationController extends AbstractController /** * Displays the page */ - $urlParams['goto'] = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $urlParams['back'] = Url::getFromRoute('/sql'); - $urlParams['sql_query'] = $sqlQuery; - $urlParams['sql_signature'] = Core::signSqlQuery($sqlQuery); + $GLOBALS['urlParams']['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['urlParams']['back'] = Url::getFromRoute('/sql'); + $GLOBALS['urlParams']['sql_query'] = $sqlQuery; + $GLOBALS['urlParams']['sql_signature'] = Core::signSqlQuery($sqlQuery); $downloadUrl = Url::getFromRoute('/table/gis-visualization', array_merge( - $urlParams, + $GLOBALS['urlParams'], [ 'saveToFile' => true, 'session_max_rows' => $rows, @@ -181,7 +179,7 @@ final class GisVisualizationController extends AbstractController $startAndNumberOfRowsFieldset = Generator::getStartAndNumberOfRowsFieldsetData($sqlQuery); $html = $this->template->render('table/gis_visualization/gis_visualization', [ - 'url_params' => $urlParams, + 'url_params' => $GLOBALS['urlParams'], 'download_url' => $downloadUrl, 'label_candidates' => $labelCandidates, 'spatial_candidates' => $spatialCandidates, diff --git a/libraries/classes/Controllers/Table/ImportController.php b/libraries/classes/Controllers/Table/ImportController.php index edcb332ba2..e156b3052e 100644 --- a/libraries/classes/Controllers/Table/ImportController.php +++ b/libraries/classes/Controllers/Table/ImportController.php @@ -40,8 +40,6 @@ final class ImportController extends AbstractController public function __invoke(): void { - global $db, $table, $urlParams, $SESSION_KEY, $cfg, $errorUrl; - $pageSettings = new PageSettings('Import'); $pageSettingsErrorHtml = $pageSettings->getErrorHTML(); $pageSettingsHtml = $pageSettings->getHTML(); @@ -50,16 +48,16 @@ final class ImportController extends AbstractController Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); - $urlParams['goto'] = Url::getFromRoute('/table/import'); - $urlParams['back'] = Url::getFromRoute('/table/import'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/table/import'); + $GLOBALS['urlParams']['back'] = Url::getFromRoute('/table/import'); - [$SESSION_KEY, $uploadId] = Ajax::uploadProgressSetup(); + [$GLOBALS['SESSION_KEY'], $uploadId] = Ajax::uploadProgressSetup(); $importList = Plugins::getImport('table'); @@ -80,14 +78,14 @@ final class ImportController extends AbstractController $localImportFile = $_REQUEST['local_import_file'] ?? null; $compressions = Import::getCompressions(); - $charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']); + $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); - $idKey = $_SESSION[$SESSION_KEY]['handler']::getIdKey(); + $idKey = $_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getIdKey(); $hiddenInputs = [ $idKey => $uploadId, 'import_type' => 'table', - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], ]; $default = isset($_GET['format']) ? (string) $_GET['format'] : Plugins::getDefault('Import', 'format'); @@ -101,10 +99,10 @@ final class ImportController extends AbstractController 'page_settings_error_html' => $pageSettingsErrorHtml, 'page_settings_html' => $pageSettingsHtml, 'upload_id' => $uploadId, - 'handler' => $_SESSION[$SESSION_KEY]['handler'], + 'handler' => $_SESSION[$GLOBALS['SESSION_KEY']]['handler'], 'hidden_inputs' => $hiddenInputs, - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'max_upload_size' => $maxUploadSize, 'formatted_maximum_upload_size' => Util::getFormattedMaximumUploadSize($maxUploadSize), 'plugins_choice' => $choice, @@ -113,18 +111,18 @@ final class ImportController extends AbstractController 'is_allow_interrupt_checked' => $isAllowInterruptChecked, 'local_import_file' => $localImportFile, 'is_upload' => $GLOBALS['config']->get('enable_upload'), - 'upload_dir' => $cfg['UploadDir'] ?? null, + 'upload_dir' => $GLOBALS['cfg']['UploadDir'] ?? null, 'timeout_passed_global' => $GLOBALS['timeout_passed'] ?? null, 'compressions' => $compressions, 'is_encoding_supported' => Encoding::isSupported(), 'encodings' => Encoding::listEncodings(), - 'import_charset' => $cfg['Import']['charset'] ?? null, + 'import_charset' => $GLOBALS['cfg']['Import']['charset'] ?? null, 'timeout_passed' => $timeoutPassed, 'offset' => $offset, 'can_convert_kanji' => Encoding::canConvertKanji(), 'charsets' => $charsets, 'is_foreign_key_check' => ForeignKey::isCheckEnabled(), - 'user_upload_dir' => Util::userDir((string) ($cfg['UploadDir'] ?? '')), + 'user_upload_dir' => Util::userDir((string) ($GLOBALS['cfg']['UploadDir'] ?? '')), 'local_files' => Import::getLocalFiles($importList), ]); } diff --git a/libraries/classes/Controllers/Table/IndexRenameController.php b/libraries/classes/Controllers/Table/IndexRenameController.php index 1eb3c198f3..8965ef6a56 100644 --- a/libraries/classes/Controllers/Table/IndexRenameController.php +++ b/libraries/classes/Controllers/Table/IndexRenameController.php @@ -37,16 +37,14 @@ final class IndexRenameController extends AbstractController public function __invoke(): void { - global $db, $table, $urlParams, $cfg, $errorUrl; - if (! isset($_POST['create_edit_table'])) { Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); } if (isset($_POST['index'])) { diff --git a/libraries/classes/Controllers/Table/IndexesController.php b/libraries/classes/Controllers/Table/IndexesController.php index 97471e22f2..c2dd4f2396 100644 --- a/libraries/classes/Controllers/Table/IndexesController.php +++ b/libraries/classes/Controllers/Table/IndexesController.php @@ -44,16 +44,14 @@ class IndexesController extends AbstractController public function __invoke(): void { - global $db, $table, $urlParams, $cfg, $errorUrl; - if (! isset($_POST['create_edit_table'])) { Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); } if (isset($_POST['index'])) { diff --git a/libraries/classes/Controllers/Table/OperationsController.php b/libraries/classes/Controllers/Table/OperationsController.php index 8052975e76..509be58036 100644 --- a/libraries/classes/Controllers/Table/OperationsController.php +++ b/libraries/classes/Controllers/Table/OperationsController.php @@ -64,60 +64,57 @@ class OperationsController extends AbstractController public function __invoke(): void { - global $urlParams, $reread_info, $tbl_is_view, $tbl_storage_engine; - global $show_comment, $tbl_collation, $table_info_num_rows, $row_format, $auto_increment, $create_options; - global $table_alters, $warning_messages, $lowerCaseNames, $db, $table, $reload, $result; - global $new_tbl_storage_engine, $sql_query, $message_to_show, $columns, $hideOrderTable, $indexes; - global $notNull, $comment, $errorUrl, $cfg; - $this->checkUserPrivileges->getPrivileges(); // lower_case_table_names=1 `DB` becomes `db` - $lowerCaseNames = $this->dbi->getLowerCaseNames() === '1'; + $GLOBALS['lowerCaseNames'] = $this->dbi->getLowerCaseNames() === '1'; - if ($lowerCaseNames) { - $table = mb_strtolower($table); + if ($GLOBALS['lowerCaseNames']) { + $GLOBALS['table'] = mb_strtolower($GLOBALS['table']); } - $pma_table = $this->dbi->getTable($db, $table); + $pma_table = $this->dbi->getTable($GLOBALS['db'], $GLOBALS['table']); $this->addScriptFiles(['table/operations.js']); Util::checkParameters(['db', 'table']); - $isSystemSchema = Utilities::isSystemSchema($db); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $isSystemSchema = Utilities::isSystemSchema($GLOBALS['db']); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); - $urlParams['goto'] = $urlParams['back'] = Url::getFromRoute('/table/operations'); + $GLOBALS['urlParams']['goto'] = $GLOBALS['urlParams']['back'] = Url::getFromRoute('/table/operations'); $relationParameters = $this->relation->getRelationParameters(); /** * Reselect current db (needed in some cases probably due to the calling of {@link Relation}) */ - $this->dbi->selectDb($db); + $this->dbi->selectDb($GLOBALS['db']); - $reread_info = $pma_table->getStatusInfo(null, false); - $GLOBALS['showtable'] = $pma_table->getStatusInfo(null, (isset($reread_info) && $reread_info)); + $GLOBALS['reread_info'] = $pma_table->getStatusInfo(null, false); + $GLOBALS['showtable'] = $pma_table->getStatusInfo( + null, + (isset($GLOBALS['reread_info']) && $GLOBALS['reread_info']) + ); if ($pma_table->isView()) { - $tbl_is_view = true; - $tbl_storage_engine = __('View'); - $show_comment = null; + $GLOBALS['tbl_is_view'] = true; + $GLOBALS['tbl_storage_engine'] = __('View'); + $GLOBALS['show_comment'] = null; } else { - $tbl_is_view = false; - $tbl_storage_engine = $pma_table->getStorageEngine(); - $show_comment = $pma_table->getComment(); + $GLOBALS['tbl_is_view'] = false; + $GLOBALS['tbl_storage_engine'] = $pma_table->getStorageEngine(); + $GLOBALS['show_comment'] = $pma_table->getComment(); } - $tbl_collation = $pma_table->getCollation(); - $table_info_num_rows = $pma_table->getNumRows(); - $row_format = $pma_table->getRowFormat(); - $auto_increment = $pma_table->getAutoIncrement(); - $create_options = $pma_table->getCreateOptions(); + $GLOBALS['tbl_collation'] = $pma_table->getCollation(); + $GLOBALS['table_info_num_rows'] = $pma_table->getNumRows(); + $GLOBALS['row_format'] = $pma_table->getRowFormat(); + $GLOBALS['auto_increment'] = $pma_table->getAutoIncrement(); + $GLOBALS['create_options'] = $pma_table->getCreateOptions(); // set initial value of these variables, based on the current table engine if ($pma_table->isEngine('ARIA')) { @@ -126,21 +123,21 @@ class OperationsController extends AbstractController // or explicit (option found with a value of 0 or 1) // ($create_options['transactional'] may have been set by Table class, // from the $create_options) - $create_options['transactional'] = ($create_options['transactional'] ?? '') == '0' + $GLOBALS['create_options']['transactional'] = ($GLOBALS['create_options']['transactional'] ?? '') == '0' ? '0' : '1'; - $create_options['page_checksum'] = $create_options['page_checksum'] ?? ''; + $GLOBALS['create_options']['page_checksum'] = $GLOBALS['create_options']['page_checksum'] ?? ''; } - $pma_table = $this->dbi->getTable($db, $table); - $reread_info = false; - $table_alters = []; + $pma_table = $this->dbi->getTable($GLOBALS['db'], $GLOBALS['table']); + $GLOBALS['reread_info'] = false; + $GLOBALS['table_alters'] = []; /** * If the table has to be moved to some other database */ if (isset($_POST['submit_move']) || isset($_POST['submit_copy'])) { - $message = $this->operations->moveOrCopyTable($db, $table); + $message = $this->operations->moveOrCopyTable($GLOBALS['db'], $GLOBALS['table']); if (! $this->response->isAjax()) { return; @@ -150,10 +147,10 @@ class OperationsController extends AbstractController if ($message->isSuccess()) { if (isset($_POST['submit_move'], $_POST['target_db'])) { - $db = $_POST['target_db'];// Used in Header::getJsParams() + $GLOBALS['db'] = $_POST['target_db'];// Used in Header::getJsParams() } - $this->response->addJSON('db', $db); + $this->response->addJSON('db', $GLOBALS['db']); return; } @@ -168,11 +165,11 @@ class OperationsController extends AbstractController */ if (isset($_POST['submitoptions'])) { $_message = ''; - $warning_messages = []; + $GLOBALS['warning_messages'] = []; if (isset($_POST['new_name'])) { // lower_case_table_names=1 `DB` becomes `db` - if ($lowerCaseNames) { + if ($GLOBALS['lowerCaseNames']) { $_POST['new_name'] = mb_strtolower($_POST['new_name']); } @@ -191,62 +188,66 @@ class OperationsController extends AbstractController } // Reselect the original DB - $db = $oldDb; + $GLOBALS['db'] = $oldDb; $this->dbi->selectDb($oldDb); $_message .= $pma_table->getLastMessage(); - $result = true; - $table = $pma_table->getName(); - $reread_info = true; - $reload = true; + $GLOBALS['result'] = true; + $GLOBALS['table'] = $pma_table->getName(); + $GLOBALS['reread_info'] = true; + $GLOBALS['reload'] = true; } else { $_message .= $pma_table->getLastError(); - $result = false; + $GLOBALS['result'] = false; } } if ( ! empty($_POST['new_tbl_storage_engine']) - && mb_strtoupper($_POST['new_tbl_storage_engine']) !== $tbl_storage_engine + && mb_strtoupper($_POST['new_tbl_storage_engine']) !== $GLOBALS['tbl_storage_engine'] ) { - $new_tbl_storage_engine = mb_strtoupper($_POST['new_tbl_storage_engine']); + $GLOBALS['new_tbl_storage_engine'] = mb_strtoupper($_POST['new_tbl_storage_engine']); if ($pma_table->isEngine('ARIA')) { - $create_options['transactional'] = ($create_options['transactional'] ?? '') == '0' - ? '0' - : '1'; - $create_options['page_checksum'] = $create_options['page_checksum'] ?? ''; + $GLOBALS['create_options']['transactional'] = ($GLOBALS['create_options']['transactional'] ?? '') + == '0' ? '0' : '1'; + $GLOBALS['create_options']['page_checksum'] = $GLOBALS['create_options']['page_checksum'] ?? ''; } } else { - $new_tbl_storage_engine = ''; + $GLOBALS['new_tbl_storage_engine'] = ''; } - $row_format = $create_options['row_format'] ?? $pma_table->getRowFormat(); + $GLOBALS['row_format'] = $GLOBALS['create_options']['row_format'] ?? $pma_table->getRowFormat(); - $table_alters = $this->operations->getTableAltersArray( + $GLOBALS['table_alters'] = $this->operations->getTableAltersArray( $pma_table, - $create_options['pack_keys'], - (empty($create_options['checksum']) ? '0' : '1'), - ($create_options['page_checksum'] ?? ''), - (empty($create_options['delay_key_write']) ? '0' : '1'), - $row_format, - $new_tbl_storage_engine, - (isset($create_options['transactional']) && $create_options['transactional'] == '0' ? '0' : '1'), - $tbl_collation + $GLOBALS['create_options']['pack_keys'], + (empty($GLOBALS['create_options']['checksum']) ? '0' : '1'), + ($GLOBALS['create_options']['page_checksum'] ?? ''), + (empty($GLOBALS['create_options']['delay_key_write']) ? '0' : '1'), + $GLOBALS['row_format'], + $GLOBALS['new_tbl_storage_engine'], + (isset($GLOBALS['create_options']['transactional']) + && $GLOBALS['create_options']['transactional'] == '0' ? '0' : '1'), + $GLOBALS['tbl_collation'] ); - if (count($table_alters) > 0) { - $sql_query = 'ALTER TABLE ' - . Util::backquote($table); - $sql_query .= "\r\n" . implode("\r\n", $table_alters); - $sql_query .= ';'; - $result = (bool) $this->dbi->query($sql_query); - $reread_info = true; - unset($table_alters); - $warning_messages = $this->operations->getWarningMessagesArray(); + if (count($GLOBALS['table_alters']) > 0) { + $GLOBALS['sql_query'] = 'ALTER TABLE ' + . Util::backquote($GLOBALS['table']); + $GLOBALS['sql_query'] .= "\r\n" . implode("\r\n", $GLOBALS['table_alters']); + $GLOBALS['sql_query'] .= ';'; + $GLOBALS['result'] = (bool) $this->dbi->query($GLOBALS['sql_query']); + $GLOBALS['reread_info'] = true; + unset($GLOBALS['table_alters']); + $GLOBALS['warning_messages'] = $this->operations->getWarningMessagesArray(); } if (! empty($_POST['tbl_collation']) && ! empty($_POST['change_all_collations'])) { - $this->operations->changeAllColumnsCollation($db, $table, $_POST['tbl_collation']); + $this->operations->changeAllColumnsCollation( + $GLOBALS['db'], + $GLOBALS['table'], + $_POST['tbl_collation'] + ); } if (isset($_POST['tbl_collation']) && empty($_POST['tbl_collation'])) { @@ -266,57 +267,57 @@ class OperationsController extends AbstractController * Reordering the table has been requested by the user */ if (isset($_POST['submitorderby']) && ! empty($_POST['order_field'])) { - $sql_query = QueryGenerator::getQueryForReorderingTable( - $table, + $GLOBALS['sql_query'] = QueryGenerator::getQueryForReorderingTable( + $GLOBALS['table'], urldecode($_POST['order_field']), $_POST['order_order'] ?? null ); - $result = $this->dbi->query($sql_query); + $GLOBALS['result'] = $this->dbi->query($GLOBALS['sql_query']); } /** * A partition operation has been requested by the user */ if (isset($_POST['submit_partition']) && ! empty($_POST['partition_operation'])) { - $sql_query = QueryGenerator::getQueryForPartitioningTable( - $table, + $GLOBALS['sql_query'] = QueryGenerator::getQueryForPartitioningTable( + $GLOBALS['table'], $_POST['partition_operation'], $_POST['partition_name'] ); - $result = $this->dbi->query($sql_query); + $GLOBALS['result'] = $this->dbi->query($GLOBALS['sql_query']); } - if ($reread_info) { + if ($GLOBALS['reread_info']) { // to avoid showing the old value (for example the AUTO_INCREMENT) after // a change, clear the cache $this->dbi->getCache()->clearTableCache(); - $this->dbi->selectDb($db); + $this->dbi->selectDb($GLOBALS['db']); $GLOBALS['showtable'] = $pma_table->getStatusInfo(null, true); if ($pma_table->isView()) { - $tbl_is_view = true; - $tbl_storage_engine = __('View'); - $show_comment = null; + $GLOBALS['tbl_is_view'] = true; + $GLOBALS['tbl_storage_engine'] = __('View'); + $GLOBALS['show_comment'] = null; } else { - $tbl_is_view = false; - $tbl_storage_engine = $pma_table->getStorageEngine(); - $show_comment = $pma_table->getComment(); + $GLOBALS['tbl_is_view'] = false; + $GLOBALS['tbl_storage_engine'] = $pma_table->getStorageEngine(); + $GLOBALS['show_comment'] = $pma_table->getComment(); } - $tbl_collation = $pma_table->getCollation(); - $table_info_num_rows = $pma_table->getNumRows(); - $row_format = $pma_table->getRowFormat(); - $auto_increment = $pma_table->getAutoIncrement(); - $create_options = $pma_table->getCreateOptions(); + $GLOBALS['tbl_collation'] = $pma_table->getCollation(); + $GLOBALS['table_info_num_rows'] = $pma_table->getNumRows(); + $GLOBALS['row_format'] = $pma_table->getRowFormat(); + $GLOBALS['auto_increment'] = $pma_table->getAutoIncrement(); + $GLOBALS['create_options'] = $pma_table->getCreateOptions(); } - unset($reread_info); + unset($GLOBALS['reread_info']); - if (isset($result) && empty($message_to_show)) { + if (isset($GLOBALS['result']) && empty($GLOBALS['message_to_show'])) { if (empty($_message)) { - if (empty($sql_query)) { + if (empty($GLOBALS['sql_query'])) { $_message = Message::success(__('No change')); } else { - $_message = $result + $_message = $GLOBALS['result'] ? Message::success() : Message::error(); } @@ -324,67 +325,67 @@ class OperationsController extends AbstractController if ($this->response->isAjax()) { $this->response->setRequestStatus($_message->isSuccess()); $this->response->addJSON('message', $_message); - if (! empty($sql_query)) { + if (! empty($GLOBALS['sql_query'])) { $this->response->addJSON( 'sql_query', - Generator::getMessage('', $sql_query) + Generator::getMessage('', $GLOBALS['sql_query']) ); } return; } } else { - $_message = $result + $_message = $GLOBALS['result'] ? Message::success($_message) : Message::error($_message); } - if (! empty($warning_messages)) { + if (! empty($GLOBALS['warning_messages'])) { $_message = new Message(); - $_message->addMessagesString($warning_messages); + $_message->addMessagesString($GLOBALS['warning_messages']); $_message->isError(true); if ($this->response->isAjax()) { $this->response->setRequestStatus(false); $this->response->addJSON('message', $_message); - if (! empty($sql_query)) { + if (! empty($GLOBALS['sql_query'])) { $this->response->addJSON( 'sql_query', - Generator::getMessage('', $sql_query) + Generator::getMessage('', $GLOBALS['sql_query']) ); } return; } - unset($warning_messages); + unset($GLOBALS['warning_messages']); } - if (empty($sql_query)) { + if (empty($GLOBALS['sql_query'])) { $this->response->addHTML( $_message->getDisplay() ); } else { $this->response->addHTML( - Generator::getMessage($_message, $sql_query) + Generator::getMessage($_message, $GLOBALS['sql_query']) ); } unset($_message); } - $urlParams['goto'] = $urlParams['back'] = Url::getFromRoute('/table/operations'); + $GLOBALS['urlParams']['goto'] = $GLOBALS['urlParams']['back'] = Url::getFromRoute('/table/operations'); - $columns = $this->dbi->getColumns($db, $table); + $GLOBALS['columns'] = $this->dbi->getColumns($GLOBALS['db'], $GLOBALS['table']); - $hideOrderTable = false; + $GLOBALS['hideOrderTable'] = false; // `ALTER TABLE ORDER BY` does not make sense for InnoDB tables that contain // a user-defined clustered index (PRIMARY KEY or NOT NULL UNIQUE index). // InnoDB always orders table rows according to such an index if one is present. - if ($tbl_storage_engine === 'INNODB') { - $indexes = Index::getFromTable($table, $db); - foreach ($indexes as $name => $idx) { + if ($GLOBALS['tbl_storage_engine'] === 'INNODB') { + $GLOBALS['indexes'] = Index::getFromTable($GLOBALS['table'], $GLOBALS['db']); + foreach ($GLOBALS['indexes'] as $name => $idx) { if ($name === 'PRIMARY') { - $hideOrderTable = true; + $GLOBALS['hideOrderTable'] = true; break; } @@ -392,33 +393,33 @@ class OperationsController extends AbstractController continue; } - $notNull = true; + $GLOBALS['notNull'] = true; foreach ($idx->getColumns() as $column) { if ($column->getNull()) { - $notNull = false; + $GLOBALS['notNull'] = false; break; } } - if ($notNull) { - $hideOrderTable = true; + if ($GLOBALS['notNull']) { + $GLOBALS['hideOrderTable'] = true; break; } } } - $comment = ''; - if (mb_strstr((string) $show_comment, '; InnoDB free') === false) { - if (mb_strstr((string) $show_comment, 'InnoDB free') === false) { + $GLOBALS['comment'] = ''; + if (mb_strstr((string) $GLOBALS['show_comment'], '; InnoDB free') === false) { + if (mb_strstr((string) $GLOBALS['show_comment'], 'InnoDB free') === false) { // only user entered comment - $comment = (string) $show_comment; + $GLOBALS['comment'] = (string) $GLOBALS['show_comment']; } else { // here we have just InnoDB generated part - $comment = ''; + $GLOBALS['comment'] = ''; } } else { // remove InnoDB comment from end, just the minimal part (*? is non greedy) - $comment = preg_replace('@; InnoDB free:.*?$@', '', (string) $show_comment); + $GLOBALS['comment'] = preg_replace('@; InnoDB free:.*?$@', '', (string) $GLOBALS['show_comment']); } $storageEngines = StorageEngine::getArray(); @@ -426,11 +427,11 @@ class OperationsController extends AbstractController $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); $collations = Charsets::getCollations($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); - $hasPackKeys = isset($create_options['pack_keys']) + $hasPackKeys = isset($GLOBALS['create_options']['pack_keys']) && $pma_table->isEngine(['MYISAM', 'ARIA', 'ISAM']); $hasChecksumAndDelayKeyWrite = $pma_table->isEngine(['MYISAM', 'ARIA']); $hasTransactionalAndPageChecksum = $pma_table->isEngine('ARIA'); - $hasAutoIncrement = strlen((string) $auto_increment) > 0 + $hasAutoIncrement = strlen((string) $GLOBALS['auto_increment']) > 0 && $pma_table->isEngine(['MYISAM', 'ARIA', 'INNODB', 'PBXT', 'ROCKSDB']); $possibleRowFormats = $this->operations->getPossibleRowFormat(); @@ -440,7 +441,7 @@ class OperationsController extends AbstractController $databaseList = $GLOBALS['dblist']->databases->getList(); } - $hasForeignKeys = ! empty($this->relation->getForeigners($db, $table, '', 'foreign')); + $hasForeignKeys = ! empty($this->relation->getForeigners($GLOBALS['db'], $GLOBALS['table'], '', 'foreign')); $hasPrivileges = $GLOBALS['table_priv'] && $GLOBALS['col_priv'] && $GLOBALS['is_reload_priv']; $switchToNew = isset($_SESSION['pma_switch_to_new']) && $_SESSION['pma_switch_to_new']; @@ -448,7 +449,7 @@ class OperationsController extends AbstractController $partitionsChoices = []; if (Partition::havePartitioning()) { - $partitionNames = Partition::getPartitionNames($db, $table); + $partitionNames = Partition::getPartitionNames($GLOBALS['db'], $GLOBALS['table']); if ($partitionNames[0] !== null) { $partitions = $partitionNames; $partitionsChoices = $this->operations->getPartitionMaintenanceChoices(); @@ -456,40 +457,40 @@ class OperationsController extends AbstractController } $foreigners = $this->operations->getForeignersForReferentialIntegrityCheck( - $urlParams, + $GLOBALS['urlParams'], $relationParameters->relationFeature !== null ); $this->render('table/operations/index', [ - 'db' => $db, - 'table' => $table, - 'url_params' => $urlParams, - 'columns' => $columns, - 'hide_order_table' => $hideOrderTable, - 'table_comment' => $comment, - 'storage_engine' => $tbl_storage_engine, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], + 'url_params' => $GLOBALS['urlParams'], + 'columns' => $GLOBALS['columns'], + 'hide_order_table' => $GLOBALS['hideOrderTable'], + 'table_comment' => $GLOBALS['comment'], + 'storage_engine' => $GLOBALS['tbl_storage_engine'], 'storage_engines' => $storageEngines, 'charsets' => $charsets, 'collations' => $collations, - 'tbl_collation' => $tbl_collation, - 'row_formats' => $possibleRowFormats[$tbl_storage_engine] ?? [], + 'tbl_collation' => $GLOBALS['tbl_collation'], + 'row_formats' => $possibleRowFormats[$GLOBALS['tbl_storage_engine']] ?? [], 'row_format_current' => $GLOBALS['showtable']['Row_format'], 'has_auto_increment' => $hasAutoIncrement, - 'auto_increment' => $auto_increment, + 'auto_increment' => $GLOBALS['auto_increment'], 'has_pack_keys' => $hasPackKeys, - 'pack_keys' => $create_options['pack_keys'] ?? '', + 'pack_keys' => $GLOBALS['create_options']['pack_keys'] ?? '', 'has_transactional_and_page_checksum' => $hasTransactionalAndPageChecksum, 'has_checksum_and_delay_key_write' => $hasChecksumAndDelayKeyWrite, - 'delay_key_write' => empty($create_options['delay_key_write']) ? '0' : '1', - 'transactional' => ($create_options['transactional'] ?? '') == '0' ? '0' : '1', - 'page_checksum' => $create_options['page_checksum'] ?? '', - 'checksum' => empty($create_options['checksum']) ? '0' : '1', + 'delay_key_write' => empty($GLOBALS['create_options']['delay_key_write']) ? '0' : '1', + 'transactional' => ($GLOBALS['create_options']['transactional'] ?? '') == '0' ? '0' : '1', + 'page_checksum' => $GLOBALS['create_options']['page_checksum'] ?? '', + 'checksum' => empty($GLOBALS['create_options']['checksum']) ? '0' : '1', 'database_list' => $databaseList, 'has_foreign_keys' => $hasForeignKeys, 'has_privileges' => $hasPrivileges, 'switch_to_new' => $switchToNew, 'is_system_schema' => $isSystemSchema, - 'is_view' => $tbl_is_view, + 'is_view' => $GLOBALS['tbl_is_view'], 'partitions' => $partitions, 'partitions_choices' => $partitionsChoices, 'foreigners' => $foreigners, diff --git a/libraries/classes/Controllers/Table/PrivilegesController.php b/libraries/classes/Controllers/Table/PrivilegesController.php index 30218faeb0..71cbadffac 100644 --- a/libraries/classes/Controllers/Table/PrivilegesController.php +++ b/libraries/classes/Controllers/Table/PrivilegesController.php @@ -41,9 +41,7 @@ class PrivilegesController extends AbstractController */ public function __invoke(array $params): string { - global $cfg, $text_dir; - - $scriptName = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); + $scriptName = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); $privileges = []; if ($this->dbi->isSuperUser()) { @@ -55,7 +53,7 @@ class PrivilegesController extends AbstractController 'table' => $params['checkprivstable'], 'is_superuser' => $this->dbi->isSuperUser(), 'table_url' => $scriptName, - 'text_dir' => $text_dir, + 'text_dir' => $GLOBALS['text_dir'], 'is_createuser' => $this->dbi->isCreateUser(), 'is_grantuser' => $this->dbi->isGrantUser(), 'privileges' => $privileges, diff --git a/libraries/classes/Controllers/Table/RecentFavoriteController.php b/libraries/classes/Controllers/Table/RecentFavoriteController.php index c422abb848..0807c4bd2c 100644 --- a/libraries/classes/Controllers/Table/RecentFavoriteController.php +++ b/libraries/classes/Controllers/Table/RecentFavoriteController.php @@ -15,14 +15,12 @@ class RecentFavoriteController extends AbstractController { public function __invoke(): void { - global $containerBuilder; - RecentFavoriteTable::getInstance('recent')->removeIfInvalid($_REQUEST['db'], $_REQUEST['table']); RecentFavoriteTable::getInstance('favorite')->removeIfInvalid($_REQUEST['db'], $_REQUEST['table']); /** @var SqlController $controller */ - $controller = $containerBuilder->get(SqlController::class); + $controller = $GLOBALS['containerBuilder']->get(SqlController::class); $controller(); } } diff --git a/libraries/classes/Controllers/Table/ReplaceController.php b/libraries/classes/Controllers/Table/ReplaceController.php index e94dec3f17..07f0fed202 100644 --- a/libraries/classes/Controllers/Table/ReplaceController.php +++ b/libraries/classes/Controllers/Table/ReplaceController.php @@ -69,21 +69,14 @@ final class ReplaceController extends AbstractController public function __invoke(): void { - global $containerBuilder, $db, $table, $urlParams, $message; - global $errorUrl, $mime_map, $unsaved_values, $active_page, $disp_query, $disp_message; - global $goto_include, $loop_array, $using_key, $is_insert, $is_insertignore, $query; - global $value_sets, $func_no_param, $func_optional_param, $gis_from_text_functions, $gis_from_wkb_functions; - global $query_fields, $insert_errors, $row_skipped, $query_values; - global $total_affected_rows, $last_messages, $warning_messages, $error_messages, $return_to_sql_query; - Util::checkParameters(['db', 'table', 'goto']); - $this->dbi->selectDb($db); + $this->dbi->selectDb($GLOBALS['db']); /** * Initializes some variables */ - $goto_include = false; + $GLOBALS['goto_include'] = false; $this->addScriptFiles([ 'makegrid.js', @@ -102,7 +95,7 @@ final class ReplaceController extends AbstractController ]); $GLOBALS['cfg']['InsertRows'] = $_POST['insert_rows']; /** @var ChangeController $controller */ - $controller = $containerBuilder->get(ChangeController::class); + $controller = $GLOBALS['containerBuilder']->get(ChangeController::class); $controller(); return; @@ -114,11 +107,11 @@ final class ReplaceController extends AbstractController 'edit_next', ]; if (isset($_POST['after_insert']) && in_array($_POST['after_insert'], $after_insert_actions)) { - $urlParams['after_insert'] = $_POST['after_insert']; + $GLOBALS['urlParams']['after_insert'] = $_POST['after_insert']; if (isset($_POST['where_clause'])) { foreach ($_POST['where_clause'] as $one_where_clause) { if ($_POST['after_insert'] === 'same_insert') { - $urlParams['where_clause'][] = $one_where_clause; + $GLOBALS['urlParams']['where_clause'][] = $one_where_clause; } elseif ($_POST['after_insert'] === 'edit_next') { $this->insertEdit->setSessionForEditNext($one_where_clause); } @@ -127,24 +120,24 @@ final class ReplaceController extends AbstractController } //get $goto_include for different cases - $goto_include = $this->insertEdit->getGotoInclude($goto_include); + $GLOBALS['goto_include'] = $this->insertEdit->getGotoInclude($GLOBALS['goto_include']); // Defines the url to return in case of failure of the query - $errorUrl = $this->insertEdit->getErrorUrl($urlParams); + $GLOBALS['errorUrl'] = $this->insertEdit->getErrorUrl($GLOBALS['urlParams']); /** * Prepares the update/insert of a row */ [ - $loop_array, - $using_key, - $is_insert, - $is_insertignore, + $GLOBALS['loop_array'], + $GLOBALS['using_key'], + $GLOBALS['is_insert'], + $GLOBALS['is_insertignore'], ] = $this->insertEdit->getParamsForUpdateOrInsert(); - $query = []; - $value_sets = []; - $func_no_param = [ + $GLOBALS['query'] = []; + $GLOBALS['value_sets'] = []; + $GLOBALS['func_no_param'] = [ 'CONNECTION_ID', 'CURRENT_USER', 'CURDATE', @@ -166,12 +159,12 @@ final class ReplaceController extends AbstractController 'UUID_SHORT', 'VERSION', ]; - $func_optional_param = [ + $GLOBALS['func_optional_param'] = [ 'RAND', 'UNIX_TIMESTAMP', ]; - $gis_from_text_functions = [ + $GLOBALS['gis_from_text_functions'] = [ 'GeomFromText', 'GeomCollFromText', 'LineFromText', @@ -181,7 +174,7 @@ final class ReplaceController extends AbstractController 'PolyFromText', 'MPolyFromText', ]; - $gis_from_wkb_functions = [ + $GLOBALS['gis_from_wkb_functions'] = [ 'GeomFromWKB', 'GeomCollFromWKB', 'LineFromWKB', @@ -192,7 +185,7 @@ final class ReplaceController extends AbstractController 'MPolyFromWKB', ]; if ($this->dbi->getVersion() >= 50600) { - $gis_from_text_functions = [ + $GLOBALS['gis_from_text_functions'] = [ 'ST_GeomFromText', 'ST_GeomCollFromText', 'ST_LineFromText', @@ -202,7 +195,7 @@ final class ReplaceController extends AbstractController 'ST_PolyFromText', 'ST_MPolyFromText', ]; - $gis_from_wkb_functions = [ + $GLOBALS['gis_from_wkb_functions'] = [ 'ST_GeomFromWKB', 'ST_GeomCollFromWKB', 'ST_LineFromWKB', @@ -214,23 +207,23 @@ final class ReplaceController extends AbstractController ]; } - $mime_map = $this->transformations->getMime($db, $table); - if ($mime_map === null) { - $mime_map = []; + $GLOBALS['mime_map'] = $this->transformations->getMime($GLOBALS['db'], $GLOBALS['table']); + if ($GLOBALS['mime_map'] === null) { + $GLOBALS['mime_map'] = []; } - $query_fields = []; - $insert_errors = []; - $row_skipped = false; - $unsaved_values = []; - foreach ($loop_array as $rownumber => $where_clause) { + $GLOBALS['query_fields'] = []; + $GLOBALS['insert_errors'] = []; + $GLOBALS['row_skipped'] = false; + $GLOBALS['unsaved_values'] = []; + foreach ($GLOBALS['loop_array'] as $rownumber => $where_clause) { // skip fields to be ignored - if (! $using_key && isset($_POST['insert_ignore_' . $where_clause])) { + if (! $GLOBALS['using_key'] && isset($_POST['insert_ignore_' . $where_clause])) { continue; } // Defines the SET part of the sql query - $query_values = []; + $GLOBALS['query_values'] = []; // Map multi-edit keys to single-level arrays, dependent on how we got the fields $multi_edit_columns = $_POST['fields']['multi_edit'][$rownumber] ?? []; @@ -272,16 +265,19 @@ final class ReplaceController extends AbstractController } // Apply Input Transformation if defined - if (! empty($mime_map[$column_name]) && ! empty($mime_map[$column_name]['input_transformation'])) { + if ( + ! empty($GLOBALS['mime_map'][$column_name]) + && ! empty($GLOBALS['mime_map'][$column_name]['input_transformation']) + ) { $filename = 'libraries/classes/Plugins/Transformations/' - . $mime_map[$column_name]['input_transformation']; + . $GLOBALS['mime_map'][$column_name]['input_transformation']; if (is_file(ROOT_PATH . $filename)) { $classname = $this->transformations->getClassName($filename); if (class_exists($classname)) { /** @var IOTransformationsPlugin $transformation_plugin */ $transformation_plugin = new $classname(); $transformation_options = $this->transformations->getOptions( - $mime_map[$column_name]['input_transformation_options'] + $GLOBALS['mime_map'][$column_name]['input_transformation_options'] ); $current_value = $transformation_plugin->applyTransformation( $current_value, @@ -294,8 +290,8 @@ final class ReplaceController extends AbstractController && ! $transformation_plugin->isSuccess() ) { $insert_fail = true; - $row_skipped = true; - $insert_errors[] = sprintf( + $GLOBALS['row_skipped'] = true; + $GLOBALS['insert_errors'][] = sprintf( __('Row: %1$s, Column: %2$s, Error: %3$s'), $rownumber, $column_name, @@ -307,7 +303,7 @@ final class ReplaceController extends AbstractController } if ($file_to_insert->isError()) { - $insert_errors[] = $file_to_insert->getError(); + $GLOBALS['insert_errors'][] = $file_to_insert->getError(); } // delete $file_to_insert temporary variable @@ -323,39 +319,39 @@ final class ReplaceController extends AbstractController $multi_edit_columns_name, $multi_edit_columns_null, $multi_edit_columns_null_prev, - $is_insert, - $using_key, + $GLOBALS['is_insert'], + $GLOBALS['using_key'], $where_clause, - $table, + $GLOBALS['table'], $multi_edit_funcs ); $current_value_as_an_array = $this->insertEdit->getCurrentValueAsAnArrayForMultipleEdit( $multi_edit_funcs, $multi_edit_salt, - $gis_from_text_functions, + $GLOBALS['gis_from_text_functions'], $current_value, - $gis_from_wkb_functions, - $func_optional_param, - $func_no_param, + $GLOBALS['gis_from_wkb_functions'], + $GLOBALS['func_optional_param'], + $GLOBALS['func_no_param'], $key ); if (! isset($multi_edit_virtual, $multi_edit_virtual[$key])) { [ - $query_values, - $query_fields, + $GLOBALS['query_values'], + $GLOBALS['query_fields'], ] = $this->insertEdit->getQueryValuesForInsertAndUpdateInMultipleEdit( $multi_edit_columns_name, $multi_edit_columns_null, $current_value, $multi_edit_columns_prev, $multi_edit_funcs, - $is_insert, - $query_values, - $query_fields, + $GLOBALS['is_insert'], + $GLOBALS['query_values'], + $GLOBALS['query_fields'], $current_value_as_an_array, - $value_sets, + $GLOBALS['value_sets'], $key, $multi_edit_columns_null_prev ); @@ -371,20 +367,20 @@ final class ReplaceController extends AbstractController // temporarily store rows not inserted // so that they can be populated again. if ($insert_fail) { - $unsaved_values[$rownumber] = $multi_edit_columns; + $GLOBALS['unsaved_values'][$rownumber] = $multi_edit_columns; } - if ($insert_fail || count($query_values) <= 0) { + if ($insert_fail || count($GLOBALS['query_values']) <= 0) { continue; } - if ($is_insert) { - $value_sets[] = implode(', ', $query_values); + if ($GLOBALS['is_insert']) { + $GLOBALS['value_sets'][] = implode(', ', $GLOBALS['query_values']); } else { // build update query $clauseIsUnique = $_POST['clause_is_unique'] ?? '';// Should contain 0 or 1 - $query[] = 'UPDATE ' . Util::backquote($table) - . ' SET ' . implode(', ', $query_values) + $GLOBALS['query'][] = 'UPDATE ' . Util::backquote($GLOBALS['table']) + . ' SET ' . implode(', ', $GLOBALS['query_values']) . ' WHERE ' . $where_clause . ($clauseIsUnique ? '' : ' LIMIT 1'); } @@ -396,76 +392,80 @@ final class ReplaceController extends AbstractController $multi_edit_funcs, $multi_edit_columns_type, $multi_edit_columns_null, - $func_no_param, + $GLOBALS['func_no_param'], $multi_edit_auto_increment, $current_value_as_an_array, $key, $current_value, - $loop_array, + $GLOBALS['loop_array'], $where_clause, - $using_key, + $GLOBALS['using_key'], $multi_edit_columns_null_prev, $insert_fail ); // Builds the sql query - if ($is_insert && count($value_sets) > 0) { - $query = $this->insertEdit->buildSqlQuery($is_insertignore, $query_fields, $value_sets); - } elseif (empty($query) && ! isset($_POST['preview_sql']) && ! $row_skipped) { + if ($GLOBALS['is_insert'] && count($GLOBALS['value_sets']) > 0) { + $GLOBALS['query'] = $this->insertEdit->buildSqlQuery( + $GLOBALS['is_insertignore'], + $GLOBALS['query_fields'], + $GLOBALS['value_sets'] + ); + } elseif (empty($GLOBALS['query']) && ! isset($_POST['preview_sql']) && ! $GLOBALS['row_skipped']) { // No change -> move back to the calling script // // Note: logic passes here for inline edit - $message = Message::success(__('No change')); + $GLOBALS['message'] = Message::success(__('No change')); // Avoid infinite recursion - if ($goto_include === '/table/replace') { - $goto_include = '/table/change'; + if ($GLOBALS['goto_include'] === '/table/replace') { + $GLOBALS['goto_include'] = '/table/change'; } - $active_page = $goto_include; + $GLOBALS['active_page'] = $GLOBALS['goto_include']; - if ($goto_include === '/sql') { + if ($GLOBALS['goto_include'] === '/sql') { /** @var SqlController $controller */ - $controller = $containerBuilder->get(SqlController::class); + $controller = $GLOBALS['containerBuilder']->get(SqlController::class); $controller(); return; } - if ($goto_include === '/database/sql') { + if ($GLOBALS['goto_include'] === '/database/sql') { /** @var DatabaseSqlController $controller */ - $controller = $containerBuilder->get(DatabaseSqlController::class); + $controller = $GLOBALS['containerBuilder']->get(DatabaseSqlController::class); $controller(); return; } - if ($goto_include === '/table/change') { + if ($GLOBALS['goto_include'] === '/table/change') { /** @var ChangeController $controller */ - $controller = $containerBuilder->get(ChangeController::class); + $controller = $GLOBALS['containerBuilder']->get(ChangeController::class); $controller(); return; } - if ($goto_include === '/table/sql') { + if ($GLOBALS['goto_include'] === '/table/sql') { /** @var TableSqlController $controller */ - $controller = $containerBuilder->get(TableSqlController::class); + $controller = $GLOBALS['containerBuilder']->get(TableSqlController::class); $controller(); return; } /** @psalm-suppress UnresolvableInclude */ - include ROOT_PATH . Core::securePath($goto_include); + include ROOT_PATH . Core::securePath($GLOBALS['goto_include']); return; } - unset($multi_edit_columns, $is_insertignore); + unset($multi_edit_columns, $GLOBALS['is_insertignore']); // If there is a request for SQL previewing. if (isset($_POST['preview_sql'])) { - Core::previewSQL($query); + Core::previewSQL($GLOBALS['query']); return; } @@ -475,46 +475,46 @@ final class ReplaceController extends AbstractController * page */ [ - $urlParams, - $total_affected_rows, - $last_messages, - $warning_messages, - $error_messages, - $return_to_sql_query, - ] = $this->insertEdit->executeSqlQuery($urlParams, $query); + $GLOBALS['urlParams'], + $GLOBALS['total_affected_rows'], + $GLOBALS['last_messages'], + $GLOBALS['warning_messages'], + $GLOBALS['error_messages'], + $GLOBALS['return_to_sql_query'], + ] = $this->insertEdit->executeSqlQuery($GLOBALS['urlParams'], $GLOBALS['query']); - if ($is_insert && (count($value_sets) > 0 || $row_skipped)) { - $message = Message::getMessageForInsertedRows($total_affected_rows); - $unsaved_values = array_values($unsaved_values); + if ($GLOBALS['is_insert'] && (count($GLOBALS['value_sets']) > 0 || $GLOBALS['row_skipped'])) { + $GLOBALS['message'] = Message::getMessageForInsertedRows($GLOBALS['total_affected_rows']); + $GLOBALS['unsaved_values'] = array_values($GLOBALS['unsaved_values']); } else { - $message = Message::getMessageForAffectedRows($total_affected_rows); + $GLOBALS['message'] = Message::getMessageForAffectedRows($GLOBALS['total_affected_rows']); } - if ($row_skipped) { - $goto_include = '/table/change'; - $message->addMessagesString($insert_errors, '
'); - $message->isError(true); + if ($GLOBALS['row_skipped']) { + $GLOBALS['goto_include'] = '/table/change'; + $GLOBALS['message']->addMessagesString($GLOBALS['insert_errors'], '
'); + $GLOBALS['message']->isError(true); } - $message->addMessages($last_messages, '
'); + $GLOBALS['message']->addMessages($GLOBALS['last_messages'], '
'); - if (! empty($warning_messages)) { - $message->addMessagesString($warning_messages, '
'); - $message->isError(true); + if (! empty($GLOBALS['warning_messages'])) { + $GLOBALS['message']->addMessagesString($GLOBALS['warning_messages'], '
'); + $GLOBALS['message']->isError(true); } - if (! empty($error_messages)) { - $message->addMessagesString($error_messages); - $message->isError(true); + if (! empty($GLOBALS['error_messages'])) { + $GLOBALS['message']->addMessagesString($GLOBALS['error_messages']); + $GLOBALS['message']->isError(true); } unset( - $error_messages, - $warning_messages, - $total_affected_rows, - $last_messages, - $row_skipped, - $insert_errors + $GLOBALS['error_messages'], + $GLOBALS['warning_messages'], + $GLOBALS['total_affected_rows'], + $GLOBALS['last_messages'], + $GLOBALS['row_skipped'], + $GLOBALS['insert_errors'] ); /** @@ -530,7 +530,7 @@ final class ReplaceController extends AbstractController * link/transformed value and exit */ if (isset($_POST['rel_fields_list']) && $_POST['rel_fields_list'] != '') { - $map = $this->relation->getForeigners($db, $table, '', 'both'); + $map = $this->relation->getForeigners($GLOBALS['db'], $GLOBALS['table'], '', 'both'); /** @var array $relation_fields */ $relation_fields = []; @@ -569,13 +569,13 @@ final class ReplaceController extends AbstractController 'input_transformation', 'transformation', ]; - foreach ($mime_map as $transformation) { + foreach ($GLOBALS['mime_map'] as $transformation) { $column_name = $transformation['column_name']; foreach ($transformation_types as $type) { $file = Core::securePath($transformation[$type]); $extra_data = $this->insertEdit->transformEditedValues( - $db, - $table, + $GLOBALS['db'], + $GLOBALS['table'], $transformation, $edited_values, $file, @@ -592,8 +592,8 @@ final class ReplaceController extends AbstractController $column_name = $_POST['fields_name']['multi_edit'][0][0]; $this->insertEdit->verifyWhetherValueCanBeTruncatedAndAppendExtraData( - $db, - $table, + $GLOBALS['db'], + $GLOBALS['table'], $column_name, $extra_data ); @@ -602,25 +602,25 @@ final class ReplaceController extends AbstractController $_table = new Table($_POST['table'], $_POST['db']); $extra_data['row_count'] = $_table->countRecords(); - $extra_data['sql_query'] = Generator::getMessage($message, $GLOBALS['display_query']); + $extra_data['sql_query'] = Generator::getMessage($GLOBALS['message'], $GLOBALS['display_query']); - $this->response->setRequestStatus($message->isSuccess()); - $this->response->addJSON('message', $message); + $this->response->setRequestStatus($GLOBALS['message']->isSuccess()); + $this->response->addJSON('message', $GLOBALS['message']); $this->response->addJSON($extra_data); return; } - if (! empty($return_to_sql_query)) { - $disp_query = $GLOBALS['sql_query']; - $disp_message = $message; - unset($message); - $GLOBALS['sql_query'] = $return_to_sql_query; + if (! empty($GLOBALS['return_to_sql_query'])) { + $GLOBALS['disp_query'] = $GLOBALS['sql_query']; + $GLOBALS['disp_message'] = $GLOBALS['message']; + unset($GLOBALS['message']); + $GLOBALS['sql_query'] = $GLOBALS['return_to_sql_query']; } $this->addScriptFiles(['vendor/jquery/additional-methods.js', 'table/change.js']); - $active_page = $goto_include; + $GLOBALS['active_page'] = $GLOBALS['goto_include']; /** * If user asked for "and then Insert another new row" we have to remove @@ -631,33 +631,33 @@ final class ReplaceController extends AbstractController unset($_POST['where_clause']); } - if ($goto_include === '/sql') { + if ($GLOBALS['goto_include'] === '/sql') { /** @var SqlController $controller */ - $controller = $containerBuilder->get(SqlController::class); + $controller = $GLOBALS['containerBuilder']->get(SqlController::class); $controller(); return; } - if ($goto_include === '/database/sql') { + if ($GLOBALS['goto_include'] === '/database/sql') { /** @var DatabaseSqlController $controller */ - $controller = $containerBuilder->get(DatabaseSqlController::class); + $controller = $GLOBALS['containerBuilder']->get(DatabaseSqlController::class); $controller(); return; } - if ($goto_include === '/table/change') { + if ($GLOBALS['goto_include'] === '/table/change') { /** @var ChangeController $controller */ - $controller = $containerBuilder->get(ChangeController::class); + $controller = $GLOBALS['containerBuilder']->get(ChangeController::class); $controller(); return; } - if ($goto_include === '/table/sql') { + if ($GLOBALS['goto_include'] === '/table/sql') { /** @var TableSqlController $controller */ - $controller = $containerBuilder->get(TableSqlController::class); + $controller = $GLOBALS['containerBuilder']->get(TableSqlController::class); $controller(); return; @@ -667,6 +667,6 @@ final class ReplaceController extends AbstractController * Load target page. */ /** @psalm-suppress UnresolvableInclude */ - require ROOT_PATH . Core::securePath($goto_include); + require ROOT_PATH . Core::securePath($GLOBALS['goto_include']); } } diff --git a/libraries/classes/Controllers/Table/SearchController.php b/libraries/classes/Controllers/Table/SearchController.php index 6db60aa478..78c2600072 100644 --- a/libraries/classes/Controllers/Table/SearchController.php +++ b/libraries/classes/Controllers/Table/SearchController.php @@ -171,15 +171,13 @@ class SearchController extends AbstractController */ public function __invoke(): void { - global $db, $table, $urlParams, $cfg, $errorUrl; - Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); $this->addScriptFiles([ 'makegrid.js', @@ -283,23 +281,21 @@ class SearchController extends AbstractController */ public function displaySelectionFormAction(): void { - global $goto, $cfg; - - if (! isset($goto)) { - $goto = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); + if (! isset($GLOBALS['goto'])) { + $GLOBALS['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); } $this->render('table/search/index', [ 'db' => $GLOBALS['db'], 'table' => $GLOBALS['table'], - 'goto' => $goto, + 'goto' => $GLOBALS['goto'], 'self' => $this, 'geom_column_flag' => $this->geomColumnFlag, 'column_names' => $this->columnNames, 'column_types' => $this->columnTypes, 'column_collations' => $this->columnCollations, - 'default_sliders_state' => $cfg['InitialSlidersState'], - 'max_rows' => intval($cfg['MaxRows']), + 'default_sliders_state' => $GLOBALS['cfg']['InitialSlidersState'], + 'max_rows' => intval($GLOBALS['cfg']['MaxRows']), ]); } diff --git a/libraries/classes/Controllers/Table/SqlController.php b/libraries/classes/Controllers/Table/SqlController.php index 7692c38dad..6affce9777 100644 --- a/libraries/classes/Controllers/Table/SqlController.php +++ b/libraries/classes/Controllers/Table/SqlController.php @@ -34,8 +34,6 @@ final class SqlController extends AbstractController public function __invoke(): void { - global $errorUrl, $goto, $back, $db, $table, $cfg; - $this->addScriptFiles([ 'makegrid.js', 'vendor/jquery/jquery.uitablefilter.js', @@ -49,22 +47,22 @@ final class SqlController extends AbstractController Util::checkParameters(['db', 'table']); - $url_params = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($url_params, '&'); + $url_params = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($url_params, '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); /** * After a syntax error, we return to this script * with the typed query in the textarea. */ - $goto = Url::getFromRoute('/table/sql'); - $back = Url::getFromRoute('/table/sql'); + $GLOBALS['goto'] = Url::getFromRoute('/table/sql'); + $GLOBALS['back'] = Url::getFromRoute('/table/sql'); $this->response->addHTML($this->sqlQueryForm->getHtml( - $db, - $table, + $GLOBALS['db'], + $GLOBALS['table'], $_GET['sql_query'] ?? true, false, isset($_POST['delimiter']) diff --git a/libraries/classes/Controllers/Table/Structure/AddIndexController.php b/libraries/classes/Controllers/Table/Structure/AddIndexController.php index 4043615b16..1d77f843b8 100644 --- a/libraries/classes/Controllers/Table/Structure/AddIndexController.php +++ b/libraries/classes/Controllers/Table/Structure/AddIndexController.php @@ -36,8 +36,6 @@ final class AddIndexController extends AbstractController public function __invoke(): void { - global $sql_query, $db, $table, $message; - $selected = $_POST['selected_fld'] ?? []; if (empty($selected)) { @@ -49,22 +47,22 @@ final class AddIndexController extends AbstractController $i = 1; $selectedCount = count($selected); - $sql_query = 'ALTER TABLE ' . Util::backquote($table) . ' ADD INDEX('; + $GLOBALS['sql_query'] = 'ALTER TABLE ' . Util::backquote($GLOBALS['table']) . ' ADD INDEX('; foreach ($selected as $field) { - $sql_query .= Util::backquote($field); - $sql_query .= $i++ === $selectedCount ? ');' : ', '; + $GLOBALS['sql_query'] .= Util::backquote($field); + $GLOBALS['sql_query'] .= $i++ === $selectedCount ? ');' : ', '; } - $this->dbi->selectDb($db); - $result = $this->dbi->tryQuery($sql_query); + $this->dbi->selectDb($GLOBALS['db']); + $result = $this->dbi->tryQuery($GLOBALS['sql_query']); if (! $result) { - $message = Message::error($this->dbi->getError()); + $GLOBALS['message'] = Message::error($this->dbi->getError()); } - if (empty($message)) { - $message = Message::success(); + if (empty($GLOBALS['message'])) { + $GLOBALS['message'] = Message::success(); } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Table/Structure/AddKeyController.php b/libraries/classes/Controllers/Table/Structure/AddKeyController.php index 6f3bd865d9..6af11eaa90 100644 --- a/libraries/classes/Controllers/Table/Structure/AddKeyController.php +++ b/libraries/classes/Controllers/Table/Structure/AddKeyController.php @@ -31,11 +31,9 @@ final class AddKeyController extends AbstractController public function __invoke(): void { - global $reload; - ($this->sqlController)(); - $reload = true; + $GLOBALS['reload'] = true; ($this->structureController)(); } diff --git a/libraries/classes/Controllers/Table/Structure/CentralColumnsAddController.php b/libraries/classes/Controllers/Table/Structure/CentralColumnsAddController.php index f2581b155b..40d87ff59a 100644 --- a/libraries/classes/Controllers/Table/Structure/CentralColumnsAddController.php +++ b/libraries/classes/Controllers/Table/Structure/CentralColumnsAddController.php @@ -34,8 +34,6 @@ final class CentralColumnsAddController extends AbstractController public function __invoke(): void { - global $message; - $selected = $_POST['selected_fld'] ?? []; if (empty($selected)) { @@ -48,11 +46,11 @@ final class CentralColumnsAddController extends AbstractController $centralColsError = $this->centralColumns->syncUniqueColumns($selected, false); if ($centralColsError instanceof Message) { - $message = $centralColsError; + $GLOBALS['message'] = $centralColsError; } - if (empty($message)) { - $message = Message::success(); + if (empty($GLOBALS['message'])) { + $GLOBALS['message'] = Message::success(); } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Table/Structure/CentralColumnsRemoveController.php b/libraries/classes/Controllers/Table/Structure/CentralColumnsRemoveController.php index 12e32e6266..5a1f59daed 100644 --- a/libraries/classes/Controllers/Table/Structure/CentralColumnsRemoveController.php +++ b/libraries/classes/Controllers/Table/Structure/CentralColumnsRemoveController.php @@ -34,8 +34,6 @@ final class CentralColumnsRemoveController extends AbstractController public function __invoke(): void { - global $db, $message; - $selected = $_POST['selected_fld'] ?? []; if (empty($selected)) { @@ -45,14 +43,14 @@ final class CentralColumnsRemoveController extends AbstractController return; } - $centralColsError = $this->centralColumns->deleteColumnsFromList($db, $selected, false); + $centralColsError = $this->centralColumns->deleteColumnsFromList($GLOBALS['db'], $selected, false); if ($centralColsError instanceof Message) { - $message = $centralColsError; + $GLOBALS['message'] = $centralColsError; } - if (empty($message)) { - $message = Message::success(); + if (empty($GLOBALS['message'])) { + $GLOBALS['message'] = Message::success(); } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Table/Structure/ChangeController.php b/libraries/classes/Controllers/Table/Structure/ChangeController.php index 24799adf67..5dfc76566a 100644 --- a/libraries/classes/Controllers/Table/Structure/ChangeController.php +++ b/libraries/classes/Controllers/Table/Structure/ChangeController.php @@ -61,8 +61,6 @@ final class ChangeController extends AbstractController */ private function displayHtmlForColumnChange(?array $selected): void { - global $num_fields; - if (empty($selected)) { $selected[] = $_REQUEST['field']; $selected_cnt = 1; @@ -87,7 +85,7 @@ final class ChangeController extends AbstractController } } - $num_fields = count($fields_meta); + $GLOBALS['num_fields'] = count($fields_meta); /** * Form for changing properties. @@ -99,7 +97,7 @@ final class ChangeController extends AbstractController $templateData = $this->columnsDefinition->displayForm( '/table/structure/save', - $num_fields, + $GLOBALS['num_fields'], null, $selected, $fields_meta diff --git a/libraries/classes/Controllers/Table/Structure/FulltextController.php b/libraries/classes/Controllers/Table/Structure/FulltextController.php index 92ad724f34..5364482411 100644 --- a/libraries/classes/Controllers/Table/Structure/FulltextController.php +++ b/libraries/classes/Controllers/Table/Structure/FulltextController.php @@ -36,8 +36,6 @@ final class FulltextController extends AbstractController public function __invoke(): void { - global $sql_query, $db, $table, $message; - $selected = $_POST['selected_fld'] ?? []; if (empty($selected)) { @@ -49,22 +47,22 @@ final class FulltextController extends AbstractController $i = 1; $selectedCount = count($selected); - $sql_query = 'ALTER TABLE ' . Util::backquote($table) . ' ADD FULLTEXT('; + $GLOBALS['sql_query'] = 'ALTER TABLE ' . Util::backquote($GLOBALS['table']) . ' ADD FULLTEXT('; foreach ($selected as $field) { - $sql_query .= Util::backquote($field); - $sql_query .= $i++ === $selectedCount ? ');' : ', '; + $GLOBALS['sql_query'] .= Util::backquote($field); + $GLOBALS['sql_query'] .= $i++ === $selectedCount ? ');' : ', '; } - $this->dbi->selectDb($db); - $result = $this->dbi->tryQuery($sql_query); + $this->dbi->selectDb($GLOBALS['db']); + $result = $this->dbi->tryQuery($GLOBALS['sql_query']); if (! $result) { - $message = Message::error($this->dbi->getError()); + $GLOBALS['message'] = Message::error($this->dbi->getError()); } - if (empty($message)) { - $message = Message::success(); + if (empty($GLOBALS['message'])) { + $GLOBALS['message'] = Message::success(); } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Table/Structure/PrimaryController.php b/libraries/classes/Controllers/Table/Structure/PrimaryController.php index e4ad4c1705..a7a6fa5051 100644 --- a/libraries/classes/Controllers/Table/Structure/PrimaryController.php +++ b/libraries/classes/Controllers/Table/Structure/PrimaryController.php @@ -38,8 +38,6 @@ final class PrimaryController extends AbstractController public function __invoke(): void { - global $db, $table, $message, $sql_query, $urlParams, $errorUrl, $cfg; - $selected = $_POST['selected'] ?? []; $selected_fld = $_POST['selected_fld'] ?? []; @@ -62,15 +60,15 @@ final class PrimaryController extends AbstractController if (! empty($selected_fld) && ! empty($primary)) { Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); $this->render('table/structure/primary', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'selected' => $selected_fld, ]); @@ -78,30 +76,30 @@ final class PrimaryController extends AbstractController } if ($mult_btn === __('Yes')) { - $sql_query = 'ALTER TABLE ' . Util::backquote($table); + $GLOBALS['sql_query'] = 'ALTER TABLE ' . Util::backquote($GLOBALS['table']); if (! empty($primary)) { - $sql_query .= ' DROP PRIMARY KEY,'; + $GLOBALS['sql_query'] .= ' DROP PRIMARY KEY,'; } - $sql_query .= ' ADD PRIMARY KEY('; + $GLOBALS['sql_query'] .= ' ADD PRIMARY KEY('; $i = 1; $selectedCount = count($selected); foreach ($selected as $field) { - $sql_query .= Util::backquote($field); - $sql_query .= $i++ === $selectedCount ? ');' : ', '; + $GLOBALS['sql_query'] .= Util::backquote($field); + $GLOBALS['sql_query'] .= $i++ === $selectedCount ? ');' : ', '; } - $this->dbi->selectDb($db); - $result = $this->dbi->tryQuery($sql_query); + $this->dbi->selectDb($GLOBALS['db']); + $result = $this->dbi->tryQuery($GLOBALS['sql_query']); if (! $result) { - $message = Message::error($this->dbi->getError()); + $GLOBALS['message'] = Message::error($this->dbi->getError()); } } - if (empty($message)) { - $message = Message::success(); + if (empty($GLOBALS['message'])) { + $GLOBALS['message'] = Message::success(); } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Table/Structure/SpatialController.php b/libraries/classes/Controllers/Table/Structure/SpatialController.php index 86143932a6..b4527e0fdf 100644 --- a/libraries/classes/Controllers/Table/Structure/SpatialController.php +++ b/libraries/classes/Controllers/Table/Structure/SpatialController.php @@ -36,8 +36,6 @@ final class SpatialController extends AbstractController public function __invoke(): void { - global $sql_query, $db, $table, $message; - $selected = $_POST['selected_fld'] ?? []; if (empty($selected)) { @@ -49,22 +47,22 @@ final class SpatialController extends AbstractController $i = 1; $selectedCount = count($selected); - $sql_query = 'ALTER TABLE ' . Util::backquote($table) . ' ADD SPATIAL('; + $GLOBALS['sql_query'] = 'ALTER TABLE ' . Util::backquote($GLOBALS['table']) . ' ADD SPATIAL('; foreach ($selected as $field) { - $sql_query .= Util::backquote($field); - $sql_query .= $i++ === $selectedCount ? ');' : ', '; + $GLOBALS['sql_query'] .= Util::backquote($field); + $GLOBALS['sql_query'] .= $i++ === $selectedCount ? ');' : ', '; } - $this->dbi->selectDb($db); - $result = $this->dbi->tryQuery($sql_query); + $this->dbi->selectDb($GLOBALS['db']); + $result = $this->dbi->tryQuery($GLOBALS['sql_query']); if (! $result) { - $message = Message::error($this->dbi->getError()); + $GLOBALS['message'] = Message::error($this->dbi->getError()); } - if (empty($message)) { - $message = Message::success(); + if (empty($GLOBALS['message'])) { + $GLOBALS['message'] = Message::success(); } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Table/Structure/UniqueController.php b/libraries/classes/Controllers/Table/Structure/UniqueController.php index 6f6946a0a3..bc6dad9104 100644 --- a/libraries/classes/Controllers/Table/Structure/UniqueController.php +++ b/libraries/classes/Controllers/Table/Structure/UniqueController.php @@ -36,8 +36,6 @@ final class UniqueController extends AbstractController public function __invoke(): void { - global $sql_query, $db, $table, $message; - $selected = $_POST['selected_fld'] ?? []; if (empty($selected)) { @@ -49,22 +47,22 @@ final class UniqueController extends AbstractController $i = 1; $selectedCount = count($selected); - $sql_query = 'ALTER TABLE ' . Util::backquote($table) . ' ADD UNIQUE('; + $GLOBALS['sql_query'] = 'ALTER TABLE ' . Util::backquote($GLOBALS['table']) . ' ADD UNIQUE('; foreach ($selected as $field) { - $sql_query .= Util::backquote($field); - $sql_query .= $i++ === $selectedCount ? ');' : ', '; + $GLOBALS['sql_query'] .= Util::backquote($field); + $GLOBALS['sql_query'] .= $i++ === $selectedCount ? ');' : ', '; } - $this->dbi->selectDb($db); - $result = $this->dbi->tryQuery($sql_query); + $this->dbi->selectDb($GLOBALS['db']); + $result = $this->dbi->tryQuery($GLOBALS['sql_query']); if (! $result) { - $message = Message::error($this->dbi->getError()); + $GLOBALS['message'] = Message::error($this->dbi->getError()); } - if (empty($message)) { - $message = Message::success(); + if (empty($GLOBALS['message'])) { + $GLOBALS['message'] = Message::success(); } ($this->structureController)(); diff --git a/libraries/classes/Controllers/Table/StructureController.php b/libraries/classes/Controllers/Table/StructureController.php index cc4a2d8473..fd99cb9fad 100644 --- a/libraries/classes/Controllers/Table/StructureController.php +++ b/libraries/classes/Controllers/Table/StructureController.php @@ -88,23 +88,23 @@ class StructureController extends AbstractController public function __invoke(): void { - global $reread_info, $showtable, $db, $table, $cfg, $errorUrl; - global $tbl_is_view, $tbl_storage_engine, $tbl_collation, $table_info_num_rows; - $this->dbi->selectDb($GLOBALS['db']); - $reread_info = $this->tableObj->getStatusInfo(null, true); - $showtable = $this->tableObj->getStatusInfo(null, (isset($reread_info) && $reread_info)); + $GLOBALS['reread_info'] = $this->tableObj->getStatusInfo(null, true); + $GLOBALS['showtable'] = $this->tableObj->getStatusInfo( + null, + (isset($GLOBALS['reread_info']) && $GLOBALS['reread_info']) + ); if ($this->tableObj->isView()) { - $tbl_is_view = true; - $tbl_storage_engine = __('View'); + $GLOBALS['tbl_is_view'] = true; + $GLOBALS['tbl_storage_engine'] = __('View'); } else { - $tbl_is_view = false; - $tbl_storage_engine = $this->tableObj->getStorageEngine(); + $GLOBALS['tbl_is_view'] = false; + $GLOBALS['tbl_storage_engine'] = $this->tableObj->getStorageEngine(); } - $tbl_collation = $this->tableObj->getCollation(); - $table_info_num_rows = $this->tableObj->getNumRows(); + $GLOBALS['tbl_collation'] = $this->tableObj->getCollation(); + $GLOBALS['table_info_num_rows'] = $this->tableObj->getNumRows(); $pageSettings = new PageSettings('TableStructure'); $this->response->addHTML($pageSettings->getErrorHTML()); @@ -119,12 +119,12 @@ class StructureController extends AbstractController Util::checkParameters(['db', 'table']); - $isSystemSchema = Utilities::isSystemSchema($db); - $url_params = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($url_params, '&'); + $isSystemSchema = Utilities::isSystemSchema($GLOBALS['db']); + $url_params = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($url_params, '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); $primary = Index::getPrimary($GLOBALS['table'], $GLOBALS['db']); $columns_with_index = $this->dbi @@ -164,8 +164,6 @@ class StructureController extends AbstractController array $columns_with_index, bool $isSystemSchema ) { - global $tbl_is_view, $tbl_storage_engine; - $route = Routing::getCurrentRoute(); // prepare comments @@ -259,9 +257,9 @@ class StructureController extends AbstractController 'db' => $GLOBALS['db'], 'table' => $GLOBALS['table'], 'db_is_system_schema' => $isSystemSchema, - 'tbl_is_view' => $tbl_is_view, + 'tbl_is_view' => $GLOBALS['tbl_is_view'], 'mime_map' => $mime_map, - 'tbl_storage_engine' => $tbl_storage_engine, + 'tbl_storage_engine' => $GLOBALS['tbl_storage_engine'], 'primary' => $primary_index, 'columns_with_unique_index' => $columns_with_unique_index, 'columns_list' => $columns_list, @@ -296,69 +294,70 @@ class StructureController extends AbstractController */ protected function getTableStats(bool $isSystemSchema) { - global $showtable, $tbl_is_view; - global $tbl_storage_engine, $table_info_num_rows, $tbl_collation; - - if (empty($showtable)) { - $showtable = $this->dbi->getTable($GLOBALS['db'], $GLOBALS['table'])->getStatusInfo(null, true); + if (empty($GLOBALS['showtable'])) { + $GLOBALS['showtable'] = $this->dbi->getTable($GLOBALS['db'], $GLOBALS['table'])->getStatusInfo(null, true); } - if (is_string($showtable)) { - $showtable = []; + if (is_string($GLOBALS['showtable'])) { + $GLOBALS['showtable'] = []; } - if (empty($showtable['Data_length'])) { - $showtable['Data_length'] = 0; + if (empty($GLOBALS['showtable']['Data_length'])) { + $GLOBALS['showtable']['Data_length'] = 0; } - if (empty($showtable['Index_length'])) { - $showtable['Index_length'] = 0; + if (empty($GLOBALS['showtable']['Index_length'])) { + $GLOBALS['showtable']['Index_length'] = 0; } - $is_innodb = (isset($showtable['Type']) - && $showtable['Type'] === 'InnoDB'); + $is_innodb = (isset($GLOBALS['showtable']['Type']) + && $GLOBALS['showtable']['Type'] === 'InnoDB'); $mergetable = $this->tableObj->isMerge(); // this is to display for example 261.2 MiB instead of 268k KiB $max_digits = 3; $decimals = 1; - [$data_size, $data_unit] = Util::formatByteDown($showtable['Data_length'], $max_digits, $decimals); + [$data_size, $data_unit] = Util::formatByteDown($GLOBALS['showtable']['Data_length'], $max_digits, $decimals); if ($mergetable === false) { - [$index_size, $index_unit] = Util::formatByteDown($showtable['Index_length'], $max_digits, $decimals); + [$index_size, $index_unit] = Util::formatByteDown( + $GLOBALS['showtable']['Index_length'], + $max_digits, + $decimals + ); } - if (isset($showtable['Data_free'])) { - [$free_size, $free_unit] = Util::formatByteDown($showtable['Data_free'], $max_digits, $decimals); + if (isset($GLOBALS['showtable']['Data_free'])) { + [$free_size, $free_unit] = Util::formatByteDown($GLOBALS['showtable']['Data_free'], $max_digits, $decimals); [$effect_size, $effect_unit] = Util::formatByteDown( - $showtable['Data_length'] - + $showtable['Index_length'] - - $showtable['Data_free'], + $GLOBALS['showtable']['Data_length'] + + $GLOBALS['showtable']['Index_length'] + - $GLOBALS['showtable']['Data_free'], $max_digits, $decimals ); } else { [$effect_size, $effect_unit] = Util::formatByteDown( - $showtable['Data_length'] - + $showtable['Index_length'], + $GLOBALS['showtable']['Data_length'] + + $GLOBALS['showtable']['Index_length'], $max_digits, $decimals ); } [$tot_size, $tot_unit] = Util::formatByteDown( - $showtable['Data_length'] + $showtable['Index_length'], + $GLOBALS['showtable']['Data_length'] + $GLOBALS['showtable']['Index_length'], $max_digits, $decimals ); $avg_size = ''; $avg_unit = ''; - if ($table_info_num_rows > 0) { + if ($GLOBALS['table_info_num_rows'] > 0) { [$avg_size, $avg_unit] = Util::formatByteDown( - ($showtable['Data_length'] - + $showtable['Index_length']) - / $showtable['Rows'], + ($GLOBALS['showtable']['Data_length'] + + $GLOBALS['showtable']['Index_length']) + / $GLOBALS['showtable']['Rows'], 6, 1 ); @@ -369,7 +368,11 @@ class StructureController extends AbstractController $innodb_file_per_table = $innodbEnginePlugin->supportsFilePerTable(); $tableCollation = []; - $collation = Charsets::findCollationByName($this->dbi, $GLOBALS['cfg']['Server']['DisableIS'], $tbl_collation); + $collation = Charsets::findCollationByName( + $this->dbi, + $GLOBALS['cfg']['Server']['DisableIS'], + $GLOBALS['tbl_collation'] + ); if ($collation !== null) { $tableCollation = [ 'name' => $collation->getName(), @@ -380,11 +383,11 @@ class StructureController extends AbstractController return $this->template->render('table/structure/display_table_stats', [ 'db' => $GLOBALS['db'], 'table' => $GLOBALS['table'], - 'showtable' => $showtable, - 'table_info_num_rows' => $table_info_num_rows, - 'tbl_is_view' => $tbl_is_view, + 'showtable' => $GLOBALS['showtable'], + 'table_info_num_rows' => $GLOBALS['table_info_num_rows'], + 'tbl_is_view' => $GLOBALS['tbl_is_view'], 'db_is_system_schema' => $isSystemSchema, - 'tbl_storage_engine' => $tbl_storage_engine, + 'tbl_storage_engine' => $GLOBALS['tbl_storage_engine'], 'table_collation' => $tableCollation, 'is_innodb' => $is_innodb, 'mergetable' => $mergetable, diff --git a/libraries/classes/Controllers/Table/TrackingController.php b/libraries/classes/Controllers/Table/TrackingController.php index 70bbac30e1..62ce85815b 100644 --- a/libraries/classes/Controllers/Table/TrackingController.php +++ b/libraries/classes/Controllers/Table/TrackingController.php @@ -38,21 +38,17 @@ final class TrackingController extends AbstractController public function __invoke(): void { - global $text_dir, $urlParams, $msg, $errorUrl; - global $data, $entries, $filter_ts_from, $filter_ts_to, $filter_users, $selection_schema; - global $selection_data, $selection_both, $db, $table, $cfg; - $this->addScriptFiles(['vendor/jquery/jquery.tablesorter.js', 'table/tracking.js']); define('TABLE_MAY_BE_ABSENT', true); Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); $activeMessage = ''; if ( @@ -63,68 +59,73 @@ final class TrackingController extends AbstractController && ! (isset($_POST['report_export']) && $_POST['export_type'] === 'sqldumpfile') ) { - $msg = Message::notice( + $GLOBALS['msg'] = Message::notice( sprintf( __('Tracking of %s is activated.'), htmlspecialchars($GLOBALS['db'] . '.' . $GLOBALS['table']) ) ); - $activeMessage = $msg->getDisplay(); + $activeMessage = $GLOBALS['msg']->getDisplay(); } - $urlParams['goto'] = Url::getFromRoute('/table/tracking'); - $urlParams['back'] = Url::getFromRoute('/table/tracking'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/table/tracking'); + $GLOBALS['urlParams']['back'] = Url::getFromRoute('/table/tracking'); - $data = []; - $entries = []; - $filter_ts_from = null; - $filter_ts_to = null; - $filter_users = []; - $selection_schema = false; - $selection_data = false; - $selection_both = false; + $GLOBALS['data'] = []; + $GLOBALS['entries'] = []; + $GLOBALS['filter_ts_from'] = null; + $GLOBALS['filter_ts_to'] = null; + $GLOBALS['filter_users'] = []; + $GLOBALS['selection_schema'] = false; + $GLOBALS['selection_data'] = false; + $GLOBALS['selection_both'] = false; // Init vars for tracking report if (isset($_POST['report']) || isset($_POST['report_export'])) { - $data = Tracker::getTrackedData($GLOBALS['db'], $GLOBALS['table'], $_POST['version']); + $GLOBALS['data'] = Tracker::getTrackedData($GLOBALS['db'], $GLOBALS['table'], $_POST['version']); if (! isset($_POST['logtype'])) { $_POST['logtype'] = 'schema_and_data'; } if ($_POST['logtype'] === 'schema') { - $selection_schema = true; + $GLOBALS['selection_schema'] = true; } elseif ($_POST['logtype'] === 'data') { - $selection_data = true; + $GLOBALS['selection_data'] = true; } else { - $selection_both = true; + $GLOBALS['selection_both'] = true; } if (! isset($_POST['date_from'])) { - $_POST['date_from'] = $data['date_from']; + $_POST['date_from'] = $GLOBALS['data']['date_from']; } if (! isset($_POST['date_to'])) { - $_POST['date_to'] = $data['date_to']; + $_POST['date_to'] = $GLOBALS['data']['date_to']; } if (! isset($_POST['users'])) { $_POST['users'] = '*'; } - $filter_ts_from = strtotime($_POST['date_from']); - $filter_ts_to = strtotime($_POST['date_to']); - $filter_users = array_map('trim', explode(',', $_POST['users'])); + $GLOBALS['filter_ts_from'] = strtotime($_POST['date_from']); + $GLOBALS['filter_ts_to'] = strtotime($_POST['date_to']); + $GLOBALS['filter_users'] = array_map('trim', explode(',', $_POST['users'])); } // Prepare export if (isset($_POST['report_export'])) { - $entries = $this->tracking->getEntries($data, (int) $filter_ts_from, (int) $filter_ts_to, $filter_users); + $GLOBALS['entries'] = $this->tracking->getEntries( + $GLOBALS['data'], + (int) $GLOBALS['filter_ts_from'], + (int) $GLOBALS['filter_ts_to'], + $GLOBALS['filter_users'] + ); } // Export as file download if (isset($_POST['report_export']) && $_POST['export_type'] === 'sqldumpfile') { - $this->tracking->exportAsFileDownload($entries); + $this->tracking->exportAsFileDownload($GLOBALS['entries']); } $actionMessage = ''; @@ -132,7 +133,7 @@ final class TrackingController extends AbstractController if (! empty($_POST['selected_versions'])) { if ($_POST['submit_mult'] === 'delete_version') { foreach ($_POST['selected_versions'] as $version) { - $this->tracking->deleteTrackingVersion($db, $table, $version); + $this->tracking->deleteTrackingVersion($GLOBALS['db'], $GLOBALS['table'], $version); } $actionMessage = Message::success( @@ -148,62 +149,75 @@ final class TrackingController extends AbstractController $deleteVersion = ''; if (isset($_POST['submit_delete_version'])) { - $deleteVersion = $this->tracking->deleteTrackingVersion($db, $table, $_POST['version']); + $deleteVersion = $this->tracking->deleteTrackingVersion( + $GLOBALS['db'], + $GLOBALS['table'], + $_POST['version'] + ); } $createVersion = ''; if (isset($_POST['submit_create_version'])) { - $createVersion = $this->tracking->createTrackingVersion($db, $table); + $createVersion = $this->tracking->createTrackingVersion($GLOBALS['db'], $GLOBALS['table']); } $deactivateTracking = ''; if (isset($_POST['toggle_activation']) && $_POST['toggle_activation'] === 'deactivate_now') { - $deactivateTracking = $this->tracking->changeTracking($db, $table, 'deactivate'); + $deactivateTracking = $this->tracking->changeTracking($GLOBALS['db'], $GLOBALS['table'], 'deactivate'); } $activateTracking = ''; if (isset($_POST['toggle_activation']) && $_POST['toggle_activation'] === 'activate_now') { - $activateTracking = $this->tracking->changeTracking($db, $table, 'activate'); + $activateTracking = $this->tracking->changeTracking($GLOBALS['db'], $GLOBALS['table'], 'activate'); } // Export as SQL execution $message = ''; if (isset($_POST['report_export']) && $_POST['export_type'] === 'execution') { - $this->tracking->exportAsSqlExecution($entries); - $msg = Message::success(__('SQL statements executed.')); - $message = $msg->getDisplay(); + $this->tracking->exportAsSqlExecution($GLOBALS['entries']); + $GLOBALS['msg'] = Message::success(__('SQL statements executed.')); + $message = $GLOBALS['msg']->getDisplay(); } $sqlDump = ''; if (isset($_POST['report_export']) && $_POST['export_type'] === 'sqldump') { - $sqlDump = $this->tracking->exportAsSqlDump($db, $table, $entries); + $sqlDump = $this->tracking->exportAsSqlDump($GLOBALS['db'], $GLOBALS['table'], $GLOBALS['entries']); } $schemaSnapshot = ''; if (isset($_POST['snapshot'])) { - $schemaSnapshot = $this->tracking->getHtmlForSchemaSnapshot($urlParams); + $schemaSnapshot = $this->tracking->getHtmlForSchemaSnapshot($GLOBALS['urlParams']); } $trackingReportRows = ''; if (isset($_POST['report']) && (isset($_POST['delete_ddlog']) || isset($_POST['delete_dmlog']))) { - $trackingReportRows = $this->tracking->deleteTrackingReportRows($db, $table, $data); + $trackingReportRows = $this->tracking->deleteTrackingReportRows( + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['data'] + ); } $trackingReport = ''; if (isset($_POST['report']) || isset($_POST['report_export'])) { $trackingReport = $this->tracking->getHtmlForTrackingReport( - $data, - $urlParams, - $selection_schema, - $selection_data, - $selection_both, - (int) $filter_ts_to, - (int) $filter_ts_from, - $filter_users + $GLOBALS['data'], + $GLOBALS['urlParams'], + $GLOBALS['selection_schema'], + $GLOBALS['selection_data'], + $GLOBALS['selection_both'], + (int) $GLOBALS['filter_ts_to'], + (int) $GLOBALS['filter_ts_from'], + $GLOBALS['filter_users'] ); } - $main = $this->tracking->getHtmlForMainPage($db, $table, $urlParams, $text_dir); + $main = $this->tracking->getHtmlForMainPage( + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['urlParams'], + $GLOBALS['text_dir'] + ); $this->render('table/tracking/index', [ 'active_message' => $activeMessage, diff --git a/libraries/classes/Controllers/Table/TriggersController.php b/libraries/classes/Controllers/Table/TriggersController.php index e52614b98a..2a8e859281 100644 --- a/libraries/classes/Controllers/Table/TriggersController.php +++ b/libraries/classes/Controllers/Table/TriggersController.php @@ -35,55 +35,51 @@ class TriggersController extends AbstractController public function __invoke(): void { - global $db, $table, $tables, $num_tables, $total_num_tables, $sub_part; - global $tooltip_truename, $tooltip_aliasname, $pos; - global $errors, $urlParams, $errorUrl, $cfg; - $this->addScriptFiles(['database/triggers.js']); if (! $this->response->isAjax()) { /** * Displays the header and tabs */ - if (! empty($table) && in_array($table, $this->dbi->getTables($db))) { + if (! empty($GLOBALS['table']) && in_array($GLOBALS['table'], $this->dbi->getTables($GLOBALS['db']))) { Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); } else { - $table = ''; + $GLOBALS['table'] = ''; Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } [ - $tables, - $num_tables, - $total_num_tables, - $sub_part,,, - $tooltip_truename, - $tooltip_aliasname, - $pos, - ] = Util::getDbInfo($db, $sub_part ?? ''); + $GLOBALS['tables'], + $GLOBALS['num_tables'], + $GLOBALS['total_num_tables'], + $GLOBALS['sub_part'],,, + $GLOBALS['tooltip_truename'], + $GLOBALS['tooltip_aliasname'], + $GLOBALS['pos'], + ] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part'] ?? ''); } - } elseif (strlen($db) > 0) { - $this->dbi->selectDb($db); + } elseif (strlen($GLOBALS['db']) > 0) { + $this->dbi->selectDb($GLOBALS['db']); } /** * Keep a list of errors that occurred while * processing an 'Add' or 'Edit' operation. */ - $errors = []; + $GLOBALS['errors'] = []; $triggers = new Triggers($this->dbi, $this->template, $this->response); $triggers->main(); diff --git a/libraries/classes/Controllers/Table/ZoomSearchController.php b/libraries/classes/Controllers/Table/ZoomSearchController.php index e0790e752b..a5601a9935 100644 --- a/libraries/classes/Controllers/Table/ZoomSearchController.php +++ b/libraries/classes/Controllers/Table/ZoomSearchController.php @@ -94,15 +94,13 @@ class ZoomSearchController extends AbstractController public function __invoke(): void { - global $goto, $db, $table, $urlParams, $cfg, $errorUrl; - Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); $this->addScriptFiles([ 'vendor/stickyfill.min.js', @@ -160,11 +158,11 @@ class ZoomSearchController extends AbstractController return; } - if (! isset($goto)) { - $goto = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + if (! isset($GLOBALS['goto'])) { + $GLOBALS['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); } - $this->zoomSubmitAction($dataLabel, $goto); + $this->zoomSubmitAction($dataLabel, $GLOBALS['goto']); } /** @@ -227,10 +225,8 @@ class ZoomSearchController extends AbstractController */ public function displaySelectionFormAction($dataLabel = null): void { - global $goto; - - if (! isset($goto)) { - $goto = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + if (! isset($GLOBALS['goto'])) { + $GLOBALS['goto'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); } $column_names = $this->columnNames; @@ -251,7 +247,7 @@ class ZoomSearchController extends AbstractController $this->render('table/zoom_search/index', [ 'db' => $GLOBALS['db'], 'table' => $GLOBALS['table'], - 'goto' => $goto, + 'goto' => $GLOBALS['goto'], 'self' => $this, 'geom_column_flag' => $this->geomColumnFlag, 'column_names' => $column_names, diff --git a/libraries/classes/Controllers/ThemeSetController.php b/libraries/classes/Controllers/ThemeSetController.php index 90ad6ecbbb..aa81588c96 100644 --- a/libraries/classes/Controllers/ThemeSetController.php +++ b/libraries/classes/Controllers/ThemeSetController.php @@ -23,9 +23,7 @@ final class ThemeSetController extends AbstractController public function __invoke(): void { - global $cfg; - - if (! $cfg['ThemeManager'] || ! isset($_POST['set_theme'])) { + if (! $GLOBALS['cfg']['ThemeManager'] || ! isset($_POST['set_theme'])) { $this->response->header('Location: index.php?route=/' . Url::getCommonRaw([], '&')); return; diff --git a/libraries/classes/Controllers/Transformation/WrapperController.php b/libraries/classes/Controllers/Transformation/WrapperController.php index 72ed7f0b33..caf128d010 100644 --- a/libraries/classes/Controllers/Transformation/WrapperController.php +++ b/libraries/classes/Controllers/Transformation/WrapperController.php @@ -54,36 +54,32 @@ class WrapperController extends AbstractController public function __invoke(): void { - global $cn, $db, $table, $transform_key, $request_params, $size_params, $where_clause, $row; - global $default_ct, $mime_map, $mime_options, $ct, $mime_type, $srcImage, $srcWidth, $srcHeight; - global $ratioWidth, $ratioHeight, $destWidth, $destHeight, $destImage; - define('IS_TRANSFORMATION_WRAPPER', true); $relationParameters = $this->relation->getRelationParameters(); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); /** * Sets globals from $_REQUEST */ - $request_params = [ + $GLOBALS['request_params'] = [ 'cn', 'ct', 'sql_query', 'transform_key', 'where_clause', ]; - $size_params = [ + $GLOBALS['size_params'] = [ 'newHeight', 'newWidth', ]; - foreach ($request_params as $one_request_param) { + foreach ($GLOBALS['request_params'] as $one_request_param) { if (! isset($_REQUEST[$one_request_param])) { continue; } - if (in_array($one_request_param, $size_params)) { + if (in_array($one_request_param, $GLOBALS['size_params'])) { $GLOBALS[$one_request_param] = intval($_REQUEST[$one_request_param]); if ($GLOBALS[$one_request_param] > 2000) { $GLOBALS[$one_request_param] = 2000; @@ -96,9 +92,9 @@ class WrapperController extends AbstractController /** * Get the list of the fields of the current table */ - $this->dbi->selectDb($db); - if (isset($where_clause)) { - if (! Core::checkSqlQuerySignature($where_clause, $_GET['where_clause_sign'] ?? '')) { + $this->dbi->selectDb($GLOBALS['db']); + if (isset($GLOBALS['where_clause'])) { + if (! Core::checkSqlQuerySignature($GLOBALS['where_clause'], $_GET['where_clause_sign'] ?? '')) { /* l10n: In case a SQL query did not pass a security check */ Core::fatalError(__('There is an issue with your request.')); @@ -106,94 +102,94 @@ class WrapperController extends AbstractController } $result = $this->dbi->query( - 'SELECT * FROM ' . Util::backquote($table) - . ' WHERE ' . $where_clause . ';' + 'SELECT * FROM ' . Util::backquote($GLOBALS['table']) + . ' WHERE ' . $GLOBALS['where_clause'] . ';' ); - $row = $result->fetchAssoc(); + $GLOBALS['row'] = $result->fetchAssoc(); } else { $result = $this->dbi->query( - 'SELECT * FROM ' . Util::backquote($table) . ' LIMIT 1;' + 'SELECT * FROM ' . Util::backquote($GLOBALS['table']) . ' LIMIT 1;' ); - $row = $result->fetchAssoc(); + $GLOBALS['row'] = $result->fetchAssoc(); } // No row returned - if ($row === []) { + if ($GLOBALS['row'] === []) { return; } - $default_ct = 'application/octet-stream'; + $GLOBALS['default_ct'] = 'application/octet-stream'; if ( $relationParameters->columnCommentsFeature !== null && $relationParameters->browserTransformationFeature !== null ) { - $mime_map = $this->transformations->getMime($db, $table) ?? []; + $GLOBALS['mime_map'] = $this->transformations->getMime($GLOBALS['db'], $GLOBALS['table']) ?? []; - $mime_options = $this->transformations->getOptions( - $mime_map[$transform_key]['transformation_options'] ?? '' + $GLOBALS['mime_options'] = $this->transformations->getOptions( + $GLOBALS['mime_map'][$GLOBALS['transform_key']]['transformation_options'] ?? '' ); - foreach ($mime_options as $option) { + foreach ($GLOBALS['mime_options'] as $option) { if (substr($option, 0, 10) !== '; charset=') { continue; } - $mime_options['charset'] = $option; + $GLOBALS['mime_options']['charset'] = $option; } } $this->response->getHeader()->sendHttpHeaders(); // [MIME] - if (isset($ct) && ! empty($ct)) { - $mime_type = $ct; + if (isset($GLOBALS['ct']) && ! empty($GLOBALS['ct'])) { + $GLOBALS['mime_type'] = $GLOBALS['ct']; } else { - $mime_type = (! empty($mime_map[$transform_key]['mimetype']) - ? str_replace('_', '/', $mime_map[$transform_key]['mimetype']) - : $default_ct) - . ($mime_options['charset'] ?? ''); + $GLOBALS['mime_type'] = (! empty($GLOBALS['mime_map'][$GLOBALS['transform_key']]['mimetype']) + ? str_replace('_', '/', $GLOBALS['mime_map'][$GLOBALS['transform_key']]['mimetype']) + : $GLOBALS['default_ct']) + . ($GLOBALS['mime_options']['charset'] ?? ''); } - Core::downloadHeader($cn ?? '', $mime_type); + Core::downloadHeader($GLOBALS['cn'] ?? '', $GLOBALS['mime_type']); if (! isset($_REQUEST['resize'])) { - if (stripos($mime_type, 'html') === false) { - echo $row[$transform_key]; + if (stripos($GLOBALS['mime_type'], 'html') === false) { + echo $GLOBALS['row'][$GLOBALS['transform_key']]; } else { - echo htmlspecialchars($row[$transform_key]); + echo htmlspecialchars($GLOBALS['row'][$GLOBALS['transform_key']]); } } else { // if image_*__inline.inc.php finds that we can resize, // it sets the resize parameter to jpeg or png - $srcImage = ImageWrapper::fromString($row[$transform_key]); - if ($srcImage === null) { + $GLOBALS['srcImage'] = ImageWrapper::fromString($GLOBALS['row'][$GLOBALS['transform_key']]); + if ($GLOBALS['srcImage'] === null) { return; } - $srcWidth = $srcImage->width(); - $srcHeight = $srcImage->height(); + $GLOBALS['srcWidth'] = $GLOBALS['srcImage']->width(); + $GLOBALS['srcHeight'] = $GLOBALS['srcImage']->height(); // Check to see if the width > height or if width < height // if so adjust accordingly to make sure the image // stays smaller than the new width and new height - $ratioWidth = $srcWidth / $_REQUEST['newWidth']; - $ratioHeight = $srcHeight / $_REQUEST['newHeight']; + $GLOBALS['ratioWidth'] = $GLOBALS['srcWidth'] / $_REQUEST['newWidth']; + $GLOBALS['ratioHeight'] = $GLOBALS['srcHeight'] / $_REQUEST['newHeight']; - if ($ratioWidth < $ratioHeight) { - $destWidth = intval(round($srcWidth / $ratioHeight)); - $destHeight = intval($_REQUEST['newHeight']); + if ($GLOBALS['ratioWidth'] < $GLOBALS['ratioHeight']) { + $GLOBALS['destWidth'] = intval(round($GLOBALS['srcWidth'] / $GLOBALS['ratioHeight'])); + $GLOBALS['destHeight'] = intval($_REQUEST['newHeight']); } else { - $destWidth = intval($_REQUEST['newWidth']); - $destHeight = intval(round($srcHeight / $ratioWidth)); + $GLOBALS['destWidth'] = intval($_REQUEST['newWidth']); + $GLOBALS['destHeight'] = intval(round($GLOBALS['srcHeight'] / $GLOBALS['ratioWidth'])); } if ($_REQUEST['resize']) { - $destImage = ImageWrapper::create($destWidth, $destHeight); - if ($destImage === null) { - $srcImage->destroy(); + $GLOBALS['destImage'] = ImageWrapper::create($GLOBALS['destWidth'], $GLOBALS['destHeight']); + if ($GLOBALS['destImage'] === null) { + $GLOBALS['srcImage']->destroy(); return; } @@ -201,19 +197,29 @@ class WrapperController extends AbstractController // ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, // $destWidth, $destHeight, $srcWidth, $srcHeight); // better quality but slower: - $destImage->copyResampled($srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight); + $GLOBALS['destImage']->copyResampled( + $GLOBALS['srcImage'], + 0, + 0, + 0, + 0, + $GLOBALS['destWidth'], + $GLOBALS['destHeight'], + $GLOBALS['srcWidth'], + $GLOBALS['srcHeight'] + ); if ($_REQUEST['resize'] === 'jpeg') { - $destImage->jpeg(null, 75); + $GLOBALS['destImage']->jpeg(null, 75); } if ($_REQUEST['resize'] === 'png') { - $destImage->png(); + $GLOBALS['destImage']->png(); } - $destImage->destroy(); + $GLOBALS['destImage']->destroy(); } - $srcImage->destroy(); + $GLOBALS['srcImage']->destroy(); } } } diff --git a/libraries/classes/Controllers/UserPasswordController.php b/libraries/classes/Controllers/UserPasswordController.php index e8a14170a6..aa2cc1d6ba 100644 --- a/libraries/classes/Controllers/UserPasswordController.php +++ b/libraries/classes/Controllers/UserPasswordController.php @@ -37,19 +37,17 @@ class UserPasswordController extends AbstractController public function __invoke(): void { - global $cfg, $hostname, $username, $password, $change_password_message, $msg; - $this->addScriptFiles(['server/privileges.js', 'vendor/zxcvbn-ts.js']); /** * Displays an error message and exits if the user isn't allowed to use this * script */ - if (! $cfg['ShowChgPassword']) { - $cfg['ShowChgPassword'] = $this->dbi->selectDb('mysql'); + if (! $GLOBALS['cfg']['ShowChgPassword']) { + $GLOBALS['cfg']['ShowChgPassword'] = $this->dbi->selectDb('mysql'); } - if ($cfg['Server']['auth_type'] === 'config' || ! $cfg['ShowChgPassword']) { + if ($GLOBALS['cfg']['Server']['auth_type'] === 'config' || ! $GLOBALS['cfg']['ShowChgPassword']) { $this->response->addHTML(Message::error( __('You don\'t have sufficient privileges to be here right now!') )->getDisplay()); @@ -63,33 +61,37 @@ class UserPasswordController extends AbstractController */ if (isset($_POST['nopass'])) { if ($_POST['nopass'] == '1') { - $password = ''; + $GLOBALS['password'] = ''; } else { - $password = $_POST['pma_pw']; + $GLOBALS['password'] = $_POST['pma_pw']; } - $change_password_message = $this->userPassword->setChangePasswordMsg(); - $msg = $change_password_message['msg']; + $GLOBALS['change_password_message'] = $this->userPassword->setChangePasswordMsg(); + $GLOBALS['msg'] = $GLOBALS['change_password_message']['msg']; - if (! $change_password_message['error']) { - $sql_query = $this->userPassword->changePassword($password); + if (! $GLOBALS['change_password_message']['error']) { + $sql_query = $this->userPassword->changePassword($GLOBALS['password']); if ($this->response->isAjax()) { - $sql_query = Generator::getMessage($change_password_message['msg'], $sql_query, 'success'); + $sql_query = Generator::getMessage( + $GLOBALS['change_password_message']['msg'], + $sql_query, + 'success' + ); $this->response->addJSON('message', $sql_query); return; } $this->response->addHTML('

' . __('Change password') . '

' . "\n\n"); - $this->response->addHTML(Generator::getMessage($msg, $sql_query, 'success')); + $this->response->addHTML(Generator::getMessage($GLOBALS['msg'], $sql_query, 'success')); $this->render('user_password'); return; } if ($this->response->isAjax()) { - $this->response->addJSON('message', $change_password_message['msg']); + $this->response->addJSON('message', $GLOBALS['change_password_message']['msg']); $this->response->setRequestStatus(false); return; @@ -102,10 +104,13 @@ class UserPasswordController extends AbstractController */ // Displays an error message if required - if (isset($msg)) { - $this->response->addHTML($msg->getDisplay()); + if (isset($GLOBALS['msg'])) { + $this->response->addHTML($GLOBALS['msg']->getDisplay()); } - $this->response->addHTML($this->userPassword->getFormForChangePassword($username, $hostname)); + $this->response->addHTML($this->userPassword->getFormForChangePassword( + $GLOBALS['username'], + $GLOBALS['hostname'] + )); } } diff --git a/libraries/classes/Controllers/View/CreateController.php b/libraries/classes/Controllers/View/CreateController.php index e84c7ce806..023a5840eb 100644 --- a/libraries/classes/Controllers/View/CreateController.php +++ b/libraries/classes/Controllers/View/CreateController.php @@ -44,42 +44,38 @@ class CreateController extends AbstractController public function __invoke(): void { - global $text_dir, $urlParams, $view_algorithm_options, $view_with_options, $view_security_options; - global $message, $sep, $sql_query, $arr, $view_columns, $column_map, $systemDb, $pma_transformation_data; - global $containerBuilder, $new_transformations_sql, $view, $item, $parts, $db, $cfg, $errorUrl; - Util::checkParameters(['db']); - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $errorUrl .= Url::getCommon(['db' => $db], '&'); + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $GLOBALS['errorUrl'] .= Url::getCommon(['db' => $GLOBALS['db']], '&'); if (! $this->hasDatabase()) { return; } - $urlParams['goto'] = Url::getFromRoute('/table/structure'); - $urlParams['back'] = Url::getFromRoute('/view/create'); + $GLOBALS['urlParams']['goto'] = Url::getFromRoute('/table/structure'); + $GLOBALS['urlParams']['back'] = Url::getFromRoute('/view/create'); - $view_algorithm_options = [ + $GLOBALS['view_algorithm_options'] = [ 'UNDEFINED', 'MERGE', 'TEMPTABLE', ]; - $view_with_options = [ + $GLOBALS['view_with_options'] = [ 'CASCADED', 'LOCAL', ]; - $view_security_options = [ + $GLOBALS['view_security_options'] = [ 'DEFINER', 'INVOKER', ]; // View name is a compulsory field if (isset($_POST['view']['name']) && empty($_POST['view']['name'])) { - $message = Message::error(__('View name can not be empty!')); - $this->response->addJSON('message', $message); + $GLOBALS['message'] = Message::error(__('View name can not be empty!')); + $this->response->addJSON('message', $GLOBALS['message']); $this->response->setRequestStatus(false); return; @@ -89,56 +85,59 @@ class CreateController extends AbstractController /** * Creates the view */ - $sep = "\r\n"; + $GLOBALS['sep'] = "\r\n"; if (isset($_POST['createview'])) { - $sql_query = 'CREATE'; + $GLOBALS['sql_query'] = 'CREATE'; if (isset($_POST['view']['or_replace'])) { - $sql_query .= ' OR REPLACE'; + $GLOBALS['sql_query'] .= ' OR REPLACE'; } } else { - $sql_query = 'ALTER'; + $GLOBALS['sql_query'] = 'ALTER'; } - if (isset($_POST['view']['algorithm']) && in_array($_POST['view']['algorithm'], $view_algorithm_options)) { - $sql_query .= $sep . ' ALGORITHM = ' . $_POST['view']['algorithm']; + if ( + isset($_POST['view']['algorithm']) + && in_array($_POST['view']['algorithm'], $GLOBALS['view_algorithm_options']) + ) { + $GLOBALS['sql_query'] .= $GLOBALS['sep'] . ' ALGORITHM = ' . $_POST['view']['algorithm']; } if (! empty($_POST['view']['definer'])) { if (! str_contains($_POST['view']['definer'], '@')) { - $sql_query .= $sep . 'DEFINER=' + $GLOBALS['sql_query'] .= $GLOBALS['sep'] . 'DEFINER=' . Util::backquote($_POST['view']['definer']); } else { - $arr = explode('@', $_POST['view']['definer']); - $sql_query .= $sep . 'DEFINER=' . Util::backquote($arr[0]); - $sql_query .= '@' . Util::backquote($arr[1]) . ' '; + $GLOBALS['arr'] = explode('@', $_POST['view']['definer']); + $GLOBALS['sql_query'] .= $GLOBALS['sep'] . 'DEFINER=' . Util::backquote($GLOBALS['arr'][0]); + $GLOBALS['sql_query'] .= '@' . Util::backquote($GLOBALS['arr'][1]) . ' '; } } if ( isset($_POST['view']['sql_security']) - && in_array($_POST['view']['sql_security'], $view_security_options) + && in_array($_POST['view']['sql_security'], $GLOBALS['view_security_options']) ) { - $sql_query .= $sep . ' SQL SECURITY ' + $GLOBALS['sql_query'] .= $GLOBALS['sep'] . ' SQL SECURITY ' . $_POST['view']['sql_security']; } - $sql_query .= $sep . ' VIEW ' + $GLOBALS['sql_query'] .= $GLOBALS['sep'] . ' VIEW ' . Util::backquote($_POST['view']['name']); if (! empty($_POST['view']['column_names'])) { - $sql_query .= $sep . ' (' . $_POST['view']['column_names'] . ')'; + $GLOBALS['sql_query'] .= $GLOBALS['sep'] . ' (' . $_POST['view']['column_names'] . ')'; } - $sql_query .= $sep . ' AS ' . $_POST['view']['as']; + $GLOBALS['sql_query'] .= $GLOBALS['sep'] . ' AS ' . $_POST['view']['as']; - if (isset($_POST['view']['with']) && in_array($_POST['view']['with'], $view_with_options)) { - $sql_query .= $sep . ' WITH ' . $_POST['view']['with'] . ' CHECK OPTION'; + if (isset($_POST['view']['with']) && in_array($_POST['view']['with'], $GLOBALS['view_with_options'])) { + $GLOBALS['sql_query'] .= $GLOBALS['sep'] . ' WITH ' . $_POST['view']['with'] . ' CHECK OPTION'; } - if (! $this->dbi->tryQuery($sql_query)) { + if (! $this->dbi->tryQuery($GLOBALS['sql_query'])) { if (! isset($_POST['ajax_dialog'])) { - $message = Message::rawError($this->dbi->getError()); + $GLOBALS['message'] = Message::rawError($this->dbi->getError()); return; } @@ -146,7 +145,7 @@ class CreateController extends AbstractController $this->response->addJSON( 'message', Message::error( - '' . htmlspecialchars($sql_query) . '

' + '' . htmlspecialchars($GLOBALS['sql_query']) . '

' . $this->dbi->getError() ) ); @@ -156,44 +155,44 @@ class CreateController extends AbstractController } // If different column names defined for VIEW - $view_columns = []; + $GLOBALS['view_columns'] = []; if (isset($_POST['view']['column_names'])) { - $view_columns = explode(',', $_POST['view']['column_names']); + $GLOBALS['view_columns'] = explode(',', $_POST['view']['column_names']); } - $column_map = $this->dbi->getColumnMapFromSql($_POST['view']['as'], $view_columns); + $GLOBALS['column_map'] = $this->dbi->getColumnMapFromSql($_POST['view']['as'], $GLOBALS['view_columns']); - $systemDb = $this->dbi->getSystemDatabase(); - $pma_transformation_data = $systemDb->getExistingTransformationData($db); + $GLOBALS['systemDb'] = $this->dbi->getSystemDatabase(); + $GLOBALS['pma_transformation_data'] = $GLOBALS['systemDb']->getExistingTransformationData($GLOBALS['db']); - if ($pma_transformation_data !== false) { + if ($GLOBALS['pma_transformation_data'] !== false) { // SQL for store new transformation details of VIEW - $new_transformations_sql = $systemDb->getNewTransformationDataSql( - $pma_transformation_data, - $column_map, + $GLOBALS['new_transformations_sql'] = $GLOBALS['systemDb']->getNewTransformationDataSql( + $GLOBALS['pma_transformation_data'], + $GLOBALS['column_map'], $_POST['view']['name'], - $db + $GLOBALS['db'] ); // Store new transformations - if ($new_transformations_sql != '') { - $this->dbi->tryQuery($new_transformations_sql); + if ($GLOBALS['new_transformations_sql'] != '') { + $this->dbi->tryQuery($GLOBALS['new_transformations_sql']); } } - unset($pma_transformation_data); + unset($GLOBALS['pma_transformation_data']); if (! isset($_POST['ajax_dialog'])) { - $message = Message::success(); + $GLOBALS['message'] = Message::success(); /** @var StructureController $controller */ - $controller = $containerBuilder->get(StructureController::class); + $controller = $GLOBALS['containerBuilder']->get(StructureController::class); $controller(); } else { $this->response->addJSON( 'message', Generator::getMessage( Message::success(), - $sql_query + $GLOBALS['sql_query'] ) ); $this->response->setRequestStatus(true); @@ -202,10 +201,10 @@ class CreateController extends AbstractController return; } - $sql_query = ! empty($_POST['sql_query']) ? $_POST['sql_query'] : ''; + $GLOBALS['sql_query'] = ! empty($_POST['sql_query']) ? $_POST['sql_query'] : ''; // prefill values if not already filled from former submission - $view = [ + $GLOBALS['view'] = [ 'operation' => 'create', 'or_replace' => '', 'algorithm' => '', @@ -213,13 +212,13 @@ class CreateController extends AbstractController 'sql_security' => '', 'name' => '', 'column_names' => '', - 'as' => $sql_query, + 'as' => $GLOBALS['sql_query'], 'with' => '', ]; // Used to prefill the fields when editing a view if (isset($_GET['db'], $_GET['table'])) { - $item = $this->dbi->fetchSingleRow( + $GLOBALS['item'] = $this->dbi->fetchSingleRow( sprintf( "SELECT `VIEW_DEFINITION`, `CHECK_OPTION`, `DEFINER`, `SECURITY_TYPE` @@ -234,43 +233,43 @@ class CreateController extends AbstractController ->showCreate(); // CREATE ALGORITHM= DE... - $parts = explode(' ', substr($createView, 17)); - $item['ALGORITHM'] = $parts[0]; + $GLOBALS['parts'] = explode(' ', substr($createView, 17)); + $GLOBALS['item']['ALGORITHM'] = $GLOBALS['parts'][0]; - $view['operation'] = 'alter'; - $view['definer'] = $item['DEFINER']; - $view['sql_security'] = $item['SECURITY_TYPE']; - $view['name'] = $_GET['table']; - $view['as'] = $item['VIEW_DEFINITION']; - $view['with'] = $item['CHECK_OPTION']; - $view['algorithm'] = $item['ALGORITHM']; + $GLOBALS['view']['operation'] = 'alter'; + $GLOBALS['view']['definer'] = $GLOBALS['item']['DEFINER']; + $GLOBALS['view']['sql_security'] = $GLOBALS['item']['SECURITY_TYPE']; + $GLOBALS['view']['name'] = $_GET['table']; + $GLOBALS['view']['as'] = $GLOBALS['item']['VIEW_DEFINITION']; + $GLOBALS['view']['with'] = $GLOBALS['item']['CHECK_OPTION']; + $GLOBALS['view']['algorithm'] = $GLOBALS['item']['ALGORITHM']; // MySQL 8.0+ - issue #16194 - if (empty($view['as']) && is_string($createView)) { + if (empty($GLOBALS['view']['as']) && is_string($createView)) { $parser = new Parser($createView); /** * @var CreateStatement $stmt */ $stmt = $parser->statements[0]; - $view['as'] = isset($stmt->body) ? TokensList::build($stmt->body) : $view['as']; + $GLOBALS['view']['as'] = isset($stmt->body) ? TokensList::build($stmt->body) : $GLOBALS['view']['as']; } } if (isset($_POST['view']) && is_array($_POST['view'])) { - $view = array_merge($view, $_POST['view']); + $GLOBALS['view'] = array_merge($GLOBALS['view'], $_POST['view']); } - $urlParams['db'] = $db; - $urlParams['reload'] = 1; + $GLOBALS['urlParams']['db'] = $GLOBALS['db']; + $GLOBALS['urlParams']['reload'] = 1; echo $this->template->render('view_create', [ 'ajax_dialog' => isset($_POST['ajax_dialog']), - 'text_dir' => $text_dir, - 'url_params' => $urlParams, - 'view' => $view, - 'view_algorithm_options' => $view_algorithm_options, - 'view_with_options' => $view_with_options, - 'view_security_options' => $view_security_options, + 'text_dir' => $GLOBALS['text_dir'], + 'url_params' => $GLOBALS['urlParams'], + 'view' => $GLOBALS['view'], + 'view_algorithm_options' => $GLOBALS['view_algorithm_options'], + 'view_with_options' => $GLOBALS['view_with_options'], + 'view_security_options' => $GLOBALS['view_security_options'], ]); } } diff --git a/libraries/classes/Controllers/View/OperationsController.php b/libraries/classes/Controllers/View/OperationsController.php index d7c29cbca2..e80eb24d79 100644 --- a/libraries/classes/Controllers/View/OperationsController.php +++ b/libraries/classes/Controllers/View/OperationsController.php @@ -41,22 +41,19 @@ class OperationsController extends AbstractController public function __invoke(): void { - global $sql_query, $urlParams, $reload, $result, $warning_messages; - global $db, $table, $cfg, $errorUrl; - - $tableObject = $this->dbi->getTable($db, $table); + $tableObject = $this->dbi->getTable($GLOBALS['db'], $GLOBALS['table']); $this->addScriptFiles(['table/operations.js']); Util::checkParameters(['db', 'table']); - $urlParams = ['db' => $db, 'table' => $table]; - $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $errorUrl .= Url::getCommon($urlParams, '&'); + $GLOBALS['urlParams'] = ['db' => $GLOBALS['db'], 'table' => $GLOBALS['table']]; + $GLOBALS['errorUrl'] = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $GLOBALS['errorUrl'] .= Url::getCommon($GLOBALS['urlParams'], '&'); - DbTableExists::check($db, $table); + DbTableExists::check($GLOBALS['db'], $GLOBALS['table']); - $urlParams['goto'] = $urlParams['back'] = Url::getFromRoute('/view/operations'); + $GLOBALS['urlParams']['goto'] = $GLOBALS['urlParams']['back'] = Url::getFromRoute('/view/operations'); $message = new Message(); $type = 'success'; @@ -64,25 +61,25 @@ class OperationsController extends AbstractController if (isset($_POST['new_name'])) { if ($tableObject->rename($_POST['new_name'])) { $message->addText($tableObject->getLastMessage()); - $result = true; - $table = $tableObject->getName(); + $GLOBALS['result'] = true; + $GLOBALS['table'] = $tableObject->getName(); /* Force reread after rename */ $tableObject->getStatusInfo(null, true); - $reload = true; + $GLOBALS['reload'] = true; } else { $message->addText($tableObject->getLastError()); - $result = false; + $GLOBALS['result'] = false; } } - $warning_messages = $this->operations->getWarningMessagesArray(); + $GLOBALS['warning_messages'] = $this->operations->getWarningMessagesArray(); } - if (isset($result)) { + if (isset($GLOBALS['result'])) { // set to success by default, because result set could be empty // (for example, a table rename) if (empty($message->getString())) { - if ($result) { + if ($GLOBALS['result']) { $message->addText( __('Your SQL query has been executed successfully.') ); @@ -91,25 +88,25 @@ class OperationsController extends AbstractController } // $result should exist, regardless of $_message - $type = $result ? 'success' : 'error'; + $type = $GLOBALS['result'] ? 'success' : 'error'; } - if (! empty($warning_messages)) { - $message->addMessagesString($warning_messages); + if (! empty($GLOBALS['warning_messages'])) { + $message->addMessagesString($GLOBALS['warning_messages']); $message->isError(true); } $this->response->addHTML(Generator::getMessage( $message, - $sql_query, + $GLOBALS['sql_query'], $type )); } $this->render('table/operations/view', [ - 'db' => $db, - 'table' => $table, - 'url_params' => $urlParams, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], + 'url_params' => $GLOBALS['urlParams'], ]); } } diff --git a/libraries/classes/Core.php b/libraries/classes/Core.php index c77a2fb6a6..4685dc089a 100644 --- a/libraries/classes/Core.php +++ b/libraries/classes/Core.php @@ -89,8 +89,6 @@ class Core string $error_message, $message_args = null ): void { - global $dbi; - /* Use format string if applicable */ if (is_string($message_args)) { $error_message = sprintf($error_message, $message_args); @@ -103,7 +101,7 @@ class Core * (this can happen on early fatal error) */ if ( - isset($dbi, $GLOBALS['config']) + isset($GLOBALS['dbi'], $GLOBALS['config']) && $GLOBALS['config']->get('is_setup') === false && ResponseRenderer::getInstance()->isAjax() ) { @@ -192,8 +190,6 @@ class Core bool $fatal = false, string $extra = '' ): void { - global $errorHandler; - $message = 'The %s extension is missing. Please check your PHP configuration.'; /* Gettext does not have to be loaded yet here */ @@ -213,7 +209,7 @@ class Core return; } - $errorHandler->addError($message, E_USER_WARNING, '', 0, false); + $GLOBALS['errorHandler']->addError($message, E_USER_WARNING, '', 0, false); } /** @@ -225,9 +221,7 @@ class Core */ public static function getTableCount(string $db): int { - global $dbi; - - $tables = $dbi->tryQuery('SHOW TABLES FROM ' . Util::backquote($db) . ';'); + $tables = $GLOBALS['dbi']->tryQuery('SHOW TABLES FROM ' . Util::backquote($db) . ';'); if ($tables) { return $tables->numRows(); @@ -763,8 +757,6 @@ class Core */ public static function setPostAsGlobal(array $post_patterns): void { - global $containerBuilder; - foreach (array_keys($_POST) as $post_key) { foreach ($post_patterns as $one_post_pattern) { if (! preg_match($one_post_pattern, $post_key)) { @@ -772,7 +764,7 @@ class Core } $GLOBALS[$post_key] = $_POST[$post_key]; - $containerBuilder->setParameter($post_key, $GLOBALS[$post_key]); + $GLOBALS['containerBuilder']->setParameter($post_key, $GLOBALS[$post_key]); } } } @@ -949,11 +941,9 @@ class Core */ public static function signSqlQuery($sqlQuery) { - global $cfg; - $secret = $_SESSION[' HMAC_secret '] ?? ''; - return hash_hmac('sha256', $sqlQuery, $secret . $cfg['blowfish_secret']); + return hash_hmac('sha256', $sqlQuery, $secret . $GLOBALS['cfg']['blowfish_secret']); } /** @@ -964,10 +954,8 @@ class Core */ public static function checkSqlQuerySignature($sqlQuery, $signature): bool { - global $cfg; - $secret = $_SESSION[' HMAC_secret '] ?? ''; - $hmac = hash_hmac('sha256', $sqlQuery, $secret . $cfg['blowfish_secret']); + $hmac = hash_hmac('sha256', $sqlQuery, $secret . $GLOBALS['cfg']['blowfish_secret']); return hash_equals($hmac, $signature); } diff --git a/libraries/classes/Crypto/Crypto.php b/libraries/classes/Crypto/Crypto.php index 04f37d42c0..765b1e1c54 100644 --- a/libraries/classes/Crypto/Crypto.php +++ b/libraries/classes/Crypto/Crypto.php @@ -20,9 +20,7 @@ final class Crypto { private function getEncryptionKey(): string { - global $config; - - $key = $config->get('URLQueryEncryptionSecretKey'); + $key = $GLOBALS['config']->get('URLQueryEncryptionSecretKey'); if (is_string($key) && mb_strlen($key, '8bit') === SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { return $key; } diff --git a/libraries/classes/Database/Designer.php b/libraries/classes/Database/Designer.php index 7ec6272c46..d7bf1ed726 100644 --- a/libraries/classes/Database/Designer.php +++ b/libraries/classes/Database/Designer.php @@ -158,8 +158,6 @@ class Designer */ private function getSideMenuParamsArray() { - global $dbi; - $params = []; $databaseDesignerSettingsFeature = $this->relation->getRelationParameters()->databaseDesignerSettingsFeature; @@ -168,7 +166,7 @@ class Designer . Util::backquote($databaseDesignerSettingsFeature->database) . '.' . Util::backquote($databaseDesignerSettingsFeature->designerSettings) . ' WHERE ' . Util::backquote('username') . ' = "' - . $dbi->escapeString($GLOBALS['cfg']['Server']['user']) + . $GLOBALS['dbi']->escapeString($GLOBALS['cfg']['Server']['user']) . '";'; $result = $this->dbi->fetchSingleRow($query); @@ -251,8 +249,6 @@ class Designer array $tables_all_keys, array $tables_pk_or_unique_keys ) { - global $text_dir; - $columns_type = []; foreach ($designerTables as $designerTable) { $table_name = $designerTable->getDbTableString(); @@ -288,7 +284,7 @@ class Designer return $this->template->render('database/designer/database_tables', [ 'db' => $GLOBALS['db'], - 'text_dir' => $text_dir, + 'text_dir' => $GLOBALS['text_dir'], 'get_db' => $db, 'has_query' => isset($_REQUEST['query']), 'tab_pos' => $tab_pos, @@ -337,8 +333,6 @@ class Designer array $tablesAllKeys, array $tablesPkOrUniqueKeys ): string { - global $text_dir; - $relationParameters = $this->relation->getRelationParameters(); $columnsType = []; foreach ($designerTables as $designerTable) { @@ -393,7 +387,7 @@ class Designer return $this->template->render('database/designer/main', [ 'db' => $db, - 'text_dir' => $text_dir, + 'text_dir' => $GLOBALS['text_dir'], 'get_db' => $getDb, 'designer_config' => json_encode($designerConfig), 'display_page' => (int) $displayPage, diff --git a/libraries/classes/Database/Events.php b/libraries/classes/Database/Events.php index 9240c7ee66..ac886dd396 100644 --- a/libraries/classes/Database/Events.php +++ b/libraries/classes/Database/Events.php @@ -82,25 +82,23 @@ class Events */ public function handleEditor(): void { - global $db, $table, $errors, $message; - if (! empty($_POST['editor_process_add']) || ! empty($_POST['editor_process_edit'])) { $sql_query = ''; $item_query = $this->getQueryFromRequest(); // set by getQueryFromRequest() - if (! count($errors)) { + if (! count($GLOBALS['errors'])) { // Execute the created query if (! empty($_POST['editor_process_edit'])) { // Backup the old trigger, in case something goes wrong - $create_item = $this->dbi->getDefinition($db, 'EVENT', $_POST['item_original_name']); + $create_item = $this->dbi->getDefinition($GLOBALS['db'], 'EVENT', $_POST['item_original_name']); $drop_item = 'DROP EVENT IF EXISTS ' . Util::backquote($_POST['item_original_name']) . ";\n"; $result = $this->dbi->tryQuery($drop_item); if (! $result) { - $errors[] = sprintf( + $GLOBALS['errors'][] = sprintf( __('The following query has failed: "%s"'), htmlspecialchars($drop_item) ) @@ -109,7 +107,7 @@ class Events } else { $result = $this->dbi->tryQuery($item_query); if (! $result) { - $errors[] = sprintf( + $GLOBALS['errors'][] = sprintf( __('The following query has failed: "%s"'), htmlspecialchars($item_query) ) @@ -119,13 +117,13 @@ class Events // the new one. Try to restore the backup query $result = $this->dbi->tryQuery($create_item); if (! $result) { - $errors = $this->checkResult($create_item, $errors); + $GLOBALS['errors'] = $this->checkResult($create_item, $GLOBALS['errors']); } } else { - $message = Message::success( + $GLOBALS['message'] = Message::success( __('Event %1$s has been modified.') ); - $message->addParam( + $GLOBALS['message']->addParam( Util::backquote($_POST['item_name']) ); $sql_query = $drop_item . $item_query; @@ -135,17 +133,17 @@ class Events // 'Add a new item' mode $result = $this->dbi->tryQuery($item_query); if (! $result) { - $errors[] = sprintf( + $GLOBALS['errors'][] = sprintf( __('The following query has failed: "%s"'), htmlspecialchars($item_query) ) . '

' . __('MySQL said: ') . $this->dbi->getError(); } else { - $message = Message::success( + $GLOBALS['message'] = Message::success( __('Event %1$s has been created.') ); - $message->addParam( + $GLOBALS['message']->addParam( Util::backquote($_POST['item_name']) ); $sql_query = $item_query; @@ -153,27 +151,27 @@ class Events } } - if (count($errors)) { - $message = Message::error( + if (count($GLOBALS['errors'])) { + $GLOBALS['message'] = Message::error( '' . __( 'One or more errors have occurred while processing your request:' ) . '' ); - $message->addHtml('
    '); - foreach ($errors as $string) { - $message->addHtml('
  • ' . $string . '
  • '); + $GLOBALS['message']->addHtml('
      '); + foreach ($GLOBALS['errors'] as $string) { + $GLOBALS['message']->addHtml('
    • ' . $string . '
    • '); } - $message->addHtml('
    '); + $GLOBALS['message']->addHtml('
'); } - $output = Generator::getMessage($message, $sql_query); + $output = Generator::getMessage($GLOBALS['message'], $sql_query); if ($this->response->isAjax()) { - if ($message->isSuccess()) { - $events = $this->dbi->getEvents($db, $_POST['item_name']); + if ($GLOBALS['message']->isSuccess()) { + $events = $this->dbi->getEvents($GLOBALS['db'], $_POST['item_name']); $event = $events[0]; $this->response->addJSON( 'name', @@ -189,10 +187,10 @@ class Events $this->response->addJSON( 'new_row', $this->template->render('database/events/row', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'event' => $event, - 'has_privilege' => Util::currentUserHasPrivilege('EVENT', $db), + 'has_privilege' => Util::currentUserHasPrivilege('EVENT', $GLOBALS['db']), 'sql_drop' => $sqlDrop, 'row_class' => '', ]) @@ -203,7 +201,7 @@ class Events $this->response->addJSON('message', $output); } else { $this->response->setRequestStatus(false); - $this->response->addJSON('message', $message); + $this->response->addJSON('message', $GLOBALS['message']); } $this->response->addJSON('tableType', 'events'); @@ -215,7 +213,7 @@ class Events * Display a form used to add/edit a trigger, if necessary */ if ( - ! count($errors) + ! count($GLOBALS['errors']) && (! empty($_POST['editor_process_add']) || ! empty($_POST['editor_process_edit']) || (empty($_REQUEST['add_item']) @@ -257,7 +255,7 @@ class Events $mode = 'edit'; } - $this->sendEditor($mode, $item, $title, $db, $operation); + $this->sendEditor($mode, $item, $title, $GLOBALS['db'], $operation); } /** @@ -306,14 +304,12 @@ class Events */ public function getDataFromName($name): ?array { - global $db; - $retval = []; $columns = '`EVENT_NAME`, `STATUS`, `EVENT_TYPE`, `EXECUTE_AT`, ' . '`INTERVAL_VALUE`, `INTERVAL_FIELD`, `STARTS`, `ENDS`, ' . '`EVENT_DEFINITION`, `ON_COMPLETION`, `DEFINER`, `EVENT_COMMENT`'; $where = 'EVENT_SCHEMA ' . Util::getCollateForIS() . '=' - . "'" . $this->dbi->escapeString($db) . "' " + . "'" . $this->dbi->escapeString($GLOBALS['db']) . "' " . "AND EVENT_NAME='" . $this->dbi->escapeString($name) . "'"; $query = 'SELECT ' . $columns . ' FROM `INFORMATION_SCHEMA`.`EVENTS` WHERE ' . $where . ';'; $item = $this->dbi->fetchSingleRow($query); @@ -362,8 +358,6 @@ class Events */ public function getEditorForm($mode, $operation, array $item) { - global $db; - if ($operation === 'change') { if ($item['item_type'] === 'RECURRING') { $item['item_type'] = 'ONE TIME'; @@ -375,7 +369,7 @@ class Events } return $this->template->render('database/events/editor_form', [ - 'db' => $db, + 'db' => $GLOBALS['db'], 'event' => $item, 'mode' => $mode, 'is_ajax' => $this->response->isAjax(), @@ -392,8 +386,6 @@ class Events */ public function getQueryFromRequest() { - global $errors; - $query = 'CREATE '; if (! empty($_POST['item_definer'])) { if (str_contains($_POST['item_definer'], '@')) { @@ -401,7 +393,7 @@ class Events $query .= 'DEFINER=' . Util::backquote($arr[0]); $query .= '@' . Util::backquote($arr[1]) . ' '; } else { - $errors[] = __('The definer must be in the "username@hostname" format!'); + $GLOBALS['errors'][] = __('The definer must be in the "username@hostname" format!'); } } @@ -409,7 +401,7 @@ class Events if (! empty($_POST['item_name'])) { $query .= Util::backquote($_POST['item_name']) . ' '; } else { - $errors[] = __('You must provide an event name!'); + $GLOBALS['errors'][] = __('You must provide an event name!'); } $query .= 'ON SCHEDULE '; @@ -423,7 +415,7 @@ class Events $query .= 'EVERY ' . intval($_POST['item_interval_value']) . ' '; $query .= $_POST['item_interval_field'] . ' '; } else { - $errors[] = __('You must provide a valid interval value for the event.'); + $GLOBALS['errors'][] = __('You must provide a valid interval value for the event.'); } if (! empty($_POST['item_starts'])) { @@ -443,11 +435,11 @@ class Events . $this->dbi->escapeString($_POST['item_execute_at']) . "' "; } else { - $errors[] = __('You must provide a valid execution time for the event.'); + $GLOBALS['errors'][] = __('You must provide a valid execution time for the event.'); } } } else { - $errors[] = __('You must provide a valid type for the event.'); + $GLOBALS['errors'][] = __('You must provide a valid type for the event.'); } $query .= 'ON COMPLETION '; @@ -473,7 +465,7 @@ class Events if (! empty($_POST['item_definition'])) { $query .= $_POST['item_definition']; } else { - $errors[] = __('You must provide an event definition.'); + $GLOBALS['errors'][] = __('You must provide an event definition.'); } return $query; @@ -549,14 +541,12 @@ class Events public function export(): void { - global $db; - if (empty($_GET['export_item']) || empty($_GET['item_name'])) { return; } $itemName = $_GET['item_name']; - $exportData = $this->dbi->getDefinition($db, 'EVENT', $itemName); + $exportData = $this->dbi->getDefinition($GLOBALS['db'], 'EVENT', $itemName); if (! $exportData) { $exportData = false; @@ -588,7 +578,7 @@ class Events $message = sprintf( __('Error in processing request: No event with name %1$s found in database %2$s.'), $itemName, - htmlspecialchars(Util::backquote($db)) + htmlspecialchars(Util::backquote($GLOBALS['db'])) ); $message = Message::error($message); diff --git a/libraries/classes/Database/MultiTableQuery.php b/libraries/classes/Database/MultiTableQuery.php index 9eea9adba9..60ccd937ed 100644 --- a/libraries/classes/Database/MultiTableQuery.php +++ b/libraries/classes/Database/MultiTableQuery.php @@ -107,18 +107,16 @@ class MultiTableQuery */ public static function displayResults($sqlQuery, $db): string { - global $dbi; - [, $db] = ParseAnalyze::sqlQuery($sqlQuery, $db); $goto = Url::getFromRoute('/database/multi-table-query'); - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $sql = new Sql( - $dbi, + $GLOBALS['dbi'], $relation, - new RelationCleanup($dbi, $relation), - new Operations($dbi, $relation), + new RelationCleanup($GLOBALS['dbi'], $relation), + new Operations($GLOBALS['dbi'], $relation), new Transformations(), new Template() ); diff --git a/libraries/classes/Database/Routines.php b/libraries/classes/Database/Routines.php index 5f069fe7c9..c5c4dd4c6c 100644 --- a/libraries/classes/Database/Routines.php +++ b/libraries/classes/Database/Routines.php @@ -79,16 +79,14 @@ class Routines */ public function handleEditor(): void { - global $db, $errors; - - $errors = $this->handleRequestCreateOrEdit($errors, $db); + $GLOBALS['errors'] = $this->handleRequestCreateOrEdit($GLOBALS['errors'], $GLOBALS['db']); /** * Display a form used to add/edit a routine, if necessary */ // FIXME: this must be simpler than that if ( - ! count($errors) + ! count($GLOBALS['errors']) && ( ! empty($_POST['editor_process_add']) || ! empty($_POST['editor_process_edit']) || (empty($_REQUEST['add_item']) && empty($_REQUEST['edit_item']) @@ -157,7 +155,7 @@ class Routines htmlspecialchars( Util::backquote($_REQUEST['item_name']) ), - htmlspecialchars(Util::backquote($db)) + htmlspecialchars(Util::backquote($GLOBALS['db'])) ); $message = Message::error($message); @@ -180,8 +178,6 @@ class Routines */ public function handleRequestCreateOrEdit(array $errors, $db) { - global $message; - if (empty($_POST['editor_process_add']) && empty($_POST['editor_process_edit'])) { return $errors; } @@ -228,7 +224,11 @@ class Routines . '
' . __('MySQL said: ') . $this->dbi->getError(); } else { - [$newErrors, $message] = $this->create($routine_query, $create_routine, $privilegesBackup); + [$newErrors, $GLOBALS['message']] = $this->create( + $routine_query, + $create_routine, + $privilegesBackup + ); if (empty($newErrors)) { $sql_query = $drop_routine . $routine_query; } else { @@ -249,10 +249,10 @@ class Routines . '

' . __('MySQL said: ') . $this->dbi->getError(); } else { - $message = Message::success( + $GLOBALS['message'] = Message::success( __('Routine %1$s has been created.') ); - $message->addParam( + $GLOBALS['message']->addParam( Util::backquote($_POST['item_name']) ); $sql_query = $routine_query; @@ -261,26 +261,26 @@ class Routines } if (count($errors)) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __( 'One or more errors have occurred while processing your request:' ) ); - $message->addHtml('
    '); + $GLOBALS['message']->addHtml('
      '); foreach ($errors as $string) { - $message->addHtml('
    • ' . $string . '
    • '); + $GLOBALS['message']->addHtml('
    • ' . $string . '
    • '); } - $message->addHtml('
    '); + $GLOBALS['message']->addHtml('
'); } - $output = Generator::getMessage($message, $sql_query); + $output = Generator::getMessage($GLOBALS['message'], $sql_query); if (! $this->response->isAjax()) { return $errors; } - if (! $message->isSuccess()) { + if (! $GLOBALS['message']->isSuccess()) { $this->response->setRequestStatus(false); $this->response->addJSON('message', $output); exit; @@ -554,8 +554,6 @@ class Routines */ public function getDataFromName($name, $type, $all = true): ?array { - global $db; - $retval = []; // Build and execute the query @@ -563,7 +561,7 @@ class Routines . 'ROUTINE_DEFINITION, IS_DETERMINISTIC, SQL_DATA_ACCESS, ' . 'ROUTINE_COMMENT, SECURITY_TYPE'; $where = 'ROUTINE_SCHEMA ' . Util::getCollateForIS() . '=' - . "'" . $this->dbi->escapeString($db) . "' " + . "'" . $this->dbi->escapeString($GLOBALS['db']) . "' " . "AND SPECIFIC_NAME='" . $this->dbi->escapeString($name) . "'" . "AND ROUTINE_TYPE='" . $this->dbi->escapeString($type) . "'"; $query = 'SELECT ' . $fields . ' FROM INFORMATION_SCHEMA.ROUTINES WHERE ' . $where . ';'; @@ -578,7 +576,7 @@ class Routines $retval['item_name'] = $routine['SPECIFIC_NAME']; $retval['item_type'] = $routine['ROUTINE_TYPE']; - $definition = $this->dbi->getDefinition($db, $routine['ROUTINE_TYPE'], $routine['SPECIFIC_NAME']); + $definition = $this->dbi->getDefinition($GLOBALS['db'], $routine['ROUTINE_TYPE'], $routine['SPECIFIC_NAME']); if ($definition === null) { return null; @@ -737,8 +735,6 @@ class Routines */ public function getEditorForm($mode, $operation, array $routine) { - global $db, $errors; - for ($i = 0; $i < $routine['item_num_params']; $i++) { $routine['item_param_name'][$i] = htmlentities($routine['item_param_name'][$i], ENT_QUOTES); $routine['item_param_length'][$i] = htmlentities($routine['item_param_length'][$i], ENT_QUOTES); @@ -753,7 +749,10 @@ class Routines $routine['item_type'] = 'PROCEDURE'; $routine['item_type_toggle'] = 'FUNCTION'; } - } elseif ($operation === 'add' || ($routine['item_num_params'] == 0 && $mode === 'add' && ! $errors)) { + } elseif ( + $operation === 'add' + || ($routine['item_num_params'] == 0 && $mode === 'add' && ! $GLOBALS['errors']) + ) { $routine['item_param_dir'][] = ''; $routine['item_param_name'][] = ''; $routine['item_param_type'][] = ''; @@ -781,7 +780,7 @@ class Routines $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); return $this->template->render('database/routines/editor_form', [ - 'db' => $db, + 'db' => $GLOBALS['db'], 'routine' => $routine, 'is_edit_mode' => $mode === 'edit', 'is_ajax' => $this->response->isAjax(), @@ -815,14 +814,12 @@ class Routines string $itemType, bool &$warnedAboutLength ): string { - global $errors, $dbi; - $params = ''; $warnedAboutDir = false; for ($i = 0, $nb = count($itemParamName); $i < $nb; $i++) { if (empty($itemParamName[$i]) || empty($itemParamType[$i])) { - $errors[] = __('You must provide a name and a type for each routine parameter.'); + $GLOBALS['errors'][] = __('You must provide a name and a type for each routine parameter.'); break; } @@ -839,7 +836,7 @@ class Routines . ' ' . $itemParamType[$i]; } elseif (! $warnedAboutDir) { $warnedAboutDir = true; - $errors[] = sprintf( + $GLOBALS['errors'][] = sprintf( __('Invalid direction "%s" given for parameter.'), htmlspecialchars($itemParamDir[$i]) ); @@ -859,7 +856,7 @@ class Routines ) { if (! $warnedAboutLength) { $warnedAboutLength = true; - $errors[] = __( + $GLOBALS['errors'][] = __( 'You must provide length/values for routine parameters' . ' of type ENUM, SET, VARCHAR and VARBINARY.' ); @@ -867,7 +864,7 @@ class Routines } if (! empty($itemParamOpsText[$i])) { - if ($dbi->types->getTypeClass($itemParamType[$i]) === 'CHAR') { + if ($GLOBALS['dbi']->types->getTypeClass($itemParamType[$i]) === 'CHAR') { if (! in_array($itemParamType[$i], ['VARBINARY', 'BINARY'])) { $params .= ' CHARSET ' . mb_strtolower($itemParamOpsText[$i]); @@ -876,7 +873,7 @@ class Routines } if (! empty($itemParamOpsNum[$i])) { - if ($dbi->types->getTypeClass($itemParamType[$i]) === 'NUMBER') { + if ($GLOBALS['dbi']->types->getTypeClass($itemParamType[$i]) === 'NUMBER') { $params .= ' ' . mb_strtoupper($itemParamOpsNum[$i]); } @@ -902,14 +899,12 @@ class Routines string $query, bool $warnedAboutLength ): string { - global $errors, $dbi; - $itemReturnType = $_POST['item_returntype'] ?? null; if (! empty($itemReturnType) && in_array($itemReturnType, Util::getSupportedDatatypes())) { $query .= 'RETURNS ' . $itemReturnType; } else { - $errors[] = __('You must provide a valid return type for the routine.'); + $GLOBALS['errors'][] = __('You must provide a valid return type for the routine.'); } if ( @@ -926,21 +921,21 @@ class Routines && preg_match('@^(ENUM|SET|VARCHAR|VARBINARY)$@i', $itemReturnType) ) { if (! $warnedAboutLength) { - $errors[] = __( + $GLOBALS['errors'][] = __( 'You must provide length/values for routine parameters of type ENUM, SET, VARCHAR and VARBINARY.' ); } } if (! empty($_POST['item_returnopts_text'])) { - if ($dbi->types->getTypeClass($itemReturnType) === 'CHAR') { + if ($GLOBALS['dbi']->types->getTypeClass($itemReturnType) === 'CHAR') { $query .= ' CHARSET ' . mb_strtolower($_POST['item_returnopts_text']); } } if (! empty($_POST['item_returnopts_num'])) { - if ($dbi->types->getTypeClass($itemReturnType) === 'NUMBER') { + if ($GLOBALS['dbi']->types->getTypeClass($itemReturnType) === 'NUMBER') { $query .= ' ' . mb_strtoupper($_POST['item_returnopts_num']); } @@ -956,8 +951,6 @@ class Routines */ public function getQueryFromRequest(): string { - global $errors; - $itemType = $_POST['item_type'] ?? ''; $itemDefiner = $_POST['item_definer'] ?? ''; $itemName = $_POST['item_name'] ?? ''; @@ -981,14 +974,14 @@ class Routines $query .= '@' . Util::backquoteCompat($arr[1], 'NONE', $do_backquote) . ' '; } else { - $errors[] = __('The definer must be in the "username@hostname" format!'); + $GLOBALS['errors'][] = __('The definer must be in the "username@hostname" format!'); } } if ($itemType === 'FUNCTION' || $itemType === 'PROCEDURE') { $query .= $itemType . ' '; } else { - $errors[] = sprintf( + $GLOBALS['errors'][] = sprintf( __('Invalid routine type: "%s"'), htmlspecialchars($itemType) ); @@ -997,7 +990,7 @@ class Routines if (! empty($itemName)) { $query .= Util::backquote($itemName); } else { - $errors[] = __('You must provide a routine name!'); + $GLOBALS['errors'][] = __('You must provide a routine name!'); } $warnedAboutLength = false; @@ -1062,7 +1055,7 @@ class Routines if (! empty($itemDefinition)) { $query .= $itemDefinition; } else { - $errors[] = __('You must provide a routine definition.'); + $GLOBALS['errors'][] = __('You must provide a routine definition.'); } return $query; @@ -1135,8 +1128,6 @@ class Routines private function handleExecuteRoutine(): void { - global $db; - // Build the queries $routine = $this->getDataFromName($_POST['item_name'], $_POST['item_type'], false); if ($routine === null) { @@ -1144,7 +1135,7 @@ class Routines $message .= sprintf( __('No routine with name %1$s found in database %2$s.'), htmlspecialchars(Util::backquote($_POST['item_name'])), - htmlspecialchars(Util::backquote($db)) + htmlspecialchars(Util::backquote($GLOBALS['db'])) ); $message = Message::error($message); if ($this->response->isAjax()) { @@ -1279,8 +1270,6 @@ class Routines */ public function handleExecute(): void { - global $db; - /** * Handle all user requests other than the default of listing routines */ @@ -1313,7 +1302,7 @@ class Routines $message .= sprintf( __('No routine with name %1$s found in database %2$s.'), htmlspecialchars(Util::backquote($_GET['item_name'])), - htmlspecialchars(Util::backquote($db)) + htmlspecialchars(Util::backquote($GLOBALS['db'])) ); $message = Message::error($message); @@ -1355,8 +1344,6 @@ class Routines */ public function getExecuteForm(array $routine): string { - global $db, $cfg; - // Escape special characters $routine['item_name'] = htmlentities($routine['item_name'], ENT_QUOTES); for ($i = 0; $i < $routine['item_num_params']; $i++) { @@ -1373,7 +1360,7 @@ class Routines continue; } - if ($cfg['ShowFunctionFields']) { + if ($GLOBALS['cfg']['ShowFunctionFields']) { if ( stripos($routine['item_param_type'][$i], 'enum') !== false || stripos($routine['item_param_type'][$i], 'set') !== false @@ -1423,10 +1410,10 @@ class Routines } return $this->template->render('database/routines/execute_form', [ - 'db' => $db, + 'db' => $GLOBALS['db'], 'routine' => $routine, 'ajax' => $this->response->isAjax(), - 'show_function_fields' => $cfg['ShowFunctionFields'], + 'show_function_fields' => $GLOBALS['cfg']['ShowFunctionFields'], 'params' => $params, ]); } @@ -1441,8 +1428,6 @@ class Routines */ public function getRow(array $routine, $rowClass = '') { - global $db, $table; - $sqlDrop = sprintf( 'DROP %s IF EXISTS %s', $routine['type'], @@ -1452,7 +1437,7 @@ class Routines // this is for our purpose to decide whether to // show the edit link or not, so we need the DEFINER for the routine $where = 'ROUTINE_SCHEMA ' . Util::getCollateForIS() . '=' - . "'" . $this->dbi->escapeString($db) . "' " + . "'" . $this->dbi->escapeString($GLOBALS['db']) . "' " . "AND SPECIFIC_NAME='" . $this->dbi->escapeString($routine['name']) . "'" . "AND ROUTINE_TYPE='" . $this->dbi->escapeString($routine['type']) . "'"; $query = 'SELECT `DEFINER` FROM INFORMATION_SCHEMA.ROUTINES WHERE ' . $where . ';'; @@ -1463,12 +1448,12 @@ class Routines // Since editing a procedure involved dropping and recreating, check also for // CREATE ROUTINE privilege to avoid lost procedures. - $hasCreateRoutine = Util::currentUserHasPrivilege('CREATE ROUTINE', $db); + $hasCreateRoutine = Util::currentUserHasPrivilege('CREATE ROUTINE', $GLOBALS['db']); $hasEditPrivilege = ($hasCreateRoutine && $currentUserIsRoutineDefiner) || $this->dbi->isSuperUser(); $hasExportPrivilege = ($hasCreateRoutine && $currentUserIsRoutineDefiner) || $this->dbi->isSuperUser(); - $hasExecutePrivilege = Util::currentUserHasPrivilege('EXECUTE', $db) + $hasExecutePrivilege = Util::currentUserHasPrivilege('EXECUTE', $GLOBALS['db']) || $currentUserIsRoutineDefiner; // There is a problem with Util::currentUserHasPrivilege(): @@ -1482,7 +1467,7 @@ class Routines // we will show a dialog to get values for these parameters, // otherwise we can execute it directly. - $definition = $this->dbi->getDefinition($db, $routine['type'], $routine['name']); + $definition = $this->dbi->getDefinition($GLOBALS['db'], $routine['type'], $routine['name']); $executeAction = ''; if ($definition !== null) { @@ -1509,8 +1494,8 @@ class Routines } return $this->template->render('database/routines/row', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'sql_drop' => $sqlDrop, 'routine' => $routine, 'row_class' => $rowClass, @@ -1544,8 +1529,6 @@ class Routines public function export(): void { - global $db; - if (empty($_GET['export_item']) || empty($_GET['item_name']) || empty($_GET['item_type'])) { return; } @@ -1554,7 +1537,7 @@ class Routines return; } - $routineDefinition = $this->dbi->getDefinition($db, $_GET['item_type'], $_GET['item_name']); + $routineDefinition = $this->dbi->getDefinition($GLOBALS['db'], $_GET['item_type'], $_GET['item_name']); $exportData = false; if ($routineDefinition !== null) { @@ -1590,7 +1573,7 @@ class Routines . ' You might be lacking the necessary privileges to view/export this routine.' ), $itemName, - htmlspecialchars(Util::backquote($db)) + htmlspecialchars(Util::backquote($GLOBALS['db'])) ); $message = Message::error($message); diff --git a/libraries/classes/Database/Triggers.php b/libraries/classes/Database/Triggers.php index ca30e7eee1..9997b5f480 100644 --- a/libraries/classes/Database/Triggers.php +++ b/libraries/classes/Database/Triggers.php @@ -58,23 +58,21 @@ class Triggers */ public function main(): void { - global $db, $table; - /** * Process all requests */ $this->handleEditor(); $this->export(); - $items = $this->dbi->getTriggers($db, $table); - $hasTriggerPrivilege = Util::currentUserHasPrivilege('TRIGGER', $db, $table); + $items = $this->dbi->getTriggers($GLOBALS['db'], $GLOBALS['table']); + $hasTriggerPrivilege = Util::currentUserHasPrivilege('TRIGGER', $GLOBALS['db'], $GLOBALS['table']); $isAjax = $this->response->isAjax() && empty($_REQUEST['ajax_page_request']); $rows = ''; foreach ($items as $item) { $rows .= $this->template->render('database/triggers/row', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'trigger' => $item, 'has_drop_privilege' => $hasTriggerPrivilege, 'has_edit_privilege' => $hasTriggerPrivilege, @@ -83,8 +81,8 @@ class Triggers } echo $this->template->render('database/triggers/list', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'items' => $items, 'rows' => $rows, 'has_privilege' => $hasTriggerPrivilege, @@ -96,15 +94,13 @@ class Triggers */ public function handleEditor(): void { - global $db, $errors, $message, $table; - if (! empty($_POST['editor_process_add']) || ! empty($_POST['editor_process_edit'])) { $sql_query = ''; $item_query = $this->getQueryFromRequest(); // set by getQueryFromRequest() - if (! count($errors)) { + if (! count($GLOBALS['errors'])) { // Execute the created query if (! empty($_POST['editor_process_edit'])) { // Backup the old trigger, in case something goes wrong @@ -113,7 +109,7 @@ class Triggers $drop_item = $trigger['drop'] . ';'; $result = $this->dbi->tryQuery($drop_item); if (! $result) { - $errors[] = sprintf( + $GLOBALS['errors'][] = sprintf( __('The following query has failed: "%s"'), htmlspecialchars($drop_item) ) @@ -122,7 +118,7 @@ class Triggers } else { $result = $this->dbi->tryQuery($item_query); if (! $result) { - $errors[] = sprintf( + $GLOBALS['errors'][] = sprintf( __('The following query has failed: "%s"'), htmlspecialchars($item_query) ) @@ -133,13 +129,13 @@ class Triggers $result = $this->dbi->tryQuery($create_item); if (! $result) { - $errors = $this->checkResult($create_item, $errors); + $GLOBALS['errors'] = $this->checkResult($create_item, $GLOBALS['errors']); } } else { - $message = Message::success( + $GLOBALS['message'] = Message::success( __('Trigger %1$s has been modified.') ); - $message->addParam( + $GLOBALS['message']->addParam( Util::backquote($_POST['item_name']) ); $sql_query = $drop_item . $item_query; @@ -149,17 +145,17 @@ class Triggers // 'Add a new item' mode $result = $this->dbi->tryQuery($item_query); if (! $result) { - $errors[] = sprintf( + $GLOBALS['errors'][] = sprintf( __('The following query has failed: "%s"'), htmlspecialchars($item_query) ) . '

' . __('MySQL said: ') . $this->dbi->getError(); } else { - $message = Message::success( + $GLOBALS['message'] = Message::success( __('Trigger %1$s has been created.') ); - $message->addParam( + $GLOBALS['message']->addParam( Util::backquote($_POST['item_name']) ); $sql_query = $item_query; @@ -167,27 +163,27 @@ class Triggers } } - if (count($errors)) { - $message = Message::error( + if (count($GLOBALS['errors'])) { + $GLOBALS['message'] = Message::error( '' . __( 'One or more errors have occurred while processing your request:' ) . '' ); - $message->addHtml('
    '); - foreach ($errors as $string) { - $message->addHtml('
  • ' . $string . '
  • '); + $GLOBALS['message']->addHtml('
      '); + foreach ($GLOBALS['errors'] as $string) { + $GLOBALS['message']->addHtml('
    • ' . $string . '
    • '); } - $message->addHtml('
    '); + $GLOBALS['message']->addHtml('
'); } - $output = Generator::getMessage($message, $sql_query); + $output = Generator::getMessage($GLOBALS['message'], $sql_query); if ($this->response->isAjax()) { - if ($message->isSuccess()) { - $items = $this->dbi->getTriggers($db, $table, ''); + if ($GLOBALS['message']->isSuccess()) { + $items = $this->dbi->getTriggers($GLOBALS['db'], $GLOBALS['table'], ''); $trigger = false; foreach ($items as $value) { if ($value['name'] != $_POST['item_name']) { @@ -198,14 +194,18 @@ class Triggers } $insert = false; - if (empty($table) || ($trigger !== false && $table == $trigger['table'])) { + if (empty($GLOBALS['table']) || ($trigger !== false && $GLOBALS['table'] == $trigger['table'])) { $insert = true; - $hasTriggerPrivilege = Util::currentUserHasPrivilege('TRIGGER', $db, $table); + $hasTriggerPrivilege = Util::currentUserHasPrivilege( + 'TRIGGER', + $GLOBALS['db'], + $GLOBALS['table'] + ); $this->response->addJSON( 'new_row', $this->template->render('database/triggers/row', [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'trigger' => $trigger, 'has_drop_privilege' => $hasTriggerPrivilege, 'has_edit_privilege' => $hasTriggerPrivilege, @@ -225,7 +225,7 @@ class Triggers $this->response->addJSON('insert', $insert); $this->response->addJSON('message', $output); } else { - $this->response->addJSON('message', $message); + $this->response->addJSON('message', $GLOBALS['message']); $this->response->setRequestStatus(false); } @@ -238,7 +238,7 @@ class Triggers * Display a form used to add/edit a trigger, if necessary */ if ( - ! count($errors) + ! count($GLOBALS['errors']) && (! empty($_POST['editor_process_add']) || ! empty($_POST['editor_process_edit']) || (empty($_REQUEST['add_item']) @@ -269,7 +269,7 @@ class Triggers $mode = 'edit'; } - $this->sendEditor($mode, $item, $title, $db, $table); + $this->sendEditor($mode, $item, $title, $GLOBALS['db'], $GLOBALS['table']); } /** @@ -306,10 +306,8 @@ class Triggers */ public function getDataFromName($name): ?array { - global $db, $table; - $temp = []; - $items = $this->dbi->getTriggers($db, $table, ''); + $items = $this->dbi->getTriggers($GLOBALS['db'], $GLOBALS['table'], ''); foreach ($items as $value) { if ($value['name'] != $name) { continue; @@ -369,8 +367,6 @@ class Triggers */ public function getQueryFromRequest() { - global $db, $errors; - $query = 'CREATE '; if (! empty($_POST['item_definer'])) { if (str_contains($_POST['item_definer'], '@')) { @@ -378,7 +374,7 @@ class Triggers $query .= 'DEFINER=' . Util::backquote($arr[0]); $query .= '@' . Util::backquote($arr[1]) . ' '; } else { - $errors[] = __('The definer must be in the "username@hostname" format!'); + $GLOBALS['errors'][] = __('The definer must be in the "username@hostname" format!'); } } @@ -386,33 +382,33 @@ class Triggers if (! empty($_POST['item_name'])) { $query .= Util::backquote($_POST['item_name']) . ' '; } else { - $errors[] = __('You must provide a trigger name!'); + $GLOBALS['errors'][] = __('You must provide a trigger name!'); } if (! empty($_POST['item_timing']) && in_array($_POST['item_timing'], $this->time)) { $query .= $_POST['item_timing'] . ' '; } else { - $errors[] = __('You must provide a valid timing for the trigger!'); + $GLOBALS['errors'][] = __('You must provide a valid timing for the trigger!'); } if (! empty($_POST['item_event']) && in_array($_POST['item_event'], $this->event)) { $query .= $_POST['item_event'] . ' '; } else { - $errors[] = __('You must provide a valid event for the trigger!'); + $GLOBALS['errors'][] = __('You must provide a valid event for the trigger!'); } $query .= 'ON '; - if (! empty($_POST['item_table']) && in_array($_POST['item_table'], $this->dbi->getTables($db))) { + if (! empty($_POST['item_table']) && in_array($_POST['item_table'], $this->dbi->getTables($GLOBALS['db']))) { $query .= Util::backquote($_POST['item_table']); } else { - $errors[] = __('You must provide a valid table name!'); + $GLOBALS['errors'][] = __('You must provide a valid table name!'); } $query .= ' FOR EACH ROW '; if (! empty($_POST['item_definition'])) { $query .= $_POST['item_definition']; } else { - $errors[] = __('You must provide a trigger definition.'); + $GLOBALS['errors'][] = __('You must provide a trigger definition.'); } return $query; @@ -481,14 +477,12 @@ class Triggers private function export(): void { - global $db, $table; - if (empty($_GET['export_item']) || empty($_GET['item_name'])) { return; } $itemName = $_GET['item_name']; - $triggers = $this->dbi->getTriggers($db, $table, ''); + $triggers = $this->dbi->getTriggers($GLOBALS['db'], $GLOBALS['table'], ''); $exportData = false; foreach ($triggers as $trigger) { @@ -519,7 +513,7 @@ class Triggers $message = sprintf( __('Error in processing request: No trigger with name %1$s found in database %2$s.'), htmlspecialchars(Util::backquote($itemName)), - htmlspecialchars(Util::backquote($db)) + htmlspecialchars(Util::backquote($GLOBALS['db'])) ); $message = Message::error($message); diff --git a/libraries/classes/DatabaseInterface.php b/libraries/classes/DatabaseInterface.php index 3cc1ee4b79..290d261884 100644 --- a/libraries/classes/DatabaseInterface.php +++ b/libraries/classes/DatabaseInterface.php @@ -1724,8 +1724,6 @@ class DatabaseInterface implements DbalInterface public function isGrantUser(): bool { - global $cfg; - if (SessionCache::has('is_grantuser')) { return (bool) SessionCache::get('is_grantuser'); } @@ -1736,7 +1734,7 @@ class DatabaseInterface implements DbalInterface $hasGrantPrivilege = false; - if ($cfg['Server']['DisableIS']) { + if ($GLOBALS['cfg']['Server']['DisableIS']) { $grants = $this->getCurrentUserGrants(); foreach ($grants as $grant) { @@ -1766,8 +1764,6 @@ class DatabaseInterface implements DbalInterface public function isCreateUser(): bool { - global $cfg; - if (SessionCache::has('is_createuser')) { return (bool) SessionCache::get('is_createuser'); } @@ -1778,7 +1774,7 @@ class DatabaseInterface implements DbalInterface $hasCreatePrivilege = false; - if ($cfg['Server']['DisableIS']) { + if ($GLOBALS['cfg']['Server']['DisableIS']) { $grants = $this->getCurrentUserGrants(); foreach ($grants as $grant) { diff --git a/libraries/classes/DbTableExists.php b/libraries/classes/DbTableExists.php index 1877aba337..c70b380c3e 100644 --- a/libraries/classes/DbTableExists.php +++ b/libraries/classes/DbTableExists.php @@ -22,18 +22,16 @@ final class DbTableExists private static function checkDatabase(string $db): void { - global $dbi, $is_db, $message, $show_as_php, $sql_query; - - if (! empty($is_db)) { + if (! empty($GLOBALS['is_db'])) { return; } - $is_db = false; + $GLOBALS['is_db'] = false; if ($db !== '') { - $is_db = @$dbi->selectDb($db); + $GLOBALS['is_db'] = @$GLOBALS['dbi']->selectDb($db); } - if ($is_db || defined('IS_TRANSFORMATION_WRAPPER')) { + if ($GLOBALS['is_db'] || defined('IS_TRANSFORMATION_WRAPPER')) { return; } @@ -50,16 +48,16 @@ final class DbTableExists $urlParams = ['reload' => 1]; - if (isset($message)) { - $urlParams['message'] = $message; + if (isset($GLOBALS['message'])) { + $urlParams['message'] = $GLOBALS['message']; } - if (! empty($sql_query)) { - $urlParams['sql_query'] = $sql_query; + if (! empty($GLOBALS['sql_query'])) { + $urlParams['sql_query'] = $GLOBALS['sql_query']; } - if (isset($show_as_php)) { - $urlParams['show_as_php'] = $show_as_php; + if (isset($GLOBALS['show_as_php'])) { + $urlParams['show_as_php'] = $GLOBALS['show_as_php']; } Core::sendHeaderLocation('./index.php?route=/' . Url::getCommonRaw($urlParams, '&')); @@ -69,24 +67,22 @@ final class DbTableExists private static function checkTable(string $db, string $table): void { - global $containerBuilder, $dbi, $is_table; - - if (! empty($is_table) || defined('PMA_SUBMIT_MULT') || defined('TABLE_MAY_BE_ABSENT')) { + if (! empty($GLOBALS['is_table']) || defined('PMA_SUBMIT_MULT') || defined('TABLE_MAY_BE_ABSENT')) { return; } - $is_table = false; + $GLOBALS['is_table'] = false; if ($table !== '') { - $is_table = $dbi->getCache()->getCachedTableContent([$db, $table], false); - if ($is_table) { + $GLOBALS['is_table'] = $GLOBALS['dbi']->getCache()->getCachedTableContent([$db, $table], false); + if ($GLOBALS['is_table']) { return; } - $result = $dbi->tryQuery('SHOW TABLES LIKE \'' . $dbi->escapeString($table) . '\';'); - $is_table = $result && $result->numRows(); + $result = $GLOBALS['dbi']->tryQuery('SHOW TABLES LIKE \'' . $GLOBALS['dbi']->escapeString($table) . '\';'); + $GLOBALS['is_table'] = $result && $result->numRows(); } - if ($is_table) { + if ($GLOBALS['is_table']) { return; } @@ -99,16 +95,16 @@ final class DbTableExists * SHOW TABLES doesn't show temporary tables, so try select * (as it can happen just in case temporary table, it should be fast): */ - $result = $dbi->tryQuery('SELECT COUNT(*) FROM ' . Util::backquote($table) . ';'); - $is_table = $result && $result->numRows(); + $result = $GLOBALS['dbi']->tryQuery('SELECT COUNT(*) FROM ' . Util::backquote($table) . ';'); + $GLOBALS['is_table'] = $result && $result->numRows(); } - if ($is_table) { + if ($GLOBALS['is_table']) { return; } /** @var SqlController $controller */ - $controller = $containerBuilder->get(SqlController::class); + $controller = $GLOBALS['containerBuilder']->get(SqlController::class); $controller(); exit; diff --git a/libraries/classes/Display/Results.php b/libraries/classes/Display/Results.php index 291ac8ff32..4eb9af3701 100644 --- a/libraries/classes/Display/Results.php +++ b/libraries/classes/Display/Results.php @@ -1403,8 +1403,6 @@ class Results */ private function getFullOrPartialTextButtonOrLink(): string { - global $theme; - $urlParamsFullText = [ 'db' => $this->properties['db'], 'table' => $this->properties['table'], @@ -1425,7 +1423,7 @@ class Results } $tmpImage = '' . $tmpTxt . ''; return Generator::linkOrButton(Url::getFromRoute('/sql'), $urlParamsFullText, $tmpImage); @@ -2101,7 +2099,6 @@ class Results $isLimitedDisplay = false ) { // Mostly because of browser transformations, to make the row-data accessible in a plugin. - global $row; $tableBodyHtml = ''; @@ -2143,7 +2140,7 @@ class Results // delete/edit options correctly for tables without keys. $whereClauseMap = $this->properties['whereClauseMap']; - while ($row = $dtResult->fetchRow()) { + while ($GLOBALS['row'] = $dtResult->fetchRow()) { // add repeating headers if ( ($rowNumber !== 0) && ($_SESSION['tmpval']['repeat_cells'] > 0) @@ -2206,7 +2203,7 @@ class Results [$whereClause, $clauseIsUnique, $conditionArray] = Util::getUniqueCondition( $this->properties['fields_cnt'], $this->properties['fields_meta'], - $row, + $GLOBALS['row'], false, $this->properties['table'], $expressions @@ -2231,7 +2228,7 @@ class Results $clauseIsUnique, $urlSqlQuery, $displayParts->deleteLink, - (int) $row[0] + (int) $GLOBALS['row'][0] ); // 1.3 Displays the links at left if required @@ -2293,7 +2290,7 @@ class Results } $tableBodyHtml .= $this->getRowValues( - $row, + $GLOBALS['row'], $rowNumber, $colOrder, $map, diff --git a/libraries/classes/Engines/Innodb.php b/libraries/classes/Engines/Innodb.php index 716bfae3a3..51626e7ecc 100644 --- a/libraries/classes/Engines/Innodb.php +++ b/libraries/classes/Engines/Innodb.php @@ -117,15 +117,13 @@ class Innodb extends StorageEngine */ public function getPageBufferpool() { - global $dbi; - // The following query is only possible because we know // that we are on MySQL 5 here (checked above)! // side note: I love MySQL 5 for this. :-) $sql = 'SHOW STATUS' . ' WHERE Variable_name LIKE \'Innodb\\_buffer\\_pool\\_%\'' . ' OR Variable_name = \'Innodb_page_size\';'; - $status = $dbi->fetchResult($sql, 0, 1); + $status = $GLOBALS['dbi']->fetchResult($sql, 0, 1); /** @var string[] $bytes */ $bytes = Util::formatByteDown($status['Innodb_buffer_pool_pages_total'] * $status['Innodb_page_size']); @@ -261,10 +259,8 @@ class Innodb extends StorageEngine */ public function getPageStatus() { - global $dbi; - return '
' . "\n"
-            . htmlspecialchars((string) $dbi->fetchValue(
+            . htmlspecialchars((string) $GLOBALS['dbi']->fetchValue(
                 'SHOW ENGINE INNODB STATUS;',
                 'Status'
             )) . "\n" . '
' . "\n"; @@ -288,9 +284,7 @@ class Innodb extends StorageEngine */ public function getInnodbPluginVersion() { - global $dbi; - - return $dbi->fetchValue('SELECT @@innodb_version;') ?: ''; + return $GLOBALS['dbi']->fetchValue('SELECT @@innodb_version;') ?: ''; } /** @@ -302,9 +296,7 @@ class Innodb extends StorageEngine */ public function getInnodbFileFormat(): ?string { - global $dbi; - - $value = $dbi->fetchValue("SHOW GLOBAL VARIABLES LIKE 'innodb_file_format';", 1); + $value = $GLOBALS['dbi']->fetchValue("SHOW GLOBAL VARIABLES LIKE 'innodb_file_format';", 1); if ($value === false) { // This variable does not exist anymore on MariaDB >= 10.6.0 @@ -322,8 +314,6 @@ class Innodb extends StorageEngine */ public function supportsFilePerTable(): bool { - global $dbi; - - return $dbi->fetchValue("SHOW GLOBAL VARIABLES LIKE 'innodb_file_per_table';", 1) === 'ON'; + return $GLOBALS['dbi']->fetchValue("SHOW GLOBAL VARIABLES LIKE 'innodb_file_per_table';", 1) === 'ON'; } } diff --git a/libraries/classes/ErrorHandler.php b/libraries/classes/ErrorHandler.php index fe99961c82..f2273cf96d 100644 --- a/libraries/classes/ErrorHandler.php +++ b/libraries/classes/ErrorHandler.php @@ -194,8 +194,6 @@ class ErrorHandler string $errfile, int $errline ): void { - global $cfg; - if (Util::isErrorReportingAvailable()) { /** * Check if Error Control Operator (@) was used, but still show @@ -207,7 +205,11 @@ class ErrorHandler $isSilenced = error_reporting() == 0; } - if (isset($cfg['environment']) && $cfg['environment'] === 'development' && ! $isSilenced) { + if ( + isset($GLOBALS['cfg']['environment']) + && $GLOBALS['cfg']['environment'] === 'development' + && ! $isSilenced + ) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } diff --git a/libraries/classes/Export.php b/libraries/classes/Export.php index b98fff2eb0..cab8331956 100644 --- a/libraries/classes/Export.php +++ b/libraries/classes/Export.php @@ -125,8 +125,6 @@ class Export */ public function outputHandler(?string $line): bool { - global $time_start, $save_filename; - // Kanji encoding convert feature if ($GLOBALS['output_kanji_conversion']) { $line = Encoding::kanjiStrConv($line, $GLOBALS['knjenc'], $GLOBALS['xkana'] ?? ''); @@ -157,7 +155,7 @@ class Export $GLOBALS['message'] = Message::error( __('Insufficient space to save the file %s.') ); - $GLOBALS['message']->addParam($save_filename); + $GLOBALS['message']->addParam($GLOBALS['save_filename']); return false; } @@ -170,8 +168,8 @@ class Export } } else { $timeNow = time(); - if ($time_start >= $timeNow + 30) { - $time_start = $timeNow; + if ($GLOBALS['time_start'] >= $timeNow + 30) { + $GLOBALS['time_start'] = $timeNow; header('X-pmaPing: Pong'); } } @@ -193,14 +191,14 @@ class Export $GLOBALS['message'] = Message::error( __('Insufficient space to save the file %s.') ); - $GLOBALS['message']->addParam($save_filename); + $GLOBALS['message']->addParam($GLOBALS['save_filename']); return false; } $timeNow = time(); - if ($time_start >= $timeNow + 30) { - $time_start = $timeNow; + if ($GLOBALS['time_start'] >= $timeNow + 30) { + $GLOBALS['time_start'] = $timeNow; header('X-pmaPing: Pong'); } } else { @@ -1153,29 +1151,27 @@ class Export */ public function showPage(string $exportType): void { - global $active_page, $containerBuilder; - if ($exportType === 'server') { - $active_page = Url::getFromRoute('/server/export'); + $GLOBALS['active_page'] = Url::getFromRoute('/server/export'); /** @var ServerExportController $controller */ - $controller = $containerBuilder->get(ServerExportController::class); + $controller = $GLOBALS['containerBuilder']->get(ServerExportController::class); $controller(); return; } if ($exportType === 'database') { - $active_page = Url::getFromRoute('/database/export'); + $GLOBALS['active_page'] = Url::getFromRoute('/database/export'); /** @var DatabaseExportController $controller */ - $controller = $containerBuilder->get(DatabaseExportController::class); + $controller = $GLOBALS['containerBuilder']->get(DatabaseExportController::class); $controller(); return; } - $active_page = Url::getFromRoute('/table/export'); + $GLOBALS['active_page'] = Url::getFromRoute('/table/export'); /** @var TableExportController $controller */ - $controller = $containerBuilder->get(TableExportController::class); + $controller = $GLOBALS['containerBuilder']->get(TableExportController::class); $controller(); } diff --git a/libraries/classes/Export/Options.php b/libraries/classes/Export/Options.php index 028a1e16e9..22bc4d555b 100644 --- a/libraries/classes/Export/Options.php +++ b/libraries/classes/Export/Options.php @@ -114,8 +114,6 @@ final class Options $unlimNumRows, array $exportList ) { - global $cfg; - $exportTemplatesFeature = $this->relation->getRelationParameters()->exportTemplatesFeature; $templates = []; @@ -151,9 +149,9 @@ final class Options unset($_SESSION['tmpval']['aliases']); $filenameTemplate = $this->getFileNameTemplate($exportType, $_POST['filename_template'] ?? null); $isEncodingSupported = Encoding::isSupported(); - $selectedCompression = $_POST['compression'] ?? $cfg['Export']['compression'] ?? 'none'; + $selectedCompression = $_POST['compression'] ?? $GLOBALS['cfg']['Export']['compression'] ?? 'none'; - if (isset($cfg['Export']['as_separate_files']) && $cfg['Export']['as_separate_files']) { + if (isset($GLOBALS['cfg']['Export']['as_separate_files']) && $GLOBALS['cfg']['Export']['as_separate_files']) { $selectedCompression = 'zip'; } @@ -161,7 +159,7 @@ final class Options 'db' => $db, 'table' => $table, 'export_type' => $exportType, - 'export_method' => $_POST['export_method'] ?? $cfg['Export']['method'] ?? 'quick', + 'export_method' => $_POST['export_method'] ?? $GLOBALS['cfg']['Export']['method'] ?? 'quick', 'template_id' => $_POST['template_id'] ?? '', ]; @@ -184,14 +182,14 @@ final class Options ], 'sql_query' => $sqlQuery, 'hidden_inputs' => $hiddenInputs, - 'export_method' => $_POST['quick_or_custom'] ?? $cfg['Export']['method'] ?? '', + 'export_method' => $_POST['quick_or_custom'] ?? $GLOBALS['cfg']['Export']['method'] ?? '', 'plugins_choice' => $dropdown, 'options' => Plugins::getOptions('Export', $exportList), 'can_convert_kanji' => Encoding::canConvertKanji(), - 'exec_time_limit' => $cfg['ExecTimeLimit'], + 'exec_time_limit' => $GLOBALS['cfg']['ExecTimeLimit'], 'rows' => $rows, - 'has_save_dir' => isset($cfg['SaveDir']) && ! empty($cfg['SaveDir']), - 'save_dir' => Util::userDir((string) ($cfg['SaveDir'] ?? '')), + 'has_save_dir' => isset($GLOBALS['cfg']['SaveDir']) && ! empty($GLOBALS['cfg']['SaveDir']), + 'save_dir' => Util::userDir((string) ($GLOBALS['cfg']['SaveDir'] ?? '')), 'export_is_checked' => $this->checkboxCheck('quick_export_onserver'), 'export_overwrite_is_checked' => $this->checkboxCheck('quick_export_onserver_overwrite'), 'has_aliases' => $hasAliases, @@ -206,10 +204,10 @@ final class Options 'lock_tables' => isset($_POST['lock_tables']), 'is_encoding_supported' => $isEncodingSupported, 'encodings' => $isEncodingSupported ? Encoding::listEncodings() : [], - 'export_charset' => $cfg['Export']['charset'], - 'export_asfile' => $cfg['Export']['asfile'], - 'has_zip' => $cfg['ZipDump'] && function_exists('gzcompress'), - 'has_gzip' => $cfg['GZipDump'] && function_exists('gzencode'), + 'export_charset' => $GLOBALS['cfg']['Export']['charset'], + 'export_asfile' => $GLOBALS['cfg']['Export']['asfile'], + 'has_zip' => $GLOBALS['cfg']['ZipDump'] && function_exists('gzcompress'), + 'has_gzip' => $GLOBALS['cfg']['GZipDump'] && function_exists('gzencode'), 'selected_compression' => $selectedCompression, 'filename_template' => $filenameTemplate, ]; @@ -217,20 +215,27 @@ final class Options private function getFileNameTemplate(string $exportType, ?string $filename = null): string { - global $cfg, $config; - if ($filename !== null) { return $filename; } if ($exportType === 'database') { - return (string) $config->getUserValue('pma_db_filename_template', $cfg['Export']['file_template_database']); + return (string) $GLOBALS['config']->getUserValue( + 'pma_db_filename_template', + $GLOBALS['cfg']['Export']['file_template_database'] + ); } if ($exportType === 'table') { - return (string) $config->getUserValue('pma_table_filename_template', $cfg['Export']['file_template_table']); + return (string) $GLOBALS['config']->getUserValue( + 'pma_table_filename_template', + $GLOBALS['cfg']['Export']['file_template_table'] + ); } - return (string) $config->getUserValue('pma_server_filename_template', $cfg['Export']['file_template_server']); + return (string) $GLOBALS['config']->getUserValue( + 'pma_server_filename_template', + $GLOBALS['cfg']['Export']['file_template_server'] + ); } } diff --git a/libraries/classes/FileListing.php b/libraries/classes/FileListing.php index 83b9cbc59d..b2eccb5dd2 100644 --- a/libraries/classes/FileListing.php +++ b/libraries/classes/FileListing.php @@ -97,15 +97,13 @@ class FileListing */ public function supportedDecompressions(): string { - global $cfg; - $compressions = ''; - if ($cfg['GZipDump'] && function_exists('gzopen')) { + if ($GLOBALS['cfg']['GZipDump'] && function_exists('gzopen')) { $compressions = 'gz'; } - if ($cfg['BZipDump'] && function_exists('bzopen')) { + if ($GLOBALS['cfg']['BZipDump'] && function_exists('bzopen')) { if (! empty($compressions)) { $compressions .= '|'; } @@ -113,7 +111,7 @@ class FileListing $compressions .= 'bz2'; } - if ($cfg['ZipDump'] && function_exists('gzinflate')) { + if ($GLOBALS['cfg']['ZipDump'] && function_exists('gzinflate')) { if (! empty($compressions)) { $compressions .= '|'; } diff --git a/libraries/classes/Footer.php b/libraries/classes/Footer.php index 05d259fce9..b69a980ef8 100644 --- a/libraries/classes/Footer.php +++ b/libraries/classes/Footer.php @@ -62,13 +62,11 @@ class Footer */ public function __construct() { - global $dbi; - $this->template = new Template(); $this->isEnabled = true; $this->scripts = new Scripts(); $this->isMinimal = false; - $this->relation = new Relation($dbi); + $this->relation = new Relation($GLOBALS['dbi']); } /** @@ -140,20 +138,18 @@ class Footer */ public function getSelfUrl(): string { - global $db, $table, $server; - $params = []; $params['route'] = Routing::getCurrentRoute(); - if (isset($db) && strlen($db) > 0) { - $params['db'] = $db; + if (isset($GLOBALS['db']) && strlen($GLOBALS['db']) > 0) { + $params['db'] = $GLOBALS['db']; } - if (isset($table) && strlen($table) > 0) { - $params['table'] = $table; + if (isset($GLOBALS['table']) && strlen($GLOBALS['table']) > 0) { + $params['table'] = $GLOBALS['table']; } - $params['server'] = $server; + $params['server'] = $GLOBALS['server']; // needed for server privileges tabs if (isset($_GET['viewing_mode']) && in_array($_GET['viewing_mode'], ['server', 'db', 'table'])) { @@ -208,8 +204,6 @@ class Footer */ private function setHistory(): void { - global $dbi; - if ( ( isset($_REQUEST['no_history']) @@ -218,8 +212,8 @@ class Footer ) || ! empty($GLOBALS['error_message']) || empty($GLOBALS['sql_query']) - || ! isset($dbi) - || ! $dbi->isConnected() + || ! isset($GLOBALS['dbi']) + || ! $GLOBALS['dbi']->isConnected() ) { return; } diff --git a/libraries/classes/Gis/GisVisualization.php b/libraries/classes/Gis/GisVisualization.php index e19b5234f2..c3a994cc26 100644 --- a/libraries/classes/Gis/GisVisualization.php +++ b/libraries/classes/Gis/GisVisualization.php @@ -243,9 +243,7 @@ class GisVisualization */ private function fetchRawData(): array { - global $dbi; - - $modified_result = $dbi->tryQuery($this->modifiedSql); + $modified_result = $GLOBALS['dbi']->tryQuery($this->modifiedSql); if ($modified_result === false) { return []; diff --git a/libraries/classes/Header.php b/libraries/classes/Header.php index 3942a1c270..48e2f6e21b 100644 --- a/libraries/classes/Header.php +++ b/libraries/classes/Header.php @@ -102,8 +102,6 @@ class Header */ public function __construct() { - global $db, $table, $dbi; - $this->template = new Template(); $this->isEnabled = true; @@ -111,7 +109,7 @@ class Header $this->bodyId = ''; $this->title = ''; $this->console = new Console(); - $this->menu = new Menu($dbi, $db ?? '', $table ?? ''); + $this->menu = new Menu($GLOBALS['dbi'], $GLOBALS['db'] ?? '', $GLOBALS['table'] ?? ''); $this->menuEnabled = true; $this->warningsEnabled = true; $this->scripts = new Scripts(); @@ -172,8 +170,6 @@ class Header */ public function getJsParams(): array { - global $db, $table, $dbi; - $pftext = $_SESSION['tmpval']['pftext'] ?? ''; $params = [ @@ -182,8 +178,8 @@ class Header 'opendb_url' => Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'), 'lang' => $GLOBALS['lang'], 'server' => $GLOBALS['server'], - 'table' => $table ?? '', - 'db' => $db ?? '', + 'table' => $GLOBALS['table'] ?? '', + 'db' => $GLOBALS['db'] ?? '', 'token' => $_SESSION[' PMA_token '], 'text_dir' => $GLOBALS['text_dir'], 'LimitChars' => $GLOBALS['cfg']['LimitChars'], @@ -191,7 +187,7 @@ class Header 'confirm' => $GLOBALS['cfg']['Confirm'], 'LoginCookieValidity' => $GLOBALS['cfg']['LoginCookieValidity'], 'session_gc_maxlifetime' => (int) ini_get('session.gc_maxlifetime'), - 'logged_in' => isset($dbi) ? $dbi->isConnected() : false, + 'logged_in' => isset($GLOBALS['dbi']) ? $GLOBALS['dbi']->isConnected() : false, 'is_https' => $GLOBALS['config']->isHttps(), 'rootPath' => $GLOBALS['config']->getRootPath(), 'arg_separator' => Url::getArgSeparator(), @@ -309,15 +305,13 @@ class Header */ public function getDisplay(): string { - global $db, $table, $theme, $dbi; - if ($this->headerIsSent || ! $this->isEnabled) { return ''; } $recentTable = ''; if (empty($_REQUEST['recent_table'])) { - $recentTable = $this->addRecentTable($db, $table); + $recentTable = $this->addRecentTable($GLOBALS['db'], $GLOBALS['table']); } if ($this->isAjax) { @@ -327,7 +321,7 @@ class Header $this->sendHttpHeaders(); $baseDir = defined('PMA_PATH_TO_BASEDIR') ? PMA_PATH_TO_BASEDIR : ''; - $themePath = $theme instanceof Theme ? $theme->getPath() : ''; + $themePath = $GLOBALS['theme'] instanceof Theme ? $GLOBALS['theme']->getPath() : ''; $version = self::getVersionParameter(); // The user preferences have been merged at this point @@ -380,8 +374,8 @@ class Header if ($this->menuEnabled && $GLOBALS['server'] > 0) { $nav = new Navigation( $this->template, - new Relation($dbi), - $dbi + new Relation($GLOBALS['dbi']), + $GLOBALS['dbi'] ); $navigation = $nav->getDisplay(); } @@ -572,20 +566,18 @@ class Header */ private function getCspHeaders(): array { - global $cfg; - $mapTileUrls = ' *.tile.openstreetmap.org'; $captchaUrl = ''; - $cspAllow = $cfg['CSPAllow']; + $cspAllow = $GLOBALS['cfg']['CSPAllow']; if ( - ! empty($cfg['CaptchaLoginPrivateKey']) - && ! empty($cfg['CaptchaLoginPublicKey']) - && ! empty($cfg['CaptchaApi']) - && ! empty($cfg['CaptchaRequestParam']) - && ! empty($cfg['CaptchaResponseParam']) + ! empty($GLOBALS['cfg']['CaptchaLoginPrivateKey']) + && ! empty($GLOBALS['cfg']['CaptchaLoginPublicKey']) + && ! empty($GLOBALS['cfg']['CaptchaApi']) + && ! empty($GLOBALS['cfg']['CaptchaRequestParam']) + && ! empty($GLOBALS['cfg']['CaptchaResponseParam']) ) { - $captchaUrl = ' ' . $cfg['CaptchaCsp'] . ' '; + $captchaUrl = ' ' . $GLOBALS['cfg']['CaptchaCsp'] . ' '; } $headers = []; @@ -666,13 +658,11 @@ class Header private function getVariablesForJavaScript(): string { - global $cfg; - $maxInputVars = ini_get('max_input_vars'); $maxInputVarsValue = $maxInputVars === false || $maxInputVars === '' ? 'false' : (int) $maxInputVars; return $this->template->render('javascript/variables', [ - 'first_day_of_calendar' => $cfg['FirstDayOfCalendar'] ?? 0, + 'first_day_of_calendar' => $GLOBALS['cfg']['FirstDayOfCalendar'] ?? 0, 'max_input_vars' => $maxInputVarsValue, ]); } diff --git a/libraries/classes/Html/Generator.php b/libraries/classes/Html/Generator.php index 37d7661790..0f04c22f77 100644 --- a/libraries/classes/Html/Generator.php +++ b/libraries/classes/Html/Generator.php @@ -165,10 +165,8 @@ class Generator $minimumVersion, $bugReference ): string { - global $dbi; - $return = ''; - if (($component === 'mysql') && ($dbi->getVersion() < $minimumVersion)) { + if (($component === 'mysql') && ($GLOBALS['dbi']->getVersion() < $minimumVersion)) { $return .= self::showHint( sprintf( __('The %s functionality is affected by a known bug, see %s'), @@ -274,19 +272,17 @@ class Generator */ public static function getDefaultFunctionForField(array $field, $insertMode): string { - global $cfg, $data, $dbi; - $defaultFunction = ''; // Can we get field class based values? - $currentClass = $dbi->types->getTypeClass($field['True_Type']); - if (! empty($currentClass) && isset($cfg['DefaultFunctions']['FUNC_' . $currentClass])) { - $defaultFunction = $cfg['DefaultFunctions']['FUNC_' . $currentClass]; + $currentClass = $GLOBALS['dbi']->types->getTypeClass($field['True_Type']); + if (! empty($currentClass) && isset($GLOBALS['cfg']['DefaultFunctions']['FUNC_' . $currentClass])) { + $defaultFunction = $GLOBALS['cfg']['DefaultFunctions']['FUNC_' . $currentClass]; // Change the configured default function to include the ST_ prefix with MySQL 5.6 and later. // It needs to match the function listed in the select html element. if ( $currentClass === 'SPATIAL' && - $dbi->getVersion() >= 50600 && + $GLOBALS['dbi']->getVersion() >= 50600 && strtoupper(substr($defaultFunction, 0, 3)) !== 'ST_' ) { $defaultFunction = 'ST_' . $defaultFunction; @@ -303,11 +299,11 @@ class Generator ($field['True_Type'] === 'timestamp') && $field['first_timestamp'] && empty($field['Default']) - && empty($data) + && empty($GLOBALS['data']) && $field['Extra'] !== 'on update CURRENT_TIMESTAMP' && $field['Null'] === 'NO' ) { - $defaultFunction = $cfg['DefaultFunctions']['first_timestamp']; + $defaultFunction = $GLOBALS['cfg']['DefaultFunctions']['first_timestamp']; } // For primary keys of type char(36) or varchar(36) UUID if the default @@ -318,7 +314,7 @@ class Generator && $field['Key'] === 'PRI' && ($field['Type'] === 'char(36)' || $field['Type'] === 'varchar(36)') ) { - $defaultFunction = $cfg['DefaultFunctions']['FUNC_UUID']; + $defaultFunction = $GLOBALS['cfg']['DefaultFunctions']['FUNC_UUID']; } return $defaultFunction; @@ -335,15 +331,13 @@ class Generator */ public static function getFunctionsForField(array $field, $insertMode, array $foreignData): string { - global $dbi; - $defaultFunction = self::getDefaultFunctionForField($field, $insertMode); // Create the output $retval = '' . "\n"; // loop on the dropdown array and print all available options for that // field. - $functions = $dbi->types->getAllFunctions(); + $functions = $GLOBALS['dbi']->types->getAllFunctions(); foreach ($functions as $function) { $retval .= 'query($sqlQuery); + $result = $GLOBALS['dbi']->query($sqlQuery); $devider = '+'; $columnNames = '|'; - $fieldsMeta = $dbi->getFieldsMeta($result); + $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result); foreach ($fieldsMeta as $meta) { $devider .= '---+'; $columnNames .= ' ' . $meta->name . ' |'; @@ -510,8 +502,6 @@ class Generator $sqlQuery = null, $type = 'notice' ): string { - global $cfg, $dbi; - $retval = ''; if ($sqlQuery === null) { @@ -526,7 +516,7 @@ class Generator } } - $renderSql = $cfg['ShowSQL'] == true && ! empty($sqlQuery) && $sqlQuery !== ';'; + $renderSql = $GLOBALS['cfg']['ShowSQL'] == true && ! empty($sqlQuery) && $sqlQuery !== ';'; if (isset($GLOBALS['using_bookmark_message'])) { $retval .= $GLOBALS['using_bookmark_message']->getDisplay(); @@ -566,11 +556,11 @@ class Generator $queryTooBig = false; $queryLength = mb_strlen($sqlQuery); - if ($queryLength > $cfg['MaxCharactersInDisplayedSQL']) { + if ($queryLength > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) { // when the query is large (for example an INSERT of binary // data), the parser chokes; so avoid parsing the query $queryTooBig = true; - $queryBase = mb_substr($sqlQuery, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'; + $queryBase = mb_substr($sqlQuery, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]'; } else { $queryBase = $sqlQuery; } @@ -621,7 +611,7 @@ class Generator /* SQL-Parser-Analyzer */ $explainLink = ''; $isSelect = preg_match('@^SELECT[[:space:]]+@i', $sqlQuery); - if (! empty($cfg['SQLQuery']['Explain']) && ! $queryTooBig) { + if (! empty($GLOBALS['cfg']['SQLQuery']['Explain']) && ! $queryTooBig) { $explainParams = $urlParams; if ($isSelect) { $explainParams['sql_query'] = 'EXPLAIN ' . $sqlQuery; @@ -659,7 +649,7 @@ class Generator // even if the query is big and was truncated, offer the chance // to edit it (unless it's enormous, see linkOrButton() ) - if (! empty($cfg['SQLQuery']['Edit']) && empty($GLOBALS['show_as_php'])) { + if (! empty($GLOBALS['cfg']['SQLQuery']['Edit']) && empty($GLOBALS['show_as_php'])) { $editLink = ' [ ' . self::linkOrButton($editLink, $urlParams, __('Edit')) . ' ]'; @@ -669,7 +659,7 @@ class Generator // Also we would like to get the SQL formed in some nice // php-code - if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $queryTooBig) { + if (! empty($GLOBALS['cfg']['SQLQuery']['ShowAsPHP']) && ! $queryTooBig) { if (! empty($GLOBALS['show_as_php'])) { $phpLink = ' [ ' . self::linkOrButton( @@ -703,7 +693,7 @@ class Generator // Refresh query if ( - ! empty($cfg['SQLQuery']['Refresh']) + ! empty($GLOBALS['cfg']['SQLQuery']['Refresh']) && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sqlQuery) ) { @@ -726,7 +716,7 @@ class Generator // avoid displaying a Profiling checkbox that could // be checked, which would re-execute an INSERT, for example - if (! empty($refreshLink) && Profiling::isSupported($dbi)) { + if (! empty($refreshLink) && Profiling::isSupported($GLOBALS['dbi'])) { $retval .= ''; $retval .= 'getError(); + $serverMessage = $GLOBALS['dbi']->getError(); } // Finding the query that failed, if not specified. @@ -900,12 +888,12 @@ class Generator 'sql_query' => $sqlQuery, 'show_query' => 1, ]; - if (strlen($table) > 0) { - $urlParams['db'] = $db; - $urlParams['table'] = $table; + if (strlen($GLOBALS['table']) > 0) { + $urlParams['db'] = $GLOBALS['db']; + $urlParams['table'] = $GLOBALS['table']; $doEditGoto = ''; - } elseif (strlen($db) > 0) { - $urlParams['db'] = $db; + } elseif (strlen($GLOBALS['db']) > 0) { + $urlParams['db'] = $GLOBALS['db']; $doEditGoto = ''; } else { $doEditGoto = ''; @@ -1215,10 +1203,8 @@ class Generator */ public static function formatSql($sqlQuery, $truncate = false): string { - global $cfg; - - if ($truncate && mb_strlen($sqlQuery) > $cfg['MaxCharactersInDisplayedSQL']) { - $sqlQuery = mb_substr($sqlQuery, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'; + if ($truncate && mb_strlen($sqlQuery) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) { + $sqlQuery = mb_substr($sqlQuery, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]'; } return '
' . "\n"
@@ -1235,12 +1221,10 @@ class Generator
      */
     public static function getSupportedDatatypes($selected): string
     {
-        global $dbi;
-
         // NOTE: the SELECT tag is not included in this snippet.
         $retval = '';
 
-        foreach ($dbi->types->getColumns() as $key => $value) {
+        foreach ($GLOBALS['dbi']->types->getColumns() as $key => $value) {
             if (is_array($value)) {
                 $retval .= '';
                 foreach ($value as $subvalue) {
@@ -1251,12 +1235,12 @@ class Generator
                         continue;
                     }
 
-                    $isLengthRestricted = Compatibility::isIntegersSupportLength($subvalue, '2', $dbi);
+                    $isLengthRestricted = Compatibility::isIntegersSupportLength($subvalue, '2', $GLOBALS['dbi']);
                     $retval .= sprintf(
                         '',
                         $isLengthRestricted ? 0 : 1,
                         $selected === $subvalue ? 'selected="selected"' : '',
-                        $dbi->types->getTypeDescription($subvalue),
+                        $GLOBALS['dbi']->types->getTypeDescription($subvalue),
                         $subvalue
                     );
                 }
@@ -1265,12 +1249,12 @@ class Generator
                 continue;
             }
 
-            $isLengthRestricted = Compatibility::isIntegersSupportLength($value, '2', $dbi);
+            $isLengthRestricted = Compatibility::isIntegersSupportLength($value, '2', $GLOBALS['dbi']);
             $retval .= sprintf(
                 '',
                 $isLengthRestricted ? 0 : 1,
                 $selected === $value ? 'selected="selected"' : '',
-                $dbi->types->getTypeDescription($value),
+                $GLOBALS['dbi']->types->getTypeDescription($value),
                 $value
             );
         }
diff --git a/libraries/classes/Import.php b/libraries/classes/Import.php
index 48eccd25b0..75e455b392 100644
--- a/libraries/classes/Import.php
+++ b/libraries/classes/Import.php
@@ -68,11 +68,9 @@ class Import
 
     public function __construct()
     {
-        global $dbi;
-
         $GLOBALS['cfg']['Server']['DisableIS'] = false;
 
-        $checkUserPrivileges = new CheckUserPrivileges($dbi);
+        $checkUserPrivileges = new CheckUserPrivileges($GLOBALS['dbi']);
         $checkUserPrivileges->getPrivileges();
     }
 
@@ -81,19 +79,18 @@ class Import
      */
     public function checkTimeout(): bool
     {
-        global $timestamp, $maximum_time, $timeout_passed;
-        if ($maximum_time == 0) {
+        if ($GLOBALS['maximum_time'] == 0) {
             return false;
         }
 
-        if ($timeout_passed) {
+        if ($GLOBALS['timeout_passed']) {
             return true;
 
             /* 5 in next row might be too much */
         }
 
-        if (time() - $timestamp > $maximum_time - 5) {
-            $timeout_passed = true;
+        if (time() - $GLOBALS['timestamp'] > $GLOBALS['maximum_time'] - 5) {
+            $GLOBALS['timeout_passed'] = true;
 
             return true;
         }
@@ -111,42 +108,40 @@ class Import
      */
     public function executeQuery(string $sql, string $full, array &$sqlData): void
     {
-        global $sql_query, $my_die, $error, $reload, $result, $msg, $cfg, $sql_query_disabled, $db, $dbi;
-
-        $result = $dbi->tryQuery($sql);
+        $GLOBALS['result'] = $GLOBALS['dbi']->tryQuery($sql);
 
         // USE query changes the database, son need to track
         // while running multiple queries
         $isUseQuery = mb_stripos($sql, 'use ') !== false;
 
-        $msg = '# ';
-        if ($result === false) { // execution failed
-            if (! isset($my_die)) {
-                $my_die = [];
+        $GLOBALS['msg'] = '# ';
+        if ($GLOBALS['result'] === false) { // execution failed
+            if (! isset($GLOBALS['my_die'])) {
+                $GLOBALS['my_die'] = [];
             }
 
-            $my_die[] = [
+            $GLOBALS['my_die'][] = [
                 'sql' => $full,
-                'error' => $dbi->getError(),
+                'error' => $GLOBALS['dbi']->getError(),
             ];
 
-            $msg .= __('Error');
+            $GLOBALS['msg'] .= __('Error');
 
-            if (! $cfg['IgnoreMultiSubmitErrors']) {
-                $error = true;
+            if (! $GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
+                $GLOBALS['error'] = true;
 
                 return;
             }
         } else {
-            $aNumRows = (int) $result->numRows();
-            $aAffectedRows = (int) @$dbi->affectedRows();
+            $aNumRows = (int) $GLOBALS['result']->numRows();
+            $aAffectedRows = (int) @$GLOBALS['dbi']->affectedRows();
             if ($aNumRows > 0) {
-                $msg .= __('Rows') . ': ' . $aNumRows;
+                $GLOBALS['msg'] .= __('Rows') . ': ' . $aNumRows;
             } elseif ($aAffectedRows > 0) {
                 $message = Message::getMessageForAffectedRows($aAffectedRows);
-                $msg .= $message->getMessage();
+                $GLOBALS['msg'] .= $message->getMessage();
             } else {
-                $msg .= __('MySQL returned an empty result set (i.e. zero rows).');
+                $GLOBALS['msg'] .= __('MySQL returned an empty result set (i.e. zero rows).');
             }
 
             if (($aNumRows > 0) || $isUseQuery) {
@@ -159,22 +154,22 @@ class Import
             }
         }
 
-        if (! $sql_query_disabled) {
-            $sql_query .= $msg . "\n";
+        if (! $GLOBALS['sql_query_disabled']) {
+            $GLOBALS['sql_query'] .= $GLOBALS['msg'] . "\n";
         }
 
         // If a 'USE ' SQL-clause was found and the query
         // succeeded, set our current $db to the new one
-        if ($result != false) {
-            [$db, $reload] = $this->lookForUse($sql, $db, $reload);
+        if ($GLOBALS['result'] != false) {
+            [$GLOBALS['db'], $GLOBALS['reload']] = $this->lookForUse($sql, $GLOBALS['db'], $GLOBALS['reload']);
         }
 
         $pattern = '@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im';
-        if ($result == false || ! preg_match($pattern, $sql)) {
+        if ($GLOBALS['result'] == false || ! preg_match($pattern, $sql)) {
             return;
         }
 
-        $reload = true;
+        $GLOBALS['reload'] = true;
     }
 
     /**
@@ -190,62 +185,60 @@ class Import
         string $full = '',
         array &$sqlData = []
     ): void {
-        global $import_run_buffer, $go_sql, $complete_query, $display_query, $sql_query, $msg,
-            $skip_queries, $executed_queries, $max_sql_len, $read_multiply, $sql_query_disabled, $run_query;
-        $read_multiply = 1;
-        if (! isset($import_run_buffer)) {
+        $GLOBALS['read_multiply'] = 1;
+        if (! isset($GLOBALS['import_run_buffer'])) {
             // Do we have something to push into buffer?
-            $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
+            $GLOBALS['import_run_buffer'] = $this->runQueryPost($sql, $full);
 
             return;
         }
 
         // Should we skip something?
-        if ($skip_queries > 0) {
-            $skip_queries--;
+        if ($GLOBALS['skip_queries'] > 0) {
+            $GLOBALS['skip_queries']--;
             // Do we have something to push into buffer?
-            $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
+            $GLOBALS['import_run_buffer'] = $this->runQueryPost($sql, $full);
 
             return;
         }
 
-        if (! empty($import_run_buffer['sql']) && trim($import_run_buffer['sql']) != '') {
-            $max_sql_len = max(
-                $max_sql_len,
-                mb_strlen($import_run_buffer['sql'])
+        if (! empty($GLOBALS['import_run_buffer']['sql']) && trim($GLOBALS['import_run_buffer']['sql']) != '') {
+            $GLOBALS['max_sql_len'] = max(
+                $GLOBALS['max_sql_len'],
+                mb_strlen($GLOBALS['import_run_buffer']['sql'])
             );
-            if (! $sql_query_disabled) {
-                $sql_query .= $import_run_buffer['full'];
+            if (! $GLOBALS['sql_query_disabled']) {
+                $GLOBALS['sql_query'] .= $GLOBALS['import_run_buffer']['full'];
             }
 
-            $executed_queries++;
+            $GLOBALS['executed_queries']++;
 
-            if ($run_query && $executed_queries < 50) {
-                $go_sql = true;
+            if ($GLOBALS['run_query'] && $GLOBALS['executed_queries'] < 50) {
+                $GLOBALS['go_sql'] = true;
 
-                if (! $sql_query_disabled) {
-                    $complete_query = $sql_query;
-                    $display_query = $sql_query;
+                if (! $GLOBALS['sql_query_disabled']) {
+                    $GLOBALS['complete_query'] = $GLOBALS['sql_query'];
+                    $GLOBALS['display_query'] = $GLOBALS['sql_query'];
                 } else {
-                    $complete_query = '';
-                    $display_query = '';
+                    $GLOBALS['complete_query'] = '';
+                    $GLOBALS['display_query'] = '';
                 }
 
-                $sql_query = $import_run_buffer['sql'];
-                $sqlData['valid_sql'][] = $import_run_buffer['sql'];
-                $sqlData['valid_full'][] = $import_run_buffer['full'];
+                $GLOBALS['sql_query'] = $GLOBALS['import_run_buffer']['sql'];
+                $sqlData['valid_sql'][] = $GLOBALS['import_run_buffer']['sql'];
+                $sqlData['valid_full'][] = $GLOBALS['import_run_buffer']['full'];
                 if (! isset($sqlData['valid_queries'])) {
                     $sqlData['valid_queries'] = 0;
                 }
 
                 $sqlData['valid_queries']++;
-            } elseif ($run_query) {
+            } elseif ($GLOBALS['run_query']) {
                 /* Handle rollback from go_sql */
-                if ($go_sql && isset($sqlData['valid_full'])) {
+                if ($GLOBALS['go_sql'] && isset($sqlData['valid_full'])) {
                     $queries = $sqlData['valid_sql'];
                     $fulls = $sqlData['valid_full'];
                     $count = $sqlData['valid_queries'];
-                    $go_sql = false;
+                    $GLOBALS['go_sql'] = false;
 
                     $sqlData['valid_sql'] = [];
                     $sqlData['valid_queries'] = 0;
@@ -255,52 +248,56 @@ class Import
                     }
                 }
 
-                $this->executeQuery($import_run_buffer['sql'], $import_run_buffer['full'], $sqlData);
+                $this->executeQuery(
+                    $GLOBALS['import_run_buffer']['sql'],
+                    $GLOBALS['import_run_buffer']['full'],
+                    $sqlData
+                );
             }
-        } elseif (! empty($import_run_buffer['full'])) {
-            if ($go_sql) {
-                $complete_query .= $import_run_buffer['full'];
-                $display_query .= $import_run_buffer['full'];
-            } elseif (! $sql_query_disabled) {
-                $sql_query .= $import_run_buffer['full'];
+        } elseif (! empty($GLOBALS['import_run_buffer']['full'])) {
+            if ($GLOBALS['go_sql']) {
+                $GLOBALS['complete_query'] .= $GLOBALS['import_run_buffer']['full'];
+                $GLOBALS['display_query'] .= $GLOBALS['import_run_buffer']['full'];
+            } elseif (! $GLOBALS['sql_query_disabled']) {
+                $GLOBALS['sql_query'] .= $GLOBALS['import_run_buffer']['full'];
             }
         }
 
         // check length of query unless we decided to pass it to /sql
         // (if $run_query is false, we are just displaying so show
         // the complete query in the textarea)
-        if (! $go_sql && $run_query && ! empty($sql_query)) {
-            if (mb_strlen($sql_query) > 50000 || $executed_queries > 50 || $max_sql_len > 1000) {
-                $sql_query = '';
-                $sql_query_disabled = true;
+        if (! $GLOBALS['go_sql'] && $GLOBALS['run_query'] && ! empty($GLOBALS['sql_query'])) {
+            if (
+                mb_strlen($GLOBALS['sql_query']) > 50000
+                || $GLOBALS['executed_queries'] > 50
+                || $GLOBALS['max_sql_len'] > 1000
+            ) {
+                $GLOBALS['sql_query'] = '';
+                $GLOBALS['sql_query_disabled'] = true;
             }
         }
 
         // Do we have something to push into buffer?
-        $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
+        $GLOBALS['import_run_buffer'] = $this->runQueryPost($sql, $full);
 
         // In case of ROLLBACK, notify the user.
         if (! isset($_POST['rollback_query'])) {
             return;
         }
 
-        $msg .= __('[ROLLBACK occurred.]');
+        $GLOBALS['msg'] .= __('[ROLLBACK occurred.]');
     }
 
     /**
      * Return import run buffer
      *
-     * @param array  $importRunBuffer Buffer of queries for import
-     * @param string $sql             SQL query
-     * @param string $full            Query to display
+     * @param string $sql  SQL query
+     * @param string $full Query to display
      *
-     * @return array Buffer of queries for import
+     * @return array|null Buffer of queries for import
      */
-    public function runQueryPost(
-        ?array $importRunBuffer,
-        string $sql,
-        string $full
-    ): ?array {
+    public function runQueryPost(string $sql, string $full): ?array
+    {
         if (! empty($sql) || ! empty($full)) {
             return [
                 'sql' => $sql . ';',
@@ -308,9 +305,7 @@ class Import
             ];
         }
 
-        unset($GLOBALS['import_run_buffer']);
-
-        return $importRunBuffer;
+        return null;
     }
 
     /**
@@ -351,16 +346,14 @@ class Import
      */
     public function getNextChunk(?File $importHandle = null, int $size = 32768)
     {
-        global $charset_conversion, $charset_of_file, $read_multiply;
-
         // Add some progression while reading large amount of data
-        if ($read_multiply <= 8) {
-            $size *= $read_multiply;
+        if ($GLOBALS['read_multiply'] <= 8) {
+            $size *= $GLOBALS['read_multiply'];
         } else {
             $size *= 8;
         }
 
-        $read_multiply++;
+        $GLOBALS['read_multiply']++;
 
         // We can not read too much
         if ($size > $GLOBALS['read_limit']) {
@@ -399,8 +392,8 @@ class Import
         $GLOBALS['finished'] = $importHandle->eof();
         $GLOBALS['offset'] += $size;
 
-        if ($charset_conversion) {
-            return Encoding::convertString($charset_of_file, 'utf-8', $result);
+        if ($GLOBALS['charset_conversion']) {
+            return Encoding::convertString($GLOBALS['charset_of_file'], 'utf-8', $result);
         }
 
         /**
@@ -992,10 +985,8 @@ class Import
         ?array $options = null,
         array &$sqlData = []
     ): void {
-        global $import_notice, $dbi;
-
         /* Needed to quell the beast that is Message */
-        $import_notice = null;
+        $GLOBALS['import_notice'] = null;
 
         /* Take care of the options */
         $collation = $options['db_collation'] ?? 'utf8_general_ci';
@@ -1165,7 +1156,7 @@ class Import
                         }
 
                         $tempSQLStr .= $isVarchar ? "'" : '';
-                        $tempSQLStr .= $dbi->escapeString((string) $tables[$i][self::ROWS][$j][$k]);
+                        $tempSQLStr .= $GLOBALS['dbi']->escapeString((string) $tables[$i][self::ROWS][$j][$k]);
                         $tempSQLStr .= $isVarchar ? "'" : '';
                     }
 
@@ -1338,7 +1329,7 @@ class Import
 
         $message .= '';
 
-        $import_notice = $message;
+        $GLOBALS['import_notice'] = $message;
     }
 
     /**
@@ -1348,8 +1339,6 @@ class Import
      */
     public function handleRollbackRequest(string $sqlQuery): void
     {
-        global $dbi;
-
         $sqlDelimiter = $_POST['sql_delimiter'];
         $queries = explode($sqlDelimiter, $sqlQuery);
         $error = false;
@@ -1367,7 +1356,7 @@ class Import
                 continue;
             }
 
-            $globalError = $dbi->getError();
+            $globalError = $GLOBALS['dbi']->getError();
             if ($globalError) {
                 $error = $globalError;
             } else {
@@ -1386,7 +1375,7 @@ class Import
         }
 
         // If everything fine, START a transaction.
-        $dbi->query('START TRANSACTION');
+        $GLOBALS['dbi']->query('START TRANSACTION');
     }
 
     /**
@@ -1434,8 +1423,6 @@ class Import
      */
     public function isTableTransactional(string $table): bool
     {
-        global $dbi;
-
         $table = explode('.', $table);
         if (count($table) === 2) {
             $db = Util::unQuote($table[0]);
@@ -1450,7 +1437,7 @@ class Import
             . '.' . Util::backquote($table) . ' '
             . 'LIMIT 1';
 
-        $result = $dbi->tryQuery($checkTableQuery);
+        $result = $GLOBALS['dbi']->tryQuery($checkTableQuery);
 
         if (! $result) {
             return false;
@@ -1470,13 +1457,13 @@ class Import
 
         // Query to check if table is 'Transactional'.
         $checkQuery = 'SELECT `ENGINE` FROM `information_schema`.`tables` '
-            . 'WHERE `table_name` = "' . $dbi->escapeString($table) . '" '
-            . 'AND `table_schema` = "' . $dbi->escapeString($db) . '" '
+            . 'WHERE `table_name` = "' . $GLOBALS['dbi']->escapeString($table) . '" '
+            . 'AND `table_schema` = "' . $GLOBALS['dbi']->escapeString($db) . '" '
             . 'AND UPPER(`engine`) IN ("'
             . implode('", "', $transactionalEngines)
             . '")';
 
-        $result = $dbi->tryQuery($checkQuery);
+        $result = $GLOBALS['dbi']->tryQuery($checkQuery);
 
         return $result && $result->numRows() == 1;
     }
@@ -1484,19 +1471,17 @@ class Import
     /** @return string[] */
     public static function getCompressions(): array
     {
-        global $cfg;
-
         $compressions = [];
 
-        if ($cfg['GZipDump'] && function_exists('gzopen')) {
+        if ($GLOBALS['cfg']['GZipDump'] && function_exists('gzopen')) {
             $compressions[] = 'gzip';
         }
 
-        if ($cfg['BZipDump'] && function_exists('bzopen')) {
+        if ($GLOBALS['cfg']['BZipDump'] && function_exists('bzopen')) {
             $compressions[] = 'bzip2';
         }
 
-        if ($cfg['ZipDump'] && function_exists('zip_open')) {
+        if ($GLOBALS['cfg']['ZipDump'] && function_exists('zip_open')) {
             $compressions[] = 'zip';
         }
 
diff --git a/libraries/classes/Index.php b/libraries/classes/Index.php
index 79f9e3a239..691ea919ac 100644
--- a/libraries/classes/Index.php
+++ b/libraries/classes/Index.php
@@ -215,13 +215,11 @@ class Index
      */
     private static function loadIndexes($table, $schema): bool
     {
-        global $dbi;
-
         if (isset(self::$registry[$schema][$table])) {
             return true;
         }
 
-        $_raw_indexes = $dbi->getTableIndexes($schema, $table);
+        $_raw_indexes = $GLOBALS['dbi']->getTableIndexes($schema, $table);
         foreach ($_raw_indexes as $_each_index) {
             $_each_index['Schema'] = $schema;
             $keyName = $_each_index['Key_name'];
diff --git a/libraries/classes/InsertEdit.php b/libraries/classes/InsertEdit.php
index edfeb11e17..05093bb849 100644
--- a/libraries/classes/InsertEdit.php
+++ b/libraries/classes/InsertEdit.php
@@ -2367,15 +2367,13 @@ class InsertEdit
 
     private function isColumnBinary(array $column, bool $isUpload): bool
     {
-        global $cfg;
-
-        if (! $cfg['ShowFunctionFields']) {
+        if (! $GLOBALS['cfg']['ShowFunctionFields']) {
             return false;
         }
 
-        return ($cfg['ProtectBinary'] === 'blob' && $column['is_blob'] && ! $isUpload)
-            || ($cfg['ProtectBinary'] === 'all' && $column['is_binary'])
-            || ($cfg['ProtectBinary'] === 'noblob' && $column['is_binary']);
+        return ($GLOBALS['cfg']['ProtectBinary'] === 'blob' && $column['is_blob'] && ! $isUpload)
+            || ($GLOBALS['cfg']['ProtectBinary'] === 'all' && $column['is_binary'])
+            || ($GLOBALS['cfg']['ProtectBinary'] === 'noblob' && $column['is_binary']);
     }
 
     /**
diff --git a/libraries/classes/IpAllowDeny.php b/libraries/classes/IpAllowDeny.php
index 17b84dd557..ca93dfff85 100644
--- a/libraries/classes/IpAllowDeny.php
+++ b/libraries/classes/IpAllowDeny.php
@@ -238,8 +238,6 @@ class IpAllowDeny
      */
     private function allowDeny($type): bool
     {
-        global $cfg;
-
         // Grabs true IP of the user and returns if it can't be found
         $remote_ip = Core::getIp();
         if (empty($remote_ip)) {
@@ -247,11 +245,11 @@ class IpAllowDeny
         }
 
         // copy username
-        $username = $cfg['Server']['user'];
+        $username = $GLOBALS['cfg']['Server']['user'];
 
         // copy rule database
-        if (isset($cfg['Server']['AllowDeny']['rules'])) {
-            $rules = $cfg['Server']['AllowDeny']['rules'];
+        if (isset($GLOBALS['cfg']['Server']['AllowDeny']['rules'])) {
+            $rules = $GLOBALS['cfg']['Server']['AllowDeny']['rules'];
             if (! is_array($rules)) {
                 $rules = [];
             }
diff --git a/libraries/classes/ListDatabase.php b/libraries/classes/ListDatabase.php
index db97349e31..dc8c0f568b 100644
--- a/libraries/classes/ListDatabase.php
+++ b/libraries/classes/ListDatabase.php
@@ -25,11 +25,9 @@ class ListDatabase extends ListAbstract
 {
     public function __construct()
     {
-        global $dbi;
-
         parent::__construct();
 
-        $checkUserPrivileges = new CheckUserPrivileges($dbi);
+        $checkUserPrivileges = new CheckUserPrivileges($GLOBALS['dbi']);
         $checkUserPrivileges->getPrivileges();
 
         $this->build();
@@ -62,8 +60,6 @@ class ListDatabase extends ListAbstract
      */
     protected function retrieve($like_db_name = null)
     {
-        global $dbi;
-
         $database_list = [];
         $command = '';
         if (! $GLOBALS['cfg']['Server']['DisableIS']) {
@@ -88,7 +84,7 @@ class ListDatabase extends ListAbstract
         }
 
         if ($command) {
-            $database_list = $dbi->fetchResult($command, null, null);
+            $database_list = $GLOBALS['dbi']->fetchResult($command, null, null);
         }
 
         if ($GLOBALS['cfg']['NaturalOrder']) {
diff --git a/libraries/classes/Menu.php b/libraries/classes/Menu.php
index 20cb496654..cd4e389b2a 100644
--- a/libraries/classes/Menu.php
+++ b/libraries/classes/Menu.php
@@ -162,28 +162,26 @@ class Menu
      */
     private function getBreadcrumbs(): string
     {
-        global $cfg;
-
         $server = [];
         $database = [];
         $table = [];
 
-        if (empty($cfg['Server']['host'])) {
-            $cfg['Server']['host'] = '';
+        if (empty($GLOBALS['cfg']['Server']['host'])) {
+            $GLOBALS['cfg']['Server']['host'] = '';
         }
 
-        $server['name'] = ! empty($cfg['Server']['verbose'])
-            ? $cfg['Server']['verbose'] : $cfg['Server']['host'];
-        $server['name'] .= empty($cfg['Server']['port'])
-            ? '' : ':' . $cfg['Server']['port'];
-        $server['url'] = Util::getUrlForOption($cfg['DefaultTabServer'], 'server');
+        $server['name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
+            ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
+        $server['name'] .= empty($GLOBALS['cfg']['Server']['port'])
+            ? '' : ':' . $GLOBALS['cfg']['Server']['port'];
+        $server['url'] = Util::getUrlForOption($GLOBALS['cfg']['DefaultTabServer'], 'server');
 
         if ($this->db !== '') {
             $database['name'] = $this->db;
-            $database['url'] = Util::getUrlForOption($cfg['DefaultTabDatabase'], 'database');
+            $database['url'] = Util::getUrlForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database');
             if ($this->table !== '') {
                 $table['name'] = $this->table;
-                $table['url'] = Util::getUrlForOption($cfg['DefaultTabTable'], 'table');
+                $table['url'] = Util::getUrlForOption($GLOBALS['cfg']['DefaultTabTable'], 'table');
                 $tableObj = $this->dbi->getTable($this->db, $this->table);
                 $table['is_view'] = $tableObj->isView();
                 $table['comment'] = '';
diff --git a/libraries/classes/Navigation/Navigation.php b/libraries/classes/Navigation/Navigation.php
index f7bacef25c..fe7fc7e8da 100644
--- a/libraries/classes/Navigation/Navigation.php
+++ b/libraries/classes/Navigation/Navigation.php
@@ -67,10 +67,8 @@ class Navigation
      */
     public function getDisplay(): string
     {
-        global $cfg;
-
         $logo = [
-            'is_displayed' => $cfg['NavigationDisplayLogo'],
+            'is_displayed' => $GLOBALS['cfg']['NavigationDisplayLogo'],
             'has_link' => false,
             'link' => '#',
             'attributes' => ' target="_blank" rel="noopener noreferrer"',
@@ -80,13 +78,13 @@ class Navigation
         $response = ResponseRenderer::getInstance();
         if (! $response->isAjax()) {
             $logo['source'] = $this->getLogoSource();
-            $logo['has_link'] = (string) $cfg['NavigationLogoLink'] !== '';
-            $logo['link'] = trim((string) $cfg['NavigationLogoLink']);
+            $logo['has_link'] = (string) $GLOBALS['cfg']['NavigationLogoLink'] !== '';
+            $logo['link'] = trim((string) $GLOBALS['cfg']['NavigationLogoLink']);
             if (! Sanitize::checkLink($logo['link'], true)) {
                 $logo['link'] = 'index.php';
             }
 
-            if ($cfg['NavigationLogoLinkWindow'] === 'main') {
+            if ($GLOBALS['cfg']['NavigationLogoLinkWindow'] === 'main') {
                 if (empty(parse_url($logo['link'], PHP_URL_HOST))) {
                     $hasStartChar = strpos($logo['link'], '?');
                     $logo['link'] .= Url::getCommon(
@@ -102,7 +100,7 @@ class Navigation
                 }
             }
 
-            if ($cfg['NavigationDisplayServers'] && count($cfg['Servers']) > 1) {
+            if ($GLOBALS['cfg']['NavigationDisplayServers'] && count($GLOBALS['cfg']['Servers']) > 1) {
                 $serverSelect = Select::render(true, true);
             }
 
@@ -114,7 +112,7 @@ class Navigation
         }
 
         if (! $response->isAjax() || ! empty($_POST['full']) || ! empty($_POST['reload'])) {
-            if ($cfg['ShowDatabasesNavigationAsTree']) {
+            if ($GLOBALS['cfg']['ShowDatabasesNavigationAsTree']) {
                 // provide database tree in navigation
                 $navRender = $this->tree->renderState();
             } else {
@@ -128,19 +126,19 @@ class Navigation
         return $this->template->render('navigation/main', [
             'is_ajax' => $response->isAjax(),
             'logo' => $logo,
-            'config_navigation_width' => $cfg['NavigationWidth'],
-            'is_synced' => $cfg['NavigationLinkWithMainPanel'],
-            'is_highlighted' => $cfg['NavigationTreePointerEnable'],
-            'is_autoexpanded' => $cfg['NavigationTreeAutoexpandSingleDb'],
+            'config_navigation_width' => $GLOBALS['cfg']['NavigationWidth'],
+            'is_synced' => $GLOBALS['cfg']['NavigationLinkWithMainPanel'],
+            'is_highlighted' => $GLOBALS['cfg']['NavigationTreePointerEnable'],
+            'is_autoexpanded' => $GLOBALS['cfg']['NavigationTreeAutoexpandSingleDb'],
             'server' => $GLOBALS['server'],
-            'auth_type' => $cfg['Server']['auth_type'],
-            'is_servers_displayed' => $cfg['NavigationDisplayServers'],
-            'servers' => $cfg['Servers'],
+            'auth_type' => $GLOBALS['cfg']['Server']['auth_type'],
+            'is_servers_displayed' => $GLOBALS['cfg']['NavigationDisplayServers'],
+            'servers' => $GLOBALS['cfg']['Servers'],
             'server_select' => $serverSelect ?? '',
             'navigation_tree' => $navRender,
             'is_navigation_settings_enabled' => ! defined('PMA_DISABLE_NAVI_SETTINGS'),
             'navigation_settings' => $navigationSettings ?? '',
-            'is_drag_drop_import_enabled' => $cfg['enable_drag_drop_import'] === true,
+            'is_drag_drop_import_enabled' => $GLOBALS['cfg']['enable_drag_drop_import'] === true,
             'is_mariadb' => $this->dbi->isMariaDB(),
         ]);
     }
@@ -288,15 +286,13 @@ class Navigation
      */
     private function getLogoSource(): string
     {
-        global $theme;
-
-        if ($theme instanceof Theme) {
-            if (@file_exists($theme->getFsPath() . 'img/logo_left.png')) {
-                return $theme->getPath() . '/img/logo_left.png';
+        if ($GLOBALS['theme'] instanceof Theme) {
+            if (@file_exists($GLOBALS['theme']->getFsPath() . 'img/logo_left.png')) {
+                return $GLOBALS['theme']->getPath() . '/img/logo_left.png';
             }
 
-            if (@file_exists($theme->getFsPath() . 'img/pma_logo2.png')) {
-                return $theme->getPath() . '/img/pma_logo2.png';
+            if (@file_exists($GLOBALS['theme']->getFsPath() . 'img/pma_logo2.png')) {
+                return $GLOBALS['theme']->getPath() . '/img/pma_logo2.png';
             }
         }
 
diff --git a/libraries/classes/Navigation/Nodes/Node.php b/libraries/classes/Navigation/Nodes/Node.php
index e20d7f25a1..5fb0a5c73e 100644
--- a/libraries/classes/Navigation/Nodes/Node.php
+++ b/libraries/classes/Navigation/Nodes/Node.php
@@ -138,8 +138,6 @@ class Node
      */
     public function __construct($name, $type = self::OBJECT, $isGroup = false)
     {
-        global $dbi;
-
         if (strlen((string) $name)) {
             $this->name = $name;
             $this->realName = $name;
@@ -150,7 +148,7 @@ class Node
         }
 
         $this->isGroup = (bool) $isGroup;
-        $this->relation = new Relation($dbi);
+        $this->relation = new Relation($GLOBALS['dbi']);
     }
 
     /**
@@ -397,28 +395,26 @@ class Node
      */
     public function getPresence($type = '', $searchClause = '')
     {
-        global $dbi;
-
         if (! $GLOBALS['cfg']['NavigationTreeEnableGrouping'] || ! $GLOBALS['cfg']['ShowDatabasesNavigationAsTree']) {
             if (isset($GLOBALS['cfg']['Server']['DisableIS']) && ! $GLOBALS['cfg']['Server']['DisableIS']) {
                 $query = 'SELECT COUNT(*) ';
                 $query .= 'FROM INFORMATION_SCHEMA.SCHEMATA ';
                 $query .= $this->getWhereClause('SCHEMA_NAME', $searchClause);
 
-                return (int) $dbi->fetchValue($query);
+                return (int) $GLOBALS['dbi']->fetchValue($query);
             }
 
             if ($GLOBALS['dbs_to_test'] === false) {
                 $query = 'SHOW DATABASES ';
                 $query .= $this->getWhereClause('Database', $searchClause);
 
-                return (int) $dbi->queryAndGetNumRows($query);
+                return (int) $GLOBALS['dbi']->queryAndGetNumRows($query);
             }
 
             $retval = 0;
             foreach ($this->getDatabasesToSearch($searchClause) as $db) {
                 $query = "SHOW DATABASES LIKE '" . $db . "'";
-                $retval += (int) $dbi->queryAndGetNumRows($query);
+                $retval += (int) $GLOBALS['dbi']->queryAndGetNumRows($query);
             }
 
             return $retval;
@@ -435,14 +431,14 @@ class Node
             $query .= $this->getWhereClause('SCHEMA_NAME', $searchClause);
             $query .= ') t ';
 
-            return (int) $dbi->fetchValue($query);
+            return (int) $GLOBALS['dbi']->fetchValue($query);
         }
 
         if ($GLOBALS['dbs_to_test'] !== false) {
             $prefixMap = [];
             foreach ($this->getDatabasesToSearch($searchClause) as $db) {
                 $query = "SHOW DATABASES LIKE '" . $db . "'";
-                $handle = $dbi->tryQuery($query);
+                $handle = $GLOBALS['dbi']->tryQuery($query);
                 if ($handle === false) {
                     continue;
                 }
@@ -467,7 +463,7 @@ class Node
         $prefixMap = [];
         $query = 'SHOW DATABASES ';
         $query .= $this->getWhereClause('Database', $searchClause);
-        $handle = $dbi->tryQuery($query);
+        $handle = $GLOBALS['dbi']->tryQuery($query);
         if ($handle !== false) {
             while ($arr = $handle->fetchRow()) {
                 $prefix = strstr($arr[0], $dbSeparator, true);
@@ -505,12 +501,10 @@ class Node
      */
     private function getDatabasesToSearch($searchClause)
     {
-        global $dbi;
-
         $databases = [];
         if (! empty($searchClause)) {
             $databases = [
-                '%' . $dbi->escapeString($searchClause) . '%',
+                '%' . $GLOBALS['dbi']->escapeString($searchClause) . '%',
             ];
         } elseif (! empty($GLOBALS['cfg']['Server']['only_db'])) {
             $databases = $GLOBALS['cfg']['Server']['only_db'];
@@ -534,20 +528,18 @@ class Node
      */
     private function getWhereClause($columnName, $searchClause = '')
     {
-        global $dbi;
-
         $whereClause = 'WHERE TRUE ';
         if (! empty($searchClause)) {
             $whereClause .= 'AND ' . Util::backquote($columnName)
                 . " LIKE '%";
-            $whereClause .= $dbi->escapeString($searchClause);
+            $whereClause .= $GLOBALS['dbi']->escapeString($searchClause);
             $whereClause .= "%' ";
         }
 
         if (! empty($GLOBALS['cfg']['Server']['hide_db'])) {
             $whereClause .= 'AND ' . Util::backquote($columnName)
                 . " NOT REGEXP '"
-                . $dbi->escapeString($GLOBALS['cfg']['Server']['hide_db'])
+                . $GLOBALS['dbi']->escapeString($GLOBALS['cfg']['Server']['hide_db'])
                 . "' ";
         }
 
@@ -563,7 +555,7 @@ class Node
             foreach ($GLOBALS['cfg']['Server']['only_db'] as $eachOnlyDb) {
                 $subClauses[] = ' ' . Util::backquote($columnName)
                     . " LIKE '"
-                    . $dbi->escapeString($eachOnlyDb) . "' ";
+                    . $GLOBALS['dbi']->escapeString($eachOnlyDb) . "' ";
             }
 
             $whereClause .= implode('OR', $subClauses) . ') ';
@@ -637,18 +629,16 @@ class Node
      */
     public function getNavigationHidingData()
     {
-        global $dbi;
-
         $navigationItemsHidingFeature = $this->relation->getRelationParameters()->navigationItemsHidingFeature;
         if ($navigationItemsHidingFeature !== null) {
             $navTable = Util::backquote($navigationItemsHidingFeature->database)
                 . '.' . Util::backquote($navigationItemsHidingFeature->navigationHiding);
             $sqlQuery = 'SELECT `db_name`, COUNT(*) AS `count` FROM ' . $navTable
                 . " WHERE `username`='"
-                . $dbi->escapeString($GLOBALS['cfg']['Server']['user']) . "'"
+                . $GLOBALS['dbi']->escapeString($GLOBALS['cfg']['Server']['user']) . "'"
                 . ' GROUP BY `db_name`';
 
-            return $dbi->fetchResult($sqlQuery, 'db_name', 'count', DatabaseInterface::CONNECT_CONTROL);
+            return $GLOBALS['dbi']->fetchResult($sqlQuery, 'db_name', 'count', DatabaseInterface::CONNECT_CONTROL);
         }
 
         return null;
@@ -662,10 +652,8 @@ class Node
      */
     private function getDataFromInfoSchema($pos, $searchClause)
     {
-        global $dbi, $cfg;
-
-        $maxItems = $cfg['FirstLevelNavigationItems'];
-        if (! $cfg['NavigationTreeEnableGrouping'] || ! $cfg['ShowDatabasesNavigationAsTree']) {
+        $maxItems = $GLOBALS['cfg']['FirstLevelNavigationItems'];
+        if (! $GLOBALS['cfg']['NavigationTreeEnableGrouping'] || ! $GLOBALS['cfg']['ShowDatabasesNavigationAsTree']) {
             $query = sprintf(
                 'SELECT `SCHEMA_NAME` FROM `INFORMATION_SCHEMA`.`SCHEMATA` %sORDER BY `SCHEMA_NAME` LIMIT %d, %d',
                 $this->getWhereClause('SCHEMA_NAME', $searchClause),
@@ -673,10 +661,10 @@ class Node
                 $maxItems
             );
 
-            return $dbi->fetchResult($query);
+            return $GLOBALS['dbi']->fetchResult($query);
         }
 
-        $dbSeparator = $cfg['NavigationTreeDbSeparator'];
+        $dbSeparator = $GLOBALS['cfg']['NavigationTreeDbSeparator'];
         $query = sprintf(
             'SELECT `SCHEMA_NAME` FROM `INFORMATION_SCHEMA`.`SCHEMATA`, (SELECT DB_first_level'
                 . ' FROM ( SELECT DISTINCT SUBSTRING_INDEX(SCHEMA_NAME, \'%1$s\', 1) DB_first_level'
@@ -684,13 +672,13 @@ class Node
                 . ' ORDER BY DB_first_level ASC LIMIT %3$d, %4$d) t2'
                 . ' %2$sAND 1 = LOCATE(CONCAT(DB_first_level, \'%1$s\'),'
                 . ' CONCAT(SCHEMA_NAME, \'%1$s\')) ORDER BY SCHEMA_NAME ASC',
-            $dbi->escapeString($dbSeparator),
+            $GLOBALS['dbi']->escapeString($dbSeparator),
             $this->getWhereClause('SCHEMA_NAME', $searchClause),
             $pos,
             $maxItems
         );
 
-        return $dbi->fetchResult($query);
+        return $GLOBALS['dbi']->fetchResult($query);
     }
 
     /**
@@ -701,11 +689,9 @@ class Node
      */
     private function getDataFromShowDatabases($pos, $searchClause)
     {
-        global $dbi, $cfg;
-
-        $maxItems = $cfg['FirstLevelNavigationItems'];
-        if (! $cfg['NavigationTreeEnableGrouping'] || ! $cfg['ShowDatabasesNavigationAsTree']) {
-            $handle = $dbi->tryQuery(sprintf(
+        $maxItems = $GLOBALS['cfg']['FirstLevelNavigationItems'];
+        if (! $GLOBALS['cfg']['NavigationTreeEnableGrouping'] || ! $GLOBALS['cfg']['ShowDatabasesNavigationAsTree']) {
+            $handle = $GLOBALS['dbi']->tryQuery(sprintf(
                 'SHOW DATABASES %s',
                 $this->getWhereClause('Database', $searchClause)
             ));
@@ -731,8 +717,8 @@ class Node
             return $retval;
         }
 
-        $dbSeparator = $cfg['NavigationTreeDbSeparator'];
-        $handle = $dbi->tryQuery(sprintf(
+        $dbSeparator = $GLOBALS['cfg']['NavigationTreeDbSeparator'];
+        $handle = $GLOBALS['dbi']->tryQuery(sprintf(
             'SHOW DATABASES %s',
             $this->getWhereClause('Database', $searchClause)
         ));
@@ -759,7 +745,7 @@ class Node
         foreach ($prefixes as $prefix) {
             $subClauses[] = sprintf(
                 ' LOCATE(\'%1$s%2$s\', CONCAT(`Database`, \'%2$s\')) = 1 ',
-                $dbi->escapeString((string) $prefix),
+                $GLOBALS['dbi']->escapeString((string) $prefix),
                 $dbSeparator
             );
         }
@@ -770,7 +756,7 @@ class Node
             implode('OR', $subClauses)
         );
 
-        return $dbi->fetchResult($query);
+        return $GLOBALS['dbi']->fetchResult($query);
     }
 
     /**
@@ -781,14 +767,12 @@ class Node
      */
     private function getDataFromShowDatabasesLike($pos, $searchClause)
     {
-        global $dbi, $cfg;
-
-        $maxItems = $cfg['FirstLevelNavigationItems'];
-        if (! $cfg['NavigationTreeEnableGrouping'] || ! $cfg['ShowDatabasesNavigationAsTree']) {
+        $maxItems = $GLOBALS['cfg']['FirstLevelNavigationItems'];
+        if (! $GLOBALS['cfg']['NavigationTreeEnableGrouping'] || ! $GLOBALS['cfg']['ShowDatabasesNavigationAsTree']) {
             $retval = [];
             $count = 0;
             foreach ($this->getDatabasesToSearch($searchClause) as $db) {
-                $handle = $dbi->tryQuery(sprintf('SHOW DATABASES LIKE \'%s\'', $db));
+                $handle = $GLOBALS['dbi']->tryQuery(sprintf('SHOW DATABASES LIKE \'%s\'', $db));
                 if ($handle === false) {
                     continue;
                 }
@@ -816,12 +800,12 @@ class Node
             return $retval;
         }
 
-        $dbSeparator = $cfg['NavigationTreeDbSeparator'];
+        $dbSeparator = $GLOBALS['cfg']['NavigationTreeDbSeparator'];
         $retval = [];
         $prefixMap = [];
         $total = $pos + $maxItems;
         foreach ($this->getDatabasesToSearch($searchClause) as $db) {
-            $handle = $dbi->tryQuery(sprintf('SHOW DATABASES LIKE \'%s\'', $db));
+            $handle = $GLOBALS['dbi']->tryQuery(sprintf('SHOW DATABASES LIKE \'%s\'', $db));
             if ($handle === false) {
                 continue;
             }
@@ -846,7 +830,7 @@ class Node
         $prefixes = array_slice(array_keys($prefixMap), $pos);
 
         foreach ($this->getDatabasesToSearch($searchClause) as $db) {
-            $handle = $dbi->tryQuery(sprintf('SHOW DATABASES LIKE \'%s\'', $db));
+            $handle = $GLOBALS['dbi']->tryQuery(sprintf('SHOW DATABASES LIKE \'%s\'', $db));
             if ($handle === false) {
                 continue;
             }
diff --git a/libraries/classes/Navigation/Nodes/NodeDatabase.php b/libraries/classes/Navigation/Nodes/NodeDatabase.php
index ed31ee008a..e7ca4f1f57 100644
--- a/libraries/classes/Navigation/Nodes/NodeDatabase.php
+++ b/libraries/classes/Navigation/Nodes/NodeDatabase.php
@@ -107,8 +107,6 @@ class NodeDatabase extends Node
      */
     private function getTableOrViewCount($which, $searchClause, $singleItem)
     {
-        global $dbi;
-
         $db = $this->realName;
         if ($which === 'tables') {
             $condition = 'IN';
@@ -117,7 +115,7 @@ class NodeDatabase extends Node
         }
 
         if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-            $db = $dbi->escapeString($db);
+            $db = $GLOBALS['dbi']->escapeString($db);
             $query = 'SELECT COUNT(*) ';
             $query .= 'FROM `INFORMATION_SCHEMA`.`TABLES` ';
             $query .= "WHERE `TABLE_SCHEMA`='" . $db . "' ";
@@ -126,7 +124,7 @@ class NodeDatabase extends Node
                 $query .= 'AND ' . $this->getWhereClauseForSearch($searchClause, $singleItem, 'TABLE_NAME');
             }
 
-            $retval = (int) $dbi->fetchValue($query);
+            $retval = (int) $GLOBALS['dbi']->fetchValue($query);
         } else {
             $query = 'SHOW FULL TABLES FROM ';
             $query .= Util::backquote($db);
@@ -135,7 +133,7 @@ class NodeDatabase extends Node
                 $query .= 'AND ' . $this->getWhereClauseForSearch($searchClause, $singleItem, 'Tables_in_' . $db);
             }
 
-            $retval = $dbi->queryAndGetNumRows($query);
+            $retval = $GLOBALS['dbi']->queryAndGetNumRows($query);
         }
 
         return $retval;
@@ -183,11 +181,9 @@ class NodeDatabase extends Node
      */
     private function getProcedureCount($searchClause, $singleItem)
     {
-        global $dbi;
-
         $db = $this->realName;
         if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-            $db = $dbi->escapeString($db);
+            $db = $GLOBALS['dbi']->escapeString($db);
             $query = 'SELECT COUNT(*) ';
             $query .= 'FROM `INFORMATION_SCHEMA`.`ROUTINES` ';
             $query .= 'WHERE `ROUTINE_SCHEMA` '
@@ -197,15 +193,15 @@ class NodeDatabase extends Node
                 $query .= 'AND ' . $this->getWhereClauseForSearch($searchClause, $singleItem, 'ROUTINE_NAME');
             }
 
-            $retval = (int) $dbi->fetchValue($query);
+            $retval = (int) $GLOBALS['dbi']->fetchValue($query);
         } else {
-            $db = $dbi->escapeString($db);
+            $db = $GLOBALS['dbi']->escapeString($db);
             $query = "SHOW PROCEDURE STATUS WHERE `Db`='" . $db . "' ";
             if (! empty($searchClause)) {
                 $query .= 'AND ' . $this->getWhereClauseForSearch($searchClause, $singleItem, 'Name');
             }
 
-            $retval = $dbi->queryAndGetNumRows($query);
+            $retval = $GLOBALS['dbi']->queryAndGetNumRows($query);
         }
 
         return $retval;
@@ -223,11 +219,9 @@ class NodeDatabase extends Node
      */
     private function getFunctionCount($searchClause, $singleItem)
     {
-        global $dbi;
-
         $db = $this->realName;
         if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-            $db = $dbi->escapeString($db);
+            $db = $GLOBALS['dbi']->escapeString($db);
             $query = 'SELECT COUNT(*) ';
             $query .= 'FROM `INFORMATION_SCHEMA`.`ROUTINES` ';
             $query .= 'WHERE `ROUTINE_SCHEMA` '
@@ -237,15 +231,15 @@ class NodeDatabase extends Node
                 $query .= 'AND ' . $this->getWhereClauseForSearch($searchClause, $singleItem, 'ROUTINE_NAME');
             }
 
-            $retval = (int) $dbi->fetchValue($query);
+            $retval = (int) $GLOBALS['dbi']->fetchValue($query);
         } else {
-            $db = $dbi->escapeString($db);
+            $db = $GLOBALS['dbi']->escapeString($db);
             $query = "SHOW FUNCTION STATUS WHERE `Db`='" . $db . "' ";
             if (! empty($searchClause)) {
                 $query .= 'AND ' . $this->getWhereClauseForSearch($searchClause, $singleItem, 'Name');
             }
 
-            $retval = $dbi->queryAndGetNumRows($query);
+            $retval = $GLOBALS['dbi']->queryAndGetNumRows($query);
         }
 
         return $retval;
@@ -263,11 +257,9 @@ class NodeDatabase extends Node
      */
     private function getEventCount($searchClause, $singleItem)
     {
-        global $dbi;
-
         $db = $this->realName;
         if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-            $db = $dbi->escapeString($db);
+            $db = $GLOBALS['dbi']->escapeString($db);
             $query = 'SELECT COUNT(*) ';
             $query .= 'FROM `INFORMATION_SCHEMA`.`EVENTS` ';
             $query .= 'WHERE `EVENT_SCHEMA` '
@@ -276,7 +268,7 @@ class NodeDatabase extends Node
                 $query .= 'AND ' . $this->getWhereClauseForSearch($searchClause, $singleItem, 'EVENT_NAME');
             }
 
-            $retval = (int) $dbi->fetchValue($query);
+            $retval = (int) $GLOBALS['dbi']->fetchValue($query);
         } else {
             $db = Util::backquote($db);
             $query = 'SHOW EVENTS FROM ' . $db . ' ';
@@ -284,7 +276,7 @@ class NodeDatabase extends Node
                 $query .= 'WHERE ' . $this->getWhereClauseForSearch($searchClause, $singleItem, 'Name');
             }
 
-            $retval = $dbi->queryAndGetNumRows($query);
+            $retval = $GLOBALS['dbi']->queryAndGetNumRows($query);
         }
 
         return $retval;
@@ -304,15 +296,13 @@ class NodeDatabase extends Node
         $singleItem,
         $columnName
     ) {
-        global $dbi;
-
         $query = '';
         if ($singleItem) {
             $query .= Util::backquote($columnName) . ' = ';
-            $query .= "'" . $dbi->escapeString($searchClause) . "'";
+            $query .= "'" . $GLOBALS['dbi']->escapeString($searchClause) . "'";
         } else {
             $query .= Util::backquote($columnName) . ' LIKE ';
-            $query .= "'%" . $dbi->escapeString($searchClause)
+            $query .= "'%" . $GLOBALS['dbi']->escapeString($searchClause)
                 . "%'";
         }
 
@@ -381,8 +371,6 @@ class NodeDatabase extends Node
      */
     public function getHiddenItems($type)
     {
-        global $dbi;
-
         $db = $this->realName;
         $relationParameters = $this->relation->getRelationParameters();
         if ($relationParameters->navigationItemsHidingFeature === null || $relationParameters->user === null) {
@@ -394,9 +382,9 @@ class NodeDatabase extends Node
         $sqlQuery = 'SELECT `item_name` FROM ' . $navTable
             . " WHERE `username`='" . $relationParameters->user . "'"
             . " AND `item_type`='" . $type
-            . "' AND `db_name`='" . $dbi->escapeString($db)
+            . "' AND `db_name`='" . $GLOBALS['dbi']->escapeString($db)
             . "'";
-        $result = $dbi->tryQueryAsControlUser($sqlQuery);
+        $result = $GLOBALS['dbi']->tryQueryAsControlUser($sqlQuery);
         if ($result) {
             return $result->fetchAllColumn();
         }
@@ -415,8 +403,6 @@ class NodeDatabase extends Node
      */
     private function getTablesOrViews($which, int $pos, $searchClause)
     {
-        global $dbi;
-
         if ($which === 'tables') {
             $condition = 'IN';
         } else {
@@ -427,31 +413,31 @@ class NodeDatabase extends Node
         $retval = [];
         $db = $this->realName;
         if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-            $escdDb = $dbi->escapeString($db);
+            $escdDb = $GLOBALS['dbi']->escapeString($db);
             $query = 'SELECT `TABLE_NAME` AS `name` ';
             $query .= 'FROM `INFORMATION_SCHEMA`.`TABLES` ';
             $query .= "WHERE `TABLE_SCHEMA`='" . $escdDb . "' ";
             $query .= 'AND `TABLE_TYPE` ' . $condition . "('BASE TABLE', 'SYSTEM VERSIONED') ";
             if (! empty($searchClause)) {
                 $query .= "AND `TABLE_NAME` LIKE '%";
-                $query .= $dbi->escapeString($searchClause);
+                $query .= $GLOBALS['dbi']->escapeString($searchClause);
                 $query .= "%'";
             }
 
             $query .= 'ORDER BY `TABLE_NAME` ASC ';
             $query .= 'LIMIT ' . $pos . ', ' . $maxItems;
-            $retval = $dbi->fetchResult($query);
+            $retval = $GLOBALS['dbi']->fetchResult($query);
         } else {
             $query = ' SHOW FULL TABLES FROM ';
             $query .= Util::backquote($db);
             $query .= ' WHERE `Table_type` ' . $condition . "('BASE TABLE', 'SYSTEM VERSIONED') ";
             if (! empty($searchClause)) {
                 $query .= 'AND ' . Util::backquote('Tables_in_' . $db);
-                $query .= " LIKE '%" . $dbi->escapeString($searchClause);
+                $query .= " LIKE '%" . $GLOBALS['dbi']->escapeString($searchClause);
                 $query .= "%'";
             }
 
-            $handle = $dbi->tryQuery($query);
+            $handle = $GLOBALS['dbi']->tryQuery($query);
             if ($handle !== false) {
                 $count = 0;
                 if ($handle->seek($pos)) {
@@ -507,13 +493,11 @@ class NodeDatabase extends Node
      */
     private function getRoutines($routineType, $pos, $searchClause)
     {
-        global $dbi;
-
         $maxItems = $GLOBALS['cfg']['MaxNavigationItems'];
         $retval = [];
         $db = $this->realName;
         if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-            $escdDb = $dbi->escapeString($db);
+            $escdDb = $GLOBALS['dbi']->escapeString($db);
             $query = 'SELECT `ROUTINE_NAME` AS `name` ';
             $query .= 'FROM `INFORMATION_SCHEMA`.`ROUTINES` ';
             $query .= 'WHERE `ROUTINE_SCHEMA` '
@@ -521,23 +505,23 @@ class NodeDatabase extends Node
             $query .= "AND `ROUTINE_TYPE`='" . $routineType . "' ";
             if (! empty($searchClause)) {
                 $query .= "AND `ROUTINE_NAME` LIKE '%";
-                $query .= $dbi->escapeString($searchClause);
+                $query .= $GLOBALS['dbi']->escapeString($searchClause);
                 $query .= "%'";
             }
 
             $query .= 'ORDER BY `ROUTINE_NAME` ASC ';
             $query .= 'LIMIT ' . intval($pos) . ', ' . $maxItems;
-            $retval = $dbi->fetchResult($query);
+            $retval = $GLOBALS['dbi']->fetchResult($query);
         } else {
-            $escdDb = $dbi->escapeString($db);
+            $escdDb = $GLOBALS['dbi']->escapeString($db);
             $query = 'SHOW ' . $routineType . " STATUS WHERE `Db`='" . $escdDb . "' ";
             if (! empty($searchClause)) {
                 $query .= "AND `Name` LIKE '%";
-                $query .= $dbi->escapeString($searchClause);
+                $query .= $GLOBALS['dbi']->escapeString($searchClause);
                 $query .= "%'";
             }
 
-            $handle = $dbi->tryQuery($query);
+            $handle = $GLOBALS['dbi']->tryQuery($query);
             if ($handle !== false) {
                 $count = 0;
                 if ($handle->seek($pos)) {
@@ -592,36 +576,34 @@ class NodeDatabase extends Node
      */
     private function getEvents($pos, $searchClause)
     {
-        global $dbi;
-
         $maxItems = $GLOBALS['cfg']['MaxNavigationItems'];
         $retval = [];
         $db = $this->realName;
         if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-            $escdDb = $dbi->escapeString($db);
+            $escdDb = $GLOBALS['dbi']->escapeString($db);
             $query = 'SELECT `EVENT_NAME` AS `name` ';
             $query .= 'FROM `INFORMATION_SCHEMA`.`EVENTS` ';
             $query .= 'WHERE `EVENT_SCHEMA` '
                 . Util::getCollateForIS() . "='" . $escdDb . "' ";
             if (! empty($searchClause)) {
                 $query .= "AND `EVENT_NAME` LIKE '%";
-                $query .= $dbi->escapeString($searchClause);
+                $query .= $GLOBALS['dbi']->escapeString($searchClause);
                 $query .= "%'";
             }
 
             $query .= 'ORDER BY `EVENT_NAME` ASC ';
             $query .= 'LIMIT ' . intval($pos) . ', ' . $maxItems;
-            $retval = $dbi->fetchResult($query);
+            $retval = $GLOBALS['dbi']->fetchResult($query);
         } else {
             $escdDb = Util::backquote($db);
             $query = 'SHOW EVENTS FROM ' . $escdDb . ' ';
             if (! empty($searchClause)) {
                 $query .= "WHERE `Name` LIKE '%";
-                $query .= $dbi->escapeString($searchClause);
+                $query .= $GLOBALS['dbi']->escapeString($searchClause);
                 $query .= "%'";
             }
 
-            $handle = $dbi->tryQuery($query);
+            $handle = $GLOBALS['dbi']->tryQuery($query);
             if ($handle !== false) {
                 $count = 0;
                 if ($handle->seek($pos)) {
diff --git a/libraries/classes/Navigation/Nodes/NodeDatabaseContainer.php b/libraries/classes/Navigation/Nodes/NodeDatabaseContainer.php
index 8d2b9e5a9e..f68bcc2109 100644
--- a/libraries/classes/Navigation/Nodes/NodeDatabaseContainer.php
+++ b/libraries/classes/Navigation/Nodes/NodeDatabaseContainer.php
@@ -24,9 +24,7 @@ class NodeDatabaseContainer extends Node
      */
     public function __construct($name)
     {
-        global $dbi;
-
-        $checkUserPrivileges = new CheckUserPrivileges($dbi);
+        $checkUserPrivileges = new CheckUserPrivileges($GLOBALS['dbi']);
         $checkUserPrivileges->getPrivileges();
 
         parent::__construct($name, Node::CONTAINER);
diff --git a/libraries/classes/Navigation/Nodes/NodeTable.php b/libraries/classes/Navigation/Nodes/NodeTable.php
index a80cc58994..9856ac2c27 100644
--- a/libraries/classes/Navigation/Nodes/NodeTable.php
+++ b/libraries/classes/Navigation/Nodes/NodeTable.php
@@ -83,26 +83,24 @@ class NodeTable extends NodeDatabaseChild
      */
     public function getPresence($type = '', $searchClause = '')
     {
-        global $dbi;
-
         $retval = 0;
         $db = $this->realParent()->realName;
         $table = $this->realName;
         switch ($type) {
             case 'columns':
                 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-                    $db = $dbi->escapeString($db);
-                    $table = $dbi->escapeString($table);
+                    $db = $GLOBALS['dbi']->escapeString($db);
+                    $table = $GLOBALS['dbi']->escapeString($table);
                     $query = 'SELECT COUNT(*) ';
                     $query .= 'FROM `INFORMATION_SCHEMA`.`COLUMNS` ';
                     $query .= "WHERE `TABLE_NAME`='" . $table . "' ";
                     $query .= "AND `TABLE_SCHEMA`='" . $db . "'";
-                    $retval = (int) $dbi->fetchValue($query);
+                    $retval = (int) $GLOBALS['dbi']->fetchValue($query);
                 } else {
                     $db = Util::backquote($db);
                     $table = Util::backquote($table);
                     $query = 'SHOW COLUMNS FROM ' . $table . ' FROM ' . $db . '';
-                    $retval = (int) $dbi->queryAndGetNumRows($query);
+                    $retval = (int) $GLOBALS['dbi']->queryAndGetNumRows($query);
                 }
 
                 break;
@@ -110,24 +108,24 @@ class NodeTable extends NodeDatabaseChild
                 $db = Util::backquote($db);
                 $table = Util::backquote($table);
                 $query = 'SHOW INDEXES FROM ' . $table . ' FROM ' . $db;
-                $retval = (int) $dbi->queryAndGetNumRows($query);
+                $retval = (int) $GLOBALS['dbi']->queryAndGetNumRows($query);
                 break;
             case 'triggers':
                 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-                    $db = $dbi->escapeString($db);
-                    $table = $dbi->escapeString($table);
+                    $db = $GLOBALS['dbi']->escapeString($db);
+                    $table = $GLOBALS['dbi']->escapeString($table);
                     $query = 'SELECT COUNT(*) ';
                     $query .= 'FROM `INFORMATION_SCHEMA`.`TRIGGERS` ';
                     $query .= 'WHERE `EVENT_OBJECT_SCHEMA` '
                     . Util::getCollateForIS() . "='" . $db . "' ";
                     $query .= 'AND `EVENT_OBJECT_TABLE` '
                     . Util::getCollateForIS() . "='" . $table . "'";
-                    $retval = (int) $dbi->fetchValue($query);
+                    $retval = (int) $GLOBALS['dbi']->fetchValue($query);
                 } else {
                     $db = Util::backquote($db);
-                    $table = $dbi->escapeString($table);
+                    $table = $GLOBALS['dbi']->escapeString($table);
                     $query = 'SHOW TRIGGERS FROM ' . $db . " WHERE `Table` = '" . $table . "'";
-                    $retval = (int) $dbi->queryAndGetNumRows($query);
+                    $retval = (int) $GLOBALS['dbi']->queryAndGetNumRows($query);
                 }
 
                 break;
@@ -152,8 +150,6 @@ class NodeTable extends NodeDatabaseChild
      */
     public function getData($type, $pos, $searchClause = '')
     {
-        global $dbi;
-
         $maxItems = $GLOBALS['cfg']['MaxNavigationItems'];
         $retval = [];
         $db = $this->realParent()->realName;
@@ -161,8 +157,8 @@ class NodeTable extends NodeDatabaseChild
         switch ($type) {
             case 'columns':
                 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-                    $db = $dbi->escapeString($db);
-                    $table = $dbi->escapeString($table);
+                    $db = $GLOBALS['dbi']->escapeString($db);
+                    $table = $GLOBALS['dbi']->escapeString($table);
                     $query = 'SELECT `COLUMN_NAME` AS `name` ';
                     $query .= ',`COLUMN_KEY` AS `key` ';
                     $query .= ',`DATA_TYPE` AS `type` ';
@@ -173,14 +169,14 @@ class NodeTable extends NodeDatabaseChild
                     $query .= "AND `TABLE_SCHEMA`='" . $db . "' ";
                     $query .= 'ORDER BY `COLUMN_NAME` ASC ';
                     $query .= 'LIMIT ' . intval($pos) . ', ' . $maxItems;
-                    $retval = $dbi->fetchResult($query);
+                    $retval = $GLOBALS['dbi']->fetchResult($query);
                     break;
                 }
 
                 $db = Util::backquote($db);
                 $table = Util::backquote($table);
                 $query = 'SHOW COLUMNS FROM ' . $table . ' FROM ' . $db;
-                $handle = $dbi->tryQuery($query);
+                $handle = $GLOBALS['dbi']->tryQuery($query);
                 if ($handle === false) {
                     break;
                 }
@@ -208,7 +204,7 @@ class NodeTable extends NodeDatabaseChild
                 $db = Util::backquote($db);
                 $table = Util::backquote($table);
                 $query = 'SHOW INDEXES FROM ' . $table . ' FROM ' . $db;
-                $handle = $dbi->tryQuery($query);
+                $handle = $GLOBALS['dbi']->tryQuery($query);
                 if ($handle === false) {
                     break;
                 }
@@ -230,8 +226,8 @@ class NodeTable extends NodeDatabaseChild
                 break;
             case 'triggers':
                 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
-                    $db = $dbi->escapeString($db);
-                    $table = $dbi->escapeString($table);
+                    $db = $GLOBALS['dbi']->escapeString($db);
+                    $table = $GLOBALS['dbi']->escapeString($table);
                     $query = 'SELECT `TRIGGER_NAME` AS `name` ';
                     $query .= 'FROM `INFORMATION_SCHEMA`.`TRIGGERS` ';
                     $query .= 'WHERE `EVENT_OBJECT_SCHEMA` '
@@ -240,14 +236,14 @@ class NodeTable extends NodeDatabaseChild
                     . Util::getCollateForIS() . "='" . $table . "' ";
                     $query .= 'ORDER BY `TRIGGER_NAME` ASC ';
                     $query .= 'LIMIT ' . intval($pos) . ', ' . $maxItems;
-                    $retval = $dbi->fetchResult($query);
+                    $retval = $GLOBALS['dbi']->fetchResult($query);
                     break;
                 }
 
                 $db = Util::backquote($db);
-                $table = $dbi->escapeString($table);
+                $table = $GLOBALS['dbi']->escapeString($table);
                 $query = 'SHOW TRIGGERS FROM ' . $db . " WHERE `Table` = '" . $table . "'";
-                $handle = $dbi->tryQuery($query);
+                $handle = $GLOBALS['dbi']->tryQuery($query);
                 if ($handle === false) {
                     break;
                 }
diff --git a/libraries/classes/Operations.php b/libraries/classes/Operations.php
index 164a1f702f..a314c4071e 100644
--- a/libraries/classes/Operations.php
+++ b/libraries/classes/Operations.php
@@ -549,8 +549,6 @@ class Operations
      */
     public function getPartitionMaintenanceChoices(): array
     {
-        global $db, $table;
-
         $choices = [
             'ANALYZE' => __('Analyze'),
             'CHECK' => __('Check'),
@@ -560,7 +558,7 @@ class Operations
             'TRUNCATE' => __('Truncate'),
         ];
 
-        $partitionMethod = Partition::getPartitionMethod($db, $table);
+        $partitionMethod = Partition::getPartitionMethod($GLOBALS['db'], $GLOBALS['table']);
 
         // add COALESCE or DROP option to choices array depending on Partition method
         if (
@@ -587,34 +585,32 @@ class Operations
         array $urlParams,
         $hasRelationFeature
     ): array {
-        global $db, $table;
-
         if (! $hasRelationFeature) {
             return [];
         }
 
         $foreigners = [];
-        $this->dbi->selectDb($db);
-        $foreign = $this->relation->getForeigners($db, $table, '', 'internal');
+        $this->dbi->selectDb($GLOBALS['db']);
+        $foreign = $this->relation->getForeigners($GLOBALS['db'], $GLOBALS['table'], '', 'internal');
 
         foreach ($foreign as $master => $arr) {
             $joinQuery = 'SELECT '
-                . Util::backquote($table) . '.*'
-                . ' FROM ' . Util::backquote($table)
+                . Util::backquote($GLOBALS['table']) . '.*'
+                . ' FROM ' . Util::backquote($GLOBALS['table'])
                 . ' LEFT JOIN '
                 . Util::backquote($arr['foreign_db'])
                 . '.'
                 . Util::backquote($arr['foreign_table']);
 
-            if ($arr['foreign_table'] == $table) {
-                $foreignTable = $table . '1';
+            if ($arr['foreign_table'] == $GLOBALS['table']) {
+                $foreignTable = $GLOBALS['table'] . '1';
                 $joinQuery .= ' AS ' . Util::backquote($foreignTable);
             } else {
                 $foreignTable = $arr['foreign_table'];
             }
 
             $joinQuery .= ' ON '
-                . Util::backquote($table) . '.'
+                . Util::backquote($GLOBALS['table']) . '.'
                 . Util::backquote($master)
                 . ' = '
                 . Util::backquote($arr['foreign_db'])
@@ -627,7 +623,7 @@ class Operations
                 . Util::backquote($foreignTable) . '.'
                 . Util::backquote($arr['foreign_field'])
                 . ' IS NULL AND '
-                . Util::backquote($table) . '.'
+                . Util::backquote($GLOBALS['table']) . '.'
                 . Util::backquote($master)
                 . ' IS NOT NULL';
             $thisUrlParams = array_merge(
@@ -676,8 +672,6 @@ class Operations
         $transactional,
         $tbl_collation
     ) {
-        global $auto_increment;
-
         $table_alters = [];
 
         if (isset($_POST['comment']) && urldecode($_POST['prev_comment']) !== $_POST['comment']) {
@@ -728,8 +722,8 @@ class Operations
         if (
             $pma_table->isEngine(['MYISAM', 'ARIA', 'INNODB', 'PBXT', 'ROCKSDB'])
             && ! empty($_POST['new_auto_increment'])
-            && (! isset($auto_increment)
-            || $_POST['new_auto_increment'] !== $auto_increment)
+            && (! isset($GLOBALS['auto_increment'])
+            || $_POST['new_auto_increment'] !== $GLOBALS['auto_increment'])
             && $_POST['new_auto_increment'] !== $_POST['hidden_auto_increment']
         ) {
             $table_alters[] = 'auto_increment = '
diff --git a/libraries/classes/Partitioning/Partition.php b/libraries/classes/Partitioning/Partition.php
index 21c0bf1c91..4caee2cb4b 100644
--- a/libraries/classes/Partitioning/Partition.php
+++ b/libraries/classes/Partitioning/Partition.php
@@ -144,13 +144,11 @@ class Partition extends SubPartition
      */
     public static function getPartitions($db, $table)
     {
-        global $dbi;
-
         if (self::havePartitioning()) {
-            $result = $dbi->fetchResult(
+            $result = $GLOBALS['dbi']->fetchResult(
                 'SELECT * FROM `information_schema`.`PARTITIONS`'
-                . " WHERE `TABLE_SCHEMA` = '" . $dbi->escapeString($db)
-                . "' AND `TABLE_NAME` = '" . $dbi->escapeString($table) . "'"
+                . " WHERE `TABLE_SCHEMA` = '" . $GLOBALS['dbi']->escapeString($db)
+                . "' AND `TABLE_NAME` = '" . $GLOBALS['dbi']->escapeString($table) . "'"
             );
             if ($result) {
                 $partitionMap = [];
@@ -191,13 +189,11 @@ class Partition extends SubPartition
      */
     public static function getPartitionNames($db, $table)
     {
-        global $dbi;
-
         if (self::havePartitioning()) {
-            return $dbi->fetchResult(
+            return $GLOBALS['dbi']->fetchResult(
                 'SELECT DISTINCT `PARTITION_NAME` FROM `information_schema`.`PARTITIONS`'
-                . " WHERE `TABLE_SCHEMA` = '" . $dbi->escapeString($db)
-                . "' AND `TABLE_NAME` = '" . $dbi->escapeString($table) . "'"
+                . " WHERE `TABLE_SCHEMA` = '" . $GLOBALS['dbi']->escapeString($db)
+                . "' AND `TABLE_NAME` = '" . $GLOBALS['dbi']->escapeString($table) . "'"
             );
         }
 
@@ -214,13 +210,11 @@ class Partition extends SubPartition
      */
     public static function getPartitionMethod($db, $table)
     {
-        global $dbi;
-
         if (self::havePartitioning()) {
-            $partition_method = $dbi->fetchResult(
+            $partition_method = $GLOBALS['dbi']->fetchResult(
                 'SELECT `PARTITION_METHOD` FROM `information_schema`.`PARTITIONS`'
-                . " WHERE `TABLE_SCHEMA` = '" . $dbi->escapeString($db) . "'"
-                . " AND `TABLE_NAME` = '" . $dbi->escapeString($table) . "'"
+                . " WHERE `TABLE_SCHEMA` = '" . $GLOBALS['dbi']->escapeString($db) . "'"
+                . " AND `TABLE_NAME` = '" . $GLOBALS['dbi']->escapeString($table) . "'"
                 . ' LIMIT 1'
             );
             if (! empty($partition_method)) {
@@ -240,21 +234,19 @@ class Partition extends SubPartition
      */
     public static function havePartitioning(): bool
     {
-        global $dbi;
-
         static $have_partitioning = false;
         static $already_checked = false;
 
         if (! $already_checked) {
-            if ($dbi->getVersion() < 50600) {
-                if ($dbi->fetchValue('SELECT @@have_partitioning;')) {
+            if ($GLOBALS['dbi']->getVersion() < 50600) {
+                if ($GLOBALS['dbi']->fetchValue('SELECT @@have_partitioning;')) {
                     $have_partitioning = true;
                 }
-            } elseif ($dbi->getVersion() >= 80000) {
+            } elseif ($GLOBALS['dbi']->getVersion() >= 80000) {
                 $have_partitioning = true;
             } else {
                 // see https://dev.mysql.com/doc/refman/5.6/en/partitioning.html
-                $plugins = $dbi->fetchResult('SHOW PLUGINS');
+                $plugins = $GLOBALS['dbi']->fetchResult('SHOW PLUGINS');
                 foreach ($plugins as $value) {
                     if ($value['Name'] === 'partition') {
                         $have_partitioning = true;
diff --git a/libraries/classes/Plugins.php b/libraries/classes/Plugins.php
index 9674aa98cf..8620f5d257 100644
--- a/libraries/classes/Plugins.php
+++ b/libraries/classes/Plugins.php
@@ -58,9 +58,7 @@ class Plugins
      */
     public static function getPlugin(string $type, string $format, $param = null): ?object
     {
-        global $plugin_param;
-
-        $plugin_param = $param;
+        $GLOBALS['plugin_param'] = $param;
         $pluginType = mb_strtoupper($type[0]) . mb_strtolower(mb_substr($type, 1));
         $pluginFormat = mb_strtoupper($format[0]) . mb_strtolower(mb_substr($format, 1));
         $class = sprintf('PhpMyAdmin\\Plugins\\%s\\%s%s', $pluginType, $pluginType, $pluginFormat);
@@ -78,9 +76,7 @@ class Plugins
      */
     public static function getExport(string $type, bool $singleTable): array
     {
-        global $plugin_param;
-
-        $plugin_param = ['export_type' => $type, 'single_table' => $singleTable];
+        $GLOBALS['plugin_param'] = ['export_type' => $type, 'single_table' => $singleTable];
 
         return self::getPlugins('Export');
     }
@@ -92,9 +88,7 @@ class Plugins
      */
     public static function getImport(string $type): array
     {
-        global $plugin_param;
-
-        $plugin_param = $type;
+        $GLOBALS['plugin_param'] = $type;
 
         return self::getPlugins('Import');
     }
@@ -600,15 +594,14 @@ class Plugins
 
     public static function getAuthPlugin(): AuthenticationPlugin
     {
-        global $cfg;
-
         /** @psalm-var class-string $class */
-        $class = 'PhpMyAdmin\\Plugins\\Auth\\Authentication' . ucfirst(strtolower($cfg['Server']['auth_type']));
+        $class = 'PhpMyAdmin\\Plugins\\Auth\\Authentication'
+            . ucfirst(strtolower($GLOBALS['cfg']['Server']['auth_type']));
 
         if (! class_exists($class)) {
             Core::fatalError(
                 __('Invalid authentication method set in configuration:')
-                    . ' ' . $cfg['Server']['auth_type']
+                    . ' ' . $GLOBALS['cfg']['Server']['auth_type']
             );
         }
 
diff --git a/libraries/classes/Plugins/Auth/AuthenticationConfig.php b/libraries/classes/Plugins/Auth/AuthenticationConfig.php
index 6f814a7d70..17b29c06a7 100644
--- a/libraries/classes/Plugins/Auth/AuthenticationConfig.php
+++ b/libraries/classes/Plugins/Auth/AuthenticationConfig.php
@@ -73,10 +73,8 @@ class AuthenticationConfig extends AuthenticationPlugin
      */
     public function showFailure($failure): void
     {
-        global $dbi;
-
         parent::showFailure($failure);
-        $conn_error = $dbi->getError();
+        $conn_error = $GLOBALS['dbi']->getError();
         if (! $conn_error) {
             $conn_error = __('Cannot connect: invalid settings.');
         }
diff --git a/libraries/classes/Plugins/Auth/AuthenticationCookie.php b/libraries/classes/Plugins/Auth/AuthenticationCookie.php
index 28b5fd99fb..1198e14d17 100644
--- a/libraries/classes/Plugins/Auth/AuthenticationCookie.php
+++ b/libraries/classes/Plugins/Auth/AuthenticationCookie.php
@@ -64,8 +64,6 @@ class AuthenticationCookie extends AuthenticationPlugin
      */
     public function showLoginForm(): bool
     {
-        global $conn_error;
-
         $response = ResponseRenderer::getInstance();
 
         /**
@@ -127,8 +125,8 @@ class AuthenticationCookie extends AuthenticationPlugin
 
         $errorMessages = '';
         // Show error message
-        if (! empty($conn_error)) {
-            $errorMessages = Message::rawError((string) $conn_error)->getDisplay();
+        if (! empty($GLOBALS['conn_error'])) {
+            $errorMessages = Message::rawError((string) $GLOBALS['conn_error'])->getDisplay();
         } elseif (isset($_GET['session_expired']) && intval($_GET['session_expired']) == 1) {
             $errorMessages = Message::rawError(
                 __('Your session has expired. Please log in again.')
@@ -226,8 +224,6 @@ class AuthenticationCookie extends AuthenticationPlugin
      */
     public function readCredentials(): bool
     {
-        global $conn_error;
-
         // Initialization
         /**
          * @global $GLOBALS['pma_auth_server'] the user provided server to
@@ -248,7 +244,9 @@ class AuthenticationCookie extends AuthenticationPlugin
                 && ! empty($GLOBALS['cfg']['CaptchaLoginPublicKey'])
             ) {
                 if (empty($_POST[$GLOBALS['cfg']['CaptchaResponseParam']])) {
-                    $conn_error = __('Missing reCAPTCHA verification, maybe it has been blocked by adblock?');
+                    $GLOBALS['conn_error'] = __(
+                        'Missing reCAPTCHA verification, maybe it has been blocked by adblock?'
+                    );
 
                     return false;
                 }
@@ -283,9 +281,9 @@ class AuthenticationCookie extends AuthenticationPlugin
                     $codes = $resp->getErrorCodes();
 
                     if (in_array('invalid-json', $codes)) {
-                        $conn_error = __('Failed to connect to the reCAPTCHA service!');
+                        $GLOBALS['conn_error'] = __('Failed to connect to the reCAPTCHA service!');
                     } else {
-                        $conn_error = __('Entered captcha is wrong, try again!');
+                        $GLOBALS['conn_error'] = __('Entered captcha is wrong, try again!');
                     }
 
                     return false;
@@ -297,7 +295,7 @@ class AuthenticationCookie extends AuthenticationPlugin
 
             $password = $_POST['pma_password'] ?? '';
             if (strlen($password) >= 1000) {
-                $conn_error = __('Your password is too long. To prevent denial-of-service attacks, ' .
+                $GLOBALS['conn_error'] = __('Your password is too long. To prevent denial-of-service attacks, ' .
                     'phpMyAdmin restricts passwords to less than 1000 characters.');
 
                 return false;
@@ -316,7 +314,7 @@ class AuthenticationCookie extends AuthenticationPlugin
 
                     $match = preg_match($GLOBALS['cfg']['ArbitraryServerRegexp'], $tmp_host);
                     if (! $match) {
-                        $conn_error = __('You are not allowed to log in to this MySQL server!');
+                        $GLOBALS['conn_error'] = __('You are not allowed to log in to this MySQL server!');
 
                         return false;
                     }
@@ -423,8 +421,6 @@ class AuthenticationCookie extends AuthenticationPlugin
      */
     public function storeCredentials(): bool
     {
-        global $cfg;
-
         if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($GLOBALS['pma_auth_server'])) {
             /* Allow to specify 'host port' */
             $parts = explode(' ', $GLOBALS['pma_auth_server']);
@@ -436,10 +432,10 @@ class AuthenticationCookie extends AuthenticationPlugin
                 $tmp_port = '';
             }
 
-            if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) {
-                $cfg['Server']['host'] = $tmp_host;
+            if ($GLOBALS['cfg']['Server']['host'] != $GLOBALS['pma_auth_server']) {
+                $GLOBALS['cfg']['Server']['host'] = $tmp_host;
                 if (! empty($tmp_port)) {
-                    $cfg['Server']['port'] = $tmp_port;
+                    $GLOBALS['cfg']['Server']['port'] = $tmp_port;
                 }
             }
 
@@ -569,14 +565,12 @@ class AuthenticationCookie extends AuthenticationPlugin
      */
     public function showFailure($failure): void
     {
-        global $conn_error;
-
         parent::showFailure($failure);
 
         // Deletes password cookie and displays the login form
         $GLOBALS['config']->removeCookie('pmaAuth-' . $GLOBALS['server']);
 
-        $conn_error = $this->getErrorMessage($failure);
+        $GLOBALS['conn_error'] = $this->getErrorMessage($failure);
 
         $response = ResponseRenderer::getInstance();
 
@@ -661,23 +655,21 @@ class AuthenticationCookie extends AuthenticationPlugin
      */
     public function logOut(): void
     {
-        global $config;
-
         // -> delete password cookie(s)
         if ($GLOBALS['cfg']['LoginCookieDeleteAll']) {
             foreach (array_keys($GLOBALS['cfg']['Servers']) as $key) {
-                $config->removeCookie('pmaAuth-' . $key);
-                if (! $config->issetCookie('pmaAuth-' . $key)) {
+                $GLOBALS['config']->removeCookie('pmaAuth-' . $key);
+                if (! $GLOBALS['config']->issetCookie('pmaAuth-' . $key)) {
                     continue;
                 }
 
-                $config->removeCookie('pmaAuth-' . $key);
+                $GLOBALS['config']->removeCookie('pmaAuth-' . $key);
             }
         } else {
             $cookieName = 'pmaAuth-' . $GLOBALS['server'];
-            $config->removeCookie($cookieName);
-            if ($config->issetCookie($cookieName)) {
-                $config->removeCookie($cookieName);
+            $GLOBALS['config']->removeCookie($cookieName);
+            if ($GLOBALS['config']->issetCookie($cookieName)) {
+                $GLOBALS['config']->removeCookie($cookieName);
             }
         }
 
diff --git a/libraries/classes/Plugins/Auth/AuthenticationHttp.php b/libraries/classes/Plugins/Auth/AuthenticationHttp.php
index 4ed280fb3e..5bc0df2efa 100644
--- a/libraries/classes/Plugins/Auth/AuthenticationHttp.php
+++ b/libraries/classes/Plugins/Auth/AuthenticationHttp.php
@@ -196,10 +196,8 @@ class AuthenticationHttp extends AuthenticationPlugin
      */
     public function showFailure($failure): void
     {
-        global $dbi;
-
         parent::showFailure($failure);
-        $error = $dbi->getError();
+        $error = $GLOBALS['dbi']->getError();
         if ($error && $GLOBALS['errno'] != 1045) {
             Core::fatalError($error);
         } else {
diff --git a/libraries/classes/Plugins/AuthenticationPlugin.php b/libraries/classes/Plugins/AuthenticationPlugin.php
index 3d5c26e19d..0f683f80bd 100644
--- a/libraries/classes/Plugins/AuthenticationPlugin.php
+++ b/libraries/classes/Plugins/AuthenticationPlugin.php
@@ -77,12 +77,10 @@ abstract class AuthenticationPlugin
      */
     public function storeCredentials(): bool
     {
-        global $cfg;
-
         $this->setSessionAccessTime();
 
-        $cfg['Server']['user'] = $this->user;
-        $cfg['Server']['password'] = $this->password;
+        $GLOBALS['cfg']['Server']['user'] = $this->user;
+        $GLOBALS['cfg']['Server']['password'] = $this->password;
 
         return true;
     }
@@ -109,8 +107,6 @@ abstract class AuthenticationPlugin
      */
     public function logOut(): void
     {
-        global $config;
-
         /* Obtain redirect URL (before doing logout) */
         if (! empty($GLOBALS['cfg']['Server']['LogoutURL'])) {
             $redirect_url = $GLOBALS['cfg']['Server']['LogoutURL'];
@@ -128,7 +124,7 @@ abstract class AuthenticationPlugin
         $server = 0;
         if ($GLOBALS['cfg']['LoginCookieDeleteAll'] === false && $GLOBALS['cfg']['Server']['auth_type'] === 'cookie') {
             foreach (array_keys($GLOBALS['cfg']['Servers']) as $key) {
-                if (! $config->issetCookie('pmaAuth-' . $key)) {
+                if (! $GLOBALS['config']->issetCookie('pmaAuth-' . $key)) {
                     continue;
                 }
 
@@ -173,8 +169,6 @@ abstract class AuthenticationPlugin
      */
     public function getErrorMessage($failure)
     {
-        global $dbi;
-
         if ($failure === 'empty-denied') {
             return __('Login without a password is forbidden by configuration (see AllowNoPassword)');
         }
@@ -191,7 +185,7 @@ abstract class AuthenticationPlugin
             );
         }
 
-        $dbi_error = $dbi->getError();
+        $dbi_error = $GLOBALS['dbi']->getError();
         if (! empty($dbi_error)) {
             return htmlspecialchars($dbi_error);
         }
@@ -268,13 +262,11 @@ abstract class AuthenticationPlugin
      */
     public function checkRules(): void
     {
-        global $cfg;
-
         // Check IP-based Allow/Deny rules as soon as possible to reject the
         // user based on mod_access in Apache
-        if (isset($cfg['Server']['AllowDeny']['order'])) {
+        if (isset($GLOBALS['cfg']['Server']['AllowDeny']['order'])) {
             $allowDeny_forbidden = false; // default
-            if ($cfg['Server']['AllowDeny']['order'] === 'allow,deny') {
+            if ($GLOBALS['cfg']['Server']['AllowDeny']['order'] === 'allow,deny') {
                 $allowDeny_forbidden = true;
                 if ($this->ipAllowDeny->allow()) {
                     $allowDeny_forbidden = false;
@@ -283,7 +275,7 @@ abstract class AuthenticationPlugin
                 if ($this->ipAllowDeny->deny()) {
                     $allowDeny_forbidden = true;
                 }
-            } elseif ($cfg['Server']['AllowDeny']['order'] === 'deny,allow') {
+            } elseif ($GLOBALS['cfg']['Server']['AllowDeny']['order'] === 'deny,allow') {
                 if ($this->ipAllowDeny->deny()) {
                     $allowDeny_forbidden = true;
                 }
@@ -291,7 +283,7 @@ abstract class AuthenticationPlugin
                 if ($this->ipAllowDeny->allow()) {
                     $allowDeny_forbidden = false;
                 }
-            } elseif ($cfg['Server']['AllowDeny']['order'] === 'explicit') {
+            } elseif ($GLOBALS['cfg']['Server']['AllowDeny']['order'] === 'explicit') {
                 if ($this->ipAllowDeny->allow() && ! $this->ipAllowDeny->deny()) {
                     $allowDeny_forbidden = false;
                 } else {
@@ -306,12 +298,12 @@ abstract class AuthenticationPlugin
         }
 
         // is root allowed?
-        if (! $cfg['Server']['AllowRoot'] && $cfg['Server']['user'] === 'root') {
+        if (! $GLOBALS['cfg']['Server']['AllowRoot'] && $GLOBALS['cfg']['Server']['user'] === 'root') {
             $this->showFailure('root-denied');
         }
 
         // is a login without password allowed?
-        if ($cfg['Server']['AllowNoPassword'] || $cfg['Server']['password'] !== '') {
+        if ($GLOBALS['cfg']['Server']['AllowNoPassword'] || $GLOBALS['cfg']['Server']['password'] !== '') {
             return;
         }
 
diff --git a/libraries/classes/Plugins/Export/ExportCodegen.php b/libraries/classes/Plugins/Export/ExportCodegen.php
index c4be71107d..d7fdc45ae2 100644
--- a/libraries/classes/Plugins/Export/ExportCodegen.php
+++ b/libraries/classes/Plugins/Export/ExportCodegen.php
@@ -206,13 +206,11 @@ class ExportCodegen extends ExportPlugin
      */
     private function handleNHibernateCSBody($db, $table, $crlf, array $aliases = [])
     {
-        global $dbi;
-
         $db_alias = $db;
         $table_alias = $table;
         $this->initAlias($aliases, $db_alias, $table_alias);
 
-        $result = $dbi->query(
+        $result = $GLOBALS['dbi']->query(
             sprintf(
                 'DESC %s.%s',
                 Util::backquote($db),
@@ -315,8 +313,6 @@ class ExportCodegen extends ExportPlugin
         $crlf,
         array $aliases = []
     ) {
-        global $dbi;
-
         $db_alias = $db;
         $table_alias = $table;
         $this->initAlias($aliases, $db_alias, $table_alias);
@@ -328,7 +324,7 @@ class ExportCodegen extends ExportPlugin
         $lines[] = '    ';
-        $result = $dbi->query(
+        $result = $GLOBALS['dbi']->query(
             sprintf(
                 'DESC %s.%s',
                 Util::backquote($db),
diff --git a/libraries/classes/Plugins/Export/ExportCsv.php b/libraries/classes/Plugins/Export/ExportCsv.php
index 19f4ad355b..07ffd62114 100644
--- a/libraries/classes/Plugins/Export/ExportCsv.php
+++ b/libraries/classes/Plugins/Export/ExportCsv.php
@@ -103,38 +103,37 @@ class ExportCsv extends ExportPlugin
      */
     public function exportHeader(): bool
     {
-        global $what, $csv_terminated, $csv_separator, $csv_enclosed, $csv_escaped;
         //Enable columns names by default for CSV
-        if ($what === 'csv') {
+        if ($GLOBALS['what'] === 'csv') {
             $GLOBALS['csv_columns'] = 'yes';
         }
 
         // Here we just prepare some values for export
-        if ($what === 'excel') {
-            $csv_terminated = "\015\012";
+        if ($GLOBALS['what'] === 'excel') {
+            $GLOBALS['csv_terminated'] = "\015\012";
             switch ($GLOBALS['excel_edition']) {
                 case 'win':
                     // as tested on Windows with Excel 2002 and Excel 2007
-                    $csv_separator = ';';
+                    $GLOBALS['csv_separator'] = ';';
                     break;
                 case 'mac_excel2003':
-                    $csv_separator = ';';
+                    $GLOBALS['csv_separator'] = ';';
                     break;
                 case 'mac_excel2008':
-                    $csv_separator = ',';
+                    $GLOBALS['csv_separator'] = ',';
                     break;
             }
 
-            $csv_enclosed = '"';
-            $csv_escaped = '"';
+            $GLOBALS['csv_enclosed'] = '"';
+            $GLOBALS['csv_escaped'] = '"';
             if (isset($GLOBALS['excel_columns'])) {
                 $GLOBALS['csv_columns'] = 'yes';
             }
         } else {
-            if (empty($csv_terminated) || mb_strtolower($csv_terminated) === 'auto') {
-                $csv_terminated = $GLOBALS['crlf'];
+            if (empty($GLOBALS['csv_terminated']) || mb_strtolower($GLOBALS['csv_terminated']) === 'auto') {
+                $GLOBALS['csv_terminated'] = $GLOBALS['crlf'];
             } else {
-                $csv_terminated = str_replace(
+                $GLOBALS['csv_terminated'] = str_replace(
                     [
                         '\\r',
                         '\\n',
@@ -145,11 +144,11 @@ class ExportCsv extends ExportPlugin
                         "\012",
                         "\011",
                     ],
-                    $csv_terminated
+                    $GLOBALS['csv_terminated']
                 );
             }
 
-            $csv_separator = str_replace('\\t', "\011", $csv_separator);
+            $GLOBALS['csv_separator'] = str_replace('\\t', "\011", $GLOBALS['csv_separator']);
         }
 
         return true;
@@ -214,14 +213,16 @@ class ExportCsv extends ExportPlugin
         $sqlQuery,
         array $aliases = []
     ): bool {
-        global $what, $csv_terminated, $csv_separator, $csv_enclosed, $csv_escaped, $dbi;
-
         $db_alias = $db;
         $table_alias = $table;
         $this->initAlias($aliases, $db_alias, $table_alias);
 
         // Gets the data from the database
-        $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
+        $result = $GLOBALS['dbi']->query(
+            $sqlQuery,
+            DatabaseInterface::CONNECT_USER,
+            DatabaseInterface::QUERY_UNBUFFERED
+        );
         $fields_cnt = $result->numFields();
 
         // If required, get fields name at the first line
@@ -232,19 +233,23 @@ class ExportCsv extends ExportPlugin
                     $col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
                 }
 
-                if ($csv_enclosed == '') {
+                if ($GLOBALS['csv_enclosed'] == '') {
                     $schema_insert .= $col_as;
                 } else {
-                    $schema_insert .= $csv_enclosed
-                        . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $col_as)
-                        . $csv_enclosed;
+                    $schema_insert .= $GLOBALS['csv_enclosed']
+                        . str_replace(
+                            $GLOBALS['csv_enclosed'],
+                            $GLOBALS['csv_escaped'] . $GLOBALS['csv_enclosed'],
+                            $col_as
+                        )
+                        . $GLOBALS['csv_enclosed'];
                 }
 
-                $schema_insert .= $csv_separator;
+                $schema_insert .= $GLOBALS['csv_separator'];
             }
 
             $schema_insert = trim(mb_substr($schema_insert, 0, -1));
-            if (! $this->export->outputHandler($schema_insert . $csv_terminated)) {
+            if (! $this->export->outputHandler($schema_insert . $GLOBALS['csv_terminated'])) {
                 return false;
             }
         }
@@ -254,15 +259,17 @@ class ExportCsv extends ExportPlugin
             $schema_insert = '';
             for ($j = 0; $j < $fields_cnt; $j++) {
                 if (! isset($row[$j])) {
-                    $schema_insert .= $GLOBALS[$what . '_null'];
+                    $schema_insert .= $GLOBALS[$GLOBALS['what'] . '_null'];
                 } elseif ($row[$j] == '0' || $row[$j] != '') {
                     // always enclose fields
-                    if ($what === 'excel') {
+                    if ($GLOBALS['what'] === 'excel') {
                         $row[$j] = preg_replace("/\015(\012)?/", "\012", $row[$j]);
                     }
 
                     // remove CRLF characters within field
-                    if (isset($GLOBALS[$what . '_removeCRLF']) && $GLOBALS[$what . '_removeCRLF']) {
+                    if (
+                        isset($GLOBALS[$GLOBALS['what'] . '_removeCRLF']) && $GLOBALS[$GLOBALS['what'] . '_removeCRLF']
+                    ) {
                         $row[$j] = str_replace(
                             [
                                 "\r",
@@ -273,27 +280,31 @@ class ExportCsv extends ExportPlugin
                         );
                     }
 
-                    if ($csv_enclosed == '') {
+                    if ($GLOBALS['csv_enclosed'] == '') {
                         $schema_insert .= $row[$j];
                     } else {
                         // also double the escape string if found in the data
-                        if ($csv_escaped != $csv_enclosed) {
-                            $schema_insert .= $csv_enclosed
+                        if ($GLOBALS['csv_escaped'] != $GLOBALS['csv_enclosed']) {
+                            $schema_insert .= $GLOBALS['csv_enclosed']
                                 . str_replace(
-                                    $csv_enclosed,
-                                    $csv_escaped . $csv_enclosed,
+                                    $GLOBALS['csv_enclosed'],
+                                    $GLOBALS['csv_escaped'] . $GLOBALS['csv_enclosed'],
                                     str_replace(
-                                        $csv_escaped,
-                                        $csv_escaped . $csv_escaped,
+                                        $GLOBALS['csv_escaped'],
+                                        $GLOBALS['csv_escaped'] . $GLOBALS['csv_escaped'],
                                         $row[$j]
                                     )
                                 )
-                                . $csv_enclosed;
+                                . $GLOBALS['csv_enclosed'];
                         } else {
                             // avoid a problem when escape string equals enclose
-                            $schema_insert .= $csv_enclosed
-                                . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j])
-                                . $csv_enclosed;
+                            $schema_insert .= $GLOBALS['csv_enclosed']
+                                . str_replace(
+                                    $GLOBALS['csv_enclosed'],
+                                    $GLOBALS['csv_escaped'] . $GLOBALS['csv_enclosed'],
+                                    $row[$j]
+                                )
+                                . $GLOBALS['csv_enclosed'];
                         }
                     }
                 } else {
@@ -304,10 +315,10 @@ class ExportCsv extends ExportPlugin
                     continue;
                 }
 
-                $schema_insert .= $csv_separator;
+                $schema_insert .= $GLOBALS['csv_separator'];
             }
 
-            if (! $this->export->outputHandler($schema_insert . $csv_terminated)) {
+            if (! $this->export->outputHandler($schema_insert . $GLOBALS['csv_terminated'])) {
                 return false;
             }
         }
diff --git a/libraries/classes/Plugins/Export/ExportHtmlword.php b/libraries/classes/Plugins/Export/ExportHtmlword.php
index 1320ffa1cf..f5373a41a9 100644
--- a/libraries/classes/Plugins/Export/ExportHtmlword.php
+++ b/libraries/classes/Plugins/Export/ExportHtmlword.php
@@ -98,8 +98,6 @@ class ExportHtmlword extends ExportPlugin
      */
     public function exportHeader(): bool
     {
-        global $charset;
-
         return $this->export->outputHandler(
             '
             
                 
+            . ($GLOBALS['charset'] ?? 'utf-8') . '" />
             
             '
         );
@@ -181,8 +179,6 @@ class ExportHtmlword extends ExportPlugin
         $sqlQuery,
         array $aliases = []
     ): bool {
-        global $what, $dbi;
-
         $db_alias = $db;
         $table_alias = $table;
         $this->initAlias($aliases, $db_alias, $table_alias);
@@ -202,7 +198,11 @@ class ExportHtmlword extends ExportPlugin
         }
 
         // Gets the data from the database
-        $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
+        $result = $GLOBALS['dbi']->query(
+            $sqlQuery,
+            DatabaseInterface::CONNECT_USER,
+            DatabaseInterface::QUERY_UNBUFFERED
+        );
         $fields_cnt = $result->numFields();
 
         // If required, get fields name at the first line
@@ -229,7 +229,7 @@ class ExportHtmlword extends ExportPlugin
             $schema_insert = '';
             for ($j = 0; $j < $fields_cnt; $j++) {
                 if (! isset($row[$j])) {
-                    $value = $GLOBALS[$what . '_null'];
+                    $value = $GLOBALS[$GLOBALS['what'] . '_null'];
                 } elseif ($row[$j] == '0' || $row[$j] != '') {
                     $value = $row[$j];
                 } else {
@@ -262,8 +262,6 @@ class ExportHtmlword extends ExportPlugin
      */
     public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
     {
-        global $dbi;
-
         $schema_insert = ''
             . ''
             . '';
 
-        $columns = $dbi->getColumns($db, $table);
+        $columns = $GLOBALS['dbi']->getColumns($db, $table);
         /**
          * Get the unique keys in the table
          */
         $unique_keys = [];
-        $keys = $dbi->getTableIndexes($db, $table);
+        $keys = $GLOBALS['dbi']->getTableIndexes($db, $table);
         foreach ($keys as $key) {
             if ($key['Non_unique'] != 0) {
                 continue;
@@ -464,8 +460,6 @@ class ExportHtmlword extends ExportPlugin
      */
     protected function getTriggers($db, $table)
     {
-        global $dbi;
-
         $dump = '
'; $dump .= ''; $dump .= ''; @@ -474,7 +468,7 @@ class ExportHtmlword extends ExportPlugin $dump .= ''; $dump .= ''; - $triggers = $dbi->getTriggers($db, $table); + $triggers = $GLOBALS['dbi']->getTriggers($db, $table); foreach ($triggers as $trigger) { $dump .= ''; @@ -532,8 +526,6 @@ class ExportHtmlword extends ExportPlugin $dates = false, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -550,7 +542,7 @@ class ExportHtmlword extends ExportPlugin break; case 'triggers': $dump = ''; - $triggers = $dbi->getTriggers($db, $table); + $triggers = $GLOBALS['dbi']->getTriggers($db, $table); if ($triggers) { $dump .= '

' . __('Triggers') . ' ' . htmlspecialchars($table_alias) diff --git a/libraries/classes/Plugins/Export/ExportJson.php b/libraries/classes/Plugins/Export/ExportJson.php index 0c179e8abe..ee7f60c0bb 100644 --- a/libraries/classes/Plugins/Export/ExportJson.php +++ b/libraries/classes/Plugins/Export/ExportJson.php @@ -107,8 +107,6 @@ class ExportJson extends ExportPlugin */ public function exportHeader(): bool { - global $crlf; - $data = $this->encode([ 'type' => 'header', 'version' => Version::VERSION, @@ -118,7 +116,7 @@ class ExportJson extends ExportPlugin return false; } - return $this->export->outputHandler('[' . $crlf . $data . ',' . $crlf); + return $this->export->outputHandler('[' . $GLOBALS['crlf'] . $data . ',' . $GLOBALS['crlf']); } /** @@ -126,9 +124,7 @@ class ExportJson extends ExportPlugin */ public function exportFooter(): bool { - global $crlf; - - return $this->export->outputHandler(']' . $crlf); + return $this->export->outputHandler(']' . $GLOBALS['crlf']); } /** @@ -139,8 +135,6 @@ class ExportJson extends ExportPlugin */ public function exportDBHeader($db, $dbAlias = ''): bool { - global $crlf; - if (empty($dbAlias)) { $dbAlias = $db; } @@ -150,7 +144,7 @@ class ExportJson extends ExportPlugin return false; } - return $this->export->outputHandler($data . ',' . $crlf); + return $this->export->outputHandler($data . ',' . $GLOBALS['crlf']); } /** @@ -193,8 +187,6 @@ class ExportJson extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -217,7 +209,7 @@ class ExportJson extends ExportPlugin return false; } - return $this->doExportForQuery($dbi, $sqlQuery, $buffer, $crlf, $aliases, $db, $table); + return $this->doExportForQuery($GLOBALS['dbi'], $sqlQuery, $buffer, $crlf, $aliases, $db, $table); } /** @@ -325,8 +317,6 @@ class ExportJson extends ExportPlugin */ public function exportRawQuery(string $errorUrl, string $sqlQuery, string $crlf): bool { - global $dbi; - $buffer = $this->encode([ 'type' => 'raw', 'data' => '@@DATA@@', @@ -335,6 +325,6 @@ class ExportJson extends ExportPlugin return false; } - return $this->doExportForQuery($dbi, $sqlQuery, $buffer, $crlf, null, null, null); + return $this->doExportForQuery($GLOBALS['dbi'], $sqlQuery, $buffer, $crlf, null, null, null); } } diff --git a/libraries/classes/Plugins/Export/ExportLatex.php b/libraries/classes/Plugins/Export/ExportLatex.php index 906ecd0276..471bf237f6 100644 --- a/libraries/classes/Plugins/Export/ExportLatex.php +++ b/libraries/classes/Plugins/Export/ExportLatex.php @@ -53,9 +53,8 @@ class ExportLatex extends ExportPlugin protected function setProperties(): ExportPluginProperties { - global $plugin_param; $hide_structure = false; - if ($plugin_param['export_type'] === 'table' && ! $plugin_param['single_table']) { + if ($GLOBALS['plugin_param']['export_type'] === 'table' && ! $GLOBALS['plugin_param']['single_table']) { $hide_structure = true; } @@ -200,22 +199,20 @@ class ExportLatex extends ExportPlugin */ public function exportHeader(): bool { - global $crlf, $cfg, $dbi; - - $head = '% phpMyAdmin LaTeX Dump' . $crlf - . '% version ' . Version::VERSION . $crlf - . '% https://www.phpmyadmin.net/' . $crlf - . '%' . $crlf - . '% ' . __('Host:') . ' ' . $cfg['Server']['host']; - if (! empty($cfg['Server']['port'])) { - $head .= ':' . $cfg['Server']['port']; + $head = '% phpMyAdmin LaTeX Dump' . $GLOBALS['crlf'] + . '% version ' . Version::VERSION . $GLOBALS['crlf'] + . '% https://www.phpmyadmin.net/' . $GLOBALS['crlf'] + . '%' . $GLOBALS['crlf'] + . '% ' . __('Host:') . ' ' . $GLOBALS['cfg']['Server']['host']; + if (! empty($GLOBALS['cfg']['Server']['port'])) { + $head .= ':' . $GLOBALS['cfg']['Server']['port']; } - $head .= $crlf + $head .= $GLOBALS['crlf'] . '% ' . __('Generation Time:') . ' ' - . Util::localisedDate() . $crlf - . '% ' . __('Server version:') . ' ' . $dbi->getVersionString() . $crlf - . '% ' . __('PHP Version:') . ' ' . PHP_VERSION . $crlf; + . Util::localisedDate() . $GLOBALS['crlf'] + . '% ' . __('Server version:') . ' ' . $GLOBALS['dbi']->getVersionString() . $GLOBALS['crlf'] + . '% ' . __('PHP Version:') . ' ' . PHP_VERSION . $GLOBALS['crlf']; return $this->export->outputHandler($head); } @@ -240,10 +237,9 @@ class ExportLatex extends ExportPlugin $dbAlias = $db; } - global $crlf; - $head = '% ' . $crlf - . '% ' . __('Database:') . ' \'' . $dbAlias . '\'' . $crlf - . '% ' . $crlf; + $head = '% ' . $GLOBALS['crlf'] + . '% ' . __('Database:') . ' \'' . $dbAlias . '\'' . $GLOBALS['crlf'] + . '% ' . $GLOBALS['crlf']; return $this->export->outputHandler($head); } @@ -288,13 +284,15 @@ class ExportLatex extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); - $result = $dbi->tryQuery($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->tryQuery( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $columns_cnt = $result->numFields(); $columns = []; @@ -467,8 +465,6 @@ class ExportLatex extends ExportPlugin $dates = false, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -484,7 +480,7 @@ class ExportLatex extends ExportPlugin * Get the unique keys in the table */ $unique_keys = []; - $keys = $dbi->getTableIndexes($db, $table); + $keys = $GLOBALS['dbi']->getTableIndexes($db, $table); foreach ($keys as $key) { if ($key['Non_unique'] != 0) { continue; @@ -496,7 +492,7 @@ class ExportLatex extends ExportPlugin /** * Gets fields properties */ - $dbi->selectDb($db); + $GLOBALS['dbi']->selectDb($db); // Check if we can use Relations [$res_rel, $have_rel] = $this->relation->getRelationsAndStatus( @@ -598,7 +594,7 @@ class ExportLatex extends ExportPlugin return false; } - $fields = $dbi->getColumns($db, $table); + $fields = $GLOBALS['dbi']->getColumns($db, $table); foreach ($fields as $row) { $extracted_columnspec = Util::extractColumnSpec($row['Type']); $type = $extracted_columnspec['print_type']; diff --git a/libraries/classes/Plugins/Export/ExportMediawiki.php b/libraries/classes/Plugins/Export/ExportMediawiki.php index 17c88b8e7d..f11681ccc9 100644 --- a/libraries/classes/Plugins/Export/ExportMediawiki.php +++ b/libraries/classes/Plugins/Export/ExportMediawiki.php @@ -176,8 +176,6 @@ class ExportMediawiki extends ExportPlugin $dates = false, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -185,7 +183,7 @@ class ExportMediawiki extends ExportPlugin $output = ''; switch ($exportMode) { case 'create_table': - $columns = $dbi->getColumns($db, $table); + $columns = $GLOBALS['dbi']->getColumns($db, $table); $columns = array_values($columns); $row_cnt = count($columns); @@ -269,8 +267,6 @@ class ExportMediawiki extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -296,7 +292,7 @@ class ExportMediawiki extends ExportPlugin // Add the table headers if (isset($GLOBALS['mediawiki_headers'])) { // Get column names - $column_names = $dbi->getColumnNames($db, $table); + $column_names = $GLOBALS['dbi']->getColumnNames($db, $table); // Add column names as table headers if ($column_names !== []) { @@ -315,7 +311,11 @@ class ExportMediawiki extends ExportPlugin } // Get the table data from the database - $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->query( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $fields_cnt = $result->numFields(); while ($row = $result->fetchRow()) { diff --git a/libraries/classes/Plugins/Export/ExportOds.php b/libraries/classes/Plugins/Export/ExportOds.php index 0a3b273c82..ebe6388131 100644 --- a/libraries/classes/Plugins/Export/ExportOds.php +++ b/libraries/classes/Plugins/Export/ExportOds.php @@ -200,21 +200,23 @@ class ExportOds extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $what, $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); // Gets the data from the database - $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->query( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $fields_cnt = $result->numFields(); /** @var FieldMetadata[] $fieldsMeta */ - $fieldsMeta = $dbi->getFieldsMeta($result); + $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result); $GLOBALS['ods_buffer'] .= ''; // If required, get fields name at the first line - if (isset($GLOBALS[$what . '_columns'])) { + if (isset($GLOBALS[$GLOBALS['what'] . '_columns'])) { $GLOBALS['ods_buffer'] .= ''; foreach ($fieldsMeta as $field) { $col_as = $field->name; @@ -244,7 +246,7 @@ class ExportOds extends ExportPlugin if (! isset($row[$j])) { $GLOBALS['ods_buffer'] .= '' . '' - . htmlspecialchars($GLOBALS[$what . '_null']) + . htmlspecialchars($GLOBALS[$GLOBALS['what'] . '_null']) . '' . ''; } elseif ($fieldsMeta[$j]->isBinary && $fieldsMeta[$j]->isBlob) { diff --git a/libraries/classes/Plugins/Export/ExportOdt.php b/libraries/classes/Plugins/Export/ExportOdt.php index e6d039e3bc..59c883ef5e 100644 --- a/libraries/classes/Plugins/Export/ExportOdt.php +++ b/libraries/classes/Plugins/Export/ExportOdt.php @@ -44,9 +44,8 @@ class ExportOdt extends ExportPlugin protected function setProperties(): ExportPluginProperties { - global $plugin_param; $hide_structure = false; - if ($plugin_param['export_type'] === 'table' && ! $plugin_param['single_table']) { + if ($GLOBALS['plugin_param']['export_type'] === 'table' && ! $GLOBALS['plugin_param']['single_table']) { $hide_structure = true; } @@ -227,16 +226,18 @@ class ExportOdt extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $what, $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); // Gets the data from the database - $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->query( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $fields_cnt = $result->numFields(); /** @var FieldMetadata[] $fieldsMeta */ - $fieldsMeta = $dbi->getFieldsMeta($result); + $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result); $GLOBALS['odt_buffer'] .= ''; @@ -250,7 +251,7 @@ class ExportOdt extends ExportPlugin . ' table:number-columns-repeated="' . $fields_cnt . '"/>'; // If required, get fields name at the first line - if (isset($GLOBALS[$what . '_columns'])) { + if (isset($GLOBALS[$GLOBALS['what'] . '_columns'])) { $GLOBALS['odt_buffer'] .= ''; foreach ($fieldsMeta as $field) { $col_as = $field->name; @@ -280,7 +281,7 @@ class ExportOdt extends ExportPlugin if (! isset($row[$j])) { $GLOBALS['odt_buffer'] .= '' . '' - . htmlspecialchars($GLOBALS[$what . '_null']) + . htmlspecialchars($GLOBALS[$GLOBALS['what'] . '_null']) . '' . ''; } elseif ($fieldsMeta[$j]->isBinary && $fieldsMeta[$j]->isBlob) { @@ -340,15 +341,13 @@ class ExportOdt extends ExportPlugin */ public function getTableDefStandIn($db, $view, $crlf, $aliases = []) { - global $dbi; - $db_alias = $db; $view_alias = $view; $this->initAlias($aliases, $db_alias, $view_alias); /** * Gets fields properties */ - $dbi->selectDb($db); + $GLOBALS['dbi']->selectDb($db); /** * Displays the table structure @@ -374,7 +373,7 @@ class ExportOdt extends ExportPlugin . '' . ''; - $columns = $dbi->getColumns($db, $view); + $columns = $GLOBALS['dbi']->getColumns($db, $view); foreach ($columns as $column) { $col_as = $column['Field'] ?? null; if (! empty($aliases[$db]['tables'][$view]['columns'][$col_as])) { @@ -423,8 +422,6 @@ class ExportOdt extends ExportPlugin $view = false, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -434,7 +431,7 @@ class ExportOdt extends ExportPlugin /** * Gets fields properties */ - $dbi->selectDb($db); + $GLOBALS['dbi']->selectDb($db); // Check if we can use Relations [$res_rel, $have_rel] = $this->relation->getRelationsAndStatus( @@ -498,7 +495,7 @@ class ExportOdt extends ExportPlugin $GLOBALS['odt_buffer'] .= ''; - $columns = $dbi->getColumns($db, $table); + $columns = $GLOBALS['dbi']->getColumns($db, $table); foreach ($columns as $column) { $col_as = $field_name = $column['Field']; if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) { @@ -577,8 +574,6 @@ class ExportOdt extends ExportPlugin */ protected function getTriggers($db, $table, array $aliases = []) { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -601,7 +596,7 @@ class ExportOdt extends ExportPlugin . '' . ''; - $triggers = $dbi->getTriggers($db, $table); + $triggers = $GLOBALS['dbi']->getTriggers($db, $table); foreach ($triggers as $trigger) { $GLOBALS['odt_buffer'] .= ''; @@ -666,8 +661,6 @@ class ExportOdt extends ExportPlugin $dates = false, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -693,7 +686,7 @@ class ExportOdt extends ExportPlugin ); break; case 'triggers': - $triggers = $dbi->getTriggers($db, $table); + $triggers = $GLOBALS['dbi']->getTriggers($db, $table); if ($triggers) { $GLOBALS['odt_buffer'] .= '' diff --git a/libraries/classes/Plugins/Export/ExportPhparray.php b/libraries/classes/Plugins/Export/ExportPhparray.php index 426a01597e..0ae8e66d1f 100644 --- a/libraries/classes/Plugins/Export/ExportPhparray.php +++ b/libraries/classes/Plugins/Export/ExportPhparray.php @@ -159,13 +159,15 @@ class ExportPhparray extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); - $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->query( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $columns_cnt = $result->numFields(); $columns = []; diff --git a/libraries/classes/Plugins/Export/ExportSql.php b/libraries/classes/Plugins/Export/ExportSql.php index 2b2fc73c5d..5b894efd91 100644 --- a/libraries/classes/Plugins/Export/ExportSql.php +++ b/libraries/classes/Plugins/Export/ExportSql.php @@ -87,11 +87,9 @@ class ExportSql extends ExportPlugin protected function setProperties(): ExportPluginProperties { - global $plugin_param, $dbi; - $hideSql = false; $hideStructure = false; - if ($plugin_param['export_type'] === 'table' && ! $plugin_param['single_table']) { + if ($GLOBALS['plugin_param']['export_type'] === 'table' && ! $GLOBALS['plugin_param']['single_table']) { $hideStructure = true; $hideSql = true; } @@ -206,7 +204,7 @@ class ExportSql extends ExportPlugin $generalOptions->addProperty($leaf); // compatibility maximization - $compats = $dbi->getCompatibilities(); + $compats = $GLOBALS['dbi']->getCompatibilities(); if (count($compats) > 0) { $values = []; foreach ($compats as $val) { @@ -267,7 +265,7 @@ class ExportSql extends ExportPlugin $subgroup->setSubgroupHeader($leaf); // server export options - if ($plugin_param['export_type'] === 'server') { + if ($GLOBALS['plugin_param']['export_type'] === 'server') { $leaf = new BoolPropertyItem( 'drop_database', sprintf(__('Add %s statement'), 'DROP DATABASE IF EXISTS') @@ -275,7 +273,7 @@ class ExportSql extends ExportPlugin $subgroup->addProperty($leaf); } - if ($plugin_param['export_type'] === 'database') { + if ($GLOBALS['plugin_param']['export_type'] === 'database') { $createClause = 'CREATE DATABASE / USE'; $leaf = new BoolPropertyItem( 'create_database', @@ -284,8 +282,8 @@ class ExportSql extends ExportPlugin $subgroup->addProperty($leaf); } - if ($plugin_param['export_type'] === 'table') { - $dropClause = $dbi->getTable($GLOBALS['db'], $GLOBALS['table'])->isView() + if ($GLOBALS['plugin_param']['export_type'] === 'table') { + $dropClause = $GLOBALS['dbi']->getTable($GLOBALS['db'], $GLOBALS['table'])->isView() ? 'DROP VIEW' : 'DROP TABLE'; } else { @@ -538,8 +536,6 @@ class ExportSql extends ExportPlugin array $routines, $delimiter ) { - global $crlf, $dbi; - $text = $this->exportComment() . $this->exportComment($name) . $this->exportComment(); @@ -551,11 +547,11 @@ class ExportSql extends ExportPlugin if (! empty($GLOBALS['sql_drop_table'])) { $procQuery .= 'DROP ' . $type . ' IF EXISTS ' . Util::backquote($routine) - . $delimiter . $crlf; + . $delimiter . $GLOBALS['crlf']; } $createQuery = $this->replaceWithAliases( - $dbi->getDefinition($db, $type, $routine), + $GLOBALS['dbi']->getDefinition($db, $type, $routine), $aliases, $db, '', @@ -566,7 +562,7 @@ class ExportSql extends ExportPlugin $usedAlias = true; } - $procQuery .= $createQuery . $delimiter . $crlf . $crlf; + $procQuery .= $createQuery . $delimiter . $GLOBALS['crlf'] . $GLOBALS['crlf']; } if ($usedAlias) { @@ -592,20 +588,18 @@ class ExportSql extends ExportPlugin */ public function exportRoutines($db, array $aliases = []): bool { - global $crlf, $dbi; - $dbAlias = $db; $this->initAlias($aliases, $dbAlias); $text = ''; $delimiter = '$$'; - $procedureNames = $dbi->getProceduresOrFunctions($db, 'PROCEDURE'); - $functionNames = $dbi->getProceduresOrFunctions($db, 'FUNCTION'); + $procedureNames = $GLOBALS['dbi']->getProceduresOrFunctions($db, 'PROCEDURE'); + $functionNames = $GLOBALS['dbi']->getProceduresOrFunctions($db, 'FUNCTION'); if ($procedureNames || $functionNames) { - $text .= $crlf - . 'DELIMITER ' . $delimiter . $crlf; + $text .= $GLOBALS['crlf'] + . 'DELIMITER ' . $delimiter . $GLOBALS['crlf']; if ($procedureNames) { $text .= $this->exportRoutineSQL( @@ -629,7 +623,7 @@ class ExportSql extends ExportPlugin ); } - $text .= 'DELIMITER ;' . $crlf; + $text .= 'DELIMITER ;' . $GLOBALS['crlf']; } if (! empty($text)) { @@ -689,33 +683,31 @@ class ExportSql extends ExportPlugin */ public function exportFooter(): bool { - global $crlf, $dbi; - $foot = ''; if (isset($GLOBALS['sql_disable_fk'])) { - $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf; + $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $GLOBALS['crlf']; } if (isset($GLOBALS['sql_use_transaction'])) { - $foot .= 'COMMIT;' . $crlf; + $foot .= 'COMMIT;' . $GLOBALS['crlf']; } // restore connection settings if ($this->sentCharset) { - $foot .= $crlf + $foot .= $GLOBALS['crlf'] . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;' - . $crlf + . $GLOBALS['crlf'] . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;' - . $crlf + . $GLOBALS['crlf'] . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' - . $crlf; + . $GLOBALS['crlf']; $this->sentCharset = false; } /* Restore timezone */ if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) { - $dbi->query('SET time_zone = "' . $GLOBALS['old_tz'] . '"'); + $GLOBALS['dbi']->query('SET time_zone = "' . $GLOBALS['old_tz'] . '"'); } return $this->export->outputHandler($foot); @@ -727,15 +719,13 @@ class ExportSql extends ExportPlugin */ public function exportHeader(): bool { - global $crlf, $cfg, $dbi; - if (isset($GLOBALS['sql_compatibility'])) { $tmpCompat = $GLOBALS['sql_compatibility']; if ($tmpCompat === 'NONE') { $tmpCompat = ''; } - $dbi->tryQuery('SET SQL_MODE="' . $tmpCompat . '"'); + $GLOBALS['dbi']->tryQuery('SET SQL_MODE="' . $tmpCompat . '"'); unset($tmpCompat); } @@ -743,9 +733,9 @@ class ExportSql extends ExportPlugin . $this->exportComment('version ' . Version::VERSION) . $this->exportComment('https://www.phpmyadmin.net/') . $this->exportComment(); - $hostString = __('Host:') . ' ' . $cfg['Server']['host']; - if (! empty($cfg['Server']['port'])) { - $hostString .= ':' . $cfg['Server']['port']; + $hostString = __('Host:') . ' ' . $GLOBALS['cfg']['Server']['host']; + if (! empty($GLOBALS['cfg']['Server']['port'])) { + $hostString .= ':' . $GLOBALS['cfg']['Server']['port']; } $head .= $this->exportComment($hostString); @@ -754,7 +744,7 @@ class ExportSql extends ExportPlugin . Util::localisedDate() ) . $this->exportComment( - __('Server version:') . ' ' . $dbi->getVersionString() + __('Server version:') . ' ' . $GLOBALS['dbi']->getVersionString() ) . $this->exportComment(__('PHP Version:') . ' ' . PHP_VERSION) . $this->possibleCRLF(); @@ -772,25 +762,25 @@ class ExportSql extends ExportPlugin } if (isset($GLOBALS['sql_disable_fk'])) { - $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf; + $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $GLOBALS['crlf']; } // We want exported AUTO_INCREMENT columns to have still same value, // do this only for recent MySQL exports if (! isset($GLOBALS['sql_compatibility']) || $GLOBALS['sql_compatibility'] === 'NONE') { - $head .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . $crlf; + $head .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . $GLOBALS['crlf']; } if (isset($GLOBALS['sql_use_transaction'])) { - $head .= 'START TRANSACTION;' . $crlf; + $head .= 'START TRANSACTION;' . $GLOBALS['crlf']; } /* Change timezone if we should export timestamps in UTC */ if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) { - $head .= 'SET time_zone = "+00:00";' . $crlf; - $GLOBALS['old_tz'] = $dbi + $head .= 'SET time_zone = "+00:00";' . $GLOBALS['crlf']; + $GLOBALS['old_tz'] = $GLOBALS['dbi'] ->fetchValue('SELECT @@session.time_zone'); - $dbi->query('SET time_zone = "+00:00"'); + $GLOBALS['dbi']->query('SET time_zone = "+00:00"'); } $head .= $this->possibleCRLF(); @@ -807,18 +797,18 @@ class ExportSql extends ExportPlugin $setNames = Charsets::$mysqlCharsetMap['utf-8']; } - if ($setNames === 'utf8' && $dbi->getVersion() > 50503) { + if ($setNames === 'utf8' && $GLOBALS['dbi']->getVersion() > 50503) { $setNames = 'utf8mb4'; } - $head .= $crlf + $head .= $GLOBALS['crlf'] . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=' - . '@@CHARACTER_SET_CLIENT */;' . $crlf + . '@@CHARACTER_SET_CLIENT */;' . $GLOBALS['crlf'] . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=' - . '@@CHARACTER_SET_RESULTS */;' . $crlf + . '@@CHARACTER_SET_RESULTS */;' . $GLOBALS['crlf'] . '/*!40101 SET @OLD_COLLATION_CONNECTION=' - . '@@COLLATION_CONNECTION */;' . $crlf - . '/*!40101 SET NAMES ' . $setNames . ' */;' . $crlf . $crlf; + . '@@COLLATION_CONNECTION */;' . $GLOBALS['crlf'] + . '/*!40101 SET NAMES ' . $setNames . ' */;' . $GLOBALS['crlf'] . $GLOBALS['crlf']; $this->sentCharset = true; } @@ -834,8 +824,6 @@ class ExportSql extends ExportPlugin */ public function exportDBCreate($db, $exportType, $dbAlias = ''): bool { - global $crlf, $dbi; - if (empty($dbAlias)) { $dbAlias = $db; } @@ -855,7 +843,7 @@ class ExportSql extends ExportPlugin $compat, isset($GLOBALS['sql_backquotes']) ) - . ';' . $crlf + . ';' . $GLOBALS['crlf'] ) ) { return false; @@ -868,7 +856,7 @@ class ExportSql extends ExportPlugin $createQuery = 'CREATE DATABASE IF NOT EXISTS ' . Util::backquoteCompat($dbAlias, $compat, isset($GLOBALS['sql_backquotes'])); - $collation = $dbi->getDbCollation($db); + $collation = $GLOBALS['dbi']->getDbCollation($db); if (mb_strpos($collation, '_')) { $createQuery .= ' DEFAULT CHARACTER SET ' . mb_substr( @@ -881,7 +869,7 @@ class ExportSql extends ExportPlugin $createQuery .= ' DEFAULT CHARACTER SET ' . $collation; } - $createQuery .= ';' . $crlf; + $createQuery .= ';' . $GLOBALS['crlf']; if (! $this->export->outputHandler($createQuery)) { return false; } @@ -897,8 +885,6 @@ class ExportSql extends ExportPlugin */ private function exportUseStatement($db, $compat): bool { - global $crlf; - if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] === 'NONE') { $result = $this->export->outputHandler( 'USE ' @@ -907,10 +893,10 @@ class ExportSql extends ExportPlugin $compat, isset($GLOBALS['sql_backquotes']) ) - . ';' . $crlf + . ';' . $GLOBALS['crlf'] ); } else { - $result = $this->export->outputHandler('USE ' . $db . ';' . $crlf); + $result = $this->export->outputHandler('USE ' . $db . ';' . $GLOBALS['crlf']); } return $result; @@ -955,8 +941,6 @@ class ExportSql extends ExportPlugin */ public function exportDBFooter($db): bool { - global $crlf; - $result = true; //add indexes to the sql dump file @@ -987,20 +971,18 @@ class ExportSql extends ExportPlugin */ public function exportEvents($db): bool { - global $crlf, $dbi; - $text = ''; $delimiter = '$$'; - $eventNames = $dbi->fetchResult( + $eventNames = $GLOBALS['dbi']->fetchResult( 'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE' - . " EVENT_SCHEMA= '" . $dbi->escapeString($db) + . " EVENT_SCHEMA= '" . $GLOBALS['dbi']->escapeString($db) . "';" ); if ($eventNames) { - $text .= $crlf - . 'DELIMITER ' . $delimiter . $crlf; + $text .= $GLOBALS['crlf'] + . 'DELIMITER ' . $delimiter . $GLOBALS['crlf']; $text .= $this->exportComment() . $this->exportComment(__('Events')) @@ -1010,14 +992,14 @@ class ExportSql extends ExportPlugin if (! empty($GLOBALS['sql_drop_table'])) { $text .= 'DROP EVENT IF EXISTS ' . Util::backquote($eventName) - . $delimiter . $crlf; + . $delimiter . $GLOBALS['crlf']; } - $text .= $dbi->getDefinition($db, 'EVENT', $eventName) - . $delimiter . $crlf . $crlf; + $text .= $GLOBALS['dbi']->getDefinition($db, 'EVENT', $eventName) + . $delimiter . $GLOBALS['crlf'] . $GLOBALS['crlf']; } - $text .= 'DELIMITER ;' . $crlf; + $text .= 'DELIMITER ;' . $GLOBALS['crlf']; } if (! empty($text)) { @@ -1086,8 +1068,6 @@ class ExportSql extends ExportPlugin $table, array $metadataTypes ): bool { - global $dbi; - $relationParameters = $this->relation->getRelationParameters(); $relationParams = $relationParameters->toArray(); @@ -1148,16 +1128,16 @@ class ExportSql extends ExportPlugin $sqlQuery = 'SELECT `page_nr`, `page_descr` FROM ' . Util::backquote($relationParameters->pdfFeature->database) . '.' . Util::backquote($relationParameters->pdfFeature->pdfPages) - . ' WHERE `db_name` = \'' . $dbi->escapeString($db) . "'"; + . ' WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db) . "'"; - $result = $dbi->fetchResult($sqlQuery, 'page_nr', 'page_descr'); + $result = $GLOBALS['dbi']->fetchResult($sqlQuery, 'page_nr', 'page_descr'); foreach (array_keys($result) as $page) { // insert row for pdf_page $sqlQueryRow = 'SELECT `db_name`, `page_descr` FROM ' . Util::backquote($relationParameters->pdfFeature->database) . '.' . Util::backquote($relationParameters->pdfFeature->pdfPages) - . ' WHERE `db_name` = \'' . $dbi->escapeString($db) . "'" + . ' WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db) . "'" . " AND `page_nr` = '" . intval($page) . "'"; if ( @@ -1225,10 +1205,10 @@ class ExportSql extends ExportPlugin $sqlQuery .= Util::backquote($relationParameters->db) . '.' . Util::backquote((string) $relationParams[$type]) . ' WHERE ' . Util::backquote($dbNameColumn) - . " = '" . $dbi->escapeString($db) . "'"; + . " = '" . $GLOBALS['dbi']->escapeString($db) . "'"; if (isset($table)) { $sqlQuery .= " AND `table_name` = '" - . $dbi->escapeString($table) . "'"; + . $GLOBALS['dbi']->escapeString($table) . "'"; } if ( @@ -1260,8 +1240,6 @@ class ExportSql extends ExportPlugin */ public function getTableDefStandIn($db, $view, $crlf, $aliases = []) { - global $dbi; - $dbAlias = $db; $viewAlias = $view; $this->initAlias($aliases, $dbAlias, $viewAlias); @@ -1280,7 +1258,7 @@ class ExportSql extends ExportPlugin $createQuery .= Util::backquote($viewAlias) . ' (' . $crlf; $tmp = []; - $columns = $dbi->getColumnsFull($db, $view); + $columns = $GLOBALS['dbi']->getColumnsFull($db, $view); foreach ($columns as $columnName => $definition) { $colAlias = $columnName; if (! empty($aliases[$db]['tables'][$view]['columns'][$colAlias])) { @@ -1313,8 +1291,6 @@ class ExportSql extends ExportPlugin $addSemicolon = true, array $aliases = [] ) { - global $dbi; - $dbAlias = $db; $viewAlias = $view; $this->initAlias($aliases, $dbAlias, $viewAlias); @@ -1325,7 +1301,7 @@ class ExportSql extends ExportPlugin $createQuery .= Util::backquote($viewAlias) . '(' . $crlf; - $columns = $dbi->getColumns($db, $view, true); + $columns = $GLOBALS['dbi']->getColumns($db, $view, true); $firstCol = true; foreach ($columns as $column) { @@ -1352,7 +1328,7 @@ class ExportSql extends ExportPlugin if (isset($column['Default'])) { $createQuery .= " DEFAULT '" - . $dbi->escapeString($column['Default']) . "'"; + . $GLOBALS['dbi']->escapeString($column['Default']) . "'"; } else { if ($column['Null'] === 'YES') { $createQuery .= ' DEFAULT NULL'; @@ -1361,7 +1337,7 @@ class ExportSql extends ExportPlugin if (! empty($column['Comment'])) { $createQuery .= " COMMENT '" - . $dbi->escapeString($column['Comment']) . "'"; + . $GLOBALS['dbi']->escapeString($column['Comment']) . "'"; } $firstCol = false; @@ -1412,10 +1388,6 @@ class ExportSql extends ExportPlugin $updateIndexesIncrements = true, array $aliases = [] ) { - global $sql_drop_table, $sql_backquotes, $sql_constraints, - $sql_constraints_query, $sql_indexes, $sql_indexes_query, - $sql_auto_increments, $sql_drop_foreign_keys, $dbi; - $dbAlias = $db; $tableAlias = $table; $this->initAlias($aliases, $dbAlias, $tableAlias); @@ -1429,9 +1401,9 @@ class ExportSql extends ExportPlugin $compat = 'NONE'; } - $result = $dbi->tryQuery( + $result = $GLOBALS['dbi']->tryQuery( 'SHOW TABLE STATUS FROM ' . Util::backquote($db) - . ' WHERE Name = \'' . $dbi->escapeString((string) $table) . '\'' + . ' WHERE Name = \'' . $GLOBALS['dbi']->escapeString((string) $table) . '\'' ); if ($result != false) { if ($result->numRows() > 0) { @@ -1471,25 +1443,25 @@ class ExportSql extends ExportPlugin $schemaCreate .= $newCrlf; - if (! empty($sql_drop_table) && $dbi->getTable($db, $table)->isView()) { + if (! empty($GLOBALS['sql_drop_table']) && $GLOBALS['dbi']->getTable($db, $table)->isView()) { $schemaCreate .= 'DROP VIEW IF EXISTS ' - . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) . ';' + . Util::backquoteCompat($tableAlias, 'NONE', $GLOBALS['sql_backquotes']) . ';' . $crlf; } // no need to generate a DROP VIEW here, it was done earlier - if (! empty($sql_drop_table) && ! $dbi->getTable($db, $table)->isView()) { + if (! empty($GLOBALS['sql_drop_table']) && ! $GLOBALS['dbi']->getTable($db, $table)->isView()) { $schemaCreate .= 'DROP TABLE IF EXISTS ' - . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) . ';' + . Util::backquoteCompat($tableAlias, 'NONE', $GLOBALS['sql_backquotes']) . ';' . $crlf; } // Complete table dump, // Whether to quote table and column names or not - if ($sql_backquotes) { - $dbi->query('SET SQL_QUOTE_SHOW_CREATE = 1'); + if ($GLOBALS['sql_backquotes']) { + $GLOBALS['dbi']->query('SET SQL_QUOTE_SHOW_CREATE = 1'); } else { - $dbi->query('SET SQL_QUOTE_SHOW_CREATE = 0'); + $GLOBALS['dbi']->query('SET SQL_QUOTE_SHOW_CREATE = 0'); } // I don't see the reason why this unbuffered query could cause problems, @@ -1502,13 +1474,13 @@ class ExportSql extends ExportPlugin // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not // produce a displayable result for the default value of a BIT // column, nor does the mysqldump command. See MySQL bug 35796 - $dbi->tryQuery('USE ' . Util::backquote($db)); - $result = $dbi->tryQuery( + $GLOBALS['dbi']->tryQuery('USE ' . Util::backquote($db)); + $result = $GLOBALS['dbi']->tryQuery( 'SHOW CREATE TABLE ' . Util::backquote($db) . '.' . Util::backquote($table) ); // an error can happen, for example the table is crashed - $tmpError = $dbi->getError(); + $tmpError = $GLOBALS['dbi']->getError(); if ($tmpError) { $message = sprintf(__('Error reading structure for table %s:'), $db . '.' . $table); $message .= ' ' . $tmpError; @@ -1613,14 +1585,14 @@ class ExportSql extends ExportPlugin // Views have no constraints, indexes, etc. They do not require any // analysis. if (! $view) { - if (empty($sql_backquotes)) { + if (empty($GLOBALS['sql_backquotes'])) { // Option "Enclose table and column names with backquotes" // was checked. Context::$MODE |= Context::SQL_MODE_NO_ENCLOSING_QUOTES; } // Using appropriate quotes. - if (($compat === 'MSSQL') || ($sql_backquotes === '"')) { + if (($compat === 'MSSQL') || ($GLOBALS['sql_backquotes'] === '"')) { Context::$MODE |= Context::SQL_MODE_ANSI_QUOTES; } } @@ -1741,7 +1713,7 @@ class ExportSql extends ExportPlugin * @var string */ $alterHeader = 'ALTER TABLE ' . - Util::backquoteCompat($tableAlias, $compat, $sql_backquotes); + Util::backquoteCompat($tableAlias, $compat, $GLOBALS['sql_backquotes']); /** * The footer of the `ALTER` statement (usually ';') @@ -1752,25 +1724,25 @@ class ExportSql extends ExportPlugin // Generating constraints-related query. if (! empty($constraints)) { - $sql_constraints_query = $alterHeader . $crlf . ' ADD ' + $GLOBALS['sql_constraints_query'] = $alterHeader . $crlf . ' ADD ' . implode(',' . $crlf . ' ADD ', $constraints) . $alterFooter; - $sql_constraints = $this->generateComment( + $GLOBALS['sql_constraints'] = $this->generateComment( $crlf, - $sql_constraints, + $GLOBALS['sql_constraints'], __('Constraints for dumped tables'), __('Constraints for table'), $tableAlias, $compat - ) . $sql_constraints_query; + ) . $GLOBALS['sql_constraints_query']; } // Generating indexes-related query. - $sql_indexes_query = ''; + $GLOBALS['sql_indexes_query'] = ''; if (! empty($indexes)) { - $sql_indexes_query .= $alterHeader . $crlf . ' ADD ' + $GLOBALS['sql_indexes_query'] .= $alterHeader . $crlf . ' ADD ' . implode(',' . $crlf . ' ADD ', $indexes) . $alterFooter; } @@ -1779,24 +1751,24 @@ class ExportSql extends ExportPlugin // InnoDB supports one FULLTEXT index creation at a time. // So FULLTEXT indexes are created one-by-one after other // indexes where created. - $sql_indexes_query .= $alterHeader . + $GLOBALS['sql_indexes_query'] .= $alterHeader . ' ADD ' . implode($alterFooter . $alterHeader . ' ADD ', $indexesFulltext) . $alterFooter; } if (! empty($indexes) || ! empty($indexesFulltext)) { - $sql_indexes = $this->generateComment( + $GLOBALS['sql_indexes'] = $this->generateComment( $crlf, - $sql_indexes, + $GLOBALS['sql_indexes'], __('Indexes for dumped tables'), __('Indexes for table'), $tableAlias, $compat - ) . $sql_indexes_query; + ) . $GLOBALS['sql_indexes_query']; } // Generating drop foreign keys-related query. if (! empty($dropped)) { - $sql_drop_foreign_keys = $alterHeader . $crlf . ' DROP ' + $GLOBALS['sql_drop_foreign_keys'] = $alterHeader . $crlf . ' DROP ' . implode(',' . $crlf . ' DROP ', $dropped) . $alterFooter; } @@ -1821,9 +1793,9 @@ class ExportSql extends ExportPlugin $sqlAutoIncrementsQuery .= ';' . $crlf; - $sql_auto_increments = $this->generateComment( + $GLOBALS['sql_auto_increments'] = $this->generateComment( $crlf, - $sql_auto_increments, + $GLOBALS['sql_auto_increments'], __('AUTO_INCREMENT for dumped tables'), __('AUTO_INCREMENT for table'), $tableAlias, @@ -1872,8 +1844,6 @@ class ExportSql extends ExportPlugin $doMime = false, array $aliases = [] ) { - global $sql_backquotes; - $dbAlias = $db; $tableAlias = $table; $this->initAlias($aliases, $dbAlias, $tableAlias); @@ -1901,19 +1871,19 @@ class ExportSql extends ExportPlugin . $this->exportComment() . $this->exportComment( __('MEDIA TYPES FOR TABLE') . ' ' - . Util::backquoteCompat($table, 'NONE', $sql_backquotes) . ':' + . Util::backquoteCompat($table, 'NONE', $GLOBALS['sql_backquotes']) . ':' ); foreach ($mimeMap as $mimeField => $mime) { $schemaCreate .= $this->exportComment( ' ' - . Util::backquoteCompat($mimeField, 'NONE', $sql_backquotes) + . Util::backquoteCompat($mimeField, 'NONE', $GLOBALS['sql_backquotes']) ) . $this->exportComment( ' ' . Util::backquoteCompat( $mime['mimetype'], 'NONE', - $sql_backquotes + $GLOBALS['sql_backquotes'] ) ); } @@ -1926,7 +1896,7 @@ class ExportSql extends ExportPlugin . $this->exportComment() . $this->exportComment( __('RELATIONSHIPS FOR TABLE') . ' ' - . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) + . Util::backquoteCompat($tableAlias, 'NONE', $GLOBALS['sql_backquotes']) . ':' ); @@ -1941,7 +1911,7 @@ class ExportSql extends ExportPlugin . Util::backquoteCompat( $relFieldAlias, 'NONE', - $sql_backquotes + $GLOBALS['sql_backquotes'] ) ) . $this->exportComment( @@ -1949,13 +1919,13 @@ class ExportSql extends ExportPlugin . Util::backquoteCompat( $rel['foreign_table'], 'NONE', - $sql_backquotes + $GLOBALS['sql_backquotes'] ) . ' -> ' . Util::backquoteCompat( $rel['foreign_field'], 'NONE', - $sql_backquotes + $GLOBALS['sql_backquotes'] ) ); } else { @@ -1970,7 +1940,7 @@ class ExportSql extends ExportPlugin . Util::backquoteCompat( $relFieldAlias, 'NONE', - $sql_backquotes + $GLOBALS['sql_backquotes'] ) ) . $this->exportComment( @@ -1978,13 +1948,13 @@ class ExportSql extends ExportPlugin . Util::backquoteCompat( $oneKey['ref_table_name'], 'NONE', - $sql_backquotes + $GLOBALS['sql_backquotes'] ) . ' -> ' . Util::backquoteCompat( $oneKey['ref_index_list'][$index], 'NONE', - $sql_backquotes + $GLOBALS['sql_backquotes'] ) ); } @@ -2044,8 +2014,6 @@ class ExportSql extends ExportPlugin $dates = false, array $aliases = [] ): bool { - global $dbi; - $dbAlias = $db; $tableAlias = $table; $this->initAlias($aliases, $dbAlias, $tableAlias); @@ -2073,7 +2041,7 @@ class ExportSql extends ExportPlugin case 'triggers': $dump = ''; $delimiter = '$$'; - $triggers = $dbi->getTriggers($db, $table, $delimiter); + $triggers = $GLOBALS['dbi']->getTriggers($db, $table, $delimiter); if ($triggers) { $dump .= $this->possibleCRLF() . $this->exportComment() @@ -2182,10 +2150,8 @@ class ExportSql extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $current_row, $sql_backquotes, $dbi; - // Do not export data for merge tables - if ($dbi->getTable($db, $table)->isMerge()) { + if ($GLOBALS['dbi']->getTable($db, $table)->isMerge()) { return true; } @@ -2199,11 +2165,11 @@ class ExportSql extends ExportPlugin $compat = 'NONE'; } - $formattedTableName = Util::backquoteCompat($tableAlias, $compat, $sql_backquotes); + $formattedTableName = Util::backquoteCompat($tableAlias, $compat, $GLOBALS['sql_backquotes']); // Do not export data for a VIEW, unless asked to export the view as a table // (For a VIEW, this is called only when exporting a single VIEW) - if ($dbi->getTable($db, $table)->isView() && empty($GLOBALS['sql_views_as_tables'])) { + if ($GLOBALS['dbi']->getTable($db, $table)->isView() && empty($GLOBALS['sql_views_as_tables'])) { $head = $this->possibleCRLF() . $this->exportComment() . $this->exportComment('VIEW ' . $formattedTableName) @@ -2214,9 +2180,13 @@ class ExportSql extends ExportPlugin return $this->export->outputHandler($head); } - $result = $dbi->tryQuery($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->tryQuery( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); // a possible error: the table has crashed - $tmpError = $dbi->getError(); + $tmpError = $GLOBALS['dbi']->getError(); if ($tmpError) { $message = sprintf(__('Error reading data for table %s:'), $db . '.' . $table); $message .= ' ' . $tmpError; @@ -2237,7 +2207,7 @@ class ExportSql extends ExportPlugin // Get field information /** @var FieldMetadata[] $fieldsMeta */ - $fieldsMeta = $dbi->getFieldsMeta($result); + $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result); $fieldSet = []; for ($j = 0; $j < $fieldsCnt; $j++) { @@ -2246,7 +2216,7 @@ class ExportSql extends ExportPlugin $colAs = $aliases[$db]['tables'][$table]['columns'][$colAs]; } - $fieldSet[$j] = Util::backquoteCompat($colAs, $compat, $sql_backquotes); + $fieldSet[$j] = Util::backquoteCompat($colAs, $compat, $GLOBALS['sql_backquotes']); } if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] === 'UPDATE') { @@ -2257,7 +2227,7 @@ class ExportSql extends ExportPlugin } // avoid EOL blank - $schemaInsert .= Util::backquoteCompat($tableAlias, $compat, $sql_backquotes) . ' SET'; + $schemaInsert .= Util::backquoteCompat($tableAlias, $compat, $GLOBALS['sql_backquotes']) . ' SET'; } else { // insert or replace if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] === 'REPLACE') { @@ -2281,7 +2251,7 @@ class ExportSql extends ExportPlugin //truncate table before insert if (isset($GLOBALS['sql_truncate']) && $GLOBALS['sql_truncate'] && $sqlCommand === 'INSERT') { $truncate = 'TRUNCATE TABLE ' - . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes) . ';'; + . Util::backquoteCompat($tableAlias, $compat, $GLOBALS['sql_backquotes']) . ';'; $truncatehead = $this->possibleCRLF() . $this->exportComment() . $this->exportComment( @@ -2298,18 +2268,18 @@ class ExportSql extends ExportPlugin if ($GLOBALS['sql_insert_syntax'] === 'complete' || $GLOBALS['sql_insert_syntax'] === 'both') { $fields = implode(', ', $fieldSet); $schemaInsert = $sqlCommand . $insertDelayed . ' INTO ' - . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes) + . Util::backquoteCompat($tableAlias, $compat, $GLOBALS['sql_backquotes']) // avoid EOL blank . ' (' . $fields . ') VALUES'; } else { $schemaInsert = $sqlCommand . $insertDelayed . ' INTO ' - . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes) + . Util::backquoteCompat($tableAlias, $compat, $GLOBALS['sql_backquotes']) . ' VALUES'; } } //\x08\\x09, not required - $current_row = 0; + $GLOBALS['current_row'] = 0; $querySize = 0; if ( ($GLOBALS['sql_insert_syntax'] === 'extended' @@ -2324,7 +2294,7 @@ class ExportSql extends ExportPlugin } while ($row = $result->fetchRow()) { - if ($current_row == 0) { + if ($GLOBALS['current_row'] == 0) { $head = $this->possibleCRLF() . $this->exportComment() . $this->exportComment( @@ -2342,7 +2312,7 @@ class ExportSql extends ExportPlugin if ( isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] === 'MSSQL' - && $current_row == 0 + && $GLOBALS['current_row'] == 0 ) { if ( ! $this->export->outputHandler( @@ -2350,7 +2320,7 @@ class ExportSql extends ExportPlugin . Util::backquoteCompat( $tableAlias, $compat, - $sql_backquotes + $GLOBALS['sql_backquotes'] ) . ' ON ;' . $crlf ) @@ -2359,7 +2329,7 @@ class ExportSql extends ExportPlugin } } - $current_row++; + $GLOBALS['current_row']++; $values = []; for ($j = 0; $j < $fieldsCnt; $j++) { // NULL @@ -2391,7 +2361,7 @@ class ExportSql extends ExportPlugin } } elseif ($fieldsMeta[$j]->isMappedTypeBit) { // detection of 'bit' works only on mysqli extension - $values[] = "b'" . $dbi->escapeString( + $values[] = "b'" . $GLOBALS['dbi']->escapeString( Util::printableBitValue( (int) $row[$j], (int) $fieldsMeta[$j]->length @@ -2406,7 +2376,7 @@ class ExportSql extends ExportPlugin } else { // something else -> treat as a string $values[] = '\'' - . $dbi->escapeString($row[$j]) + . $GLOBALS['dbi']->escapeString($row[$j]) . '\''; } } @@ -2437,7 +2407,7 @@ class ExportSql extends ExportPlugin } else { // Extended inserts case if ($GLOBALS['sql_insert_syntax'] === 'extended' || $GLOBALS['sql_insert_syntax'] === 'both') { - if ($current_row == 1) { + if ($GLOBALS['current_row'] == 1) { $insertLine = $schemaInsert . '(' . implode(', ', $values) . ')'; } else { @@ -2450,7 +2420,7 @@ class ExportSql extends ExportPlugin } $querySize = 0; - $current_row = 1; + $GLOBALS['current_row'] = 1; $insertLine = $schemaInsert . $insertLine; } } @@ -2465,25 +2435,31 @@ class ExportSql extends ExportPlugin unset($values); - if (! $this->export->outputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insertLine)) { + if ( + ! $this->export->outputHandler(($GLOBALS['current_row'] == 1 ? '' : $separator . $crlf) . $insertLine) + ) { return false; } } - if ($current_row > 0) { + if ($GLOBALS['current_row'] > 0) { if (! $this->export->outputHandler(';' . $crlf)) { return false; } } // We need to SET IDENTITY_INSERT OFF for MSSQL - if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] === 'MSSQL' && $current_row > 0) { + if ( + isset($GLOBALS['sql_compatibility']) + && $GLOBALS['sql_compatibility'] === 'MSSQL' + && $GLOBALS['current_row'] > 0 + ) { $outputSucceeded = $this->export->outputHandler( $crlf . 'SET IDENTITY_INSERT ' . Util::backquoteCompat( $tableAlias, $compat, - $sql_backquotes + $GLOBALS['sql_backquotes'] ) . ' OFF;' . $crlf ); diff --git a/libraries/classes/Plugins/Export/ExportTexytext.php b/libraries/classes/Plugins/Export/ExportTexytext.php index fe4cb85d38..f64a45830e 100644 --- a/libraries/classes/Plugins/Export/ExportTexytext.php +++ b/libraries/classes/Plugins/Export/ExportTexytext.php @@ -165,8 +165,6 @@ class ExportTexytext extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $what, $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -182,11 +180,15 @@ class ExportTexytext extends ExportPlugin } // Gets the data from the database - $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->query( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $fields_cnt = $result->numFields(); // If required, get fields name at the first line - if (isset($GLOBALS[$what . '_columns'])) { + if (isset($GLOBALS[$GLOBALS['what'] . '_columns'])) { $text_output = "|------\n"; foreach ($result->getFieldNames() as $col_as) { if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) { @@ -207,7 +209,7 @@ class ExportTexytext extends ExportPlugin $text_output = ''; for ($j = 0; $j < $fields_cnt; $j++) { if (! isset($row[$j])) { - $value = $GLOBALS[$what . '_null']; + $value = $GLOBALS[$GLOBALS['what'] . '_null']; } elseif ($row[$j] == '0' || $row[$j] != '') { $value = $row[$j]; } else { @@ -255,15 +257,13 @@ class ExportTexytext extends ExportPlugin */ public function getTableDefStandIn($db, $view, $crlf, $aliases = []) { - global $dbi; - $text_output = ''; /** * Get the unique keys in the table */ $unique_keys = []; - $keys = $dbi->getTableIndexes($db, $view); + $keys = $GLOBALS['dbi']->getTableIndexes($db, $view); foreach ($keys as $key) { if ($key['Non_unique'] != 0) { continue; @@ -275,7 +275,7 @@ class ExportTexytext extends ExportPlugin /** * Gets fields properties */ - $dbi->selectDb($db); + $GLOBALS['dbi']->selectDb($db); /** * Displays the table structure @@ -288,7 +288,7 @@ class ExportTexytext extends ExportPlugin . '|' . __('Default') . "\n|------\n"; - $columns = $dbi->getColumns($db, $view); + $columns = $GLOBALS['dbi']->getColumns($db, $view); foreach ($columns as $column) { $col_as = $column['Field'] ?? null; if (! empty($aliases[$db]['tables'][$view]['columns'][$col_as])) { @@ -338,8 +338,6 @@ class ExportTexytext extends ExportPlugin $view = false, array $aliases = [] ) { - global $dbi; - $relationParameters = $this->relation->getRelationParameters(); $text_output = ''; @@ -348,7 +346,7 @@ class ExportTexytext extends ExportPlugin * Get the unique keys in the table */ $unique_keys = []; - $keys = $dbi->getTableIndexes($db, $table); + $keys = $GLOBALS['dbi']->getTableIndexes($db, $table); foreach ($keys as $key) { if ($key['Non_unique'] != 0) { continue; @@ -360,7 +358,7 @@ class ExportTexytext extends ExportPlugin /** * Gets fields properties */ - $dbi->selectDb($db); + $GLOBALS['dbi']->selectDb($db); // Check if we can use Relations [$res_rel, $have_rel] = $this->relation->getRelationsAndStatus( @@ -394,7 +392,7 @@ class ExportTexytext extends ExportPlugin $text_output .= "\n|------\n"; - $columns = $dbi->getColumns($db, $table); + $columns = $GLOBALS['dbi']->getColumns($db, $table); foreach ($columns as $column) { $col_as = $column['Field']; if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) { @@ -446,8 +444,6 @@ class ExportTexytext extends ExportPlugin */ public function getTriggers($db, $table) { - global $dbi; - $dump = "|------\n"; $dump .= '|' . __('Name'); $dump .= '|' . __('Time'); @@ -455,7 +451,7 @@ class ExportTexytext extends ExportPlugin $dump .= '|' . __('Definition'); $dump .= "\n|------\n"; - $triggers = $dbi->getTriggers($db, $table); + $triggers = $GLOBALS['dbi']->getTriggers($db, $table); foreach ($triggers as $trigger) { $dump .= '|' . $trigger['name']; @@ -507,8 +503,6 @@ class ExportTexytext extends ExportPlugin $dates = false, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); @@ -534,7 +528,7 @@ class ExportTexytext extends ExportPlugin break; case 'triggers': $dump = ''; - $triggers = $dbi->getTriggers($db, $table); + $triggers = $GLOBALS['dbi']->getTriggers($db, $table); if ($triggers) { $dump .= '== ' . __('Triggers') . ' ' . $table_alias . "\n\n"; $dump .= $this->getTriggers($db, $table); diff --git a/libraries/classes/Plugins/Export/ExportXml.php b/libraries/classes/Plugins/Export/ExportXml.php index fe3e7d7dcd..116726124f 100644 --- a/libraries/classes/Plugins/Export/ExportXml.php +++ b/libraries/classes/Plugins/Export/ExportXml.php @@ -56,13 +56,12 @@ class ExportXml extends ExportPlugin */ private function initSpecificVariables(): void { - global $table, $tables; - $this->setTable($table); - if (! is_array($tables)) { + $this->setTable($GLOBALS['table']); + if (! is_array($GLOBALS['tables'])) { return; } - $this->setTables($tables); + $this->setTables($GLOBALS['tables']); } protected function setProperties(): ExportPluginProperties @@ -156,10 +155,8 @@ class ExportXml extends ExportPlugin */ private function exportRoutinesDefinition($db, $type, $dbitype) { - global $dbi; - // Export routines - $routines = $dbi->getProceduresOrFunctions($db, $dbitype); + $routines = $GLOBALS['dbi']->getProceduresOrFunctions($db, $dbitype); return $this->exportDefinitions($db, $type, $dbitype, $routines); } @@ -176,22 +173,20 @@ class ExportXml extends ExportPlugin */ private function exportDefinitions($db, $type, $dbitype, array $names) { - global $crlf, $dbi; - $head = ''; if ($names) { foreach ($names as $name) { $head .= ' ' . $crlf; + . htmlspecialchars($name) . '">' . $GLOBALS['crlf']; // Do some formatting - $sql = $dbi->getDefinition($db, $dbitype, $name); + $sql = $GLOBALS['dbi']->getDefinition($db, $dbitype, $name); $sql = htmlspecialchars(rtrim($sql)); $sql = str_replace("\n", "\n ", $sql); - $head .= ' ' . $sql . $crlf; - $head .= ' ' . $crlf; + $head .= ' ' . $sql . $GLOBALS['crlf']; + $head .= ' ' . $GLOBALS['crlf']; } } @@ -205,7 +200,6 @@ class ExportXml extends ExportPlugin public function exportHeader(): bool { $this->initSpecificVariables(); - global $crlf, $cfg, $db, $dbi; $table = $this->getTable(); $tables = $this->getTables(); @@ -222,46 +216,46 @@ class ExportXml extends ExportPlugin $charset = 'utf-8'; } - $head = '' . $crlf - . '' . $crlf . $crlf; + . Util::localisedDate() . $GLOBALS['crlf'] + . '- ' . __('Server version:') . ' ' . $GLOBALS['dbi']->getVersionString() . $GLOBALS['crlf'] + . '- ' . __('PHP Version:') . ' ' . PHP_VERSION . $GLOBALS['crlf'] + . '-->' . $GLOBALS['crlf'] . $GLOBALS['crlf']; $head .= '' . $crlf; + . '>' . $GLOBALS['crlf']; if ($export_struct) { - $result = $dbi->fetchResult( + $result = $GLOBALS['dbi']->fetchResult( 'SELECT `DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME`' . ' FROM `information_schema`.`SCHEMATA` WHERE `SCHEMA_NAME`' - . ' = \'' . $dbi->escapeString($db) . '\' LIMIT 1' + . ' = \'' . $GLOBALS['dbi']->escapeString($GLOBALS['db']) . '\' LIMIT 1' ); $db_collation = $result[0]['DEFAULT_COLLATION_NAME']; $db_charset = $result[0]['DEFAULT_CHARACTER_SET_NAME']; - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; + . '">' . $GLOBALS['crlf']; if (count($tables) === 0) { $tables[] = $table; @@ -269,14 +263,14 @@ class ExportXml extends ExportPlugin foreach ($tables as $table) { // Export tables and views - $result = $dbi->fetchResult( - 'SHOW CREATE TABLE ' . Util::backquote($db) . '.' + $result = $GLOBALS['dbi']->fetchResult( + 'SHOW CREATE TABLE ' . Util::backquote($GLOBALS['db']) . '.' . Util::backquote($table), 0 ); $tbl = (string) $result[$table][1]; - $is_view = $dbi->getTable($db, $table) + $is_view = $GLOBALS['dbi']->getTable($GLOBALS['db'], $table) ->isView(); if ($is_view) { @@ -294,20 +288,20 @@ class ExportXml extends ExportPlugin } $head .= ' ' - . $crlf; + . $GLOBALS['crlf']; $tbl = ' ' . htmlspecialchars($tbl); $tbl = str_replace("\n", "\n ", $tbl); - $head .= $tbl . ';' . $crlf; - $head .= ' ' . $crlf; + $head .= $tbl . ';' . $GLOBALS['crlf']; + $head .= ' ' . $GLOBALS['crlf']; if (! isset($GLOBALS['xml_export_triggers']) || ! $GLOBALS['xml_export_triggers']) { continue; } // Export triggers - $triggers = $dbi->getTriggers($db, $table); + $triggers = $GLOBALS['dbi']->getTriggers($GLOBALS['db'], $table); if (! $triggers) { continue; } @@ -315,45 +309,45 @@ class ExportXml extends ExportPlugin foreach ($triggers as $trigger) { $code = $trigger['create']; $head .= ' ' . $crlf; + . htmlspecialchars($trigger['name']) . '">' . $GLOBALS['crlf']; // Do some formatting $code = mb_substr(rtrim($code), 0, -3); $code = ' ' . htmlspecialchars($code); $code = str_replace("\n", "\n ", $code); - $head .= $code . $crlf; - $head .= ' ' . $crlf; + $head .= $code . $GLOBALS['crlf']; + $head .= ' ' . $GLOBALS['crlf']; } unset($trigger, $triggers); } if (isset($GLOBALS['xml_export_functions']) && $GLOBALS['xml_export_functions']) { - $head .= $this->exportRoutinesDefinition($db, 'function', 'FUNCTION'); + $head .= $this->exportRoutinesDefinition($GLOBALS['db'], 'function', 'FUNCTION'); } if (isset($GLOBALS['xml_export_procedures']) && $GLOBALS['xml_export_procedures']) { - $head .= $this->exportRoutinesDefinition($db, 'procedure', 'PROCEDURE'); + $head .= $this->exportRoutinesDefinition($GLOBALS['db'], 'procedure', 'PROCEDURE'); } if (isset($GLOBALS['xml_export_events']) && $GLOBALS['xml_export_events']) { // Export events - $events = $dbi->fetchResult( + $events = $GLOBALS['dbi']->fetchResult( 'SELECT EVENT_NAME FROM information_schema.EVENTS ' - . "WHERE EVENT_SCHEMA='" . $dbi->escapeString($db) + . "WHERE EVENT_SCHEMA='" . $GLOBALS['dbi']->escapeString($GLOBALS['db']) . "'" ); - $head .= $this->exportDefinitions($db, 'event', 'EVENT', $events); + $head .= $this->exportDefinitions($GLOBALS['db'], 'event', 'EVENT', $events); } unset($result); - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; + $head .= ' ' . $GLOBALS['crlf']; + $head .= ' ' . $GLOBALS['crlf']; if ($export_data) { - $head .= $crlf; + $head .= $GLOBALS['crlf']; } } @@ -378,18 +372,16 @@ class ExportXml extends ExportPlugin */ public function exportDBHeader($db, $dbAlias = ''): bool { - global $crlf; - if (empty($dbAlias)) { $dbAlias = $db; } if (isset($GLOBALS['xml_export_contents']) && $GLOBALS['xml_export_contents']) { - $head = ' ' . $crlf . ' ' . $crlf; + . htmlspecialchars($dbAlias) . '\'' . $GLOBALS['crlf'] + . ' -->' . $GLOBALS['crlf'] . ' ' . $GLOBALS['crlf']; return $this->export->outputHandler($head); } @@ -404,10 +396,8 @@ class ExportXml extends ExportPlugin */ public function exportDBFooter($db): bool { - global $crlf; - if (isset($GLOBALS['xml_export_contents']) && $GLOBALS['xml_export_contents']) { - return $this->export->outputHandler(' ' . $crlf); + return $this->export->outputHandler(' ' . $GLOBALS['crlf']); } return true; @@ -443,10 +433,8 @@ class ExportXml extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $dbi; - // Do not export data for merge tables - if ($dbi->getTable($db, $table)->isMerge()) { + if ($GLOBALS['dbi']->getTable($db, $table)->isMerge()) { return true; } @@ -454,7 +442,11 @@ class ExportXml extends ExportPlugin $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); if (isset($GLOBALS['xml_export_contents']) && $GLOBALS['xml_export_contents']) { - $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->query( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $columns_cnt = $result->numFields(); $columns = $result->getFieldNames(); @@ -541,9 +533,7 @@ class ExportXml extends ExportPlugin public function isAvailable(): bool { - global $db; - // Can't do server export. - return isset($db) && strlen($db) > 0; + return isset($GLOBALS['db']) && strlen($GLOBALS['db']) > 0; } } diff --git a/libraries/classes/Plugins/Export/ExportYaml.php b/libraries/classes/Plugins/Export/ExportYaml.php index 49448cd299..ac5def7dad 100644 --- a/libraries/classes/Plugins/Export/ExportYaml.php +++ b/libraries/classes/Plugins/Export/ExportYaml.php @@ -132,15 +132,17 @@ class ExportYaml extends ExportPlugin $sqlQuery, array $aliases = [] ): bool { - global $dbi; - $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); - $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $result = $GLOBALS['dbi']->query( + $sqlQuery, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $columns_cnt = $result->numFields(); - $fieldsMeta = $dbi->getFieldsMeta($result); + $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result); $columns = []; foreach ($fieldsMeta as $i => $field) { diff --git a/libraries/classes/Plugins/Export/Helpers/Pdf.php b/libraries/classes/Plugins/Export/Helpers/Pdf.php index d24a4c2c21..ed60b5513e 100644 --- a/libraries/classes/Plugins/Export/Helpers/Pdf.php +++ b/libraries/classes/Plugins/Export/Helpers/Pdf.php @@ -115,10 +115,8 @@ class Pdf extends PdfLib $diskcache = false, $pdfa = false ) { - global $dbi; - parent::__construct($orientation, $unit, $format, $unicode, $encoding, $diskcache, $pdfa); - $this->relation = new Relation($dbi); + $this->relation = new Relation($GLOBALS['dbi']); $this->transformations = new Transformations(); } @@ -180,7 +178,6 @@ class Pdf extends PdfLib // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function Header(): void { - global $maxY; // We don't want automatic page breaks while generating header // as this can lead to infinite recursion as auto generated page // will want header as well causing another page break @@ -210,7 +207,7 @@ class Pdf extends PdfLib $this->SetXY($l, $this->tMargin); $this->MultiCell($this->tablewidths[$col], $this->FontSizePt, $txt); $l += $this->tablewidths[$col]; - $maxY = $maxY < $this->GetY() ? $this->GetY() : $maxY; + $GLOBALS['maxY'] = $GLOBALS['maxY'] < $this->GetY() ? $this->GetY() : $GLOBALS['maxY']; } $this->SetXY($this->lMargin, $this->tMargin); @@ -218,7 +215,7 @@ class Pdf extends PdfLib $l = $this->lMargin; foreach ($this->colTitles as $col => $txt) { $this->SetXY($l, $this->tMargin); - $this->Cell($this->tablewidths[$col], $maxY - $this->tMargin, '', 1, 0, 'L', true); + $this->Cell($this->tablewidths[$col], $GLOBALS['maxY'] - $this->tMargin, '', 1, 0, 'L', true); $this->SetXY($l, $this->tMargin); $this->MultiCell($this->tablewidths[$col], $this->FontSizePt, $txt, 0, 'C'); $l += $this->tablewidths[$col]; @@ -231,7 +228,7 @@ class Pdf extends PdfLib // phpcs:enable - $this->dataY = $maxY; + $this->dataY = $GLOBALS['maxY']; $this->setAutoPageBreak(true); } @@ -336,9 +333,7 @@ class Pdf extends PdfLib */ public function getTriggers($db, $table): void { - global $dbi; - - $triggers = $dbi->getTriggers($db, $table); + $triggers = $GLOBALS['dbi']->getTriggers($db, $table); if ($triggers === []) { return; //prevents printing blank trigger list for any table } @@ -486,8 +481,6 @@ class Pdf extends PdfLib $view = false, array $aliases = [] ): void { - global $dbi; - $relationParameters = $this->relation->getRelationParameters(); unset( @@ -502,7 +495,7 @@ class Pdf extends PdfLib /** * Gets fields properties */ - $dbi->selectDb($db); + $GLOBALS['dbi']->selectDb($db); /** * All these three checks do_relation, do_comment and do_mime is @@ -575,7 +568,7 @@ class Pdf extends PdfLib $mime_map = $this->transformations->getMime($db, $table, true); } - $columns = $dbi->getColumns($db, $table); + $columns = $GLOBALS['dbi']->getColumns($db, $table); // some things to set and 'remember' $l = $this->lMargin; @@ -706,8 +699,6 @@ class Pdf extends PdfLib */ public function mysqlReport($query): void { - global $dbi; - unset( $this->tablewidths, $this->colTitles, @@ -720,9 +711,13 @@ class Pdf extends PdfLib /** * Pass 1 for column widths */ - $this->results = $dbi->query($query, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $this->results = $GLOBALS['dbi']->query( + $query, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $this->numFields = $this->results->numFields(); - $this->fields = $dbi->getFieldsMeta($this->results); + $this->fields = $GLOBALS['dbi']->getFieldsMeta($this->results); // sColWidth = starting col width (an average size width) $availableWidth = $this->w - $this->lMargin - $this->rMargin; @@ -849,7 +844,11 @@ class Pdf extends PdfLib // Pass 2 - $this->results = $dbi->query($query, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED); + $this->results = $GLOBALS['dbi']->query( + $query, + DatabaseInterface::CONNECT_USER, + DatabaseInterface::QUERY_UNBUFFERED + ); $this->SetY($this->tMargin); $this->AddPage(); $this->SetFont(PdfLib::PMA_PDF_FONT, '', 9); diff --git a/libraries/classes/Plugins/ExportPlugin.php b/libraries/classes/Plugins/ExportPlugin.php index 5c77114d06..065c36872e 100644 --- a/libraries/classes/Plugins/ExportPlugin.php +++ b/libraries/classes/Plugins/ExportPlugin.php @@ -41,10 +41,8 @@ abstract class ExportPlugin implements Plugin final public function __construct() { - global $dbi; - - $this->relation = new Relation($dbi); - $this->export = new Export($dbi); + $this->relation = new Relation($GLOBALS['dbi']); + $this->export = new Export($GLOBALS['dbi']); $this->transformations = new Transformations(); $this->init(); $this->properties = $this->setProperties(); diff --git a/libraries/classes/Plugins/Import/ImportCsv.php b/libraries/classes/Plugins/Import/ImportCsv.php index 928491cf7d..dbf9d2ca59 100644 --- a/libraries/classes/Plugins/Import/ImportCsv.php +++ b/libraries/classes/Plugins/Import/ImportCsv.php @@ -158,32 +158,32 @@ class ImportCsv extends AbstractImportCsv */ public function doImport(?File $importHandle = null, array &$sql_data = []): void { - global $error, $message, $dbi; - global $db, $table, $csv_terminated, $csv_enclosed, $csv_escaped, - $csv_new_line, $csv_columns, $errorUrl; // $csv_replace and $csv_ignore should have been here, // but we use directly from $_POST - global $timeout_passed, $finished; $replacements = [ '\\n' => "\n", '\\t' => "\t", '\\r' => "\r", ]; - $csv_terminated = strtr($csv_terminated, $replacements); - $csv_enclosed = strtr($csv_enclosed, $replacements); - $csv_escaped = strtr($csv_escaped, $replacements); - $csv_new_line = strtr($csv_new_line, $replacements); + $GLOBALS['csv_terminated'] = strtr($GLOBALS['csv_terminated'], $replacements); + $GLOBALS['csv_enclosed'] = strtr($GLOBALS['csv_enclosed'], $replacements); + $GLOBALS['csv_escaped'] = strtr($GLOBALS['csv_escaped'], $replacements); + $GLOBALS['csv_new_line'] = strtr($GLOBALS['csv_new_line'], $replacements); - [$error, $message] = $this->buildErrorsForParams( - $csv_terminated, - $csv_enclosed, - $csv_escaped, - $csv_new_line, - (string) $errorUrl + [$GLOBALS['error'], $GLOBALS['message']] = $this->buildErrorsForParams( + $GLOBALS['csv_terminated'], + $GLOBALS['csv_enclosed'], + $GLOBALS['csv_escaped'], + $GLOBALS['csv_new_line'], + (string) $GLOBALS['errorUrl'] ); - [$sql_template, $required_fields, $fields] = $this->getSqlTemplateAndRequiredFields($db, $table, $csv_columns); + [$sql_template, $required_fields, $fields] = $this->getSqlTemplateAndRequiredFields( + $GLOBALS['db'], + $GLOBALS['table'], + $GLOBALS['csv_columns'] + ); // Defaults for parser $i = 0; @@ -218,8 +218,8 @@ class ImportCsv extends AbstractImportCsv $buffer = ''; $col_count = 0; $max_cols = 0; - $csv_terminated_len = mb_strlen($csv_terminated); - while (! ($finished && $i >= $len) && ! $error && ! $timeout_passed) { + $csv_terminated_len = mb_strlen($GLOBALS['csv_terminated']); + while (! ($GLOBALS['finished'] && $i >= $len) && ! $GLOBALS['error'] && ! $GLOBALS['timeout_passed']) { $data = $this->import->getNextChunk($importHandle); if ($data === false) { // subtract data we didn't handle yet and stop processing @@ -233,23 +233,23 @@ class ImportCsv extends AbstractImportCsv unset($data); // Force a trailing new line at EOF to prevent parsing problems - if ($finished && $buffer) { + if ($GLOBALS['finished'] && $buffer) { $finalch = mb_substr($buffer, -1); - if ($csv_new_line === 'auto' && $finalch != "\r" && $finalch != "\n") { + if ($GLOBALS['csv_new_line'] === 'auto' && $finalch != "\r" && $finalch != "\n") { $buffer .= "\n"; - } elseif ($csv_new_line !== 'auto' && $finalch != $csv_new_line) { - $buffer .= $csv_new_line; + } elseif ($GLOBALS['csv_new_line'] !== 'auto' && $finalch != $GLOBALS['csv_new_line']) { + $buffer .= $GLOBALS['csv_new_line']; } } // Do not parse string when we're not at the end // and don't have new line inside if ( - ($csv_new_line === 'auto' + ($GLOBALS['csv_new_line'] === 'auto' && ! str_contains($buffer, "\r") && ! str_contains($buffer, "\n")) - || ($csv_new_line !== 'auto' - && ! str_contains($buffer, $csv_new_line)) + || ($GLOBALS['csv_new_line'] !== 'auto' + && ! str_contains($buffer, $GLOBALS['csv_new_line'])) ) { continue; } @@ -260,7 +260,7 @@ class ImportCsv extends AbstractImportCsv // Currently parsed char $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len); $i += $csv_terminated_len - 1; } @@ -268,11 +268,11 @@ class ImportCsv extends AbstractImportCsv while ($i < $len) { // Deadlock protection if ($lasti == $i && $lastlen == $len) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __('Invalid format of CSV input on line %d.') ); - $message->addParam($line); - $error = true; + $GLOBALS['message']->addParam($line); + $GLOBALS['error'] = true; break; } @@ -282,7 +282,7 @@ class ImportCsv extends AbstractImportCsv // This can happen with auto EOL and \r at the end of buffer if (! $csv_finish) { // Grab empty field - if ($ch == $csv_terminated) { + if ($ch == $GLOBALS['csv_terminated']) { if ($i == $len - 1) { break; } @@ -290,7 +290,7 @@ class ImportCsv extends AbstractImportCsv $values[] = ''; $i++; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len); $i += $csv_terminated_len - 1; } @@ -300,7 +300,7 @@ class ImportCsv extends AbstractImportCsv // Grab one field $fallbacki = $i; - if ($ch == $csv_enclosed) { + if ($ch == $GLOBALS['csv_enclosed']) { if ($i == $len - 1) { break; } @@ -308,7 +308,7 @@ class ImportCsv extends AbstractImportCsv $need_end = true; $i++; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len); $i += $csv_terminated_len - 1; } @@ -320,15 +320,15 @@ class ImportCsv extends AbstractImportCsv $value = ''; while ( ($need_end - && ($ch != $csv_enclosed - || $csv_enclosed == $csv_escaped)) + && ($ch != $GLOBALS['csv_enclosed'] + || $GLOBALS['csv_enclosed'] == $GLOBALS['csv_escaped'])) || (! $need_end - && ! ($ch == $csv_terminated - || $ch == $csv_new_line - || ($csv_new_line === 'auto' + && ! ($ch == $GLOBALS['csv_terminated'] + || $ch == $GLOBALS['csv_new_line'] + || ($GLOBALS['csv_new_line'] === 'auto' && ($ch == "\r" || $ch == "\n")))) ) { - if ($ch == $csv_escaped) { + if ($ch == $GLOBALS['csv_escaped']) { if ($i == $len - 1) { $fail = true; break; @@ -336,16 +336,16 @@ class ImportCsv extends AbstractImportCsv $i++; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len); $i += $csv_terminated_len - 1; } if ( - $csv_enclosed == $csv_escaped - && ($ch == $csv_terminated - || $ch == $csv_new_line - || ($csv_new_line === 'auto' + $GLOBALS['csv_enclosed'] == $GLOBALS['csv_escaped'] + && ($ch == $GLOBALS['csv_terminated'] + || $ch == $GLOBALS['csv_new_line'] + || ($GLOBALS['csv_new_line'] === 'auto' && ($ch == "\r" || $ch == "\n"))) ) { break; @@ -354,7 +354,7 @@ class ImportCsv extends AbstractImportCsv $value .= $ch; if ($i == $len - 1) { - if (! $finished) { + if (! $GLOBALS['finished']) { $fail = true; } @@ -363,7 +363,7 @@ class ImportCsv extends AbstractImportCsv $i++; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len <= 1 || $ch != $csv_terminated[0]) { + if ($csv_terminated_len <= 1 || $ch != $GLOBALS['csv_terminated'][0]) { continue; } @@ -379,7 +379,7 @@ class ImportCsv extends AbstractImportCsv if ($fail) { $i = $fallbacki; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $i += $csv_terminated_len - 1; } @@ -387,13 +387,13 @@ class ImportCsv extends AbstractImportCsv } // Need to strip trailing enclosing char? - if ($need_end && $ch == $csv_enclosed) { - if ($finished && $i == $len - 1) { + if ($need_end && $ch == $GLOBALS['csv_enclosed']) { + if ($GLOBALS['finished'] && $i == $len - 1) { $ch = null; } elseif ($i == $len - 1) { $i = $fallbacki; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $i += $csv_terminated_len - 1; } @@ -401,7 +401,7 @@ class ImportCsv extends AbstractImportCsv } else { $i++; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len); $i += $csv_terminated_len - 1; } @@ -410,19 +410,19 @@ class ImportCsv extends AbstractImportCsv // Are we at the end? if ( - $ch == $csv_new_line - || ($csv_new_line === 'auto' && ($ch == "\r" || $ch == "\n")) - || ($finished && $i == $len - 1) + $ch == $GLOBALS['csv_new_line'] + || ($GLOBALS['csv_new_line'] === 'auto' && ($ch == "\r" || $ch == "\n")) + || ($GLOBALS['finished'] && $i == $len - 1) ) { $csv_finish = true; } // Go to next char - if ($ch == $csv_terminated) { + if ($ch == $GLOBALS['csv_terminated']) { if ($i == $len - 1) { $i = $fallbacki; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $i += $csv_terminated_len - 1; } @@ -431,7 +431,7 @@ class ImportCsv extends AbstractImportCsv $i++; $ch = mb_substr($buffer, $i, 1); - if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) { + if ($csv_terminated_len > 1 && $ch == $GLOBALS['csv_terminated'][0]) { $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len); $i += $csv_terminated_len - 1; } @@ -444,14 +444,14 @@ class ImportCsv extends AbstractImportCsv // End of line if ( ! $csv_finish - && $ch != $csv_new_line - && ($csv_new_line !== 'auto' || ($ch != "\r" && $ch != "\n")) + && $ch != $GLOBALS['csv_new_line'] + && ($GLOBALS['csv_new_line'] !== 'auto' || ($ch != "\r" && $ch != "\n")) ) { continue; } - if ($csv_new_line === 'auto' && $ch == "\r") { // Handle "\r\n" - if ($i >= ($len - 2) && ! $finished) { + if ($GLOBALS['csv_new_line'] === 'auto' && $ch == "\r") { // Handle "\r\n" + if ($i >= ($len - 2) && ! $GLOBALS['finished']) { break; // We need more data to decide new line } @@ -485,13 +485,13 @@ class ImportCsv extends AbstractImportCsv if (count($values) != $required_fields) { // Hack for excel if ($values[count($values) - 1] !== ';') { - $message = Message::error( + $GLOBALS['message'] = Message::error( __( 'Invalid column count in CSV input on line %d.' ) ); - $message->addParam($line); - $error = true; + $GLOBALS['message']->addParam($line); + $GLOBALS['error'] = true; break; } @@ -509,7 +509,7 @@ class ImportCsv extends AbstractImportCsv $sql .= 'NULL'; } else { $sql .= '\'' - . $dbi->escapeString($val) + . $GLOBALS['dbi']->escapeString($val) . '\''; } @@ -544,13 +544,13 @@ class ImportCsv extends AbstractImportCsv $lasti = -1; $ch = mb_substr($buffer, 0, 1); if ($max_lines > 0 && $line == $max_lines_constraint) { - $finished = 1; + $GLOBALS['finished'] = 1; break; } } if ($max_lines > 0 && $line == $max_lines_constraint) { - $finished = 1; + $GLOBALS['finished'] = 1; break; } } @@ -571,7 +571,7 @@ class ImportCsv extends AbstractImportCsv array_shift($rows); } - $tbl_name = $this->getTableNameFromImport((string) $db); + $tbl_name = $this->getTableNameFromImport((string) $GLOBALS['db']); $tables[] = [ $tbl_name, @@ -604,12 +604,12 @@ class ImportCsv extends AbstractImportCsv if (isset($_REQUEST['csv_new_db_name']) && strlen($_REQUEST['csv_new_db_name']) > 0) { $newDb = $_REQUEST['csv_new_db_name']; } else { - $result = $dbi->fetchResult('SHOW DATABASES'); + $result = $GLOBALS['dbi']->fetchResult('SHOW DATABASES'); $newDb = 'CSV_DB ' . (count($result) + 1); } - [$db_name, $options] = $this->getDbnameAndOptions($db, $newDb); + [$db_name, $options] = $this->getDbnameAndOptions($GLOBALS['db'], $newDb); /* Non-applicable parameters */ $create = null; @@ -623,15 +623,15 @@ class ImportCsv extends AbstractImportCsv // Commit any possible data in buffers $this->import->runQuery('', '', $sql_data); - if (count($values) == 0 || $error !== false) { + if (count($values) == 0 || $GLOBALS['error'] !== false) { return; } - $message = Message::error( + $GLOBALS['message'] = Message::error( __('Invalid format of CSV input on line %d.') ); - $message->addParam($line); - $error = true; + $GLOBALS['message']->addParam($line); + $GLOBALS['error'] = true; } private function buildErrorsForParams( @@ -641,15 +641,13 @@ class ImportCsv extends AbstractImportCsv string $csvNewLine, string $errUrl ): array { - global $error, $message; - $param_error = false; if (strlen($csvTerminated) === 0) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __('Invalid parameter for CSV import: %s') ); - $message->addParam(__('Columns terminated with')); - $error = true; + $GLOBALS['message']->addParam(__('Columns terminated with')); + $GLOBALS['error'] = true; $param_error = true; // The default dialog of MS Excel when generating a CSV produces a // semi-colon-separated file with no chance of specifying the @@ -660,29 +658,29 @@ class ImportCsv extends AbstractImportCsv // But the parser won't work correctly with strings so we allow just // one character. } elseif (mb_strlen($csvEnclosed) > 1) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __('Invalid parameter for CSV import: %s') ); - $message->addParam(__('Columns enclosed with')); - $error = true; + $GLOBALS['message']->addParam(__('Columns enclosed with')); + $GLOBALS['error'] = true; $param_error = true; // I could not find a test case where having no escaping characters // confuses this script. // But the parser won't work correctly with strings so we allow just // one character. } elseif (mb_strlen($csvEscaped) > 1) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __('Invalid parameter for CSV import: %s') ); - $message->addParam(__('Columns escaped with')); - $error = true; + $GLOBALS['message']->addParam(__('Columns escaped with')); + $GLOBALS['error'] = true; $param_error = true; } elseif (mb_strlen($csvNewLine) != 1 && $csvNewLine !== 'auto') { - $message = Message::error( + $GLOBALS['message'] = Message::error( __('Invalid parameter for CSV import: %s') ); - $message->addParam(__('Lines terminated with')); - $error = true; + $GLOBALS['message']->addParam(__('Lines terminated with')); + $GLOBALS['error'] = true; $param_error = true; } @@ -690,21 +688,19 @@ class ImportCsv extends AbstractImportCsv // indicate that immediately. if ($param_error) { Generator::mysqlDie( - $message->getMessage(), + $GLOBALS['message']->getMessage(), '', false, $errUrl ); } - return [$error, $message]; + return [$GLOBALS['error'], $GLOBALS['message']]; } private function getTableNameFromImport(string $databaseName): string { - global $import_file_name, $dbi; - - $importFileName = basename($import_file_name, '.csv'); + $importFileName = basename($GLOBALS['import_file_name'], '.csv'); $importFileName = mb_strtolower($importFileName); $importFileName = (string) preg_replace('/[^a-zA-Z0-9_]/', '_', $importFileName); @@ -714,7 +710,7 @@ class ImportCsv extends AbstractImportCsv } if (mb_strlen($databaseName)) { - $result = $dbi->fetchResult('SHOW TABLES'); + $result = $GLOBALS['dbi']->fetchResult('SHOW TABLES'); // logic to get table name from filename // if no table then use filename as table name @@ -767,8 +763,6 @@ class ImportCsv extends AbstractImportCsv ?string $table, ?string $csvColumns ): array { - global $dbi, $error, $message; - $requiredFields = 0; $sqlTemplate = ''; $fields = []; @@ -780,7 +774,7 @@ class ImportCsv extends AbstractImportCsv $sqlTemplate .= ' INTO ' . Util::backquote($table); - $tmp_fields = $dbi->getColumns($db, $table); + $tmp_fields = $GLOBALS['dbi']->getColumns($db, $table); if (empty($csvColumns)) { $fields = $tmp_fields; @@ -808,15 +802,15 @@ class ImportCsv extends AbstractImportCsv } if (! $found) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __( 'Invalid column (%s) specified! Ensure that columns' . ' names are spelled correctly, separated by commas' . ', and not enclosed in quotes.' ) ); - $message->addParam($val); - $error = true; + $GLOBALS['message']->addParam($val); + $GLOBALS['error'] = true; break; } diff --git a/libraries/classes/Plugins/Import/ImportLdi.php b/libraries/classes/Plugins/Import/ImportLdi.php index bbfee3107e..249cb8845a 100644 --- a/libraries/classes/Plugins/Import/ImportLdi.php +++ b/libraries/classes/Plugins/Import/ImportLdi.php @@ -91,16 +91,12 @@ class ImportLdi extends AbstractImportCsv */ public function doImport(?File $importHandle = null, array &$sql_data = []): void { - global $finished, $import_file, $charset_conversion, $table, $dbi; - global $ldi_local_option, $ldi_replace, $ldi_ignore, $ldi_terminated, - $ldi_enclosed, $ldi_escaped, $ldi_new_line, $skip_queries, $ldi_columns; - $compression = ''; if ($importHandle !== null) { $compression = $importHandle->getCompression(); } - if ($import_file === 'none' || $compression !== 'none' || $charset_conversion) { + if ($GLOBALS['import_file'] === 'none' || $compression !== 'none' || $GLOBALS['charset_conversion']) { // We handle only some kind of data! $GLOBALS['message'] = Message::error( __('This plugin does not support compressed imports!') @@ -111,52 +107,52 @@ class ImportLdi extends AbstractImportCsv } $sql = 'LOAD DATA'; - if (isset($ldi_local_option)) { + if (isset($GLOBALS['ldi_local_option'])) { $sql .= ' LOCAL'; } - $sql .= ' INFILE \'' . $dbi->escapeString($import_file) + $sql .= ' INFILE \'' . $GLOBALS['dbi']->escapeString($GLOBALS['import_file']) . '\''; - if (isset($ldi_replace)) { + if (isset($GLOBALS['ldi_replace'])) { $sql .= ' REPLACE'; - } elseif (isset($ldi_ignore)) { + } elseif (isset($GLOBALS['ldi_ignore'])) { $sql .= ' IGNORE'; } - $sql .= ' INTO TABLE ' . Util::backquote($table); + $sql .= ' INTO TABLE ' . Util::backquote($GLOBALS['table']); - if (strlen((string) $ldi_terminated) > 0) { - $sql .= ' FIELDS TERMINATED BY \'' . $ldi_terminated . '\''; + if (strlen((string) $GLOBALS['ldi_terminated']) > 0) { + $sql .= ' FIELDS TERMINATED BY \'' . $GLOBALS['ldi_terminated'] . '\''; } - if (strlen((string) $ldi_enclosed) > 0) { + if (strlen((string) $GLOBALS['ldi_enclosed']) > 0) { $sql .= ' ENCLOSED BY \'' - . $dbi->escapeString($ldi_enclosed) . '\''; + . $GLOBALS['dbi']->escapeString($GLOBALS['ldi_enclosed']) . '\''; } - if (strlen((string) $ldi_escaped) > 0) { + if (strlen((string) $GLOBALS['ldi_escaped']) > 0) { $sql .= ' ESCAPED BY \'' - . $dbi->escapeString($ldi_escaped) . '\''; + . $GLOBALS['dbi']->escapeString($GLOBALS['ldi_escaped']) . '\''; } - if (strlen((string) $ldi_new_line) > 0) { - if ($ldi_new_line === 'auto') { - $ldi_new_line = PHP_EOL == "\n" + if (strlen((string) $GLOBALS['ldi_new_line']) > 0) { + if ($GLOBALS['ldi_new_line'] === 'auto') { + $GLOBALS['ldi_new_line'] = PHP_EOL == "\n" ? '\n' : '\r\n'; } - $sql .= ' LINES TERMINATED BY \'' . $ldi_new_line . '\''; + $sql .= ' LINES TERMINATED BY \'' . $GLOBALS['ldi_new_line'] . '\''; } - if ($skip_queries > 0) { - $sql .= ' IGNORE ' . $skip_queries . ' LINES'; - $skip_queries = 0; + if ($GLOBALS['skip_queries'] > 0) { + $sql .= ' IGNORE ' . $GLOBALS['skip_queries'] . ' LINES'; + $GLOBALS['skip_queries'] = 0; } - if (strlen((string) $ldi_columns) > 0) { + if (strlen((string) $GLOBALS['ldi_columns']) > 0) { $sql .= ' ('; - $tmp = preg_split('/,( ?)/', $ldi_columns); + $tmp = preg_split('/,( ?)/', $GLOBALS['ldi_columns']); if (! is_array($tmp)) { $tmp = []; @@ -179,23 +175,19 @@ class ImportLdi extends AbstractImportCsv $this->import->runQuery($sql, $sql, $sql_data); $this->import->runQuery('', '', $sql_data); - $finished = true; + $GLOBALS['finished'] = true; } public function isAvailable(): bool { - global $plugin_param; - // We need relations enabled and we work only on database. - return isset($plugin_param) && $plugin_param === 'table'; + return isset($GLOBALS['plugin_param']) && $GLOBALS['plugin_param'] === 'table'; } private function setLdiLocalOptionConfig(): void { - global $dbi; - $GLOBALS['cfg']['Import']['ldi_local_option'] = false; - $result = $dbi->tryQuery('SELECT @@local_infile;'); + $result = $GLOBALS['dbi']->tryQuery('SELECT @@local_infile;'); if ($result === false || $result->numRows() <= 0) { return; diff --git a/libraries/classes/Plugins/Import/ImportMediawiki.php b/libraries/classes/Plugins/Import/ImportMediawiki.php index 17bfd6ac1d..a306fe9ceb 100644 --- a/libraries/classes/Plugins/Import/ImportMediawiki.php +++ b/libraries/classes/Plugins/Import/ImportMediawiki.php @@ -68,8 +68,6 @@ class ImportMediawiki extends ImportPlugin */ public function doImport(?File $importHandle = null, array &$sql_data = []): void { - global $error, $timeout_passed, $finished; - // Defaults for parser // The buffer that will be used to store chunks read from the imported file @@ -97,7 +95,7 @@ class ImportMediawiki extends ImportPlugin $in_table_header = false; - while (! $finished && ! $error && ! $timeout_passed) { + while (! $GLOBALS['finished'] && ! $GLOBALS['error'] && ! $GLOBALS['timeout_passed']) { $data = $this->import->getNextChunk($importHandle); if ($data === false) { @@ -129,7 +127,7 @@ class ImportMediawiki extends ImportPlugin $full_buffer_lines_count = count($buffer_lines); // If the reading is not finalized, the final line of the current chunk // will not be complete - if (! $finished) { + if (! $GLOBALS['finished']) { $last_chunk_line = $buffer_lines[--$full_buffer_lines_count]; } @@ -275,7 +273,7 @@ class ImportMediawiki extends ImportPlugin __('Invalid format of mediawiki input on line:
%s.') ); $message->addParam($cur_buffer_line); - $error = true; + $GLOBALS['error'] = true; } } } @@ -331,13 +329,11 @@ class ImportMediawiki extends ImportPlugin */ private function setTableName(&$table_name): void { - global $dbi; - if (! empty($table_name)) { return; } - $result = $dbi->fetchResult('SHOW TABLES'); + $result = $GLOBALS['dbi']->fetchResult('SHOW TABLES'); // todo check if the name below already exists $table_name = 'TABLE ' . (count($result) + 1); } @@ -382,12 +378,10 @@ class ImportMediawiki extends ImportPlugin */ private function executeImportTables(array &$tables, array &$analyses, array &$sql_data): void { - global $db; - // $db_name : The currently selected database name, if applicable // No backquotes // $options : An associative array of options - [$db_name, $options] = $this->getDbnameAndOptions($db, 'mediawiki_DB'); + [$db_name, $options] = $this->getDbnameAndOptions($GLOBALS['db'], 'mediawiki_DB'); // Array of SQL strings // Non-applicable parameters diff --git a/libraries/classes/Plugins/Import/ImportOds.php b/libraries/classes/Plugins/Import/ImportOds.php index 71499abaf8..d78f71bf25 100644 --- a/libraries/classes/Plugins/Import/ImportOds.php +++ b/libraries/classes/Plugins/Import/ImportOds.php @@ -103,15 +103,13 @@ class ImportOds extends ImportPlugin */ public function doImport(?File $importHandle = null, array &$sql_data = []): void { - global $db, $error, $timeout_passed, $finished; - $buffer = ''; /** * Read in the file via Import::getNextChunk so that * it can process compressed files */ - while (! $finished && ! $error && ! $timeout_passed) { + while (! $GLOBALS['finished'] && ! $GLOBALS['error'] && ! $GLOBALS['timeout_passed']) { $data = $this->import->getNextChunk($importHandle); if ($data === false) { /* subtract data we didn't handle yet and stop processing */ @@ -215,7 +213,7 @@ class ImportOds extends ImportPlugin */ /* Set database name to the currently selected one, if applicable */ - [$db_name, $options] = $this->getDbnameAndOptions($db, 'ODS_DB'); + [$db_name, $options] = $this->getDbnameAndOptions($GLOBALS['db'], 'ODS_DB'); /* Non-applicable parameters */ $create = null; diff --git a/libraries/classes/Plugins/Import/ImportShp.php b/libraries/classes/Plugins/Import/ImportShp.php index 667eee0e2f..9cc4430486 100644 --- a/libraries/classes/Plugins/Import/ImportShp.php +++ b/libraries/classes/Plugins/Import/ImportShp.php @@ -79,8 +79,6 @@ class ImportShp extends ImportPlugin */ public function doImport(?File $importHandle = null, array &$sql_data = []): void { - global $db, $error, $finished, $import_file, $local_import_file, $message, $dbi; - $GLOBALS['finished'] = false; if ($importHandle === null || $this->zipExtension === null) { @@ -95,12 +93,12 @@ class ImportShp extends ImportPlugin $shp = new ShapeFileImport(1); // If the zip archive has more than one file, // get the correct content to the buffer from .shp file. - if ($compression === 'application/zip' && $this->zipExtension->getNumberOfFiles($import_file) > 1) { + if ($compression === 'application/zip' && $this->zipExtension->getNumberOfFiles($GLOBALS['import_file']) > 1) { if ($importHandle->openZip('/^.*\.shp$/i') === false) { - $message = Message::error( + $GLOBALS['message'] = Message::error( __('There was an error importing the ESRI shape file: "%s".') ); - $message->addParam($importHandle->getError()); + $GLOBALS['message']->addParam($importHandle->getError()); return; } @@ -113,11 +111,11 @@ class ImportShp extends ImportPlugin // If we can extract the zip archive to 'TempDir' // and use the files in it for import if ($compression === 'application/zip' && $temp !== null) { - $dbf_file_name = $this->zipExtension->findFile($import_file, '/^.*\.dbf$/i'); + $dbf_file_name = $this->zipExtension->findFile($GLOBALS['import_file'], '/^.*\.dbf$/i'); // If the corresponding .dbf file is in the zip archive if ($dbf_file_name) { // Extract the .dbf file and point to it. - $extracted = $this->zipExtension->extract($import_file, $dbf_file_name); + $extracted = $this->zipExtension->extract($GLOBALS['import_file'], $dbf_file_name); if ($extracted !== false) { // remove filename extension, e.g. // dresden_osm.shp/gis.osm_transport_a_v06.dbf @@ -140,12 +138,16 @@ class ImportShp extends ImportPlugin } } } - } elseif (! empty($local_import_file) && ! empty($GLOBALS['cfg']['UploadDir']) && $compression === 'none') { + } elseif ( + ! empty($GLOBALS['local_import_file']) + && ! empty($GLOBALS['cfg']['UploadDir']) + && $compression === 'none' + ) { // If file is in UploadDir, use .dbf file in the same UploadDir // to load extra data. // Replace the .shp with .*, // so the bsShapeFiles library correctly locates .dbf file. - $shp->fileName = mb_substr($import_file, 0, -4) . '.*'; + $shp->fileName = mb_substr($GLOBALS['import_file'], 0, -4) . '.*'; } } @@ -158,11 +160,11 @@ class ImportShp extends ImportPlugin } if ($shp->lastError != '') { - $error = true; - $message = Message::error( + $GLOBALS['error'] = true; + $GLOBALS['message'] = Message::error( __('There was an error importing the ESRI shape file: "%s".') ); - $message->addParam($shp->lastError); + $GLOBALS['message']->addParam($shp->lastError); return; } @@ -188,11 +190,11 @@ class ImportShp extends ImportPlugin $gis_type = 'multipoint'; break; default: - $error = true; - $message = Message::error( + $GLOBALS['error'] = true; + $GLOBALS['message'] = Message::error( __('MySQL Spatial Extension does not support ESRI type "%s".') ); - $message->addParam($shp->getShapeName()); + $GLOBALS['message']->addParam($shp->getShapeName()); return; } @@ -237,8 +239,8 @@ class ImportShp extends ImportPlugin } if (count($rows) === 0) { - $error = true; - $message = Message::error( + $GLOBALS['error'] = true; + $GLOBALS['message'] = Message::error( __('The imported file does not contain any data!') ); @@ -258,8 +260,8 @@ class ImportShp extends ImportPlugin } // Set table name based on the number of tables - if (strlen((string) $db) > 0) { - $result = $dbi->fetchResult('SHOW TABLES'); + if (strlen((string) $GLOBALS['db']) > 0) { + $result = $GLOBALS['dbi']->fetchResult('SHOW TABLES'); $table_name = 'TABLE ' . (count($result) + 1); } else { $table_name = 'TBL_NAME'; @@ -283,8 +285,8 @@ class ImportShp extends ImportPlugin $analyses[$table_no][Import::FORMATTEDSQL][$spatial_col] = true; // Set database name to the currently selected one, if applicable - if (strlen((string) $db) > 0) { - $db_name = $db; + if (strlen((string) $GLOBALS['db']) > 0) { + $db_name = $GLOBALS['db']; $options = ['create_db' => false]; } else { $db_name = 'SHP_DB'; @@ -297,8 +299,8 @@ class ImportShp extends ImportPlugin unset($tables, $analyses); - $finished = true; - $error = false; + $GLOBALS['finished'] = true; + $GLOBALS['error'] = false; // Commit any possible data in buffers $this->import->runQuery('', '', $sql_data); @@ -316,20 +318,18 @@ class ImportShp extends ImportPlugin */ public static function readFromBuffer($length) { - global $buffer, $eof, $importHandle; - $import = new Import(); - if (strlen((string) $buffer) < $length) { + if (strlen((string) $GLOBALS['buffer']) < $length) { if ($GLOBALS['finished']) { - $eof = true; + $GLOBALS['eof'] = true; } else { - $buffer .= $import->getNextChunk($importHandle); + $GLOBALS['buffer'] .= $import->getNextChunk($GLOBALS['importHandle']); } } - $result = substr($buffer, 0, $length); - $buffer = substr($buffer, $length); + $result = substr($GLOBALS['buffer'], 0, $length); + $GLOBALS['buffer'] = substr($GLOBALS['buffer'], $length); return $result; } diff --git a/libraries/classes/Plugins/Import/ImportSql.php b/libraries/classes/Plugins/Import/ImportSql.php index a881c1f238..9fa01ace65 100644 --- a/libraries/classes/Plugins/Import/ImportSql.php +++ b/libraries/classes/Plugins/Import/ImportSql.php @@ -38,14 +38,12 @@ class ImportSql extends ImportPlugin protected function setProperties(): ImportPluginProperties { - global $dbi; - $importPluginProperties = new ImportPluginProperties(); $importPluginProperties->setText('SQL'); $importPluginProperties->setExtension('sql'); $importPluginProperties->setOptionsText(__('Options')); - $compats = $dbi->getCompatibilities(); + $compats = $GLOBALS['dbi']->getCompatibilities(); if (count($compats) > 0) { $values = []; foreach ($compats as $val) { @@ -101,10 +99,8 @@ class ImportSql extends ImportPlugin */ public function doImport(?File $importHandle = null, array &$sql_data = []): void { - global $error, $timeout_passed, $dbi; - // Handle compatibility options. - $this->setSQLMode($dbi, $_REQUEST); + $this->setSQLMode($GLOBALS['dbi'], $_REQUEST); $bq = new BufferedQuery(); if (isset($_POST['sql_delimiter'])) { @@ -118,7 +114,7 @@ class ImportSql extends ImportPlugin */ $GLOBALS['finished'] = false; - while (! $error && (! $timeout_passed)) { + while (! $GLOBALS['error'] && (! $GLOBALS['timeout_passed'])) { // Getting the first statement, the remaining data and the last // delimiter. $statement = $bq->extract(); @@ -152,7 +148,7 @@ class ImportSql extends ImportPlugin } // Extracting remaining statements. - while (! $error && ! $timeout_passed && ! empty($bq->query)) { + while (! $GLOBALS['error'] && ! $GLOBALS['timeout_passed'] && ! empty($bq->query)) { $statement = $bq->extract(true); if (empty($statement)) { continue; diff --git a/libraries/classes/Plugins/Import/ImportXml.php b/libraries/classes/Plugins/Import/ImportXml.php index e54f5da1cb..a5b88b2831 100644 --- a/libraries/classes/Plugins/Import/ImportXml.php +++ b/libraries/classes/Plugins/Import/ImportXml.php @@ -60,15 +60,13 @@ class ImportXml extends ImportPlugin */ public function doImport(?File $importHandle = null, array &$sql_data = []): void { - global $error, $timeout_passed, $finished, $db; - $buffer = ''; /** * Read in the file via Import::getNextChunk so that * it can process compressed files */ - while (! $finished && ! $error && ! $timeout_passed) { + while (! $GLOBALS['finished'] && ! $GLOBALS['error'] && ! $GLOBALS['timeout_passed']) { $data = $this->import->getNextChunk($importHandle); if ($data === false) { /* subtract data we didn't handle yet and stop processing */ @@ -338,9 +336,9 @@ class ImportXml extends ImportPlugin */ /* Set database name to the currently selected one, if applicable */ - if (strlen((string) $db)) { + if (strlen((string) $GLOBALS['db'])) { /* Override the database name in the XML file, if one is selected */ - $db_name = $db; + $db_name = $GLOBALS['db']; $options = ['create_db' => false]; } else { /* Set database collation/charset */ diff --git a/libraries/classes/Plugins/Import/ShapeFileImport.php b/libraries/classes/Plugins/Import/ShapeFileImport.php index ad33377de5..18cb02355a 100644 --- a/libraries/classes/Plugins/Import/ShapeFileImport.php +++ b/libraries/classes/Plugins/Import/ShapeFileImport.php @@ -32,8 +32,6 @@ class ShapeFileImport extends ShapeFile */ public function eofSHP(): bool { - global $eof; - - return (bool) $eof; + return (bool) $GLOBALS['eof']; } } diff --git a/libraries/classes/Plugins/Import/Upload/UploadNoplugin.php b/libraries/classes/Plugins/Import/Upload/UploadNoplugin.php index 987080ad21..82fcfbe048 100644 --- a/libraries/classes/Plugins/Import/Upload/UploadNoplugin.php +++ b/libraries/classes/Plugins/Import/Upload/UploadNoplugin.php @@ -39,14 +39,12 @@ class UploadNoplugin implements UploadInterface */ public static function getUploadStatus($id) { - global $SESSION_KEY; - if (trim($id) == '') { return null; } - if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) { - $_SESSION[$SESSION_KEY][$id] = [ + if (! array_key_exists($id, $_SESSION[$GLOBALS['SESSION_KEY']])) { + $_SESSION[$GLOBALS['SESSION_KEY']][$id] = [ 'id' => $id, 'finished' => false, 'percent' => 0, @@ -56,6 +54,6 @@ class UploadNoplugin implements UploadInterface ]; } - return $_SESSION[$SESSION_KEY][$id]; + return $_SESSION[$GLOBALS['SESSION_KEY']][$id]; } } diff --git a/libraries/classes/Plugins/Import/Upload/UploadProgress.php b/libraries/classes/Plugins/Import/Upload/UploadProgress.php index fc971e173b..45e65376f8 100644 --- a/libraries/classes/Plugins/Import/Upload/UploadProgress.php +++ b/libraries/classes/Plugins/Import/Upload/UploadProgress.php @@ -40,14 +40,12 @@ class UploadProgress implements UploadInterface */ public static function getUploadStatus($id) { - global $SESSION_KEY; - if (trim($id) == '') { return null; } - if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) { - $_SESSION[$SESSION_KEY][$id] = [ + if (! array_key_exists($id, $_SESSION[$GLOBALS['SESSION_KEY']])) { + $_SESSION[$GLOBALS['SESSION_KEY']][$id] = [ 'id' => $id, 'finished' => false, 'percent' => 0, @@ -57,7 +55,7 @@ class UploadProgress implements UploadInterface ]; } - $ret = $_SESSION[$SESSION_KEY][$id]; + $ret = $_SESSION[$GLOBALS['SESSION_KEY']][$id]; if (! Ajax::progressCheck() || $ret['finished']) { return $ret; @@ -94,7 +92,7 @@ class UploadProgress implements UploadInterface ]; } - $_SESSION[$SESSION_KEY][$id] = $ret; + $_SESSION[$GLOBALS['SESSION_KEY']][$id] = $ret; return $ret; } diff --git a/libraries/classes/Plugins/Import/Upload/UploadSession.php b/libraries/classes/Plugins/Import/Upload/UploadSession.php index 1e94f64e4b..c601a4aaae 100644 --- a/libraries/classes/Plugins/Import/Upload/UploadSession.php +++ b/libraries/classes/Plugins/Import/Upload/UploadSession.php @@ -40,14 +40,12 @@ class UploadSession implements UploadInterface */ public static function getUploadStatus($id) { - global $SESSION_KEY; - if (trim($id) == '') { return null; } - if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) { - $_SESSION[$SESSION_KEY][$id] = [ + if (! array_key_exists($id, $_SESSION[$GLOBALS['SESSION_KEY']])) { + $_SESSION[$GLOBALS['SESSION_KEY']][$id] = [ 'id' => $id, 'finished' => false, 'percent' => 0, @@ -57,7 +55,7 @@ class UploadSession implements UploadInterface ]; } - $ret = $_SESSION[$SESSION_KEY][$id]; + $ret = $_SESSION[$GLOBALS['SESSION_KEY']][$id]; if (! Ajax::sessionCheck() || $ret['finished']) { return $ret; @@ -89,7 +87,7 @@ class UploadSession implements UploadInterface ]; } - $_SESSION[$SESSION_KEY][$id] = $ret; + $_SESSION[$GLOBALS['SESSION_KEY']][$id] = $ret; return $ret; } diff --git a/libraries/classes/Plugins/Schema/ExportRelationSchema.php b/libraries/classes/Plugins/Schema/ExportRelationSchema.php index 7a56736011..370e2a2e84 100644 --- a/libraries/classes/Plugins/Schema/ExportRelationSchema.php +++ b/libraries/classes/Plugins/Schema/ExportRelationSchema.php @@ -62,13 +62,11 @@ class ExportRelationSchema */ public function __construct($db, $diagram) { - global $dbi; - $this->db = $db; $this->diagram = $diagram; $this->setPageNumber((int) $_REQUEST['page_number']); $this->setOffline(isset($_REQUEST['offline_export'])); - $this->relation = new Relation($dbi); + $this->relation = new Relation($GLOBALS['dbi']); } /** @@ -247,8 +245,6 @@ class ExportRelationSchema */ protected function getFileName($extension): string { - global $dbi; - $pdfFeature = $this->relation->getRelationParameters()->pdfFeature; $filename = $this->db . $extension; @@ -258,7 +254,7 @@ class ExportRelationSchema . Util::backquote($pdfFeature->database) . '.' . Util::backquote($pdfFeature->pdfPages) . ' WHERE page_nr = ' . $this->pageNumber; - $_name_rs = $dbi->queryAsControlUser($_name_sql); + $_name_rs = $GLOBALS['dbi']->queryAsControlUser($_name_sql); $_name_row = $_name_rs->fetchRow(); $filename = $_name_row[0] . $extension; } diff --git a/libraries/classes/Plugins/Schema/Pdf/Pdf.php b/libraries/classes/Plugins/Schema/Pdf/Pdf.php index 32d591d6ad..7e0a7fa188 100644 --- a/libraries/classes/Plugins/Schema/Pdf/Pdf.php +++ b/libraries/classes/Plugins/Schema/Pdf/Pdf.php @@ -98,13 +98,11 @@ class Pdf extends PdfLib $withDoc, $db ) { - global $dbi; - parent::__construct($orientation, $unit, $paper); $this->pageNumber = $pageNumber; $this->withDoc = $withDoc; $this->db = $db; - $this->relation = new Relation($dbi); + $this->relation = new Relation($GLOBALS['dbi']); } /** @@ -258,8 +256,6 @@ class Pdf extends PdfLib // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function Header(): void { - global $dbi; - // We only show this if we find something in the new pdf_pages table // This function must be named "Header" to work with the TCPDF library @@ -274,9 +270,9 @@ class Pdf extends PdfLib $test_query = 'SELECT * FROM ' . Util::backquote($pdfFeature->database) . '.' . Util::backquote($pdfFeature->pdfPages) - . ' WHERE db_name = \'' . $dbi->escapeString($this->db) + . ' WHERE db_name = \'' . $GLOBALS['dbi']->escapeString($this->db) . '\' AND page_nr = \'' . $this->pageNumber . '\''; - $test_rs = $dbi->queryAsControlUser($test_query); + $test_rs = $GLOBALS['dbi']->queryAsControlUser($test_query); $pageDesc = (string) $test_rs->fetchValue('page_descr'); $pg_name = ucfirst($pageDesc); diff --git a/libraries/classes/Plugins/Schema/Pdf/PdfRelationSchema.php b/libraries/classes/Plugins/Schema/Pdf/PdfRelationSchema.php index 6c23e0f9d3..bea748e63a 100644 --- a/libraries/classes/Plugins/Schema/Pdf/PdfRelationSchema.php +++ b/libraries/classes/Plugins/Schema/Pdf/PdfRelationSchema.php @@ -479,8 +479,6 @@ class PdfRelationSchema extends ExportRelationSchema */ public function dataDictionaryDoc(array $alltables): void { - global $dbi; - // TOC $this->diagram->AddPage($this->orientation); $this->diagram->Cell(0, 9, __('Table of contents'), 1, 0, 'C'); @@ -512,7 +510,7 @@ class PdfRelationSchema extends ExportRelationSchema $this->diagram->customLinks['doc'][$table]['-'] ); // $this->diagram->Ln(1); - $fields = $dbi->getColumns($this->db, $table); + $fields = $GLOBALS['dbi']->getColumns($this->db, $table); foreach ($fields as $row) { $this->diagram->SetX(20); $field_name = $row['Field']; @@ -580,7 +578,7 @@ class PdfRelationSchema extends ExportRelationSchema /** * Gets table information */ - $showtable = $dbi->getTable($this->db, $table) + $showtable = $GLOBALS['dbi']->getTable($this->db, $table) ->getStatusInfo(); $show_comment = $showtable['Comment'] ?? ''; $create_time = isset($showtable['Create_time']) @@ -602,7 +600,7 @@ class PdfRelationSchema extends ExportRelationSchema /** * Gets fields properties */ - $columns = $dbi->getColumns($this->db, $table); + $columns = $GLOBALS['dbi']->getColumns($this->db, $table); // Find which tables are related with the current one and write it in // an array diff --git a/libraries/classes/Plugins/Schema/TableStats.php b/libraries/classes/Plugins/Schema/TableStats.php index a3c4d83b69..6c4c0950e9 100644 --- a/libraries/classes/Plugins/Schema/TableStats.php +++ b/libraries/classes/Plugins/Schema/TableStats.php @@ -96,8 +96,6 @@ abstract class TableStats $tableDimension, $offline ) { - global $dbi; - $this->diagram = $diagram; $this->db = $db; $this->pageNumber = $pageNumber; @@ -108,7 +106,7 @@ abstract class TableStats $this->offline = $offline; - $this->relation = new Relation($dbi); + $this->relation = new Relation($GLOBALS['dbi']); $this->font = new Font(); // checks whether the table exists @@ -127,10 +125,8 @@ abstract class TableStats */ protected function validateTableAndLoadFields(): void { - global $dbi; - $sql = 'DESCRIBE ' . Util::backquote($this->tableName); - $result = $dbi->tryQuery($sql); + $result = $GLOBALS['dbi']->tryQuery($sql); if (! $result || ! $result->numRows()) { $this->showMissingTableError(); exit; @@ -192,9 +188,7 @@ abstract class TableStats */ protected function loadPrimaryKey(): void { - global $dbi; - - $result = $dbi->query('SHOW INDEX FROM ' . Util::backquote($this->tableName) . ';'); + $result = $GLOBALS['dbi']->query('SHOW INDEX FROM ' . Util::backquote($this->tableName) . ';'); if ($result->numRows() <= 0) { return; } diff --git a/libraries/classes/Plugins/Transformations/Abs/DownloadTransformationsPlugin.php b/libraries/classes/Plugins/Transformations/Abs/DownloadTransformationsPlugin.php index b584a17208..3b248f0a67 100644 --- a/libraries/classes/Plugins/Transformations/Abs/DownloadTransformationsPlugin.php +++ b/libraries/classes/Plugins/Transformations/Abs/DownloadTransformationsPlugin.php @@ -45,13 +45,11 @@ abstract class DownloadTransformationsPlugin extends TransformationsPlugin */ public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null) { - global $row, $fields_meta; - if (isset($options[0]) && ! empty($options[0])) { $cn = $options[0]; // filename } else { if (isset($options[1]) && ! empty($options[1])) { - foreach ($fields_meta as $key => $val) { + foreach ($GLOBALS['fields_meta'] as $key => $val) { if ($val->name == $options[1]) { $pos = $key; break; @@ -59,7 +57,7 @@ abstract class DownloadTransformationsPlugin extends TransformationsPlugin } if (isset($pos)) { - $cn = $row[$pos]; + $cn = $GLOBALS['row'][$pos]; } } diff --git a/libraries/classes/Plugins/TwoFactorPlugin.php b/libraries/classes/Plugins/TwoFactorPlugin.php index 38f8bcfab2..39d038cbc9 100644 --- a/libraries/classes/Plugins/TwoFactorPlugin.php +++ b/libraries/classes/Plugins/TwoFactorPlugin.php @@ -149,9 +149,7 @@ class TwoFactorPlugin */ public function getAppId($return_url) { - global $config; - - $url = $config->get('PmaAbsoluteUri'); + $url = $GLOBALS['config']->get('PmaAbsoluteUri'); $parsed = []; if (! empty($url)) { $parsedUrl = parse_url($url); @@ -162,7 +160,7 @@ class TwoFactorPlugin } if (! isset($parsed['scheme']) || strlen($parsed['scheme']) === 0) { - $parsed['scheme'] = $config->isHttps() ? 'https' : 'http'; + $parsed['scheme'] = $GLOBALS['config']->isHttps() ? 'https' : 'http'; } if (! isset($parsed['host']) || strlen($parsed['host']) === 0) { diff --git a/libraries/classes/Query/Utilities.php b/libraries/classes/Query/Utilities.php index 5b9beae877..ebf7e68ba0 100644 --- a/libraries/classes/Query/Utilities.php +++ b/libraries/classes/Query/Utilities.php @@ -136,8 +136,6 @@ class Utilities */ public static function usortComparisonCallback(array $a, array $b, string $sortBy, string $sortOrder): int { - global $cfg; - /* No sorting when key is not present */ if (! isset($a[$sortBy], $b[$sortBy])) { return 0; @@ -145,7 +143,7 @@ class Utilities // produces f.e.: // return -1 * strnatcasecmp($a['SCHEMA_TABLES'], $b['SCHEMA_TABLES']) - $compare = $cfg['NaturalOrder'] ? strnatcasecmp( + $compare = $GLOBALS['cfg']['NaturalOrder'] ? strnatcasecmp( (string) $a[$sortBy], (string) $b[$sortBy] ) : strcasecmp( diff --git a/libraries/classes/RecentFavoriteTable.php b/libraries/classes/RecentFavoriteTable.php index 4f07fdfeae..03b815e9bf 100644 --- a/libraries/classes/RecentFavoriteTable.php +++ b/libraries/classes/RecentFavoriteTable.php @@ -70,9 +70,7 @@ class RecentFavoriteTable { $this->template = $template; - global $dbi; - - $this->relation = new Relation($dbi); + $this->relation = new Relation($GLOBALS['dbi']); $this->tableType = $type; $server_id = $GLOBALS['server']; if (! isset($_SESSION['tmpval'][$this->tableType . 'Tables'][$server_id])) { @@ -117,13 +115,11 @@ class RecentFavoriteTable */ public function getFromDb(): array { - global $dbi; - // Read from phpMyAdmin database, if recent tables is not in session $sql_query = ' SELECT `tables` FROM ' . $this->getPmaTable() . - " WHERE `username` = '" . $dbi->escapeString($GLOBALS['cfg']['Server']['user']) . "'"; + " WHERE `username` = '" . $GLOBALS['dbi']->escapeString($GLOBALS['cfg']['Server']['user']) . "'"; - $result = $dbi->tryQueryAsControlUser($sql_query); + $result = $GLOBALS['dbi']->tryQueryAsControlUser($sql_query); if ($result) { $value = $result->fetchValue(); if (is_string($value)) { @@ -141,16 +137,14 @@ class RecentFavoriteTable */ public function saveToDb() { - global $dbi; - $username = $GLOBALS['cfg']['Server']['user']; $sql_query = ' REPLACE INTO ' . $this->getPmaTable() . ' (`username`, `tables`)' . - " VALUES ('" . $dbi->escapeString($username) . "', '" - . $dbi->escapeString( + " VALUES ('" . $GLOBALS['dbi']->escapeString($username) . "', '" + . $GLOBALS['dbi']->escapeString( json_encode($this->tables) ) . "')"; - $success = $dbi->tryQuery($sql_query, DatabaseInterface::CONNECT_CONTROL); + $success = $GLOBALS['dbi']->tryQuery($sql_query, DatabaseInterface::CONNECT_CONTROL); if (! $success) { $error_msg = ''; @@ -166,7 +160,7 @@ class RecentFavoriteTable $message = Message::error($error_msg); $message->addMessage( - Message::rawError($dbi->getError(DatabaseInterface::CONNECT_CONTROL)), + Message::rawError($GLOBALS['dbi']->getError(DatabaseInterface::CONNECT_CONTROL)), '

' ); @@ -269,10 +263,8 @@ class RecentFavoriteTable */ public function add($db, $table) { - global $dbi; - // If table does not exist, do not add._getPmaTable() - if (! $dbi->getColumns($db, $table)) { + if (! $GLOBALS['dbi']->getColumns($db, $table)) { return true; } @@ -304,15 +296,13 @@ class RecentFavoriteTable */ public function removeIfInvalid($db, $table) { - global $dbi; - foreach ($this->tables as $tbl) { if ($tbl['db'] != $db || $tbl['table'] != $table) { continue; } // TODO Figure out a better way to find the existence of a table - if (! $dbi->getColumns($tbl['db'], $tbl['table'])) { + if (! $GLOBALS['dbi']->getColumns($tbl['db'], $tbl['table'])) { return $this->remove($tbl['db'], $tbl['table']); } } diff --git a/libraries/classes/Replication.php b/libraries/classes/Replication.php index fb4170b308..ecbb9539b0 100644 --- a/libraries/classes/Replication.php +++ b/libraries/classes/Replication.php @@ -49,8 +49,6 @@ class Replication */ public function replicaControl(string $action, ?string $control, int $link) { - global $dbi; - $action = mb_strtoupper($action); $control = $control !== null ? mb_strtoupper($control) : ''; @@ -62,7 +60,7 @@ class Replication return -1; } - return $dbi->tryQuery($action . ' SLAVE ' . $control . ';', $link); + return $GLOBALS['dbi']->tryQuery($action . ' SLAVE ' . $control . ';', $link); } /** @@ -89,13 +87,11 @@ class Replication bool $start, int $link ) { - global $dbi; - if ($stop) { $this->replicaControl('STOP', null, $link); } - $out = $dbi->tryQuery( + $out = $GLOBALS['dbi']->tryQuery( 'CHANGE MASTER TO ' . 'MASTER_HOST=\'' . $host . '\',' . 'MASTER_PORT=' . ($port * 1) . ',' . @@ -131,8 +127,6 @@ class Replication $port = null, $socket = null ) { - global $dbi; - $server = []; $server['user'] = $user; $server['password'] = $password; @@ -142,7 +136,7 @@ class Replication // 5th parameter set to true means that it's an auxiliary connection // and we must not go back to login page if it fails - return $dbi->connect(DatabaseInterface::CONNECT_AUXILIARY, $server); + return $GLOBALS['dbi']->connect(DatabaseInterface::CONNECT_AUXILIARY, $server); } /** @@ -156,9 +150,7 @@ class Replication */ public function replicaBinLogPrimary(int $link): array { - global $dbi; - - $data = $dbi->fetchResult('SHOW MASTER STATUS', null, null, $link); + $data = $GLOBALS['dbi']->fetchResult('SHOW MASTER STATUS', null, null, $link); $output = []; if (! empty($data)) { diff --git a/libraries/classes/ReplicationGui.php b/libraries/classes/ReplicationGui.php index 67534e9b95..d62bccfe30 100644 --- a/libraries/classes/ReplicationGui.php +++ b/libraries/classes/ReplicationGui.php @@ -72,11 +72,9 @@ class ReplicationGui */ public function getHtmlForPrimaryReplication(): string { - global $dbi; - if (! isset($_POST['repl_clear_scr'])) { $primaryStatusTable = $this->getHtmlForReplicationStatusTable('primary', true, false); - $replicas = $dbi->fetchResult('SHOW SLAVE HOSTS', null, null); + $replicas = $GLOBALS['dbi']->fetchResult('SHOW SLAVE HOSTS', null, null); $urlParams = $GLOBALS['urlParams']; $urlParams['primary_add_user'] = true; @@ -124,9 +122,7 @@ class ReplicationGui $serverReplicaStatus, array $serverReplicaReplication ): string { - global $dbi; - - $serverReplicaMultiReplication = $dbi->fetchResult('SHOW ALL SLAVES STATUS'); + $serverReplicaMultiReplication = $GLOBALS['dbi']->fetchResult('SHOW ALL SLAVES STATUS'); if ($serverReplicaStatus) { $urlParams = $GLOBALS['urlParams']; $urlParams['sr_take_action'] = true; @@ -255,9 +251,7 @@ class ReplicationGui $isHidden = false, $hasTitle = true ): string { - global $dbi; - - $replicationInfo = new ReplicationInfo($dbi); + $replicationInfo = new ReplicationInfo($GLOBALS['dbi']); $replicationInfo->load($_POST['primary_connection'] ?? null); $replicationVariables = $replicationInfo->primaryVariables; @@ -325,9 +319,7 @@ class ReplicationGui */ public function getUsernameHostnameLength(): array { - global $dbi; - - $fieldsInfo = $dbi->getColumns('mysql', 'user'); + $fieldsInfo = $GLOBALS['dbi']->getColumns('mysql', 'user'); $usernameLength = 16; $hostnameLength = 41; foreach ($fieldsInfo as $val) { @@ -359,8 +351,6 @@ class ReplicationGui */ public function getHtmlForReplicationPrimaryAddReplicaUser(): string { - global $dbi; - [ $usernameLength, $hostnameLength, @@ -375,7 +365,7 @@ class ReplicationGui $username = $GLOBALS['new_username'] ?? $_POST['username']; } - $currentUser = $dbi->fetchValue('SELECT USER();'); + $currentUser = $GLOBALS['dbi']->fetchValue('SELECT USER();'); if (! empty($currentUser)) { $userHost = str_replace( "'", @@ -489,13 +479,11 @@ class ReplicationGui public function handleRequestForReplicaChangePrimary(): bool { - global $dbi; - $sr = [ - 'username' => $dbi->escapeString($_POST['username']), - 'pma_pw' => $dbi->escapeString($_POST['pma_pw']), - 'hostname' => $dbi->escapeString($_POST['hostname']), - 'port' => (int) $dbi->escapeString($_POST['text_port']), + 'username' => $GLOBALS['dbi']->escapeString($_POST['username']), + 'pma_pw' => $GLOBALS['dbi']->escapeString($_POST['pma_pw']), + 'hostname' => $GLOBALS['dbi']->escapeString($_POST['hostname']), + 'port' => (int) $GLOBALS['dbi']->escapeString($_POST['text_port']), ]; $_SESSION['replication']['m_username'] = $sr['username']; @@ -561,14 +549,12 @@ class ReplicationGui public function handleRequestForReplicaServerControl(): bool { - global $dbi; - /** @var string|null $control */ $control = $_POST['sr_replica_control_param'] ?? null; if ($_POST['sr_replica_action'] === 'reset') { $qStop = $this->replication->replicaControl('STOP', null, DatabaseInterface::CONNECT_USER); - $qReset = $dbi->tryQuery('RESET SLAVE;'); + $qReset = $GLOBALS['dbi']->tryQuery('RESET SLAVE;'); $qStart = $this->replication->replicaControl('START', null, DatabaseInterface::CONNECT_USER); $result = $qStop !== false && $qStop !== -1 && @@ -589,15 +575,13 @@ class ReplicationGui public function handleRequestForReplicaSkipError(): bool { - global $dbi; - $count = 1; if (isset($_POST['sr_skip_errors_count'])) { $count = $_POST['sr_skip_errors_count'] * 1; } $qStop = $this->replication->replicaControl('STOP', null, DatabaseInterface::CONNECT_USER); - $qSkip = $dbi->tryQuery('SET GLOBAL SQL_SLAVE_SKIP_COUNTER = ' . $count . ';'); + $qSkip = $GLOBALS['dbi']->tryQuery('SET GLOBAL SQL_SLAVE_SKIP_COUNTER = ' . $count . ';'); $qStart = $this->replication->replicaControl('START', null, DatabaseInterface::CONNECT_USER); return $qStop !== false && $qStop !== -1 && diff --git a/libraries/classes/ReplicationInfo.php b/libraries/classes/ReplicationInfo.php index 982d8fc726..036948b55f 100644 --- a/libraries/classes/ReplicationInfo.php +++ b/libraries/classes/ReplicationInfo.php @@ -80,8 +80,6 @@ final class ReplicationInfo public function load(?string $connection = null): void { - global $urlParams; - $this->setPrimaryStatus(); if (! empty($connection)) { @@ -89,7 +87,7 @@ final class ReplicationInfo if ($this->multiPrimaryStatus) { $this->setDefaultPrimaryConnection($connection); - $urlParams['primary_connection'] = $connection; + $GLOBALS['urlParams']['primary_connection'] = $connection; } } diff --git a/libraries/classes/ResponseRenderer.php b/libraries/classes/ResponseRenderer.php index 95790034ef..2284debf8d 100644 --- a/libraries/classes/ResponseRenderer.php +++ b/libraries/classes/ResponseRenderer.php @@ -302,8 +302,6 @@ class ResponseRenderer */ private function ajaxResponse(): string { - global $dbi; - /* Avoid wrapping in case we're disabled */ if ($this->isDisabled) { return $this->getDisplay(); @@ -328,7 +326,7 @@ class ResponseRenderer $this->addJSON('title', '' . $this->getHeader()->getPageTitle() . ''); } - if (isset($dbi)) { + if (isset($GLOBALS['dbi'])) { $this->addJSON('menu', $this->getHeader()->getMenu()->getDisplay()); } diff --git a/libraries/classes/Routing.php b/libraries/classes/Routing.php index afff4babf7..41d4465040 100644 --- a/libraries/classes/Routing.php +++ b/libraries/classes/Routing.php @@ -45,9 +45,7 @@ class Routing public static function skipCache(): bool { - global $cfg; - - return ($cfg['environment'] ?? '') === 'development'; + return ($GLOBALS['cfg']['environment'] ?? '') === 'development'; } public static function canWriteCache(): bool diff --git a/libraries/classes/SavedSearches.php b/libraries/classes/SavedSearches.php index 9ac29920b9..fc6f8abe76 100644 --- a/libraries/classes/SavedSearches.php +++ b/libraries/classes/SavedSearches.php @@ -232,8 +232,6 @@ class SavedSearches */ public function save(SavedQueryByExampleSearchesFeature $savedQueryByExampleSearchesFeature): bool { - global $dbi; - if ($this->getSearchName() == null) { $message = Message::error( __('Please provide a name for this bookmarked search.') @@ -266,7 +264,7 @@ class SavedSearches //If it's an insert. if ($this->getId() === null) { $wheres = [ - "search_name = '" . $dbi->escapeString($this->getSearchName()) + "search_name = '" . $GLOBALS['dbi']->escapeString($this->getSearchName()) . "'", ]; $existingSearches = $this->getList($savedQueryByExampleSearchesFeature, $wheres); @@ -285,15 +283,15 @@ class SavedSearches $sqlQuery = 'INSERT INTO ' . $savedSearchesTbl . '(`username`, `db_name`, `search_name`, `search_data`)' . ' VALUES (' - . "'" . $dbi->escapeString($this->getUsername()) . "'," - . "'" . $dbi->escapeString($this->getDbname()) . "'," - . "'" . $dbi->escapeString($this->getSearchName()) . "'," - . "'" . $dbi->escapeString(json_encode($this->getCriterias())) + . "'" . $GLOBALS['dbi']->escapeString($this->getUsername()) . "'," + . "'" . $GLOBALS['dbi']->escapeString($this->getDbname()) . "'," + . "'" . $GLOBALS['dbi']->escapeString($this->getSearchName()) . "'," + . "'" . $GLOBALS['dbi']->escapeString(json_encode($this->getCriterias())) . "')"; - $dbi->queryAsControlUser($sqlQuery); + $GLOBALS['dbi']->queryAsControlUser($sqlQuery); - $this->setId($dbi->insertId()); + $this->setId($GLOBALS['dbi']->insertId()); return true; } @@ -301,7 +299,7 @@ class SavedSearches //Else, it's an update. $wheres = [ 'id != ' . $this->getId(), - "search_name = '" . $dbi->escapeString($this->getSearchName()) . "'", + "search_name = '" . $GLOBALS['dbi']->escapeString($this->getSearchName()) . "'", ]; $existingSearches = $this->getList($savedQueryByExampleSearchesFeature, $wheres); @@ -318,12 +316,12 @@ class SavedSearches $sqlQuery = 'UPDATE ' . $savedSearchesTbl . "SET `search_name` = '" - . $dbi->escapeString($this->getSearchName()) . "', " + . $GLOBALS['dbi']->escapeString($this->getSearchName()) . "', " . "`search_data` = '" - . $dbi->escapeString(json_encode($this->getCriterias())) . "' " + . $GLOBALS['dbi']->escapeString(json_encode($this->getCriterias())) . "' " . 'WHERE id = ' . $this->getId(); - return (bool) $dbi->queryAsControlUser($sqlQuery); + return (bool) $GLOBALS['dbi']->queryAsControlUser($sqlQuery); } /** @@ -331,8 +329,6 @@ class SavedSearches */ public function delete(SavedQueryByExampleSearchesFeature $savedQueryByExampleSearchesFeature): bool { - global $dbi; - if ($this->getId() == null) { $message = Message::error( __('Missing information to delete the search.') @@ -348,9 +344,9 @@ class SavedSearches . Util::backquote($savedQueryByExampleSearchesFeature->savedSearches); $sqlQuery = 'DELETE FROM ' . $savedSearchesTbl - . "WHERE id = '" . $dbi->escapeString((string) $this->getId()) . "'"; + . "WHERE id = '" . $GLOBALS['dbi']->escapeString((string) $this->getId()) . "'"; - return (bool) $dbi->queryAsControlUser($sqlQuery); + return (bool) $GLOBALS['dbi']->queryAsControlUser($sqlQuery); } /** @@ -358,8 +354,6 @@ class SavedSearches */ public function load(SavedQueryByExampleSearchesFeature $savedQueryByExampleSearchesFeature): bool { - global $dbi; - if ($this->getId() == null) { $message = Message::error( __('Missing information to load the search.') @@ -376,9 +370,9 @@ class SavedSearches . Util::backquote($savedQueryByExampleSearchesFeature->savedSearches); $sqlQuery = 'SELECT id, search_name, search_data ' . 'FROM ' . $savedSearchesTbl . ' ' - . "WHERE id = '" . $dbi->escapeString((string) $this->getId()) . "' "; + . "WHERE id = '" . $GLOBALS['dbi']->escapeString((string) $this->getId()) . "' "; - $resList = $dbi->queryAsControlUser($sqlQuery); + $resList = $GLOBALS['dbi']->queryAsControlUser($sqlQuery); $oneResult = $resList->fetchAssoc(); if ($oneResult === []) { @@ -405,8 +399,6 @@ class SavedSearches */ public function getList(SavedQueryByExampleSearchesFeature $savedQueryByExampleSearchesFeature, array $wheres = []) { - global $dbi; - if ($this->getUsername() == null || $this->getDbname() == null) { return []; } @@ -417,8 +409,8 @@ class SavedSearches $sqlQuery = 'SELECT id, search_name ' . 'FROM ' . $savedSearchesTbl . ' ' . 'WHERE ' - . "username = '" . $dbi->escapeString($this->getUsername()) . "' " - . "AND db_name = '" . $dbi->escapeString($this->getDbname()) . "' "; + . "username = '" . $GLOBALS['dbi']->escapeString($this->getUsername()) . "' " + . "AND db_name = '" . $GLOBALS['dbi']->escapeString($this->getDbname()) . "' "; foreach ($wheres as $where) { $sqlQuery .= 'AND ' . $where . ' '; @@ -426,7 +418,7 @@ class SavedSearches $sqlQuery .= 'order by search_name ASC '; - $resList = $dbi->queryAsControlUser($sqlQuery); + $resList = $GLOBALS['dbi']->queryAsControlUser($sqlQuery); return $resList->fetchAllKeyPair(); } diff --git a/libraries/classes/Server/Plugins.php b/libraries/classes/Server/Plugins.php index 5404b053b8..920e177d8a 100644 --- a/libraries/classes/Server/Plugins.php +++ b/libraries/classes/Server/Plugins.php @@ -26,10 +26,8 @@ class Plugins */ public function getAll(): array { - global $cfg; - $sql = 'SHOW PLUGINS'; - if (! $cfg['Server']['DisableIS']) { + if (! $GLOBALS['cfg']['Server']['DisableIS']) { $sql = 'SELECT * FROM information_schema.PLUGINS ORDER BY PLUGIN_TYPE, PLUGIN_NAME'; } diff --git a/libraries/classes/Server/Privileges.php b/libraries/classes/Server/Privileges.php index 1d1a315a53..7dd5e1479b 100644 --- a/libraries/classes/Server/Privileges.php +++ b/libraries/classes/Server/Privileges.php @@ -744,12 +744,10 @@ class Privileges $user = null, $host = null ) { - global $pred_username, $pred_hostname, $username, $hostname, $new_username; - [$usernameLength, $hostnameLength] = $this->getUsernameAndHostnameLength(); - if (isset($username) && strlen($username) === 0) { - $pred_username = 'any'; + if (isset($GLOBALS['username']) && strlen($GLOBALS['username']) === 0) { + $GLOBALS['pred_username'] = 'any'; } $currentUser = $this->dbi->fetchValue('SELECT USER();'); @@ -765,17 +763,17 @@ class Privileges ); } - if (! isset($pred_hostname) && isset($hostname)) { - switch (mb_strtolower($hostname)) { + if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) { + switch (mb_strtolower($GLOBALS['hostname'])) { case 'localhost': case '127.0.0.1': - $pred_hostname = 'localhost'; + $GLOBALS['pred_hostname'] = 'localhost'; break; case '%': - $pred_hostname = 'any'; + $GLOBALS['pred_hostname'] = 'any'; break; default: - $pred_hostname = 'userdefined'; + $GLOBALS['pred_hostname'] = 'userdefined'; break; } } @@ -795,13 +793,13 @@ class Privileges } return $this->template->render('server/privileges/login_information_fields', [ - 'pred_username' => $pred_username ?? null, - 'pred_hostname' => $pred_hostname ?? null, + 'pred_username' => $GLOBALS['pred_username'] ?? null, + 'pred_hostname' => $GLOBALS['pred_hostname'] ?? null, 'username_length' => $usernameLength, 'hostname_length' => $hostnameLength, - 'username' => $username ?? null, - 'new_username' => $new_username ?? null, - 'hostname' => $hostname ?? null, + 'username' => $GLOBALS['username'] ?? null, + 'new_username' => $GLOBALS['new_username'] ?? null, + 'hostname' => $GLOBALS['hostname'] ?? null, 'this_host' => $thisHost, 'is_change' => $mode === 'change', 'auth_plugin' => $authPlugin, @@ -857,8 +855,6 @@ class Privileges $username = null, $hostname = null ) { - global $dbi; - /* Fallback (standard) value */ $authenticationPlugin = 'mysql_native_password'; $serverVersion = $this->dbi->getVersion(); @@ -866,9 +862,9 @@ class Privileges if (isset($username, $hostname) && $mode === 'change') { $row = $this->dbi->fetchSingleRow( 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "' - . $dbi->escapeString($username) + . $GLOBALS['dbi']->escapeString($username) . '" AND `Host` = "' - . $dbi->escapeString($hostname) + . $GLOBALS['dbi']->escapeString($hostname) . '" LIMIT 1' ); // Table 'mysql'.'user' may not exist for some previous @@ -881,9 +877,9 @@ class Privileges $row = $this->dbi->fetchSingleRow( 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "' - . $dbi->escapeString($username) + . $GLOBALS['dbi']->escapeString($username) . '" AND `Host` = "' - . $dbi->escapeString($hostname) + . $GLOBALS['dbi']->escapeString($hostname) . '"' ); if (is_array($row) && isset($row['plugin'])) { @@ -932,8 +928,6 @@ class Privileges */ public function updatePassword($errorUrl, $username, $hostname) { - global $dbi; - // similar logic in /user-password $message = null; @@ -1012,8 +1006,8 @@ class Privileges . " `authentication_string` = '" . $hashedPassword . "', `Password` = '', " . " `plugin` = '" . $authenticationPlugin . "'" - . " WHERE `User` = '" . $dbi->escapeString($username) - . "' AND Host = '" . $dbi->escapeString($hostname) . "';"; + . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) + . "' AND Host = '" . $GLOBALS['dbi']->escapeString($hostname) . "';"; } else { // USE 'SET PASSWORD ...' syntax for rest of the versions // Backup the old value, to be reset later @@ -1021,8 +1015,8 @@ class Privileges $origValue = $row['@@old_passwords']; $updatePluginQuery = 'UPDATE `mysql`.`user` SET' . " `plugin` = '" . $authenticationPlugin . "'" - . " WHERE `User` = '" . $dbi->escapeString($username) - . "' AND Host = '" . $dbi->escapeString($hostname) . "';"; + . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) + . "' AND Host = '" . $GLOBALS['dbi']->escapeString($hostname) . "';"; // Update the plugin for the user if (! $this->dbi->tryQuery($updatePluginQuery)) { @@ -3082,8 +3076,6 @@ class Privileges $dbname, $tablename ) { - global $cfg; - $sql = "SELECT '1' FROM `mysql`.`user`" . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'" . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';"; @@ -3143,10 +3135,10 @@ class Privileges } } - $databaseUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database'); - $databaseUrlTitle = Util::getTitleForTarget($cfg['DefaultTabDatabase']); - $tableUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table'); - $tableUrlTitle = Util::getTitleForTarget($cfg['DefaultTabTable']); + $databaseUrl = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'); + $databaseUrlTitle = Util::getTitleForTarget($GLOBALS['cfg']['DefaultTabDatabase']); + $tableUrl = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); + $tableUrlTitle = Util::getTitleForTarget($GLOBALS['cfg']['DefaultTabTable']); $changePassword = ''; $userGroup = ''; diff --git a/libraries/classes/Server/Status/Data.php b/libraries/classes/Server/Status/Data.php index ea54b6129c..4a14a1fb4d 100644 --- a/libraries/classes/Server/Status/Data.php +++ b/libraries/classes/Server/Status/Data.php @@ -352,15 +352,13 @@ class Data public function __construct() { - global $dbi; - - $this->replicationInfo = new ReplicationInfo($dbi); + $this->replicationInfo = new ReplicationInfo($GLOBALS['dbi']); $this->replicationInfo->load($_POST['primary_connection'] ?? null); $this->selfUrl = basename($GLOBALS['PMA_PHP_SELF']); // get status from server - $server_status_result = $dbi->tryQuery('SHOW GLOBAL STATUS'); + $server_status_result = $GLOBALS['dbi']->tryQuery('SHOW GLOBAL STATUS'); if ($server_status_result === false) { $server_status = []; $this->dataLoaded = false; @@ -371,7 +369,7 @@ class Data } // for some calculations we require also some server settings - $server_variables = $dbi->fetchResult('SHOW GLOBAL VARIABLES', 0, 1); + $server_variables = $GLOBALS['dbi']->fetchResult('SHOW GLOBAL VARIABLES', 0, 1); // cleanup of some deprecated values $server_status = self::cleanDeprecated($server_status); diff --git a/libraries/classes/Server/Status/Monitor.php b/libraries/classes/Server/Status/Monitor.php index d00f4e7d26..07fb85a5a5 100644 --- a/libraries/classes/Server/Status/Monitor.php +++ b/libraries/classes/Server/Status/Monitor.php @@ -506,8 +506,6 @@ class Monitor string $database, string $query ): array { - global $cached_affected_rows; - $return = []; if (strlen($database) > 0) { @@ -524,7 +522,7 @@ class Monitor $sqlQuery = preg_replace('/^(\s*SELECT)/i', '\\1 SQL_NO_CACHE', $query); $this->dbi->tryQuery($sqlQuery); - $return['affectedRows'] = $cached_affected_rows; + $return['affectedRows'] = $GLOBALS['cached_affected_rows']; $result = $this->dbi->tryQuery('EXPLAIN ' . $sqlQuery); if ($result !== false) { diff --git a/libraries/classes/Sql.php b/libraries/classes/Sql.php index ccc1dc6fc4..f4a4c78736 100644 --- a/libraries/classes/Sql.php +++ b/libraries/classes/Sql.php @@ -1399,8 +1399,6 @@ class Sql $sqlQuery, ?string $completeQuery ): string { - global $showtable; - // If we are retrieving the full value of a truncated field or the original // value of a transformed field, show it here if (isset($_POST['grid_edit']) && $_POST['grid_edit'] == true && is_object($result)) { @@ -1415,8 +1413,8 @@ class Sql } // Should be initialized these parameters before parsing - if (! is_array($showtable)) { - $showtable = null; + if (! is_array($GLOBALS['showtable'])) { + $GLOBALS['showtable'] = null; } $response = ResponseRenderer::getInstance(); @@ -1526,7 +1524,7 @@ class Sql $editable, $unlimNumRows, $numRows, - $showtable, + $GLOBALS['showtable'], $result, $analyzedSqlResults ); diff --git a/libraries/classes/SqlQueryForm.php b/libraries/classes/SqlQueryForm.php index 3fbc2b064f..7673f9c029 100644 --- a/libraries/classes/SqlQueryForm.php +++ b/libraries/classes/SqlQueryForm.php @@ -64,8 +64,6 @@ class SqlQueryForm $display_tab = false, $delimiter = ';' ) { - global $dbi; - if (! $display_tab) { $display_tab = 'full'; } @@ -92,12 +90,17 @@ class SqlQueryForm [$legend, $query, $columns_list] = $this->init($query); } - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $bookmarkFeature = $relation->getRelationParameters()->bookmarkFeature; $bookmarks = []; if ($display_tab === 'full' && $bookmarkFeature !== null) { - $bookmark_list = Bookmark::getList($bookmarkFeature, $dbi, $GLOBALS['cfg']['Server']['user'], $db); + $bookmark_list = Bookmark::getList( + $bookmarkFeature, + $GLOBALS['dbi'], + $GLOBALS['cfg']['Server']['user'], + $db + ); foreach ($bookmark_list as $bookmarkItem) { $bookmarks[] = [ @@ -140,8 +143,6 @@ class SqlQueryForm */ public function init($query) { - global $dbi; - $columns_list = []; if (strlen($GLOBALS['db']) === 0) { // prepare for server related @@ -172,7 +173,7 @@ class SqlQueryForm // Get the list and number of fields // we do a try_query here, because we could be in the query window, // trying to synchronize and the table has not yet been created - $columns_list = $dbi->getColumns($db, $GLOBALS['table'], true); + $columns_list = $GLOBALS['dbi']->getColumns($db, $GLOBALS['table'], true); $scriptName = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabTable'], 'table'); $tmp_tbl_link = ''; diff --git a/libraries/classes/StorageEngine.php b/libraries/classes/StorageEngine.php index be18f516d6..b973d5b379 100644 --- a/libraries/classes/StorageEngine.php +++ b/libraries/classes/StorageEngine.php @@ -103,18 +103,16 @@ class StorageEngine */ public static function getStorageEngines() { - global $dbi; - static $storage_engines = null; if ($storage_engines == null) { - $storage_engines = $dbi->fetchResult('SHOW STORAGE ENGINES', 'Engine'); - if (! $dbi->isMariaDB() && $dbi->getVersion() >= 50708) { + $storage_engines = $GLOBALS['dbi']->fetchResult('SHOW STORAGE ENGINES', 'Engine'); + if (! $GLOBALS['dbi']->isMariaDB() && $GLOBALS['dbi']->getVersion() >= 50708) { $disabled = (string) SessionCache::get( 'disabled_storage_engines', /** @return mixed|false */ - static function () use ($dbi) { - return $dbi->fetchValue( + static function () { + return $GLOBALS['dbi']->fetchValue( 'SELECT @@disabled_storage_engines' ); } @@ -141,14 +139,13 @@ class StorageEngine */ public static function hasMroongaEngine(): bool { - global $dbi; $cacheKey = 'storage-engine.mroonga.has.mroonga_command'; if (Cache::has($cacheKey)) { return (bool) Cache::get($cacheKey, false); } - $supportsMroonga = $dbi->tryQuery('SELECT mroonga_command(\'object_list\');') !== false; + $supportsMroonga = $GLOBALS['dbi']->tryQuery('SELECT mroonga_command(\'object_list\');') !== false; Cache::set($cacheKey, $supportsMroonga); return $supportsMroonga; @@ -164,13 +161,15 @@ class StorageEngine */ public static function getMroongaLengths(string $dbName, string $tableName): array { - global $dbi; $cacheKey = 'storage-engine.mroonga.object_list.' . $dbName; - $dbi->selectDb($dbName);// Needed for mroonga_command calls + $GLOBALS['dbi']->selectDb($dbName);// Needed for mroonga_command calls if (! Cache::has($cacheKey)) { - $result = $dbi->fetchSingleRow('SELECT mroonga_command(\'object_list\');', DatabaseInterface::FETCH_NUM); + $result = $GLOBALS['dbi']->fetchSingleRow( + 'SELECT mroonga_command(\'object_list\');', + DatabaseInterface::FETCH_NUM + ); $objectList = (array) json_decode($result[0] ?? '', true); foreach ($objectList as $mroongaName => $mroongaData) { /** @@ -200,7 +199,7 @@ class StorageEngine continue; } - $result = $dbi->fetchSingleRow( + $result = $GLOBALS['dbi']->fetchSingleRow( 'SELECT mroonga_command(\'object_inspect ' . $mroongaName . '\');', DatabaseInterface::FETCH_NUM ); @@ -400,8 +399,6 @@ class StorageEngine */ public function getVariablesStatus() { - global $dbi; - $variables = $this->getVariables(); $like = $this->getVariablesLikePattern(); @@ -414,7 +411,7 @@ class StorageEngine $mysql_vars = []; $sql_query = 'SHOW GLOBAL VARIABLES ' . $like . ';'; - $res = $dbi->query($sql_query); + $res = $GLOBALS['dbi']->query($sql_query); foreach ($res as $row) { if (isset($variables[$row['Variable_name']])) { $mysql_vars[$row['Variable_name']] = $variables[$row['Variable_name']]; diff --git a/libraries/classes/Table.php b/libraries/classes/Table.php index 3925b386a3..00d85467cd 100644 --- a/libraries/classes/Table.php +++ b/libraries/classes/Table.php @@ -519,8 +519,6 @@ class Table implements Stringable $columnsWithIndex = null, $oldColumnName = null ) { - global $dbi; - $strLength = strlen($length); $isTimestamp = mb_stripos($type, 'TIMESTAMP') !== false; @@ -536,7 +534,7 @@ class Table implements Stringable if ( $strLength !== 0 && ! preg_match($pattern, $type) - && Compatibility::isIntegersSupportLength($type, $length, $dbi) + && Compatibility::isIntegersSupportLength($type, $length, $GLOBALS['dbi']) ) { // Note: The variable $length here can contain several other things // besides length - ENUM/SET value or length of DECIMAL (eg. 12,3) @@ -607,13 +605,13 @@ class Table implements Stringable } else { // Invalid BOOLEAN value $query .= ' DEFAULT \'' - . $dbi->escapeString($defaultValue) . '\''; + . $GLOBALS['dbi']->escapeString($defaultValue) . '\''; } } elseif ($type === 'BINARY' || $type === 'VARBINARY') { $query .= ' DEFAULT 0x' . $defaultValue; } else { $query .= ' DEFAULT \'' - . $dbi->escapeString((string) $defaultValue) . '\''; + . $GLOBALS['dbi']->escapeString((string) $defaultValue) . '\''; } break; @@ -654,7 +652,7 @@ class Table implements Stringable } if (! empty($comment)) { - $query .= " COMMENT '" . $dbi->escapeString($comment) . "'"; + $query .= " COMMENT '" . $GLOBALS['dbi']->escapeString($comment) . "'"; } // move column @@ -893,9 +891,7 @@ class Table implements Stringable array $whereFields, array $newFields ) { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $relationParameters = $relation->getRelationParameters(); $relationParams = $relationParameters->toArray(); $lastId = -1; @@ -914,14 +910,14 @@ class Table implements Stringable $whereParts = []; foreach ($whereFields as $where => $value) { $whereParts[] = Util::backquote($where) . ' = \'' - . $dbi->escapeString((string) $value) . '\''; + . $GLOBALS['dbi']->escapeString((string) $value) . '\''; } $newParts = []; $newValueParts = []; foreach ($newFields as $where => $value) { $newParts[] = Util::backquote($where); - $newValueParts[] = $dbi->escapeString((string) $value); + $newValueParts[] = $GLOBALS['dbi']->escapeString((string) $value); } $tableCopyQuery = ' @@ -932,7 +928,7 @@ class Table implements Stringable // must use DatabaseInterface::QUERY_BUFFERED here, since we execute // another query inside the loop - $tableCopyRs = $dbi->queryAsControlUser($tableCopyQuery); + $tableCopyRs = $GLOBALS['dbi']->queryAsControlUser($tableCopyQuery); foreach ($tableCopyRs as $tableCopyRow) { $valueParts = []; @@ -941,7 +937,7 @@ class Table implements Stringable continue; } - $valueParts[] = $dbi->escapeString($val); + $valueParts[] = $GLOBALS['dbi']->escapeString($val); } $newTableQuery = 'INSERT IGNORE INTO ' @@ -952,8 +948,8 @@ class Table implements Stringable . implode('\', \'', $valueParts) . '\', \'' . implode('\', \'', $newValueParts) . '\')'; - $dbi->queryAsControlUser($newTableQuery); - $lastId = $dbi->insertId(); + $GLOBALS['dbi']->queryAsControlUser($newTableQuery); + $lastId = $GLOBALS['dbi']->insertId(); } return $lastId; @@ -980,9 +976,7 @@ class Table implements Stringable $mode, bool $addDropIfExists ): bool { - global $errorUrl, $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); // Try moving the tables directly, using native `RENAME` statement. if ($move && $what === 'data') { @@ -1037,7 +1031,7 @@ class Table implements Stringable // Selecting the database could avoid some problems with replicated // databases, when moving table from replicated one to not replicated one. - $dbi->selectDb($targetDb); + $GLOBALS['dbi']->selectDb($targetDb); /** * The full name of target table, quoted. @@ -1069,7 +1063,14 @@ class Table implements Stringable /** * The old structure of the table.. */ - $sqlStructure = $exportSqlPlugin->getTableDef($sourceDb, $sourceTable, "\n", $errorUrl, false, false); + $sqlStructure = $exportSqlPlugin->getTableDef( + $sourceDb, + $sourceTable, + "\n", + $GLOBALS['errorUrl'], + false, + false + ); unset($noConstraintsComments); @@ -1084,7 +1085,7 @@ class Table implements Stringable // Find server's SQL mode so the builder can generate correct // queries. // One of the options that alters the behaviour is `ANSI_QUOTES`. - Context::setMode((string) $dbi->fetchValue('SELECT @@sql_mode')); + Context::setMode((string) $GLOBALS['dbi']->fetchValue('SELECT @@sql_mode')); // ----------------------------------------------------------------- // Phase 1: Dropping existent element of the same name (if exists @@ -1111,7 +1112,7 @@ class Table implements Stringable $dropQuery = $statement->build() . ';'; // Executing it. - $dbi->query($dropQuery); + $GLOBALS['dbi']->query($dropQuery); $GLOBALS['sql_query'] .= "\n" . $dropQuery; // If an existing table gets deleted, maintain any entries for @@ -1145,11 +1146,11 @@ class Table implements Stringable // This is to avoid some issues when renaming databases with views // See: https://github.com/phpmyadmin/phpmyadmin/issues/16422 if ($move) { - $dbi->selectDb($targetDb); + $GLOBALS['dbi']->selectDb($targetDb); } // Executing it - $dbi->query($sqlStructure); + $GLOBALS['dbi']->query($sqlStructure); $GLOBALS['sql_query'] .= "\n" . $sqlStructure; } @@ -1185,7 +1186,7 @@ class Table implements Stringable // Executing it. if ($mode === 'one_table') { - $dbi->query($GLOBALS['sql_constraints_query']); + $GLOBALS['dbi']->query($GLOBALS['sql_constraints_query']); } $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query']; @@ -1226,7 +1227,7 @@ class Table implements Stringable // Executing it. if ($mode === 'one_table' || $mode === 'db_copy') { - $dbi->query($sqlIndex); + $GLOBALS['dbi']->query($sqlIndex); } $GLOBALS['sql_indexes'] .= $sqlIndex; @@ -1256,7 +1257,7 @@ class Table implements Stringable $GLOBALS['sql_auto_increments'] = $statement->build() . ';'; // Executing it. - $dbi->query($GLOBALS['sql_auto_increments']); + $GLOBALS['dbi']->query($GLOBALS['sql_auto_increments']); $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_auto_increments']; } @@ -1270,7 +1271,7 @@ class Table implements Stringable // Copy the data unless this is a VIEW if (($what === 'data' || $what === 'dataonly') && ! $table->isView()) { $sqlSetMode = "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'"; - $dbi->query($sqlSetMode); + $GLOBALS['dbi']->query($sqlSetMode); $GLOBALS['sql_query'] .= "\n\n" . $sqlSetMode . ';'; $oldTable = new Table($sourceTable, $sourceDb); @@ -1281,7 +1282,7 @@ class Table implements Stringable . ') SELECT ' . implode(', ', $nonGeneratedCols) . ' FROM ' . $source; - $dbi->query($sqlInsertData); + $GLOBALS['dbi']->query($sqlInsertData); $GLOBALS['sql_query'] .= "\n\n" . $sqlInsertData . ';'; } } @@ -1292,7 +1293,7 @@ class Table implements Stringable if ($move) { // This could avoid some problems with replicated databases, when // moving table from replicated one to not replicated one - $dbi->selectDb($sourceDb); + $GLOBALS['dbi']->selectDb($sourceDb); $sourceTableObj = new Table($sourceTable, $sourceDb); if ($sourceTableObj->isView()) { @@ -1302,7 +1303,7 @@ class Table implements Stringable } $sqlDropQuery .= ' ' . $source; - $dbi->query($sqlDropQuery); + $GLOBALS['dbi']->query($sqlDropQuery); // Rename table in configuration storage $relation->renameTable($sourceDb, $targetDb, $sourceTable, $targetTable); @@ -1320,7 +1321,7 @@ class Table implements Stringable if ($relationParameters->columnCommentsFeature !== null) { // Get all comments and MIME-Types for current table - $commentsCopyRs = $dbi->queryAsControlUser( + $commentsCopyRs = $GLOBALS['dbi']->queryAsControlUser( 'SELECT column_name, comment' . ($relationParameters->browserTransformationFeature !== null ? ', mimetype, transformation, transformation_options' @@ -1331,10 +1332,10 @@ class Table implements Stringable . Util::backquote($relationParameters->columnCommentsFeature->columnInfo) . ' WHERE ' . ' db_name = \'' - . $dbi->escapeString($sourceDb) . '\'' + . $GLOBALS['dbi']->escapeString($sourceDb) . '\'' . ' AND ' . ' table_name = \'' - . $dbi->escapeString((string) $sourceTable) . '\'' + . $GLOBALS['dbi']->escapeString((string) $sourceTable) . '\'' ); // Write every comment as new copied entry. [MIME] @@ -1346,20 +1347,20 @@ class Table implements Stringable . ($relationParameters->browserTransformationFeature !== null ? ', mimetype, transformation, transformation_options' : '') - . ') VALUES(\'' . $dbi->escapeString($targetDb) - . '\',\'' . $dbi->escapeString($targetTable) . '\',\'' - . $dbi->escapeString($commentsCopyRow['column_name']) + . ') VALUES(\'' . $GLOBALS['dbi']->escapeString($targetDb) + . '\',\'' . $GLOBALS['dbi']->escapeString($targetTable) . '\',\'' + . $GLOBALS['dbi']->escapeString($commentsCopyRow['column_name']) . '\',\'' - . $dbi->escapeString($commentsCopyRow['comment']) + . $GLOBALS['dbi']->escapeString($commentsCopyRow['comment']) . '\'' . ($relationParameters->browserTransformationFeature !== null - ? ',\'' . $dbi->escapeString($commentsCopyRow['mimetype']) - . '\',\'' . $dbi->escapeString($commentsCopyRow['transformation']) - . '\',\'' . $dbi->escapeString($commentsCopyRow['transformation_options']) + ? ',\'' . $GLOBALS['dbi']->escapeString($commentsCopyRow['mimetype']) + . '\',\'' . $GLOBALS['dbi']->escapeString($commentsCopyRow['transformation']) + . '\',\'' . $GLOBALS['dbi']->escapeString($commentsCopyRow['transformation_options']) . '\'' : '') . ')'; - $dbi->queryAsControlUser($newCommentQuery); + $GLOBALS['dbi']->queryAsControlUser($newCommentQuery); } unset($commentsCopyRs); diff --git a/libraries/classes/Table/ColumnsDefinition.php b/libraries/classes/Table/ColumnsDefinition.php index 869e55e295..ca9002fd89 100644 --- a/libraries/classes/Table/ColumnsDefinition.php +++ b/libraries/classes/Table/ColumnsDefinition.php @@ -68,8 +68,6 @@ final class ColumnsDefinition ?array $selected = null, $fields_meta = null ): array { - global $db, $table, $cfg, $col_priv, $is_reload_priv, $mime_map; - Util::checkParameters([ 'server', 'db', @@ -79,7 +77,7 @@ final class ColumnsDefinition $length_values_input_size = 8; $content_cells = []; - $form_params = ['db' => $db]; + $form_params = ['db' => $GLOBALS['db']]; if ($action === '/table/create') { $form_params['reload'] = 1; @@ -96,7 +94,7 @@ final class ColumnsDefinition } } - $form_params['table'] = $table; + $form_params['table'] = $GLOBALS['table']; } $form_params['orig_num_fields'] = $num_fields; @@ -119,16 +117,16 @@ final class ColumnsDefinition $relationParameters = $this->relation->getRelationParameters(); - $comments_map = $this->relation->getComments($db, $table); + $comments_map = $this->relation->getComments($GLOBALS['db'], $GLOBALS['table']); $move_columns = []; if (isset($fields_meta)) { - $move_columns = $this->dbi->getTable($db, $table)->getColumnsMeta(); + $move_columns = $this->dbi->getTable($GLOBALS['db'], $GLOBALS['table'])->getColumnsMeta(); } $available_mime = []; - if ($relationParameters->browserTransformationFeature !== null && $cfg['BrowseMIME']) { - $mime_map = $this->transformations->getMime($db, $table); + if ($relationParameters->browserTransformationFeature !== null && $GLOBALS['cfg']['BrowseMIME']) { + $GLOBALS['mime_map'] = $this->transformations->getMime($GLOBALS['db'], $GLOBALS['table']); $available_mime = $this->transformations->getAvailableMimeTypes(); } @@ -154,12 +152,12 @@ final class ColumnsDefinition $regenerate = 1; } - $foreigners = $this->relation->getForeigners($db, $table, '', 'foreign'); + $foreigners = $this->relation->getForeigners($GLOBALS['db'], $GLOBALS['table'], '', 'foreign'); $child_references = null; // From MySQL 5.6.6 onwards columns with foreign keys can be renamed. // Hence, no need to get child references if ($this->dbi->getVersion() < 50606) { - $child_references = $this->relation->getChildReferences($db, $table); + $child_references = $this->relation->getChildReferences($GLOBALS['db'], $GLOBALS['table']); } for ($columnNumber = 0; $columnNumber < $num_fields; $columnNumber++) { @@ -261,8 +259,8 @@ final class ColumnsDefinition $submit_attribute = Util::getValueByKey($_POST, "field_attribute.${columnNumber}", false); $comments_map[$columnMeta['Field']] = Util::getValueByKey($_POST, "field_comments.${columnNumber}"); - $mime_map[$columnMeta['Field']] = array_merge( - $mime_map[$columnMeta['Field']] ?? [], + $GLOBALS['mime_map'][$columnMeta['Field']] = array_merge( + $GLOBALS['mime_map'][$columnMeta['Field']] ?? [], [ 'mimetype' => Util::getValueByKey($_POST, "field_mimetype.${columnNumber}"), 'transformation' => Util::getValueByKey( @@ -284,7 +282,7 @@ final class ColumnsDefinition 'STORED GENERATED', ]; if (in_array($columnMeta['Extra'], $virtual)) { - $tableObj = new Table($table, $db); + $tableObj = new Table($GLOBALS['table'], $GLOBALS['db']); $expressions = $tableObj->getColumnGenerationExpression($columnMeta['Field']); $columnMeta['Expression'] = is_array($expressions) ? $expressions[$columnMeta['Field']] : null; } @@ -465,14 +463,14 @@ final class ColumnsDefinition 'is_backup' => $is_backup, 'move_columns' => $move_columns, 'available_mime' => $available_mime, - 'mime_map' => $mime_map ?? [], + 'mime_map' => $GLOBALS['mime_map'] ?? [], ]; } $partitionDetails = TablePartitionDefinition::getDetails(); - $charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']); - $collations = Charsets::getCollations($this->dbi, $cfg['Server']['DisableIS']); + $charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); + $collations = Charsets::getCollations($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']); $charsetsList = []; foreach ($charsets as $charset) { $collationsList = []; @@ -516,19 +514,19 @@ final class ColumnsDefinition 'change_column' => $_POST['change_column'] ?? $_GET['change_column'] ?? null, 'is_virtual_columns_supported' => Compatibility::isVirtualColumnsSupported($this->dbi->getVersion()), 'is_integers_length_restricted' => $isIntegersLengthRestricted, - 'browse_mime' => $cfg['BrowseMIME'] ?? null, + 'browse_mime' => $GLOBALS['cfg']['BrowseMIME'] ?? null, 'supports_stored_keyword' => Compatibility::supportsStoredKeywordForVirtualColumns( $this->dbi->getVersion() ), 'server_version' => $this->dbi->getVersion(), - 'max_rows' => intval($cfg['MaxRows']), - 'char_editing' => $cfg['CharEditing'] ?? null, + 'max_rows' => intval($GLOBALS['cfg']['MaxRows']), + 'char_editing' => $GLOBALS['cfg']['CharEditing'] ?? null, 'attribute_types' => $this->dbi->types->getAttributes(), - 'privs_available' => ($col_priv ?? false) && ($is_reload_priv ?? false), + 'privs_available' => ($GLOBALS['col_priv'] ?? false) && ($GLOBALS['is_reload_priv'] ?? false), 'max_length' => $this->dbi->getVersion() >= 50503 ? 1024 : 255, 'have_partitioning' => Partition::havePartitioning(), 'dbi' => $this->dbi, - 'disable_is' => $cfg['Server']['DisableIS'], + 'disable_is' => $GLOBALS['cfg']['Server']['DisableIS'], ]; } } diff --git a/libraries/classes/Table/Indexes.php b/libraries/classes/Table/Indexes.php index 96f0857ee8..343e95f795 100644 --- a/libraries/classes/Table/Indexes.php +++ b/libraries/classes/Table/Indexes.php @@ -44,8 +44,6 @@ final class Indexes */ public function doSaveData(Index $index, bool $renameMode, string $db, string $table): void { - global $containerBuilder; - $error = false; if ($renameMode && Compatibility::isCompatibleRenameIndex($this->dbi->getVersion())) { $oldIndexName = $_POST['old_index']; @@ -106,7 +104,7 @@ final class Indexes ); } else { /** @var StructureController $controller */ - $controller = $containerBuilder->get(StructureController::class); + $controller = $GLOBALS['containerBuilder']->get(StructureController::class); $controller(); } } else { diff --git a/libraries/classes/Template.php b/libraries/classes/Template.php index b638cdd0cd..c741fa0b80 100644 --- a/libraries/classes/Template.php +++ b/libraries/classes/Template.php @@ -64,8 +64,6 @@ class Template public static function getTwigEnvironment(?string $cacheDir): Environment { - global $cfg, $containerBuilder; - /* Twig expects false when cache is not configured */ if ($cacheDir === null) { $cacheDir = false; @@ -77,9 +75,9 @@ class Template 'cache' => $cacheDir, ]); - $twig->addRuntimeLoader(new ContainerRuntimeLoader($containerBuilder)); + $twig->addRuntimeLoader(new ContainerRuntimeLoader($GLOBALS['containerBuilder'])); - if (is_array($cfg) && ($cfg['environment'] ?? '') === 'development') { + if (is_array($GLOBALS['cfg']) && ($GLOBALS['cfg']['environment'] ?? '') === 'development') { $twig->enableDebug(); $twig->addExtension(new DebugExtension()); // This will enable debug for the extension to print lines @@ -87,7 +85,7 @@ class Template TransNode::$enableAddDebugInfo = true; } - if ($cfg['environment'] === 'production') { + if ($GLOBALS['cfg']['environment'] === 'production') { $twig->disableDebug(); TransNode::$enableAddDebugInfo = false; } diff --git a/libraries/classes/ThemeManager.php b/libraries/classes/ThemeManager.php index 9c10859f21..b41b1ec59c 100644 --- a/libraries/classes/ThemeManager.php +++ b/libraries/classes/ThemeManager.php @@ -179,11 +179,9 @@ class ThemeManager */ public function getThemeCookie() { - global $config; - $name = $this->getThemeCookieName(); - if ($config->issetCookie($name)) { - return $config->getCookie($name); + if ($GLOBALS['config']->issetCookie($name)) { + return $GLOBALS['config']->getCookie($name); } return false; diff --git a/libraries/classes/Tracker.php b/libraries/classes/Tracker.php index fb97c6de32..3a64ec7587 100644 --- a/libraries/classes/Tracker.php +++ b/libraries/classes/Tracker.php @@ -69,8 +69,6 @@ class Tracker */ public static function isActive(): bool { - global $dbi; - $trackingEnabled = Cache::get(self::TRACKER_ENABLED_CACHE_KEY, false); if (! $trackingEnabled) { return false; @@ -80,7 +78,7 @@ class Tracker * We need to avoid attempt to track any queries from {@link Relation::getRelationParameters()} */ Cache::set(self::TRACKER_ENABLED_CACHE_KEY, false); - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $relationParameters = $relation->getRelationParameters(); /* Restore original state */ Cache::set(self::TRACKER_ENABLED_CACHE_KEY, true); @@ -125,8 +123,6 @@ class Tracker */ public static function isTracked($dbName, $tableName): bool { - global $dbi; - $trackingEnabled = Cache::get(self::TRACKER_ENABLED_CACHE_KEY, false); if (! $trackingEnabled) { return false; @@ -140,7 +136,7 @@ class Tracker * We need to avoid attempt to track any queries from {@link Relation::getRelationParameters()} */ Cache::set(self::TRACKER_ENABLED_CACHE_KEY, false); - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $trackingFeature = $relation->getRelationParameters()->trackingFeature; /* Restore original state */ Cache::set(self::TRACKER_ENABLED_CACHE_KEY, true); @@ -153,11 +149,11 @@ class Tracker . ' ORDER BY version DESC LIMIT 1', Util::backquote($trackingFeature->database), Util::backquote($trackingFeature->tracking), - $dbi->escapeString($dbName), - $dbi->escapeString($tableName) + $GLOBALS['dbi']->escapeString($dbName), + $GLOBALS['dbi']->escapeString($tableName) ); - $result = $dbi->fetchValue($sqlQuery, 0, DatabaseInterface::CONNECT_CONTROL) == 1; + $result = $GLOBALS['dbi']->fetchValue($sqlQuery, 0, DatabaseInterface::CONNECT_CONTROL) == 1; self::$trackingCache[$dbName][$tableName] = $result; @@ -196,29 +192,27 @@ class Tracker $trackingSet = '', bool $isView = false ): bool { - global $sql_backquotes, $export_type, $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); if ($trackingSet == '') { $trackingSet = $GLOBALS['cfg']['Server']['tracking_default_statements']; } $exportSqlPlugin = Plugins::getPlugin('export', 'sql', [ - 'export_type' => (string) $export_type, + 'export_type' => (string) $GLOBALS['export_type'], 'single_table' => false, ]); if (! $exportSqlPlugin instanceof ExportSql) { return false; } - $sql_backquotes = true; + $GLOBALS['sql_backquotes'] = true; $date = Util::date('Y-m-d H:i:s'); // Get data definition snapshot of table - $columns = $dbi->getColumns($dbName, $tableName, true); + $columns = $GLOBALS['dbi']->getColumns($dbName, $tableName, true); // int indices to reduce size $columns = array_values($columns); // remove Privileges to reduce size @@ -226,7 +220,7 @@ class Tracker unset($columns[$i]['Privileges']); } - $indexes = $dbi->getTableIndexes($dbName, $tableName); + $indexes = $GLOBALS['dbi']->getTableIndexes($dbName, $tableName); $snapshot = [ 'COLUMNS' => $columns, @@ -235,7 +229,7 @@ class Tracker $snapshot = serialize($snapshot); // Get DROP TABLE / DROP VIEW and CREATE TABLE SQL statements - $sql_backquotes = true; + $GLOBALS['sql_backquotes'] = true; $createSql = ''; @@ -264,18 +258,18 @@ class Tracker . ' values (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\')', Util::backquote($trackingFeature->database), Util::backquote($trackingFeature->tracking), - $dbi->escapeString($dbName), - $dbi->escapeString($tableName), - $dbi->escapeString($version), - $dbi->escapeString($date), - $dbi->escapeString($date), - $dbi->escapeString($snapshot), - $dbi->escapeString($createSql), - $dbi->escapeString("\n"), - $dbi->escapeString($trackingSet) + $GLOBALS['dbi']->escapeString($dbName), + $GLOBALS['dbi']->escapeString($tableName), + $GLOBALS['dbi']->escapeString($version), + $GLOBALS['dbi']->escapeString($date), + $GLOBALS['dbi']->escapeString($date), + $GLOBALS['dbi']->escapeString($snapshot), + $GLOBALS['dbi']->escapeString($createSql), + $GLOBALS['dbi']->escapeString("\n"), + $GLOBALS['dbi']->escapeString($trackingSet) ); - $dbi->queryAsControlUser($sqlQuery); + $GLOBALS['dbi']->queryAsControlUser($sqlQuery); // Deactivate previous version return self::deactivateTracking($dbName, $tableName, (int) $version - 1); @@ -290,9 +284,7 @@ class Tracker */ public static function deleteTracking($dbName, $tableName, $version = ''): bool { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $trackingFeature = $relation->getRelationParameters()->trackingFeature; if ($trackingFeature === null) { return false; @@ -302,14 +294,14 @@ class Tracker '/*NOTRACK*/' . "\n" . 'DELETE FROM %s.%s WHERE `db_name` = \'%s\' AND `table_name` = \'%s\'', Util::backquote($trackingFeature->database), Util::backquote($trackingFeature->tracking), - $dbi->escapeString($dbName), - $dbi->escapeString($tableName) + $GLOBALS['dbi']->escapeString($dbName), + $GLOBALS['dbi']->escapeString($tableName) ); if ($version) { - $sqlQuery .= " AND `version` = '" . $dbi->escapeString($version) . "'"; + $sqlQuery .= " AND `version` = '" . $GLOBALS['dbi']->escapeString($version) . "'"; } - return (bool) $dbi->queryAsControlUser($sqlQuery); + return (bool) $GLOBALS['dbi']->queryAsControlUser($sqlQuery); } /** @@ -327,9 +319,7 @@ class Tracker $query, $trackingSet = 'CREATE DATABASE,ALTER DATABASE,DROP DATABASE' ): bool { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $date = Util::date('Y-m-d H:i:s'); @@ -357,18 +347,18 @@ class Tracker . ' values (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\')', Util::backquote($trackingFeature->database), Util::backquote($trackingFeature->tracking), - $dbi->escapeString($dbName), - $dbi->escapeString(''), - $dbi->escapeString($version), - $dbi->escapeString($date), - $dbi->escapeString($date), - $dbi->escapeString(''), - $dbi->escapeString($createSql), - $dbi->escapeString("\n"), - $dbi->escapeString($trackingSet) + $GLOBALS['dbi']->escapeString($dbName), + $GLOBALS['dbi']->escapeString(''), + $GLOBALS['dbi']->escapeString($version), + $GLOBALS['dbi']->escapeString($date), + $GLOBALS['dbi']->escapeString($date), + $GLOBALS['dbi']->escapeString(''), + $GLOBALS['dbi']->escapeString($createSql), + $GLOBALS['dbi']->escapeString("\n"), + $GLOBALS['dbi']->escapeString($trackingSet) ); - return (bool) $dbi->queryAsControlUser($sqlQuery); + return (bool) $GLOBALS['dbi']->queryAsControlUser($sqlQuery); } /** @@ -385,9 +375,7 @@ class Tracker $version, $newState ): bool { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $trackingFeature = $relation->getRelationParameters()->trackingFeature; if ($trackingFeature === null) { return false; @@ -399,12 +387,12 @@ class Tracker Util::backquote($trackingFeature->database), Util::backquote($trackingFeature->tracking), $newState, - $dbi->escapeString($dbName), - $dbi->escapeString($tableName), - $dbi->escapeString((string) $version) + $GLOBALS['dbi']->escapeString($dbName), + $GLOBALS['dbi']->escapeString($tableName), + $GLOBALS['dbi']->escapeString((string) $version) ); - return (bool) $dbi->queryAsControlUser($sqlQuery); + return (bool) $GLOBALS['dbi']->queryAsControlUser($sqlQuery); } /** @@ -425,9 +413,7 @@ class Tracker $type, $newData ): bool { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); if ($type === 'DDL') { $saveTo = 'schema_sql'; @@ -443,7 +429,7 @@ class Tracker if (is_array($newData)) { foreach ($newData as $data) { $newDataProcessed .= '# log ' . $date . ' ' . $data['username'] - . $dbi->escapeString($data['statement']) . "\n"; + . $GLOBALS['dbi']->escapeString($data['statement']) . "\n"; } } else { $newDataProcessed = $newData; @@ -460,12 +446,12 @@ class Tracker Util::backquote($trackingFeature->tracking), $saveTo, $newDataProcessed, - $dbi->escapeString($dbName), - $dbi->escapeString($tableName), - $dbi->escapeString($version) + $GLOBALS['dbi']->escapeString($dbName), + $GLOBALS['dbi']->escapeString($tableName), + $GLOBALS['dbi']->escapeString($version) ); - $result = $dbi->queryAsControlUser($sqlQuery); + $result = $GLOBALS['dbi']->queryAsControlUser($sqlQuery); return (bool) $result; } @@ -508,9 +494,7 @@ class Tracker */ public static function getVersion(string $dbname, string $tablename, ?string $statement = null) { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $trackingFeature = $relation->getRelationParameters()->trackingFeature; if ($trackingFeature === null) { return -1; @@ -520,15 +504,15 @@ class Tracker 'SELECT MAX(version) FROM %s.%s WHERE `db_name` = \'%s\' AND `table_name` = \'%s\'', Util::backquote($trackingFeature->database), Util::backquote($trackingFeature->tracking), - $dbi->escapeString($dbname), - $dbi->escapeString($tablename) + $GLOBALS['dbi']->escapeString($dbname), + $GLOBALS['dbi']->escapeString($tablename) ); if ($statement != '') { $sqlQuery .= " AND FIND_IN_SET('" . $statement . "',tracking) > 0"; } - $result = $dbi->tryQueryAsControlUser($sqlQuery); + $result = $GLOBALS['dbi']->tryQueryAsControlUser($sqlQuery); if ($result === false) { return -1; @@ -553,9 +537,7 @@ class Tracker */ public static function getTrackedData($dbname, $tablename, $version) { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $trackingFeature = $relation->getRelationParameters()->trackingFeature; if ($trackingFeature === null) { return []; @@ -565,17 +547,17 @@ class Tracker 'SELECT * FROM %s.%s WHERE `db_name` = \'%s\'', Util::backquote($trackingFeature->database), Util::backquote($trackingFeature->tracking), - $dbi->escapeString($dbname) + $GLOBALS['dbi']->escapeString($dbname) ); if (! empty($tablename)) { $sqlQuery .= " AND `table_name` = '" - . $dbi->escapeString($tablename) . "' "; + . $GLOBALS['dbi']->escapeString($tablename) . "' "; } - $sqlQuery .= " AND `version` = '" . $dbi->escapeString($version) + $sqlQuery .= " AND `version` = '" . $GLOBALS['dbi']->escapeString($version) . "' ORDER BY `version` DESC LIMIT 1"; - $mixed = $dbi->queryAsControlUser($sqlQuery)->fetchAssoc(); + $mixed = $GLOBALS['dbi']->queryAsControlUser($sqlQuery)->fetchAssoc(); // PHP 7.4 fix for accessing array offset on null if ($mixed === []) { @@ -834,9 +816,7 @@ class Tracker */ public static function handleQuery($query): void { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); // If query is marked as untouchable, leave if (mb_strstr($query, '/*NOTRACK*/')) { @@ -929,7 +909,7 @@ class Tracker Util::backquote($trackingFeature->tracking), Util::backquote($saveTo), Util::backquote($saveTo), - $dbi->escapeString($query), + $GLOBALS['dbi']->escapeString($query), $date ); @@ -937,7 +917,7 @@ class Tracker // the tablename attribute in pma_tracking too if ($result['identifier'] === 'RENAME TABLE') { $sqlQuery .= ', `table_name` = \'' - . $dbi->escapeString($result['tablename_after_rename']) + . $GLOBALS['dbi']->escapeString($result['tablename_after_rename']) . '\' '; } @@ -947,11 +927,11 @@ class Tracker // 3. the statements // we want to track $sqlQuery .= " WHERE FIND_IN_SET('" . $result['identifier'] . "',tracking) > 0" . - " AND `db_name` = '" . $dbi->escapeString($dbname ?? '') . "' " . + " AND `db_name` = '" . $GLOBALS['dbi']->escapeString($dbname ?? '') . "' " . " AND `table_name` = '" - . $dbi->escapeString($result['tablename']) . "' " . - " AND `version` = '" . $dbi->escapeString((string) $version) . "' "; + . $GLOBALS['dbi']->escapeString($result['tablename']) . "' " . + " AND `version` = '" . $GLOBALS['dbi']->escapeString((string) $version) . "' "; - $dbi->queryAsControlUser($sqlQuery); + $GLOBALS['dbi']->queryAsControlUser($sqlQuery); } } diff --git a/libraries/classes/Tracking.php b/libraries/classes/Tracking.php index 8c5c6fa209..36d2f36700 100644 --- a/libraries/classes/Tracking.php +++ b/libraries/classes/Tracking.php @@ -138,8 +138,6 @@ class Tracking $textDir, $lastVersion = null ) { - global $cfg; - $selectableTablesSqlResult = $this->getSqlResultForSelectableTables($db); $selectableTablesEntries = []; $selectableTablesNumRows = 0; @@ -174,7 +172,7 @@ class Tracking 'last_version' => $lastVersion, 'versions' => $versions, 'type' => $type, - 'default_statements' => $cfg['Server']['tracking_default_statements'], + 'default_statements' => $GLOBALS['cfg']['Server']['tracking_default_statements'], 'text_dir' => $textDir, ]); } @@ -1160,10 +1158,8 @@ class Tracking */ public function extractTableNames(array $table_list, $db, $testing = false) { - global $cfg; - $untracked_tables = []; - $sep = $cfg['NavigationTreeTableSeparator']; + $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator']; foreach ($table_list as $value) { if (is_array($value) && array_key_exists('is' . $sep . 'group', $value) && $value['is' . $sep . 'group']) { diff --git a/libraries/classes/Transformations.php b/libraries/classes/Transformations.php index 81df453a03..acde44396c 100644 --- a/libraries/classes/Transformations.php +++ b/libraries/classes/Transformations.php @@ -282,9 +282,7 @@ class Transformations */ public function getMime($db, $table, $strict = false, $fullName = false) { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $browserTransformationFeature = $relation->getRelationParameters()->browserTransformationFeature; if ($browserTransformationFeature === null) { return null; @@ -304,14 +302,14 @@ class Transformations . '`input_transformation_options`' . ' FROM ' . Util::backquote($browserTransformationFeature->database) . '.' . Util::backquote($browserTransformationFeature->columnInfo) - . ' WHERE `db_name` = \'' . $dbi->escapeString($db) . '\'' - . ' AND `table_name` = \'' . $dbi->escapeString($table) . '\'' + . ' WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db) . '\'' + . ' AND `table_name` = \'' . $GLOBALS['dbi']->escapeString($table) . '\'' . ' AND ( `mimetype` != \'\'' . (! $strict ? ' OR `transformation` != \'\'' . ' OR `transformation_options` != \'\'' . ' OR `input_transformation` != \'\'' . ' OR `input_transformation_options` != \'\'' : '') . ')'; - $result = $dbi->fetchResult($com_qry, 'column_name', null, DatabaseInterface::CONNECT_CONTROL); + $result = $GLOBALS['dbi']->fetchResult($com_qry, 'column_name', null, DatabaseInterface::CONNECT_CONTROL); foreach ($result as $column => $values) { // convert mimetype to new format (f.e. Text_Plain, etc) @@ -360,9 +358,7 @@ class Transformations $inputTransformOpts, $forcedelete = false ): bool { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $browserTransformationFeature = $relation->getRelationParameters()->browserTransformationFeature; if ($browserTransformationFeature === null) { return false; @@ -386,11 +382,11 @@ class Transformations `comment` FROM ' . Util::backquote($browserTransformationFeature->database) . '.' . Util::backquote($browserTransformationFeature->columnInfo) . ' - WHERE `db_name` = \'' . $dbi->escapeString($db) . '\' - AND `table_name` = \'' . $dbi->escapeString($table) . '\' - AND `column_name` = \'' . $dbi->escapeString($key) . '\''; + WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db) . '\' + AND `table_name` = \'' . $GLOBALS['dbi']->escapeString($table) . '\' + AND `column_name` = \'' . $GLOBALS['dbi']->escapeString($key) . '\''; - $test_rs = $dbi->queryAsControlUser($test_qry); + $test_rs = $GLOBALS['dbi']->queryAsControlUser($test_qry); if ($test_rs->numRows() > 0) { $row = $test_rs->fetchAssoc(); @@ -401,15 +397,15 @@ class Transformations . Util::backquote($browserTransformationFeature->columnInfo) . ' SET ' . '`mimetype` = \'' - . $dbi->escapeString($mimetype) . '\', ' + . $GLOBALS['dbi']->escapeString($mimetype) . '\', ' . '`transformation` = \'' - . $dbi->escapeString($transformation) . '\', ' + . $GLOBALS['dbi']->escapeString($transformation) . '\', ' . '`transformation_options` = \'' - . $dbi->escapeString($transformationOpts) . '\', ' + . $GLOBALS['dbi']->escapeString($transformationOpts) . '\', ' . '`input_transformation` = \'' - . $dbi->escapeString($inputTransform) . '\', ' + . $GLOBALS['dbi']->escapeString($inputTransform) . '\', ' . '`input_transformation_options` = \'' - . $dbi->escapeString($inputTransformOpts) . '\''; + . $GLOBALS['dbi']->escapeString($inputTransformOpts) . '\''; } else { $upd_query = 'DELETE FROM ' . Util::backquote($browserTransformationFeature->database) @@ -417,10 +413,10 @@ class Transformations } $upd_query .= ' - WHERE `db_name` = \'' . $dbi->escapeString($db) . '\' - AND `table_name` = \'' . $dbi->escapeString($table) + WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db) . '\' + AND `table_name` = \'' . $GLOBALS['dbi']->escapeString($table) . '\' - AND `column_name` = \'' . $dbi->escapeString($key) + AND `column_name` = \'' . $GLOBALS['dbi']->escapeString($key) . '\''; } elseif ($has_value) { $upd_query = 'INSERT INTO ' @@ -430,18 +426,18 @@ class Transformations . 'transformation, transformation_options, ' . 'input_transformation, input_transformation_options) ' . ' VALUES(' - . '\'' . $dbi->escapeString($db) . '\',' - . '\'' . $dbi->escapeString($table) . '\',' - . '\'' . $dbi->escapeString($key) . '\',' - . '\'' . $dbi->escapeString($mimetype) . '\',' - . '\'' . $dbi->escapeString($transformation) . '\',' - . '\'' . $dbi->escapeString($transformationOpts) . '\',' - . '\'' . $dbi->escapeString($inputTransform) . '\',' - . '\'' . $dbi->escapeString($inputTransformOpts) . '\')'; + . '\'' . $GLOBALS['dbi']->escapeString($db) . '\',' + . '\'' . $GLOBALS['dbi']->escapeString($table) . '\',' + . '\'' . $GLOBALS['dbi']->escapeString($key) . '\',' + . '\'' . $GLOBALS['dbi']->escapeString($mimetype) . '\',' + . '\'' . $GLOBALS['dbi']->escapeString($transformation) . '\',' + . '\'' . $GLOBALS['dbi']->escapeString($transformationOpts) . '\',' + . '\'' . $GLOBALS['dbi']->escapeString($inputTransform) . '\',' + . '\'' . $GLOBALS['dbi']->escapeString($inputTransformOpts) . '\')'; } if (isset($upd_query)) { - return (bool) $dbi->queryAsControlUser($upd_query); + return (bool) $GLOBALS['dbi']->queryAsControlUser($upd_query); } return false; @@ -461,9 +457,7 @@ class Transformations */ public function clear($db, $table = '', $column = ''): bool { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); $browserTransformationFeature = $relation->getRelationParameters()->browserTransformationFeature; if ($browserTransformationFeature === null) { return false; @@ -485,6 +479,6 @@ class Transformations $delete_sql .= '`db_name` = \'' . $db . '\' '; } - return (bool) $dbi->tryQuery($delete_sql); + return (bool) $GLOBALS['dbi']->tryQuery($delete_sql); } } diff --git a/libraries/classes/Twig/AssetExtension.php b/libraries/classes/Twig/AssetExtension.php index 5f6bbd9eb3..58995fe8a7 100644 --- a/libraries/classes/Twig/AssetExtension.php +++ b/libraries/classes/Twig/AssetExtension.php @@ -22,12 +22,10 @@ final class AssetExtension extends AbstractExtension public function getImagePath(?string $filename = null, ?string $fallback = null): string { - global $theme; - - if (! $theme instanceof Theme) { + if (! $GLOBALS['theme'] instanceof Theme) { return ''; } - return $theme->getImgPath($filename, $fallback); + return $GLOBALS['theme']->getImgPath($filename, $fallback); } } diff --git a/libraries/classes/Twig/RelationExtension.php b/libraries/classes/Twig/RelationExtension.php index 2d6e1a457a..e16678f2a2 100644 --- a/libraries/classes/Twig/RelationExtension.php +++ b/libraries/classes/Twig/RelationExtension.php @@ -17,9 +17,7 @@ class RelationExtension extends AbstractExtension */ public function getFunctions() { - global $dbi; - - $relation = new Relation($dbi); + $relation = new Relation($GLOBALS['dbi']); return [ new TwigFunction( diff --git a/libraries/classes/TwoFactor.php b/libraries/classes/TwoFactor.php index 3ebb7200b6..1aef08fcb1 100644 --- a/libraries/classes/TwoFactor.php +++ b/libraries/classes/TwoFactor.php @@ -51,9 +51,7 @@ class TwoFactor */ public function __construct($user) { - global $dbi; - - (new Relation($dbi))->initRelationParamsCache(); + (new Relation($GLOBALS['dbi']))->initRelationParamsCache(); $this->userPreferences = new UserPreferences(); $this->user = $user; diff --git a/libraries/classes/Url.php b/libraries/classes/Url.php index c6bf3f5ed1..849bb13b38 100644 --- a/libraries/classes/Url.php +++ b/libraries/classes/Url.php @@ -47,8 +47,6 @@ class Url $indent = 0, $skip = [] ) { - global $config; - if (is_array($db)) { $params =& $db; } else { @@ -66,7 +64,7 @@ class Url $params['server'] = $GLOBALS['server']; } - if (empty($config->getCookie('pma_lang')) && ! empty($GLOBALS['lang'])) { + if (empty($GLOBALS['config']->getCookie('pma_lang')) && ! empty($GLOBALS['lang'])) { $params['lang'] = $GLOBALS['lang']; } @@ -211,20 +209,20 @@ class Url */ public static function getCommonRaw(array $params = [], $divider = '?', $encrypt = true) { - global $config; - // avoid overwriting when creating navigation panel links to servers if ( isset($GLOBALS['server']) && $GLOBALS['server'] != $GLOBALS['cfg']['ServerDefault'] && ! isset($params['server']) - && ! $config->get('is_setup') + && ! $GLOBALS['config']->get('is_setup') ) { $params['server'] = $GLOBALS['server']; } // Can be null when the user is missing an extension. - if ($config !== null && empty($config->getCookie('pma_lang')) && ! empty($GLOBALS['lang'])) { + if ( + $GLOBALS['config'] !== null && empty($GLOBALS['config']->getCookie('pma_lang')) && ! empty($GLOBALS['lang']) + ) { $params['lang'] = $GLOBALS['lang']; } @@ -245,11 +243,9 @@ class Url */ public static function buildHttpQuery($params, $encrypt = true) { - global $config; - $separator = self::getArgSeparator(); - if (! $encrypt || ! $config->get('URLQueryEncryption')) { + if (! $encrypt || ! $GLOBALS['config']->get('URLQueryEncryption')) { return http_build_query($params, '', $separator); } diff --git a/libraries/classes/UrlRedirector.php b/libraries/classes/UrlRedirector.php index 86ab1270b6..fdb990a79b 100644 --- a/libraries/classes/UrlRedirector.php +++ b/libraries/classes/UrlRedirector.php @@ -19,11 +19,9 @@ final class UrlRedirector */ public static function redirect(): void { - global $containerBuilder, $dbi; - // Load database service because services.php is not available here - $dbi = DatabaseInterface::load(); - $containerBuilder->set(DatabaseInterface::class, $dbi); + $GLOBALS['dbi'] = DatabaseInterface::load(); + $GLOBALS['containerBuilder']->set(DatabaseInterface::class, $GLOBALS['dbi']); // Only output the http headers $response = ResponseRenderer::getInstance(); @@ -46,7 +44,7 @@ final class UrlRedirector * * @var Template $template */ - $template = $containerBuilder->get('template'); + $template = $GLOBALS['containerBuilder']->get('template'); echo $template->render('javascript/redirect', [ 'url' => Sanitize::escapeJsString((string) $_GET['url']), ]); diff --git a/libraries/classes/UserPassword.php b/libraries/classes/UserPassword.php index 2e0173f78a..8d54fbb8fc 100644 --- a/libraries/classes/UserPassword.php +++ b/libraries/classes/UserPassword.php @@ -65,13 +65,11 @@ class UserPassword */ public function changePassword($password): string { - global $auth_plugin, $dbi; - $hashing_function = $this->changePassHashingFunction(); - [$username, $hostname] = $dbi->getCurrentUserAndHost(); + [$username, $hostname] = $GLOBALS['dbi']->getCurrentUserAndHost(); - $serverVersion = $dbi->getVersion(); + $serverVersion = $GLOBALS['dbi']->getVersion(); if (isset($_POST['authentication_plugin']) && ! empty($_POST['authentication_plugin'])) { $orig_auth_plugin = $_POST['authentication_plugin']; @@ -84,8 +82,8 @@ class UserPassword $isPerconaOrMySql = Compatibility::isMySqlOrPerconaDb(); if ($isPerconaOrMySql && $serverVersion >= 50706) { - $sql_query = 'ALTER USER \'' . $dbi->escapeString($username) - . '\'@\'' . $dbi->escapeString($hostname) + $sql_query = 'ALTER USER \'' . $GLOBALS['dbi']->escapeString($username) + . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\' IDENTIFIED WITH ' . $orig_auth_plugin . ' BY ' . ($password == '' ? '\'\'' : '\'***\''); } elseif ( @@ -102,7 +100,7 @@ class UserPassword $value = 0; } - $dbi->tryQuery('SET `old_passwords` = ' . $value . ';'); + $GLOBALS['dbi']->tryQuery('SET `old_passwords` = ' . $value . ';'); } $this->changePassUrlParamsAndSubmitQuery( @@ -114,7 +112,7 @@ class UserPassword $orig_auth_plugin ); - $auth_plugin->handlePasswordChange($password); + $GLOBALS['auth_plugin']->handlePasswordChange($password); return $sql_query; } @@ -153,19 +151,17 @@ class UserPassword $hashing_function, $orig_auth_plugin ): void { - global $dbi; - $err_url = Url::getFromRoute('/user-password'); - $serverVersion = $dbi->getVersion(); + $serverVersion = $GLOBALS['dbi']->getVersion(); if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706) { - $local_query = 'ALTER USER \'' . $dbi->escapeString($username) - . '\'@\'' . $dbi->escapeString($hostname) . '\'' + $local_query = 'ALTER USER \'' . $GLOBALS['dbi']->escapeString($username) + . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\'' . ' IDENTIFIED with ' . $orig_auth_plugin . ' BY ' . ($password == '' ? '\'\'' - : '\'' . $dbi->escapeString($password) . '\''); + : '\'' . $GLOBALS['dbi']->escapeString($password) . '\''); } elseif ( Compatibility::isMariaDb() && $serverVersion >= 50200 @@ -175,11 +171,11 @@ class UserPassword if ($orig_auth_plugin === 'mysql_native_password') { // Set the hashing method used by PASSWORD() // to be 'mysql_native_password' type - $dbi->tryQuery('SET old_passwords = 0;'); + $GLOBALS['dbi']->tryQuery('SET old_passwords = 0;'); } elseif ($orig_auth_plugin === 'sha256_password') { // Set the hashing method used by PASSWORD() // to be 'sha256_password' type - $dbi->tryQuery('SET `old_passwords` = 2;'); + $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 2;'); } $hashedPassword = $this->serverPrivileges->getHashedPassword($_POST['pma_pw']); @@ -188,18 +184,18 @@ class UserPassword . " `authentication_string` = '" . $hashedPassword . "', `Password` = '', " . " `plugin` = '" . $orig_auth_plugin . "'" - . " WHERE `User` = '" . $dbi->escapeString($username) - . "' AND Host = '" . $dbi->escapeString($hostname) . "';"; + . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) + . "' AND Host = '" . $GLOBALS['dbi']->escapeString($hostname) . "';"; } else { $local_query = 'SET password = ' . ($password == '' ? '\'\'' : $hashing_function . '(\'' - . $dbi->escapeString($password) . '\')'); + . $GLOBALS['dbi']->escapeString($password) . '\')'); } - if (! @$dbi->tryQuery($local_query)) { + if (! @$GLOBALS['dbi']->tryQuery($local_query)) { Generator::mysqlDie( - $dbi->getError(), + $GLOBALS['dbi']->getError(), $sql_query, false, $err_url @@ -207,7 +203,7 @@ class UserPassword } // Flush privileges after successful password change - $dbi->tryQuery('FLUSH PRIVILEGES;'); + $GLOBALS['dbi']->tryQuery('FLUSH PRIVILEGES;'); } public function getFormForChangePassword(?string $username, ?string $hostname): string diff --git a/libraries/classes/UserPreferences.php b/libraries/classes/UserPreferences.php index b3d6a1340a..c735ca9722 100644 --- a/libraries/classes/UserPreferences.php +++ b/libraries/classes/UserPreferences.php @@ -35,9 +35,7 @@ class UserPreferences public function __construct() { - global $dbi; - - $this->relation = new Relation($dbi); + $this->relation = new Relation($GLOBALS['dbi']); $this->template = new Template(); } @@ -72,8 +70,6 @@ class UserPreferences */ public function load() { - global $dbi; - $relationParameters = $this->relation->getRelationParameters(); if ($relationParameters->userPreferencesFeature === null) { // no pmadb table, use session storage @@ -97,9 +93,13 @@ class UserPreferences $query = 'SELECT `config_data`, UNIX_TIMESTAMP(`timevalue`) ts' . ' FROM ' . $query_table . ' WHERE `username` = \'' - . $dbi->escapeString((string) $relationParameters->user) + . $GLOBALS['dbi']->escapeString((string) $relationParameters->user) . '\''; - $row = $dbi->fetchSingleRow($query, DatabaseInterface::FETCH_ASSOC, DatabaseInterface::CONNECT_CONTROL); + $row = $GLOBALS['dbi']->fetchSingleRow( + $query, + DatabaseInterface::FETCH_ASSOC, + DatabaseInterface::CONNECT_CONTROL + ); return [ 'config_data' => $row ? json_decode($row['config_data'], true) : [], @@ -117,8 +117,6 @@ class UserPreferences */ public function save(array $config_array) { - global $dbi; - $relationParameters = $this->relation->getRelationParameters(); $server = $GLOBALS['server'] ?? $GLOBALS['cfg']['ServerDefault']; $cache_key = 'server_' . $server; @@ -144,34 +142,37 @@ class UserPreferences . Util::backquote($relationParameters->userPreferencesFeature->userConfig); $query = 'SELECT `username` FROM ' . $query_table . ' WHERE `username` = \'' - . $dbi->escapeString($relationParameters->user) + . $GLOBALS['dbi']->escapeString($relationParameters->user) . '\''; - $has_config = $dbi->fetchValue($query, 0, DatabaseInterface::CONNECT_CONTROL); + $has_config = $GLOBALS['dbi']->fetchValue($query, 0, DatabaseInterface::CONNECT_CONTROL); $config_data = json_encode($config_array); if ($has_config) { $query = 'UPDATE ' . $query_table . ' SET `timevalue` = NOW(), `config_data` = \'' - . $dbi->escapeString($config_data) + . $GLOBALS['dbi']->escapeString($config_data) . '\'' . ' WHERE `username` = \'' - . $dbi->escapeString($relationParameters->user) + . $GLOBALS['dbi']->escapeString($relationParameters->user) . '\''; } else { $query = 'INSERT INTO ' . $query_table . ' (`username`, `timevalue`,`config_data`) ' . 'VALUES (\'' - . $dbi->escapeString($relationParameters->user) . '\', NOW(), ' - . '\'' . $dbi->escapeString($config_data) . '\')'; + . $GLOBALS['dbi']->escapeString($relationParameters->user) . '\', NOW(), ' + . '\'' . $GLOBALS['dbi']->escapeString($config_data) . '\')'; } if (isset($_SESSION['cache'][$cache_key]['userprefs'])) { unset($_SESSION['cache'][$cache_key]['userprefs']); } - if (! $dbi->tryQuery($query, DatabaseInterface::CONNECT_CONTROL)) { + if (! $GLOBALS['dbi']->tryQuery($query, DatabaseInterface::CONNECT_CONTROL)) { $message = Message::error(__('Could not save configuration')); - $message->addMessage(Message::error($dbi->getError(DatabaseInterface::CONNECT_CONTROL)), '

'); + $message->addMessage( + Message::error($GLOBALS['dbi']->getError(DatabaseInterface::CONNECT_CONTROL)), + '

' + ); if (! $this->hasAccessToDatabase($relationParameters->db)) { /** * When phpMyAdmin cached the configuration storage parameters, it checked if the database can be diff --git a/libraries/classes/Util.php b/libraries/classes/Util.php index 554635ec3d..12f84ca740 100644 --- a/libraries/classes/Util.php +++ b/libraries/classes/Util.php @@ -203,8 +203,6 @@ class Util */ public static function getMySQLDocuURL(string $link, string $anchor = ''): string { - global $dbi; - // Fixup for newly used names: $link = str_replace('_', '-', mb_strtolower($link)); @@ -214,8 +212,8 @@ class Util $mysql = '5.5'; $lang = 'en'; - if (isset($dbi)) { - $serverVersion = $dbi->getVersion(); + if (isset($GLOBALS['dbi'])) { + $serverVersion = $GLOBALS['dbi']->getVersion(); if ($serverVersion >= 80000) { $mysql = '8.0'; } elseif ($serverVersion >= 50700) { @@ -266,8 +264,6 @@ class Util */ private static function checkRowCount($db, array $table) { - global $dbi; - $rowCount = 0; if ($table['Rows'] === null) { @@ -283,7 +279,7 @@ class Util $tableIsView = $table['TABLE_TYPE'] === 'VIEW'; if ($tableIsView || Utilities::isSystemSchema($db)) { - $rowCount = $dbi + $rowCount = $GLOBALS['dbi'] ->getTable($db, $table['Name']) ->countRecords(); } @@ -301,11 +297,9 @@ class Util */ public static function getTableList($db): array { - global $dbi; - $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator']; - $tables = $dbi->getTablesFull($db); + $tables = $GLOBALS['dbi']->getTablesFull($db); if ($GLOBALS['cfg']['NaturalOrder']) { uksort($tables, 'strnatcasecmp'); @@ -865,8 +859,6 @@ class Util string $conditionKey, string $condition ): array { - global $dbi; - if ($row === null) { return ['IS NULL', $condition]; } @@ -911,7 +903,7 @@ class Util . self::printableBitValue((int) $row, (int) $meta->length) . "'"; } else { $conditionValue = '= \'' - . $dbi->escapeString($row) . '\''; + . $GLOBALS['dbi']->escapeString($row) . '\''; } return [$conditionValue, $condition]; @@ -938,8 +930,6 @@ class Util $restrictToTable = false, array $expressions = [] ): array { - global $dbi; - $primaryKey = ''; $uniqueKey = ''; $nonPrimaryCondition = ''; @@ -981,7 +971,7 @@ class Util // because there is some caching in the function). if ( $meta->table !== $meta->orgtable - && ! $dbi->getTable($GLOBALS['db'], $meta->table)->isView() + && ! $GLOBALS['dbi']->getTable($GLOBALS['db'], $meta->table)->isView() ) { $meta->table = $meta->orgtable; } @@ -1609,8 +1599,6 @@ class Util $escape = null, array $updates = [] ) { - global $dbi; - /* Content */ $vars = []; $vars['http_host'] = Core::getenv('HTTP_HOST'); @@ -1675,7 +1663,7 @@ class Util /* Fetch columns list if required */ if (str_contains($string, '@COLUMNS@')) { - $columnsList = $dbi->getColumns($GLOBALS['db'], $GLOBALS['table']); + $columnsList = $GLOBALS['dbi']->getColumns($GLOBALS['db'], $GLOBALS['table']); // sometimes the table no longer exists at this point if ($columnsList !== null) { @@ -1711,13 +1699,11 @@ class Util */ public static function getSupportedDatatypes($html = false, $selected = '') { - global $dbi; - if ($html) { $retval = Generator::getSupportedDatatypes($selected); } else { $retval = []; - foreach ($dbi->types->getColumns() as $value) { + foreach ($GLOBALS['dbi']->types->getColumns() as $value) { if (is_array($value)) { foreach ($value as $subvalue) { if ($subvalue === '-') { @@ -1769,11 +1755,9 @@ class Util */ public static function currentUserHasPrivilege(string $priv, ?string $db = null, ?string $tbl = null): bool { - global $dbi; - // Get the username for the current user in the format // required to use in the information schema database. - [$user, $host] = $dbi->getCurrentUserAndHost(); + [$user, $host] = $GLOBALS['dbi']->getCurrentUserAndHost(); // MySQL is started with --skip-grant-tables if ($user === '') { @@ -1791,7 +1775,7 @@ class Util . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'"; // Check global privileges first. - $userPrivileges = $dbi->fetchValue( + $userPrivileges = $GLOBALS['dbi']->fetchValue( sprintf( $query, 'USER_PRIVILEGES', @@ -1812,13 +1796,13 @@ class Util } $query .= " AND '%s' LIKE `TABLE_SCHEMA`"; - $schemaPrivileges = $dbi->fetchValue( + $schemaPrivileges = $GLOBALS['dbi']->fetchValue( sprintf( $query, 'SCHEMA_PRIVILEGES', $username, $priv, - $dbi->escapeString($db) + $GLOBALS['dbi']->escapeString($db) ) ); if ($schemaPrivileges) { @@ -1829,14 +1813,14 @@ class Util // find any valid privileges, try table-wise privileges. if ($tbl !== null) { $query .= " AND TABLE_NAME='%s'"; - $tablePrivileges = $dbi->fetchValue( + $tablePrivileges = $GLOBALS['dbi']->fetchValue( sprintf( $query, 'TABLE_PRIVILEGES', $username, $priv, - $dbi->escapeString($db), - $dbi->escapeString($tbl) + $GLOBALS['dbi']->escapeString($db), + $GLOBALS['dbi']->escapeString($tbl) ) ); if ($tablePrivileges) { @@ -1860,13 +1844,11 @@ class Util */ public static function getServerType(): string { - global $dbi; - - if ($dbi->isMariaDB()) { + if ($GLOBALS['dbi']->isMariaDB()) { return 'MariaDB'; } - if ($dbi->isPercona()) { + if ($GLOBALS['dbi']->isPercona()) { return 'Percona Server'; } @@ -2067,9 +2049,7 @@ class Util */ public static function getCollateForIS() { - global $dbi; - - $names = $dbi->getLowerCaseNames(); + $names = $GLOBALS['dbi']->getLowerCaseNames(); if ($names === '0') { return 'COLLATE utf8_bin'; } @@ -2149,8 +2129,6 @@ class Util */ public static function getDbInfo($db, string $subPart) { - global $cfg, $dbi; - /** * limits for table list */ @@ -2168,7 +2146,7 @@ class Util /** * whether to display extended stats */ - $isShowStats = $cfg['ShowStats']; + $isShowStats = $GLOBALS['cfg']['ShowStats']; /** * whether selected db is information_schema @@ -2189,8 +2167,8 @@ class Util $tooltipAliasName = []; // Special speedup for newer MySQL Versions (in 4.0 format changed) - if ($cfg['SkipLockedTables'] === true) { - $dbInfoResult = $dbi->query( + if ($GLOBALS['cfg']['SkipLockedTables'] === true) { + $dbInfoResult = $GLOBALS['dbi']->query( 'SHOW OPEN TABLES FROM ' . self::backquote($db) . ' WHERE In_use > 0;' ); @@ -2245,7 +2223,7 @@ class Util $tableGroup = $_REQUEST['tbl_group']; // include the table with the exact name of the group if such // exists - $groupTable = $dbi->getTablesFull( + $groupTable = $GLOBALS['dbi']->getTablesFull( $db, $tableGroup, false, @@ -2262,7 +2240,7 @@ class Util // all tables in db // - get the total number of tables // (needed for proper working of the MaxTableList feature) - $tables = $dbi->getTables($db); + $tables = $GLOBALS['dbi']->getTables($db); $totalNumTables = count($tables); if ($subPart !== '_export') { // fetch the details for a possible limited subset @@ -2272,7 +2250,7 @@ class Util } // We must use union operator here instead of array_merge to preserve numerical keys - $tables = $groupTable + $dbi->getTablesFull( + $tables = $groupTable + $GLOBALS['dbi']->getTablesFull( $db, $groupWithSeparator !== false ? $groupWithSeparator : '', $groupWithSeparator !== false, @@ -2322,8 +2300,6 @@ class Util */ public static function getTablesWhenOpen($db, ResultInterface $dbInfoResult): array { - global $dbi; - $sotCache = []; $tables = []; @@ -2363,7 +2339,7 @@ class Util } } - $dbInfoResult = $dbi->query('SHOW FULL TABLES FROM ' . self::backquote($db) . $tblGroupSql); + $dbInfoResult = $GLOBALS['dbi']->query('SHOW FULL TABLES FROM ' . self::backquote($db) . $tblGroupSql); unset($tblGroupSql, $whereAdded); if ($dbInfoResult->numRows() > 0) { @@ -2385,7 +2361,7 @@ class Util if (count($names) > 0) { $tables = array_merge( $tables, - $dbi->getTablesFull($db, $names) + $GLOBALS['dbi']->getTablesFull($db, $names) ); } diff --git a/libraries/classes/Utils/ForeignKey.php b/libraries/classes/Utils/ForeignKey.php index 165c02c3e7..217296f6d7 100644 --- a/libraries/classes/Utils/ForeignKey.php +++ b/libraries/classes/Utils/ForeignKey.php @@ -18,8 +18,6 @@ final class ForeignKey */ public static function isSupported($engine): bool { - global $dbi; - $engine = strtoupper((string) $engine); if (($engine === 'INNODB') || ($engine === 'PBXT')) { return true; @@ -27,7 +25,7 @@ final class ForeignKey if ($engine === 'NDBCLUSTER' || $engine === 'NDB') { $ndbver = strtolower( - $dbi->fetchValue('SELECT @@ndb_version_string') ?: '' + $GLOBALS['dbi']->fetchValue('SELECT @@ndb_version_string') ?: '' ); if (substr($ndbver, 0, 4) === 'ndb-') { $ndbver = substr($ndbver, 4); @@ -44,8 +42,6 @@ final class ForeignKey */ public static function isCheckEnabled(): bool { - global $dbi; - if ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'enable') { return true; } @@ -54,7 +50,7 @@ final class ForeignKey return false; } - return $dbi->getVariable('FOREIGN_KEY_CHECKS') === 'ON'; + return $GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') === 'ON'; } /** @@ -62,16 +58,14 @@ final class ForeignKey */ public static function handleDisableCheckInit(): bool { - global $dbi; - - $defaultCheckValue = $dbi->getVariable('FOREIGN_KEY_CHECKS') === 'ON'; + $defaultCheckValue = $GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') === 'ON'; if (isset($_REQUEST['fk_checks'])) { if (empty($_REQUEST['fk_checks'])) { // Disable foreign key checks - $dbi->setVariable('FOREIGN_KEY_CHECKS', 'OFF'); + $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'OFF'); } else { // Enable foreign key checks - $dbi->setVariable('FOREIGN_KEY_CHECKS', 'ON'); + $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'ON'); } } @@ -85,8 +79,6 @@ final class ForeignKey */ public static function handleDisableCheckCleanup(bool $defaultCheckValue): void { - global $dbi; - - $dbi->setVariable('FOREIGN_KEY_CHECKS', $defaultCheckValue ? 'ON' : 'OFF'); + $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', $defaultCheckValue ? 'ON' : 'OFF'); } } diff --git a/libraries/classes/Utils/Gis.php b/libraries/classes/Utils/Gis.php index f35d75324b..9b2c9839ef 100644 --- a/libraries/classes/Utils/Gis.php +++ b/libraries/classes/Utils/Gis.php @@ -22,20 +22,18 @@ final class Gis */ public static function convertToWellKnownText($data, $includeSRID = false): string { - global $dbi; - // Convert to WKT format $hex = bin2hex($data); $spatialAsText = 'ASTEXT'; $spatialSrid = 'SRID'; $axisOrder = ''; - $mysqlVersionInt = $dbi->getVersion(); + $mysqlVersionInt = $GLOBALS['dbi']->getVersion(); if ($mysqlVersionInt >= 50600) { $spatialAsText = 'ST_ASTEXT'; $spatialSrid = 'ST_SRID'; } - if ($mysqlVersionInt >= 80001 && ! $dbi->isMariaDb()) { + if ($mysqlVersionInt >= 80001 && ! $GLOBALS['dbi']->isMariaDb()) { $axisOrder = ', \'axis-order=long-lat\''; } @@ -44,7 +42,7 @@ final class Gis $wktsql .= ', ' . $spatialSrid . "(x'" . $hex . "')"; } - $wktresult = $dbi->tryQuery($wktsql); + $wktresult = $GLOBALS['dbi']->tryQuery($wktsql); $wktarr = []; if ($wktresult) { $wktarr = $wktresult->fetchRow(); @@ -129,8 +127,6 @@ final class Gis $binary = true, $display = false ): array { - global $dbi; - $funcs = []; if ($display) { $funcs[] = ['display' => ' ']; @@ -246,7 +242,7 @@ final class Gis } $spatialPrefix = ''; - if ($dbi->getVersion() >= 50601) { + if ($GLOBALS['dbi']->getVersion() >= 50601) { // If MySQL version is greater than or equal 5.6.1, // use the ST_ prefix. $spatialPrefix = 'ST_'; diff --git a/libraries/classes/Utils/HttpRequest.php b/libraries/classes/Utils/HttpRequest.php index b9dc488768..67ff7f62ef 100644 --- a/libraries/classes/Utils/HttpRequest.php +++ b/libraries/classes/Utils/HttpRequest.php @@ -58,27 +58,23 @@ class HttpRequest public function __construct() { - global $cfg; - - $this->proxyUrl = $cfg['ProxyUrl']; - $this->proxyUser = $cfg['ProxyUser']; - $this->proxyPass = $cfg['ProxyPass']; + $this->proxyUrl = $GLOBALS['cfg']['ProxyUrl']; + $this->proxyUser = $GLOBALS['cfg']['ProxyUser']; + $this->proxyPass = $GLOBALS['cfg']['ProxyPass']; } public static function setProxySettingsFromEnv(): void { - global $cfg; - $httpProxy = getenv('http_proxy'); $urlInfo = parse_url((string) $httpProxy); if (PHP_SAPI !== 'cli' || ! is_array($urlInfo)) { return; } - $cfg['ProxyUrl'] = ($urlInfo['host'] ?? '') + $GLOBALS['cfg']['ProxyUrl'] = ($urlInfo['host'] ?? '') . (isset($urlInfo['port']) ? ':' . $urlInfo['port'] : ''); - $cfg['ProxyUser'] = $urlInfo['user'] ?? ''; - $cfg['ProxyPass'] = $urlInfo['pass'] ?? ''; + $GLOBALS['cfg']['ProxyUser'] = $urlInfo['user'] ?? ''; + $GLOBALS['cfg']['ProxyPass'] = $urlInfo['pass'] ?? ''; } /** diff --git a/libraries/classes/Utils/SessionCache.php b/libraries/classes/Utils/SessionCache.php index 99333e952b..a87a7a5232 100644 --- a/libraries/classes/Utils/SessionCache.php +++ b/libraries/classes/Utils/SessionCache.php @@ -8,12 +8,10 @@ final class SessionCache { private static function key(): string { - global $cfg, $server; + $key = 'server_' . $GLOBALS['server']; - $key = 'server_' . $server; - - if (isset($cfg['Server']['user'])) { - return $key . '_' . $cfg['Server']['user']; + if (isset($GLOBALS['cfg']['Server']['user'])) { + return $key . '_' . $GLOBALS['cfg']['Server']['user']; } return $key; diff --git a/libraries/classes/VersionInformation.php b/libraries/classes/VersionInformation.php index cf4899a344..91aab0dc95 100644 --- a/libraries/classes/VersionInformation.php +++ b/libraries/classes/VersionInformation.php @@ -252,10 +252,8 @@ class VersionInformation */ protected function getMySQLVersion() { - global $dbi; - - if (isset($dbi)) { - return $dbi->getVersionString(); + if (isset($GLOBALS['dbi'])) { + return $GLOBALS['dbi']->getVersionString(); } return null; diff --git a/phpcs.xml.dist b/phpcs.xml.dist index fbd5ed115a..78426933e4 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -25,6 +25,8 @@ */libraries/classes/Plugins/Transformations/* + + 4 diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 84926a073c..7f20ca7852 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1015,21 +1015,16 @@ parameters: count: 1 path: libraries/classes/Controllers/Database/DataDictionaryController.php - - - message: "#^Argument of an invalid type array\\|null supplied for foreach, only iterables are supported\\.$#" - count: 1 - path: libraries/classes/Controllers/Database/DesignerController.php - - - - message: "#^Parameter \\#9 \\$selectedPage of method PhpMyAdmin\\\\Database\\\\Designer\\:\\:getHtmlForMain\\(\\) expects string, string\\|null given\\.$#" - count: 1 - path: libraries/classes/Controllers/Database/DesignerController.php - - message: "#^Negated boolean expression is always true\\.$#" count: 6 path: libraries/classes/Controllers/Database/OperationsController.php + - + message: "#^Parameter \\#2 \\$export_sql_plugin of method PhpMyAdmin\\\\Operations\\:\\:getViewsAndCreateSqlViewStandIn\\(\\) expects PhpMyAdmin\\\\Plugins\\\\Export\\\\ExportSql, object\\|null given\\.$#" + count: 1 + path: libraries/classes/Controllers/Database/OperationsController.php + - message: "#^Method PhpMyAdmin\\\\Controllers\\\\Database\\\\PrivilegesController\\:\\:__invoke\\(\\) has parameter \\$params with no value type specified in iterable type array\\.$#" count: 1 @@ -1165,36 +1160,6 @@ parameters: count: 1 path: libraries/classes/Controllers/Database/StructureController.php - - - message: "#^Argument of an invalid type mixed supplied for foreach, only iterables are supported\\.$#" - count: 1 - path: libraries/classes/Controllers/Database/TrackingController.php - - - - message: "#^Cannot access offset 'date' on mixed\\.$#" - count: 1 - path: libraries/classes/Controllers/Database/TrackingController.php - - - - message: "#^Cannot access offset 'ddlog' on mixed\\.$#" - count: 3 - path: libraries/classes/Controllers/Database/TrackingController.php - - - - message: "#^Cannot access offset 'statement' on mixed\\.$#" - count: 1 - path: libraries/classes/Controllers/Database/TrackingController.php - - - - message: "#^Cannot access offset 'username' on mixed\\.$#" - count: 1 - path: libraries/classes/Controllers/Database/TrackingController.php - - - - message: "#^Parameter \\#1 \\$var of function count expects array\\|Countable, mixed given\\.$#" - count: 2 - path: libraries/classes/Controllers/Database/TrackingController.php - - message: "#^Cannot access offset 'success' on mixed\\.$#" count: 1 @@ -1225,11 +1190,6 @@ parameters: count: 1 path: libraries/classes/Controllers/Export/ExportController.php - - - message: "#^Variable \\$export_plugin in empty\\(\\) always exists and is not falsy\\.$#" - count: 1 - path: libraries/classes/Controllers/Export/ExportController.php - - message: "#^Cannot cast mixed to int\\.$#" count: 1 @@ -1265,21 +1225,6 @@ parameters: count: 1 path: libraries/classes/Controllers/HomeController.php - - - message: "#^If condition is always false\\.$#" - count: 1 - path: libraries/classes/Controllers/Import/ImportController.php - - - - message: "#^Left side of && is always false\\.$#" - count: 1 - path: libraries/classes/Controllers/Import/ImportController.php - - - - message: "#^Negated boolean expression is always true\\.$#" - count: 1 - path: libraries/classes/Controllers/Import/ImportController.php - - message: "#^Parameter \\#1 \\$dependencies of method PhpMyAdmin\\\\Normalization\\:\\:getHtmlForNewTables3NF\\(\\) expects object, mixed given\\.$#" count: 1 @@ -1310,11 +1255,6 @@ parameters: count: 1 path: libraries/classes/Controllers/NormalizationController.php - - - message: "#^Parameter \\#1 \\$file_name of method PhpMyAdmin\\\\UserPreferences\\:\\:redirect\\(\\) expects string, string\\|false given\\.$#" - count: 1 - path: libraries/classes/Controllers/Preferences/ManageController.php - - message: "#^Property PhpMyAdmin\\\\Controllers\\\\Server\\\\BinlogController\\:\\:\\$binaryLogs type has no value type specified in iterable type array\\.$#" count: 1 @@ -1455,11 +1395,6 @@ parameters: count: 1 path: libraries/classes/Controllers/Setup/ServersController.php - - - message: "#^Comparison operation \"\\>\" between 0 and 0 is always false\\.$#" - count: 1 - path: libraries/classes/Controllers/Table/ChangeController.php - - message: "#^Property PhpMyAdmin\\\\SqlParser\\\\Statements\\\\SelectStatement\\:\\:\\$limit \\(PhpMyAdmin\\\\SqlParser\\\\Components\\\\Limit\\) in empty\\(\\) is not falsy\\.$#" count: 1 @@ -1485,11 +1420,6 @@ parameters: count: 1 path: libraries/classes/Controllers/Table/IndexesController.php - - - message: "#^Comparison operation \"\\>\" between int\\<1, max\\> and 0 is always true\\.$#" - count: 1 - path: libraries/classes/Controllers/Table/OperationsController.php - - message: "#^Method PhpMyAdmin\\\\Controllers\\\\Table\\\\PrivilegesController\\:\\:__invoke\\(\\) has parameter \\$params with no value type specified in iterable type array\\.$#" count: 1 @@ -1530,11 +1460,6 @@ parameters: count: 1 path: libraries/classes/Controllers/Table/ReplaceController.php - - - message: "#^Parameter \\#1 \\$messages of method PhpMyAdmin\\\\Message\\:\\:addMessagesString\\(\\) expects array\\, array\\ given\\.$#" - count: 1 - path: libraries/classes/Controllers/Table/ReplaceController.php - - message: "#^Method PhpMyAdmin\\\\Controllers\\\\Table\\\\SearchController\\:\\:getColumnMinMax\\(\\) return type has no value type specified in iterable type array\\.$#" count: 1 @@ -1690,26 +1615,6 @@ parameters: count: 1 path: libraries/classes/Controllers/Table/StructureController.php - - - message: "#^Cannot access offset 'date_from' on mixed\\.$#" - count: 1 - path: libraries/classes/Controllers/Table/TrackingController.php - - - - message: "#^Cannot access offset 'date_to' on mixed\\.$#" - count: 1 - path: libraries/classes/Controllers/Table/TrackingController.php - - - - message: "#^Parameter \\#1 \\$data of method PhpMyAdmin\\\\Tracking\\:\\:getEntries\\(\\) expects array, mixed given\\.$#" - count: 1 - path: libraries/classes/Controllers/Table/TrackingController.php - - - - message: "#^Parameter \\#1 \\$data of method PhpMyAdmin\\\\Tracking\\:\\:getHtmlForTrackingReport\\(\\) expects array, mixed given\\.$#" - count: 1 - path: libraries/classes/Controllers/Table/TrackingController.php - - message: "#^Method PhpMyAdmin\\\\Controllers\\\\Table\\\\ZoomSearchController\\:\\:getColumnProperties\\(\\) return type has no value type specified in iterable type array\\.$#" count: 1 @@ -1750,16 +1655,6 @@ parameters: count: 1 path: libraries/classes/Controllers/Table/ZoomSearchController.php - - - message: "#^Parameter \\#1 \\$data of static method PhpMyAdmin\\\\Image\\\\ImageWrapper\\:\\:fromString\\(\\) expects string, string\\|null given\\.$#" - count: 1 - path: libraries/classes/Controllers/Transformation/WrapperController.php - - - - message: "#^Parameter \\#1 \\$string of function htmlspecialchars expects string, string\\|null given\\.$#" - count: 1 - path: libraries/classes/Controllers/Transformation/WrapperController.php - - message: "#^Parameter \\#1 \\$string of function substr expects string, mixed given\\.$#" count: 1 @@ -4385,11 +4280,6 @@ parameters: count: 1 path: libraries/classes/Import.php - - - message: "#^Method PhpMyAdmin\\\\Import\\:\\:runQueryPost\\(\\) has parameter \\$importRunBuffer with no value type specified in iterable type array\\.$#" - count: 1 - path: libraries/classes/Import.php - - message: "#^Method PhpMyAdmin\\\\Import\\:\\:runQueryPost\\(\\) return type has no value type specified in iterable type array\\.$#" count: 1 diff --git a/psalm-baseline.xml b/psalm-baseline.xml index 349edab775..04fb0558f1 100644 --- a/psalm-baseline.xml +++ b/psalm-baseline.xml @@ -1,14 +1,20 @@ - - global $containerBuilder; - + + $GLOBALS['containerBuilder'] + + + $GLOBALS['containerBuilder'] + - - $isMinimumCommon - + + $GLOBALS['containerBuilder'] + + + get + @@ -86,6 +92,9 @@ + + $GLOBALS['theme'] + $_POST['foreign_filter'] $descriptions[$indexByDescription] @@ -119,10 +128,10 @@ $pos - (bool) $cfg['ShowAll'] - (int) $cfg['LimitChars'] - (int) $cfg['MaxRows'] - (int) $cfg['RepeatCells'] + (bool) $GLOBALS['cfg']['ShowAll'] + (int) $GLOBALS['cfg']['LimitChars'] + (int) $GLOBALS['cfg']['MaxRows'] + (int) $GLOBALS['cfg']['RepeatCells'] @@ -235,40 +244,84 @@ + + $GLOBALS['config'] + $GLOBALS['config'] + $GLOBALS['errorHandler'] + + + $GLOBALS['cfg']['Server']['controluser'] + + $GLOBALS['back'] + $GLOBALS['cfg']['Server']['user'] + $GLOBALS['goto'] + $GLOBALS['server'] $_REQUEST['back'] $_REQUEST['goto'] $_SESSION[' PMA_token '] - $back - $cfg['Server']['user'] - $goto $sqlDelimiter - $urlParams - $cfg['MysqlMinVersion']['human'] - $cfg['MysqlMinVersion']['internal'] - $cfg['Server']['user'] + $GLOBALS['cfg']['MysqlMinVersion']['human'] + $GLOBALS['cfg']['MysqlMinVersion']['internal'] + $GLOBALS['cfg']['Server']['user'] - - $urlParams['goto'] - - - $back + + $GLOBALS['back'] + $GLOBALS['cfg'] + $GLOBALS['goto'] + $GLOBALS['server'] + $GLOBALS['sql_query'] + $GLOBALS['urlParams']['goto'] + $GLOBALS['urlParams']['server'] $controlLink - $goto $sqlDelimiter - $sql_query - $urlParams['goto'] $userLink + + checkErrors + checkPermissions + checkServers + getLoginCookieValidityFromCache + loadUserPreferences + loadUserPreferences + selectServer + setCookie + + + $GLOBALS['config'] + $GLOBALS['config'] + $GLOBALS['errorHandler'] + + + $GLOBALS['config']->settings + + + checkErrors + checkPermissions + checkServers + getLoginCookieValidityFromCache + loadUserPreferences + loadUserPreferences + selectServer + setCookie + + + (string) $GLOBALS['lang'] + + + is_array($GLOBALS['urlParams']) + $optionalParams - - $cfg['Server']['hide_connection_errors'] + + $GLOBALS['cfg']['Server']['controlpass'] + $GLOBALS['cfg']['Server']['controluser'] + $GLOBALS['cfg']['Server']['hide_connection_errors'] $collation_connection @@ -312,10 +365,10 @@ $this->settings['Servers'][$server] $this->settings['Servers'][$this->settings['ServerDefault']] - + + $GLOBALS['cfg']['LoginCookieValidity'] $_SESSION['cache'][$cache_key]['userprefs_mtime'] $_SESSION['cache'][$cache_key]['userprefs_type'] - $cfg['LoginCookieValidity'] $collation_connection $config_data $default_value @@ -324,6 +377,7 @@ $eval_result $i $password + $password $path $prefs_type $prefs_type @@ -339,6 +393,7 @@ $url $url $user + $user $val $value @@ -949,26 +1004,15 @@ - - $db - $params - - $params['message'] - readgzfile - - - $db - - $_POST['collation_connection'] @@ -985,10 +1029,9 @@ - + $columnDefault $columnDefault - $db $name['selected_fld'] $params['col_attribute'] $params['col_attribute'] @@ -1009,18 +1052,17 @@ $params['orig_col_name'] $params['selected_fld'] $params['table-select'] - $text_dir $variables + $GLOBALS['message'] $columnDefault $columnDefault - $message - (int) $cfg['MaxRows'] + (int) $GLOBALS['cfg']['MaxRows'] @@ -1050,7 +1092,13 @@ - + + $GLOBALS['display_page'] + $GLOBALS['display_page'] + $GLOBALS['display_page'] + $GLOBALS['page'] + $GLOBALS['sub_part'] ?? '' + $GLOBALS['success'] $_GET['db'] $_GET['db'] $_GET['db'] @@ -1085,21 +1133,10 @@ $_POST['table'] $_POST['table'] $_POST['value'] - $db - $db - $display_page - $display_page - $display_page $html - $page $position['dbName'] $position['tableName'] - $sub_part ?? '' - $success - - ['db' => $db] - $position['dbName'] $position['dbName'] @@ -1107,57 +1144,49 @@ $position['tableName'] - $display_page - $page - $params['db'] + $GLOBALS['display_page'] + $GLOBALS['page'] + $GLOBALS['params']['db'] $position $position['dbName'] $position['tableName'] - + + $GLOBALS['display_page'] + $GLOBALS['display_page'] + $GLOBALS['display_page'] + $GLOBALS['page'] + $GLOBALS['selected_page'] $_GET['db'] - $display_page - $display_page - $page - $selected_page - $tab_pos + $GLOBALS['tab_pos'] $_GET['db'] - - $db - $db - $db - $sub_part ?? '' + + $GLOBALS['sub_part'] ?? '' - - ['db' => $db] - - - $db - $db + + $GLOBALS['num_tables'] + $GLOBALS['tables'] + + + $GLOBALS['num_tables'] + $GLOBALS['table_select'] + $GLOBALS['unlim_num_rows'] $each_table['Name'] $each_table['Name'] $each_table['Name'] $each_table['Name'] - $num_tables - $sql_query - $table - $table_select - $unlim_num_rows - - ['db' => $db] - $each_table['Name'] $each_table['Name'] @@ -1165,29 +1194,23 @@ $each_table['Name'] $each_table['Name'] - - $urlParams['goto'] - $GLOBALS['single_table'] + $GLOBALS['table_select'] $each_table - $table_select - - $db - $sub_part ?? '' + + $GLOBALS['sub_part'] ?? '' - - ['db' => $db] - - $_SESSION[$SESSION_KEY]['handler'] - $_SESSION[$SESSION_KEY]['handler'] + $_SESSION[$GLOBALS['SESSION_KEY']]['handler'] + $_SESSION[$GLOBALS['SESSION_KEY']]['handler'] - - $_SESSION[$SESSION_KEY] + + $_SESSION[$GLOBALS['SESSION_KEY']] + $_SESSION[$GLOBALS['SESSION_KEY']] $idKey @@ -1195,7 +1218,7 @@ $timeoutPassed - $_SESSION[$SESSION_KEY]['handler']::getIdKey() + $_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getIdKey() @@ -1217,18 +1240,12 @@ - + $_POST['db_collation'] $_POST['db_collation'] ?? '' $_POST['db_collation'] ?? '' - $db - $db - $db $tableName - - ['db' => $db] - $tableName @@ -1240,31 +1257,36 @@ + + $GLOBALS['export_sql_plugin'] + + + $GLOBALS['cfg']['AllowUserDropDatabase'] + $GLOBALS['cfg']['PmaNoRelation_DisableWarning'] + + $GLOBALS['db'] + $GLOBALS['db'] + $GLOBALS['db'] + $GLOBALS['db'] + $GLOBALS['db'] $_POST['comment'] $_POST['newname'] $_POST['newname'] $_POST['newname'] $_POST['newname'] - $db - $db - $db - $db - $message - - ['db' => $db] + + ['db' => $GLOBALS['db']] + ['db' => $GLOBALS['db']] - - $urlParams['goto'] - - - $cfg['Servers'][$server] - - $db - $db + $GLOBALS['db'] + $GLOBALS['db'] + + $GLOBALS['export_sql_plugin'] + ! $_error ! $_error @@ -1284,77 +1306,49 @@ - + $_POST['db'] $_POST['searchId'] $_POST['searchName'] - $db - $db - $db - $db - $db - $sql_query - $sql_query - - ['db' => $db] - - - $urlParams['goto'] - - - $db - $db - $db - $db + + $GLOBALS['sub_part'] ?? '' $item - $sub_part ?? '' - $table - $table $type - - $urlParams - ['db' => $db] - $item $type - - $db - $db - $sub_part ?? '' + + $GLOBALS['cfg']['UseDbSearch'] + + + $GLOBALS['sub_part'] ?? '' - - ['db' => $db] - - - $urlParams['goto'] - - - $db + + $GLOBALS['cfg']['EnableAutocompleteForTablesAndColumns'] + + + $GLOBALS['db'] + $GLOBALS['db'] $tableName - $db + $GLOBALS['db'] $tableName - + $_POST['delimiter'] - $db - - ['db' => $db] - @@ -1375,8 +1369,7 @@ - - $db + $selected $selected[$i] @@ -1399,8 +1392,7 @@ - - $db + $selected @@ -1437,15 +1429,10 @@ getList offsetUnset - - $dblist->databases - - + $_POST['what'] - $db - $db $selected $selected[$i] $selected[$i] @@ -1462,11 +1449,9 @@ - + $current $current - $db - $db $selected @@ -1483,10 +1468,9 @@ - + $current $current - $db $current @@ -1497,10 +1481,9 @@ - + $current $current - $db $selected $selected[$i] @@ -1510,9 +1493,9 @@ $selected[$i] + $GLOBALS['reload'] $current $multBtn - $reload $selected @@ -1526,13 +1509,10 @@ - + $_REQUEST['pos'] - $db - $db $selected $selected[$i] - $table $selected[$i] @@ -1550,9 +1530,6 @@ $value['db'] $value['table'] - - ['db' => $db] - $_SESSION['tmpval']['favoriteTables'][$GLOBALS['server']] $value['db'] @@ -1576,9 +1553,6 @@ $table['TABLE_NAME'] - - ['db' => $db] - $table['TABLE_NAME'] $table['TABLE_NAME'] @@ -1588,10 +1562,9 @@ - + $current $current - $db $newTableName $selected $selected[$i] @@ -1666,9 +1639,6 @@ $updateTime $updateTimeAll - - ['db' => $db] - $_SESSION['tmpval']['favoriteTables'][$GLOBALS['server']] $currentTable['Check_time'] @@ -1758,39 +1728,24 @@ - + + $GLOBALS['data']['ddlog'] + $GLOBALS['data']['ddlog'] $_POST['selected'] $_POST['table'] $_POST['version'] - $data['ddlog'] - $data['ddlog'] - $db - $db - $db - $db - $db - $db $table - $text_dir - $urlParams - - ['db' => $db] - - $data['ddlog'] - $data['ddlog'] - $data['ddlog'] + $GLOBALS['data']['ddlog'] + $GLOBALS['data']['ddlog'] + $GLOBALS['data']['ddlog'] $entry['date'] $entry['statement'] $entry['username'] - - $urlParams['back'] - $urlParams['goto'] - - $data + $GLOBALS['data'] $entry $table @@ -1801,22 +1756,9 @@ - - $db - $db - $db - $sub_part ?? '' - $table + + $GLOBALS['sub_part'] ?? '' - - $urlParams - ['db' => $db] - - - - - $dblist->databases - @@ -1833,61 +1775,51 @@ - - empty($export_plugin) - - - $asfile - $whatStrucOrData - $whatStrucOrData - $whatStrucOrData - $whatStrucOrData - $whatStrucOrData - $whatStrucOrData + + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + + + $GLOBALS['asfile'] + $GLOBALS['file_handle'] - - $allrows - $allrows - $cfg['MemoryLimit'] - $db - $db - $db - $db - $db - $db - $db - $db - $db_select - $export_type - $export_type - $export_type - $export_type - $export_type - $export_type - $export_type - $file_handle - $filename_template - $limit_from - $limit_from - $limit_to - $limit_to - $remember_template - $save_filename - $sql_query - $sql_query - $sql_query - $sql_query - $table - $table - $table - $table - $table_data - $table_data - $table_structure - $table_structure - $tables - $tables - $tables + + $GLOBALS['containerBuilder'] + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['filename_template'] + + + $GLOBALS['allrows'] + $GLOBALS['allrows'] + $GLOBALS['cfg']['MemoryLimit'] + $GLOBALS['db_select'] + $GLOBALS['filename_template'] + $GLOBALS['limit_from'] + $GLOBALS['limit_from'] + $GLOBALS['limit_to'] + $GLOBALS['limit_to'] + $GLOBALS['remember_template'] + $GLOBALS['table_data'] + $GLOBALS['table_data'] + $GLOBALS['table_structure'] + $GLOBALS['table_structure'] + $GLOBALS['tables'] + $GLOBALS['tables'] + $GLOBALS['tables'] + $GLOBALS['tables'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] $this->export->dumpBuffer $this->export->dumpBuffer $this->export->dumpBuffer @@ -1896,29 +1828,85 @@ $_SESSION['tmpval']['aliases'] - - $table_data - $table_structure - $tables + + $GLOBALS['table_data'] + $GLOBALS['table_structure'] + $GLOBALS['tables'] + $GLOBALS['whatStrucOrData'] - - $file_handle + + exportFooter + exportHeader + get + + + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['export_type'] + + + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] - $whatStrucOrData - $whatStrucOrData - $whatStrucOrData - $whatStrucOrData - $whatStrucOrData - $whatStrucOrData + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + $GLOBALS['whatStrucOrData'] + + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + $GLOBALS['export_plugin'] + + + exportFooter + exportHeader + + + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['export_type'] + $GLOBALS['mime_type'] + + + ! $GLOBALS['save_on_server'] + $GLOBALS['export_type'] === 'raw' + $GLOBALS['export_type'] === 'raw' + $GLOBALS['export_type'] === 'raw' + $outputFormat === 'sendit' && ! $GLOBALS['save_on_server'] + + + $GLOBALS['export_type'] === 'database' + $GLOBALS['export_type'] === 'database' + $GLOBALS['export_type'] === 'database' + $GLOBALS['export_type'] === 'database' + $GLOBALS['export_type'] === 'server' + $GLOBALS['export_type'] === 'server' + - $geom_type + $GLOBALS['geom_type'] - $geom_type + $GLOBALS['geom_type'] @@ -1940,22 +1928,37 @@ + + $GLOBALS['cfg']['LoginCookieValidityDisableWarning'] + $GLOBALS['cfg']['NavigationDisplayServers'] + $GLOBALS['cfg']['PmaNoRelation_DisableWarning'] + $GLOBALS['cfg']['ShowChgPassword'] + $GLOBALS['cfg']['ShowPhpInfo'] + $GLOBALS['cfg']['ShowServerInfo'] + $GLOBALS['cfg']['SuhosinDisableWarning'] + $GLOBALS['cfg']['ThemeManager'] + $GLOBALS['cfg']['TranslationWarningThreshold'] + $GLOBALS['language_stats'] + - $message + $GLOBALS['cfg']['blowfish_secret'] $this->config->get('ShowGitRevision') ?? true $this->config->get('TempDir') - - $GLOBALS['language_stats'][$lang] - $cfg['Servers'][$server] - + + $GLOBALS['language_stats'][$GLOBALS['lang']] + - $db + $GLOBALS['db'] $webServer['software'] $this->config->get('TempDir') + + $GLOBALS['cfg']['ShowServerInfo'] + $GLOBALS['cfg']['ShowServerInfo'] + $collationsList @@ -1964,7 +1967,18 @@ $import_plugin == null - + + $GLOBALS['cfg']['AllowUserDropDatabase'] + + + $GLOBALS['cfg']['AllowUserDropDatabase'] + $GLOBALS['cfg']['MemoryLimit'] + $GLOBALS['format'] + $GLOBALS['import_file'] + $GLOBALS['import_file'] + $GLOBALS['import_notice'] + $GLOBALS['local_import_file'] + $GLOBALS['table'] $_POST['bkm_label'] $_POST['bkm_label'] $_POST['bookmark_variable'] @@ -1972,42 +1986,14 @@ $_POST['sql_query'] $_SESSION['Import_message']['go_back_url'] $analyzed_sql_results - $cfg['MemoryLimit'] - $collation_connection - $db - $db - $db - $db - $db - $db - $db - $db - $db $die['error'] $die['sql'] - $format - $goto - $goto $importHandle ?? null - $import_file - $import_file - $import_notice - $import_text - $import_type - $local_import_file $replacement - $sql_query - $sql_query - $sql_query - $sql_query - $sql_query - $sql_query - $table - $table + $GLOBALS['urlParams'] $parameter - $urlParams $_FILES['import_file']['name'] @@ -2033,53 +2019,41 @@ $_SESSION['Import_message']['message'] $_SESSION['Import_message']['message'] - - $MAX_FILE_SIZE - $_SESSION['Import_message']['go_back_url'] - $_SESSION['Import_message']['message'] - $active_page - $charset_of_file + + $GLOBALS['MAX_FILE_SIZE'] + $GLOBALS['charset_of_file'] + $GLOBALS['format'] + $GLOBALS['import_file'] + $GLOBALS['import_file'] + $GLOBALS['import_file_name'] + $GLOBALS['import_type'] + $GLOBALS['is_js_confirmed'] + $GLOBALS['local_import_file'] + $GLOBALS['message_to_show'] + $GLOBALS['noplugin'] + $GLOBALS['offset'] + $GLOBALS['offset'] + $GLOBALS['reload'] + $GLOBALS['reload'] + $GLOBALS['show_as_php'] + $GLOBALS['skip_queries'] + $GLOBALS['table'] + $GLOBALS['table'] + $GLOBALS['urlParams']['local_import_file'] $die - $display_query - $format - $import_file - $import_file - $import_file_name - $import_text - $import_type - $is_js_confirmed - $local_import_file - $message_to_show - $noplugin - $offset - $offset - $reload - $reload $replacement - $show_as_php - $skip_queries - $sql_queries - $sql_query - $table - $table - $urlParams['local_import_file'] - + close - getDisplay - + + $GLOBALS['charset_of_file'] + $GLOBALS['format'] + $GLOBALS['local_import_file'] $_FILES['import_file']['name'] - $charset_connection - $charset_of_file - $format - $goto - $goto - $goto - $local_import_file - $skip < $read_limit ? $skip : $read_limit + $skip < $GLOBALS['read_limit'] ? $skip : $GLOBALS['read_limit'] $_FILES['import_file']['name'] @@ -2087,12 +2061,16 @@ $_FILES['import_file'] - - $offset == 0 + + $GLOBALS['go_sql'] + $GLOBALS['offset'] == 0 + $GLOBALS['result'] === false - - $finished - $timeout_passed + + ! empty($GLOBALS['sql_data']) && ($GLOBALS['sql_data']['valid_queries'] > 1) + $GLOBALS['finished'] + $GLOBALS['result'] + $GLOBALS['timeout_passed'] @@ -2110,6 +2088,9 @@ + + $GLOBALS['auth_plugin'] + logOut @@ -2128,29 +2109,13 @@ - + $_POST['newTables'] $_POST['newTablesName'] $_POST['pd'] $_POST['pd'] $_POST['pd'] $_POST['tables'] - $db - $db - $db - $db - $db - $db - $db - $db - $db - $db - $db - $db - $db - $db - $db - $db $dependencies $newColumn $newTable @@ -2160,20 +2125,6 @@ $partialDependencies $primary_columns $repeatingColumns - $table - $table - $table - $table - $table - $table - $table - $table - $table - $table - $table - $table - $table - $table $tables $tables $tablesName @@ -2192,64 +2143,66 @@ $tables $tablesName - - $table - + + + + $GLOBALS['cfg']['ShowPhpInfo'] + - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] + $GLOBALS['json'] + $GLOBALS['return_url'] + $GLOBALS['return_url'] $_FILES['import_file']['tmp_name'] $_FILES['import_file']['tmp_name'] $configuration['ThemeDefault'] $configuration['ThemeDefault'] - $json $key - $return_url - $return_url $_FILES['import_file']['error'] @@ -2257,45 +2210,45 @@ $_FILES['import_file']['tmp_name'] + $GLOBALS['json'] + $GLOBALS['params']['lang'] + $GLOBALS['return_url'] $_POST[str_replace('/', '-', (string) $k)] $configuration - $json $key - $params['lang'] - $return_url $v $val - $json + $GLOBALS['json'] $pos - $json + $GLOBALS['json'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] - $tabHash + $GLOBALS['tabHash'] @@ -2320,7 +2273,7 @@ $urlParams['log'] - (int) $cfg['MaxRows'] + (int) $GLOBALS['cfg']['MaxRows'] @@ -2336,10 +2289,13 @@ ['db' => $params['new_db']] - $db + $GLOBALS['db'] + + $GLOBALS['cfg']['AllowUserDropDatabase'] + $database $database @@ -2351,16 +2307,17 @@ build - - $dblist->databases - + + $GLOBALS['cfg']['AllowUserDropDatabase'] + $GLOBALS['db_to_create'] + + $GLOBALS['dblist']->databases $_POST['primary_connection'] ?? null $database['DEFAULT_COLLATION_NAME'] $database['SCHEMA_NAME'] - $dblist->databases $params['sort_by'] $params['sort_order'] $primaryInfo['Do_DB'] @@ -2408,9 +2365,6 @@ $totalStatistics[$key]['raw'] - - $dblist->databases - $hasStatistics $position @@ -2425,26 +2379,24 @@ - - $db - $num_tables - $select_item - $sql_query - $table - $unlim_num_rows + + $GLOBALS['num_tables'] + $GLOBALS['select_item'] + $GLOBALS['unlim_num_rows'] + $GLOBALS['select_item'] $GLOBALS['single_table'] - $select_item - $_SESSION[$SESSION_KEY]['handler'] - $_SESSION[$SESSION_KEY]['handler'] + $_SESSION[$GLOBALS['SESSION_KEY']]['handler'] + $_SESSION[$GLOBALS['SESSION_KEY']]['handler'] - - $_SESSION[$SESSION_KEY] + + $_SESSION[$GLOBALS['SESSION_KEY']] + $_SESSION[$GLOBALS['SESSION_KEY']] $idKey @@ -2452,42 +2404,49 @@ $timeoutPassed - $_SESSION[$SESSION_KEY]['handler']::getIdKey() + $_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getIdKey() - + + $GLOBALS['sql_query'] + + + $GLOBALS['grants'] + $GLOBALS['one_grant'] + $GLOBALS['queries_for_display'] + + + $GLOBALS['db'] + $GLOBALS['message'] + $GLOBALS['password'] ?? '' + $GLOBALS['password'] ?? null + $GLOBALS['queries'] + $GLOBALS['queries'] + $GLOBALS['queries'] + $GLOBALS['queries_for_display'] $_GET['checkprivsdb'] $_GET['checkprivsdb'] $_POST['userGroup'] - $db $db_name ?? '' - $password ?? '' - $password ?? null - $queries - $queries - $queries - $queries_for_display - $sql_query - $sql_query ?? '' - $text_dir - $url_dbname ?? '' - $url_dbname ?? '' - $queries + $GLOBALS['queries'] + $GLOBALS['db'] + $GLOBALS['message'] + $GLOBALS['queries'] $_REQUEST['db'] - $db $db_name - $message - $queries - $export - $title + $GLOBALS['export'] + $GLOBALS['title'] + + $GLOBALS['_add_user_error'] === true + $key @@ -2681,18 +2640,10 @@ $id - - - $db - $table - - - + $column $curr_value - $db - $table $column @@ -2700,11 +2651,9 @@ - + $column $curr_value - $db - $table $_SESSION['tmpval']['relational_display'] @@ -2716,11 +2665,9 @@ - + $column $currentValue - $db - $table $whereClause @@ -2731,55 +2678,56 @@ - + + $GLOBALS['cfg']['AllowUserDropDatabase'] + + + $GLOBALS['cfg']['AllowUserDropDatabase'] + $GLOBALS['db'] + $GLOBALS['db'] + $GLOBALS['db'] + $GLOBALS['db'] + $GLOBALS['db'] + $GLOBALS['disp_message'] ?? null + $GLOBALS['errorUrl'] + $GLOBALS['errorUrl'] + $GLOBALS['extra_data'] ?? null + $GLOBALS['find_real_end'] ?? null + $GLOBALS['message_to_show'] ?? null + $GLOBALS['sql_data'] ?? null + $GLOBALS['sql_query'] + $GLOBALS['sql_query'] + $GLOBALS['table'] + $GLOBALS['table'] $_GET['sql_query'] $_GET['sql_signature'] $_POST['bkm_fields'] $analyzed_sql_results - $complete_query ?? null - $db - $db - $db - $db - $disp_message ?? null - $errorUrl - $errorUrl - $extra_data ?? null - $find_real_end ?? null - $goto - $goto - $import_text ?? null - $message_to_show ?? null - $sql_data ?? null - $sql_query - $sql_query - $table - $table - $table - $table - isset($disp_query) ? $display_query : null + $GLOBALS['ajax_reload']['reload'] $_POST['bkm_fields']['bkm_label'] $_POST['bkm_fields']['bkm_label'] - $ajax_reload['reload'] - $db - $errorUrl - $sql_query - $sql_query - $sql_query - $table - $unlim_num_rows + $GLOBALS['db'] + $GLOBALS['errorUrl'] + $GLOBALS['sql_query'] + $GLOBALS['sql_query'] + $GLOBALS['sql_query'] + $GLOBALS['table'] + $GLOBALS['unlim_num_rows'] + $GLOBALS['errorUrl'] $_POST['bkm_fields']['bkm_label'] - $errorUrl - + + $GLOBALS['regenerate'] + + $_POST['field_input_transformation'][$fieldindex] $_POST['field_input_transformation_options'][$fieldindex] $_POST['field_name'][$fieldindex] @@ -2787,16 +2735,8 @@ $_POST['field_transformation'][$fieldindex] $_POST['field_transformation_options'][$fieldindex] $cfg['DefaultTabTable'] - $db - $db $mimetype - $regenerate - $table - $table - - $url_params - $_POST['field_input_transformation'][$fieldindex] $_POST['field_input_transformation_options'][$fieldindex] @@ -2808,100 +2748,92 @@ $_POST['field_where'] $mimetype + + $GLOBALS['regenerate'] + - - $current_result + $current_row - $db - $disp_message - $insert_mode + + + $GLOBALS['found_unique_key'] + $GLOBALS['where_clause_array'] + $GLOBALS['where_clause_array'] + $GLOBALS['where_clauses'] + + + $GLOBALS['jsvkey'] + + + $GLOBALS['current_result'] + $GLOBALS['disp_message'] + $GLOBALS['insert_mode'] + $GLOBALS['repopulate'] + $GLOBALS['rows'] + $GLOBALS['unsaved_values'] + $GLOBALS['unsaved_values'] + $GLOBALS['where_clause'] + $GLOBALS['where_clause'] ?? null + $GLOBALS['where_clause_array'] + $GLOBALS['where_clause_array'] + $GLOBALS['where_clause_array'] + $GLOBALS['where_clause_array'] + $GLOBALS['where_clauses'] $isUpload $isUpload - $jsvkey - $repopulate - $row_id - $row_id - $rows - $table - $text_dir - $unsaved_values - $unsaved_values - $where_clause - $where_clause ?? null - $where_clause_array - $where_clauses - $urlParams + $GLOBALS['urlParams'] - - $unsaved_values[$row_id] - - - $result[$row_id] - $result[$row_id] - $unsaved_values[$row_id] - $unsaved_values[$row_id] - - - $current_result - $current_row + + $GLOBALS['current_result'] + $GLOBALS['repopulate'] $isUpload - $jsvkey - $repopulate - $row_id - - $biggest_max_file_size - $jsvkey + + $GLOBALS['biggest_max_file_size'] - $current_result + $GLOBALS['current_result'] $isUpload - - $GLOBALS['goto'] - - - $urlParams - + + $GLOBALS['insert_mode'] + $GLOBALS['insert_mode'] + $GLOBALS['result'] + $GLOBALS['rows'] + $GLOBALS['where_clause'] + + + empty($current_row) + is_array($GLOBALS['result']) + - $biggest_max_file_size > 0 + $GLOBALS['biggest_max_file_size'] > 0 + $GLOBALS['where_clause'][] $i_where_clause - $where_clause[] empty($statement->limit) - + $_REQUEST['pos'] $_REQUEST['session_max_rows'] - $db - $db - $db $rows - $sql_query - $sql_query $start - $table - $table - - $url_params - - + $rows $start - $url_params['db'] $_REQUEST['pos'] @@ -2909,16 +2841,14 @@ - + $_POST['field_input_transformation'][$fieldindex] $_POST['field_input_transformation_options'][$fieldindex] $_POST['field_name'][$fieldindex] $_POST['field_name'][$fieldindex] $_POST['field_transformation'][$fieldindex] $_POST['field_transformation_options'][$fieldindex] - $db $mimetype - $table $_POST['field_input_transformation'][$fieldindex] @@ -2930,43 +2860,23 @@ $mimetype - - - $db - $table - - - $urlParams - - - + + $GLOBALS['disp_message'] ?? null + $GLOBALS['disp_query'] ?? null + $GLOBALS['sql_query'] $_REQUEST['pos'] - $db - $db - $db - $disp_message ?? null - $disp_query ?? null - $goto $row - $sql_query - $table - $table - $table + $GLOBALS['sql_query'] $mult_btn $original_sql_query $row $selected - $sql_query - - $db - $table - $selected @@ -2988,35 +2898,25 @@ - - $db - $num_tables - $replaces - $sql_query - $sql_query - $table - $unlim_num_rows + + $GLOBALS['num_tables'] + $GLOBALS['unlim_num_rows'] - - $urlParams - $where_clause + + $GLOBALS['where_clause'] - - $replaces[] - $replaces[] - $GLOBALS['single_table'] + $GLOBALS['where_clause'][] $i_where_clause - $where_clause[] - + $_POST['columnIndex'] $_POST['columnIndex'] $_POST['find'] @@ -3040,15 +2940,10 @@ $column $column $column_types[$i] - $db $row[0] $row[0] $row[1] - $table - - $urlParams - $row[0] $row[0] @@ -3069,14 +2964,10 @@ - + $_GET['transform_key'] $_GET['where_clause'] $_GET['where_clause_sign'] - $db - $db - $db - $table $_GET['transform_key'] @@ -3087,27 +2978,17 @@ - + $_GET['fileFormat'] $_GET['sql_query'] $_GET['sql_signature'] $sqlQuery - $urlParams $visualizationSettings['spatialColumn'] - - ['db' => $db] - $_SESSION['tmpval']['max_rows'] $_SESSION['tmpval']['pos'] - - $urlParams['back'] - $urlParams['goto'] - $urlParams['sql_query'] - $urlParams['sql_signature'] - $sqlQuery $sqlQuery @@ -3122,19 +3003,13 @@ - - $db - $table - - - $urlParams - - $_SESSION[$SESSION_KEY]['handler'] - $_SESSION[$SESSION_KEY]['handler'] + $_SESSION[$GLOBALS['SESSION_KEY']]['handler'] + $_SESSION[$GLOBALS['SESSION_KEY']]['handler'] - - $_SESSION[$SESSION_KEY] + + $_SESSION[$GLOBALS['SESSION_KEY']] + $_SESSION[$GLOBALS['SESSION_KEY']] $idKey @@ -3142,35 +3017,25 @@ $timeoutPassed - $_SESSION[$SESSION_KEY]['handler']::getIdKey() + $_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getIdKey() - + $_POST['index'] - $db - $table - - $urlParams - $formParams['old_index'] $formParams['old_index'] - + $_POST['columns'] $_POST['index'] $_POST['index']['columns']['names'] - $db $fields - $table - - $urlParams - $_POST['index']['Index_choice'] @@ -3185,8 +3050,11 @@ - + + $GLOBALS['create_options']['pack_keys'] + $GLOBALS['create_options']['page_checksum'] ?? '' $GLOBALS['dblist']->databases + $GLOBALS['row_format'] $_POST['db'] $_POST['new_name'] $_POST['new_name'] @@ -3200,32 +3068,22 @@ $_POST['tbl_collation'] $_message $_message - $create_options['pack_keys'] - $create_options['page_checksum'] ?? '' - $db - $row_format - $sql_query - $sql_query - $sql_query - $table - $table - $warning_messages - $table_alters + $GLOBALS['table_alters'] $GLOBALS['showtable']['Row_format'] + $GLOBALS['create_options']['page_checksum'] + $GLOBALS['create_options']['page_checksum'] + $GLOBALS['db'] + $GLOBALS['reread_info'] + $GLOBALS['row_format'] $GLOBALS['showtable'] $GLOBALS['showtable'] - $create_options['page_checksum'] - $create_options['page_checksum'] $databaseList - $db - $reread_info - $row_format getList @@ -3264,12 +3122,18 @@ + + $GLOBALS['containerBuilder'] + $_REQUEST['db'] $_REQUEST['db'] $_REQUEST['table'] $_REQUEST['table'] + + get + @@ -3316,9 +3180,28 @@ - $insert_errors + $GLOBALS['insert_errors'] - + + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['last_messages'] + $GLOBALS['total_affected_rows'] + + + $GLOBALS['error_messages'] + $GLOBALS['last_messages'] + $GLOBALS['mime_map'][$column_name]['input_transformation_options'] + $GLOBALS['total_affected_rows'] + $GLOBALS['total_affected_rows'] + $GLOBALS['warning_messages'] $_POST['db'] $_POST['rel_fields_list'] $_POST['table'] @@ -3328,15 +3211,7 @@ $column_name $current_value $current_value - $db - $db - $db - $db - $db - $error_messages $extra_data - $last_messages - $mime_map[$column_name]['input_transformation_options'] $multi_edit_auto_increment $multi_edit_columns_name $multi_edit_columns_null @@ -3353,49 +3228,38 @@ $relation_field $relation_field $relation_field_value - $table - $table - $table - $table - $table - $table - $total_affected_rows - $total_affected_rows $transformation $transformation[$type] - $urlParams - $warning_messages $where_clause - + $key $key $key - $query_values - $query_values $rownumber - + $_POST['fields_name']['multi_edit'] $extra_data['relations'] $multi_edit_columns[$key] $transformation[$type] $transformation['column_name'] - $urlParams['where_clause'] - + + $GLOBALS['urlParams']['where_clause'][] $extra_data['relations'] $multi_edit_columns[$key] $multi_edit_columns[$key] - $urlParams['after_insert'] - $urlParams['where_clause'] - $mime_map[$column_name] + $GLOBALS['mime_map'][$column_name] $GLOBALS['cfg']['InsertRows'] $GLOBALS['sql_query'] + $GLOBALS['unsaved_values'][$rownumber] + $GLOBALS['urlParams']['after_insert'] + $GLOBALS['urlParams']['where_clause'][] $clauseIsUnique $column_name $column_name @@ -3418,16 +3282,22 @@ $relation_field $relation_field_value $transformation - $unsaved_values[$rownumber] - $urlParams['after_insert'] - $urlParams['where_clause'][] $where_clause - + + get + get + get + get + get + get + get + get + get new $classname() - $mime_map[$column_name]['input_transformation'] + $GLOBALS['mime_map'][$column_name]['input_transformation'] $relation_field_value $where_clause $where_clause @@ -3444,26 +3314,24 @@ $extra_data + + count($GLOBALS['query_values']) <= 0 + - + $_POST['column'] $_POST['db'] $_POST['table'] $_POST['where_clause'] $_POST['where_clause_sign'] - $db $selected_operator - $table $this->columnNames[$column_index] $this->columnNames[$column_index] $this->columnNullFlags[$column_index] $this->originalColumnTypes[$column_index] $type - - $urlParams - $collation $entered_value @@ -3479,27 +3347,23 @@ - + $_GET['sql_query'] ?? true $_POST['delimiter'] - $db - $table - - $url_params - - - $db + $field $selected - $table $field $selected + + empty($GLOBALS['message']) + @@ -3520,15 +3384,20 @@ $selected + + empty($GLOBALS['message']) + - - $db + $selected $selected + + empty($GLOBALS['message']) + @@ -3541,16 +3410,17 @@ - - $db + $field $selected - $table $field $selected + + empty($GLOBALS['message']) + @@ -3618,17 +3488,10 @@ - - $db - $db + $field $selected - $table - $table - - $urlParams - $field $mult_btn @@ -3639,6 +3502,9 @@ $row['Column_name'] + + empty($GLOBALS['message']) + @@ -3747,47 +3613,53 @@ - - $db + $field $selected - $table $field $selected + + empty($GLOBALS['message']) + - - $db + $field $selected - $table $field $selected + + empty($GLOBALS['message']) + - - $db + + $GLOBALS['table_info_num_rows'] + $GLOBALS['tbl_collation'] + $GLOBALS['tbl_is_view'] + $GLOBALS['tbl_is_view'] + + + $GLOBALS['showtable']['Data_free'] + $GLOBALS['showtable']['Data_length'] + $GLOBALS['showtable']['Data_length'] + $GLOBALS['showtable']['Index_length'] + $GLOBALS['showtable']['Index_length'] + $GLOBALS['tbl_collation'] $field['Collation'] ?? '' $field['Extra'] $field['Field'] $field['Type'] - $showtable['Data_free'] - $showtable['Data_length'] - $showtable['Data_length'] + $showtable['Index_length'] - $showtable['Index_length'] - $table - $tbl_collation - - $url_params - - + + $GLOBALS['showtable']['Data_length'] + $GLOBALS['showtable']['Index_length'] + $GLOBALS['showtable']['Rows'] $field['Collation'] $field['Extra'] $field['Field'] @@ -3797,11 +3669,10 @@ $field['Field'] $field['Field'] $field['Type'] - $showtable['Rows'] - $showtable['Data_length'] - $showtable['Index_length'] + $GLOBALS['showtable']['Data_length'] + $GLOBALS['showtable']['Index_length'] $comments_map[$field['Field']] @@ -3809,21 +3680,21 @@ $comments_map[$field['Field']] + $GLOBALS['reread_info'] + $GLOBALS['showtable'] + $GLOBALS['showtable'] $attributes[$rownum] $columns_list[] $field - $reread_info $row_comments[$rownum] - $showtable - $showtable - + + $GLOBALS['showtable']['Data_length'] + $GLOBALS['showtable']['Data_length'] + $GLOBALS['showtable']['Data_length'] + $GLOBALS['showtable']['Index_length'] $displayed_fields[$rownum]->icon $displayed_fields[$rownum]->icon - $showtable['Data_length'] - $showtable['Index_length'] - $showtable['Index_length'] - $showtable['Index_length'] $avg_size @@ -3843,49 +3714,35 @@ - + + $GLOBALS['data'] + $GLOBALS['data'] + $GLOBALS['data'] $_POST['date_from'] $_POST['date_to'] $_POST['users'] $_POST['version'] $_POST['version'] - $data - $data - $data - $db - $table - $text_dir $version - - $urlParams - - $data['date_from'] - $data['date_to'] + $GLOBALS['data']['date_from'] + $GLOBALS['data']['date_to'] + $GLOBALS['data'] $_POST['date_from'] $_POST['date_to'] - $data $version - - $db - $db - $db - $sub_part ?? '' - $table + + $GLOBALS['sub_part'] ?? '' - - $urlParams - ['db' => $db] - - + $_POST['db'] $_POST['table'] $_POST['where_clause'] @@ -3893,11 +3750,8 @@ $columnName $dataLabel $dataLabel - $db - $goto $properties['type'] $selected_operator - $table $this->columnNames[$column_index] $this->columnNames[$column_index] $this->columnNullFlags[$column_index] @@ -3906,9 +3760,8 @@ $uniqueCondition[0] $uniqueCondition[0] - + $key - $urlParams $_POST['criteriaColumnNames'][0] @@ -3956,6 +3809,9 @@ + + $GLOBALS['cfg']['ThemeManager'] + $_POST['set_theme'] $preferences['config_data'] @@ -3985,63 +3841,83 @@ - + + $GLOBALS['cn'] ?? '' + $GLOBALS['mime_map'][$GLOBALS['transform_key']]['mimetype'] + $GLOBALS['mime_map'][$GLOBALS['transform_key']]['transformation_options'] ?? '' + $GLOBALS['mime_type'] + $GLOBALS['mime_type'] + $GLOBALS['srcHeight'] / $GLOBALS['ratioWidth'] + $GLOBALS['srcWidth'] / $GLOBALS['ratioHeight'] + $GLOBALS['where_clause'] $_GET['where_clause_sign'] ?? '' - $cn ?? '' - $db - $mime_map[$transform_key]['mimetype'] - $mime_map[$transform_key]['transformation_options'] ?? '' - $mime_type $option - $srcHeight / $ratioWidth - $srcWidth / $ratioHeight - $table - $where_clause - $mime_map[$transform_key] - $mime_options['charset'] + $GLOBALS['mime_map'][$GLOBALS['transform_key']]['mimetype'] + $GLOBALS['mime_map'][$GLOBALS['transform_key']]['transformation_options'] - $mime_map[$transform_key] - $mime_map[$transform_key] - $mime_map[$transform_key] - $row[$transform_key] - $row[$transform_key] - $row[$transform_key] + $GLOBALS['mime_map'][$GLOBALS['transform_key']] + $GLOBALS['mime_map'][$GLOBALS['transform_key']] + $GLOBALS['mime_map'][$GLOBALS['transform_key']] + $GLOBALS['row'][$GLOBALS['transform_key']] + $GLOBALS['row'][$GLOBALS['transform_key']] + $GLOBALS['row'][$GLOBALS['transform_key']] + + $GLOBALS['mime_map'][$GLOBALS['transform_key']] + $GLOBALS['mime_map'][$GLOBALS['transform_key']] + $GLOBALS['mime_map'][$GLOBALS['transform_key']] + $GLOBALS['row'][$GLOBALS['transform_key']] + $GLOBALS['row'][$GLOBALS['transform_key']] + $GLOBALS['row'][$GLOBALS['transform_key']] + $GLOBALS[$one_request_param] - $mime_type + $GLOBALS['mime_type'] + $GLOBALS['ratioHeight'] + $GLOBALS['ratioWidth'] $option - $ratioHeight - $ratioWidth + $GLOBALS['mime_options']['charset'] ?? '' + $GLOBALS['ratioHeight'] + $GLOBALS['ratioWidth'] + $GLOBALS['where_clause'] $_REQUEST['newHeight'] $_REQUEST['newWidth'] - $mime_options['charset'] ?? '' - $ratioHeight - $ratioWidth - $where_clause + + $GLOBALS['mime_type'] + $GLOBALS['mime_type'] + - $row[$transform_key] - $row[$transform_key] + $GLOBALS['row'][$GLOBALS['transform_key']] + $GLOBALS['row'][$GLOBALS['transform_key']] + + $GLOBALS['mime_map'] + $GLOBALS['transform_key'] + $GLOBALS['transform_key'] + $GLOBALS['transform_key'] + $GLOBALS['transform_key'] + $GLOBALS['transform_key'] + - - $change_password_message['msg'] - $hostname - $msg - $msg->getDisplay() - $password - $username + + $GLOBALS['cfg']['ShowChgPassword'] + + + $GLOBALS['change_password_message']['msg'] + $GLOBALS['msg'] + $GLOBALS['msg']->getDisplay() + $GLOBALS['password'] - $msg - $password + $GLOBALS['msg'] + $GLOBALS['password'] getDisplay @@ -4058,9 +3934,12 @@ - $view['as'] + $GLOBALS['view']['as'] - + + $GLOBALS['containerBuilder'] + + $_GET['db'] $_GET['db'] $_GET['table'] @@ -4073,12 +3952,7 @@ $_POST['view']['name'] $_POST['view']['name'] $createView - $db - $db - - ['db' => $db] - $_POST['view']['as'] $_POST['view']['as'] @@ -4087,23 +3961,19 @@ $_POST['view']['name'] $_POST['view']['name'] - - $urlParams['back'] - $urlParams['db'] - $urlParams['goto'] - $urlParams['reload'] - - + + $GLOBALS['sql_query'] + $GLOBALS['view']['as'] + $GLOBALS['view']['as'] + $GLOBALS['view']['definer'] + $GLOBALS['view']['name'] + $GLOBALS['view']['sql_security'] + $GLOBALS['view']['with'] $createView - $sql_query - $urlParams['db'] - $view['as'] - $view['as'] - $view['definer'] - $view['name'] - $view['sql_security'] - $view['with'] + + get + $_POST['view']['algorithm'] $_POST['view']['as'] @@ -4112,7 +3982,7 @@ $_POST['view']['with'] - empty($view['as']) && is_string($createView) + empty($GLOBALS['view']['as']) && is_string($createView) is_string($createView) @@ -4120,15 +3990,15 @@ - + $_POST['new_name'] - $db - $sql_query - $table - $warning_messages + + $GLOBALS['cfg']['blowfish_secret'] + $GLOBALS['cfg']['blowfish_secret'] + $matches[1] @@ -4144,15 +4014,13 @@ $i $i - - $GLOBALS[$post_key] + $GLOBALS['cfg']['TrustedProxies'][$direct_ip] $one_post_pattern $path[$depth + 1] $query - - $post_key + $post_key @@ -4191,8 +4059,8 @@ string|bool - addError get + setParameter $secret @@ -4202,12 +4070,20 @@ $direct_ip $empty + + setParameter + + + setParameter + + + setParameter + (string) gmdate(DATE_RFC1123) - + $GLOBALS['config'] !== null - isset($dbi, $GLOBALS['config']) @@ -4321,9 +4197,6 @@ $key $key - - get - @@ -4662,7 +4535,15 @@ - + + $GLOBALS['errors'] + $GLOBALS['errors'] + + + $GLOBALS['errors'] + $GLOBALS['errors'] + $GLOBALS['errors'] + $GLOBALS['errors'] $_POST['item_comment'] $_POST['item_definer'] $_POST['item_definer'] @@ -4678,32 +4559,16 @@ $_POST['item_starts'] $_REQUEST['item_name'] $_REQUEST['item_name'] - $db - $db - $db - $db - $db - $errors - $errors - $errors - $errors $event['name'] $itemName - $message $event['name'] - - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] + + $GLOBALS['errors'][] + $GLOBALS['errors'][] + $GLOBALS['errors'][] $event @@ -4723,9 +4588,6 @@ $retval['item_type'] $string - - isSuccess - $_POST['item_definition'] $_POST['item_interval_field'] @@ -4734,6 +4596,9 @@ $create_item + + $GLOBALS['errors'] + @@ -4947,7 +4812,12 @@ - + + $GLOBALS['errors'] + $GLOBALS['errors'] + + + $GLOBALS['errors'] $_GET['item_name'] $_GET['item_name'] $_GET['item_name'] @@ -4973,14 +4843,6 @@ $_POST['item_type'] $_POST['item_type'] $_REQUEST['item_name'] - $db - $db - $db - $db - $db - $db - $db - $errors $itemDefiner $itemName $itemParamOpsNum[$i] @@ -4994,7 +4856,6 @@ $itemReturnType $itemReturnType $itemType - $message $newErrors $routine $routine['ROUTINE_TYPE'] @@ -5072,16 +4933,7 @@ $routine['item_param_type'][$i] $routine['item_param_type'][$routine['item_num_params'] - 1] - - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] + $params[$i]['htmlentities'][] $retval['item_param_dir'][$key] $routine['item_param_dir'][] @@ -5158,9 +5010,6 @@ $value $value - - isSuccess - $_POST['funcs'][$routine['item_param_name'][$i]] $_POST['item_name'] @@ -5234,7 +5083,15 @@ - + + $GLOBALS['errors'] + $GLOBALS['errors'] + + + $GLOBALS['errors'] + $GLOBALS['errors'] + $GLOBALS['errors'] + $GLOBALS['errors'] $_POST['item_definer'] $_POST['item_definer'] $_POST['item_name'] @@ -5246,25 +5103,9 @@ $_REQUEST['item_name'] $_REQUEST['item_name'] $create_item - $db - $db - $db - $db - $db - $db - $errors - $errors - $errors - $errors $exportData $itemName $itemName - $message - $table - $table - $table - $table - $table $temp['action_timing'] @@ -5281,16 +5122,10 @@ $value['name'] $value['name'] - - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] - $errors[] + + $GLOBALS['errors'][] + $GLOBALS['errors'][] + $GLOBALS['errors'][] $create_item @@ -5314,9 +5149,6 @@ $value $value - - isSuccess - $_POST['item_definition'] $_POST['item_event'] @@ -5331,6 +5163,9 @@ $trigger['create'] $trigger['drop'] + + $GLOBALS['errors'] + @@ -5567,15 +5402,19 @@ + + $GLOBALS['containerBuilder'] + $urlParams - - $is_table - $urlParams['message'] + + $GLOBALS['is_table'] $urlParams['show_as_php'] - $urlParams['sql_query'] + + get + @@ -5651,7 +5490,8 @@ $added[$orgFullTableName] $multiOrderUrlParams - + + $GLOBALS['theme'] $delUrlParams @@ -6176,6 +6016,15 @@ $exportPlugin === null + + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['save_filename'] + $GLOBALS['save_filename'] + $GLOBALS['time_start'] + $GLOBALS['time_start'] + $memoryLimit @@ -6240,6 +6089,11 @@ $view $views[] + + get + get + get + $currentDb $table @@ -6259,11 +6113,21 @@ + + $GLOBALS['cfg']['Export'] + $GLOBALS['cfg']['Export'] + $GLOBALS['cfg']['Export'] + $GLOBALS['cfg']['Export'] + $_POST['filename_template'] ?? null $currentDb - + + $GLOBALS['cfg']['Export']['compression'] + $GLOBALS['cfg']['Export']['file_template_database'] + $GLOBALS['cfg']['Export']['file_template_server'] + $GLOBALS['cfg']['Export']['file_template_table'] $_SESSION['tmpval']['aliases'] @@ -6271,11 +6135,11 @@ $currentDb $selectedCompression - - getUserValue - getUserValue - getUserValue - + + $GLOBALS['cfg']['Export'] + $GLOBALS['cfg']['Export'] + $GLOBALS['cfg']['Export'] + @@ -6381,18 +6245,13 @@ - - $db - $table - $params - + $info $params['checkprivsdb'] $params['checkprivstable'] - $params['server'] $params['single_table'] $params['viewing_mode'] $subObject @@ -6414,9 +6273,6 @@ isset($GLOBALS['db']) && is_scalar($GLOBALS['db']) isset($GLOBALS['table']) && is_scalar($GLOBALS['table']) - - ! isset($dbi) - @@ -7246,30 +7102,38 @@ - - $db - $db ?? '' + + $GLOBALS['cfg']['CSPAllow'] + $GLOBALS['cfg']['CaptchaCsp'] + $GLOBALS['theme'] + + + $cspAllow + $cspAllow + $cspAllow + $cspAllow + $cspAllow + $cspAllow + $cspAllow + $cspAllow + $cspAllow $message - $table - $table ?? '' $value $params - + $GLOBALS['buffer_message'] $bufferMessage + $cspAllow $message $pftext $value - - isset($dbi) - - - false - + + $GLOBALS['cfg']['CaptchaCsp'] + @@ -7280,11 +7144,10 @@ $server['ssl'] $server['ssl_verify'] - + $GLOBALS['special_message'] $GLOBALS['special_message'] $alt - $cfg['MaxCharactersInDisplayedSQL'] $defaultFunction $field['True_Type'] $queryBase @@ -7307,9 +7170,9 @@ $key - $cfg['DefaultFunctions']['FUNC_' . $currentClass] - $cfg['DefaultFunctions']['FUNC_UUID'] - $cfg['DefaultFunctions']['first_timestamp'] + $GLOBALS['cfg']['DefaultFunctions']['FUNC_' . $currentClass] + $GLOBALS['cfg']['DefaultFunctions']['FUNC_UUID'] + $GLOBALS['cfg']['DefaultFunctions']['first_timestamp'] $_SESSION['Import_message']['go_back_url'] @@ -7345,6 +7208,10 @@ $defaultFunction + + $GLOBALS['cfg']['DefaultFunctions'] + $GLOBALS['cfg']['DefaultFunctions'] + (int) $GLOBALS['cfg']['MaxRows'] (string) $GLOBALS['db'] @@ -7359,28 +7226,44 @@ - + + $GLOBALS['charset_conversion'] + $GLOBALS['charset_of_file'] + $GLOBALS['executed_queries'] + $GLOBALS['go_sql'] + $GLOBALS['go_sql'] + $GLOBALS['max_sql_len'] + $GLOBALS['maximum_time'] + $GLOBALS['msg'] + $GLOBALS['read_multiply'] + $GLOBALS['reload'] + $GLOBALS['run_query'] + $GLOBALS['skip_queries'] + $GLOBALS['sql_query_disabled'] + $GLOBALS['sql_query_disabled'] + $GLOBALS['sql_query_disabled'] + $GLOBALS['timeout_passed'] + $GLOBALS['timestamp'] + + + $GLOBALS['charset_of_file'] + $GLOBALS['import_run_buffer']['full'] + $GLOBALS['import_run_buffer']['sql'] + $GLOBALS['import_run_buffer']['sql'] + $GLOBALS['import_run_buffer']['sql'] + $GLOBALS['reload'] + $GLOBALS['sql_query'] $active $additionalSql[$i] $additionalSql[$i] $additionalSql[$i] - $charset_of_file - $db $fulls[$i] - $import_run_buffer - $import_run_buffer - $import_run_buffer['full'] - $import_run_buffer['sql'] - $import_run_buffer['sql'] - $import_run_buffer['sql'] $queries[$i] - $reload $size $size $size $sqlDelimiter $sqlQuery - $sql_query $table $table[self::COL_NAMES] $table[self::ROWS] @@ -7401,16 +7284,13 @@ $tables[$i][self::TBL_NAME] $tables[$n][self::TBL_NAME] - + $analyses[$i][self::FORMATTEDSQL][$colCount] $analyses[$i][self::SIZES] $analyses[$i][self::TYPES] $analyses[$i][self::TYPES] $analyses[$i][self::TYPES] $fulls[$i] - $import_run_buffer['full'] - $import_run_buffer['full'] - $import_run_buffer['full'] $queries[$i] $table[self::ROWS][$j][$i] $table[self::TBL_NAME] @@ -7431,7 +7311,7 @@ $tables[$n][self::TBL_NAME] - $my_die[] + $GLOBALS['my_die'][] $sqlData['valid_full'][] $sqlData['valid_sql'][] $sqlData['valid_sql'][] @@ -7439,33 +7319,31 @@ $typeArray[$analyses[$i][self::TYPES][$j]] - + + $GLOBALS['executed_queries'] + $GLOBALS['max_sql_len'] $GLOBALS['offset'] + $GLOBALS['read_multiply'] + $GLOBALS['skip_queries'] + $GLOBALS['sql_query'] $active $cellValue $charset $collation - $complete_query $count $createDb - $display_query - $executed_queries $fulls $importPlugin - $max_sql_len $queries $queries - $read_multiply $size $size - $skip_queries $sqlData['valid_full'][] $sqlData['valid_queries'] $sqlData['valid_queries'] $sqlData['valid_sql'][] $sqlDelimiter $sqlQuery - $sql_query $table $table @@ -7476,31 +7354,30 @@ getExtension getProperties - + + $GLOBALS['executed_queries'] + $GLOBALS['import_run_buffer']['full'] + $GLOBALS['import_run_buffer']['full'] + $GLOBALS['import_run_buffer']['full'] + $GLOBALS['import_run_buffer']['full'] + $GLOBALS['maximum_time'] + $GLOBALS['msg'] + $GLOBALS['read_multiply'] + $GLOBALS['read_multiply'] + $GLOBALS['skip_queries'] + $GLOBALS['timestamp'] $charset $charset $collation $collation - $complete_query - $display_query - $executed_queries $importPlugin->getProperties()->getExtension() - $maximum_time - $msg - $read_multiply - $read_multiply $size $size $size[self::D] $size[self::D] > $oldD ? $size[self::D] : $oldD $size[self::M] > $oldM ? $size[self::M] : $oldM - $skip_queries $sqlData['valid_queries'] $sqlData['valid_queries'] - $sql_query - $sql_query - $sql_query - $timestamp $size[self::FULL] @@ -7522,6 +7399,12 @@ $additionalSql[$i] + + $GLOBALS['executed_queries'] + $GLOBALS['go_sql'] + $GLOBALS['max_sql_len'] + $GLOBALS['run_query'] + (string) $cell (string) $cell @@ -7636,7 +7519,7 @@ - + $_POST['fields']['multi_edit'] $_POST['fields']['multi_edit'][$rownumber][$key] $backupField @@ -7648,8 +7531,6 @@ $column['Default'] $column['Default'] $column['Extra'] - $column['Extra'] - $column['Extra'] $column['Field'] $column['Field'] $column['Field'] @@ -7672,9 +7553,6 @@ $column['pma_type'] $column['pma_type'] $column['pma_type'] - $column['pma_type'] - $column['pma_type'] - $column['pma_type'] $commentsMap[$column['Field']] $currCellEditedValues[$columnName] $currentRow[$column['Field']] @@ -7858,9 +7736,13 @@ $remote_ip - - is_array($rules) - + + $rule + + + $rule + $rules + @@ -8036,14 +7918,23 @@ + + $GLOBALS['cfg']['NavigationDisplayLogo'] + $GLOBALS['cfg']['NavigationDisplayServers'] + $GLOBALS['cfg']['NavigationLogoLink'] + $GLOBALS['cfg']['NavigationLogoLinkWindow'] + $GLOBALS['cfg']['NavigationTreeAutoexpandSingleDb'] + $GLOBALS['cfg']['NavigationTreePointerEnable'] + $GLOBALS['cfg']['NavigationWidth'] + $GLOBALS['theme'] + $hidden $hidden - - (string) $cfg['NavigationLogoLink'] - (string) $cfg['NavigationLogoLink'] - + + $GLOBALS['cfg']['NavigationDisplayServers'] + @@ -8539,7 +8430,7 @@ - + $_POST['comment'] $_POST['db_collation'] ?? '' $_POST['new_auto_increment'] @@ -8562,9 +8453,6 @@ $arr['foreign_field'] $arr['foreign_field'] $arr['foreign_table'] - $db - $db - $db $event_name $foreignTable $foreignTable @@ -8574,12 +8462,6 @@ $old_priv $one_query $procedure_name - $table - $table - $table - $table - $table - $table $this_what ?? 'data' $trigger['create'] $view @@ -8662,7 +8544,7 @@ build - + $_POST['new_pack_keys'] $old_priv[$i] $old_priv[0] @@ -8697,7 +8579,6 @@ $old_priv[7] $old_priv[7] $old_priv[7] - $table $trigger['create'] @@ -9017,17 +8898,9 @@ $tmp_host $value - - issetCookie - issetCookie - removeCookie - removeCookie - removeCookie - removeCookie - (int) $GLOBALS['cfg']['LoginCookieStore'] - (string) $conn_error + (string) $GLOBALS['conn_error'] @@ -9077,6 +8950,10 @@ + + $GLOBALS['cfg']['Server']['AllowNoPassword'] + $GLOBALS['cfg']['Server']['AllowRoot'] + $redirect_url @@ -9086,9 +8963,6 @@ $redirect_url - - issetCookie - @@ -9108,44 +8982,32 @@ - + + $GLOBALS['what'] + $GLOBALS['what'] + $GLOBALS['what'] + $GLOBALS['what'] + + $col_as - $csv_enclosed - $csv_enclosed - $csv_enclosed - $csv_escaped - $csv_separator - $csv_terminated - $csv_terminated $col_as - + + $GLOBALS['what'] + $GLOBALS['what'] + $GLOBALS['what'] $col_as - $csv_enclosed - $csv_enclosed - $csv_enclosed - $csv_enclosed - $csv_enclosed - $csv_enclosed - $csv_escaped - $csv_escaped - $csv_escaped - $csv_escaped - $csv_separator - $csv_separator - $csv_terminated - $csv_terminated - $what - $what - $what - $GLOBALS[$what . '_null'] + $GLOBALS[$GLOBALS['what'] . '_null'] + + $GLOBALS['what'] + $col_alias $col_as @@ -9195,9 +9057,8 @@ $unique_keys[] $value - - $charset ?? 'utf-8' - $what + + $GLOBALS['what'] $do_comments @@ -9227,12 +9088,6 @@ $col_as $columns[$i] - - $crlf - $crlf - $crlf - $crlf - @@ -9241,12 +9096,10 @@ $mime_map[$field_name]['mimetype'] $row['Type'] - + $key['Column_name'] $key['Non_unique'] $mime_map[$field_name]['mimetype'] - $plugin_param['export_type'] - $plugin_param['single_table'] $aliases[$db]['tables'][$table]['columns'][$col_as] @@ -9261,20 +9114,9 @@ $type $unique_keys[] - + $col_as $comments[$field_name] - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf $row['Default'] ?? '' $type @@ -9286,6 +9128,10 @@ numFields + + $GLOBALS['plugin_param']['export_type'] + $GLOBALS['plugin_param']['single_table'] + $record[$columns[$i]] @@ -9324,8 +9170,11 @@ - $GLOBALS[$what . '_null'] + $GLOBALS[$GLOBALS['what'] . '_null'] + + $GLOBALS['what'] + $col_as @@ -9333,8 +9182,8 @@ $col_as - $what - $what + $GLOBALS['what'] + $GLOBALS['what'] $row[$j] @@ -9346,8 +9195,11 @@ - $GLOBALS[$what . '_null'] + $GLOBALS[$GLOBALS['what'] . '_null'] + + $GLOBALS['what'] + $col_as $col_as @@ -9364,10 +9216,8 @@ $trigger['event_manipulation'] $trigger['name'] - + $mime_map[$field_name]['mimetype'] - $plugin_param['export_type'] - $plugin_param['single_table'] $trigger['action_timing'] $trigger['definition'] $trigger['event_manipulation'] @@ -9394,16 +9244,20 @@ $trigger + $GLOBALS['what'] + $GLOBALS['what'] $rfield $rtable - $what - $what $do_comments $do_mime $do_relation + + $GLOBALS['plugin_param']['export_type'] + $GLOBALS['plugin_param']['single_table'] + $col_as $row[$j] @@ -9454,10 +9308,48 @@ $GLOBALS['asfile'] $GLOBALS['sql_if_not_exists'] - + $GLOBALS['sql_auto_increments'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_indexes'] + + + $GLOBALS['sql_auto_increments'] + $GLOBALS['sql_auto_increments'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] + $GLOBALS['sql_backquotes'] $GLOBALS['sql_header_comment'] $GLOBALS['sql_indexes'] + $GLOBALS['sql_indexes'] $GLOBALS['table_data'] $colAlias $colAlias @@ -9479,30 +9371,6 @@ $rel['foreign_table'] $routine $routine - $sql_auto_increments - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_backquotes - $sql_constraints - $sql_indexes $table $token->value $trigger['create'] @@ -9514,7 +9382,7 @@ $indexes $indexesFulltext - + $aliases[$oldDatabase]['tables'] $columnAliases[$column['name']] $definition['Type'] @@ -9522,11 +9390,6 @@ $oneKey['index_list'] $oneKey['ref_index_list'] $oneKey['ref_table_name'] - $plugin_param['export_type'] - $plugin_param['export_type'] - $plugin_param['export_type'] - $plugin_param['export_type'] - $plugin_param['single_table'] $rel['foreign_field'] $rel['foreign_table'] $trigger['create'] @@ -9570,46 +9433,19 @@ $val $values[$val] - + $column['Collation'] $column['Type'] - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf $definition['Type'] $statement->entityOptions->has('AUTO_INCREMENT') $tmpUniqueCondition $trigger['drop'] + + $GLOBALS['plugin_param']['export_type'] + $GLOBALS['plugin_param']['export_type'] + $GLOBALS['plugin_param']['single_table'] + Context::escape($field->name) @@ -9617,14 +9453,14 @@ Context::escape($alias) + $GLOBALS['dbi']->getDefinition($db, $type, $routine) $createQuery - $dbi->getDefinition($db, $type, $routine) $tableAlias $tableAlias $tableAlias - $dbi->getDefinition($db, 'EVENT', $eventName) + $GLOBALS['dbi']->getDefinition($db, 'EVENT', $eventName) $field->key->columns @@ -9650,6 +9486,9 @@ $value + + $GLOBALS['what'] + $col_alias $col_as @@ -9697,11 +9536,11 @@ $unique_keys[] + $GLOBALS['what'] + $GLOBALS['what'] $trigger['action_timing'] $trigger['event_manipulation'] $trigger['name'] - $what - $what $do_comments @@ -9723,17 +9562,17 @@ - + + $GLOBALS['tables'] + + $code $col_as - $db - $db $db_charset $db_collation $name $table $table - $table $trigger['name'] @@ -9758,43 +9597,6 @@ $table $trigger - - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $crlf - $sql $table_alias @@ -9821,7 +9623,13 @@ + + $GLOBALS['maxY'] + $GLOBALS['maxY'] + $GLOBALS['maxY'] + + $GLOBALS['maxY'] - $this->tMargin $col_as $column['Type'] $fullwidth + $l @@ -9860,7 +9668,6 @@ $lh $lh $lh - $maxY - $this->tMargin $t $t $t @@ -9929,6 +9736,7 @@ $this->pagedim[$this->page] + $GLOBALS['maxY'] $availableWidth $col_as $current_page @@ -9979,7 +9787,6 @@ $lh $lh $lh - $maxY $maxpage $maxpage $maxpage @@ -10018,6 +9825,7 @@ $y + $GLOBALS['maxY'] $availableWidth $fullwidth $fullwidth @@ -10065,7 +9873,6 @@ $this->sColWidth $this->tMargin $this->tMargin - $this->tMargin $this->w $this_page_orm $width @@ -10161,24 +9968,23 @@ $nameArray === false $nameArray === false - + + $GLOBALS['csv_columns'] + + + $GLOBALS['csv_new_line'] + $GLOBALS['errorUrl'] + + + $GLOBALS['csv_new_line'] $_REQUEST['csv_new_db_name'] $_REQUEST['csv_new_tbl_name'] $col_name $columnNames - $csv_columns - $csv_enclosed - $csv_escaped - $csv_new_line - $csv_terminated - $db $db_name $field['Field'] - $import_file_name - $message->getMessage() $newDb $options - $table $result @@ -10210,9 +10016,6 @@ array string - - getMessage - $max_lines $max_lines_constraint @@ -10228,25 +10031,43 @@ $ch + + $GLOBALS['timeout_passed'] + $analyze + + (string) $GLOBALS['db'] + - - $import_file - $ldi_columns - $ldi_enclosed - $ldi_escaped - $table + + $GLOBALS['charset_conversion'] + $GLOBALS['ldi_columns'] + $GLOBALS['ldi_enclosed'] + $GLOBALS['ldi_escaped'] + $GLOBALS['ldi_new_line'] + $GLOBALS['ldi_terminated'] + $GLOBALS['skip_queries'] + + + $GLOBALS['ldi_columns'] + $GLOBALS['ldi_enclosed'] + $GLOBALS['ldi_escaped'] - - $ldi_new_line - $ldi_terminated - $skip_queries + + $GLOBALS['ldi_terminated'] + $GLOBALS['skip_queries'] + + $GLOBALS['ldi_new_line'] + + + $GLOBALS['timeout_passed'] + $cell $cell @@ -10275,18 +10096,20 @@ $analyze - ! $finished - $finished + ! $GLOBALS['finished'] + $GLOBALS['finished'] $analyses - + + $GLOBALS['timeout_passed'] + + $col_names $col_names - $db $db_name $max_cols $options @@ -10339,15 +10162,16 @@ - - $buffer + + $GLOBALS['buffer'] + $GLOBALS['importHandle'] + + + $GLOBALS['importHandle'] $dbf_file_name $dbf_file_path $dbf_file_path $extracted - $importHandle - $import_file - $import_file $result $shp->getDBFHeader() @@ -10363,24 +10187,23 @@ $record->dbfData[$c[0]] - + + $GLOBALS['message'] + $GLOBALS['message'] + $GLOBALS['message'] $analyses[] $c $col_names[] - $db_name $dbfHeader $dbf_file_name $dbf_file_name $extracted - $message - $message - $message $record $result $temp - $buffer + $GLOBALS['buffer'] $dbf_file_name $temp @@ -10388,6 +10211,13 @@ $record->dbfData $record->shpData + + $GLOBALS['buffer'] + + + (string) $GLOBALS['db'] + (string) $GLOBALS['db'] + $null_param @@ -10407,16 +10237,21 @@ $val $values[$val] + + $GLOBALS['timeout_passed'] + $GLOBALS['timeout_passed'] + - - $db_name + + $GLOBALS['timeout_passed'] + + $namespaces['pma'] $namespaces['pma'] ?? null - + $db_attr - $db_name @@ -10425,58 +10260,55 @@ $tables[$i][Import::TBL_NAME] + + (string) $GLOBALS['db'] + $val3 + + + $GLOBALS['eof'] + + - $_SESSION[$SESSION_KEY] + $_SESSION[$GLOBALS['SESSION_KEY']] - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] - - $_SESSION[$SESSION_KEY] - $_SESSION[$SESSION_KEY] - $_SESSION[$SESSION_KEY] - array|null - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] - $_SESSION[$SESSION_KEY] + $_SESSION[$GLOBALS['SESSION_KEY']] - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] $ret['finished'] $ret['total'] - $_SESSION[$SESSION_KEY][$id] - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] $ret['complete'] $ret['finished'] $ret['finished'] $ret['percent'] $ret['total'] - - $_SESSION[$SESSION_KEY] - $_SESSION[$SESSION_KEY] - $_SESSION[$SESSION_KEY] - $_SESSION[$SESSION_KEY] - - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] $ret @@ -10489,10 +10321,10 @@ - $_SESSION[$SESSION_KEY] + $_SESSION[$GLOBALS['SESSION_KEY']] - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] $ret['finished'] $ret['total'] $status['bytes_processed'] @@ -10500,22 +10332,16 @@ $status['done'] - $_SESSION[$SESSION_KEY][$id] - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] $ret['complete'] $ret['complete'] $ret['finished'] $ret['percent'] $ret['total'] - - $_SESSION[$SESSION_KEY] - $_SESSION[$SESSION_KEY] - $_SESSION[$SESSION_KEY] - $_SESSION[$SESSION_KEY] - - $_SESSION[$SESSION_KEY][$id] + $_SESSION[$GLOBALS['SESSION_KEY']][$id] $ret $ret['complete'] $ret['finished'] @@ -11290,15 +11116,19 @@ + + $GLOBALS['fields_meta'] + $GLOBALS['row'] + $cn $options['wrapper_params'] - $row[$pos] + $GLOBALS['row'][$pos] - $row[$pos] + $GLOBALS['row'][$pos] $cn @@ -11503,10 +11333,6 @@ $url - - get - isHttps - @@ -11814,9 +11640,6 @@ $status[0][$key] - - $urlParams['primary_connection'] - @@ -11829,12 +11652,11 @@ (string) $GLOBALS['db'] (string) $GLOBALS['table'] - + is_scalar($GLOBALS['db']) is_scalar($GLOBALS['table']) isset($GLOBALS['db']) && is_scalar($GLOBALS['db']) isset($GLOBALS['table']) && is_scalar($GLOBALS['table']) - isset($dbi) @@ -11942,7 +11764,7 @@ array - + $GLOBALS['dbname'] $_GET['initial'] $_GET['initial'] @@ -11980,7 +11802,6 @@ $exportUser $hashedPassword $hostname - $hostname $oldUserGroup $paramDbName $paramDbName @@ -12012,7 +11833,6 @@ $updQuery $user $username - $username $queries @@ -12381,7 +12201,7 @@ $serverVarValues[$dataPoint['name']] $statusVarValues[$dataPoint['name']] - + $chartNodes $chartNodes $cpuload @@ -12401,7 +12221,6 @@ $ret['idle'] $ret['value'] $ret['value'] - $return['affectedRows'] loadavg @@ -12761,6 +12580,9 @@ (bool) $GLOBALS['cfg']['ShowSQL'] + + is_array($GLOBALS['showtable']) + @@ -12869,10 +12691,14 @@ isset($this->uiprefs) isset($this->uiprefs) + + $GLOBALS['errorUrl'] + $tableAutoIncrement ?? '' + $GLOBALS['errorUrl'] $GLOBALS['sql_auto_increments'] $GLOBALS['sql_indexes'] $_POST['constraint_name'][$masterFieldMd5] @@ -12886,7 +12712,6 @@ $createTable $eachCol $eachCol - $errorUrl $existrelForeign[$masterFieldMd5]['constraint'] $existrelForeign[$masterFieldMd5]['constraint'] $existrelForeign[$masterFieldMd5]['ref_db_name'] @@ -13150,7 +12975,8 @@ - + + $GLOBALS['mime_map'][$columnMeta['Field']] ?? [] $available_mime[$mime_type . '_file'][$mimekey] $columnMeta $columnMeta['Default'] @@ -13161,26 +12987,13 @@ $columnMeta['Field'] $columnMeta['Type'] $columnMeta['Type'] - $db - $db - $db - $db - $db - $db $form_params['db'] $form_params['table'] - $mime_map[$columnMeta['Field']] ?? [] - $table - $table - $table - $table - $table - $table $type Util::getValueByKey($_POST, "field_key.${columnNumber}", '') Util::getValueByKey($extracted_columnspec, 'attribute', '') - + $available_mime[$mime_type . '_file'][$mimekey] $columnMeta['Default'] $columnMeta['Extra'] @@ -13190,9 +13003,8 @@ $columnMeta['Type'] $columnMeta['column_status']['isEditable'] $columnMeta['column_status']['isEditable'] - $mime_map[$columnMeta['Field']] - + $available_mime[$mime_type . '_file_quoted'][$mimekey] $columnMeta['Default'] $columnMeta['DefaultType'] @@ -13207,15 +13019,14 @@ $columnMeta['DefaultValue'] $columnMeta['Expression'] $columnMeta['Type'] - $mime_map[$columnMeta['Field']] + $GLOBALS['mime_map'][$columnMeta['Field']] + $GLOBALS['mime_map'][$columnMeta['Field']] $comments_map[$columnMeta['Field']] $expressions[$columnMeta['Field']] - $mime_map[$columnMeta['Field']] - $mime_map[$columnMeta['Field']] - + $columnMeta $columnMeta['Default'] $columnMeta['Default'] @@ -13230,7 +13041,6 @@ $form_params['field_name[' . $columnNumber . ']'] $form_params['field_orig[' . $columnNumber . ']'] $form_params['selected[' . $o_fld_nr . ']'] - $form_params['table'] $length $length $o_fld_val @@ -13239,12 +13049,18 @@ + + $GLOBALS['containerBuilder'] + $oldIndexName $oldIndexName + + get + @@ -13309,8 +13125,17 @@ + + $GLOBALS['containerBuilder'] + + + $GLOBALS['containerBuilder'] + + + $GLOBALS['cfg']['environment'] + - is_array($cfg) + is_array($GLOBALS['cfg']) static::$twig !== null @@ -13333,13 +13158,12 @@ string|false - - getCookie - issetCookie - - $config->getCookie($name) + $GLOBALS['config']->getCookie($name) + + $GLOBALS['config']->getCookie($name) + $this->themes @@ -13368,6 +13192,9 @@ null null + + $GLOBALS['export_type'] + (int) $version - 1 @@ -13604,6 +13431,11 @@ $row['comment'] + + + $GLOBALS['theme'] + + $cls::$id @@ -13670,12 +13502,6 @@ string - - get - get - getCookie - getCookie - $html_separator $separator @@ -13684,8 +13510,23 @@ (string) $db (string) $table + + $GLOBALS['config'] !== null + + + + + $GLOBALS['containerBuilder'] + + + get + set + + + $GLOBALS['auth_plugin'] + $_POST['pma_pw'] $_POST['pma_pw'] @@ -13741,7 +13582,8 @@ $group[$groupName]['tab' . $sep . 'count'] - + + $GLOBALS['cfg']['SkipLockedTables'] $group[$groupName]['is' . $sep . 'group'] $group[$groupName]['tab' . $sep . 'count'] $group[$tableName] @@ -13934,9 +13776,8 @@ (int) $timestamp (int) $timestamp - + $columnsList !== null - isset($dbi) @@ -13971,12 +13812,20 @@ + + $GLOBALS['cfg']['ProxyPass'] + $GLOBALS['cfg']['ProxyUrl'] + $GLOBALS['cfg']['ProxyUser'] + $httpStatus - + $context['http']['content'] $httpStatus + $this->proxyPass + $this->proxyUrl + $this->proxyUser string|bool|null @@ -14000,9 +13849,6 @@ $_SESSION['cache'][self::key()][$name] $value - - $server - @@ -14045,9 +13891,6 @@ $response - - isset($dbi) - @@ -14063,6 +13906,11 @@ $value + + + $cfg + + $argumentName @@ -14090,9 +13938,6 @@ (string) $GLOBALS['lang'] - - $isMinimumCommon - @@ -14104,6 +13949,28 @@ $http_response_code_param + + + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + + + get + get + get + get + get + set + set + setAlias + setAlias + + array @@ -14340,6 +14207,14 @@ array + + + $GLOBALS['containerBuilder'] + + + get + + $json @@ -14352,6 +14227,9 @@ + + $GLOBALS['containerBuilder'] + $currentTable $result @@ -14400,8 +14278,25 @@ [$currentTable, , , , , , $sumSize] [$currentTable] + + get + setParameter + setParameter + + + + + $GLOBALS['containerBuilder'] + + + get + + + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $responseMessage $responseMessage @@ -14410,6 +14305,32 @@ $responseMessage $responseMessage + + get + get + + + + + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + + + get + get + get + get + setParameter + setParameter + setParameter + setParameter + setParameter + setParameter + setParameter + setParameter + @@ -14486,6 +14407,34 @@ [$formattedValue, $isHtmlFormatted] + + + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + + + get + get + setParameter + setParameter + setParameter + setParameter + + + + + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + + + get + get + setParameter + setParameter + setParameter + setParameter + + method @@ -14495,6 +14444,16 @@ expects + + + $GLOBALS['containerBuilder'] + + + get + setParameter + setParameter + + method @@ -14513,9 +14472,29 @@ expects + + + $GLOBALS['containerBuilder'] + $GLOBALS['containerBuilder'] + + + get + get + setParameter + setParameter + setParameter + setParameter + + - + + $GLOBALS['containerBuilder'] + + + get method + setParameter + setParameter will with @@ -14564,12 +14543,6 @@ array array - - set - set - set - set - $page @@ -14591,13 +14564,6 @@ $_SESSION['URLQueryEncryptionSecretKey'] - - set - set - set - set - set - @@ -14828,6 +14794,17 @@ + + $GLOBALS['cfg']['Export']['as_separate_files'] + $GLOBALS['cfg']['Export']['asfile'] + $GLOBALS['cfg']['Export']['charset'] + $GLOBALS['cfg']['Export']['lock_tables'] + $GLOBALS['cfg']['Export']['onserver'] + $GLOBALS['cfg']['Export']['onserver_overwrite'] + $GLOBALS['cfg']['Export']['quick_export_onserver'] + $GLOBALS['cfg']['Export']['quick_export_onserver_overwrite'] + $GLOBALS['cfg']['Export']['remember_file_template'] + assertIsArray @@ -15001,7 +14978,8 @@ - + + assertNull assertSame assertSame assertSame @@ -15021,8 +14999,7 @@ testSkipByteOrderMarksFromContents - - assertNull + assertNull assertNull @@ -15501,54 +15478,66 @@ array - - - $sql_query - $sql_query - $sql_query - - - - $sql_query - $sql_query - assertTrue - - $import_notice + + $GLOBALS['import_notice'] + + + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] - - $import_notice - $import_notice - $sql_query + + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + + + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] array - - $import_notice - $sql_query + + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + + + $GLOBALS['import_notice'] assertFalse - - - $sql_query - - - - $import_notice + + $GLOBALS['import_notice'] + + + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] + $GLOBALS['import_notice'] @@ -15713,8 +15702,7 @@ - - $db + $this->parseAndAnalyze('DROP DATABASE db') $this->parseAndAnalyze('DROP TABLE tbl') $this->parseAndAnalyze('SELECT * FROM db.tbl') @@ -15811,16 +15799,14 @@ $unUsed[] $val - + ?array array - int|numeric-string $query_data['pos'] - - $cached_affected_rows ?? 0 + $ret $this->dummyQueries[$result - self::OFFSET_GLOBAL] $this->filoQueries[$result] @@ -15894,6 +15880,9 @@ + + $GLOBALS['theme'] + $this->backup @@ -15950,15 +15939,6 @@ array - - - set - set - set - set - set - - $_SESSION['userconfig'] diff --git a/psalm.xml b/psalm.xml index be42de0e80..6e9a5d48fe 100644 --- a/psalm.xml +++ b/psalm.xml @@ -34,96 +34,6 @@ - - - - diff --git a/setup/index.php b/setup/index.php index 2368f981b7..6f7e85deb3 100644 --- a/setup/index.php +++ b/setup/index.php @@ -19,16 +19,13 @@ if (! defined('ROOT_PATH')) { // phpcs:enable } -/** @psalm-suppress InvalidGlobal */ -global $cfg; - // phpcs:disable PSR1.Files.SideEffects define('PHPMYADMIN', true); // phpcs:enable require ROOT_PATH . 'setup/lib/common.inc.php'; -if (@file_exists(CONFIG_FILE) && ! $cfg['DBG']['demo']) { +if (@file_exists(CONFIG_FILE) && ! $GLOBALS['cfg']['DBG']['demo']) { Core::fatalError(__('Configuration already exists, setup is disabled!')); } diff --git a/setup/lib/common.inc.php b/setup/lib/common.inc.php index 17adc52dbe..c8a8589037 100644 --- a/setup/lib/common.inc.php +++ b/setup/lib/common.inc.php @@ -32,7 +32,7 @@ require AUTOLOAD_FILE; chdir('..'); -$isMinimumCommon = true; +$GLOBALS['isMinimumCommon'] = true; Common::run(); diff --git a/test/classes/AbstractNetworkTestCase.php b/test/classes/AbstractNetworkTestCase.php index db7838b464..6535705fdb 100644 --- a/test/classes/AbstractNetworkTestCase.php +++ b/test/classes/AbstractNetworkTestCase.php @@ -30,10 +30,8 @@ abstract class AbstractNetworkTestCase extends AbstractTestCase */ public static function setUpBeforeClass(): void { - global $cfg; - $settings = new Settings([]); - $cfg = $settings->toArray(); + $GLOBALS['cfg'] = $settings->toArray(); } /** diff --git a/test/classes/AbstractTestCase.php b/test/classes/AbstractTestCase.php index 8e44c67c96..0605cca081 100644 --- a/test/classes/AbstractTestCase.php +++ b/test/classes/AbstractTestCase.php @@ -85,10 +85,19 @@ abstract class AbstractTestCase extends TestCase $_COOKIE = []; $_FILES = []; $_REQUEST = []; + + $GLOBALS['server'] = 1; + $GLOBALS['db'] = ''; + $GLOBALS['table'] = ''; + $GLOBALS['sql_query'] = ''; + $GLOBALS['text_dir'] = 'ltr'; + $GLOBALS['PMA_PHP_SELF'] = 'index.php'; + // Config before DBI $this->setGlobalConfig(); $this->loadContainerBuilder(); $this->setGlobalDbi(); + $this->setTheme(); Cache::purge(); } @@ -121,97 +130,80 @@ abstract class AbstractTestCase extends TestCase protected function loadContainerBuilder(): void { - global $containerBuilder; - - $containerBuilder = Core::getContainerBuilder(); + $GLOBALS['containerBuilder'] = Core::getContainerBuilder(); } protected function loadDbiIntoContainerBuilder(): void { - global $containerBuilder, $dbi; - - $containerBuilder->set(DatabaseInterface::class, $dbi); - $containerBuilder->setAlias('dbi', DatabaseInterface::class); + $GLOBALS['containerBuilder']->set(DatabaseInterface::class, $GLOBALS['dbi']); + $GLOBALS['containerBuilder']->setAlias('dbi', DatabaseInterface::class); } protected function loadResponseIntoContainerBuilder(): void { - global $containerBuilder; - $response = new ResponseRenderer(); - $containerBuilder->set(ResponseRenderer::class, $response); - $containerBuilder->setAlias('response', ResponseRenderer::class); + $GLOBALS['containerBuilder']->set(ResponseRenderer::class, $response); + $GLOBALS['containerBuilder']->setAlias('response', ResponseRenderer::class); } protected function setResponseIsAjax(): void { - global $containerBuilder; - /** @var ResponseRenderer $response */ - $response = $containerBuilder->get(ResponseRenderer::class); + $response = $GLOBALS['containerBuilder']->get(ResponseRenderer::class); $response->setAjax(true); } protected function getResponseHtmlResult(): string { - global $containerBuilder; - /** @var ResponseRenderer $response */ - $response = $containerBuilder->get(ResponseRenderer::class); + $response = $GLOBALS['containerBuilder']->get(ResponseRenderer::class); return $response->getHTMLResult(); } protected function getResponseJsonResult(): array { - global $containerBuilder; - /** @var ResponseRenderer $response */ - $response = $containerBuilder->get(ResponseRenderer::class); + $response = $GLOBALS['containerBuilder']->get(ResponseRenderer::class); return $response->getJSONResult(); } protected function assertResponseWasNotSuccessfull(): void { - global $containerBuilder; /** @var ResponseRenderer $response */ - $response = $containerBuilder->get(ResponseRenderer::class); + $response = $GLOBALS['containerBuilder']->get(ResponseRenderer::class); $this->assertFalse($response->hasSuccessState(), 'expected the request to fail'); } protected function assertResponseWasSuccessfull(): void { - global $containerBuilder; /** @var ResponseRenderer $response */ - $response = $containerBuilder->get(ResponseRenderer::class); + $response = $GLOBALS['containerBuilder']->get(ResponseRenderer::class); $this->assertTrue($response->hasSuccessState(), 'expected the request not to fail'); } protected function setGlobalDbi(): void { - global $dbi; $this->dummyDbi = new DbiDummy(); $this->dbi = DatabaseInterface::load($this->dummyDbi); - $dbi = $this->dbi; + $GLOBALS['dbi'] = $this->dbi; } protected function setGlobalConfig(): void { - global $config, $cfg; - $config = new Config(); - $config->checkServers(); - $config->set('environment', 'development'); - $cfg = $config->settings; + $GLOBALS['config'] = new Config(); + $GLOBALS['config']->checkServers(); + $GLOBALS['config']->set('environment', 'development'); + $GLOBALS['cfg'] = $GLOBALS['config']->settings; } protected function setTheme(): void { - global $theme; - $theme = Theme::load( + $GLOBALS['theme'] = Theme::load( ThemeManager::getThemesDir() . 'pmahomme', ThemeManager::getThemesFsDir() . 'pmahomme' . DIRECTORY_SEPARATOR, 'pmahomme' @@ -220,9 +212,7 @@ abstract class AbstractTestCase extends TestCase protected function setLanguage(string $code = 'en'): void { - global $lang; - - $lang = $code; + $GLOBALS['lang'] = $code; /* Ensure default language is active */ $languageEn = LanguageManager::getInstance()->getLanguage($code); if ($languageEn === false) { diff --git a/test/classes/Command/TwigLintCommandTest.php b/test/classes/Command/TwigLintCommandTest.php index f56f9a089a..b97d2cd703 100644 --- a/test/classes/Command/TwigLintCommandTest.php +++ b/test/classes/Command/TwigLintCommandTest.php @@ -28,15 +28,13 @@ class TwigLintCommandTest extends AbstractTestCase public function setUp(): void { - global $cfg, $config; - if (! class_exists(Command::class)) { $this->markTestSkipped('The Symfony Console is missing'); } parent::setUp(); - $cfg['environment'] = 'development'; - $config = null; + $GLOBALS['cfg']['environment'] = 'development'; + $GLOBALS['config'] = null; $this->command = new TwigLintCommand(); } diff --git a/test/classes/CommonTest.php b/test/classes/CommonTest.php index 83c05cfae1..ca156c5238 100644 --- a/test/classes/CommonTest.php +++ b/test/classes/CommonTest.php @@ -84,18 +84,16 @@ class CommonTest extends AbstractTestCase public function testCheckTokenRequestParam(): void { - global $token_mismatch, $token_provided; - $_SERVER['REQUEST_METHOD'] = 'GET'; Common::checkTokenRequestParam(); - $this->assertTrue($token_mismatch); - $this->assertFalse($token_provided); + $this->assertTrue($GLOBALS['token_mismatch']); + $this->assertFalse($GLOBALS['token_provided']); $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST['test'] = 'test'; Common::checkTokenRequestParam(); - $this->assertTrue($token_mismatch); - $this->assertFalse($token_provided); + $this->assertTrue($GLOBALS['token_mismatch']); + $this->assertFalse($GLOBALS['token_provided']); $this->assertArrayNotHasKey('test', $_POST); $_SERVER['REQUEST_METHOD'] = 'POST'; @@ -103,8 +101,8 @@ class CommonTest extends AbstractTestCase $_POST['test'] = 'test'; $_SESSION[' PMA_token '] = 'mismatch'; Common::checkTokenRequestParam(); - $this->assertTrue($token_mismatch); - $this->assertTrue($token_provided); + $this->assertTrue($GLOBALS['token_mismatch']); + $this->assertTrue($GLOBALS['token_provided']); $this->assertArrayNotHasKey('test', $_POST); $_SERVER['REQUEST_METHOD'] = 'POST'; @@ -112,8 +110,8 @@ class CommonTest extends AbstractTestCase $_POST['test'] = 'test'; $_SESSION[' PMA_token '] = 'token'; Common::checkTokenRequestParam(); - $this->assertFalse($token_mismatch); - $this->assertTrue($token_provided); + $this->assertFalse($GLOBALS['token_mismatch']); + $this->assertTrue($GLOBALS['token_provided']); $this->assertArrayHasKey('test', $_POST); $this->assertEquals('test', $_POST['test']); } diff --git a/test/classes/Controllers/CheckRelationsControllerTest.php b/test/classes/Controllers/CheckRelationsControllerTest.php index 590d6ba3e6..bc3d36ff85 100644 --- a/test/classes/Controllers/CheckRelationsControllerTest.php +++ b/test/classes/Controllers/CheckRelationsControllerTest.php @@ -19,6 +19,8 @@ class CheckRelationsControllerTest extends AbstractTestCase public function testCheckRelationsController(): void { $GLOBALS['server'] = 1; + $GLOBALS['db'] = ''; + $GLOBALS['table'] = ''; $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; diff --git a/test/classes/Controllers/Database/MultiTableQuery/TablesControllerTest.php b/test/classes/Controllers/Database/MultiTableQuery/TablesControllerTest.php index 0d74f7be9f..7fa05e550f 100644 --- a/test/classes/Controllers/Database/MultiTableQuery/TablesControllerTest.php +++ b/test/classes/Controllers/Database/MultiTableQuery/TablesControllerTest.php @@ -32,9 +32,8 @@ class TablesControllerTest extends AbstractTestCase ]; $_GET['db'] = 'test'; - global $containerBuilder; /** @var TablesController $multiTableQueryController */ - $multiTableQueryController = $containerBuilder->get(TablesController::class); + $multiTableQueryController = $GLOBALS['containerBuilder']->get(TablesController::class); $multiTableQueryController(); $this->assertSame( [ diff --git a/test/classes/Controllers/Database/PrivilegesControllerTest.php b/test/classes/Controllers/Database/PrivilegesControllerTest.php index e601b10522..4a3fb575be 100644 --- a/test/classes/Controllers/Database/PrivilegesControllerTest.php +++ b/test/classes/Controllers/Database/PrivilegesControllerTest.php @@ -31,12 +31,10 @@ class PrivilegesControllerTest extends AbstractTestCase public function testIndex(): void { - global $dbi, $db, $server, $cfg, $PMA_PHP_SELF; - - $db = 'db'; - $server = 0; - $cfg['Server']['DisableIS'] = false; - $PMA_PHP_SELF = 'index.php'; + $GLOBALS['db'] = 'db'; + $GLOBALS['server'] = 0; + $GLOBALS['cfg']['Server']['DisableIS'] = false; + $GLOBALS['PMA_PHP_SELF'] = 'index.php'; $privileges = []; @@ -48,15 +46,15 @@ class PrivilegesControllerTest extends AbstractTestCase ResponseRenderer::getInstance(), new Template(), $serverPrivileges, - $dbi - ))(['checkprivsdb' => $db]); + $GLOBALS['dbi'] + ))(['checkprivsdb' => $GLOBALS['db']]); $this->assertStringContainsString( - Url::getCommon(['db' => $db], ''), + Url::getCommon(['db' => $GLOBALS['db']], ''), $actual ); - $this->assertStringContainsString($db, $actual); + $this->assertStringContainsString($GLOBALS['db'], $actual); $this->assertStringContainsString( __('User'), @@ -89,7 +87,7 @@ class PrivilegesControllerTest extends AbstractTestCase $actual ); $this->assertStringContainsString( - Url::getCommon(['checkprivsdb' => $db]), + Url::getCommon(['checkprivsdb' => $GLOBALS['db']]), $actual ); } diff --git a/test/classes/Controllers/Database/StructureControllerTest.php b/test/classes/Controllers/Database/StructureControllerTest.php index abdf86cae0..1cd678f816 100644 --- a/test/classes/Controllers/Database/StructureControllerTest.php +++ b/test/classes/Controllers/Database/StructureControllerTest.php @@ -413,17 +413,16 @@ class StructureControllerTest extends AbstractTestCase */ public function testGetValuesForMroongaTable(): void { - global $containerBuilder; parent::loadContainerBuilder(); parent::loadDbiIntoContainerBuilder(); $GLOBALS['db'] = 'testdb'; $GLOBALS['table'] = 'mytable'; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var StructureController $structureController */ - $structureController = $containerBuilder->get(StructureController::class); + $structureController = $GLOBALS['containerBuilder']->get(StructureController::class); $this->assertSame( [ diff --git a/test/classes/Controllers/Export/ExportControllerTest.php b/test/classes/Controllers/Export/ExportControllerTest.php index b50d70d1dc..7b5f816f63 100644 --- a/test/classes/Controllers/Export/ExportControllerTest.php +++ b/test/classes/Controllers/Export/ExportControllerTest.php @@ -31,6 +31,8 @@ class ExportControllerTest extends AbstractTestCase $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['lang'] = 'en'; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; + $GLOBALS['sql_indexes'] = null; + $GLOBALS['sql_auto_increments'] = null; $GLOBALS['dblist'] = (object) ['databases' => ['test_db']]; $GLOBALS['config']->selectServer(); $GLOBALS['cfg'] = $GLOBALS['config']->settings; diff --git a/test/classes/Controllers/Export/Template/CreateControllerTest.php b/test/classes/Controllers/Export/Template/CreateControllerTest.php index ca43f31784..6b45a93084 100644 --- a/test/classes/Controllers/Export/Template/CreateControllerTest.php +++ b/test/classes/Controllers/Export/Template/CreateControllerTest.php @@ -21,8 +21,6 @@ class CreateControllerTest extends AbstractTestCase { public function testCreate(): void { - global $cfg; - $GLOBALS['server'] = 1; $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; @@ -34,7 +32,7 @@ class CreateControllerTest extends AbstractTestCase 'export_templates' => 'table', ])->toArray(); - $cfg['Server']['user'] = 'user'; + $GLOBALS['cfg']['Server']['user'] = 'user'; $response = new ResponseRenderer(); $template = new Template(); diff --git a/test/classes/Controllers/Export/Template/DeleteControllerTest.php b/test/classes/Controllers/Export/Template/DeleteControllerTest.php index eac9eca9e3..f738e4dfef 100644 --- a/test/classes/Controllers/Export/Template/DeleteControllerTest.php +++ b/test/classes/Controllers/Export/Template/DeleteControllerTest.php @@ -19,13 +19,11 @@ class DeleteControllerTest extends AbstractTestCase { public function testDelete(): void { - global $cfg; - $GLOBALS['server'] = 1; $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; - $cfg['Server']['user'] = 'user'; + $GLOBALS['cfg']['Server']['user'] = 'user'; $response = new ResponseRenderer(); $request = $this->createStub(ServerRequest::class); diff --git a/test/classes/Controllers/Export/Template/LoadControllerTest.php b/test/classes/Controllers/Export/Template/LoadControllerTest.php index 51ab552e03..042dfb811c 100644 --- a/test/classes/Controllers/Export/Template/LoadControllerTest.php +++ b/test/classes/Controllers/Export/Template/LoadControllerTest.php @@ -20,8 +20,6 @@ class LoadControllerTest extends AbstractTestCase { public function testLoad(): void { - global $cfg; - $GLOBALS['server'] = 1; $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; @@ -33,7 +31,7 @@ class LoadControllerTest extends AbstractTestCase 'export_templates' => 'table', ])->toArray(); - $cfg['Server']['user'] = 'user'; + $GLOBALS['cfg']['Server']['user'] = 'user'; $response = new ResponseRenderer(); $request = $this->createStub(ServerRequest::class); diff --git a/test/classes/Controllers/Export/Template/UpdateControllerTest.php b/test/classes/Controllers/Export/Template/UpdateControllerTest.php index c7b04d7028..3d1cb7b169 100644 --- a/test/classes/Controllers/Export/Template/UpdateControllerTest.php +++ b/test/classes/Controllers/Export/Template/UpdateControllerTest.php @@ -19,13 +19,11 @@ class UpdateControllerTest extends AbstractTestCase { public function testUpdate(): void { - global $cfg; - $GLOBALS['server'] = 1; $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; - $cfg['Server']['user'] = 'user'; + $GLOBALS['cfg']['Server']['user'] = 'user'; $response = new ResponseRenderer(); $request = $this->createStub(ServerRequest::class); diff --git a/test/classes/Controllers/Import/ImportControllerTest.php b/test/classes/Controllers/Import/ImportControllerTest.php index 31a731d76e..e23d07f221 100644 --- a/test/classes/Controllers/Import/ImportControllerTest.php +++ b/test/classes/Controllers/Import/ImportControllerTest.php @@ -14,8 +14,6 @@ class ImportControllerTest extends AbstractTestCase { public function testIndexParametrized(): void { - global $containerBuilder, $db, $table, $sql_query; - parent::loadContainerBuilder(); parent::loadDbiIntoContainerBuilder(); parent::setLanguage(); @@ -24,19 +22,21 @@ class ImportControllerTest extends AbstractTestCase $GLOBALS['server'] = 1; $GLOBALS['cfg']['Server']['user'] = 'user'; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; + $GLOBALS['import_run_buffer'] = null; + parent::loadResponseIntoContainerBuilder(); // Some params where not added as they where not required for this test $_POST['db'] = 'pma_test'; $_POST['table'] = 'table1'; - $db = $_POST['db']; - $table = $_POST['table']; + $GLOBALS['db'] = $_POST['db']; + $GLOBALS['table'] = $_POST['table']; $_POST['parameterized'] = 'on'; $_POST['parameters'] = [':nomEta' => 'Saint-Louis - Châteaulin', ':1' => '4']; $_POST['sql_query'] = 'SELECT A.*' . "\n" . 'FROM table1 A' . "\n" . 'WHERE A.nomEtablissement = :nomEta AND foo = :1 AND `:a` IS NULL'; - $sql_query = $_POST['sql_query']; + $GLOBALS['sql_query'] = $_POST['sql_query']; $this->dummyDbi->addResult( 'SELECT A.* FROM table1 A WHERE A.nomEtablissement = \'Saint-Louis - Châteaulin\'' @@ -55,7 +55,7 @@ class ImportControllerTest extends AbstractTestCase ); /** @var ImportController $importController */ - $importController = $containerBuilder->get(ImportController::class); + $importController = $GLOBALS['containerBuilder']->get(ImportController::class); $this->dummyDbi->addSelectDb('pma_test'); $this->dummyDbi->addSelectDb('pma_test'); $importController(); diff --git a/test/classes/Controllers/NavigationControllerTest.php b/test/classes/Controllers/NavigationControllerTest.php index f3515ab042..27867582bf 100644 --- a/test/classes/Controllers/NavigationControllerTest.php +++ b/test/classes/Controllers/NavigationControllerTest.php @@ -16,11 +16,10 @@ class NavigationControllerTest extends AbstractTestCase { public function testIndex(): void { - global $containerBuilder; - parent::loadContainerBuilder(); parent::loadDbiIntoContainerBuilder(); parent::setLanguage(); + $this->setTheme(); $GLOBALS['server'] = 1; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; @@ -111,7 +110,7 @@ class NavigationControllerTest extends AbstractTestCase ); /** @var NavigationController $navigationController */ - $navigationController = $containerBuilder->get(NavigationController::class); + $navigationController = $GLOBALS['containerBuilder']->get(NavigationController::class); $_POST['full'] = '1'; $this->setResponseIsAjax(); $navigationController(); @@ -167,8 +166,6 @@ class NavigationControllerTest extends AbstractTestCase public function testIndexWithPosAndValue(): void { - global $containerBuilder; - parent::loadContainerBuilder(); parent::loadDbiIntoContainerBuilder(); parent::setLanguage(); @@ -267,7 +264,7 @@ class NavigationControllerTest extends AbstractTestCase ); /** @var NavigationController $navigationController */ - $navigationController = $containerBuilder->get(NavigationController::class); + $navigationController = $GLOBALS['containerBuilder']->get(NavigationController::class); $_POST['full'] = '1'; $this->setResponseIsAjax(); $navigationController(); diff --git a/test/classes/Controllers/NormalizationControllerTest.php b/test/classes/Controllers/NormalizationControllerTest.php index 0d556e55eb..e13d076ba1 100644 --- a/test/classes/Controllers/NormalizationControllerTest.php +++ b/test/classes/Controllers/NormalizationControllerTest.php @@ -31,8 +31,6 @@ class NormalizationControllerTest extends AbstractTestCase public function testGetNewTables3NF(): void { - global $containerBuilder; - $_POST['getNewTables3NF'] = 1; $_POST['tables'] = json_encode([ 'test_tbl' => [ @@ -61,10 +59,10 @@ class NormalizationControllerTest extends AbstractTestCase ]); $GLOBALS['goto'] = 'index.php?route=/sql'; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var NormalizationController $normalizationController */ - $normalizationController = $containerBuilder->get(NormalizationController::class); + $normalizationController = $GLOBALS['containerBuilder']->get(NormalizationController::class); $normalizationController(); $this->assertResponseWasSuccessfull(); @@ -104,8 +102,6 @@ class NormalizationControllerTest extends AbstractTestCase public function testGetNewTables2NF(): void { - global $containerBuilder; - $_POST['getNewTables2NF'] = 1; $_POST['pd'] = json_encode([ 'ID, task' => [], @@ -113,10 +109,10 @@ class NormalizationControllerTest extends AbstractTestCase ]); $GLOBALS['goto'] = 'index.php?route=/sql'; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var NormalizationController $normalizationController */ - $normalizationController = $containerBuilder->get(NormalizationController::class); + $normalizationController = $GLOBALS['containerBuilder']->get(NormalizationController::class); $normalizationController(); $this->expectOutputString( '

In order to put the original table \'test_tbl\' into Second normal' @@ -128,8 +124,6 @@ class NormalizationControllerTest extends AbstractTestCase public function testCreateNewTables2NF(): void { - global $containerBuilder; - $_POST['createNewTables2NF'] = 1; $_POST['pd'] = json_encode([ 'ID, task' => [], @@ -141,10 +135,10 @@ class NormalizationControllerTest extends AbstractTestCase ]); $GLOBALS['goto'] = 'index.php?route=/sql'; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var NormalizationController $normalizationController */ - $normalizationController = $containerBuilder->get(NormalizationController::class); + $normalizationController = $GLOBALS['containerBuilder']->get(NormalizationController::class); $this->dummyDbi->addSelectDb('my_db'); $normalizationController(); $this->assertAllSelectsConsumed(); @@ -164,8 +158,6 @@ class NormalizationControllerTest extends AbstractTestCase public function testCreateNewTables3NF(): void { - global $containerBuilder; - $_POST['createNewTables3NF'] = 1; $_POST['newTables'] = json_encode([ 'test_tbl' => [ @@ -181,10 +173,10 @@ class NormalizationControllerTest extends AbstractTestCase ]); $GLOBALS['goto'] = 'index.php?route=/sql'; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var NormalizationController $normalizationController */ - $normalizationController = $containerBuilder->get(NormalizationController::class); + $normalizationController = $GLOBALS['containerBuilder']->get(NormalizationController::class); $this->dummyDbi->addSelectDb('my_db'); $normalizationController(); $this->assertAllSelectsConsumed(); diff --git a/test/classes/Controllers/Server/Databases/DestroyControllerTest.php b/test/classes/Controllers/Server/Databases/DestroyControllerTest.php index 472fee3c5a..33fdf0bbc0 100644 --- a/test/classes/Controllers/Server/Databases/DestroyControllerTest.php +++ b/test/classes/Controllers/Server/Databases/DestroyControllerTest.php @@ -22,8 +22,6 @@ class DestroyControllerTest extends AbstractTestCase { public function testDropDatabases(): void { - global $cfg; - $GLOBALS['server'] = 1; $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; @@ -35,7 +33,7 @@ class DestroyControllerTest extends AbstractTestCase $response = new ResponseRenderer(); $response->setAjax(true); - $cfg['AllowUserDropDatabase'] = true; + $GLOBALS['cfg']['AllowUserDropDatabase'] = true; $controller = new DestroyController( $response, diff --git a/test/classes/Controllers/Server/DatabasesControllerTest.php b/test/classes/Controllers/Server/DatabasesControllerTest.php index 4136f3bab2..1a2dfa0abe 100644 --- a/test/classes/Controllers/Server/DatabasesControllerTest.php +++ b/test/classes/Controllers/Server/DatabasesControllerTest.php @@ -36,10 +36,8 @@ class DatabasesControllerTest extends AbstractTestCase public function testIndexAction(): void { - global $cfg, $dblist, $is_create_db_priv; - - $dblist = new stdClass(); - $dblist->databases = [ + $GLOBALS['dblist'] = new stdClass(); + $GLOBALS['dblist']->databases = [ 'sakila', 'employees', ]; @@ -92,8 +90,8 @@ class DatabasesControllerTest extends AbstractTestCase $GLOBALS['dbi'] ); - $cfg['ShowCreateDb'] = true; - $is_create_db_priv = true; + $GLOBALS['cfg']['ShowCreateDb'] = true; + $GLOBALS['is_create_db_priv'] = true; $_REQUEST['statistics'] = '1'; $_REQUEST['sort_by'] = 'SCHEMA_TABLES'; $_REQUEST['sort_order'] = 'desc'; diff --git a/test/classes/Controllers/Server/EnginesControllerTest.php b/test/classes/Controllers/Server/EnginesControllerTest.php index cc411ab489..808c56b773 100644 --- a/test/classes/Controllers/Server/EnginesControllerTest.php +++ b/test/classes/Controllers/Server/EnginesControllerTest.php @@ -33,11 +33,9 @@ class EnginesControllerTest extends AbstractTestCase public function testIndex(): void { - global $dbi; - $response = new ResponseRenderer(); - $controller = new EnginesController($response, new Template(), $dbi); + $controller = new EnginesController($response, new Template(), $GLOBALS['dbi']); $this->dummyDbi->addSelectDb('mysql'); $controller->__invoke(); diff --git a/test/classes/Controllers/Server/ShowEngineControllerTest.php b/test/classes/Controllers/Server/ShowEngineControllerTest.php index 2b2d04ce2d..37dd3b7c9c 100644 --- a/test/classes/Controllers/Server/ShowEngineControllerTest.php +++ b/test/classes/Controllers/Server/ShowEngineControllerTest.php @@ -27,8 +27,6 @@ class ShowEngineControllerTest extends AbstractTestCase parent::setGlobalConfig(); parent::setTheme(); - global $dbi; - $GLOBALS['server'] = 1; $GLOBALS['db'] = 'db'; $GLOBALS['table'] = 'table'; @@ -39,7 +37,7 @@ class ShowEngineControllerTest extends AbstractTestCase $request = $this->createMock(ServerRequest::class); $this->dummyDbi->addSelectDb('mysql'); - (new ShowEngineController($response, new Template(), $dbi))($request, [ + (new ShowEngineController($response, new Template(), $GLOBALS['dbi']))($request, [ 'engine' => 'Pbxt', 'page' => 'page', ]); diff --git a/test/classes/Controllers/Server/Status/Monitor/QueryAnalyzerControllerTest.php b/test/classes/Controllers/Server/Status/Monitor/QueryAnalyzerControllerTest.php index 783a1a2374..731fb8ca3c 100644 --- a/test/classes/Controllers/Server/Status/Monitor/QueryAnalyzerControllerTest.php +++ b/test/classes/Controllers/Server/Status/Monitor/QueryAnalyzerControllerTest.php @@ -39,9 +39,7 @@ class QueryAnalyzerControllerTest extends AbstractTestCase public function testQueryAnalyzer(): void { - global $cached_affected_rows; - - $cached_affected_rows = 'cached_affected_rows'; + $GLOBALS['cached_affected_rows'] = 'cached_affected_rows'; SessionCache::set('profiling_supported', true); $value = [ diff --git a/test/classes/Controllers/Server/Status/QueriesControllerTest.php b/test/classes/Controllers/Server/Status/QueriesControllerTest.php index 2856d27278..72631228b1 100644 --- a/test/classes/Controllers/Server/Status/QueriesControllerTest.php +++ b/test/classes/Controllers/Server/Status/QueriesControllerTest.php @@ -51,11 +51,9 @@ class QueriesControllerTest extends AbstractTestCase public function testIndex(): void { - global $dbi; - $response = new ResponseRenderer(); - $controller = new QueriesController($response, new Template(), $this->data, $dbi); + $controller = new QueriesController($response, new Template(), $this->data, $GLOBALS['dbi']); $this->dummyDbi->addSelectDb('mysql'); $controller(); diff --git a/test/classes/Controllers/Sql/EnumValuesControllerTest.php b/test/classes/Controllers/Sql/EnumValuesControllerTest.php index 2ed5ae0b16..ece829a734 100644 --- a/test/classes/Controllers/Sql/EnumValuesControllerTest.php +++ b/test/classes/Controllers/Sql/EnumValuesControllerTest.php @@ -26,8 +26,6 @@ class EnumValuesControllerTest extends AbstractTestCase public function testGetEnumValuesError(): void { - global $containerBuilder, $_POST; - $this->dummyDbi->addResult('SHOW COLUMNS FROM `cvv`.`enums` LIKE \'set\'', false); $_POST = [ @@ -40,10 +38,10 @@ class EnumValuesControllerTest extends AbstractTestCase $GLOBALS['db'] = $_POST['db']; $GLOBALS['table'] = $_POST['table']; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var EnumValuesController $sqlController */ - $sqlController = $containerBuilder->get(EnumValuesController::class); + $sqlController = $GLOBALS['containerBuilder']->get(EnumValuesController::class); $sqlController(); $this->assertResponseWasNotSuccessfull(); @@ -56,8 +54,6 @@ class EnumValuesControllerTest extends AbstractTestCase public function testGetEnumValuesSuccess(): void { - global $containerBuilder, $_POST; - $this->dummyDbi->addResult( 'SHOW COLUMNS FROM `cvv`.`enums` LIKE \'set\'', [ @@ -90,10 +86,10 @@ class EnumValuesControllerTest extends AbstractTestCase $GLOBALS['db'] = $_POST['db']; $GLOBALS['table'] = $_POST['table']; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var EnumValuesController $sqlController */ - $sqlController = $containerBuilder->get(EnumValuesController::class); + $sqlController = $GLOBALS['containerBuilder']->get(EnumValuesController::class); $sqlController(); $this->assertResponseWasSuccessfull(); diff --git a/test/classes/Controllers/Sql/SetValuesControllerTest.php b/test/classes/Controllers/Sql/SetValuesControllerTest.php index 7c7570209b..0a3a941ae4 100644 --- a/test/classes/Controllers/Sql/SetValuesControllerTest.php +++ b/test/classes/Controllers/Sql/SetValuesControllerTest.php @@ -26,8 +26,6 @@ class SetValuesControllerTest extends AbstractTestCase public function testError(): void { - global $containerBuilder, $_POST; - $this->dummyDbi->addResult('SHOW COLUMNS FROM `cvv`.`enums` LIKE \'set\'', false); $_POST = [ @@ -40,10 +38,10 @@ class SetValuesControllerTest extends AbstractTestCase $GLOBALS['db'] = $_POST['db']; $GLOBALS['table'] = $_POST['table']; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var SetValuesController $sqlController */ - $sqlController = $containerBuilder->get(SetValuesController::class); + $sqlController = $GLOBALS['containerBuilder']->get(SetValuesController::class); $sqlController(); $this->assertResponseWasNotSuccessfull(); @@ -56,8 +54,6 @@ class SetValuesControllerTest extends AbstractTestCase public function testSuccess(): void { - global $containerBuilder, $_POST; - $this->dummyDbi->addResult( 'SHOW COLUMNS FROM `cvv`.`enums` LIKE \'set\'', [ @@ -90,10 +86,10 @@ class SetValuesControllerTest extends AbstractTestCase $GLOBALS['db'] = $_POST['db']; $GLOBALS['table'] = $_POST['table']; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var SetValuesController $sqlController */ - $sqlController = $containerBuilder->get(SetValuesController::class); + $sqlController = $GLOBALS['containerBuilder']->get(SetValuesController::class); $sqlController(); $this->assertResponseWasSuccessfull(); diff --git a/test/classes/Controllers/Table/AddFieldControllerTest.php b/test/classes/Controllers/Table/AddFieldControllerTest.php index ee85414768..81f25609c3 100644 --- a/test/classes/Controllers/Table/AddFieldControllerTest.php +++ b/test/classes/Controllers/Table/AddFieldControllerTest.php @@ -22,6 +22,7 @@ class AddFieldControllerTest extends AbstractTestCase { $GLOBALS['db'] = 'test_db'; $GLOBALS['table'] = 'test_table'; + $GLOBALS['regenerate'] = null; $GLOBALS['cfg']['Server'] = $GLOBALS['config']->defaultServer; $_POST = [ 'db' => 'test_db', diff --git a/test/classes/Controllers/Table/DeleteRowsControllerTest.php b/test/classes/Controllers/Table/DeleteRowsControllerTest.php index e33caab4e2..64f7d32f31 100644 --- a/test/classes/Controllers/Table/DeleteRowsControllerTest.php +++ b/test/classes/Controllers/Table/DeleteRowsControllerTest.php @@ -16,6 +16,9 @@ class DeleteRowsControllerTest extends AbstractTestCase { public function testDeleteRowsController(): void { + $this->setTheme(); + $GLOBALS['goto'] = null; + $GLOBALS['showtable'] = null; $GLOBALS['db'] = 'test_db'; $GLOBALS['table'] = 'test_table'; $GLOBALS['urlParams'] = []; diff --git a/test/classes/Controllers/Table/ImportControllerTest.php b/test/classes/Controllers/Table/ImportControllerTest.php index d2c039c9fc..74e717e490 100644 --- a/test/classes/Controllers/Table/ImportControllerTest.php +++ b/test/classes/Controllers/Table/ImportControllerTest.php @@ -20,6 +20,7 @@ class ImportControllerTest extends AbstractTestCase { public function testImportController(): void { + $this->setTheme(); $GLOBALS['server'] = 2; $GLOBALS['db'] = 'test_db'; $GLOBALS['table'] = 'test_table'; diff --git a/test/classes/Controllers/Table/OperationsControllerTest.php b/test/classes/Controllers/Table/OperationsControllerTest.php index 2116a642ec..fad802c7a0 100644 --- a/test/classes/Controllers/Table/OperationsControllerTest.php +++ b/test/classes/Controllers/Table/OperationsControllerTest.php @@ -17,8 +17,6 @@ class OperationsControllerTest extends AbstractTestCase { public function testOperationsController(): void { - global $containerBuilder; - $GLOBALS['server'] = 1; $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['lang'] = 'en'; @@ -34,8 +32,8 @@ class OperationsControllerTest extends AbstractTestCase $this->loadDbiIntoContainerBuilder(); $this->loadResponseIntoContainerBuilder(); - $containerBuilder->setParameter('db', 'test_db'); - $containerBuilder->setParameter('table', 'test_table'); + $GLOBALS['containerBuilder']->setParameter('db', 'test_db'); + $GLOBALS['containerBuilder']->setParameter('table', 'test_table'); $this->dummyDbi->addSelectDb('test_db'); $this->dummyDbi->addSelectDb('test_db'); @@ -103,7 +101,7 @@ class OperationsControllerTest extends AbstractTestCase ]); /** @var OperationsController $controller */ - $controller = $containerBuilder->get(OperationsController::class); + $controller = $GLOBALS['containerBuilder']->get(OperationsController::class); $controller(); $this->assertEquals($expectedOutput, $this->getResponseHtmlResult()); diff --git a/test/classes/Controllers/Table/PrivilegesControllerTest.php b/test/classes/Controllers/Table/PrivilegesControllerTest.php index f439137c9e..86e619a4e9 100644 --- a/test/classes/Controllers/Table/PrivilegesControllerTest.php +++ b/test/classes/Controllers/Table/PrivilegesControllerTest.php @@ -31,13 +31,11 @@ class PrivilegesControllerTest extends AbstractTestCase public function testIndex(): void { - global $dbi, $db, $table, $server, $cfg, $PMA_PHP_SELF; - - $db = 'db'; - $table = 'table'; - $server = 0; - $cfg['Server']['DisableIS'] = false; - $PMA_PHP_SELF = 'index.php'; + $GLOBALS['db'] = 'db'; + $GLOBALS['table'] = 'table'; + $GLOBALS['server'] = 0; + $GLOBALS['cfg']['Server']['DisableIS'] = false; + $GLOBALS['PMA_PHP_SELF'] = 'index.php'; $privileges = []; @@ -49,15 +47,15 @@ class PrivilegesControllerTest extends AbstractTestCase ResponseRenderer::getInstance(), new Template(), $serverPrivileges, - $dbi - ))(['checkprivsdb' => $db, 'checkprivstable' => $table]); + $GLOBALS['dbi'] + ))(['checkprivsdb' => $GLOBALS['db'], 'checkprivstable' => $GLOBALS['table']]); - $this->assertStringContainsString($db . '.' . $table, $actual); + $this->assertStringContainsString($GLOBALS['db'] . '.' . $GLOBALS['table'], $actual); //validate 2: Url::getCommon $item = Url::getCommon([ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], ], ''); $this->assertStringContainsString($item, $actual); @@ -98,8 +96,8 @@ class PrivilegesControllerTest extends AbstractTestCase ); $this->assertStringContainsString( Url::getCommon([ - 'checkprivsdb' => $db, - 'checkprivstable' => $table, + 'checkprivsdb' => $GLOBALS['db'], + 'checkprivstable' => $GLOBALS['table'], ]), $actual ); diff --git a/test/classes/Controllers/Table/ReplaceControllerTest.php b/test/classes/Controllers/Table/ReplaceControllerTest.php index fac53e765f..5240fc8485 100644 --- a/test/classes/Controllers/Table/ReplaceControllerTest.php +++ b/test/classes/Controllers/Table/ReplaceControllerTest.php @@ -23,6 +23,7 @@ class ReplaceControllerTest extends AbstractTestCase parent::loadContainerBuilder(); parent::loadDbiIntoContainerBuilder(); $GLOBALS['server'] = 1; + $GLOBALS['showtable'] = null; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; parent::loadResponseIntoContainerBuilder(); $GLOBALS['db'] = 'my_db'; @@ -52,7 +53,6 @@ class ReplaceControllerTest extends AbstractTestCase public function testReplace(): void { - global $containerBuilder; $GLOBALS['urlParams'] = []; ResponseRenderer::getInstance()->setAjax(true); $_POST['db'] = $GLOBALS['db']; @@ -89,10 +89,10 @@ class ReplaceControllerTest extends AbstractTestCase ], ]; $GLOBALS['goto'] = 'index.php?route=/sql'; - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var ReplaceController $replaceController */ - $replaceController = $containerBuilder->get(ReplaceController::class); + $replaceController = $GLOBALS['containerBuilder']->get(ReplaceController::class); $this->dummyDbi->addSelectDb('my_db'); $this->dummyDbi->addSelectDb('my_db'); $replaceController(); @@ -109,7 +109,6 @@ class ReplaceControllerTest extends AbstractTestCase public function testIsInsertRow(): void { - global $containerBuilder; $GLOBALS['urlParams'] = []; $GLOBALS['goto'] = 'index.php?route=/sql'; $_POST['insert_rows'] = 5; @@ -130,10 +129,10 @@ class ReplaceControllerTest extends AbstractTestCase [] ); - $containerBuilder->setParameter('db', $GLOBALS['db']); - $containerBuilder->setParameter('table', $GLOBALS['table']); + $GLOBALS['containerBuilder']->setParameter('db', $GLOBALS['db']); + $GLOBALS['containerBuilder']->setParameter('table', $GLOBALS['table']); /** @var ReplaceController $replaceController */ - $replaceController = $containerBuilder->get(ReplaceController::class); + $replaceController = $GLOBALS['containerBuilder']->get(ReplaceController::class); $this->dummyDbi->addSelectDb('my_db'); $this->dummyDbi->addSelectDb('my_db'); $this->dummyDbi->addSelectDb('my_db'); diff --git a/test/classes/Controllers/Table/SearchControllerTest.php b/test/classes/Controllers/Table/SearchControllerTest.php index f8122cef6b..c2018852b1 100644 --- a/test/classes/Controllers/Table/SearchControllerTest.php +++ b/test/classes/Controllers/Table/SearchControllerTest.php @@ -125,8 +125,6 @@ class SearchControllerTest extends AbstractTestCase */ public function testGetDataRowAction(): void { - global $containerBuilder; - parent::setGlobalDbi(); parent::loadDbiIntoContainerBuilder(); parent::loadResponseIntoContainerBuilder(); @@ -161,11 +159,11 @@ class SearchControllerTest extends AbstractTestCase ] ); - $containerBuilder->setParameter('db', 'PMA'); - $containerBuilder->setParameter('table', 'PMA_BookMark'); + $GLOBALS['containerBuilder']->setParameter('db', 'PMA'); + $GLOBALS['containerBuilder']->setParameter('table', 'PMA_BookMark'); /** @var SearchController $ctrl */ - $ctrl = $containerBuilder->get(SearchController::class); + $ctrl = $GLOBALS['containerBuilder']->get(SearchController::class); $_POST['db'] = 'PMA'; $_POST['table'] = 'PMA_BookMark'; diff --git a/test/classes/CoreTest.php b/test/classes/CoreTest.php index b728fed2b0..489acfcab7 100644 --- a/test/classes/CoreTest.php +++ b/test/classes/CoreTest.php @@ -931,11 +931,9 @@ class CoreTest extends AbstractNetworkTestCase public function testPopulateRequestWithEncryptedQueryParams(): void { - global $config; - $_SESSION = []; - $config->set('URLQueryEncryption', true); - $config->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); + $GLOBALS['config']->set('URLQueryEncryption', true); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); $_GET = ['pos' => '0', 'eq' => Url::encryptQuery('{"db":"test_db","table":"test_table"}')]; $_REQUEST = $_GET; @@ -964,11 +962,9 @@ class CoreTest extends AbstractNetworkTestCase array $encrypted, array $decrypted ): void { - global $config; - $_SESSION = []; - $config->set('URLQueryEncryption', true); - $config->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); + $GLOBALS['config']->set('URLQueryEncryption', true); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); $_GET = $encrypted; $_REQUEST = $encrypted; diff --git a/test/classes/Crypto/CryptoTest.php b/test/classes/Crypto/CryptoTest.php index 4e525ec9ae..f136004e29 100644 --- a/test/classes/Crypto/CryptoTest.php +++ b/test/classes/Crypto/CryptoTest.php @@ -17,10 +17,8 @@ class CryptoTest extends AbstractTestCase { public function testWithValidKeyFromConfig(): void { - global $config; - $_SESSION = []; - $config->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); $crypto = new Crypto(); $encrypted = $crypto->encrypt('test'); @@ -31,10 +29,8 @@ class CryptoTest extends AbstractTestCase public function testWithValidKeyFromSession(): void { - global $config; - $_SESSION = ['URLQueryEncryptionSecretKey' => str_repeat('a', 32)]; - $config->set('URLQueryEncryptionSecretKey', ''); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', ''); $crypto = new Crypto(); $encrypted = $crypto->encrypt('test'); @@ -45,10 +41,8 @@ class CryptoTest extends AbstractTestCase public function testWithNewSessionKey(): void { - global $config; - $_SESSION = []; - $config->set('URLQueryEncryptionSecretKey', ''); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', ''); $crypto = new Crypto(); $encrypted = $crypto->encrypt('test'); @@ -60,17 +54,15 @@ class CryptoTest extends AbstractTestCase public function testDecryptWithInvalidKey(): void { - global $config; - $_SESSION = []; - $config->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); $crypto = new Crypto(); $encrypted = $crypto->encrypt('test'); $this->assertNotSame('test', $encrypted); $this->assertSame('test', $crypto->decrypt($encrypted)); - $config->set('URLQueryEncryptionSecretKey', str_repeat('b', 32)); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', str_repeat('b', 32)); $crypto = new Crypto(); $this->assertNull($crypto->decrypt($encrypted)); diff --git a/test/classes/Database/EventsTest.php b/test/classes/Database/EventsTest.php index 7bcb60d567..cd3742bf68 100644 --- a/test/classes/Database/EventsTest.php +++ b/test/classes/Database/EventsTest.php @@ -310,9 +310,7 @@ class EventsTest extends AbstractTestCase */ public function testGetQueryFromRequest(array $request, string $query, int $num_err): void { - global $errors; - - $errors = []; + $GLOBALS['errors'] = []; unset($_POST); $_POST = $request; @@ -326,7 +324,7 @@ class EventsTest extends AbstractTestCase $GLOBALS['dbi'] = $dbi; $this->assertEquals($query, $this->events->getQueryFromRequest()); - $this->assertCount($num_err, $errors); + $this->assertCount($num_err, $GLOBALS['errors']); } /** diff --git a/test/classes/Database/RoutinesTest.php b/test/classes/Database/RoutinesTest.php index 071e3fe254..dfa9f152e7 100644 --- a/test/classes/Database/RoutinesTest.php +++ b/test/classes/Database/RoutinesTest.php @@ -37,6 +37,7 @@ class RoutinesTest extends AbstractTestCase $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['proc_priv'] = false; $GLOBALS['is_reload_priv'] = false; + $GLOBALS['errors'] = []; $this->routines = new Routines( $GLOBALS['dbi'], @@ -1135,11 +1136,9 @@ class RoutinesTest extends AbstractTestCase */ public function testGetQueryFromRequest(array $request, string $query, int $num_err): void { - global $errors, $cfg; + $GLOBALS['cfg']['ShowFunctionFields'] = false; - $cfg['ShowFunctionFields'] = false; - - $errors = []; + $GLOBALS['errors'] = []; $old_dbi = $GLOBALS['dbi'] ?? null; $dbi = $this->getMockBuilder(DatabaseInterface::class) @@ -1180,7 +1179,7 @@ class RoutinesTest extends AbstractTestCase unset($_POST); $_POST = $request; $this->assertEquals($query, $routines->getQueryFromRequest()); - $this->assertCount($num_err, $errors); + $this->assertCount($num_err, $GLOBALS['errors']); // reset $GLOBALS['dbi'] = $old_dbi; diff --git a/test/classes/Database/TriggersTest.php b/test/classes/Database/TriggersTest.php index e67c7a5cff..75f991eb92 100644 --- a/test/classes/Database/TriggersTest.php +++ b/test/classes/Database/TriggersTest.php @@ -269,9 +269,7 @@ class TriggersTest extends AbstractTestCase string $query, int $num_err ): void { - global $errors; - - $errors = []; + $GLOBALS['errors'] = []; $_POST['item_definer'] = $definer; $_POST['item_name'] = $name; @@ -282,7 +280,7 @@ class TriggersTest extends AbstractTestCase $GLOBALS['server'] = 1; $this->assertEquals($query, $this->triggers->getQueryFromRequest()); - $this->assertCount($num_err, $errors); + $this->assertCount($num_err, $GLOBALS['errors']); } /** diff --git a/test/classes/Display/ResultsTest.php b/test/classes/Display/ResultsTest.php index 46feae4570..b134116861 100644 --- a/test/classes/Display/ResultsTest.php +++ b/test/classes/Display/ResultsTest.php @@ -56,6 +56,7 @@ class ResultsTest extends AbstractTestCase parent::setUp(); parent::setLanguage(); parent::setGlobalConfig(); + $this->setTheme(); $GLOBALS['server'] = 0; $GLOBALS['db'] = 'db'; $GLOBALS['table'] = 'table'; @@ -1365,18 +1366,16 @@ class ResultsTest extends AbstractTestCase public function testGetTable(): void { - global $db, $table; - $GLOBALS['cfg']['Server']['DisableIS'] = true; - $db = 'test_db'; - $table = 'test_table'; + $GLOBALS['db'] = 'test_db'; + $GLOBALS['table'] = 'test_table'; $query = 'SELECT * FROM `test_db`.`test_table`;'; - $object = new DisplayResults($this->dbi, $db, $table, 1, '', $query); + $object = new DisplayResults($this->dbi, $GLOBALS['db'], $GLOBALS['table'], 1, '', $query); $object->properties['unique_id'] = 1234567890; - [$analyzedSqlResults] = ParseAnalyze::sqlQuery($query, $db); + [$analyzedSqlResults] = ParseAnalyze::sqlQuery($query, $GLOBALS['db']); $fieldsMeta = [ new FieldMetadata( MYSQLI_TYPE_DECIMAL, @@ -1540,8 +1539,8 @@ class ResultsTest extends AbstractTestCase 'number_total_page' => 1, 'has_show_all' => true, 'hidden_fields' => [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'server' => 1, 'sql_query' => $query, 'is_browse_distinct' => false, @@ -1553,8 +1552,8 @@ class ResultsTest extends AbstractTestCase 'pos' => 0, 'sort_by_key' => [ 'hidden_fields' => [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'server' => 1, 'sort_by_key' => '1', 'session_max_rows' => 25, @@ -1619,16 +1618,16 @@ class ResultsTest extends AbstractTestCase 'has_print_link' => true, 'has_export_link' => true, 'url_params' => [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'printview' => '1', 'sql_query' => $query, 'single_table' => 'true', 'unlim_num_rows' => 3, ], ], - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'unique_id' => 1234567890, 'sql_query' => $query, 'goto' => '', @@ -1645,18 +1644,16 @@ class ResultsTest extends AbstractTestCase public function testGetTable2(): void { - global $db, $table; - $GLOBALS['cfg']['Server']['DisableIS'] = true; - $db = 'test_db'; - $table = 'test_table'; + $GLOBALS['db'] = 'test_db'; + $GLOBALS['table'] = 'test_table'; $query = 'SELECT COUNT(*) AS `Rows`, `name` FROM `test_table` GROUP BY `name` ORDER BY `name`'; - $object = new DisplayResults($this->dbi, $db, $table, 1, '', $query); + $object = new DisplayResults($this->dbi, $GLOBALS['db'], $GLOBALS['table'], 1, '', $query); $object->properties['unique_id'] = 1234567890; - [$analyzedSqlResults] = ParseAnalyze::sqlQuery($query, $db); + [$analyzedSqlResults] = ParseAnalyze::sqlQuery($query, $GLOBALS['db']); $fieldsMeta = [ new FieldMetadata( MYSQLI_TYPE_LONG, @@ -1796,8 +1793,8 @@ class ResultsTest extends AbstractTestCase 'number_total_page' => 1, 'has_show_all' => true, 'hidden_fields' => [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'server' => 1, 'sql_query' => $query, 'is_browse_distinct' => true, @@ -1842,16 +1839,16 @@ class ResultsTest extends AbstractTestCase 'has_print_link' => true, 'has_export_link' => true, 'url_params' => [ - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'printview' => '1', 'sql_query' => $query, 'single_table' => 'true', 'unlim_num_rows' => 2, ], ], - 'db' => $db, - 'table' => $table, + 'db' => $GLOBALS['db'], + 'table' => $GLOBALS['table'], 'unique_id' => 1234567890, 'sql_query' => $query, 'goto' => '', diff --git a/test/classes/Export/OptionsTest.php b/test/classes/Export/OptionsTest.php index 0ad51d2d82..92acd16137 100644 --- a/test/classes/Export/OptionsTest.php +++ b/test/classes/Export/OptionsTest.php @@ -52,12 +52,10 @@ class OptionsTest extends AbstractTestCase public function testGetOptions(): void { - global $cfg; - - $cfg['Export']['method'] = 'XML'; - $cfg['SaveDir'] = '/tmp'; - $cfg['ZipDump'] = false; - $cfg['GZipDump'] = false; + $GLOBALS['cfg']['Export']['method'] = 'XML'; + $GLOBALS['cfg']['SaveDir'] = '/tmp'; + $GLOBALS['cfg']['ZipDump'] = false; + $GLOBALS['cfg']['GZipDump'] = false; $export_type = 'server'; $db = 'PMA'; @@ -110,35 +108,35 @@ class OptionsTest extends AbstractTestCase 'db' => $db, 'table' => $table, 'export_type' => $export_type, - 'export_method' => $cfg['Export']['method'], + 'export_method' => $GLOBALS['cfg']['Export']['method'], 'template_id' => '', ], - 'export_method' => $cfg['Export']['method'], + 'export_method' => $GLOBALS['cfg']['Export']['method'], 'plugins_choice' => $dropdown, 'options' => Plugins::getOptions('Export', $exportList), 'can_convert_kanji' => Encoding::canConvertKanji(), - 'exec_time_limit' => $cfg['ExecTimeLimit'], + 'exec_time_limit' => $GLOBALS['cfg']['ExecTimeLimit'], 'rows' => [], 'has_save_dir' => true, - 'save_dir' => Util::userDir($cfg['SaveDir']), - 'export_is_checked' => $cfg['Export']['quick_export_onserver'], - 'export_overwrite_is_checked' => $cfg['Export']['quick_export_onserver_overwrite'], + 'save_dir' => Util::userDir($GLOBALS['cfg']['SaveDir']), + 'export_is_checked' => $GLOBALS['cfg']['Export']['quick_export_onserver'], + 'export_overwrite_is_checked' => $GLOBALS['cfg']['Export']['quick_export_onserver_overwrite'], 'has_aliases' => false, 'aliases' => [], - 'is_checked_lock_tables' => $cfg['Export']['lock_tables'], - 'is_checked_asfile' => $cfg['Export']['asfile'], - 'is_checked_as_separate_files' => $cfg['Export']['as_separate_files'], - 'is_checked_export' => $cfg['Export']['onserver'], - 'is_checked_export_overwrite' => $cfg['Export']['onserver_overwrite'], - 'is_checked_remember_file_template' => $cfg['Export']['remember_file_template'], + 'is_checked_lock_tables' => $GLOBALS['cfg']['Export']['lock_tables'], + 'is_checked_asfile' => $GLOBALS['cfg']['Export']['asfile'], + 'is_checked_as_separate_files' => $GLOBALS['cfg']['Export']['as_separate_files'], + 'is_checked_export' => $GLOBALS['cfg']['Export']['onserver'], + 'is_checked_export_overwrite' => $GLOBALS['cfg']['Export']['onserver_overwrite'], + 'is_checked_remember_file_template' => $GLOBALS['cfg']['Export']['remember_file_template'], 'repopulate' => '', 'lock_tables' => '', 'is_encoding_supported' => true, 'encodings' => Encoding::listEncodings(), - 'export_charset' => $cfg['Export']['charset'], - 'export_asfile' => $cfg['Export']['asfile'], - 'has_zip' => $cfg['ZipDump'], - 'has_gzip' => $cfg['GZipDump'], + 'export_charset' => $GLOBALS['cfg']['Export']['charset'], + 'export_asfile' => $GLOBALS['cfg']['Export']['asfile'], + 'has_zip' => $GLOBALS['cfg']['ZipDump'], + 'has_gzip' => $GLOBALS['cfg']['GZipDump'], 'selected_compression' => 'none', 'filename_template' => 'user value for test', ]; diff --git a/test/classes/HeaderTest.php b/test/classes/HeaderTest.php index 20a17bd698..057a333ba1 100644 --- a/test/classes/HeaderTest.php +++ b/test/classes/HeaderTest.php @@ -148,16 +148,14 @@ class HeaderTest extends AbstractTestCase string $expectedXCsp, string $expectedWebKitCsp ): void { - global $cfg; - $header = new Header(); $date = (string) gmdate(DATE_RFC1123); - $cfg['AllowThirdPartyFraming'] = $frameOptions; - $cfg['CSPAllow'] = $cspAllow; - $cfg['CaptchaLoginPrivateKey'] = $privateKey; - $cfg['CaptchaLoginPublicKey'] = $publicKey; - $cfg['CaptchaCsp'] = $captchaCsp; + $GLOBALS['cfg']['AllowThirdPartyFraming'] = $frameOptions; + $GLOBALS['cfg']['CSPAllow'] = $cspAllow; + $GLOBALS['cfg']['CaptchaLoginPrivateKey'] = $privateKey; + $GLOBALS['cfg']['CaptchaLoginPublicKey'] = $publicKey; + $GLOBALS['cfg']['CaptchaCsp'] = $captchaCsp; $expected = [ 'X-Frame-Options' => $expectedFrameOptions, diff --git a/test/classes/Html/GeneratorTest.php b/test/classes/Html/GeneratorTest.php index f483c8c008..d05fc57571 100644 --- a/test/classes/Html/GeneratorTest.php +++ b/test/classes/Html/GeneratorTest.php @@ -47,7 +47,6 @@ class GeneratorTest extends AbstractTestCase */ public function testGetDbLinkNull(): void { - global $cfg; $GLOBALS['db'] = 'test_db'; $GLOBALS['server'] = 99; $database = $GLOBALS['db']; @@ -355,8 +354,6 @@ class GeneratorTest extends AbstractTestCase */ public function testGetServerSSL(): void { - global $cfg; - $sslNotUsed = 'SSL is not being used' . ' DocumentationDocumentation'; - $cfg['Server'] = [ + $GLOBALS['cfg']['Server'] = [ 'ssl' => false, 'host' => '127.0.0.1', ]; @@ -376,29 +373,29 @@ class GeneratorTest extends AbstractTestCase Generator::getServerSSL() ); - $cfg['Server'] = [ + $GLOBALS['cfg']['Server'] = [ 'ssl' => false, 'host' => 'custom.host', ]; - $cfg['MysqlSslWarningSafeHosts'] = ['localhost', '127.0.0.1']; + $GLOBALS['cfg']['MysqlSslWarningSafeHosts'] = ['localhost', '127.0.0.1']; $this->assertEquals( $sslNotUsedCaution, Generator::getServerSSL() ); - $cfg['Server'] = [ + $GLOBALS['cfg']['Server'] = [ 'ssl' => false, 'host' => 'custom.host', ]; - $cfg['MysqlSslWarningSafeHosts'] = ['localhost', '127.0.0.1', 'custom.host']; + $GLOBALS['cfg']['MysqlSslWarningSafeHosts'] = ['localhost', '127.0.0.1', 'custom.host']; $this->assertEquals( $sslNotUsed, Generator::getServerSSL() ); - $cfg['Server'] = [ + $GLOBALS['cfg']['Server'] = [ 'ssl' => false, 'ssl_verify' => true, 'host' => 'custom.host', @@ -409,7 +406,7 @@ class GeneratorTest extends AbstractTestCase Generator::getServerSSL() ); - $cfg['Server'] = [ + $GLOBALS['cfg']['Server'] = [ 'ssl' => true, 'ssl_verify' => false, 'host' => 'custom.host', @@ -423,7 +420,7 @@ class GeneratorTest extends AbstractTestCase Generator::getServerSSL() ); - $cfg['Server'] = [ + $GLOBALS['cfg']['Server'] = [ 'ssl' => true, 'ssl_verify' => true, 'host' => 'custom.host', @@ -437,7 +434,7 @@ class GeneratorTest extends AbstractTestCase Generator::getServerSSL() ); - $cfg['Server'] = [ + $GLOBALS['cfg']['Server'] = [ 'ssl' => true, 'ssl_verify' => true, 'ssl_ca' => '/etc/ssl/ca.crt', diff --git a/test/classes/ImportTest.php b/test/classes/ImportTest.php index 6cd7ea0225..bdd3d569e7 100644 --- a/test/classes/ImportTest.php +++ b/test/classes/ImportTest.php @@ -26,6 +26,13 @@ class ImportTest extends AbstractTestCase parent::setUp(); $GLOBALS['server'] = 0; $GLOBALS['cfg']['ServerDefault'] = ''; + $GLOBALS['import_run_buffer'] = null; + $GLOBALS['complete_query'] = null; + $GLOBALS['display_query'] = null; + $GLOBALS['skip_queries'] = null; + $GLOBALS['max_sql_len'] = null; + $GLOBALS['sql_query_disabled'] = null; + $GLOBALS['executed_queries'] = null; $this->import = new Import(); } @@ -34,40 +41,38 @@ class ImportTest extends AbstractTestCase */ public function testCheckTimeout(): void { - global $timestamp, $maximum_time, $timeout_passed; - //Reinit values. - $timestamp = time(); - $maximum_time = 0; - $timeout_passed = false; + $GLOBALS['timestamp'] = time(); + $GLOBALS['maximum_time'] = 0; + $GLOBALS['timeout_passed'] = false; $this->assertFalse($this->import->checkTimeout()); //Reinit values. - $timestamp = time(); - $maximum_time = 0; - $timeout_passed = true; + $GLOBALS['timestamp'] = time(); + $GLOBALS['maximum_time'] = 0; + $GLOBALS['timeout_passed'] = true; $this->assertFalse($this->import->checkTimeout()); //Reinit values. - $timestamp = time(); - $maximum_time = 30; - $timeout_passed = true; + $GLOBALS['timestamp'] = time(); + $GLOBALS['maximum_time'] = 30; + $GLOBALS['timeout_passed'] = true; $this->assertTrue($this->import->checkTimeout()); //Reinit values. - $timestamp = time() - 15; - $maximum_time = 30; - $timeout_passed = false; + $GLOBALS['timestamp'] = time() - 15; + $GLOBALS['maximum_time'] = 30; + $GLOBALS['timeout_passed'] = false; $this->assertFalse($this->import->checkTimeout()); //Reinit values. - $timestamp = time() - 60; - $maximum_time = 30; - $timeout_passed = false; + $GLOBALS['timestamp'] = time() - 60; + $GLOBALS['maximum_time'] = 30; + $GLOBALS['timeout_passed'] = false; $this->assertTrue($this->import->checkTimeout()); } @@ -562,7 +567,7 @@ class ImportTest extends AbstractTestCase 'sql' => 'SELECT 1;', 'full' => 'SELECT 1;', ], $GLOBALS['import_run_buffer']); - $this->assertNull($GLOBALS['sql_query']); + $this->assertSame('', $GLOBALS['sql_query']); $this->assertNull($GLOBALS['complete_query']); $this->assertNull($GLOBALS['display_query']); @@ -601,7 +606,7 @@ class ImportTest extends AbstractTestCase 'valid_queries' => 2, ], $sqlData); - $this->assertArrayNotHasKey('import_run_buffer', $GLOBALS); + $this->assertNull($GLOBALS['import_run_buffer']); $this->assertSame('SELECT 2;', $GLOBALS['sql_query']); $this->assertSame('SELECT 1;SELECT 2;', $GLOBALS['complete_query']); $this->assertSame('SELECT 1;SELECT 2;', $GLOBALS['display_query']); diff --git a/test/classes/OperationsTest.php b/test/classes/OperationsTest.php index fea0406c4a..4f1075ebcc 100644 --- a/test/classes/OperationsTest.php +++ b/test/classes/OperationsTest.php @@ -31,10 +31,8 @@ class OperationsTest extends AbstractTestCase */ public function testGetPartitionMaintenanceChoices(string $tableName, array $extraChoice): void { - global $db, $table; - - $db = 'database'; - $table = $tableName; + $GLOBALS['db'] = 'database'; + $GLOBALS['table'] = $tableName; $choices = [ 'ANALYZE' => 'Analyze', diff --git a/test/classes/Plugins/Auth/AuthenticationCookieTest.php b/test/classes/Plugins/Auth/AuthenticationCookieTest.php index 2f693930bb..7aafc2242b 100644 --- a/test/classes/Plugins/Auth/AuthenticationCookieTest.php +++ b/test/classes/Plugins/Auth/AuthenticationCookieTest.php @@ -53,6 +53,7 @@ class AuthenticationCookieTest extends AbstractNetworkTestCase $this->object = new AuthenticationCookie(); $GLOBALS['PMA_PHP_SELF'] = '/phpmyadmin/'; $GLOBALS['cfg']['Server']['DisableIS'] = false; + $GLOBALS['conn_error'] = null; } /** diff --git a/test/classes/Plugins/Export/ExportCsvTest.php b/test/classes/Plugins/Export/ExportCsvTest.php index 6599c71fd3..793081b7bb 100644 --- a/test/classes/Plugins/Export/ExportCsvTest.php +++ b/test/classes/Plugins/Export/ExportCsvTest.php @@ -40,6 +40,10 @@ class ExportCsvTest extends AbstractTestCase $GLOBALS['lang'] = ''; $GLOBALS['text_dir'] = ''; $GLOBALS['PMA_PHP_SELF'] = ''; + $GLOBALS['csv_enclosed'] = null; + $GLOBALS['csv_separator'] = null; + $GLOBALS['save_filename'] = null; + $this->object = new ExportCsv(); } diff --git a/test/classes/Plugins/Export/ExportSqlTest.php b/test/classes/Plugins/Export/ExportSqlTest.php index 94240e1f44..d1cab2b0e0 100644 --- a/test/classes/Plugins/Export/ExportSqlTest.php +++ b/test/classes/Plugins/Export/ExportSqlTest.php @@ -65,6 +65,11 @@ class ExportSqlTest extends AbstractTestCase $GLOBALS['plugin_param'] = []; $GLOBALS['plugin_param']['export_type'] = 'table'; $GLOBALS['plugin_param']['single_table'] = false; + $GLOBALS['sql_constraints'] = null; + $GLOBALS['sql_backquotes'] = null; + $GLOBALS['sql_indexes'] = null; + $GLOBALS['sql_auto_increments'] = null; + $this->object = new ExportSql(); } @@ -1070,6 +1075,7 @@ class ExportSqlTest extends AbstractTestCase // case 3 $GLOBALS['sql_views_as_tables'] = false; + $GLOBALS['sql_backquotes'] = null; ob_start(); $this->assertTrue( diff --git a/test/classes/Plugins/Export/ExportXmlTest.php b/test/classes/Plugins/Export/ExportXmlTest.php index 5f4e77d118..9dda1d2ac7 100644 --- a/test/classes/Plugins/Export/ExportXmlTest.php +++ b/test/classes/Plugins/Export/ExportXmlTest.php @@ -45,6 +45,7 @@ class ExportXmlTest extends AbstractTestCase $GLOBALS['plugin_param']['single_table'] = false; $GLOBALS['db'] = 'db'; $GLOBALS['cfg']['Server']['DisableIS'] = true; + $GLOBALS['crlf'] = "\n"; $this->object = new ExportXml(); } diff --git a/test/classes/Plugins/Import/ImportCsvTest.php b/test/classes/Plugins/Import/ImportCsvTest.php index 4798f278aa..28d6c85d89 100644 --- a/test/classes/Plugins/Import/ImportCsvTest.php +++ b/test/classes/Plugins/Import/ImportCsvTest.php @@ -29,9 +29,24 @@ class ImportCsvTest extends AbstractTestCase parent::setUp(); $GLOBALS['server'] = 0; $GLOBALS['plugin_param'] = 'csv'; - $this->object = new ImportCsv(); + $GLOBALS['errorUrl'] = 'index.php?route=/'; + $GLOBALS['error'] = false; + $GLOBALS['db'] = ''; + $GLOBALS['table'] = ''; + $GLOBALS['sql_query'] = ''; + $GLOBALS['message'] = null; + $GLOBALS['csv_columns'] = null; + $GLOBALS['timeout_passed'] = null; + $GLOBALS['maximum_time'] = null; + $GLOBALS['charset_conversion'] = null; + $GLOBALS['import_run_buffer'] = null; + $GLOBALS['skip_queries'] = null; + $GLOBALS['max_sql_len'] = null; + $GLOBALS['executed_queries'] = null; + $GLOBALS['run_query'] = null; + $GLOBALS['go_sql'] = null; - unset($GLOBALS['db']); + $this->object = new ImportCsv(); //setting $GLOBALS['finished'] = false; @@ -97,8 +112,8 @@ class ImportCsvTest extends AbstractTestCase public function testDoImport(): void { //$sql_query_disabled will show the import SQL detail - global $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; $importHandle = new File($GLOBALS['import_file']); $importHandle->open(); @@ -107,10 +122,13 @@ class ImportCsvTest extends AbstractTestCase $this->object->doImport($importHandle); //asset that all sql are executed - $this->assertStringContainsString('CREATE DATABASE IF NOT EXISTS `CSV_DB 1` DEFAULT CHARACTER', $sql_query); + $this->assertStringContainsString( + 'CREATE DATABASE IF NOT EXISTS `CSV_DB 1` DEFAULT CHARACTER', + $GLOBALS['sql_query'] + ); $this->assertStringContainsString( 'CREATE TABLE IF NOT EXISTS `CSV_DB 1`.`' . $GLOBALS['import_file_name'] . '`', - $sql_query + $GLOBALS['sql_query'] ); $this->assertTrue($GLOBALS['finished']); @@ -124,8 +142,8 @@ class ImportCsvTest extends AbstractTestCase public function testDoPartialImport(): void { //$sql_query_disabled will show the import SQL detail - global $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; $importHandle = new File($GLOBALS['import_file']); $importHandle->open(); @@ -139,8 +157,14 @@ class ImportCsvTest extends AbstractTestCase $this->object->doImport($importHandle); //asset that all sql are executed - $this->assertStringContainsString('CREATE DATABASE IF NOT EXISTS `ImportTestDb` DEFAULT CHARACTER', $sql_query); - $this->assertStringContainsString('CREATE TABLE IF NOT EXISTS `ImportTestDb`.`ImportTestTable`', $sql_query); + $this->assertStringContainsString( + 'CREATE DATABASE IF NOT EXISTS `ImportTestDb` DEFAULT CHARACTER', + $GLOBALS['sql_query'] + ); + $this->assertStringContainsString( + 'CREATE TABLE IF NOT EXISTS `ImportTestDb`.`ImportTestTable`', + $GLOBALS['sql_query'] + ); $this->assertTrue($GLOBALS['finished']); @@ -177,8 +201,8 @@ class ImportCsvTest extends AbstractTestCase public function testDoImportNotAnalysis(): void { //$sql_query_disabled will show the import SQL detail - global $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; $importHandle = new File($GLOBALS['import_file']); $importHandle->open(); @@ -187,11 +211,14 @@ class ImportCsvTest extends AbstractTestCase $this->object->doImport($importHandle); //asset that all sql are executed - $this->assertStringContainsString('CREATE DATABASE IF NOT EXISTS `CSV_DB 1` DEFAULT CHARACTER', $sql_query); + $this->assertStringContainsString( + 'CREATE DATABASE IF NOT EXISTS `CSV_DB 1` DEFAULT CHARACTER', + $GLOBALS['sql_query'] + ); $this->assertStringContainsString( 'CREATE TABLE IF NOT EXISTS `CSV_DB 1`.`' . $GLOBALS['import_file_name'] . '`', - $sql_query + $GLOBALS['sql_query'] ); $this->assertTrue($GLOBALS['finished']); @@ -205,8 +232,8 @@ class ImportCsvTest extends AbstractTestCase public function testDoImportNormal(): void { //$sql_query_disabled will show the import SQL detail - global $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; $GLOBALS['import_type'] = 'query'; $GLOBALS['import_file'] = 'none'; $GLOBALS['csv_terminated'] = ','; @@ -232,7 +259,7 @@ class ImportCsvTest extends AbstractTestCase . 'CREATE TABLE IF NOT EXISTS `CSV_DB 1`.`db_test` (`COL 1` varchar(5), `COL 2` varchar(5))' . ' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;;INSERT INTO `CSV_DB 1`.`db_test`' . ' (`COL 1`, `COL 2`) VALUES (\'Row 1\', \'Row 2\'),' . "\n" . ' (\'123\', \'456\');;', - $sql_query + $GLOBALS['sql_query'] ); $this->assertEquals(true, $GLOBALS['finished']); @@ -247,8 +274,8 @@ class ImportCsvTest extends AbstractTestCase public function testDoImportSkipHeaders(): void { //$sql_query_disabled will show the import SQL detail - global $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; $GLOBALS['import_type'] = 'query'; $GLOBALS['import_file'] = 'none'; $GLOBALS['csv_terminated'] = ','; @@ -276,7 +303,7 @@ class ImportCsvTest extends AbstractTestCase . 'CREATE TABLE IF NOT EXISTS `CSV_DB 1`.`db_test` (`Row 1` int(3), `Row 2` int(3))' . ' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;;INSERT INTO `CSV_DB 1`.`db_test`' . ' (`Row 1`, `Row 2`) VALUES (123, 456);;', - $sql_query + $GLOBALS['sql_query'] ); $this->assertEquals(true, $GLOBALS['finished']); diff --git a/test/classes/Plugins/Import/ImportLdiTest.php b/test/classes/Plugins/Import/ImportLdiTest.php index 8450b80c8d..b71f699e88 100644 --- a/test/classes/Plugins/Import/ImportLdiTest.php +++ b/test/classes/Plugins/Import/ImportLdiTest.php @@ -31,6 +31,19 @@ class ImportLdiTest extends AbstractTestCase protected function setUp(): void { parent::setUp(); + $GLOBALS['charset_conversion'] = null; + $GLOBALS['ldi_terminated'] = null; + $GLOBALS['ldi_escaped'] = null; + $GLOBALS['ldi_columns'] = null; + $GLOBALS['ldi_enclosed'] = null; + $GLOBALS['ldi_new_line'] = null; + $GLOBALS['import_run_buffer'] = null; + $GLOBALS['max_sql_len'] = null; + $GLOBALS['sql_query'] = ''; + $GLOBALS['executed_queries'] = null; + $GLOBALS['skip_queries'] = null; + $GLOBALS['run_query'] = null; + $GLOBALS['go_sql'] = null; //setting $GLOBALS['server'] = 0; $GLOBALS['plugin_param'] = 'table'; @@ -139,8 +152,8 @@ class ImportLdiTest extends AbstractTestCase public function testDoImport(): void { //$sql_query_disabled will show the import SQL detail - global $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; /** * The \PhpMyAdmin\DatabaseInterface mocked object * @@ -160,7 +173,7 @@ class ImportLdiTest extends AbstractTestCase //asset that all sql are executed $this->assertStringContainsString( 'LOAD DATA INFILE \'test/test_data/db_test_ldi.csv\' INTO TABLE `phpmyadmintest`', - $sql_query + $GLOBALS['sql_query'] ); $this->assertTrue($GLOBALS['finished']); @@ -173,8 +186,7 @@ class ImportLdiTest extends AbstractTestCase */ public function testDoImportInvalidFile(): void { - global $import_file; - $import_file = 'none'; + $GLOBALS['import_file'] = 'none'; //Test function called $this->object->doImport(); @@ -195,12 +207,9 @@ class ImportLdiTest extends AbstractTestCase */ public function testDoImportLDISetting(): void { - global $ldi_local_option, $ldi_replace, $ldi_ignore, $ldi_terminated, - $ldi_enclosed, $ldi_new_line, $skip_queries; - //$sql_query_disabled will show the import SQL detail - global $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; /** * The \PhpMyAdmin\DatabaseInterface mocked object * @@ -211,13 +220,13 @@ class ImportLdiTest extends AbstractTestCase ->will($this->returnArgument(0)); $GLOBALS['dbi'] = $dbi; - $ldi_local_option = true; - $ldi_replace = true; - $ldi_ignore = true; - $ldi_terminated = ','; - $ldi_enclosed = ')'; - $ldi_new_line = 'newline_mark'; - $skip_queries = true; + $GLOBALS['ldi_local_option'] = true; + $GLOBALS['ldi_replace'] = true; + $GLOBALS['ldi_ignore'] = true; + $GLOBALS['ldi_terminated'] = ','; + $GLOBALS['ldi_enclosed'] = ')'; + $GLOBALS['ldi_new_line'] = 'newline_mark'; + $GLOBALS['skip_queries'] = true; $importHandle = new File($GLOBALS['import_file']); $importHandle->open(); @@ -229,17 +238,17 @@ class ImportLdiTest extends AbstractTestCase //replace $this->assertStringContainsString( 'LOAD DATA LOCAL INFILE \'test/test_data/db_test_ldi.csv\' REPLACE INTO TABLE `phpmyadmintest`', - $sql_query + $GLOBALS['sql_query'] ); //FIELDS TERMINATED - $this->assertStringContainsString("FIELDS TERMINATED BY ','", $sql_query); + $this->assertStringContainsString("FIELDS TERMINATED BY ','", $GLOBALS['sql_query']); //LINES TERMINATED - $this->assertStringContainsString("LINES TERMINATED BY 'newline_mark'", $sql_query); + $this->assertStringContainsString("LINES TERMINATED BY 'newline_mark'", $GLOBALS['sql_query']); //IGNORE - $this->assertStringContainsString('IGNORE 1 LINES', $sql_query); + $this->assertStringContainsString('IGNORE 1 LINES', $GLOBALS['sql_query']); $this->assertTrue($GLOBALS['finished']); } diff --git a/test/classes/Plugins/Import/ImportMediawikiTest.php b/test/classes/Plugins/Import/ImportMediawikiTest.php index 7c2423609b..f4e2e888f2 100644 --- a/test/classes/Plugins/Import/ImportMediawikiTest.php +++ b/test/classes/Plugins/Import/ImportMediawikiTest.php @@ -27,6 +27,19 @@ class ImportMediawikiTest extends AbstractTestCase { parent::setUp(); $GLOBALS['server'] = 0; + $GLOBALS['error'] = null; + $GLOBALS['timeout_passed'] = null; + $GLOBALS['maximum_time'] = null; + $GLOBALS['charset_conversion'] = null; + $GLOBALS['db'] = ''; + $GLOBALS['import_run_buffer'] = null; + $GLOBALS['skip_queries'] = null; + $GLOBALS['max_sql_len'] = null; + $GLOBALS['sql_query_disabled'] = null; + $GLOBALS['sql_query'] = ''; + $GLOBALS['executed_queries'] = null; + $GLOBALS['run_query'] = null; + $GLOBALS['go_sql'] = null; $GLOBALS['plugin_param'] = 'database'; $this->object = new ImportMediawiki(); @@ -87,7 +100,6 @@ class ImportMediawikiTest extends AbstractTestCase public function testDoImport(): void { //$import_notice will show the import detail result - global $import_notice; //Mock DBI $dbi = $this->getMockBuilder(DatabaseInterface::class) @@ -117,12 +129,12 @@ class ImportMediawikiTest extends AbstractTestCase //asset that all databases and tables are imported $this->assertStringContainsString( 'The following structures have either been created or altered.', - $import_notice + $GLOBALS['import_notice'] ); - $this->assertStringContainsString('Go to database: `mediawiki_DB`', $import_notice); - $this->assertStringContainsString('Edit settings for `mediawiki_DB`', $import_notice); - $this->assertStringContainsString('Go to table: `pma_bookmarktest`', $import_notice); - $this->assertStringContainsString('Edit settings for `pma_bookmarktest`', $import_notice); + $this->assertStringContainsString('Go to database: `mediawiki_DB`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Edit settings for `mediawiki_DB`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Go to table: `pma_bookmarktest`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Edit settings for `pma_bookmarktest`', $GLOBALS['import_notice']); $this->assertTrue($GLOBALS['finished']); } } diff --git a/test/classes/Plugins/Import/ImportOdsTest.php b/test/classes/Plugins/Import/ImportOdsTest.php index 10f289f035..d62092692a 100644 --- a/test/classes/Plugins/Import/ImportOdsTest.php +++ b/test/classes/Plugins/Import/ImportOdsTest.php @@ -29,6 +29,18 @@ class ImportOdsTest extends AbstractTestCase parent::setUp(); $GLOBALS['server'] = 0; $GLOBALS['plugin_param'] = 'csv'; + $GLOBALS['error'] = null; + $GLOBALS['timeout_passed'] = null; + $GLOBALS['maximum_time'] = null; + $GLOBALS['charset_conversion'] = null; + $GLOBALS['db'] = ''; + $GLOBALS['import_run_buffer'] = null; + $GLOBALS['skip_queries'] = null; + $GLOBALS['max_sql_len'] = null; + $GLOBALS['executed_queries'] = null; + $GLOBALS['run_query'] = null; + $GLOBALS['sql_query'] = ''; + $GLOBALS['go_sql'] = null; $this->object = new ImportOds(); //setting @@ -89,8 +101,8 @@ class ImportOdsTest extends AbstractTestCase { //$sql_query_disabled will show the import SQL detail //$import_notice will show the import detail result - global $import_notice, $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; $GLOBALS['import_file'] = 'test/test_data/db_test.ods'; $_REQUEST['ods_empty_rows'] = true; @@ -106,23 +118,23 @@ class ImportOdsTest extends AbstractTestCase $this->assertStringContainsString( 'CREATE DATABASE IF NOT EXISTS `ODS_DB` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci', - $sql_query + $GLOBALS['sql_query'] ); - $this->assertStringContainsString('CREATE TABLE IF NOT EXISTS `ODS_DB`.`pma_bookmark`', $sql_query); + $this->assertStringContainsString('CREATE TABLE IF NOT EXISTS `ODS_DB`.`pma_bookmark`', $GLOBALS['sql_query']); $this->assertStringContainsString( 'INSERT INTO `ODS_DB`.`pma_bookmark` (`A`, `B`, `C`, `D`) VALUES (1, \'dbbase\', NULL, \'ddd\');', - $sql_query + $GLOBALS['sql_query'] ); //asset that all databases and tables are imported $this->assertStringContainsString( 'The following structures have either been created or altered.', - $import_notice + $GLOBALS['import_notice'] ); - $this->assertStringContainsString('Go to database: `ODS_DB`', $import_notice); - $this->assertStringContainsString('Edit settings for `ODS_DB`', $import_notice); - $this->assertStringContainsString('Go to table: `pma_bookmark`', $import_notice); - $this->assertStringContainsString('Edit settings for `pma_bookmark`', $import_notice); + $this->assertStringContainsString('Go to database: `ODS_DB`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Edit settings for `ODS_DB`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Go to table: `pma_bookmark`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Edit settings for `pma_bookmark`', $GLOBALS['import_notice']); //asset that the import process is finished $this->assertTrue($GLOBALS['finished']); @@ -147,8 +159,8 @@ class ImportOdsTest extends AbstractTestCase { //$sql_query_disabled will show the import SQL detail //$import_notice will show the import detail result - global $import_notice, $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; $GLOBALS['import_file'] = 'test/test_data/import-slim.ods.xml'; $_REQUEST['ods_col_names'] = true; @@ -226,18 +238,18 @@ class ImportOdsTest extends AbstractTestCase . ' (\'12\')' . ($odsEmptyRowsMode ? '' : ',' . "\n" . ' (NULL)') . ($odsEmptyRowsMode ? ';;' : ',' . "\n" . ' (NULL);;'), - $sql_query + $GLOBALS['sql_query'] ); //asset that all databases and tables are imported $this->assertStringContainsString( 'The following structures have either been created or altered.', - $import_notice + $GLOBALS['import_notice'] ); - $this->assertStringContainsString('Go to database: `ODS_DB`', $import_notice); - $this->assertStringContainsString('Edit settings for `ODS_DB`', $import_notice); - $this->assertStringContainsString('Go to table: `Shop`', $import_notice); - $this->assertStringContainsString('Edit settings for `Shop`', $import_notice); + $this->assertStringContainsString('Go to database: `ODS_DB`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Edit settings for `ODS_DB`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Go to table: `Shop`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Edit settings for `Shop`', $GLOBALS['import_notice']); //asset that the import process is finished $this->assertTrue($GLOBALS['finished']); diff --git a/test/classes/Plugins/Import/ImportShpTest.php b/test/classes/Plugins/Import/ImportShpTest.php index b9f06b56c0..af870d060b 100644 --- a/test/classes/Plugins/Import/ImportShpTest.php +++ b/test/classes/Plugins/Import/ImportShpTest.php @@ -28,6 +28,19 @@ class ImportShpTest extends AbstractTestCase protected function setUp(): void { parent::setUp(); + $GLOBALS['error'] = null; + $GLOBALS['buffer'] = null; + $GLOBALS['maximum_time'] = null; + $GLOBALS['charset_conversion'] = null; + $GLOBALS['import_run_buffer'] = null; + $GLOBALS['eof'] = null; + $GLOBALS['db'] = ''; + $GLOBALS['skip_queries'] = null; + $GLOBALS['max_sql_len'] = null; + $GLOBALS['sql_query'] = ''; + $GLOBALS['executed_queries'] = null; + $GLOBALS['run_query'] = null; + $GLOBALS['go_sql'] = null; $GLOBALS['server'] = 0; //setting @@ -114,13 +127,14 @@ class ImportShpTest extends AbstractTestCase { //$sql_query_disabled will show the import SQL detail //$import_notice will show the import detail result - global $import_notice, $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; + $GLOBALS['db'] = ''; //Test function called $this->runImport('test/test_data/dresden_osm.shp.zip'); - $this->assertMessages($import_notice); + $this->assertMessages($GLOBALS['import_notice']); $endsWith = "13.737122 51.0542065)))'))"; @@ -135,7 +149,7 @@ class ImportShpTest extends AbstractTestCase . '13.7372661 51.0540944,' . '13.7370842 51.0541711,' . $endsWith, - $sql_query + $GLOBALS['sql_query'] ); } @@ -149,8 +163,9 @@ class ImportShpTest extends AbstractTestCase { //$sql_query_disabled will show the import SQL detail //$import_notice will show the import detail result - global $import_notice, $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; + $GLOBALS['db'] = ''; //Test function called $this->runImport('test/test_data/timezone.shp.zip'); @@ -158,7 +173,7 @@ class ImportShpTest extends AbstractTestCase // asset that all sql are executed $this->assertStringContainsString( 'CREATE DATABASE IF NOT EXISTS `SHP_DB` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci', - $sql_query + $GLOBALS['sql_query'] ); // dbase extension will generate different sql statement @@ -167,26 +182,29 @@ class ImportShpTest extends AbstractTestCase 'CREATE TABLE IF NOT EXISTS `SHP_DB`.`TBL_NAME` ' . '(`SPATIAL` geometry, `ID` int(2), `AUTHORITY` varchar(25), `NAME` varchar(42)) ' . 'DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;', - $sql_query + $GLOBALS['sql_query'] ); $this->assertStringContainsString( 'INSERT INTO `SHP_DB`.`TBL_NAME` (`SPATIAL`, `ID`, `AUTHORITY`, `NAME`) VALUES', - $sql_query + $GLOBALS['sql_query'] ); } else { $this->assertStringContainsString( 'CREATE TABLE IF NOT EXISTS `SHP_DB`.`TBL_NAME` (`SPATIAL` geometry)', - $sql_query + $GLOBALS['sql_query'] ); - $this->assertStringContainsString('INSERT INTO `SHP_DB`.`TBL_NAME` (`SPATIAL`) VALUES', $sql_query); + $this->assertStringContainsString( + 'INSERT INTO `SHP_DB`.`TBL_NAME` (`SPATIAL`) VALUES', + $GLOBALS['sql_query'] + ); } - $this->assertStringContainsString("GeomFromText('POINT(1294523.1759236", $sql_query); + $this->assertStringContainsString("GeomFromText('POINT(1294523.1759236", $GLOBALS['sql_query']); //asset that all databases and tables are imported - $this->assertMessages($import_notice); + $this->assertMessages($GLOBALS['import_notice']); } /** diff --git a/test/classes/Plugins/Import/ImportSqlTest.php b/test/classes/Plugins/Import/ImportSqlTest.php index 6222cf9cd1..a2db2ca973 100644 --- a/test/classes/Plugins/Import/ImportSqlTest.php +++ b/test/classes/Plugins/Import/ImportSqlTest.php @@ -25,6 +25,17 @@ class ImportSqlTest extends AbstractTestCase { parent::setUp(); $GLOBALS['server'] = 0; + $GLOBALS['error'] = null; + $GLOBALS['timeout_passed'] = null; + $GLOBALS['maximum_time'] = null; + $GLOBALS['charset_conversion'] = null; + $GLOBALS['import_run_buffer'] = null; + $GLOBALS['skip_queries'] = null; + $GLOBALS['max_sql_len'] = null; + $GLOBALS['sql_query'] = ''; + $GLOBALS['executed_queries'] = null; + $GLOBALS['run_query'] = null; + $GLOBALS['go_sql'] = null; $this->object = new ImportSql(); @@ -59,8 +70,8 @@ class ImportSqlTest extends AbstractTestCase public function testDoImport(): void { //$sql_query_disabled will show the import SQL detail - global $sql_query, $sql_query_disabled; - $sql_query_disabled = false; + + $GLOBALS['sql_query_disabled'] = false; //Mock DBI $dbi = $this->getMockBuilder(DatabaseInterface::class) @@ -75,11 +86,11 @@ class ImportSqlTest extends AbstractTestCase $this->object->doImport($importHandle); //asset that all sql are executed - $this->assertStringContainsString('SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"', $sql_query); - $this->assertStringContainsString('CREATE TABLE IF NOT EXISTS `pma_bookmark`', $sql_query); + $this->assertStringContainsString('SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"', $GLOBALS['sql_query']); + $this->assertStringContainsString('CREATE TABLE IF NOT EXISTS `pma_bookmark`', $GLOBALS['sql_query']); $this->assertStringContainsString( 'INSERT INTO `pma_bookmark` (`id`, `dbase`, `user`, `label`, `query`) VALUES', - $sql_query + $GLOBALS['sql_query'] ); $this->assertTrue($GLOBALS['finished']); diff --git a/test/classes/Plugins/Import/ImportXmlTest.php b/test/classes/Plugins/Import/ImportXmlTest.php index c90bb97e1c..0db818dd5b 100644 --- a/test/classes/Plugins/Import/ImportXmlTest.php +++ b/test/classes/Plugins/Import/ImportXmlTest.php @@ -29,6 +29,19 @@ class ImportXmlTest extends AbstractTestCase { parent::setUp(); $GLOBALS['server'] = 0; + $GLOBALS['error'] = null; + $GLOBALS['timeout_passed'] = null; + $GLOBALS['maximum_time'] = null; + $GLOBALS['charset_conversion'] = null; + $GLOBALS['db'] = ''; + $GLOBALS['import_run_buffer'] = null; + $GLOBALS['skip_queries'] = null; + $GLOBALS['max_sql_len'] = null; + $GLOBALS['sql_query_disabled'] = null; + $GLOBALS['sql_query'] = ''; + $GLOBALS['executed_queries'] = null; + $GLOBALS['run_query'] = null; + $GLOBALS['go_sql'] = null; $this->object = new ImportXml(); @@ -91,7 +104,6 @@ class ImportXmlTest extends AbstractTestCase public function testDoImport(): void { //$import_notice will show the import detail result - global $import_notice; //Mock DBI $dbi = $this->getMockBuilder(DatabaseInterface::class) @@ -121,12 +133,12 @@ class ImportXmlTest extends AbstractTestCase //asset that all databases and tables are imported $this->assertStringContainsString( 'The following structures have either been created or altered.', - $import_notice + $GLOBALS['import_notice'] ); - $this->assertStringContainsString('Go to database: `phpmyadmintest`', $import_notice); - $this->assertStringContainsString('Edit settings for `phpmyadmintest`', $import_notice); - $this->assertStringContainsString('Go to table: `pma_bookmarktest`', $import_notice); - $this->assertStringContainsString('Edit settings for `pma_bookmarktest`', $import_notice); + $this->assertStringContainsString('Go to database: `phpmyadmintest`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Edit settings for `phpmyadmintest`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Go to table: `pma_bookmarktest`', $GLOBALS['import_notice']); + $this->assertStringContainsString('Edit settings for `pma_bookmarktest`', $GLOBALS['import_notice']); $this->assertTrue($GLOBALS['finished']); } } diff --git a/test/classes/Plugins/Transformations/TransformationPluginsTest.php b/test/classes/Plugins/Transformations/TransformationPluginsTest.php index 5a9344bef9..dfdcdadf0a 100644 --- a/test/classes/Plugins/Transformations/TransformationPluginsTest.php +++ b/test/classes/Plugins/Transformations/TransformationPluginsTest.php @@ -49,9 +49,9 @@ class TransformationPluginsTest extends AbstractTestCase parent::setUp(); parent::setLanguage(); // For Application Octetstream Download plugin - global $row, $fields_meta; - $fields_meta = []; - $row = [ + + $GLOBALS['fields_meta'] = []; + $GLOBALS['row'] = [ 'pma' => 'aaa', 'pca' => 'bbb', ]; diff --git a/test/classes/PluginsTest.php b/test/classes/PluginsTest.php index 697d82e48a..f107279b3a 100644 --- a/test/classes/PluginsTest.php +++ b/test/classes/PluginsTest.php @@ -13,11 +13,9 @@ class PluginsTest extends AbstractTestCase { public function testGetExport(): void { - global $plugin_param; - $GLOBALS['server'] = 1; $plugins = Plugins::getExport('database', false); - $this->assertEquals(['export_type' => 'database', 'single_table' => false], $plugin_param); + $this->assertEquals(['export_type' => 'database', 'single_table' => false], $GLOBALS['plugin_param']); $this->assertIsArray($plugins); $this->assertCount(14, $plugins); $this->assertContainsOnlyInstancesOf(Plugins\ExportPlugin::class, $plugins); @@ -25,10 +23,8 @@ class PluginsTest extends AbstractTestCase public function testGetImport(): void { - global $plugin_param; - $plugins = Plugins::getImport('database'); - $this->assertEquals('database', $plugin_param); + $this->assertEquals('database', $GLOBALS['plugin_param']); $this->assertIsArray($plugins); $this->assertCount(6, $plugins); $this->assertContainsOnlyInstancesOf(Plugins\ImportPlugin::class, $plugins); @@ -56,21 +52,19 @@ class PluginsTest extends AbstractTestCase string $option, ?bool $timeoutPassed ): void { - global $cfg, $strLatexContinued, $strLatexStructure, $timeout_passed; - $_GET = []; $_REQUEST = []; if ($timeoutPassed !== null) { - $timeout_passed = $timeoutPassed; + $GLOBALS['timeout_passed'] = $timeoutPassed; $_REQUEST[$option] = $actualGet; } elseif ($actualGet !== null) { $_GET[$option] = $actualGet; } - $strLatexContinued = '(continued)'; - $strLatexStructure = 'Structure of table @TABLE@'; + $GLOBALS['strLatexContinued'] = '(continued)'; + $GLOBALS['strLatexStructure'] = 'Structure of table @TABLE@'; /** @psalm-suppress InvalidArrayOffset, PossiblyInvalidArrayAssignment */ - $cfg[$section][$option] = $actualConfig; + $GLOBALS['cfg'][$section][$option] = $actualConfig; $default = Plugins::getDefault($section, $option); $this->assertSame($expected, $default); } @@ -102,10 +96,8 @@ class PluginsTest extends AbstractTestCase public function testGetChoice(): void { - global $plugin_param; - $GLOBALS['server'] = 1; - $plugin_param = ['export_type' => 'database', 'single_table' => false]; + $GLOBALS['plugin_param'] = ['export_type' => 'database', 'single_table' => false]; $exportList = [ new Plugins\Export\ExportJson(), new Plugins\Export\ExportOds(), diff --git a/test/classes/ProfilingTest.php b/test/classes/ProfilingTest.php index eb73b8711c..752491e6b1 100644 --- a/test/classes/ProfilingTest.php +++ b/test/classes/ProfilingTest.php @@ -14,16 +14,14 @@ class ProfilingTest extends AbstractTestCase { public function testIsSupported(): void { - global $dbi, $server; - - $server = 1; + $GLOBALS['server'] = 1; SessionCache::set('profiling_supported', true); - $condition = Profiling::isSupported($dbi); + $condition = Profiling::isSupported($GLOBALS['dbi']); $this->assertTrue($condition); SessionCache::set('profiling_supported', false); - $condition = Profiling::isSupported($dbi); + $condition = Profiling::isSupported($GLOBALS['dbi']); $this->assertFalse($condition); } } diff --git a/test/classes/SqlTest.php b/test/classes/SqlTest.php index 4fc9be9328..b464cbfe8a 100644 --- a/test/classes/SqlTest.php +++ b/test/classes/SqlTest.php @@ -50,6 +50,7 @@ class SqlTest extends AbstractTestCase $GLOBALS['cfg']['LoginCookieValidity'] = 1440; $GLOBALS['cfg']['enable_drag_drop_import'] = true; $GLOBALS['PMA_PHP_SELF'] = 'index.php'; + $GLOBALS['showtable'] = null; $relation = new Relation($GLOBALS['dbi']); $this->sql = new Sql( @@ -346,9 +347,7 @@ class SqlTest extends AbstractTestCase */ private function parseAndAnalyze(string $sqlQuery) { - global $db; - - [$analyzedSqlResults] = ParseAnalyze::sqlQuery($sqlQuery, $db); + [$analyzedSqlResults] = ParseAnalyze::sqlQuery($sqlQuery, $GLOBALS['db']); return $analyzedSqlResults; } diff --git a/test/classes/Stubs/DbiDummy.php b/test/classes/Stubs/DbiDummy.php index 148045bed5..00d4f29ca8 100644 --- a/test/classes/Stubs/DbiDummy.php +++ b/test/classes/Stubs/DbiDummy.php @@ -421,9 +421,7 @@ class DbiDummy implements DbiExtension */ public function affectedRows($link = null, $get_from_cache = true) { - global $cached_affected_rows; - - return $cached_affected_rows ?? 0; + return $GLOBALS['cached_affected_rows'] ?? 0; } /** diff --git a/test/classes/Table/SearchTest.php b/test/classes/Table/SearchTest.php index d90f6cda23..c71fa2e884 100644 --- a/test/classes/Table/SearchTest.php +++ b/test/classes/Table/SearchTest.php @@ -18,9 +18,8 @@ class SearchTest extends AbstractTestCase protected function setUp(): void { parent::setUp(); - global $dbi; - $this->search = new Search($dbi); + $this->search = new Search($GLOBALS['dbi']); } public function testBuildSqlQuery(): void diff --git a/test/classes/TableTest.php b/test/classes/TableTest.php index c95cff3d68..75d0d2a759 100644 --- a/test/classes/TableTest.php +++ b/test/classes/TableTest.php @@ -943,9 +943,7 @@ class TableTest extends AbstractTestCase */ public function testIsMergeCase2(): void { - global $dbi; - - $dbi->getCache()->cacheTableContent( + $GLOBALS['dbi']->getCache()->cacheTableContent( ['PMA', 'PMA_BookMark'], ['ENGINE' => 'MERGE'] ); @@ -961,9 +959,7 @@ class TableTest extends AbstractTestCase */ public function testIsMergeCase3(): void { - global $dbi; - - $dbi->getCache()->cacheTableContent( + $GLOBALS['dbi']->getCache()->cacheTableContent( ['PMA', 'PMA_BookMark'], ['ENGINE' => 'MRG_MYISAM'] ); diff --git a/test/classes/TemplateTest.php b/test/classes/TemplateTest.php index 6c915f42ba..dba4b249e5 100644 --- a/test/classes/TemplateTest.php +++ b/test/classes/TemplateTest.php @@ -31,15 +31,13 @@ class TemplateTest extends AbstractTestCase */ public function testGetTwigEnvironment(): void { - global $cfg; - $this->loadContainerBuilder(); - $cfg['environment'] = 'production'; + $GLOBALS['cfg']['environment'] = 'production'; $twig = Template::getTwigEnvironment(null); $this->assertFalse($twig->isDebug()); $this->assertFalse(TransNode::$enableAddDebugInfo); - $cfg['environment'] = 'development'; + $GLOBALS['cfg']['environment'] = 'development'; $twig = Template::getTwigEnvironment(null); $this->assertTrue($twig->isDebug()); $this->assertTrue(TransNode::$enableAddDebugInfo); diff --git a/test/classes/ThemeTest.php b/test/classes/ThemeTest.php index e5c39099ab..32762d6512 100644 --- a/test/classes/ThemeTest.php +++ b/test/classes/ThemeTest.php @@ -28,13 +28,11 @@ class ThemeTest extends AbstractTestCase */ protected function setUp(): void { - global $theme; - parent::setUp(); parent::setTheme(); $this->object = new Theme(); - $this->backup = $theme; - $theme = $this->object; + $this->backup = $GLOBALS['theme']; + $GLOBALS['theme'] = $this->object; parent::setGlobalConfig(); $GLOBALS['text_dir'] = 'ltr'; $GLOBALS['server'] = '99'; @@ -46,10 +44,8 @@ class ThemeTest extends AbstractTestCase */ protected function tearDown(): void { - global $theme; - parent::tearDown(); - $theme = $this->backup; + $GLOBALS['theme'] = $this->backup; } /** diff --git a/test/classes/TrackerTest.php b/test/classes/TrackerTest.php index a642d4c2e8..af7c6d9e64 100644 --- a/test/classes/TrackerTest.php +++ b/test/classes/TrackerTest.php @@ -33,6 +33,7 @@ class TrackerTest extends AbstractTestCase $GLOBALS['cfg']['Server']['tracking_default_statements'] = ''; $GLOBALS['cfg']['Server']['tracking_version_auto_create'] = ''; $GLOBALS['cfg']['Server']['DisableIS'] = false; + $GLOBALS['export_type'] = null; $_SESSION['relation'] = []; $_SESSION['relation'][$GLOBALS['server']] = RelationParameters::fromArray([ diff --git a/test/classes/UrlTest.php b/test/classes/UrlTest.php index 0e54fe1fbe..5708af34f6 100644 --- a/test/classes/UrlTest.php +++ b/test/classes/UrlTest.php @@ -188,9 +188,7 @@ class UrlTest extends AbstractTestCase */ public function testBuildHttpQueryWithUrlQueryEncryptionDisabled() { - global $config; - - $config->set('URLQueryEncryption', false); + $GLOBALS['config']->set('URLQueryEncryption', false); $params = ['db' => 'test_db', 'table' => 'test_table', 'pos' => 0]; $this->assertEquals('db=test_db&table=test_table&pos=0', Url::buildHttpQuery($params)); } @@ -200,11 +198,9 @@ class UrlTest extends AbstractTestCase */ public function testBuildHttpQueryWithUrlQueryEncryptionEnabled() { - global $config; - $_SESSION = []; - $config->set('URLQueryEncryption', true); - $config->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); + $GLOBALS['config']->set('URLQueryEncryption', true); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); $params = ['db' => 'test_db', 'table' => 'test_table', 'pos' => 0]; $query = Url::buildHttpQuery($params); @@ -232,11 +228,9 @@ class UrlTest extends AbstractTestCase */ public function testQueryEncryption() { - global $config; - $_SESSION = []; - $config->set('URLQueryEncryption', true); - $config->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); + $GLOBALS['config']->set('URLQueryEncryption', true); + $GLOBALS['config']->set('URLQueryEncryptionSecretKey', str_repeat('a', 32)); $query = '{"db":"test_db","table":"test_table"}'; $encrypted = Url::encryptQuery($query); diff --git a/test/classes/Utils/SessionCacheTest.php b/test/classes/Utils/SessionCacheTest.php index 6f45870b1b..08ea101b7f 100644 --- a/test/classes/Utils/SessionCacheTest.php +++ b/test/classes/Utils/SessionCacheTest.php @@ -14,11 +14,9 @@ class SessionCacheTest extends TestCase { public function testGet(): void { - global $cfg, $server; - $_SESSION = []; - $cfg['Server']['user'] = null; - $server = 'server'; + $GLOBALS['cfg']['Server']['user'] = null; + $GLOBALS['server'] = 'server'; SessionCache::set('test_data', 5); SessionCache::set('test_data_2', 5); @@ -30,11 +28,9 @@ class SessionCacheTest extends TestCase public function testRemove(): void { - global $cfg, $server; - $_SESSION = []; - $cfg['Server']['user'] = null; - $server = 'server'; + $GLOBALS['cfg']['Server']['user'] = null; + $GLOBALS['server'] = 'server'; SessionCache::set('test_data', 25); SessionCache::set('test_data_2', 25); @@ -47,11 +43,9 @@ class SessionCacheTest extends TestCase public function testSet(): void { - global $cfg, $server; - $_SESSION = []; - $cfg['Server']['user'] = null; - $server = 'server'; + $GLOBALS['cfg']['Server']['user'] = null; + $GLOBALS['server'] = 'server'; SessionCache::set('test_data', 25); SessionCache::set('test_data', 5); @@ -62,11 +56,9 @@ class SessionCacheTest extends TestCase public function testHas(): void { - global $cfg, $server; - $_SESSION = []; - $cfg['Server']['user'] = null; - $server = 'server'; + $GLOBALS['cfg']['Server']['user'] = null; + $GLOBALS['server'] = 'server'; SessionCache::set('test_data', 5); SessionCache::set('test_data_2', 5); @@ -78,11 +70,9 @@ class SessionCacheTest extends TestCase public function testKeyWithoutUser(): void { - global $cfg, $server; - $_SESSION = []; - $cfg['Server']['user'] = null; - $server = 123; + $GLOBALS['cfg']['Server']['user'] = null; + $GLOBALS['server'] = 123; SessionCache::set('test_data', 5); $this->assertArrayHasKey('cache', $_SESSION); @@ -95,11 +85,9 @@ class SessionCacheTest extends TestCase public function testKeyWithUser(): void { - global $cfg, $server; - $_SESSION = []; - $cfg['Server']['user'] = 'test_user'; - $server = 123; + $GLOBALS['cfg']['Server']['user'] = 'test_user'; + $GLOBALS['server'] = 123; SessionCache::set('test_data', 5); $this->assertArrayHasKey('cache', $_SESSION);