diff options
author | Felipe Figueroa <amenadiel@gmail.com> | 2020-02-26 11:39:06 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-02-26 11:39:06 +0300 |
commit | 1bc0ba72128586602faece1dae9ee0d111cea0b1 (patch) | |
tree | 5152c04f3072c3816b8664b9b4a1439825791997 | |
parent | f1bae70b23dfbc39449cf40161356091642f27ae (diff) | |
parent | 07ec914da495f018220311bd6b46f6ce40dd5dee (diff) |
Merge pull request #262 from HuasoFoundries/enabling_psalm
Enabling psalm
242 files changed, 10344 insertions, 8331 deletions
diff --git a/.gitattributes b/.gitattributes index 81c5bcd0..56aec528 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,15 @@ -/tests export-ignore -.gitattributes export-ignore -.gitignore export-ignore -.build_tests.php export-ignore +.build_tests.php export-ignore +.gitattributes export-ignore +.gitignore export-ignore +/.dependabot export-ignore +/.editorconfig export-ignore +/.gitattributes export-ignore +/.github export-ignore +/.gitignore export-ignore +/.php_cs export-ignore +/infection.json export-ignore +/phpstan-baseline.neon export-ignore +/phpstan.neon export-ignore +/psalm-baseline.xml export-ignore +/psalm.xml export-ignore +/tests export-ignore
\ No newline at end of file @@ -1,28 +1,44 @@ selenium/tests/config.inc.php tests/selenium/config.test.php *sublime* -.php.tools.ini -.*.sh -sftp-config* -config.*.php* -!config.inc.php-dist -!tests/config* -vendor -!assets/vendor -*.log + + + +###> deploy files fabfile* -/.idea/* phppga -.php_cs.cache +.*.sh + + +###> editor specific files +/.idea/* +sublime-* +.php.tools.ini -playground -node_modules +###> temp and generated files temp/sessions/* +playground +*.log +tests/_output + +###> Vendor files +node_modules +vendor +!assets/vendor -config.inc.php +###> Config files other tan examples config.yml -tests/_output -debug.*.php +.configs/ +sftp-config* +config.*.php* +!config.inc.php-dist +!tests/config* + + +###> cache for linters and fixers +.build +.php_cs.cache +.phpunit.result.cache @@ -1,74 +1,142 @@ <?php -$composerinfo = json_decode(file_get_contents('composer.json')); -$version = $composerinfo->version; - -$header = "PHPPgAdmin v$version"; - -$rules=[ - 'no_php4_constructor'=>true, - '@PHP56Migration' => true, - '@PHPUnit60Migration:risky' => true, - '@Symfony' => true, - '@Symfony:risky' => false, - '@PSR1'=>true, - '@PSR2'=>true, - 'align_multiline_comment' => true, - 'array_syntax' => ['syntax' => 'short'], - 'blank_line_before_statement' => true, - 'combine_consecutive_issets' => true, - 'combine_consecutive_unsets' => true, - 'compact_nullable_typehint' => true, - 'escape_implicit_backslashes' => true, - 'explicit_indirect_variable' => true, - 'no_whitespace_in_blank_line'=> true, - 'no_unused_imports'=>true, - 'elseif'=>true, - 'explicit_string_variable' => true, - 'final_internal_class' => true, - 'modernize_types_casting'=>true, - 'header_comment' => ['commentType'=>'PHPDoc','header' => $header], - 'heredoc_to_nowdoc' => true, - 'phpdoc_no_package' => false, - 'list_syntax' => ['syntax' => 'long'], - 'method_chaining_indentation' => true, - 'method_argument_space' => ['ensure_fully_multiline' => true], - 'multiline_comment_opening_closing' => true, - 'no_extra_blank_lines' => ['tokens' => ['break', 'case', 'continue', 'curly_brace_block', 'default', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'switch', 'throw', 'use', 'useTrait', 'use_trait']], - 'no_null_property_initialization' => true, - 'no_short_echo_tag' => true, - 'no_superfluous_elseif' => true, - 'no_unneeded_curly_braces' => true, - 'no_unneeded_final_method' => true, - 'no_unreachable_default_argument_value' => true, - 'no_useless_else' => true, - 'no_useless_return' => true, - 'ordered_class_elements' => false, - 'ordered_imports' => true, - 'php_unit_strict' => true, - 'php_unit_test_annotation' => true, - 'php_unit_test_class_requires_covers' => true, - 'phpdoc_add_missing_param_annotation' => true, - 'phpdoc_align'=>true, - 'phpdoc_order' => true, - 'phpdoc_separation'=>true, - 'phpdoc_scalar'=>true, - 'phpdoc_trim'=>true, - 'phpdoc_types_order' => true, - 'semicolon_after_instruction' => true, - 'single_line_comment_style' => false, - 'strict_comparison' => false, - 'strict_param' => true, - 'single_quote'=>true, - 'yoda_style' => false, - 'binary_operator_spaces' => [ - 'align_double_arrow' => true, - 'align_equals' => true - ] +declare(strict_types=1); +/** + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + */ + +use Ergebnis\PhpCsFixer\Config; + +$composerinfo = \json_decode(\file_get_contents('composer.json')); + + +$tags = [ + 'master' => trim(shell_exec('git describe --tags master')), + + 'develop' => trim(shell_exec('git describe --tags develop')), ]; - -$config = PhpCsFixer\Config::create() + +$current_branch = \trim(\shell_exec('git rev-parse --abbrev-ref HEAD')); + +$version = $tags[$current_branch] ?? $tags['develop']; + + +$composer_tags = $composerinfo->extra->current_tags; +var_dump($composerinfo->extra->current_tags); +if ( + \array_key_exists( trim($current_branch), $tags) && + ($tags['master'] !== $composer_tags->master + || $tags['develop'] !== $composer_tags->develop) +) { + $composerinfo->extra->current_tags->master = $tags['master']; + $composerinfo->extra->current_tags->develop = $tags['develop']; + $composerinfo->extra->version = $version; + \file_put_contents('composer.json', \json_encode($composerinfo)); +} + +$header = "PHPPgAdmin {$version}"; +; + +$rules = [ + 'no_php4_constructor' => true, + '@PHP56Migration' => true, + '@PHPUnit60Migration:risky' => true, + '@Symfony' => true, + '@Symfony:risky' => false, + '@PSR1' => true, + '@PSR2' => true, + 'align_multiline_comment' => true, + 'array_syntax' => ['syntax' => 'short'], + 'blank_line_before_statement' => true, + 'combine_consecutive_issets' => true, + 'combine_consecutive_unsets' => true, + 'compact_nullable_typehint' => true, + 'escape_implicit_backslashes' => true, + 'explicit_indirect_variable' => true, + 'no_whitespace_in_blank_line' => true, + 'no_unused_imports' => true, + 'elseif' => true, + 'explicit_string_variable' => true, + 'final_internal_class' => true, + 'modernize_types_casting' => true, + 'header_comment' => ['commentType' => 'PHPDoc', 'header' => $header], + 'heredoc_to_nowdoc' => true, + 'phpdoc_no_package' => false, + 'list_syntax' => ['syntax' => 'long'], + 'method_chaining_indentation' => true, + 'method_argument_space' => ['ensure_fully_multiline' => true], + 'multiline_comment_opening_closing' => true, + 'no_extra_blank_lines' => ['tokens' => ['break', 'case', 'continue', 'curly_brace_block', 'default', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'switch', 'throw', 'use', 'useTrait', 'use_trait']], + 'no_null_property_initialization' => true, + 'no_short_echo_tag' => true, + 'no_superfluous_elseif' => true, + 'no_unneeded_curly_braces' => true, + 'no_unneeded_final_method' => true, + 'no_unreachable_default_argument_value' => true, + 'no_useless_else' => true, + 'no_useless_return' => true, + 'ordered_class_elements' => false, + 'ordered_imports' => true, + 'php_unit_strict' => true, + 'php_unit_test_annotation' => true, + 'php_unit_test_class_requires_covers' => true, + 'phpdoc_add_missing_param_annotation' => true, + 'phpdoc_align' => true, + 'phpdoc_order' => true, + 'phpdoc_separation' => true, + 'phpdoc_scalar' => true, + 'phpdoc_trim' => true, + 'phpdoc_types_order' => true, + 'semicolon_after_instruction' => true, + 'single_line_comment_style' => false, + 'strict_comparison' => false, + 'strict_param' => true, + 'single_quote' => true, + 'yoda_style' => false, + 'binary_operator_spaces' => [ + 'align_double_arrow' => true, + 'align_equals' => true, + ], +]; + +$config = Config\Factory::fromRuleSet(new Config\RuleSet\Php71($header),[ + 'declare_strict_types' => false, + 'header_comment' => ['commentType' => 'PHPDoc', 'header' => $header], + 'escape_implicit_backslashes' => false, + 'final_class'=>false, + 'final_internal_class' => false, + 'final_public_method_for_abstract_class' => false, + 'final_static_access' => false, + 'global_namespace_import' => false, + 'fully_qualified_strict_types' => false, + 'visibility_required' => [ + 'elements' => [ + 'method', + 'property', + ], + ], +]); + + +$config->getFinder() + ->ignoreDotFiles(false) + ->in(__DIR__.'/src/decorators') + ->exclude([ + '.build', + '.configs', + '__pycache__', + 'assets', + 'docs', + 'node_modules', + 'temp', + 'tests', + 'vendor', + '.github', + ]) + ->name('.php_cs'); + +/*$config = PhpCsFixer\Config::create() ->setRiskyAllowed(true) ->setRules($rules) ->setFinder( @@ -83,10 +151,25 @@ $config = PhpCsFixer\Config::create() ->in(__DIR__.'/src/traits') ->in(__DIR__.'/src/database/databasetraits') ->in(__DIR__.'/tests') - - ); + ->exclude([ + '.build', + '.configs', + '__pycache__', + 'assets', + 'docs', + 'node_modules', + 'temp', + 'tests', + 'vendor', + '.github', + ]) + ->name('.php_cs') + + );*/ +$config->setCacheFile(__DIR__ . '/.build/php-cs-fixer/php_cs.cache'); // special handling of fabbot.io service if it's using too old PHP CS Fixer version +/* try { PhpCsFixer\FixerFactory::create() ->registerBuiltInFixers() @@ -98,6 +181,6 @@ try { $config->setRules([]); } catch (InvalidArgumentException $e) { $config->setRules([]); -} - +} +*/ return $config; diff --git a/.psalm.log b/.psalm.log new file mode 100644 index 00000000..373d262e --- /dev/null +++ b/.psalm.log @@ -0,0 +1,15 @@ +------------------------------ +339 errors found +------------------------------ +1617 other issues found. +You can hide them with --show-info=false +------------------------------ +Psalm can automatically fix 97 issues. +Run Psalm again with +--alter --issues=InvalidReturnType,InvalidNullableReturnType,MissingParamType --dry-run +to see what it can fix. +------------------------------ + +Checks took 14.46 seconds and used 203.375MB of memory +Psalm was able to infer types for 81.7737% of the codebase + @@ -2,6 +2,7 @@ VERSION = $(shell cat composer.json | sed -n 's/.*"version": "\([^"]*\)",/\1/p') SHELL = /usr/bin/env bash +HAS_PSALM := $(shell ls ./vendor/bin/xpsalm 2> /dev/null) XDSWI := $(shell command -v xd_swi 2> /dev/null) HAS_PHPMD := $(shell command -v phpmd 2> /dev/null) HAS_CSFIXER:= $(shell command -v php-cs-fixer 2> /dev/null) @@ -18,25 +19,35 @@ default: install .PHONY: tag install test csfixer create_testdb destroy_testdb run_local phpmd version: - @echo -e "Current version is: ${GREEN} $(VERSION) ${WHITE}" - + @echo -e "Current version is: ${GREEN} $(VERSION) ${WHITE}" ;\ + echo -e " master branch closest tag is $(GREEN)" ` git describe --tags master `;\ + echo -e "$(WHITE) develop branch closest tag is $(GREEN)" ` git describe --tags develop `;\ + echo -e "$(WHITE) " +install: fix_permissions install: - sudo rm -R --force temp/twigcache/* - composer install --no-dev - chmod 777 temp -R + @composer install --no-interaction --no-progress --no-suggest --prefer-dist ;\ + composer validate --strict ;\ + #composer normalize + + -fix_permissions: fix_permissions: - sudo chmod 777 temp -R - sudo chown -R www-data:www-data temp/sessions + @sudo chmod 777 temp -R ;\ + sudo chown -R $$USER:www-data temp/sessions ;\ + sudo chown -R $$USER:www-data temp/twigcache ;\ + sudo rm -R --force temp/twigcache/* + +composer_update: + @echo -e "updating composer...${YELLOW}--lock --root-reqs --prefer-dist --prefer-stable --no-suggest -a${WHITE}" ;\ + composer update --lock --root-reqs --prefer-dist --prefer-stable --no-suggest -a update_version: @echo "Current version is " ${VERSION} ;\ echo "Next version is " $(v) ;\ - sed -i s/"$(VERSION)"/"$(v)"/g composer.json - composer update nothing --lock --root-reqs --prefer-dist + sed -i s/"version": "$(VERSION)"/"version": "$(v)"/g composer.json + @${MAKE} composer_update --no-print-directory mocktag: @@ -66,24 +77,31 @@ ifeq ("$(wildcard config.inc.php)","") endif ./vendor/bin/codecept run unit --debug -runcsfixer: - @if [[ "$(HAS_CSFIXER)" == "" ]]; then \ - echo -e "$(GREEN)php-cs-fixer$(WHITE) is $(RED)NOT$(WHITE) installed. " ;\ - echo -e "Install it with $(GREEN)phive install php-cs-fixer global$(WHITE)" ;\ +csfixer: + @if [ -f "vendor/bin/php-cs-fixer" ]; then \ + echo "XDEBUG was: "$(XDSWI_STATUS) ;\ + ${MAKE} disable_xdebug --no-print-directory ;\ + mkdir -p .build/php-cs-fixer ;\ + vendor/bin/php-cs-fixer fix --config=.php_cs --verbose ;\ + ${MAKE} enable_xdebug new_status=$(XDSWI_STATUS) --no-print-directory;\ else \ - php-cs-fixer --verbose fix ;\ - php-cs-fixer --verbose fix index.php ;\ + echo -e "$(GREEN)php-cs-fixer$(WHITE) is $(RED)NOT$(WHITE) installed. " ;\ + echo -e "Install it with $(GREEN)composer install --dev friendsofphp/php-cs-fixer$(WHITE)" ;\ + fi ;\ + sudo rm -rf temp/route.cache.php + + + +disable_xdebug: + @if [[ "$(XDSWI)" != "" ]]; then \ + xd_swi off ;\ + fi + +enable_xdebug: + @if [[ "$(XDSWI)" != "" ]]; then \ + xd_swi $(new_status) ;\ fi -csfixer: - @if [[ "$(XDSWI)" == "" ]]; then \ - ${MAKE} runcsfixer --no-print-directory ;\ - else \ - xd_swi off ;\ - ${MAKE} runcsfixer --no-print-directory ;\ - xd_swi $(XDSWI_STATUS) ;\ - fi - phpmd: @if [ "$(HAS_PHPMD)" == "" ]; then \ echo -e "$(GREEN)phpmd$(WHITE) is $(RED)NOT$(WHITE) installed. " ;\ @@ -98,10 +116,26 @@ var_dumper: vendor/bin/var-dump-server ;\ else \ echo -e "$(GREEN)symfony/var-dumper$(WHITE) is $(RED)NOT$(WHITE) installed. " ;\ - echo -e "Install it with $(GREEN)composer require symfony/var-dumper$(WHITE)" ;\ + echo -e "Install it with $(GREEN)composer require --dev symfony/var-dumper$(WHITE)" ;\ fi; @echo "" +folder ?= src +psalm: FOLDER_BASENAME:=`basename $(folder)` +psalm: + @if [ -f "vendor/bin/psalm" ]; then \ + mkdir -p .build/psalm ;\ + ${MAKE} disable_xdebug --no-print-directory ;\ + vendor/bin/psalm --show-info=false \ + --config=psalm.xml \ + --set-baseline=psalm-baseline-$(FOLDER_BASENAME).xml \ + --shepherd $(folder) ;\ + ${MAKE} enable_xdebug new_status=$(XDSWI_STATUS) --no-print-directory;\ + else \ + echo -e "$(GREEN)vimeo/psalm$(WHITE) is $(RED)NOT$(WHITE) installed. " ;\ + echo -e "Install it with $(GREEN)composer require --dev vimeo/psalm$(WHITE)" ;\ + fi + @echo "" create_testdb: PGPASSWORD=scrutinizer psql -U scrutinizer -h localhost -f tests/simpletest/data/ppatests_install.sql diff --git a/composer.json b/composer.json index e146f6d8..0481df37 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,5 @@ { "name": "huasofoundries/phppgadmin6", - "version": "6.0.0-RC9", "description": "Like phpmyadmin but for postgres", "type": "project", "license": [ @@ -35,7 +34,8 @@ "slim/twig-view": "~2.5.1", "twig/twig": "~1.42.4", "adodb/adodb-php": "^5.20", - "slim/flash": "^0.4.0" + "slim/flash": "^0.4.0", + "symfony/yaml": "^5.0" }, "require-dev": { "kint-php/kint": "~3.3", @@ -43,15 +43,22 @@ "simpletest/simpletest": "^1.1", "codeception/module-asserts": "^1.1", "filp/whoops": "^2.7", - "symfony/var-dumper": "^5.0" + "symfony/var-dumper": "^5.0", + "vimeo/psalm": "^3.9", + "ergebnis/composer-normalize": "^2.2", + "friendsofphp/php-cs-fixer": "^2.16", + "ergebnis/php-cs-fixer-config": "^2.0" + }, + "extra": { + "version": "6.0.0-RC9", + "current_tags": { + "master": "6.0.0-RC9", + "develop": "6.0.0-RC9" + } }, "scripts": { - "fix_temp_permissions": [ - "php -r \"chmod( __DIR__ . '/temp', 0777);\"", - "php -r \"chmod( __DIR__ . '/temp/twigcache', 0777);\"" - ], "clear_twig_cache": [ - "@fix_temp_permissions", + "make fix_permissions", "php -r \"array_map( 'unlink', array_filter((array) glob('temp/twigcache/**/*.php', GLOB_BRACE)));\"", "php -r \"array_map( 'rmdir', array_filter((array) glob('temp/twigcache/*', GLOB_BRACE)));\"" ], diff --git a/composer.lock b/composer.lock index c0d58f0f..b717fdfe 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "4d0807c867bfdbd9141195705ca1731d", + "content-hash": "ee6f925218a52a37f1df9dd6c580ee95", "packages": [ { "name": "adodb/adodb-php", @@ -486,6 +486,65 @@ "time": "2020-01-13T11:15:53+00:00" }, { + "name": "symfony/yaml", + "version": "v5.0.4", + "source": { + "type": "git", + "url": "https://github.com/symfony/yaml.git", + "reference": "69b44e3b8f90949aee2eb3aa9b86ceeb01cbf62a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/yaml/zipball/69b44e3b8f90949aee2eb3aa9b86ceeb01cbf62a", + "reference": "69b44e3b8f90949aee2eb3aa9b86ceeb01cbf62a", + "shasum": "" + }, + "require": { + "php": "^7.2.5", + "symfony/polyfill-ctype": "~1.8" + }, + "conflict": { + "symfony/console": "<4.4" + }, + "require-dev": { + "symfony/console": "^4.4|^5.0" + }, + "suggest": { + "symfony/console": "For validating YAML files using the lint command" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Yaml\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "https://symfony.com", + "time": "2020-01-21T11:12:28+00:00" + }, + { "name": "twig/twig", "version": "v1.42.4", "source": { @@ -3202,65 +3261,6 @@ "time": "2020-01-25T15:56:29+00:00" }, { - "name": "symfony/yaml", - "version": "v5.0.4", - "source": { - "type": "git", - "url": "https://github.com/symfony/yaml.git", - "reference": "69b44e3b8f90949aee2eb3aa9b86ceeb01cbf62a" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/69b44e3b8f90949aee2eb3aa9b86ceeb01cbf62a", - "reference": "69b44e3b8f90949aee2eb3aa9b86ceeb01cbf62a", - "shasum": "" - }, - "require": { - "php": "^7.2.5", - "symfony/polyfill-ctype": "~1.8" - }, - "conflict": { - "symfony/console": "<4.4" - }, - "require-dev": { - "symfony/console": "^4.4|^5.0" - }, - "suggest": { - "symfony/console": "For validating YAML files using the lint command" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.0-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\Yaml\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony Yaml Component", - "homepage": "https://symfony.com", - "time": "2020-01-21T11:12:28+00:00" - }, - { "name": "theseer/tokenizer", "version": "1.1.3", "source": { diff --git a/config.example.yml b/config.example.yml new file mode 100644 index 00000000..14b53843 --- /dev/null +++ b/config.example.yml @@ -0,0 +1,50 @@ +# uncomment to turn debug mode on/off +debugmode: false +# by default, display tables size. +# displaying schema sizes may hit performance +display_sizes: + - tables: true + schemas: false +servers: + # Define a server + - desc: "Server on remote host" + host: server.host1.com + port: 5432 + sslmode: prefer + defaultdb: template1 + pg_dump_path: /usr/bin/pg_dump + pg_dumpall_path: /usr/bin/pg_dumpall + theme: + default: default + hiddendbs: + - rdsadmin + # Define a second server + - desc: "Server on localhost" + host: localhost + pg_dump_path: /usr/bin/pg_dump + pg_dumpall_path: /usr/bin/pg_dumpall + theme: + default: default + port: 5433 + sslmode: prefer + hiddendbs: + - rdsadmin + - postgres + +default_lang: auto +autocomplete: "default on" +extra_login_security: true +owned_only: true +show_comments: true +show_advanced: false +show_system: false +min_password_length: 1 +left_width: 200 +theme: default +show_oids: false +max_rows: 30 +max_chars: 50 +use_xhtml_strict: false +help_base: "http://www.postgresql.org/docs/%s/interactive/" +ajax_refresh: 3 +version: 60 diff --git a/config.inc.php-dist b/config.inc.php-dist index eecb7ac1..c540238d 100644 --- a/config.inc.php-dist +++ b/config.inc.php-dist @@ -1,12 +1,6 @@ <?php - -/** -* Central phpPgAdmin configuration. As a user you may modify the -* settings here for your particular configuration. -* -* $Id: config.inc.php-dist,v 1.55 2008/02/18 21:10:31 xzilla Exp $ -*/ - +// Allows to load yaml config. Matching keys will override config defined in this file +use Symfony\Component\Yaml\Yaml; @@ -67,41 +61,48 @@ $conf['display_sizes'] = false; // An example server. Create as many of these as you wish, // indexed from zero upwards. +$server_index=0; -// Display name for the server on the login screen -$conf['servers'][0]['desc'] = 'PostgreSQL'; +$conf['servers'][$server_index] = [ + // Display name for the server on the login screen + 'desc' => 'PostgreSQL', -// Hostname or IP address for server. Use '' for UNIX domain socket. -// use 'localhost' for TCP/IP connection on this computer -$conf['servers'][0]['host'] = ''; + // Hostname or IP address for server. Use '' for UNIX domain socket. + // use 'localhost' for TCP/IP connection on this computer + 'host' => '', -// Database port on server (5432 is the PostgreSQL default) -$conf['servers'][0]['port'] = 5432; + // Database port on server (5432 is the PostgreSQL default) + 'port' => 5432, -// Database SSL mode -// Possible options: disable, allow, prefer, require -// To require SSL on older servers use option: legacy -// To ignore the SSL mode, use option: unspecified -$conf['servers'][0]['sslmode'] = 'allow'; + // Database SSL mode + // Possible options: disable, allow, prefer, require + // To require SSL on older servers use option: legacy + // To ignore the SSL mode, use option: unspecified + 'sslmode' => 'allow', -// Change the default database only if you cannot connect to template1. -// For a PostgreSQL 8.1+ server, you can set this to 'postgres'. -$conf['servers'][0]['defaultdb'] = 'template1'; + // Change the default database only if you cannot connect to template1. + // For a PostgreSQL 8.1+ server, you can set this to 'postgres'. + 'defaultdb' => 'template1', -// Specify the path to the database dump utilities for this server. -// You can set these to '' if no dumper is available. -$conf['servers'][0]['pg_dump_path'] = '/usr/bin/pg_dump'; -$conf['servers'][0]['pg_dumpall_path'] = '/usr/bin/pg_dumpall'; + // Specify the path to the database dump utilities for this server. + // You can set these to '' if no dumper is available. + 'pg_dump_path' => '/usr/bin/pg_dump', + 'pg_dumpall_path' => '/usr/bin/pg_dumpall', +]; // Example for a second server (PostgreSQL for Windows) -//$conf['servers'][1]['desc'] = 'Test Server'; -//$conf['servers'][1]['host'] = '127.0.0.1'; -//$conf['servers'][1]['port'] = 5432; -//$conf['servers'][1]['sslmode'] = 'allow'; -//$conf['servers'][1]['defaultdb'] = 'template1'; -//$conf['servers'][1]['pg_dump_path'] = 'C:\\Program Files\\PostgreSQL\\8.0\\bin\\pg_dump.exe'; -//$conf['servers'][1]['pg_dumpall_path'] = 'C:\\Program Files\\PostgreSQL\\8.0\\bin\\pg_dumpall.exe'; - +/* +$server_index++; +$conf['servers'][$server_index][ + 'desc'=> 'Test Server', + 'host'=> '127.0.0.1', + 'port'=> 5432, + 'sslmode'=> 'allow', + 'defaultdb'=> 'template1', + 'pg_dump_path'=> 'C:\\Program Files\\PostgreSQL\\8.0\\bin\\pg_dump.exe', + 'pg_dumpall_path'=> 'C:\\Program Files\\PostgreSQL\\8.0\\bin\\pg_dumpall.exe' +]; +*/ /* Groups definition */ /* Groups allow administrators to logicaly group servers together under @@ -211,18 +212,16 @@ $conf['help_base'] = 'http://www.postgresql.org/docs/%s/interactive/'; // Time in seconds. If set to 0, refreshing data using ajax will be disabled (locks and activity pages) $conf['ajax_refresh'] = 3; -/** Plugins management - * Add plugin names to the following array to activate them - * Example: - * $conf['plugins'] = array( - * 'Example', - * 'Slony' - * ); - */ -$conf['plugins'] = []; - -/***************************************** - * Don't modify anything below this line * - *****************************************/ -$conf['version'] = 60; +// If there's a config.yml in the root folder, parse it and merge its contents with $conf array +// see config.example.yml +$yamlConfigPath = implode(DIRECTORY_SEPARATOR, [__DIR__, 'config.yml']); +if (is_readable($yamlConfigPath) && class_exists('Symfony\Component\Yaml\Yaml')) { + try { + $yamlConfig = Symfony\Component\Yaml\Yaml::parseFile($yamlConfigPath); + $conf = array_merge($conf, $yamlConfig); + } catch (\Exception $e) { + die($e->getMessage()); + error_log($e->getTraceAsString()); + } +} @@ -1,35 +1,39 @@ <?php +declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f */ // This section is made to be able to parse requests coming from PHP Builtin webserver -if (PHP_SAPI === 'cli-server') { +if (\PHP_SAPI === 'cli-server') { $will_redirect = false; - // @todo is PHP_SELF is not set, chances are REQUEST_URI won't either - $req_uri = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['REQUEST_URI']; - if (substr($req_uri, 0, 10) === '/index.php') { + /** @todo is PHP_SELF is not set, chances are REQUEST_URI won't either */ + $req_uri = $_SERVER['PHP_SELF'] ?? $_SERVER['REQUEST_URI']; + + if ('/index.php' === \mb_substr($req_uri, 0, 10)) { $will_redirect = true; - $req_uri = substr($req_uri, 10); + $req_uri = \mb_substr($req_uri, 10); } - $filePath = realpath(ltrim($req_uri, '/')); - $new_location = 'Location: http://'.$_SERVER['HTTP_HOST'].$req_uri; + $filePath = \realpath(\ltrim($req_uri, '/')); + $new_location = 'Location: http://' . $_SERVER['HTTP_HOST'] . $req_uri; if ($filePath && // 1. check that filepath is set - is_readable($filePath) && // 2. and references a readable file/folder - strpos($filePath, BASE_PATH.DIRECTORY_SEPARATOR) === 0 && // 3. And is inside this folder - $filePath != BASE_PATH.DIRECTORY_SEPARATOR.'index.php' && // 4. discard circular references to index.php - substr(basename($filePath), 0, 1) != '.' // 5. don't serve dotfiles + \is_readable($filePath) && // 2. and references a readable file/folder + 0 === \mb_strpos($filePath, BASE_PATH . \DIRECTORY_SEPARATOR) && // 3. And is inside this folder + BASE_PATH . \DIRECTORY_SEPARATOR . 'index.php' !== $filePath && // 4. discard circular references to index.php + '.' !== \mb_substr(\basename($filePath), 0, 1) // 5. don't serve dotfiles ) { - if (strtolower(substr($filePath, -4)) == '.php') { + if ('.php' === \mb_strtolower(\mb_substr($filePath, -4))) { // php file; serve through interpreter include $filePath; return; } + if ($will_redirect) { - header($new_location, true, 301); + \header($new_location, true, 301); return; } @@ -38,4 +42,4 @@ if (PHP_SAPI === 'cli-server') { } } -require_once __DIR__.'/src/router.php'; +require_once __DIR__ . '/src/router.php'; diff --git a/psalm-baseline.xml b/psalm-baseline.xml new file mode 100644 index 00000000..8bea7c5d --- /dev/null +++ b/psalm-baseline.xml @@ -0,0 +1,146 @@ +<?xml version="1.0" encoding="UTF-8"?> +<files psalm-version="3.9.3@2e4154d76e24d1b4e59e6cc2bebef7790cb9e550"> + <file src="src/decorators/ActionUrlDecorator.php"> + <UndefinedConstant occurrences="1"> + <code>\SUBFOLDER</code> + </UndefinedConstant> + <UndefinedThisPropertyAssignment occurrences="4"> + <code>$this->base</code> + <code>$this->queryVars</code> + <code>$this->base</code> + <code>$this->queryVars</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="1"> + <code>$this->base</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/ArrayMergeDecorator.php"> + <UndefinedThisPropertyAssignment occurrences="1"> + <code>$this->m</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="1"> + <code>$this->m</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/BranchUrlDecorator.php"> + <UndefinedConstant occurrences="3"> + <code>\SUBFOLDER</code> + <code>\SUBFOLDER</code> + <code>\SUBFOLDER</code> + </UndefinedConstant> + <UndefinedThisPropertyAssignment occurrences="4"> + <code>$this->base</code> + <code>$this->queryVars</code> + <code>$this->base</code> + <code>$this->queryVars</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="1"> + <code>$this->base</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/CallbackDecorator.php"> + <UndefinedThisPropertyAssignment occurrences="2"> + <code>$this->fn</code> + <code>$this->p</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="2"> + <code>$this->fn</code> + <code>$this->p</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/ConcatDecorator.php"> + <UndefinedThisPropertyAssignment occurrences="1"> + <code>$this->c</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="1"> + <code>$this->c</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/Decorator.php"> + <UndefinedThisPropertyAssignment occurrences="1"> + <code>$this->val</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="1"> + <code>$this->val</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/FieldDecorator.php"> + <UndefinedThisPropertyAssignment occurrences="2"> + <code>$this->f</code> + <code>$this->d</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="2"> + <code>$this->f</code> + <code>$this->d</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/IfEmptyDecorator.php"> + <UndefinedThisPropertyAssignment occurrences="6"> + <code>$this->val</code> + <code>$this->empty</code> + <code>$this->full</code> + <code>$this->val</code> + <code>$this->empty</code> + <code>$this->full</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="2"> + <code>$this->val</code> + <code>$this->empty</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/RedirectUrlDecorator.php"> + <UndefinedConstant occurrences="3"> + <code>\SUBFOLDER</code> + <code>\SUBFOLDER</code> + <code>\SUBFOLDER</code> + </UndefinedConstant> + <UndefinedThisPropertyAssignment occurrences="4"> + <code>$this->base</code> + <code>$this->queryVars</code> + <code>$this->base</code> + <code>$this->queryVars</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="1"> + <code>$this->base</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/ReplaceDecorator.php"> + <UndefinedThisPropertyAssignment occurrences="2"> + <code>$this->s</code> + <code>$this->p</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="2"> + <code>$this->s</code> + <code>$this->p</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/decorators/UrlDecorator.php"> + <UndefinedConstant occurrences="3"> + <code>\SUBFOLDER</code> + <code>\SUBFOLDER</code> + <code>\SUBFOLDER</code> + </UndefinedConstant> + <UndefinedThisPropertyAssignment occurrences="4"> + <code>$this->base</code> + <code>$this->queryVars</code> + <code>$this->base</code> + <code>$this->queryVars</code> + </UndefinedThisPropertyAssignment> + <UndefinedThisPropertyFetch occurrences="1"> + <code>$this->base</code> + </UndefinedThisPropertyFetch> + </file> + <file src="src/traits/HelperTrait.php"> + <UndefinedConstant occurrences="1"> + <code>BASE_PATH</code> + </UndefinedConstant> + <UndefinedDocblockClass occurrences="1"> + <code>$set->recordCount()</code> + </UndefinedDocblockClass> + <UndefinedThisPropertyFetch occurrences="3"> + <code>$this->container</code> + <code>$this->container</code> + <code>$this->container</code> + </UndefinedThisPropertyFetch> + </file> +</files> @@ -5,6 +5,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" + errorBaseline="psalm-baseline-src.xml" > <projectFiles> <directory name="src" /> diff --git a/simple_to_phpunit.php b/simple_to_phpunit.php deleted file mode 100755 index e1ad0253..00000000 --- a/simple_to_phpunit.php +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env php -<?php - -/** - * Convert SimpleTest tests to PHPUnit, mocks to Mockery. - * - * Caveats: - * - Assertion + return value can't be combined automatically - */ - -// filter down to arguments -$args = preg_grep('/^-[dhom]/', array_slice($argv, 1), PREG_GREP_INVERT); - -// show help -if (in_array('-h', $argv, true) || in_array('--help', $argv, true)) { - echo "\nusage: {$argv[0]} [-o] [-d]\n\n"; - echo " -o : output changes only, don't update file\n"; - echo " -d : shows a diff of changes that would be made, implies -o\n\n"; - echo " -m : convert mocks\n\n"; - exit(1); -} - -// handle diff output -if (in_array('-d', $argv, true)) { - passthru('php ' . __FILE__ . " {$argv[1]} -o | diff -u {$argv[1]} -"); - exit(0); -} - -$php = file_get_contents($argv[1]); - -// ---------------------------- -// Convert Mockery - -if (in_array('-m', $argv, true)) { - $patterns = [ - '/->setReturn(?:Value|Reference)\((.+?),\s*(.+?)\);/ims' => '->shouldReceive(\1)->andReturn(\2);', - '/->throwOn\((.+?),(.+?)\);/ims' => '->shouldReceive(\1)->andThrow(\2);', - '/->expectOnce\(([^,\)]+)\);/ims' => '->shouldReceive(\1)->once();', - '/->expectNever\(([^,\)]+)\);/ims' => '->shouldReceive(\1)->never();', - '/->expectOnce\((.+?),\s*array\((.+?)\)\s*\);/ims' => '->shouldReceive(\1)->with(\2)->once();', - '/->expectCallCount\((.+?),\s*(.+?)\)/ims' => '->shouldReceive(\1)->times(\2);', - '/new ([a-z_]*Mock[a-z_]+)\([^\)]*\)/ims' => 'Mockery::mock()', - '/new ([a-z_]*Mock[a-z_]+)\;/ims' => 'Mockery::mock();', - '/Mock::generate[^;]+;\s*/' => '', - '/new AnythingExpectation\(\)/' => '\Mockery::any()', - ]; - - foreach ($patterns as $from => $to) { - $php = preg_replace($from, $to, $php); - } -} - -// ---------------------------- -// Convert SimpleTest classes and assertions - -$patterns = [ - '/assertEquals?/' => 'assertEquals', - '/assertNotEquals?/' => 'assertNotEquals', - '/assertPattern/' => 'assertRegExp', - '/assertIdentical/' => 'assertSame', - '/assertNotIdentical/' => 'assertNotSame', - '/assertNoPattern/' => 'assertNotRegExp', - '/assertReference/' => 'assertSame', - '/assertIsA\((.+?),\s*(.+?)(,\s*.+?)?\)/' => 'assertInstanceOf(\2, \1)', - '/expectException/' => 'setExpectedException', - '/$this->pass()/' => '$this->assertTrue(true)', - '/\bUnitTest(Case)?\b/' => 'PHPUnit_Framework_TestCase', - '/setup/' => 'setUp', -]; - -foreach ($patterns as $from => $to) { - $php = preg_replace($from, $to, $php); -} - -// ---------------------------- -// Output - -if (in_array('-o', $argv, true)) { - echo $php; -} else { - if (file_get_contents($argv[1]) != $php) { - echo "updating {$argv[1]}\n"; - file_put_contents($argv[1], $php); - } -} diff --git a/src/classes/ADONewConnection.php b/src/classes/ADONewConnection.php index 33c38879..0958465b 100644 --- a/src/classes/ADONewConnection.php +++ b/src/classes/ADONewConnection.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin; @@ -9,14 +12,10 @@ namespace PHPPgAdmin; /** * @file * Extends ADONewConnection to let correct inference on PHPDoc params - * - * @package PHPPgAdmin */ /** * Extends ADONewConnection to let correct inference on PHPDoc params. - * - * @package PHPPgAdmin */ class ADONewConnection extends \ADONewConnection { diff --git a/src/classes/ADORecordSet.php b/src/classes/ADORecordSet.php index 4f014289..74fb783d 100644 --- a/src/classes/ADORecordSet.php +++ b/src/classes/ADORecordSet.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin; @@ -9,14 +12,10 @@ namespace PHPPgAdmin; /** * @file * Extends ADORecordSet to let correct inference on PHPDoc params - * - * @package PHPPgAdmin */ /** * Extends ADORecordSet to let correct inference on PHPDoc params. - * - * @package PHPPgAdmin */ class ADORecordSet extends \ADORecordSet implements \Countable { diff --git a/src/classes/ADOdbException.php b/src/classes/ADOdbException.php index 83d49e01..666b05e4 100644 --- a/src/classes/ADOdbException.php +++ b/src/classes/ADOdbException.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin; @@ -19,8 +22,6 @@ namespace PHPPgAdmin; * Latest version is available at http://php.weblogs.com * Exception-handling code using PHP5 exceptions (try-catch-throw). * - * @package PHPPgAdmin - * * @author John Lim * @copyright 2000-2013 John Lim <jlim@natsoft.com> * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community @@ -30,10 +31,15 @@ namespace PHPPgAdmin; class ADOdbException extends \Exception { public $dbms; + public $fn; - public $sql = ''; - public $params = ''; - public $host = ''; + + public $sql = ''; + + public $params = ''; + + public $host = ''; + public $database = ''; /** @@ -53,24 +59,25 @@ class ADOdbException extends \Exception { switch ($fn) { case 'EXECUTE': - $this->sql = is_array($p1) ? $p1[0] : $p1; + $this->sql = \is_array($p1) ? $p1[0] : $p1; $this->params = $p2; - $s = "${dbms} error: [${errno}: ${errmsg}] in ${fn}(\"{$this->sql}\")"; + $s = "{$dbms} error: [{$errno}: {$errmsg}] in {$fn}(\"{$this->sql}\")"; break; case 'PCONNECT': case 'CONNECT': $user = $thisConnection->user; - $s = "${dbms} error: [${errno}: ${errmsg}] in ${fn}(${p1}, '${user}', '****', ${p2})"; + $s = "{$dbms} error: [{$errno}: {$errmsg}] in {$fn}({$p1}, '{$user}', '****', {$p2})"; break; default: - $s = "${dbms} error: [${errno}: ${errmsg}] in ${fn}(${p1}, ${p2})"; + $s = "{$dbms} error: [{$errno}: {$errmsg}] in {$fn}({$p1}, {$p2})"; break; } $this->dbms = $dbms; + if ($thisConnection) { $this->host = $thisConnection->host; $this->database = $thisConnection->database; @@ -78,7 +85,7 @@ class ADOdbException extends \Exception $this->fn = $fn; $this->msg = $errmsg; - if (!is_numeric($errno)) { + if (!\is_numeric($errno)) { $errno = -1; } @@ -100,13 +107,13 @@ class ADOdbException extends \Exception * * @internal param $P2 $fn specific parameter - see below */ - public static function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection) + public static function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection): void { - if (error_reporting() == 0) { + if (0 === \error_reporting()) { return; } - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); + $backtrace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 2); $btarray0 = [ 'msg' => 'ADOdbException at ', @@ -117,13 +124,13 @@ class ADOdbException extends \Exception 'line' => $backtrace[0]['line'], ]; - $errmsg = htmlentities(\PHPPgAdmin\Traits\HelperTrait::br2ln($errmsg), ENT_NOQUOTES); - $p1 = htmlentities(\PHPPgAdmin\Traits\HelperTrait::br2ln($p1), ENT_NOQUOTES); - $p2 = htmlentities(\PHPPgAdmin\Traits\HelperTrait::br2ln($p2), ENT_NOQUOTES); + $errmsg = \htmlentities(\PHPPgAdmin\Traits\HelperTrait::br2ln($errmsg), \ENT_NOQUOTES); + $p1 = \htmlentities(\PHPPgAdmin\Traits\HelperTrait::br2ln($p1), \ENT_NOQUOTES); + $p2 = \htmlentities(\PHPPgAdmin\Traits\HelperTrait::br2ln($p2), \ENT_NOQUOTES); switch ($fn) { case 'EXECUTE': - $sql = str_replace( + $sql = \str_replace( [ 'SELECT', 'WHERE', @@ -138,9 +145,9 @@ class ADOdbException extends \Exception $inputparams = $p2; - $error_msg = '<p><b>strsqlerror</b><br />'.nl2br($errmsg).'</p> <p><b>SQL:</b><br />'.nl2br($sql).'</p> '; + $error_msg = '<p><b>strsqlerror</b><br />' . \nl2br($errmsg) . '</p> <p><b>SQL:</b><br />' . \nl2br($sql) . '</p> '; - echo '<table class="error" cellpadding="5"><tr><td>'.nl2br($error_msg).'</td></tr></table><br />'."\n"; + echo '<table class="error" cellpadding="5"><tr><td>' . \nl2br($error_msg) . '</td></tr></table><br />' . "\n"; break; case 'PCONNECT': @@ -148,16 +155,16 @@ class ADOdbException extends \Exception // do nothing; break; default: - $s = "${dbms} error: [${errno}: ${errmsg}] in ${fn}(${p1}, ${p2})\n"; + $s = "{$dbms} error: [{$errno}: {$errmsg}] in {$fn}({$p1}, {$p2})\n"; echo "<table class=\"error\" cellpadding=\"5\"><tr><td>{$s}</td></tr></table><br />\n"; break; } - $tag = implode('', $btarray0); + $tag = \implode('', $btarray0); //\PC::debug(['errno' => $errno, 'fn' => $fn, 'errmsg' => $errmsg], $tag); - throw new \PHPPgAdmin\ADOdbException($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection); + throw new self($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection); } } diff --git a/src/classes/ArrayRecordSet.php b/src/classes/ArrayRecordSet.php index bb9a7922..8814b478 100644 --- a/src/classes/ArrayRecordSet.php +++ b/src/classes/ArrayRecordSet.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin; @@ -11,8 +14,6 @@ namespace PHPPgAdmin; * Really simple RecordSet to allow printTable of arrays. * * Id: ArrayRecordSet.php,v 1.3 2007/01/10 01:46:28 soranzo Exp $ - * - * @package PHPPgAdmin */ /** @@ -20,16 +21,17 @@ namespace PHPPgAdmin; * Mimics the behavior of an ADORecordset. * * Id: ArrayRecordSet.php,v 1.3 2007/01/10 01:46:28 soranzo Exp $ - * - * @package PHPPgAdmin */ class ArrayRecordSet { - private $_array; - private $_count; public $EOF = false; + public $fields; + private $_array; + + private $_count; + /** * Constructor. * @@ -38,9 +40,10 @@ class ArrayRecordSet public function __construct($data) { $this->_array = $data; - $this->_count = count($this->_array); - $this->fields = reset($this->_array); - if ($this->fields === false) { + $this->_count = \count($this->_array); + $this->fields = \reset($this->_array); + + if (false === $this->fields) { $this->EOF = true; } } @@ -59,10 +62,11 @@ class ArrayRecordSet * Advance the internal pointer of the instance array * if no more fields are left, marks the instance variable $EOF as true. */ - public function moveNext() + public function moveNext(): void { - $this->fields = next($this->_array); - if ($this->fields === false) { + $this->fields = \next($this->_array); + + if (false === $this->fields) { $this->EOF = true; } } diff --git a/src/classes/ContainerUtils.php b/src/classes/ContainerUtils.php index 98473677..fe568b03 100644 --- a/src/classes/ContainerUtils.php +++ b/src/classes/ContainerUtils.php @@ -1,11 +1,24 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin; +use Psr\Container\ContainerInterface; +use Slim\App; + +\defined('BASE_PATH') || \define(BASE_PATH, \dirname(__DIR__, 2)); +\defined('SUBFOLDER') || \define( + 'SUBFOLDER', + \str_replace($_SERVER['DOCUMENT_ROOT'] ?? '', '', BASE_PATH) +); +\defined('DEBUGMODE') || \define('DEBUGMODE', false); +defined('IN_TEST') || define('IN_TEST', false); /** * @file * A class that adds convenience methods to the container @@ -13,31 +26,74 @@ namespace PHPPgAdmin; /** * A class that adds convenience methods to the container. - * - * @package PHPPgAdmin */ class ContainerUtils { use \PHPPgAdmin\Traits\HelperTrait; + /** + * @var string + */ + const BASE_PATH = BASE_PATH; + /** + * @var string + */ + const SUBFOLDER = SUBFOLDER; + /** + * @var string + */ + const DEBUGMODE = DEBUGMODE; + + /** + * @var ContainerInterface + */ + protected $_container; + + /** + * @var App + */ + protected $_app; - protected $container; - /** @var Connector */ - protected static $instance; + /** + * @var self + */ + protected static $_instance; /** * Constructor of the ContainerUtils class. - * - * @param \Slim\Container $container The app container */ public function __construct() { - $composerinfo = json_decode(file_get_contents(BASE_PATH.'/composer.json')); - $appVersion = $composerinfo->version; + $composerinfo = \json_decode(\file_get_contents(BASE_PATH . '/composer.json')); + $appVersion = $composerinfo->extra->version; - $phpMinVer = (str_replace(['<', '>', '='], '', $composerinfo->require->php)); + $phpMinVer = (\str_replace(['<', '>', '='], '', $composerinfo->require->php)); //$this->prtrace($appVersion); //$this->dump($composerinfo); + $settings = [ + 'displayErrorDetails' => self::DEBUGMODE, + 'determineRouteBeforeAppMiddleware' => true, + 'base_path' => self::BASE_PATH, + 'debug' => self::DEBUGMODE, + + // Configuration file version. If this is greater than that in config.inc.php, then + // the app will refuse to run. This and $conf['version'] should be incremented whenever + // backwards incompatible changes are made to config.inc.php-dist. + 'base_version' => 60, + // Application version + 'appVersion' => 'v' . $appVersion, + // Application name + 'appName' => 'phpPgAdmin6', + + // PostgreSQL and PHP minimum version + 'postgresqlMinVer' => '9.3', + 'phpMinVer' => $phpMinVer, + 'displayErrorDetails' => self::DEBUGMODE, + 'addContentLengthHeader' => false, + ]; + if (!self::DEBUGMODE && !IN_TEST) { + $settings['routerCacheFile'] = self::BASE_PATH . '/temp/route.cache.php'; + } $config = [ 'msg' => '', 'appThemes' => [ @@ -46,72 +102,71 @@ class ContainerUtils 'gotar' => 'Blue/Green', 'bootstrap' => 'Bootstrap3', ], - 'settings' => [ - 'displayErrorDetails' => DEBUGMODE, - 'determineRouteBeforeAppMiddleware' => true, - 'base_path' => BASE_PATH, - 'debug' => DEBUGMODE, - - // 'routerCacheFile' => BASE_PATH . '/temp/route.cache.php', - - // Configuration file version. If this is greater than that in config.inc.php, then - // the app will refuse to run. This and $conf['version'] should be incremented whenever - // backwards incompatible changes are made to config.inc.php-dist. - 'base_version' => 60, - // Application version - 'appVersion' => 'v'.$appVersion, - // Application name - 'appName' => 'phpPgAdmin6', - - // PostgreSQL and PHP minimum version - 'postgresqlMinVer' => '9.3', - 'phpMinVer' => $phpMinVer, - 'displayErrorDetails' => DEBUGMODE, - 'addContentLengthHeader' => false, - ], + 'settings' => $settings, ]; - $this->app = new \Slim\App($config); + $this->_app = new App($config); // Fetch DI Container - $container = $this->app->getContainer(); + $container = $this->_app->getContainer(); $container['utils'] = $this; - $container['version'] = 'v'.$appVersion; + $container['version'] = 'v' . $appVersion; $container['errors'] = []; - $this->container = $container; + $this->_container = $container; } - public static function createContainer($conf) + public static function getContainerInstance() + { + $_instance = self::getInstance(); + + if (!$container = $_instance->_container) { + throw new \Exception('Could not get a container'); + } + + return $container; + } + + public static function getInstance() { - if (!self::$instance) { - self::$instance = new self(); + if (!self::$_instance) { + self::$_instance = new self(); } + return self::$_instance; + } + + public static function createContainer($conf) + { + $container = self::getContainerInstance(); // Complete missing conf keys - self::$instance->container['conf'] = function ($c) use ($conf) { + $container['conf'] = static function ($c) use ($conf) { $display_sizes = $conf['display_sizes'] ?? false; $conf['display_sizes'] = [ 'schemas' => (bool) $display_sizes, 'tables' => (bool) $display_sizes, ]; - if (is_array($display_sizes)) { + + if (\is_array($display_sizes)) { $conf['display_sizes'] = [ - 'schemas' => $display_sizes['schemas'] ?? in_array('schemas', $display_sizes, true), - 'tables' => $display_sizes['tables'] ?? in_array('tables', $display_sizes, true), + 'schemas' => $display_sizes['schemas'] ?? \in_array('schemas', $display_sizes, true), + 'tables' => $display_sizes['tables'] ?? \in_array('tables', $display_sizes, true), ]; } // Plugins are removed $conf['plugins'] = []; + if (!isset($conf['theme'])) { $conf['theme'] = 'default'; } + foreach ($conf['servers'] as &$server) { if (!isset($server['port'])) { $server['port'] = 5432; } + if (!isset($server['sslmode'])) { $server['sslmode'] = 'unspecified'; } @@ -119,24 +174,42 @@ class ContainerUtils return $conf; }; + $requestUri = $container->request->getUri() ?? null; + + if ($requestBasePath = $requestUri->getBasePath() ?? null) { + $subfolder = $requestBasePath; + } elseif (\PHP_SAPI === 'cli-server') { + $subfolder = '/index.php'; + } elseif (isset($conf['subfolder']) && \is_string($conf['subfolder'])) { + $subfolder = $conf['subfolder']; + } else { + $subfolder = \str_replace( + $container->environment->get('DOCUMENT_ROOT'), + '', + \dirname(__DIR__, 2) + ); + } - return [self::$instance->container, self::$instance->app]; + $container->subfolder = $subfolder ?? self::SUBFOLDER; + //ddd($container->subfolder); + return [$container, self::$_instance->_app]; } public function maybeRenderIframes($response, $subject, $query_string) { - $c = $this->container; + $c = self::getContainerInstance(); + $in_test = $c->view->offsetGet('in_test'); - if ($in_test === '1') { - $className = '\PHPPgAdmin\Controller\\'.ucfirst($subject).'Controller'; + if ('1' === $in_test) { + $className = '\PHPPgAdmin\Controller\\' . \ucfirst($subject) . 'Controller'; $controller = new $className($c); return $controller->render(); } $viewVars = [ - 'url' => '/src/views/'.$subject.($query_string ? '?'.$query_string : ''), + 'url' => '/src/views/' . $subject . ($query_string ? '?' . $query_string : ''), 'headertemplate' => 'header.twig', ]; @@ -164,27 +237,27 @@ class ContainerUtils $themefolders = $this->getThemeFolders(); // Check if theme is in $_REQUEST, $_SESSION or $_COOKIE // 1.- First priority: $_REQUEST, this happens when you use the selector - if (array_key_exists('theme', $_REQUEST) && - array_key_exists($_REQUEST['theme'], $themefolders)) { + if (\array_key_exists('theme', $_REQUEST) && + \array_key_exists($_REQUEST['theme'], $themefolders)) { $_theme = $_REQUEST['theme']; } elseif ( // otherwise, see if there's a theme associated with this particular server - !is_null($_server_info) && - array_key_exists('theme', $_server_info) && - is_string($_server_info['theme']) && - array_key_exists($_COOKIE['ppaTheme'], $themefolders)) { + null !== $_server_info && + \array_key_exists('theme', $_server_info) && + \is_string($_server_info['theme']) && + \array_key_exists($_COOKIE['ppaTheme'], $themefolders)) { $_theme = $_server_info['theme']; - } elseif (array_key_exists('ppaTheme', $_SESSION) && - array_key_exists($_SESSION['ppaTheme'], $themefolders)) { + } elseif (\array_key_exists('ppaTheme', $_SESSION) && + \array_key_exists($_SESSION['ppaTheme'], $themefolders)) { // otherwise check $_SESSION $_theme = $_SESSION['ppaTheme']; - } elseif (array_key_exists('ppaTheme', $_SESSION) && - array_key_exists($_COOKIE['ppaTheme'], $themefolders)) { + } elseif (\array_key_exists('ppaTheme', $_SESSION) && + \array_key_exists($_COOKIE['ppaTheme'], $themefolders)) { // oterwise check $_COOKIE $_theme = $_COOKIE['ppaTheme']; } elseif ( // see if there's a valid theme set in config file - array_key_exists('theme', $conf) && - is_string($conf['theme']) && - array_key_exists($conf['theme'], $themefolders)) { + \array_key_exists('theme', $conf) && + \is_string($conf['theme']) && + \array_key_exists($conf['theme'], $themefolders)) { $_theme = $conf['theme']; } else { // okay then, use default theme @@ -195,56 +268,20 @@ class ContainerUtils } /** - * Traverse THEME_PATH, consider as theme folders those which - * contain a `global.css` stylesheet. - * - * @return array the theme folders - */ - private function getThemeFolders() - { - // no THEME_PATH (how?) then return empty array - if (!$gestor = opendir(THEME_PATH)) { - closedir($gestor); - - return []; - } - $themefolders = []; - - /* This is the right way to iterate on a folder */ - while (false !== ($foldername = readdir($gestor))) { - if ($foldername == '.' || $foldername == '..') { - continue; - } - - $folderpath = sprintf('%s%s%s', THEME_PATH, DIRECTORY_SEPARATOR, $foldername); - $stylesheet = sprintf('%s%s%s', $folderpath, DIRECTORY_SEPARATOR, 'global.css'); - // if $folderpath if indeed a folder and contains a global.css file, then it's a theme - if (is_dir($folderpath) && - is_file($stylesheet)) { - $themefolders[$foldername] = $folderpath; - } - } - - closedir($gestor); - - return $themefolders; - } - - /** * Determines the redirection url according to query string. * * @return string the redirect url */ public function getRedirectUrl() { - $query_string = $this->container->requestobj->getUri()->getQuery(); + $query_string = $this->_container->requestobj->getUri()->getQuery(); // if server_id isn't set, then you will be redirected to intro - if ($this->container->requestobj->getQueryParam('server') === null) { - $destinationurl = \SUBFOLDER.'/src/views/intro'; + if (null === $this->_container->requestobj->getQueryParam('server')) { + $destinationurl = \SUBFOLDER . '/src/views/intro'; } else { // otherwise, you'll be redirected to the login page for that server; - $destinationurl = \SUBFOLDER.'/src/views/login'.($query_string ? '?'.$query_string : ''); + $destinationurl = \SUBFOLDER . '/src/views/login' . ($query_string ? '?' . $query_string : ''); } return $destinationurl; @@ -260,30 +297,31 @@ class ContainerUtils */ public function getDestinationWithLastTab($subject) { - $_server_info = $this->container->misc->getServerInfo(); + $_server_info = $this->_container->misc->getServerInfo(); $this->addFlash($subject, 'getDestinationWithLastTab'); //$this->prtrace('$_server_info', $_server_info); // If username isn't set in server_info, you should login if (!isset($_server_info['username'])) { $destinationurl = $this->getRedirectUrl(); } else { - $url = $this->container->misc->getLastTabURL($subject); - $this->addFlash($url, 'getLastTabURL for '.$subject); + $url = $this->_container->misc->getLastTabURL($subject); + $this->addFlash($url, 'getLastTabURL for ' . $subject); // Load query vars into superglobal arrays if (isset($url['urlvars'])) { $urlvars = []; + foreach ($url['urlvars'] as $key => $urlvar) { //$this->prtrace($key, $urlvar); $urlvars[$key] = \PHPPgAdmin\Decorators\Decorator::get_sanitized_value($urlvar, $_REQUEST); } - $_REQUEST = array_merge($_REQUEST, $urlvars); - $_GET = array_merge($_GET, $urlvars); + $_REQUEST = \array_merge($_REQUEST, $urlvars); + $_GET = \array_merge($_GET, $urlvars); } $actionurl = \PHPPgAdmin\Decorators\Decorator::actionurl($url['url'], $_GET); $destinationurl = $actionurl->value($_GET); } - $destinationurl = str_replace('views/?', "views/{$subject}?", $destinationurl); + $destinationurl = \str_replace('views/?', "views/{$subject}?", $destinationurl); // $this->prtrace('destinationurl for ' . $subject, $destinationurl); return $destinationurl; } @@ -297,10 +335,46 @@ class ContainerUtils */ public function addError($errormsg) { - $errors = $this->container->get('errors'); + $errors = $this->_container->get('errors'); $errors[] = $errormsg; - $this->container->offsetSet('errors', $errors); + $this->_container->offsetSet('errors', $errors); + + return $this->_container; + } - return $this->container; + /** + * Traverse THEME_PATH, consider as theme folders those which + * contain a `global.css` stylesheet. + * + * @return array the theme folders + */ + private function getThemeFolders() + { + // no THEME_PATH (how?) then return empty array + if (!$gestor = \opendir(THEME_PATH)) { + \closedir($gestor); + + return []; + } + $themefolders = []; + + /* This is the right way to iterate on a folder */ + while (false !== ($foldername = \readdir($gestor))) { + if ('.' === $foldername || '..' === $foldername) { + continue; + } + + $folderpath = \sprintf('%s%s%s', THEME_PATH, \DIRECTORY_SEPARATOR, $foldername); + $stylesheet = \sprintf('%s%s%s', $folderpath, \DIRECTORY_SEPARATOR, 'global.css'); + // if $folderpath if indeed a folder and contains a global.css file, then it's a theme + if (\is_dir($folderpath) && + \is_file($stylesheet)) { + $themefolders[$foldername] = $folderpath; + } + } + + \closedir($gestor); + + return $themefolders; } } diff --git a/src/classes/Misc.php b/src/classes/Misc.php index 3690bf8c..960bc175 100644 --- a/src/classes/Misc.php +++ b/src/classes/Misc.php @@ -1,50 +1,82 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin; +\defined('BASE_PATH') || \define(BASE_PATH, \dirname(__DIR__, 2)); +\defined('SUBFOLDER') || \define( + 'SUBFOLDER', + \str_replace($_SERVER['DOCUMENT_ROOT'] ?? '', '', BASE_PATH) +); +\defined('DEBUGMODE') || \define('DEBUGMODE', false); + /** * @file * Class to hold various commonly used functions * * Id: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $ - * - * @package PHPPgAdmin */ /** * Class to hold various commonly used functions. * * Release: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $ - * - * @package PHPPgAdmin */ class Misc { use \PHPPgAdmin\Traits\HelperTrait; use \PHPPgAdmin\Traits\MiscTrait; + /** + * @var string + */ + const BASE_PATH = BASE_PATH; + /** + * @var string + */ + const SUBFOLDER = SUBFOLDER; + /** + * @var string + */ + const DEBUGMODE = DEBUGMODE; + + public $appLangFiles = []; + + public $appName = ''; + + public $appVersion = ''; + + public $form = ''; + + public $href = ''; + + public $controller_name = 'Misc'; + + public $lang = []; + + protected $container; + private $_connection; + private $_no_db_connection = false; - private $_reload_browser = false; + + private $_reload_browser = false; + private $_data; + private $_database; + private $_server_id; - private $_server_info; - private $_error_msg = ''; - public $appLangFiles = []; - public $appName = ''; - public $appVersion = ''; - public $form = ''; - public $href = ''; - public $controller_name = 'Misc'; - public $lang = []; + private $_server_info; - protected $container; + private $_error_msg = ''; /** * @param \Slim\Container $container The container @@ -75,13 +107,13 @@ class Misc } // Check database support is properly compiled in - if (!function_exists('pg_connect')) { + if (!\function_exists('pg_connect')) { $container->get('utils')->addError($this->lang['strnotloaded']); } // Check the version of PHP - if (version_compare(PHP_VERSION, $this->phpMinVer, '<')) { - $container->get('utils')->addError(sprintf('Version of PHP not supported. Please upgrade to version %s or later.', $this->phpMinVer)); + if (\version_compare(\PHP_VERSION, $this->phpMinVer, '<')) { + $container->get('utils')->addError(\sprintf('Version of PHP not supported. Please upgrade to version %s or later.', $this->phpMinVer)); } //$this->dumpAndDie($this); @@ -91,12 +123,14 @@ class Misc public function serverToSha() { $request_server = $this->container->requestobj->getParam('server'); - if ($request_server === null) { + + if (null === $request_server) { return null; } - $srv_array = explode(':', $request_server); - if (count($srv_array) === 3) { - return sha1($request_server); + $srv_array = \explode(':', $request_server); + + if (3 === \count($srv_array)) { + return \sha1($request_server); } return $request_server; @@ -110,14 +144,14 @@ class Misc $request_server = $this->serverToSha(); - if (count($this->conf['servers']) === 1) { + if (1 === \count($this->conf['servers'])) { $info = $this->conf['servers'][0]; - $this->_server_id = sha1($info['host'].':'.$info['port'].':'.$info['sslmode']); - } elseif ($request_server !== null) { + $this->_server_id = \sha1($info['host'] . ':' . $info['port'] . ':' . $info['sslmode']); + } elseif (null !== $request_server) { $this->_server_id = $request_server; - } elseif (isset($_SESSION['webdbLogin']) && count($_SESSION['webdbLogin']) > 0) { + } elseif (isset($_SESSION['webdbLogin']) && 0 < \count($_SESSION['webdbLogin'])) { //$this->prtrace('webdbLogin', $_SESSION['webdbLogin']); - $this->_server_id = array_keys($_SESSION['webdbLogin'])[0]; + $this->_server_id = \array_keys($_SESSION['webdbLogin'])[0]; } return $this->_server_id; @@ -161,10 +195,11 @@ class Misc */ public function getConf($key = null) { - if ($key === null) { + if (null === $key) { return $this->conf; } - if (array_key_exists($key, $this->conf)) { + + if (\array_key_exists($key, $this->conf)) { return $this->conf[$key]; } @@ -180,11 +215,12 @@ class Misc */ public function printHelp($str, $help = null, $do_print = true) { - if ($help !== null) { + if (null !== $help) { $helplink = $this->getHelpLink($help); - $str .= '<a class="help" href="'.$helplink.'" title="'.$this->lang['strhelp'].'" target="phppgadminhelp">'; - $str .= $this->lang['strhelpicon'].'</a>'; + $str .= '<a class="help" href="' . $helplink . '" title="' . $this->lang['strhelp'] . '" target="phppgadminhelp">'; + $str .= $this->lang['strhelpicon'] . '</a>'; } + if ($do_print) { echo $str; } else { @@ -201,7 +237,7 @@ class Misc */ public function getHelpLink($help) { - return htmlspecialchars(SUBFOLDER.'/help?help='.urlencode($help).'&server='.urlencode($this->getServerId())); + return \htmlspecialchars($this->getSubfolder('help?help=') . \urlencode($help) . '&server=' . \urlencode($this->getServerId())); } /** @@ -290,7 +326,7 @@ class Misc { $lang = $this->lang; - if ($server_id !== null) { + if (null !== $server_id) { $this->_server_id = $server_id; } //$this->prtrace($this->_server_id); @@ -301,7 +337,7 @@ class Misc return null; } - if ($this->_data === null) { + if (null === $this->_data) { try { $_connection = $this->getConnection($database, $this->_server_id); } catch (\Exception $e) { @@ -325,14 +361,14 @@ class Misc //$this->prtrace(['type' => $_type, 'platform' => $platform, 'pgVersion' => $_connection->conn->pgVersion]); - if ($_type === null) { - $errormsg = sprintf($lang['strpostgresqlversionnotsupported'], $this->postgresqlMinVer); + if (null === $_type) { + $errormsg = \sprintf($lang['strpostgresqlversionnotsupported'], $this->postgresqlMinVer); $this->container->utils->addError($errormsg); $this->setErrorMsg($errormsg); return null; } - $_type = '\PHPPgAdmin\Database\\'.$_type; + $_type = '\PHPPgAdmin\Database\\' . $_type; //$this->prtrace('driver:', $_type); @@ -357,13 +393,13 @@ class Misc } } - if ($this->_no_db_connection === false && - $this->getDatabase() !== null && + if (false === $this->_no_db_connection && + null !== $this->getDatabase() && isset($_REQUEST['schema']) ) { $status = $this->_data->setSchema($_REQUEST['schema']); - if ($status != 0) { + if (0 !== $status) { $this->container->utils->addError($this->lang['strbadschema']); $this->setErrorMsg($this->lang['strbadschema']); @@ -378,8 +414,8 @@ class Misc { $lang = $this->lang; - if ($this->_connection === null) { - if ($server_id !== null) { + if (null === $this->_connection) { + if (null !== $server_id) { $this->_server_id = $server_id; } $server_info = $this->getServerInfo($this->_server_id); @@ -397,7 +433,7 @@ class Misc ]; if (isset($server_info['username']) && - array_key_exists(strtolower($server_info['username']), $bad_usernames) + \array_key_exists(\mb_strtolower($server_info['username']), $bad_usernames) ) { $msg = $lang['strlogindisallowed']; @@ -405,7 +441,7 @@ class Misc } if (!isset($server_info['password']) || - $server_info['password'] == '' + '' === $server_info['password'] ) { $msg = $lang['strlogindisallowed']; @@ -439,9 +475,9 @@ class Misc */ public function getServerInfo($server_id = null) { - if ($server_id !== null) { + if (null !== $server_id) { $this->_server_id = $server_id; - } elseif ($this->_server_info !== null) { + } elseif (null !== $this->_server_info) { return $this->_server_info; } @@ -454,8 +490,8 @@ class Misc // Otherwise, look for it in the conf file foreach ($this->conf['servers'] as $idx => $info) { - $server_string = $info['host'].':'.$info['port'].':'.$info['sslmode']; - $server_sha = sha1($server_string); + $server_string = $info['host'] . ':' . $info['port'] . ':' . $info['sslmode']; + $server_sha = \sha1($server_string); if ($this->_server_id === $server_string || $this->_server_id === $server_sha @@ -474,7 +510,7 @@ class Misc } } - if ($server_id === null) { + if (null === $server_id) { $this->_server_info = null; return $this->_server_info; @@ -494,20 +530,20 @@ class Misc * @param mixed $value the new value, or null to unset the parameter * @param null|string $server_id the server identifier, or null for current server */ - public function setServerInfo($key, $value, $server_id = null) + public function setServerInfo($key, $value, $server_id = null): void { - if ($server_id === null) { + if (null === $server_id) { $server_id = $this->container->requestobj->getParam('server'); } - if ($key === null) { - if ($value === null) { + if (null === $key) { + if (null === $value) { unset($_SESSION['webdbLogin'][$server_id]); } else { $_SESSION['webdbLogin'][$server_id] = $value; } } else { - if ($value === null) { + if (null === $value) { unset($_SESSION['webdbLogin'][$server_id][$key]); } else { $_SESSION['webdbLogin'][$server_id][$key] = $value; @@ -517,19 +553,19 @@ class Misc public function getDatabase($database = '') { - if ($this->_server_id === null && !isset($_REQUEST['database'])) { + if (null === $this->_server_id && !isset($_REQUEST['database'])) { return null; } $server_info = $this->getServerInfo($this->_server_id); - if ($this->_server_id !== null && + if (null !== $this->_server_id && isset($server_info['useonlydefaultdb']) && - $server_info['useonlydefaultdb'] === true && + true === $server_info['useonlydefaultdb'] && isset($server_info['defaultdb']) ) { $this->_database = $server_info['defaultdb']; - } elseif ($database !== '') { + } elseif ('' !== $database) { $this->_database = $database; } elseif (isset($_REQUEST['database'])) { // Connect to the current database @@ -556,7 +592,8 @@ class Misc $data = $this->getDatabaseAccessor(); $status = $data->setSchema($schema); - if ($status != 0) { + + if (0 !== $status) { return $status; } @@ -608,17 +645,19 @@ class Misc $database = $this->container->database || isset($_REQUEST['database']) ? $_REQUEST['database'] : null; $schema = $this->container->schema || isset($_REQUEST['schema']) ? $_REQUEST['schema'] : null; - if ($server && $exclude_from !== 'server') { - $href[] = 'server='.urlencode($server); + if ($server && 'server' !== $exclude_from) { + $href[] = 'server=' . \urlencode($server); } - if ($database && $exclude_from !== 'database') { - $href[] = 'database='.urlencode($database); + + if ($database && 'database' !== $exclude_from) { + $href[] = 'database=' . \urlencode($database); } - if ($schema && $exclude_from !== 'schema') { - $href[] = 'schema='.urlencode($schema); + + if ($schema && 'schema' !== $exclude_from) { + $href[] = 'schema=' . \urlencode($schema); } - $this->href = htmlentities(implode('&', $href)); + $this->href = \htmlentities(\implode('&', $href)); return $this->href; } @@ -629,17 +668,19 @@ class Misc public function setForm() { $form = []; + if ($this->container->server) { - $form[] = '<input type="hidden" name="server" value="'.htmlspecialchars($this->container->server).'" />'; + $form[] = '<input type="hidden" name="server" value="' . \htmlspecialchars($this->container->server) . '" />'; } + if ($this->container->database) { - $form[] = '<input type="hidden" name="database" value="'.htmlspecialchars($this->container->database).'" />'; + $form[] = '<input type="hidden" name="database" value="' . \htmlspecialchars($this->container->database) . '" />'; } if ($this->container->schema) { - $form[] = '<input type="hidden" name="schema" value="'.htmlspecialchars($this->container->schema).'" />'; + $form[] = '<input type="hidden" name="schema" value="' . \htmlspecialchars($this->container->schema) . '" />'; } - $this->form = implode("\n", $form); + $this->form = \implode("\n", $form); return $this->form; } @@ -650,15 +691,16 @@ class Misc * * @param mixed $var The variable to strip (passed by reference) */ - public function stripVar(&$var) + public function stripVar(&$var): void { - if (is_array($var)) { + if (\is_array($var)) { foreach ($var as $k => $v) { $this->stripVar($var[$k]); /* magic_quotes_gpc escape keys as well ...*/ - if (is_string($k)) { - $ek = stripslashes($k); + if (\is_string($k)) { + $ek = \stripslashes($k); + if ($ek !== $k) { $var[$ek] = $var[$k]; unset($var[$k]); @@ -666,7 +708,7 @@ class Misc } } } else { - $var = stripslashes($var); + $var = \stripslashes($var); } } @@ -685,16 +727,16 @@ class Misc // that the parameter represents. Or false if $strIniSize is unparseable. $a_IniParts = []; - if (!is_string($strIniSize)) { + if (!\is_string($strIniSize)) { return false; } - if (!preg_match('/^(\d+)([bkm]*)$/i', $strIniSize, $a_IniParts)) { + if (!\preg_match('/^(\d+)([bkm]*)$/i', $strIniSize, $a_IniParts)) { return false; } $nSize = (float) $a_IniParts[1]; - $strUnit = strtolower($a_IniParts[2]); + $strUnit = \mb_strtolower($a_IniParts[2]); switch ($strUnit) { case 'm': @@ -710,15 +752,18 @@ class Misc public function getRequestVars($subject = '') { $v = []; + if (!empty($subject)) { $v['subject'] = $subject; } - if ($this->_server_id !== null && $subject != 'root') { + if (null !== $this->_server_id && 'root' !== $subject) { $v['server'] = $this->_server_id; - if ($this->_database !== null && $subject != 'server') { + + if (null !== $this->_database && 'server' !== $subject) { $v['database'] = $this->_database; - if (isset($_REQUEST['schema']) && $subject != 'database') { + + if (isset($_REQUEST['schema']) && 'database' !== $subject) { $v['schema'] = $_REQUEST['schema']; } } @@ -729,34 +774,36 @@ class Misc public function icon($icon) { - if (!is_string($icon)) { + if (!\is_string($icon)) { return ''; } + $theme = $this->conf['theme']; $path = 'assets/images/themes'; - $default_icon = sprintf('%s/%s/default/DisconnectedServer.png', SUBFOLDER, $path); - if (is_readable(sprintf('%s/%s/%s/%s.png', \BASE_PATH, $path, $theme, $icon))) { - return sprintf('%s/%s/%s/%s.png', \SUBFOLDER, $path, $theme, $icon); + $default_icon = \sprintf('%s/%s/default/DisconnectedServer.png', self::SUBFOLDER, $path); + + if (\is_readable(\sprintf('%s/%s/%s/%s.png', self::BASE_PATH, $path, $theme, $icon))) { + return \sprintf('%s/%s/%s/%s.png', self::SUBFOLDER, $path, $theme, $icon); } - if (is_readable(sprintf('%s/%s/%s/%s.gif', \BASE_PATH, $path, $theme, $icon))) { - return sprintf('%s/%s/%s/%s.gif', \SUBFOLDER, $path, $theme, $icon); + if (\is_readable(\sprintf('%s/%s/%s/%s.gif', self::BASE_PATH, $path, $theme, $icon))) { + return \sprintf('%s/%s/%s/%s.gif', self::SUBFOLDER, $path, $theme, $icon); } - if (is_readable(sprintf('%s/%s/%s/%s.ico', \BASE_PATH, $path, $theme, $icon))) { - return sprintf('%s/%s/%s/%s.ico', \SUBFOLDER, $path, $theme, $icon); + if (\is_readable(\sprintf('%s/%s/%s/%s.ico', self::BASE_PATH, $path, $theme, $icon))) { + return \sprintf('%s/%s/%s/%s.ico', self::SUBFOLDER, $path, $theme, $icon); } - if (is_readable(sprintf('%s/%s/default/%s.png', \BASE_PATH, $path, $icon))) { - return sprintf('%s/%s/default/%s.png', \SUBFOLDER, $path, $icon); + if (\is_readable(\sprintf('%s/%s/default/%s.png', self::BASE_PATH, $path, $icon))) { + return \sprintf('%s/%s/default/%s.png', self::SUBFOLDER, $path, $icon); } - if (is_readable(sprintf('%s/%s/default/%s.gif', \BASE_PATH, $path, $icon))) { - return sprintf('%s/%s/default/%s.gif', \SUBFOLDER, $path, $icon); + if (\is_readable(\sprintf('%s/%s/default/%s.gif', self::BASE_PATH, $path, $icon))) { + return \sprintf('%s/%s/default/%s.gif', self::SUBFOLDER, $path, $icon); } - if (is_readable(sprintf('%s/%s/default/%s.ico', \BASE_PATH, $path, $icon))) { - return sprintf('%s/%s/default/%s.ico', \SUBFOLDER, $path, $icon); + if (\is_readable(\sprintf('%s/%s/default/%s.ico', self::BASE_PATH, $path, $icon))) { + return \sprintf('%s/%s/default/%s.ico', self::SUBFOLDER, $path, $icon); } return $default_icon; @@ -774,18 +821,18 @@ class Misc //$data = $this->getDatabaseAccessor(); $lang = $this->lang; - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + if ('WIN' === \mb_strtoupper(\mb_substr(\PHP_OS, 0, 3))) { // Due to annoying PHP bugs, shell arguments cannot be escaped // (command simply fails), so we cannot allow complex objects // to be dumped. - if (preg_match('/^[_.[:alnum:]]+$/', $str)) { + if (\preg_match('/^[_.[:alnum:]]+$/', $str)) { return $str; } return $this->halt($lang['strcannotdumponwindows']); } - return escapeshellarg($str); + return \escapeshellarg($str); } /** @@ -799,13 +846,13 @@ class Misc { $data = $this->getDatabaseAccessor(); - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + if ('WIN' === \mb_strtoupper(\mb_substr(\PHP_OS, 0, 3))) { $data->fieldClean($str); - return '"'.$str.'"'; + return '"' . $str . '"'; } - return escapeshellcmd($str); + return \escapeshellcmd($str); } /** @@ -814,15 +861,15 @@ class Misc * * @param string $script the SQL script to save */ - public function saveScriptHistory($script) + public function saveScriptHistory($script): void { - list($usec, $sec) = explode(' ', microtime()); + list($usec, $sec) = \explode(' ', \microtime()); $time = ((float) $usec + (float) $sec); $server = $this->container->server ? $this->container->server : $_REQUEST['server']; $database = $this->container->database ? $this->container->database : $_REQUEST['database']; - $_SESSION['history'][$server][$database]["${time}"] = [ + $_SESSION['history'][$server][$database]["{$time}"] = [ 'query' => $script, 'paginate' => !isset($_REQUEST['paginate']) ? 'f' : 't', 'queryid' => $time, diff --git a/src/classes/Translations.php b/src/classes/Translations.php index 620b5db5..7982d187 100644 --- a/src/classes/Translations.php +++ b/src/classes/Translations.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin; @@ -83,8 +86,6 @@ class Translations 'ukrainian' => 'Ukrainian', ]; - private $_language; - /** * ISO639 language code to language file mapping. * See http://www.w3.org/WAI/ER/IG/ert/iso639.htm for language codes @@ -162,6 +163,8 @@ class Translations 'ukrainian' => 'uk', ]; + private $_language; + public function __construct($container) { $appLangFiles = $this->appLangFiles; @@ -178,7 +181,7 @@ class Translations // 1. Check for the language from a request var if (isset($_REQUEST['language'], $appLangFiles[$_REQUEST['language']])) { /* save the selected language in cookie for a year */ - setcookie('webdbLanguage', $_REQUEST['language'], time() + 31536000); + \setcookie('webdbLanguage', $_REQUEST['language'], \time() + 31536000); $_language = $_REQUEST['language']; } elseif (!isset($_language) && isset($_SESSION['webdbLanguage'], $appLangFiles[$_SESSION['webdbLanguage']])) { // 2. Check for language in $_SESSION superglobal @@ -186,12 +189,12 @@ class Translations } elseif (!isset($_language) && isset($_COOKIE['webdbLanguage'], $appLangFiles[$_COOKIE['webdbLanguage']])) { // 3. Check for language in $_COOKIE superglobal $_language = $_COOKIE['webdbLanguage']; - } elseif (!isset($_language) && $conf['default_lang'] == 'auto' && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { + } elseif (!isset($_language) && 'auto' === $conf['default_lang'] && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // 4. Check for acceptable languages in$_SERVER['HTTP_ACCEPT_LANGUAGE'] // extract acceptable language tags // (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4) $_language = $this->_pregMatchAcceptLanguage(); - } elseif (!isset($_language) && $conf['default_lang'] != 'auto' && isset($appLangFiles[$conf['default_lang']])) { + } elseif (!isset($_language) && 'auto' !== $conf['default_lang'] && isset($appLangFiles[$conf['default_lang']])) { // 5. Otherwise resort to the default set in the config file $_language = $conf['default_lang']; } else { @@ -199,13 +202,13 @@ class Translations $_language = 'english'; } - $_type = '\PHPPgAdmin\Translations\\'.$appClasses[$_language]; + $_type = '\PHPPgAdmin\Translations\\' . $appClasses[$_language]; $langClass = new $_type(); $_SESSION['webdbLanguage'] = $_language; - if (array_key_exists($_language, $languages_iso_code)) { + if (\array_key_exists($_language, $languages_iso_code)) { $_isolang = $languages_iso_code[$_language]; } else { $_isolang = 'en'; @@ -232,19 +235,20 @@ class Translations { $_language = null; $_acceptLang = []; - preg_match_all( + \preg_match_all( '/\s*([a-z]{1,8}(?:-[a-z]{1,8})*)(?:;q=([01](?:.[0-9]{0,3})?))?\s*(?:,|$)/', - strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']), + \mb_strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']), $_m, - PREG_SET_ORDER + \PREG_SET_ORDER ); + foreach ($_m as $_l) { // $_l[1] = language tag, [2] = quality if (!isset($_l[2])) { $_l[2] = 1; } // Default quality to 1 - if ($_l[2] > 0 && $_l[2] <= 1 && isset($this->availableLanguages[$_l[1]])) { + if (0 < $_l[2] && 1 >= $_l[2] && isset($this->availableLanguages[$_l[1]])) { // Build up array of (quality => language_file) $_acceptLang[$_l[2]] = $this->availableLanguages[$_l[1]]; } @@ -253,8 +257,8 @@ class Translations if (!empty($_acceptLang)) { // Sort acceptable languages by quality - krsort($_acceptLang, SORT_NUMERIC); - $_language = reset($_acceptLang); + \krsort($_acceptLang, \SORT_NUMERIC); + $_language = \reset($_acceptLang); unset($_acceptLang); } diff --git a/src/controllers/AcinsertController.php b/src/controllers/AcinsertController.php index 9bea57f6..52a3ada5 100644 --- a/src/controllers/AcinsertController.php +++ b/src/controllers/AcinsertController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -14,7 +17,7 @@ class AcinsertController extends BaseController /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { $data = $this->misc->getDatabaseAccessor(); @@ -26,15 +29,16 @@ class AcinsertController extends BaseController } $fkeynames = []; + foreach ($_POST['fkeynames'] as $k => $v) { - $fkeynames[$k] = html_entity_decode($v, ENT_QUOTES); + $fkeynames[$k] = \html_entity_decode($v, \ENT_QUOTES); } - $keyspos = array_combine($fkeynames, $_POST['keys']); + $keyspos = \array_combine($fkeynames, $_POST['keys']); - $f_schema = html_entity_decode($_POST['f_schema'], ENT_QUOTES); + $f_schema = \html_entity_decode($_POST['f_schema'], \ENT_QUOTES); $data->fieldClean($f_schema); - $f_table = html_entity_decode($_POST['f_table'], ENT_QUOTES); + $f_table = \html_entity_decode($_POST['f_table'], \ENT_QUOTES); $data->fieldClean($f_table); $f_attname = $fkeynames[$_POST['fattpos'][0]]; $data->fieldClean($f_attname); @@ -49,23 +53,27 @@ class AcinsertController extends BaseController if (!$res->EOF) { echo '<table class="ac_values">'; echo '<tr>'; - foreach (array_keys($res->fields) as $h) { + + foreach (\array_keys($res->fields) as $h) { echo '<th>'; - if (in_array($h, $fkeynames, true)) { - echo '<img src="'.$this->misc->icon('ForeignKey').'" alt="[referenced key]" />'; + if (\in_array($h, $fkeynames, true)) { + echo '<img src="' . $this->misc->icon('ForeignKey') . '" alt="[referenced key]" />'; } - echo htmlentities($h, ENT_QUOTES, 'UTF-8'), '</th>'; + echo \htmlentities($h, \ENT_QUOTES, 'UTF-8'), '</th>'; } - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; $i = 0; - while ((!$res->EOF) && ($i < 11)) { + + while ((!$res->EOF) && (11 > $i)) { $j = 0; echo '<tr class="acline">'; + foreach ($res->fields as $n => $v) { $finfo = $res->fetchField($j++); - if (in_array($n, $fkeynames, true)) { + + if (\in_array($n, $fkeynames, true)) { echo "<td><a href=\"javascript:void(0)\" class=\"fkval\" name=\"{$keyspos[$n]}\">", $this->misc->printVal($v, $finfo->type, ['clip' => 'collapsed']), '</a></td>'; @@ -75,13 +83,13 @@ class AcinsertController extends BaseController '</a></td>'; } } - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; ++$i; $res->moveNext(); } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; - $js = '<script type="text/javascript">'.PHP_EOL; + $js = '<script type="text/javascript">' . \PHP_EOL; if ($_POST['offset']) { echo '<a href="javascript:void(0)" id="fkprev"><< Prev</a>'; @@ -90,16 +98,16 @@ class AcinsertController extends BaseController $js .= "fkl_hasprev=false;\n"; } - if (12 == $res->recordCount()) { + if (12 === $res->recordCount()) { $js .= "fkl_hasnext=true;\n"; echo ' <a href="javascript:void(0)" id="fknext">Next >></a>'; } else { $js .= "fkl_hasnext=false;\n"; } - echo $js.'</script>'; + echo $js . '</script>'; } else { - printf("<p>{$this->lang['strnofkref']}</p>", "\"{$_POST['f_schema']}\".\"{$_POST['f_table']}\".\"{$fkeynames[$_POST['fattpos']]}\""); + \printf("<p>{$this->lang['strnofkref']}</p>", "\"{$_POST['f_schema']}\".\"{$_POST['f_table']}\".\"{$fkeynames[$_POST['fattpos']]}\""); if ($_POST['offset']) { echo '<a href="javascript:void(0)" class="fkprev">Prev <<</a>'; diff --git a/src/controllers/AggregatesController.php b/src/controllers/AggregatesController.php index 44062f0b..eddcf7ce 100644 --- a/src/controllers/AggregatesController.php +++ b/src/controllers/AggregatesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,12 +13,11 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class AggregatesController extends BaseController { - public $table_place = 'aggregates-aggregates'; + public $table_place = 'aggregates-aggregates'; + public $controller_title = 'straggregates'; /** @@ -23,11 +25,12 @@ class AggregatesController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } - ob_start(); + \ob_start(); + switch ($this->action) { case 'create': $this->doCreate(); @@ -75,7 +78,7 @@ class AggregatesController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $this->printHeader($this->headerTitle()); $this->printBody(); @@ -89,7 +92,7 @@ class AggregatesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $this->printTrail('schema'); $this->printTabs('schema', 'aggregates'); @@ -152,6 +155,7 @@ class AggregatesController extends BaseController ], ], ]; + if (!$this->data->hasAlterAggregate()) { unset($actions['alter']); } @@ -174,7 +178,7 @@ class AggregatesController extends BaseController 'content' => $this->lang['strcreateaggregate'], ], ]; - $this->printNavLinks($navlinks, $this->table_place, get_defined_vars()); + $this->printNavLinks($navlinks, $this->table_place, \get_defined_vars()); } public function doTree() @@ -210,16 +214,19 @@ class AggregatesController extends BaseController { $this->data = $this->misc->getDatabaseAccessor(); // Check inputs - if ('' == trim($_REQUEST['name'])) { + if ('' === \trim($_REQUEST['name'])) { return $this->doCreate($this->lang['straggrneedsname']); } - if ('' == trim($_REQUEST['basetype'])) { + + if ('' === \trim($_REQUEST['basetype'])) { return $this->doCreate($this->lang['straggrneedsbasetype']); } - if ('' == trim($_REQUEST['sfunc'])) { + + if ('' === \trim($_REQUEST['sfunc'])) { return $this->doCreate($this->lang['straggrneedssfunc']); } - if ('' == trim($_REQUEST['stype'])) { + + if ('' === \trim($_REQUEST['stype'])) { return $this->doCreate($this->lang['straggrneedsstype']); } @@ -234,7 +241,7 @@ class AggregatesController extends BaseController $_REQUEST['aggrcomment'] ); - if (0 == $status) { + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['straggrcreated']); } else { @@ -247,7 +254,7 @@ class AggregatesController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $this->data = $this->misc->getDatabaseAccessor(); @@ -271,50 +278,50 @@ class AggregatesController extends BaseController $this->printTitle($this->lang['strcreateaggregate'], 'pg.aggregate.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/aggregates" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/aggregates" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"name\" size=\"32\" maxlength=\"{$this->data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['straggrbasetype']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['straggrbasetype']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"basetype\" size=\"32\" maxlength=\"{$this->data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['basetype']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['straggrsfunc']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['basetype']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['straggrsfunc']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"sfunc\" size=\"32\" maxlength=\"{$this->data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['sfunc']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['straggrstype']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['sfunc']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['straggrstype']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"stype\" size=\"32\" maxlength=\"{$this->data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['stype']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['straggrffunc']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['stype']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['straggrffunc']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"ffunc\" size=\"32\" maxlength=\"{$this->data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['ffunc']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['straggrinitcond']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['ffunc']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['straggrinitcond']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"initcond\" size=\"32\" maxlength=\"{$this->data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['initcond']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['straggrsortop']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['initcond']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['straggrsortop']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"sortop\" size=\"32\" maxlength=\"{$this->data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['sortop']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['sortop']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td><textarea name=\"aggrcomment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_REQUEST['aggrcomment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['aggrcomment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Function to save after altering an aggregate. */ - public function doSaveAlter() + public function doSaveAlter(): void { $this->data = $this->misc->getDatabaseAccessor(); // Check inputs - if ('' == trim($_REQUEST['aggrname'])) { + if ('' === \trim($_REQUEST['aggrname'])) { $this->doAlter($this->lang['straggrneedsname']); return; @@ -331,7 +338,8 @@ class AggregatesController extends BaseController $_REQUEST['newaggrschema'], $_REQUEST['newaggrcomment'] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['straggraltered']); } else { $this->doAlter($this->lang['straggralteredbad']); @@ -345,7 +353,7 @@ class AggregatesController extends BaseController * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $this->data = $this->misc->getDatabaseAccessor(); @@ -353,37 +361,38 @@ class AggregatesController extends BaseController $this->printTitle($this->lang['stralter'], 'pg.aggregate.alter'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/aggregates" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/aggregates" method="post">' . \PHP_EOL; $aggrdata = $this->data->getAggregate($_REQUEST['aggrname'], $_REQUEST['aggrtype']); - if ($aggrdata->recordCount() > 0) { + + if (0 < $aggrdata->recordCount()) { // Output table header - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "\t<tr>\n\t\t<th class=\"data required\">{$this->lang['strname']}</th>"; echo "<th class=\"data required\">{$this->lang['strowner']}</th>"; - echo "<th class=\"data required\">{$this->lang['strschema']}</th>\n\t</tr>".PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strschema']}</th>\n\t</tr>" . \PHP_EOL; // Display aggregate's name, owner and schema - echo "\t<tr>\n\t\t<td><input name=\"newaggrname\" size=\"32\" maxlength=\"32\" value=\"", htmlspecialchars($_REQUEST['aggrname']), '" /></td>'; - echo '<td><input name="newaggrowner" size="32" maxlength="32" value="', htmlspecialchars($aggrdata->fields['usename']), '" /></td>'; - echo '<td><input name="newaggrschema" size="32" maxlength="32" value="', htmlspecialchars($_REQUEST['schema']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<td><input name=\"newaggrname\" size=\"32\" maxlength=\"32\" value=\"", \htmlspecialchars($_REQUEST['aggrname']), '" /></td>'; + echo '<td><input name="newaggrowner" size="32" maxlength="32" value="', \htmlspecialchars($aggrdata->fields['usename']), '" /></td>'; + echo '<td><input name="newaggrschema" size="32" maxlength="32" value="', \htmlspecialchars($_REQUEST['schema']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td><textarea name=\"newaggrcomment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($aggrdata->fields['aggrcomment']), "</textarea></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_alter" />'.PHP_EOL; + \htmlspecialchars($aggrdata->fields['aggrcomment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_alter" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="aggrname" value="', htmlspecialchars($_REQUEST['aggrname']), '" />'.PHP_EOL; - echo '<input type="hidden" name="aggrtype" value="', htmlspecialchars($_REQUEST['aggrtype']), '" />'.PHP_EOL; - echo '<input type="hidden" name="aggrowner" value="', htmlspecialchars($aggrdata->fields['usename']), '" />'.PHP_EOL; - echo '<input type="hidden" name="aggrschema" value="', htmlspecialchars($_REQUEST['schema']), '" />'.PHP_EOL; - echo '<input type="hidden" name="aggrcomment" value="', htmlspecialchars($aggrdata->fields['aggrcomment']), '" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; + echo '<input type="hidden" name="aggrname" value="', \htmlspecialchars($_REQUEST['aggrname']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="aggrtype" value="', \htmlspecialchars($_REQUEST['aggrtype']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="aggrowner" value="', \htmlspecialchars($aggrdata->fields['usename']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="aggrschema" value="', \htmlspecialchars($_REQUEST['schema']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="aggrcomment" value="', \htmlspecialchars($aggrdata->fields['aggrcomment']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strback']}\" /></p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strback']}\" /></p>" . \PHP_EOL; } - echo '</form>'.PHP_EOL; + echo '</form>' . \PHP_EOL; } /** @@ -391,7 +400,7 @@ class AggregatesController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $this->data = $this->misc->getDatabaseAccessor(); @@ -399,20 +408,21 @@ class AggregatesController extends BaseController $this->printTrail('aggregate'); $this->printTitle($this->lang['strdrop'], 'pg.aggregate.drop'); - echo '<p>', sprintf($this->lang['strconfdropaggregate'], htmlspecialchars($_REQUEST['aggrname'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropaggregate'], \htmlspecialchars($_REQUEST['aggrname'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/aggregates" method="post">'.PHP_EOL; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo '<p><input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="aggrname" value="', htmlspecialchars($_REQUEST['aggrname']), '" />'.PHP_EOL; - echo '<input type="hidden" name="aggrtype" value="', htmlspecialchars($_REQUEST['aggrtype']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/aggregates" method="post">' . \PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="aggrname" value="', \htmlspecialchars($_REQUEST['aggrname']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="aggrtype" value="', \htmlspecialchars($_REQUEST['aggrtype']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $this->data->dropAggregate($_POST['aggrname'], $_POST['aggrtype'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['straggregatedropped']); } else { @@ -426,7 +436,7 @@ class AggregatesController extends BaseController * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $this->data = $this->misc->getDatabaseAccessor(); @@ -436,32 +446,33 @@ class AggregatesController extends BaseController $aggrdata = $this->data->getAggregate($_REQUEST['aggrname'], $_REQUEST['aggrtype']); - if ($aggrdata->recordCount() > 0) { + if (0 < $aggrdata->recordCount()) { // Display aggregate's info - echo '<table>'.PHP_EOL; - echo "<tr>\n\t<th class=\"data left\">{$this->lang['strname']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", htmlspecialchars($_REQUEST['aggrname']), "</td>\n</tr>".PHP_EOL; - echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrbasetype']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", htmlspecialchars($_REQUEST['aggrtype']), "</td>\n</tr>".PHP_EOL; - echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrsfunc']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", htmlspecialchars($aggrdata->fields['aggtransfn']), "</td>\n</tr>".PHP_EOL; - echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrstype']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", htmlspecialchars($aggrdata->fields['aggstype']), "</td>\n</tr>".PHP_EOL; - echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrffunc']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", htmlspecialchars($aggrdata->fields['aggfinalfn']), "</td>\n</tr>".PHP_EOL; - echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrinitcond']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", htmlspecialchars($aggrdata->fields['agginitval']), "</td>\n</tr>".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", \htmlspecialchars($_REQUEST['aggrname']), "</td>\n</tr>" . \PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrbasetype']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", \htmlspecialchars($_REQUEST['aggrtype']), "</td>\n</tr>" . \PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrsfunc']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", \htmlspecialchars($aggrdata->fields['aggtransfn']), "</td>\n</tr>" . \PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrstype']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", \htmlspecialchars($aggrdata->fields['aggstype']), "</td>\n</tr>" . \PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrffunc']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", \htmlspecialchars($aggrdata->fields['aggfinalfn']), "</td>\n</tr>" . \PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrinitcond']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", \htmlspecialchars($aggrdata->fields['agginitval']), "</td>\n</tr>" . \PHP_EOL; + if ($this->data->hasAggregateSortOp()) { - echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrsortop']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", htmlspecialchars($aggrdata->fields['aggsortop']), "</td>\n</tr>".PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['straggrsortop']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", \htmlspecialchars($aggrdata->fields['aggsortop']), "</td>\n</tr>" . \PHP_EOL; } - echo "<tr>\n\t<th class=\"data left\">{$this->lang['strowner']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", htmlspecialchars($aggrdata->fields['usename']), "</td>\n</tr>".PHP_EOL; - echo "<tr>\n\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; - echo "\t<td class=\"data1\">", $this->misc->printVal($aggrdata->fields['aggrcomment']), "</td>\n</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['strowner']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", \htmlspecialchars($aggrdata->fields['usename']), "</td>\n</tr>" . \PHP_EOL; + echo "<tr>\n\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; + echo "\t<td class=\"data1\">", $this->misc->printVal($aggrdata->fields['aggrcomment']), "</td>\n</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } $navlinks = [ @@ -516,6 +527,6 @@ class AggregatesController extends BaseController 'content' => $this->lang['strdrop'], ]; - $this->printNavLinks($navlinks, 'aggregates-properties', get_defined_vars()); + $this->printNavLinks($navlinks, 'aggregates-properties', \get_defined_vars()); } } diff --git a/src/controllers/AlldbController.php b/src/controllers/AlldbController.php index 22d40b30..562dc065 100644 --- a/src/controllers/AlldbController.php +++ b/src/controllers/AlldbController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,13 +13,13 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class AlldbController extends BaseController { use \PHPPgAdmin\Traits\ExportTrait; - public $table_place = 'alldb-databases'; + + public $table_place = 'alldb-databases'; + public $controller_title = 'strdatabases'; /** @@ -24,13 +27,14 @@ class AlldbController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } $header_template = 'header.twig'; - ob_start(); + \ob_start(); + switch ($this->action) { case 'export': $this->doExport(); @@ -78,7 +82,7 @@ class AlldbController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $this->printHeader($this->headerTitle(), null, true, $header_template); $this->printBody(); @@ -92,7 +96,7 @@ class AlldbController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $this->printTrail('server'); $this->printTabs('server', 'databases'); @@ -114,7 +118,7 @@ class AlldbController extends BaseController 'database' => [ 'title' => $this->lang['strdatabase'], 'field' => Decorator::field('datname'), - 'url' => \SUBFOLDER.$redirecturl.'&', + 'url' => self::SUBFOLDER . $redirecturl . '&', 'vars' => ['database' => 'datname'], ], 'owner' => [ @@ -185,6 +189,7 @@ class AlldbController extends BaseController ], ], ]; + if ($data->hasAlterDatabase()) { $actions['alter'] = [ 'content' => $this->lang['stralter'], @@ -233,7 +238,7 @@ class AlldbController extends BaseController 'content' => $this->lang['strcreatedatabase'], ], ]; - $this->printNavLinks($navlinks, $this->table_place, get_defined_vars()); + $this->printNavLinks($navlinks, $this->table_place, \get_defined_vars()); } public function doTree() @@ -260,7 +265,7 @@ class AlldbController extends BaseController * * @param mixed $confirm */ - public function doAlter($confirm) + public function doAlter($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -268,12 +273,12 @@ class AlldbController extends BaseController $this->printTrail('database'); $this->printTitle($this->lang['stralter'], 'pg.database.alter'); - echo '<form action="'.\SUBFOLDER.'/src/views/alldb" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/alldb" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo "<input name=\"newname\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['alterdatabase']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_REQUEST['alterdatabase']), '" /></td></tr>' . \PHP_EOL; if ($data->hasAlterDatabaseOwner() && $data->isSuperUser()) { // Fetch all users @@ -282,38 +287,40 @@ class AlldbController extends BaseController $owner = isset($rs->fields['usename']) ? $rs->fields['usename'] : ''; $users = $data->getUsers(); - echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="owner">'; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $owner) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $owner) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } + if ($data->hasSharedComments()) { $rs = $data->getDatabaseComment($_REQUEST['alterdatabase']); $comment = isset($rs->fields['description']) ? $rs->fields['description'] : ''; - echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo '<textarea rows="3" cols="32" name="dbcomment">', - htmlspecialchars($comment), '</textarea></td></tr>'.PHP_EOL; + \htmlspecialchars($comment), '</textarea></td></tr>' . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<input type="hidden" name="action" value="alter" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<input type="hidden" name="action" value="alter" />' . \PHP_EOL; echo $this->misc->form; echo '<input type="hidden" name="oldname" value="', - htmlspecialchars($_REQUEST['alterdatabase']), '" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + \htmlspecialchars($_REQUEST['alterdatabase']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $this->coalesceArr($_POST, 'owner', ''); $this->coalesceArr($_POST, 'dbcomment', ''); - if (0 == $data->alterDatabase($_POST['oldname'], $_POST['newname'], $_POST['owner'], $_POST['dbcomment'])) { + if (0 === $data->alterDatabase($_POST['oldname'], $_POST['newname'], $_POST['owner'], $_POST['dbcomment'])) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strdatabasealtered']); } else { @@ -339,35 +346,37 @@ class AlldbController extends BaseController $this->printTrail('database'); $this->printTitle($this->lang['strdrop'], 'pg.database.drop'); - echo '<form action="'.\SUBFOLDER.'/src/views/alldb" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/alldb" method="post">' . \PHP_EOL; //If multi drop if (isset($_REQUEST['ma'])) { foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfdropdatabase'], $this->misc->printVal($a['database'])), '</p>'.PHP_EOL; - printf('<input type="hidden" name="dropdatabase[]" value="%s" />', htmlspecialchars($a['database'])); + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfdropdatabase'], $this->misc->printVal($a['database'])), '</p>' . \PHP_EOL; + \printf('<input type="hidden" name="dropdatabase[]" value="%s" />', \htmlspecialchars($a['database'])); } } else { - echo '<p>', sprintf($this->lang['strconfdropdatabase'], $this->misc->printVal($_REQUEST['dropdatabase'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="dropdatabase" value="', htmlspecialchars($_REQUEST['dropdatabase']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropdatabase'], $this->misc->printVal($_REQUEST['dropdatabase'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="dropdatabase" value="', \htmlspecialchars($_REQUEST['dropdatabase']), '" />' . \PHP_EOL; // END if multi drop } - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; echo "</form>\n"; // END confirm } else { //If multi drop - if (is_array($_REQUEST['dropdatabase'])) { + if (\is_array($_REQUEST['dropdatabase'])) { $msg = ''; + foreach ($_REQUEST['dropdatabase'] as $d) { $status = $data->dropDatabase($d); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($d, ENT_QUOTES, 'UTF-8'), $this->lang['strdatabasedropped']); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($d, \ENT_QUOTES, 'UTF-8'), $this->lang['strdatabasedropped']); } else { - $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($d, ENT_QUOTES, 'UTF-8'), $this->lang['strdatabasedroppedbad'])); + $this->doDefault(\sprintf('%s%s: %s<br />', $msg, \htmlentities($d, \ENT_QUOTES, 'UTF-8'), $this->lang['strdatabasedroppedbad'])); return; } @@ -377,7 +386,8 @@ class AlldbController extends BaseController $this->doDefault($msg); } else { $status = $data->dropDatabase($_POST['dropdatabase']); - if (0 == $status) { + + if (0 === $status) { $this->setReloadDropDatabase(true); $this->doDefault($this->lang['strdatabasedropped']); } else { @@ -395,7 +405,7 @@ class AlldbController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -422,45 +432,47 @@ class AlldbController extends BaseController $tablespaces = $data->getTablespaces(); } - echo '<form action="'.\SUBFOLDER.'/src/views/alldb" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/alldb" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input name=\"formName\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['formName']), "\" /></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formName']), "\" /></td>\n\t</tr>" . \PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strtemplatedb']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">".PHP_EOL; - echo "\t\t\t<select name=\"formTemplate\">".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strtemplatedb']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">" . \PHP_EOL; + echo "\t\t\t<select name=\"formTemplate\">" . \PHP_EOL; // Always offer template0 and template1 echo "\t\t\t\t<option value=\"template0\"", - ('template0' == $_POST['formTemplate']) ? ' selected="selected"' : '', '>template0</option>'.PHP_EOL; + ('template0' === $_POST['formTemplate']) ? ' selected="selected"' : '', '>template0</option>' . \PHP_EOL; echo "\t\t\t\t<option value=\"template1\"", - ('template1' == $_POST['formTemplate']) ? ' selected="selected"' : '', '>template1</option>'.PHP_EOL; + ('template1' === $_POST['formTemplate']) ? ' selected="selected"' : '', '>template1</option>' . \PHP_EOL; + while (!$templatedbs->EOF) { - $dbname = htmlspecialchars($templatedbs->fields['datname']); - if ('template1' != $dbname) { + $dbname = \htmlspecialchars($templatedbs->fields['datname']); + + if ('template1' !== $dbname) { // filter out for $this->conf[show_system] users so we dont get duplicates echo "\t\t\t\t<option value=\"{$dbname}\"", - ($dbname == $_POST['formTemplate']) ? ' selected="selected"' : '', ">{$dbname}</option>".PHP_EOL; + ($dbname === $_POST['formTemplate']) ? ' selected="selected"' : '', ">{$dbname}</option>" . \PHP_EOL; } $templatedbs->moveNext(); } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; // ENCODING - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strencoding']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">".PHP_EOL; - echo "\t\t\t<select name=\"formEncoding\">".PHP_EOL; - echo "\t\t\t\t<option value=\"\"></option>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strencoding']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">" . \PHP_EOL; + echo "\t\t\t<select name=\"formEncoding\">" . \PHP_EOL; + echo "\t\t\t\t<option value=\"\"></option>" . \PHP_EOL; foreach ($data->codemap as $key) { - echo "\t\t\t\t<option value=\"", htmlspecialchars($key), '"', - ($key == $_POST['formEncoding']) ? ' selected="selected"' : '', '>', - $this->misc->printVal($key), '</option>'.PHP_EOL; + echo "\t\t\t\t<option value=\"", \htmlspecialchars($key), '"', + ($key === $_POST['formEncoding']) ? ' selected="selected"' : '', '>', + $this->misc->printVal($key), '</option>' . \PHP_EOL; } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; if ($data->hasDatabaseCollation()) { $this->coalesceArr($_POST, 'formCollate', ''); @@ -468,54 +480,54 @@ class AlldbController extends BaseController $this->coalesceArr($_POST, 'formCType', ''); // LC_COLLATE - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcollation']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">".PHP_EOL; - echo "\t\t\t<input name=\"formCollate\" value=\"", htmlspecialchars($_POST['formCollate']), '" />'.PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcollation']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">" . \PHP_EOL; + echo "\t\t\t<input name=\"formCollate\" value=\"", \htmlspecialchars($_POST['formCollate']), '" />' . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; // LC_CTYPE - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strctype']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">".PHP_EOL; - echo "\t\t\t<input name=\"formCType\" value=\"", htmlspecialchars($_POST['formCType']), '" />'.PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strctype']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">" . \PHP_EOL; + echo "\t\t\t<input name=\"formCType\" value=\"", \htmlspecialchars($_POST['formCType']), '" />' . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; } // Tablespace (if there are any) - if ($data->hasTablespaces() && $tablespaces->recordCount() > 0) { - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"formSpc\">".PHP_EOL; + if ($data->hasTablespaces() && 0 < $tablespaces->recordCount()) { + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"formSpc\">" . \PHP_EOL; // Always offer the default (empty) option echo "\t\t\t\t<option value=\"\"", - ('' == $_POST['formSpc']) ? ' selected="selected"' : '', '></option>'.PHP_EOL; + ('' === $_POST['formSpc']) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; // Display all other tablespaces while (!$tablespaces->EOF) { - $spcname = htmlspecialchars($tablespaces->fields['spcname']); + $spcname = \htmlspecialchars($tablespaces->fields['spcname']); echo "\t\t\t\t<option value=\"{$spcname}\"", - ($spcname == $_POST['formSpc']) ? ' selected="selected"' : '', ">{$spcname}</option>".PHP_EOL; + ($spcname === $_POST['formSpc']) ? ' selected="selected"' : '', ">{$spcname}</option>" . \PHP_EOL; $tablespaces->moveNext(); } - echo "\t\t\t</select>\n\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>\n\t\t</td>\n\t</tr>" . \PHP_EOL; } // Comments (if available) if ($data->hasSharedComments()) { - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td><textarea name=\"formComment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new view in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); @@ -532,7 +544,7 @@ class AlldbController extends BaseController $this->coalesceArr($_POST, 'formCType', null); // Check that they've given a name and a definition - if ('' == $_POST['formName']) { + if ('' === $_POST['formName']) { $this->doCreate($this->lang['strdatabaseneedsname']); } else { $status = $data->createDatabase( @@ -544,7 +556,8 @@ class AlldbController extends BaseController $_POST['formCollate'], $_POST['formCType'] ); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strdatabasecreated']); } else { @@ -558,7 +571,7 @@ class AlldbController extends BaseController * * @param mixed $msg */ - public function doExport($msg = '') + public function doExport($msg = ''): void { $this->printTrail('server'); $this->printTabs('server', 'export'); @@ -579,7 +592,7 @@ class AlldbController extends BaseController $server_info = $this->misc->getServerInfo(); - echo $this->offerNoRoleExport(isset($server_info['pgVersion']) && (float) (substr($server_info['pgVersion'], 0, 3)) >= 10); + echo $this->offerNoRoleExport(isset($server_info['pgVersion']) && 10 <= (float) (\mb_substr($server_info['pgVersion'], 0, 3))); // dumpall doesn't support gzip echo $this->displayOrDownload(false); diff --git a/src/controllers/BaseController.php b/src/controllers/BaseController.php index 840d6a10..78d80041 100644 --- a/src/controllers/BaseController.php +++ b/src/controllers/BaseController.php @@ -1,34 +1,59 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; -ini_set('display_errors', 1); +use PHPPgAdmin\XHtml; + +\defined('BASE_PATH') || \define(BASE_PATH, \dirname(__DIR__, 2)); +\defined('SUBFOLDER') || \define( + 'SUBFOLDER', + \str_replace($_SERVER['DOCUMENT_ROOT'] ?? '', '', BASE_PATH) +); +\defined('DEBUGMODE') || \define('DEBUGMODE', false); + +\ini_set('display_errors', DEBUGMODE); /** * Base controller class. - * - * @package PHPPgAdmin */ class BaseController { use \PHPPgAdmin\Traits\HelperTrait; + /** + * @var string + */ + const BASE_PATH = BASE_PATH; + /** + * @var string + */ + const SUBFOLDER = SUBFOLDER; + /** + * @var string + */ + const DEBUGMODE = DEBUGMODE; - protected $container; - protected $app; - protected $data; - protected $database; - protected $server_id; public $appLangFiles = []; - public $appThemes = []; - public $appName = ''; - public $appVersion = ''; - public $form = ''; - public $href = ''; - public $lang = []; - public $action = ''; + + public $appThemes = []; + + public $appName = ''; + + public $appVersion = ''; + + public $form = ''; + + public $href = ''; + + public $lang = []; + + public $action = ''; + public $controller_name; /** @@ -37,24 +62,61 @@ class BaseController * @var string */ public $view_name; + /** * Used to print the title passing its value to $lang. * * @var string */ public $controller_title = 'base'; - protected $table_controller; - protected $trail_controller; - protected $tree_controller; - protected $footer_controller; - protected $header_controller; - protected $scripts = ''; - public $msg = ''; + + public $msg = ''; + public $view; public $misc; + public $conf; + public $phpMinVer; + + protected $container; + + protected $app; + + protected $data; + + protected $database; + + protected $server_id; + + /** + * @var XHtml\HTMLTableController + */ + protected $_table_controller; + + /** + * @var XHtml\HTMLFooterController + */ + protected $_footer_controller; + + /** + * @var XHtml\HTMLHeaderController + */ + protected $_header_controller; + + /** + * @var XHtml\HTMLNavbarController + */ + protected $_trail_controller; + + /** + * @var TreeController + */ + protected $_tree_controller; + + protected $scripts = ''; + protected $no_db_connection = false; /** @@ -68,8 +130,8 @@ class BaseController $this->container = $container; $this->lang = $container->get('lang'); - $this->controller_name = str_replace(__NAMESPACE__.'\\', '', get_class($this)); - $this->view_name = str_replace('controller', '', strtolower($this->controller_name)); + $this->controller_name = \str_replace(__NAMESPACE__ . '\\', '', \get_class($this)); + $this->view_name = \str_replace('controller', '', \mb_strtolower($this->controller_name)); $this->script = $this->view_name; $this->view = $container->get('view'); @@ -103,7 +165,7 @@ class BaseController $_server_info = $this->misc->getServerInfo(); // Redirect to the login form if not logged in if (!isset($_server_info['username'])) { - $msg = sprintf($this->lang['strlogoutmsg'], $_server_info['desc']); + $msg = \sprintf($this->lang['strlogoutmsg'], $_server_info['desc']); $servers_controller = new \PHPPgAdmin\Controller\ServersController($container); @@ -114,6 +176,7 @@ class BaseController /** * Default method to render the controller according to the action parameter. + * @return string|void */ public function render() { @@ -153,7 +216,7 @@ class BaseController { $title = $title ? $title : $this->controller_title; - return $prefix.$this->lang[$title].($suffix ? ': '.$suffix : ''); + return $prefix . $this->lang[$title] . ($suffix ? ': ' . $suffix : ''); } public function getContainer() @@ -161,51 +224,6 @@ class BaseController return $this->container; } - private function _getTableController() - { - if (null === $this->table_controller) { - $this->table_controller = new \PHPPgAdmin\XHtml\HTMLTableController($this->getContainer(), $this->controller_name); - } - - return $this->table_controller; - } - - private function _getFooterController() - { - if (null === $this->footer_controller) { - $this->footer_controller = new \PHPPgAdmin\XHtml\HTMLFooterController($this->getContainer(), $this->controller_name); - } - - return $this->footer_controller; - } - - private function _getHeaderController() - { - if (null === $this->header_controller) { - $this->header_controller = new \PHPPgAdmin\XHtml\HTMLHeaderController($this->getContainer(), $this->controller_name); - } - - return $this->header_controller; - } - - private function _getNavbarController() - { - if (null === $this->trail_controller) { - $this->trail_controller = new \PHPPgAdmin\XHtml\HTMLNavbarController($this->getContainer(), $this->controller_name); - } - - return $this->trail_controller; - } - - private function _getTreeController() - { - if (null === $this->tree_controller) { - $this->tree_controller = new \PHPPgAdmin\XHtml\TreeController($this->getContainer(), $this->controller_name); - } - - return $this->tree_controller; - } - /** * Display a table of data. * @@ -227,7 +245,14 @@ class BaseController return $html_table->printTable(); } - public function adjustTabsForTree($tabs) + /** + * Hides or show tree tabs according to their properties. + * + * @param array $tabs The tabs + * + * @return \PHPPgAdmin\ArrayRecordSet filtered tabs in the form of an ArrayRecordSet + */ + public function adjustTabsForTree(&$tabs) { $tree = $this->_getTreeController(); @@ -395,10 +420,12 @@ class BaseController public function printMsg($msg, $do_print = true) { $html = ''; - $msg = htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($msg)); - if ('' != $msg) { - $html .= '<p class="message">'.nl2br($msg).'</p>'.PHP_EOL; + $msg = \htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($msg)); + + if ('' !== $msg) { + $html .= '<p class="message">' . \nl2br($msg) . '</p>' . \PHP_EOL; } + if ($do_print) { echo $html; @@ -407,4 +434,49 @@ class BaseController return $html; } + + private function _getTableController() + { + if (null === $this->_table_controller) { + $this->_table_controller = new XHtml\HTMLTableController($this->getContainer(), $this->controller_name); + } + + return $this->_table_controller; + } + + private function _getFooterController() + { + if (null === $this->_footer_controller) { + $this->_footer_controller = new XHtml\HTMLFooterController($this->getContainer(), $this->controller_name); + } + + return $this->_footer_controller; + } + + private function _getHeaderController() + { + if (null === $this->_header_controller) { + $this->_header_controller = new XHtml\HTMLHeaderController($this->getContainer(), $this->controller_name); + } + + return $this->_header_controller; + } + + private function _getNavbarController() + { + if (null === $this->_trail_controller) { + $this->_trail_controller = new XHtml\HTMLNavbarController($this->getContainer(), $this->controller_name); + } + + return $this->_trail_controller; + } + + private function _getTreeController() + { + if (null === $this->_tree_controller) { + $this->_tree_controller = new TreeController($this->getContainer(), $this->controller_name); + } + + return $this->_tree_controller; + } } diff --git a/src/controllers/BrowserController.php b/src/controllers/BrowserController.php index a3a0d4bd..318372c1 100644 --- a/src/controllers/BrowserController.php +++ b/src/controllers/BrowserController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class BrowserController extends BaseController { @@ -24,7 +25,7 @@ class BrowserController extends BaseController */ public function render($action = null) { - if ($action === null) { + if (null === $action) { $action = $this->action; } diff --git a/src/controllers/CastsController.php b/src/controllers/CastsController.php index 68c0a1a9..27e52e96 100644 --- a/src/controllers/CastsController.php +++ b/src/controllers/CastsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class CastsController extends BaseController { @@ -22,7 +23,7 @@ class CastsController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -44,12 +45,12 @@ class CastsController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $lang = $this->lang; - $renderCastContext = function ($val) use ($lang) { + $renderCastContext = static function ($val) use ($lang) { switch ($val) { case 'e': return $lang['strno']; diff --git a/src/controllers/ColpropertiesController.php b/src/controllers/ColpropertiesController.php index 1d113b72..ef733b59 100644 --- a/src/controllers/ColpropertiesController.php +++ b/src/controllers/ColpropertiesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,19 +13,19 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class ColpropertiesController extends BaseController { - public $tableName = ''; - public $table_place = 'colproperties-colproperties'; + public $tableName = ''; + + public $table_place = 'colproperties-colproperties'; + public $controller_title = 'strtables'; /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { if (isset($_REQUEST['table']) && !empty($_REQUEST['table'])) { $this->tableName = &$_REQUEST['table']; @@ -65,14 +68,14 @@ class ColpropertiesController extends BaseController * @param string $msg message to display * @param bool $isTable tells if we're showing table properties */ - public function doDefault($msg = '', $isTable = true) + public function doDefault($msg = '', $isTable = true): void { if (!isset($_REQUEST['table']) || empty($_REQUEST['table'])) { $isTable = false; } $data = $this->misc->getDatabaseAccessor(); - $attPre = function (&$rowdata) use ($data) { + $attPre = static function (&$rowdata) use ($data): void { $rowdata->fields['+type'] = $data->formatType($rowdata->fields['type'], $rowdata->fields['atttypmod']); }; @@ -94,7 +97,7 @@ class ColpropertiesController extends BaseController // Show comment if any if (null !== $attrs->fields['comment']) { - echo '<p class="comment">', $this->misc->printVal($attrs->fields['comment']), '</p>'.PHP_EOL; + echo '<p class="comment">', $this->misc->printVal($attrs->fields['comment']), '</p>' . \PHP_EOL; } //$this->prtrace('$isTable', $isTable); @@ -125,7 +128,7 @@ class ColpropertiesController extends BaseController $actions = []; echo $this->printTable($attrs, $column, $actions, $this->table_place, $this->lang['strnodata'], $attPre); - echo '<br />'.PHP_EOL; + echo '<br />' . \PHP_EOL; $f_attname = $_REQUEST['column']; $f_table = $this->tableName; @@ -217,7 +220,7 @@ class ColpropertiesController extends BaseController ]; } - $this->printNavLinks($navlinks, $this->table_place, get_defined_vars()); + $this->printNavLinks($navlinks, $this->table_place, \get_defined_vars()); } } @@ -226,13 +229,13 @@ class ColpropertiesController extends BaseController * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $this->coalesceArr($_REQUEST, 'stage', 1); - #$this->prtrace('$_REQUEST', $_REQUEST, 'msg', $msg); + //$this->prtrace('$_REQUEST', $_REQUEST, 'msg', $msg); switch ($_REQUEST['stage']) { case 1: @@ -240,19 +243,20 @@ class ColpropertiesController extends BaseController $this->printTitle($this->lang['stralter'], 'pg.column.alter'); $this->printMsg($msg); - echo '<script src="'.\SUBFOLDER.'/assets/js/tables.js" type="text/javascript"></script>'; - echo '<form action="'.\SUBFOLDER.'/src/views/colproperties" method="post">'.PHP_EOL; + echo '<script src="' . self::SUBFOLDER . '/assets/js/tables.js" type="text/javascript"></script>'; + echo '<form action="' . self::SUBFOLDER . '/src/views/colproperties" method="post">' . \PHP_EOL; // Output table header - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data required\">{$this->lang['strname']}</th>" . \PHP_EOL; + if ($data->hasAlterColumnType()) { - echo "<th class=\"data required\" colspan=\"2\">{$this->lang['strtype']}</th>".PHP_EOL; - echo "<th class=\"data\">{$this->lang['strlength']}</th>".PHP_EOL; + echo "<th class=\"data required\" colspan=\"2\">{$this->lang['strtype']}</th>" . \PHP_EOL; + echo "<th class=\"data\">{$this->lang['strlength']}</th>" . \PHP_EOL; } else { - echo "<th class=\"data required\">{$this->lang['strtype']}</th>".PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strtype']}</th>" . \PHP_EOL; } - echo "<th class=\"data\">{$this->lang['strnotnull']}</th>\n<th class=\"data\">{$this->lang['strdefault']}</th>\n<th class=\"data\">{$this->lang['strcomment']}</th></tr>".PHP_EOL; + echo "<th class=\"data\">{$this->lang['strnotnull']}</th>\n<th class=\"data\">{$this->lang['strdefault']}</th>\n<th class=\"data\">{$this->lang['strcomment']}</th></tr>" . \PHP_EOL; $column = $data->getTableAttributes($_REQUEST['table'], $_REQUEST['column']); $column->fields['attnotnull'] = $data->phpBool($column->fields['attnotnull']); @@ -264,8 +268,8 @@ class ColpropertiesController extends BaseController $_REQUEST['type'] = $column->fields['base_type']; // Check to see if its' an array type... // @todo this is pretty hacky! - if ('[]' == substr($column->fields['base_type'], strlen($column->fields['base_type']) - 2)) { - $_REQUEST['type'] = substr($column->fields['base_type'], 0, strlen($column->fields['base_type']) - 2); + if ('[]' === \mb_substr($column->fields['base_type'], \mb_strlen($column->fields['base_type']) - 2)) { + $_REQUEST['type'] = \mb_substr($column->fields['base_type'], 0, \mb_strlen($column->fields['base_type']) - 2); $_REQUEST['array'] = '[]'; } else { $_REQUEST['type'] = $column->fields['base_type']; @@ -273,13 +277,14 @@ class ColpropertiesController extends BaseController } // To figure out the length, look in the brackets :( // @todo this is pretty hacky - if ($column->fields['type'] != $column->fields['base_type'] && preg_match('/\\(([0-9, ]*)\\)/', $column->fields['type'], $bits)) { + if ($column->fields['type'] !== $column->fields['base_type'] && \preg_match('/\\(([0-9, ]*)\\)/', $column->fields['type'], $bits)) { $_REQUEST['length'] = $bits[1]; } else { $_REQUEST['length'] = ''; } $_REQUEST['default'] = $_REQUEST['olddefault'] = $column->fields['adsrc']; + if ($column->fields['attnotnull']) { $_REQUEST['notnull'] = 'YES'; } @@ -289,7 +294,7 @@ class ColpropertiesController extends BaseController // Column name echo "<tr><td><input name=\"field\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['field']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_REQUEST['field']), '" /></td>' . \PHP_EOL; // Column type $escaped_predef_types = []; // the JS escaped array elements @@ -298,66 +303,69 @@ class ColpropertiesController extends BaseController $types = $data->getTypes(true, false, true); $types_for_js = []; - echo "<td><select name=\"type\" id=\"type\" class=\"select2\" onchange=\"checkLengths(document.getElementById('type').value,'');\">".PHP_EOL; + echo "<td><select name=\"type\" id=\"type\" class=\"select2\" onchange=\"checkLengths(document.getElementById('type').value,'');\">" . \PHP_EOL; + while (!$types->EOF) { $typname = $types->fields['typname']; $types_for_js[] = $typname; - echo "\t<option value=\"", htmlspecialchars($typname), '"', ($typname == $_REQUEST['type']) ? ' selected="selected"' : '', '>', - $this->misc->printVal($typname), '</option>'.PHP_EOL; + echo "\t<option value=\"", \htmlspecialchars($typname), '"', ($typname === $_REQUEST['type']) ? ' selected="selected"' : '', '>', + $this->misc->printVal($typname), '</option>' . \PHP_EOL; $types->moveNext(); } - echo '</select>'.PHP_EOL; - echo '</td>'.PHP_EOL; + echo '</select>' . \PHP_EOL; + echo '</td>' . \PHP_EOL; // Output array type selector - echo '<td><select name="array">'.PHP_EOL; - echo "\t<option value=\"\"", ('' == $_REQUEST['array']) ? ' selected="selected"' : '', '></option>'.PHP_EOL; - echo "\t<option value=\"[]\"", ('[]' == $_REQUEST['array']) ? ' selected="selected"' : '', '>[ ]</option>'.PHP_EOL; - echo '</select></td>'.PHP_EOL; - $predefined_size_types = array_intersect($data->predefined_size_types, $types_for_js); + echo '<td><select name="array">' . \PHP_EOL; + echo "\t<option value=\"\"", ('' === $_REQUEST['array']) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; + echo "\t<option value=\"[]\"", ('[]' === $_REQUEST['array']) ? ' selected="selected"' : '', '>[ ]</option>' . \PHP_EOL; + echo '</select></td>' . \PHP_EOL; + $predefined_size_types = \array_intersect($data->predefined_size_types, $types_for_js); + foreach ($predefined_size_types as $value) { $escaped_predef_types[] = "'{$value}'"; } echo '<td><input name="length" id="lengths" size="8" value="', - htmlspecialchars($_REQUEST['length']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_REQUEST['length']), '" /></td>' . \PHP_EOL; } else { // Otherwise draw the read-only type name - echo '<td>', $this->misc->printVal($data->formatType($column->fields['type'], $column->fields['atttypmod'])), '</td>'.PHP_EOL; + echo '<td>', $this->misc->printVal($data->formatType($column->fields['type'], $column->fields['atttypmod'])), '</td>' . \PHP_EOL; } - echo '<td><input type="checkbox" name="notnull"', (isset($_REQUEST['notnull'])) ? ' checked="checked"' : '', ' /></td>'.PHP_EOL; + echo '<td><input type="checkbox" name="notnull"', (isset($_REQUEST['notnull'])) ? ' checked="checked"' : '', ' /></td>' . \PHP_EOL; echo '<td><input name="default" size="20" value="', - htmlspecialchars($_REQUEST['default']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_REQUEST['default']), '" /></td>' . \PHP_EOL; echo '<td><input name="comment" size="40" value="', - htmlspecialchars($_REQUEST['comment']), '" /></td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="properties" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="2" />'.PHP_EOL; + \htmlspecialchars($_REQUEST['comment']), '" /></td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="properties" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="2" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo '<input type="hidden" name="column" value="', htmlspecialchars($_REQUEST['column']), '" />'.PHP_EOL; - echo '<input type="hidden" name="olddefault" value="', htmlspecialchars($_REQUEST['olddefault']), '" />'.PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="column" value="', \htmlspecialchars($_REQUEST['column']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="olddefault" value="', \htmlspecialchars($_REQUEST['olddefault']), '" />' . \PHP_EOL; + if ($column->fields['attnotnull']) { - echo '<input type="hidden" name="oldnotnull" value="on" />'.PHP_EOL; + echo '<input type="hidden" name="oldnotnull" value="on" />' . \PHP_EOL; } - echo '<input type="hidden" name="oldtype" value="', htmlspecialchars($data->formatType($column->fields['type'], $column->fields['atttypmod'])), '" />'.PHP_EOL; + echo '<input type="hidden" name="oldtype" value="', \htmlspecialchars($data->formatType($column->fields['type'], $column->fields['atttypmod'])), '" />' . \PHP_EOL; // Add hidden variables to suppress error notices if we don't support altering column type if (!$data->hasAlterColumnType()) { - echo '<input type="hidden" name="type" value="', htmlspecialchars($_REQUEST['type']), '" />'.PHP_EOL; - echo '<input type="hidden" name="length" value="', htmlspecialchars($_REQUEST['length']), '" />'.PHP_EOL; - echo '<input type="hidden" name="array" value="', htmlspecialchars($_REQUEST['array']), '" />'.PHP_EOL; + echo '<input type="hidden" name="type" value="', \htmlspecialchars($_REQUEST['type']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="length" value="', \htmlspecialchars($_REQUEST['length']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="array" value="', \htmlspecialchars($_REQUEST['array']), '" />' . \PHP_EOL; } - echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; - echo '<script type="text/javascript">predefined_lengths = new Array('.implode(',', $escaped_predef_types).");checkLengths(document.getElementById('type').value,'');</script>".PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; + echo '<script type="text/javascript">predefined_lengths = new Array(' . \implode(',', $escaped_predef_types) . ");checkLengths(document.getElementById('type').value,'');</script>" . \PHP_EOL; break; case 2: // Check inputs - if ('' == trim($_REQUEST['field'])) { + if ('' === \trim($_REQUEST['field'])) { $_REQUEST['stage'] = 1; $this->doAlter($this->lang['strcolneedsname']); @@ -381,22 +389,22 @@ class ColpropertiesController extends BaseController ); //$this->prtrace('status', $status, 'sql', $sql); - if (0 == $status) { - if ($_REQUEST['column'] != $_REQUEST['field']) { + if (0 === $status) { + if ($_REQUEST['column'] !== $_REQUEST['field']) { $_REQUEST['column'] = $_REQUEST['field']; $this->misc->setReloadBrowser(true); } - $this->doDefault($sql."<br/>{$this->lang['strcolumnaltered']}"); + $this->doDefault($sql . "<br/>{$this->lang['strcolumnaltered']}"); } else { $_REQUEST['stage'] = 1; - $this->doAlter($sql."<br/>{$this->lang['strcolumnalteredbad']}"); + $this->doAlter($sql . "<br/>{$this->lang['strcolumnalteredbad']}"); return; } break; default: - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } } } diff --git a/src/controllers/ConstraintsController.php b/src/controllers/ConstraintsController.php index fec5d29e..c7c0a278 100644 --- a/src/controllers/ConstraintsController.php +++ b/src/controllers/ConstraintsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class ConstraintsController extends BaseController { @@ -22,13 +23,13 @@ class ConstraintsController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->/* @scrutinizer ignore-call */doTree(); } $this->printHeader( - $this->lang['strtables'].' - '.$_REQUEST['table'].' - '.$this->lang['strconstraints'], - '<script src="'.\SUBFOLDER.'/assets/js/indexes.js" type="text/javascript"></script>', + $this->lang['strtables'] . ' - ' . $_REQUEST['table'] . ' - ' . $this->lang['strconstraints'], + '<script src="' . self::SUBFOLDER . '/assets/js/indexes.js" type="text/javascript"></script>', true, 'header_select2.twig' ); @@ -44,12 +45,13 @@ class ConstraintsController extends BaseController ]; $onloadInit = false; - if (in_array($this->action, $onloadInitActions, true)) { + + if (\in_array($this->action, $onloadInitActions, true)) { $onloadInit = true; } $this->printBody(true, 'detailbody', $onloadInit); - if (isset($_POST['cancel']) || ($this->action === 'drop' && !isset($_POST['drop']))) { + if (isset($_POST['cancel']) || ('drop' === $this->action && !isset($_POST['drop']))) { $this->action = 'default'; } @@ -112,14 +114,14 @@ class ConstraintsController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); - $cnPre = function (&$rowdata) use ($data) { - if (is_null($rowdata->fields['consrc'])) { - $atts = $data->getAttributeNames($_REQUEST['table'], explode(' ', $rowdata->fields['indkey'])); - $rowdata->fields['+definition'] = ('u' == $rowdata->fields['contype'] ? 'UNIQUE (' : 'PRIMARY KEY (').join(',', $atts).')'; + $cnPre = static function (&$rowdata) use ($data): void { + if (null === $rowdata->fields['consrc']) { + $atts = $data->getAttributeNames($_REQUEST['table'], \explode(' ', $rowdata->fields['indkey'])); + $rowdata->fields['+definition'] = ('u' === $rowdata->fields['contype'] ? 'UNIQUE (' : 'PRIMARY KEY (') . \implode(',', $atts) . ')'; } else { $rowdata->fields['+definition'] = $rowdata->fields['consrc']; } @@ -231,7 +233,7 @@ class ConstraintsController extends BaseController 'content' => $this->lang['straddfk'], ], ]; - $this->printNavLinks($navlinks, 'constraints-constraints', get_defined_vars()); + $this->printNavLinks($navlinks, 'constraints-constraints', \get_defined_vars()); } /** @@ -239,7 +241,7 @@ class ConstraintsController extends BaseController * * @param string $msg The message */ - public function formAddForeignKey($msg = '') + public function formAddForeignKey($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -253,7 +255,7 @@ class ConstraintsController extends BaseController $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10); $selColumns->set_style('width: 15em;'); - if ($attrs->recordCount() > 0) { + if (0 < $attrs->recordCount()) { while (!$attrs->EOF) { $xmloption = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']); $selColumns->add($xmloption); @@ -272,36 +274,38 @@ class ConstraintsController extends BaseController $buttonRemove->set_attribute('onclick', 'buttonPressed(this);'); $buttonRemove->set_attribute('type', 'button'); - echo '<form onsubmit="doSelectAll();" name="formIndex" action="constraints" method="post">'.PHP_EOL; + echo '<form onsubmit="doSelectAll();" name="formIndex" action="constraints" method="post">' . \PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strname']}</th></tr>".PHP_EOL; - echo "<tr><td class=\"data1\" colspan=\"3\"><input type=\"text\" name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" /></td></tr>".PHP_EOL; - echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\"> </th><th class=\"data required\">{$this->lang['strfkcolumnlist']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1">'.$selColumns->fetch().'</td>'.PHP_EOL; - echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch().'</td>'.PHP_EOL; - echo '<td class=data1>'.$selIndex->fetch().'</td></tr>'.PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strname']}</th></tr>" . \PHP_EOL; + echo "<tr><td class=\"data1\" colspan=\"3\"><input type=\"text\" name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" /></td></tr>" . \PHP_EOL; + echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\"> </th><th class=\"data required\">{$this->lang['strfkcolumnlist']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1">' . $selColumns->fetch() . '</td>' . \PHP_EOL; + echo '<td class="data1" style="text-align: center">' . $buttonRemove->fetch() . $buttonAdd->fetch() . '</td>' . \PHP_EOL; + echo '<td class=data1>' . $selIndex->fetch() . '</td></tr>' . \PHP_EOL; echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strfktarget']}</th></tr>"; echo '<tr>'; echo '<td class="data1" colspan="3"><select class="select2" name="target">'; + while (!$tables->EOF) { $key = ['schemaname' => $tables->fields['nspname'], 'tablename' => $tables->fields['relname']]; - $key = serialize($key); - echo '<option value="', htmlspecialchars($key), '">'; - if ($tables->fields['nspname'] != $_REQUEST['schema']) { - echo htmlspecialchars($tables->fields['nspname']), '.'; + $key = \serialize($key); + echo '<option value="', \htmlspecialchars($key), '">'; + + if ($tables->fields['nspname'] !== $_REQUEST['schema']) { + echo \htmlspecialchars($tables->fields['nspname']), '.'; } - echo htmlspecialchars($tables->fields['relname']), '</option>'.PHP_EOL; + echo \htmlspecialchars($tables->fields['relname']), '</option>' . \PHP_EOL; $tables->moveNext(); } - echo '</select>'.PHP_EOL; + echo '</select>' . \PHP_EOL; echo '</td></tr>'; - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; echo $this->getFormInputsAndButtons( [ ['name' => 'action', 'type' => 'hidden', 'value' => 'select_referenced_columns'], - ['name' => 'table', 'type' => 'hidden', 'value' => htmlspecialchars($_REQUEST['table'])], + ['name' => 'table', 'type' => 'hidden', 'value' => \htmlspecialchars($_REQUEST['table'])], ], [ ['type' => 'submit', 'name' => '', 'value' => $this->lang['stradd']], @@ -309,146 +313,7 @@ class ConstraintsController extends BaseController ] ); - echo sprintf('</form>%s', PHP_EOL); - } - - /** - * Prints second screen of FK creation, where you select which columns - * to use in the referencing table. - * - * @param string $msg optional message to display - */ - private function _selectFKColumns($msg = '') - { - $data = $this->misc->getDatabaseAccessor(); - - $this->coalesceArr($_POST, 'name', ''); - - $this->coalesceArr($_POST, 'target', ''); - - // Check that they've given at least one source column - if (!isset($_REQUEST['SourceColumnList']) && (!isset($_POST['IndexColumnList']) || - !is_array($_POST['IndexColumnList']) || - 0 == sizeof($_POST['IndexColumnList']))) { - return $this->formAddForeignKey($this->lang['strfkneedscols']); - } - // Copy the IndexColumnList variable from stage 1 - if (isset($_REQUEST['IndexColumnList']) && !isset($_REQUEST['SourceColumnList'])) { - $_REQUEST['SourceColumnList'] = serialize($_REQUEST['IndexColumnList']); - } - - // Initialise variables - $this->coalesceArr($_POST, 'upd_action', null); - - $this->coalesceArr($_POST, 'del_action', null); - - $this->coalesceArr($_POST, 'match', null); - - $this->coalesceArr($_POST, 'deferrable', null); - - $this->coalesceArr($_POST, 'initially', null); - - $_REQUEST['target'] = unserialize($_REQUEST['target']); - - $this->printTrail('table'); - $this->printTitle($this->lang['straddfk'], 'pg.constraint.foreign_key'); - $this->printMsg($msg); - - // Unserialize target and fetch appropriate table. This is a bit messy - // because the table could be in another schema. - $data->setSchema($_REQUEST['target']['schemaname']); - $attrs = $data->getTableAttributes($_REQUEST['target']['tablename']); - $data->setSchema($_REQUEST['schema']); - - $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10); - $selColumns->set_style('width: 15em;'); - - if ($attrs->recordCount() > 0) { - while (!$attrs->EOF) { - $xmloption = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']); - $selColumns->add($xmloption); - $attrs->moveNext(); - } - } - - $selIndex = new \PHPPgAdmin\XHtml\XHtmlSelect('IndexColumnList[]', true, 10); - $selIndex->set_style('width: 15em;'); - $selIndex->set_attribute('id', 'IndexColumnList'); - $buttonAdd = new \PHPPgAdmin\XHtml\XHtmlButton('add', '>>'); - $buttonAdd->set_attribute('onclick', 'buttonPressed(this);'); - $buttonAdd->set_attribute('type', 'button'); - - $buttonRemove = new \PHPPgAdmin\XHtml\XHtmlButton('remove', '<<'); - $buttonRemove->set_attribute('onclick', 'buttonPressed(this);'); - $buttonRemove->set_attribute('type', 'button'); - - echo '<form onsubmit="doSelectAll();" name="formIndex" action="constraints" method="post">'.PHP_EOL; - - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strfktarget']}</th></tr>"; - echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\"> </th><th class=data>{$this->lang['strfkcolumnlist']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1">'.$selColumns->fetch().'</td>'.PHP_EOL; - echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch().'</td>'; - echo '<td class="data1">'.$selIndex->fetch().'</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['stractions']}</th></tr>"; - echo '<tr>'; - echo '<td class="data1" colspan="3">'.PHP_EOL; - // ON SELECT actions - echo "{$this->lang['stronupdate']} <select name=\"upd_action\">"; - foreach ($data->fkactions as $v) { - echo "<option value=\"{$v}\"", ($_POST['upd_action'] == $v) ? ' selected="selected"' : '', ">{$v}</option>".PHP_EOL; - } - - echo '</select><br />'.PHP_EOL; - - // ON DELETE actions - echo "{$this->lang['strondelete']} <select name=\"del_action\">"; - foreach ($data->fkactions as $v) { - echo "<option value=\"{$v}\"", ($_POST['del_action'] == $v) ? ' selected="selected"' : '', ">{$v}</option>".PHP_EOL; - } - - echo '</select><br />'.PHP_EOL; - - // MATCH options - echo '<select name="match">'; - foreach ($data->fkmatches as $v) { - echo "<option value=\"{$v}\"", ($_POST['match'] == $v) ? ' selected="selected"' : '', ">{$v}</option>".PHP_EOL; - } - - echo '</select><br />'.PHP_EOL; - - // DEFERRABLE options - echo '<select name="deferrable">'; - foreach ($data->fkdeferrable as $v) { - echo "<option value=\"{$v}\"", ($_POST['deferrable'] == $v) ? ' selected="selected"' : '', ">{$v}</option>".PHP_EOL; - } - - echo '</select><br />'.PHP_EOL; - - // INITIALLY options - echo '<select name="initially">'; - foreach ($data->fkinitial as $v) { - echo "<option value=\"{$v}\"", ($_POST['initially'] == $v) ? ' selected="selected"' : '', ">{$v}</option>".PHP_EOL; - } - - echo '</select>'.PHP_EOL; - echo '</td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - - echo '<p>'; - - echo '<input type="hidden" name="name" value="', htmlspecialchars($_REQUEST['name']), '" />'.PHP_EOL; - echo '<input type="hidden" name="target" value="', htmlspecialchars(serialize($_REQUEST['target'])), '" />'.PHP_EOL; - echo '<input type="hidden" name="SourceColumnList" value="', htmlspecialchars($_REQUEST['SourceColumnList']), '" />'.PHP_EOL; - - echo $this->getActionTableAndButtons( - 'save_add_foreign_key', - htmlspecialchars($_REQUEST['table']), - $this->lang['stradd'], - $this->lang['strcancel'] - ); - - echo sprintf('</p>%s</form>%s', PHP_EOL, PHP_EOL); + echo \sprintf('</form>%s', \PHP_EOL); } /** @@ -469,15 +334,15 @@ class ConstraintsController extends BaseController $this->coalesceArr($_POST, 'IndexColumnList', []); // Unserialize target - $_POST['target'] = unserialize($_POST['target']); + $_POST['target'] = \unserialize($_POST['target']); // Check that they've given at least one column - $temp = unserialize($_POST['SourceColumnList']); + $temp = \unserialize($_POST['SourceColumnList']); // If IndexColumnList or SourceColumnList are empty, return to screen to select referencing table columns - if (!is_array($_POST['IndexColumnList']) - || 0 == sizeof($_POST['IndexColumnList']) - || 0 == sizeof($temp)) { + if (!\is_array($_POST['IndexColumnList']) + || 0 === \count($_POST['IndexColumnList']) + || 0 === \count($temp)) { return $this->_selectFKColumns($this->lang['strfkneedscols']); } @@ -485,7 +350,7 @@ class ConstraintsController extends BaseController $_POST['table'], $_POST['target']['schemaname'], $_POST['target']['tablename'], - unserialize($_POST['SourceColumnList']), + \unserialize($_POST['SourceColumnList']), $_POST['IndexColumnList'], $_POST['upd_action'], $_POST['del_action'], @@ -494,7 +359,8 @@ class ConstraintsController extends BaseController $_POST['initially'], $_POST['name'] ); - if (0 == $status) { + + if (0 === $status) { return $this->doDefault($this->lang['strfkadded']); } @@ -507,7 +373,7 @@ class ConstraintsController extends BaseController * @param string $type either primary or unique * @param string $msg optional message */ - public function formPrimaryOrUniqueKey($type, $msg = '') + public function formPrimaryOrUniqueKey($type, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $this->coalesceArr($_POST, 'name', ''); @@ -543,7 +409,7 @@ class ConstraintsController extends BaseController $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10); $selColumns->set_style('width: 15em;'); - if ($attrs->recordCount() > 0) { + if (0 < $attrs->recordCount()) { while (!$attrs->EOF) { $new_option = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']); $selColumns->add($new_option); @@ -562,41 +428,41 @@ class ConstraintsController extends BaseController $buttonRemove->set_attribute('onclick', 'buttonPressed(this);'); $buttonRemove->set_attribute('type', 'button'); - echo '<form onsubmit="doSelectAll();" name="formIndex" action="constraints" method="post">'.PHP_EOL; + echo '<form onsubmit="doSelectAll();" name="formIndex" action="constraints" method="post">' . \PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strname']}</th></tr>"; echo '<tr>'; - echo '<td class="data1" colspan="3"><input type="text" name="name" value="', htmlspecialchars($_POST['name']), + echo '<td class="data1" colspan="3"><input type="text" name="name" value="', \htmlspecialchars($_POST['name']), "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" /></td></tr>"; - echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\"> </th><th class=\"data required\">{$this->lang['strindexcolumnlist']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1">'.$selColumns->fetch().'</td>'.PHP_EOL; - echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch().'</td>'; - echo '<td class=data1>'.$selIndex->fetch().'</td></tr>'.PHP_EOL; + echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\"> </th><th class=\"data required\">{$this->lang['strindexcolumnlist']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1">' . $selColumns->fetch() . '</td>' . \PHP_EOL; + echo '<td class="data1" style="text-align: center">' . $buttonRemove->fetch() . $buttonAdd->fetch() . '</td>'; + echo '<td class=data1>' . $selIndex->fetch() . '</td></tr>' . \PHP_EOL; // Tablespace (if there are any) - if ($data->hasTablespaces() && $tablespaces->recordCount() > 0) { + if ($data->hasTablespaces() && 0 < $tablespaces->recordCount()) { echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strtablespace']}</th></tr>"; - echo '<tr><td class="data1" colspan="3"><select name="tablespace">'.PHP_EOL; + echo '<tr><td class="data1" colspan="3"><select name="tablespace">' . \PHP_EOL; // Always offer the default (empty) option echo "\t\t\t\t<option value=\"\"", - ('' == $_POST['tablespace']) ? ' selected="selected"' : '', '></option>'.PHP_EOL; + ('' === $_POST['tablespace']) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; // Display all other tablespaces while (!$tablespaces->EOF) { - $spcname = htmlspecialchars($tablespaces->fields['spcname']); + $spcname = \htmlspecialchars($tablespaces->fields['spcname']); echo "\t\t\t\t<option value=\"{$spcname}\"", - ($spcname == $_POST['tablespace']) ? ' selected="selected"' : '', ">{$spcname}</option>".PHP_EOL; + ($spcname === $_POST['tablespace']) ? ' selected="selected"' : '', ">{$spcname}</option>" . \PHP_EOL; $tablespaces->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; echo $this->getFormInputsAndButtons( [ - ['name' => 'action', 'type' => 'hidden', 'value' => ($type === 'primary' ? 'save_add_primary_key' : 'save_add_unique_key')], - ['name' => 'table', 'type' => 'hidden', 'value' => htmlspecialchars($_REQUEST['table'])], + ['name' => 'action', 'type' => 'hidden', 'value' => ('primary' === $type ? 'save_add_primary_key' : 'save_add_unique_key')], + ['name' => 'table', 'type' => 'hidden', 'value' => \htmlspecialchars($_REQUEST['table'])], ], [ ['type' => 'submit', 'name' => '', 'value' => $this->lang['stradd']], @@ -604,7 +470,7 @@ class ConstraintsController extends BaseController ] ); - echo sprintf('</form>%s', PHP_EOL); + echo \sprintf('</form>%s', \PHP_EOL); } /** @@ -621,29 +487,31 @@ class ConstraintsController extends BaseController // Default tablespace to empty if it isn't set $this->coalesceArr($_POST, 'tablespace', ''); - if ('primary' == $type) { + if ('primary' === $type) { // Check that they've given at least one column - if (!isset($_POST['IndexColumnList']) || !is_array($_POST['IndexColumnList']) - || 0 == sizeof($_POST['IndexColumnList']) + if (!isset($_POST['IndexColumnList']) || !\is_array($_POST['IndexColumnList']) + || 0 === \count($_POST['IndexColumnList']) ) { $this->formPrimaryOrUniqueKey($type, $this->lang['strpkneedscols']); } else { $status = $data->addPrimaryKey($_POST['table'], $_POST['IndexColumnList'], $_POST['name'], $_POST['tablespace']); - if (0 == $status) { + + if (0 === $status) { return $this->doDefault($this->lang['strpkadded']); } return $this->formPrimaryOrUniqueKey($type, $this->lang['strpkaddedbad']); } - } elseif ('unique' == $type) { + } elseif ('unique' === $type) { // Check that they've given at least one column - if (!isset($_POST['IndexColumnList']) || !is_array($_POST['IndexColumnList']) - || 0 == sizeof($_POST['IndexColumnList']) + if (!isset($_POST['IndexColumnList']) || !\is_array($_POST['IndexColumnList']) + || 0 === \count($_POST['IndexColumnList']) ) { $this->formPrimaryOrUniqueKey($type, $this->lang['struniqneedscols']); } else { $status = $data->addUniqueKey($_POST['table'], $_POST['IndexColumnList'], $_POST['name'], $_POST['tablespace']); - if (0 == $status) { + + if (0 === $status) { return $this->doDefault($this->lang['struniqadded']); } @@ -673,22 +541,22 @@ class ConstraintsController extends BaseController $this->printTitle($this->lang['straddcheck'], 'pg.constraint.check'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/constraints" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data\">{$this->lang['strname']}</th>".PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strdefinition']}</th></tr>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/constraints" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strdefinition']}</th></tr>" . \PHP_EOL; echo "<tr><td class=\"data1\"><input name=\"name\" size=\"24\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_POST['name']), '" /></td>' . \PHP_EOL; echo '<td class="data1">(<input name="definition" size="64" value="', - htmlspecialchars($_POST['definition']), '" />)</td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; + \htmlspecialchars($_POST['definition']), '" />)</td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; echo $this->getFormInputsAndButtons( [ ['name' => 'action', 'type' => 'hidden', 'value' => 'save_add_check'], - ['name' => 'table', 'type' => 'hidden', 'value' => htmlspecialchars($_REQUEST['table'])], + ['name' => 'table', 'type' => 'hidden', 'value' => \htmlspecialchars($_REQUEST['table'])], ], [ ['type' => 'submit', 'name' => '', 'value' => $this->lang['stradd']], @@ -696,9 +564,9 @@ class ConstraintsController extends BaseController ] ); - echo sprintf('</form>%s', PHP_EOL); + echo \sprintf('</form>%s', \PHP_EOL); } else { - if ('' == trim($_POST['definition'])) { + if ('' === \trim($_POST['definition'])) { $this->addCheck(true, $this->lang['strcheckneedsdefinition']); } else { $status = $data->addCheckConstraint( @@ -706,7 +574,8 @@ class ConstraintsController extends BaseController $_POST['definition'], $_POST['name'] ); - if (0 == $status) { + + if (0 === $status) { return $this->doDefault($this->lang['strcheckadded']); } @@ -718,25 +587,25 @@ class ConstraintsController extends BaseController /** * Prints the drop form. */ - public function formDrop() + public function formDrop(): void { $this->printTrail('constraint'); $this->printTitle($this->lang['strdrop'], 'pg.constraint.drop'); - echo '<p>', sprintf( + echo '<p>', \sprintf( $this->lang['strconfdropconstraint'], $this->misc->printVal($_REQUEST['constraint']), $this->misc->printVal($_REQUEST['table']) - ), '</p>'.PHP_EOL; + ), '</p>' . \PHP_EOL; - echo sprintf('<form action="constraints" method="post">%s', PHP_EOL); + echo \sprintf('<form action="constraints" method="post">%s', \PHP_EOL); echo $this->getFormInputsAndButtons( [ ['name' => 'action', 'value' => 'drop', 'type' => 'hidden'], - ['name' => 'table', 'value' => htmlspecialchars($_REQUEST['table']), 'type' => 'hidden'], - ['name' => 'constraint', 'value' => htmlspecialchars($_REQUEST['constraint']), 'type' => 'hidden'], - ['name' => 'type', 'value' => htmlspecialchars($_REQUEST['type']), 'type' => 'hidden'], + ['name' => 'table', 'value' => \htmlspecialchars($_REQUEST['table']), 'type' => 'hidden'], + ['name' => 'constraint', 'value' => \htmlspecialchars($_REQUEST['constraint']), 'type' => 'hidden'], + ['name' => 'type', 'value' => \htmlspecialchars($_REQUEST['type']), 'type' => 'hidden'], ], [ ['type' => 'submit', 'name' => 'drop', 'value' => $this->lang['strdrop']], @@ -747,7 +616,7 @@ class ConstraintsController extends BaseController ] ); - echo sprintf('</form>%s', PHP_EOL); + echo \sprintf('</form>%s', \PHP_EOL); } /** @@ -758,10 +627,155 @@ class ConstraintsController extends BaseController $data = $this->misc->getDatabaseAccessor(); $status = $data->dropConstraint($_POST['constraint'], $_POST['table'], $_POST['type'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { return $this->doDefault($this->lang['strconstraintdropped']); } return $this->doDefault($this->lang['strconstraintdroppedbad']); } + + /** + * Prints second screen of FK creation, where you select which columns + * to use in the referencing table. + * + * @param string $msg optional message to display + */ + private function _selectFKColumns($msg = '') + { + $data = $this->misc->getDatabaseAccessor(); + + $this->coalesceArr($_POST, 'name', ''); + + $this->coalesceArr($_POST, 'target', ''); + + // Check that they've given at least one source column + if (!isset($_REQUEST['SourceColumnList']) && (!isset($_POST['IndexColumnList']) || + !\is_array($_POST['IndexColumnList']) || + 0 === \count($_POST['IndexColumnList']))) { + return $this->formAddForeignKey($this->lang['strfkneedscols']); + } + // Copy the IndexColumnList variable from stage 1 + if (isset($_REQUEST['IndexColumnList']) && !isset($_REQUEST['SourceColumnList'])) { + $_REQUEST['SourceColumnList'] = \serialize($_REQUEST['IndexColumnList']); + } + + // Initialise variables + $this->coalesceArr($_POST, 'upd_action', null); + + $this->coalesceArr($_POST, 'del_action', null); + + $this->coalesceArr($_POST, 'match', null); + + $this->coalesceArr($_POST, 'deferrable', null); + + $this->coalesceArr($_POST, 'initially', null); + + $_REQUEST['target'] = \unserialize($_REQUEST['target']); + + $this->printTrail('table'); + $this->printTitle($this->lang['straddfk'], 'pg.constraint.foreign_key'); + $this->printMsg($msg); + + // Unserialize target and fetch appropriate table. This is a bit messy + // because the table could be in another schema. + $data->setSchema($_REQUEST['target']['schemaname']); + $attrs = $data->getTableAttributes($_REQUEST['target']['tablename']); + $data->setSchema($_REQUEST['schema']); + + $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10); + $selColumns->set_style('width: 15em;'); + + if (0 < $attrs->recordCount()) { + while (!$attrs->EOF) { + $xmloption = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']); + $selColumns->add($xmloption); + $attrs->moveNext(); + } + } + + $selIndex = new \PHPPgAdmin\XHtml\XHtmlSelect('IndexColumnList[]', true, 10); + $selIndex->set_style('width: 15em;'); + $selIndex->set_attribute('id', 'IndexColumnList'); + $buttonAdd = new \PHPPgAdmin\XHtml\XHtmlButton('add', '>>'); + $buttonAdd->set_attribute('onclick', 'buttonPressed(this);'); + $buttonAdd->set_attribute('type', 'button'); + + $buttonRemove = new \PHPPgAdmin\XHtml\XHtmlButton('remove', '<<'); + $buttonRemove->set_attribute('onclick', 'buttonPressed(this);'); + $buttonRemove->set_attribute('type', 'button'); + + echo '<form onsubmit="doSelectAll();" name="formIndex" action="constraints" method="post">' . \PHP_EOL; + + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strfktarget']}</th></tr>"; + echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\"> </th><th class=data>{$this->lang['strfkcolumnlist']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1">' . $selColumns->fetch() . '</td>' . \PHP_EOL; + echo '<td class="data1" style="text-align: center">' . $buttonRemove->fetch() . $buttonAdd->fetch() . '</td>'; + echo '<td class="data1">' . $selIndex->fetch() . '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['stractions']}</th></tr>"; + echo '<tr>'; + echo '<td class="data1" colspan="3">' . \PHP_EOL; + // ON SELECT actions + echo "{$this->lang['stronupdate']} <select name=\"upd_action\">"; + + foreach ($data->fkactions as $v) { + echo "<option value=\"{$v}\"", ($_POST['upd_action'] === $v) ? ' selected="selected"' : '', ">{$v}</option>" . \PHP_EOL; + } + + echo '</select><br />' . \PHP_EOL; + + // ON DELETE actions + echo "{$this->lang['strondelete']} <select name=\"del_action\">"; + + foreach ($data->fkactions as $v) { + echo "<option value=\"{$v}\"", ($_POST['del_action'] === $v) ? ' selected="selected"' : '', ">{$v}</option>" . \PHP_EOL; + } + + echo '</select><br />' . \PHP_EOL; + + // MATCH options + echo '<select name="match">'; + + foreach ($data->fkmatches as $v) { + echo "<option value=\"{$v}\"", ($_POST['match'] === $v) ? ' selected="selected"' : '', ">{$v}</option>" . \PHP_EOL; + } + + echo '</select><br />' . \PHP_EOL; + + // DEFERRABLE options + echo '<select name="deferrable">'; + + foreach ($data->fkdeferrable as $v) { + echo "<option value=\"{$v}\"", ($_POST['deferrable'] === $v) ? ' selected="selected"' : '', ">{$v}</option>" . \PHP_EOL; + } + + echo '</select><br />' . \PHP_EOL; + + // INITIALLY options + echo '<select name="initially">'; + + foreach ($data->fkinitial as $v) { + echo "<option value=\"{$v}\"", ($_POST['initially'] === $v) ? ' selected="selected"' : '', ">{$v}</option>" . \PHP_EOL; + } + + echo '</select>' . \PHP_EOL; + echo '</td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + + echo '<p>'; + + echo '<input type="hidden" name="name" value="', \htmlspecialchars($_REQUEST['name']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="target" value="', \htmlspecialchars(\serialize($_REQUEST['target'])), '" />' . \PHP_EOL; + echo '<input type="hidden" name="SourceColumnList" value="', \htmlspecialchars($_REQUEST['SourceColumnList']), '" />' . \PHP_EOL; + + echo $this->getActionTableAndButtons( + 'save_add_foreign_key', + \htmlspecialchars($_REQUEST['table']), + $this->lang['stradd'], + $this->lang['strcancel'] + ); + + echo \sprintf('</p>%s</form>%s', \PHP_EOL, \PHP_EOL); + } } diff --git a/src/controllers/ConversionsController.php b/src/controllers/ConversionsController.php index aaaa5ecf..52dfddef 100644 --- a/src/controllers/ConversionsController.php +++ b/src/controllers/ConversionsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class ConversionsController extends BaseController { @@ -22,7 +23,7 @@ class ConversionsController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -91,7 +92,7 @@ class ConversionsController extends BaseController $constraints = $data->getConstraints($_REQUEST['table']); - $getIcon = function ($f) { + $getIcon = static function ($f) { switch ($f['contype']) { case 'u': return 'UniqueConstraint'; diff --git a/src/controllers/DatabaseController.php b/src/controllers/DatabaseController.php index ed71f119..43988e0d 100644 --- a/src/controllers/DatabaseController.php +++ b/src/controllers/DatabaseController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,63 +13,60 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class DatabaseController extends BaseController { use \PHPPgAdmin\Traits\AdminTrait; use \PHPPgAdmin\Traits\ExportTrait; + public $table_place = 'database-variables'; + public $fields; - public $controller_title = 'strdatabase'; - private function _highlight($string, $term) - { - return str_replace($term, "<b>{$term}</b>", $string); - } + public $controller_title = 'strdatabase'; /** * Default method to render the controller according to the action parameter. */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } - if ('refresh_locks' == $this->action) { + if ('refresh_locks' === $this->action) { return $this->currentLocks(true); } - if ('refresh_processes' == $this->action) { + if ('refresh_processes' === $this->action) { return $this->currentProcesses(true); } $scripts = ''; // normal flow - if ('locks' == $this->action || 'processes' == $this->action) { - $scripts .= '<script src="'.\SUBFOLDER.'/assets/js/database.js" type="text/javascript"></script>'; + if ('locks' === $this->action || 'processes' === $this->action) { + $scripts .= '<script src="' . self::SUBFOLDER . '/assets/js/database.js" type="text/javascript"></script>'; $refreshTime = $this->conf['ajax_refresh'] * 1500; - $scripts .= '<script type="text/javascript">'.PHP_EOL; + $scripts .= '<script type="text/javascript">' . \PHP_EOL; $scripts .= "var Database = {\n"; $scripts .= "ajax_time_refresh: {$refreshTime},\n"; - $scripts .= "str_start: {text:'{$this->lang['strstart']}',icon: '".$this->misc->icon('Execute')."'},\n"; - $scripts .= "str_stop: {text:'{$this->lang['strstop']}',icon: '".$this->misc->icon('Stop')."'},\n"; - $scripts .= "load_icon: '".$this->misc->icon('Loading')."',\n"; + $scripts .= "str_start: {text:'{$this->lang['strstart']}',icon: '" . $this->misc->icon('Execute') . "'},\n"; + $scripts .= "str_stop: {text:'{$this->lang['strstop']}',icon: '" . $this->misc->icon('Stop') . "'},\n"; + $scripts .= "load_icon: '" . $this->misc->icon('Loading') . "',\n"; $scripts .= "server:'{$_REQUEST['server']}',\n"; $scripts .= "dbname:'{$_REQUEST['database']}',\n"; $scripts .= "action:'refresh_{$this->action}',\n"; - $scripts .= "errmsg: '".str_replace("'", "\\'", $this->lang['strconnectionfail'])."'\n"; + $scripts .= "errmsg: '" . \str_replace("'", "\\'", $this->lang['strconnectionfail']) . "'\n"; $scripts .= "};\n"; - $scripts .= '</script>'.PHP_EOL; + $scripts .= '</script>' . \PHP_EOL; } $header_template = 'header.twig'; $footer_template = 'footer.twig'; // @todo convert all these methods to return text instead of print text - ob_start(); + \ob_start(); + switch ($this->action) { case 'find': if (isset($_REQUEST['term'])) { @@ -111,7 +111,7 @@ class DatabaseController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $this->printHeader($this->headerTitle(), $scripts, true, $header_template); $this->printBody(); @@ -155,12 +155,13 @@ class DatabaseController extends BaseController /** * Sends a signal to a process. */ - public function doSignal() + public function doSignal(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->sendSignal($_REQUEST['pid'], $_REQUEST['signal']); - if (0 == $status) { + + if (0 === $status) { $this->doProcesses($this->lang['strsignalsent']); } else { $this->doProcesses($this->lang['strsignalsentbad']); @@ -185,11 +186,11 @@ class DatabaseController extends BaseController $this->printTabs('database', 'find'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/database" method="post">'.PHP_EOL; - echo '<p><input name="term" value="', htmlspecialchars($_REQUEST['term']), - "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" />".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/database" method="post">' . \PHP_EOL; + echo '<p><input name="term" value="', \htmlspecialchars($_REQUEST['term']), + "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" />" . \PHP_EOL; // Output list of filters. This is complex due to all the 'has' and 'conf' feature possibilities - echo '<select name="filter">'.PHP_EOL; + echo '<select name="filter">' . \PHP_EOL; echo $this->_printTypeOption(''); echo $this->_printTypeOption('COLUMN'); @@ -213,276 +214,63 @@ class DatabaseController extends BaseController echo $this->_printTypeOption('LANGUAGE'); } - echo '</select>'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['strfind']}\" />".PHP_EOL; + echo '</select>' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strfind']}\" />" . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="action" value="find" /></p>'.PHP_EOL; - echo '<input type="hidden" name="confirm" value="true" /></p>'.PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="action" value="find" /></p>' . \PHP_EOL; + echo '<input type="hidden" name="confirm" value="true" /></p>' . \PHP_EOL; + echo '</form>' . \PHP_EOL; // Default focus $this->setFocus('forms[0].term'); // If a search term has been specified, then perform the search // and display the results, grouped by object type - if (!$confirm && '' != $_REQUEST['term']) { + if (!$confirm && '' !== $_REQUEST['term']) { return $this->doFind(); } } - private function _printTypeOption($curr) - { - $filter = $_REQUEST['filter']; - $optionhtml = sprintf('%s<option value="%s" %s>', "\t", $curr, ($curr === $filter) ? ' selected="selected"' : ''); - $optionhtml .= $this->_translatedType($curr); - $optionhtml .= '</option>'.PHP_EOL; - - return $optionhtml; - } - - private function _translatedType($curr) - { - $types = [ - 'COLUMN' => $this->lang['strcolumns'], - 'CONSTRAINT' => $this->lang['strconstraints'], - 'COLUMNTABLE' => $this->lang['strcolumns'], - 'COLUMNVIEW' => $this->lang['strcolumns'], - 'CONSTRAINTDOMAIN' => $this->lang['strconstraints'], - 'CONSTRAINTTABLE' => $this->lang['strconstraints'], - 'DOMAIN' => $this->lang['strdomains'], - 'FUNCTION' => $this->lang['strfunctions'], - 'INDEX' => $this->lang['strindexes'], - 'RULE' => $this->lang['strrules'], - 'RULETABLE' => $this->lang['strrules'], - 'RULEVIEW' => $this->lang['strrules'], - 'SCHEMA' => $this->lang['strschemas'], - 'SEQUENCE' => $this->lang['strsequences'], - 'TABLE' => $this->lang['strtables'], - 'TRIGGER' => $this->lang['strtriggers'], - 'VIEW' => $this->lang['strviews'], - - 'AGGREGATE' => $this->lang['straggregates'], - 'CONVERSION' => $this->lang['strconversions'], - 'LANGUAGE' => $this->lang['strlanguages'], - 'OPCLASS' => $this->lang['stropclasses'], - 'OPERATOR' => $this->lang['stroperators'], - 'TYPE' => $this->lang['strtypes'], - ]; - if (array_key_exists($curr, $types)) { - return $types[$curr]; - } - - return $this->lang['strallobjects']; - } - - private function _printHtmlForType($curr, $rs) - { - $destination = null; - switch ($curr) { - case 'SCHEMA': - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<li><a href="'.\SUBFOLDER."{$destination}"; - echo $this->misc->printVal($rs->fields['name']), '">'; - echo $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']); - echo '</a></li>'.PHP_EOL; - - break; - case 'TABLE': - echo '<li>'; - echo "<a href=\"tables?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - $destination = $this->container->utils->getDestinationWithLastTab('table'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&table=', - urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'VIEW': - echo '<li>'; - echo "<a href=\"views?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - $destination = $this->container->utils->getDestinationWithLastTab('view'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&view=', - urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'SEQUENCE': - echo '<li>'; - echo "<a href=\"sequences?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"sequences?subject=sequence&action=properties&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), - '&sequence=', urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'COLUMNTABLE': - echo '<li>'; - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"tblproperties?subject=table&{$this->misc->href}&table=", urlencode($rs->fields['relname']), '&schema=', urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; - echo "<a href=\"colproperties?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&table=', - urlencode($rs->fields['relname']), '&column=', urlencode($rs->fields['name']), '">', - $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'COLUMNVIEW': - echo '<li>'; - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"viewproperties?subject=view&{$this->misc->href}&view=", urlencode($rs->fields['relname']), '&schema=', urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; - echo "<a href=\"colproperties?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&view=', - urlencode($rs->fields['relname']), '&column=', urlencode($rs->fields['name']), '">', - $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'INDEX': - echo '<li>'; - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - $destination = $this->container->utils->getDestinationWithLastTab('table'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&table=", urlencode($rs->fields['relname']), '&schema=', urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; - echo "<a href=\"indexes?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&table=', urlencode($rs->fields['relname']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'CONSTRAINTTABLE': - echo '<li>'; - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - $destination = $this->container->utils->getDestinationWithLastTab('table'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&table=", urlencode($rs->fields['relname']), '&schema=', urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; - echo "<a href=\"constraints?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&table=', - urlencode($rs->fields['relname']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'CONSTRAINTDOMAIN': - echo '<li>'; - echo "<a href=\"domains?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"domains?action=properties&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&domain=', urlencode($rs->fields['relname']), '">', - $this->misc->printVal($rs->fields['relname']), '.', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'TRIGGER': - echo '<li>'; - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - $destination = $this->container->utils->getDestinationWithLastTab('table'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&table=", urlencode($rs->fields['relname']), '&schema=', urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; - echo "<a href=\"triggers?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&table=', urlencode($rs->fields['relname']), '">', - $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'RULETABLE': - echo '<li>'; - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - $destination = $this->container->utils->getDestinationWithLastTab('table'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&table=", urlencode($rs->fields['relname']), '&schema=', urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; - echo "<a href=\"rules?subject=table&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&reltype=table&table=', - urlencode($rs->fields['relname']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'RULEVIEW': - echo '<li>'; - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - $destination = $this->container->utils->getDestinationWithLastTab('view'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&view=", urlencode($rs->fields['relname']), '&schema=', urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; - echo "<a href=\"rules?subject=view&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&reltype=view&view=', - urlencode($rs->fields['relname']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'FUNCTION': - echo '<li>'; - echo "<a href=\"functions?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"functions?action=properties&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&function=', - urlencode($rs->fields['name']), '&function_oid=', urlencode($rs->fields['oid']), '">', - $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'TYPE': - echo '<li>'; - echo "<a href=\"types?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"types?action=properties&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&type=', - urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'DOMAIN': - echo '<li>'; - echo "<a href=\"domains?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"domains?action=properties&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&domain=', - urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'OPERATOR': - echo '<li>'; - echo "<a href=\"operators?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"operators?action=properties&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '&operator=', - urlencode($rs->fields['name']), '&operator_oid=', urlencode($rs->fields['oid']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'CONVERSION': - echo '<li>'; - echo "<a href=\"conversions?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"conversions?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), - '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'LANGUAGE': - echo "<li><a href=\"languages?{$this->misc->href}\">", $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'AGGREGATE': - echo '<li>'; - echo "<a href=\"aggregates?subject=schema&{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"aggregates?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', - $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - case 'OPCLASS': - echo '<li>'; - $destination = $this->container->utils->getDestinationWithLastTab('schema'); - echo '<a href="'.\SUBFOLDER."{$destination}?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; - echo "<a href=\"opclasses?{$this->misc->href}&schema=", urlencode($rs->fields['schemaname']), '">', - $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>'.PHP_EOL; - - break; - } - //$this->dump(['curr' => $curr, 'destination' => $destination]); - } - - public function doFind() + public function doFind(): void { $data = $this->misc->getDatabaseAccessor(); $rs = $data->findObject($_REQUEST['term'], $_REQUEST['filter']); - if ($rs->recordCount() > 0) { + + if (0 < $rs->recordCount()) { $curr = ''; + while (!$rs->EOF) { // Output a new header if the current type has changed, but not if it's just changed the rule type - if ($rs->fields['type'] != $curr) { + if ($rs->fields['type'] !== $curr) { // Short-circuit in the case of changing from table rules to view rules; table cols to view cols; // table constraints to domain constraints - if ('RULEVIEW' == $rs->fields['type'] && 'RULETABLE' == $curr) { + if ('RULEVIEW' === $rs->fields['type'] && 'RULETABLE' === $curr) { $curr = $rs->fields['type']; - } elseif ('COLUMNVIEW' == $rs->fields['type'] && 'COLUMNTABLE' == $curr) { + } elseif ('COLUMNVIEW' === $rs->fields['type'] && 'COLUMNTABLE' === $curr) { $curr = $rs->fields['type']; - } elseif ('CONSTRAINTTABLE' == $rs->fields['type'] && 'CONSTRAINTDOMAIN' == $curr) { + } elseif ('CONSTRAINTTABLE' === $rs->fields['type'] && 'CONSTRAINTDOMAIN' === $curr) { $curr = $rs->fields['type']; } else { - if ('' != $curr) { - echo '</ul>'.PHP_EOL; + if ('' !== $curr) { + echo '</ul>' . \PHP_EOL; } $curr = $rs->fields['type']; echo '<h3>'; echo $this->_translatedType($curr); echo '</h3>'; - echo '<ul>'.PHP_EOL; + echo '<ul>' . \PHP_EOL; } } $this->_printHtmlForType($curr, $rs); $rs->moveNext(); } - echo '</ul>'.PHP_EOL; + echo '</ul>' . \PHP_EOL; - echo '<p>', $rs->recordCount(), ' ', $this->lang['strobjects'], '</p>'.PHP_EOL; + echo '<p>', $rs->recordCount(), ' ', $this->lang['strobjects'], '</p>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnoobjects']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnoobjects']}</p>" . \PHP_EOL; } } @@ -491,7 +279,7 @@ class DatabaseController extends BaseController * * @param mixed $msg */ - public function doExport($msg = '') + public function doExport($msg = ''): void { $this->printTrail('database'); $this->printTabs('database', 'export'); @@ -511,7 +299,7 @@ class DatabaseController extends BaseController // $server_info = $this->misc->getServerInfo(); // echo $this->offerNoRoleExport(isset($server_info['pgVersion']) && floatval(substr($server_info['pgVersion'], 0, 3)) >= 10); - echo $this->displayOrDownload(!(strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS']))); + echo $this->displayOrDownload(!(\mb_strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS']))); echo $this->formFooter($subject, $object); } @@ -519,7 +307,7 @@ class DatabaseController extends BaseController /** * Show the current status of all database variables. */ - public function doVariables() + public function doVariables(): void { $data = $this->misc->getDatabaseAccessor(); @@ -550,14 +338,14 @@ class DatabaseController extends BaseController * * @param mixed $msg */ - public function doProcesses($msg = '') + public function doProcesses($msg = ''): void { $this->printTrail('database'); $this->printTabs('database', 'processes'); $this->printMsg($msg); - if (0 === strlen($msg)) { - echo '<br /><a id="control" href=""><img src="'.$this->misc->icon('Refresh')."\" alt=\"{$this->lang['strrefresh']}\" title=\"{$this->lang['strrefresh']}\"/> {$this->lang['strrefresh']}</a>"; + if (0 === \mb_strlen($msg)) { + echo '<br /><a id="control" href=""><img src="' . $this->misc->icon('Refresh') . "\" alt=\"{$this->lang['strrefresh']}\" title=\"{$this->lang['strrefresh']}\"/> {$this->lang['strrefresh']}</a>"; } echo '<div id="data_block">'; @@ -565,13 +353,13 @@ class DatabaseController extends BaseController echo '</div>'; } - public function currentProcesses($isAjax = false) + public function currentProcesses($isAjax = false): void { $data = $this->misc->getDatabaseAccessor(); // Display prepared transactions if ($data->hasPreparedXacts()) { - echo "<h3>{$this->lang['strpreparedxacts']}</h3>".PHP_EOL; + echo "<h3>{$this->lang['strpreparedxacts']}</h3>" . \PHP_EOL; $prep_xacts = $data->getPreparedXacts($_REQUEST['database']); $columns = [ @@ -599,7 +387,7 @@ class DatabaseController extends BaseController } // Fetch the processes from the database - echo "<h3>{$this->lang['strprocesses']}</h3>".PHP_EOL; + echo "<h3>{$this->lang['strprocesses']}</h3>" . \PHP_EOL; $processes = $data->getProcesses($_REQUEST['database']); $columns = [ @@ -637,6 +425,7 @@ class DatabaseController extends BaseController $columns['actions'] = ['title' => $this->lang['stractions']]; $actions = []; + if ($data->hasUserSignals() || $data->isSuperUser()) { $actions = [ 'cancel' => [ @@ -677,14 +466,14 @@ class DatabaseController extends BaseController } } - if (0 == count($actions)) { + if (0 === \count($actions)) { unset($columns['actions']); } echo $this->printTable($processes, $columns, $actions, 'database-processes', $this->lang['strnodata']); } - public function currentLocks($isAjax = false) + public function currentLocks($isAjax = false): void { $data = $this->misc->getDatabaseAccessor(); @@ -734,12 +523,12 @@ class DatabaseController extends BaseController /** * Show the existing table locks in the current database. */ - public function doLocks() + public function doLocks(): void { $this->printTrail('database'); $this->printTabs('database', 'locks'); - echo '<br /><a id="control" href=""><img src="'.$this->misc->icon('Refresh')."\" alt=\"{$this->lang['strrefresh']}\" title=\"{$this->lang['strrefresh']}\"/> {$this->lang['strrefresh']}</a>"; + echo '<br /><a id="control" href=""><img src="' . $this->misc->icon('Refresh') . "\" alt=\"{$this->lang['strrefresh']}\" title=\"{$this->lang['strrefresh']}\"/> {$this->lang['strrefresh']}</a>"; echo '<div id="data_block">'; $this->currentLocks(); @@ -749,7 +538,7 @@ class DatabaseController extends BaseController /** * Allow execution of arbitrary SQL statements on a database. */ - public function doSQL() + public function doSQL(): void { if ((!isset($_SESSION['sqlquery'])) || isset($_REQUEST['new'])) { $_SESSION['sqlquery'] = ''; @@ -758,27 +547,28 @@ class DatabaseController extends BaseController $this->printTrail('database'); $this->printTabs('database', 'sql'); - echo "<p>{$this->lang['strentersql']}</p>".PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/sql" method="post" enctype="multipart/form-data" id="sqlform">'.PHP_EOL; - echo "<p>{$this->lang['strsql']}<br />".PHP_EOL; + echo "<p>{$this->lang['strentersql']}</p>" . \PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/sql" method="post" enctype="multipart/form-data" id="sqlform">' . \PHP_EOL; + echo "<p>{$this->lang['strsql']}<br />" . \PHP_EOL; echo '<textarea style="width:95%;" rows="15" cols="50" name="query" id="query">', - htmlspecialchars($_SESSION['sqlquery']), '</textarea></p>'.PHP_EOL; + \htmlspecialchars($_SESSION['sqlquery']), '</textarea></p>' . \PHP_EOL; // Check that file uploads are enabled - if (ini_get('file_uploads')) { + if (\ini_get('file_uploads')) { // Don't show upload option if max size of uploads is zero - $max_size = $this->misc->inisizeToBytes(ini_get('upload_max_filesize')); - if (is_double($max_size) && $max_size > 0) { - echo "<p><input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"{$max_size}\" />".PHP_EOL; - echo "<label for=\"script\">{$this->lang['struploadscript']}</label> <input id=\"script\" name=\"script\" type=\"file\" /></p>".PHP_EOL; + $max_size = $this->misc->inisizeToBytes(\ini_get('upload_max_filesize')); + + if (\is_float($max_size) && 0 < $max_size) { + echo "<p><input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"{$max_size}\" />" . \PHP_EOL; + echo "<label for=\"script\">{$this->lang['struploadscript']}</label> <input id=\"script\" name=\"script\" type=\"file\" /></p>" . \PHP_EOL; } } - echo '<p><input type="checkbox" id="paginate" name="paginate"', (isset($_REQUEST['paginate']) ? ' checked="checked"' : ''), " /><label for=\"paginate\">{$this->lang['strpaginate']}</label></p>".PHP_EOL; - echo "<p><input type=\"submit\" name=\"execute\" accesskey=\"r\" value=\"{$this->lang['strexecute']}\" />".PHP_EOL; + echo '<p><input type="checkbox" id="paginate" name="paginate"', (isset($_REQUEST['paginate']) ? ' checked="checked"' : ''), " /><label for=\"paginate\">{$this->lang['strpaginate']}</label></p>" . \PHP_EOL; + echo "<p><input type=\"submit\" name=\"execute\" accesskey=\"r\" value=\"{$this->lang['strexecute']}\" />" . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"reset\" accesskey=\"q\" value=\"{$this->lang['strreset']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"reset\" accesskey=\"q\" value=\"{$this->lang['strreset']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; // Default focus $this->setFocus('forms[0].query'); @@ -796,4 +586,226 @@ class DatabaseController extends BaseController { return $msg; } + + private function _highlight($string, $term) + { + return \str_replace($term, "<b>{$term}</b>", $string); + } + + private function _printTypeOption($curr) + { + $filter = $_REQUEST['filter']; + $optionhtml = \sprintf('%s<option value="%s" %s>', "\t", $curr, ($curr === $filter) ? ' selected="selected"' : ''); + $optionhtml .= $this->_translatedType($curr); + $optionhtml .= '</option>' . \PHP_EOL; + + return $optionhtml; + } + + private function _translatedType($curr) + { + $types = [ + 'COLUMN' => $this->lang['strcolumns'], + 'CONSTRAINT' => $this->lang['strconstraints'], + 'COLUMNTABLE' => $this->lang['strcolumns'], + 'COLUMNVIEW' => $this->lang['strcolumns'], + 'CONSTRAINTDOMAIN' => $this->lang['strconstraints'], + 'CONSTRAINTTABLE' => $this->lang['strconstraints'], + 'DOMAIN' => $this->lang['strdomains'], + 'FUNCTION' => $this->lang['strfunctions'], + 'INDEX' => $this->lang['strindexes'], + 'RULE' => $this->lang['strrules'], + 'RULETABLE' => $this->lang['strrules'], + 'RULEVIEW' => $this->lang['strrules'], + 'SCHEMA' => $this->lang['strschemas'], + 'SEQUENCE' => $this->lang['strsequences'], + 'TABLE' => $this->lang['strtables'], + 'TRIGGER' => $this->lang['strtriggers'], + 'VIEW' => $this->lang['strviews'], + + 'AGGREGATE' => $this->lang['straggregates'], + 'CONVERSION' => $this->lang['strconversions'], + 'LANGUAGE' => $this->lang['strlanguages'], + 'OPCLASS' => $this->lang['stropclasses'], + 'OPERATOR' => $this->lang['stroperators'], + 'TYPE' => $this->lang['strtypes'], + ]; + + if (\array_key_exists($curr, $types)) { + return $types[$curr]; + } + + return $this->lang['strallobjects']; + } + + private function _printHtmlForType($curr, $rs): void + { + $destination = null; + + switch ($curr) { + case 'SCHEMA': + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<li><a href="' . self::SUBFOLDER . "{$destination}"; + echo $this->misc->printVal($rs->fields['name']), '">'; + echo $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']); + echo '</a></li>' . \PHP_EOL; + + break; + case 'TABLE': + echo '<li>'; + echo "<a href=\"tables?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + $destination = $this->container->utils->getDestinationWithLastTab('table'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&table=', + \urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'VIEW': + echo '<li>'; + echo "<a href=\"views?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + $destination = $this->container->utils->getDestinationWithLastTab('view'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&view=', + \urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'SEQUENCE': + echo '<li>'; + echo "<a href=\"sequences?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"sequences?subject=sequence&action=properties&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), + '&sequence=', \urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'COLUMNTABLE': + echo '<li>'; + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"tblproperties?subject=table&{$this->misc->href}&table=", \urlencode($rs->fields['relname']), '&schema=', \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; + echo "<a href=\"colproperties?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&table=', + \urlencode($rs->fields['relname']), '&column=', \urlencode($rs->fields['name']), '">', + $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'COLUMNVIEW': + echo '<li>'; + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"viewproperties?subject=view&{$this->misc->href}&view=", \urlencode($rs->fields['relname']), '&schema=', \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; + echo "<a href=\"colproperties?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&view=', + \urlencode($rs->fields['relname']), '&column=', \urlencode($rs->fields['name']), '">', + $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'INDEX': + echo '<li>'; + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + $destination = $this->container->utils->getDestinationWithLastTab('table'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&table=", \urlencode($rs->fields['relname']), '&schema=', \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; + echo "<a href=\"indexes?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&table=', \urlencode($rs->fields['relname']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'CONSTRAINTTABLE': + echo '<li>'; + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + $destination = $this->container->utils->getDestinationWithLastTab('table'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&table=", \urlencode($rs->fields['relname']), '&schema=', \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; + echo "<a href=\"constraints?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&table=', + \urlencode($rs->fields['relname']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'CONSTRAINTDOMAIN': + echo '<li>'; + echo "<a href=\"domains?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"domains?action=properties&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&domain=', \urlencode($rs->fields['relname']), '">', + $this->misc->printVal($rs->fields['relname']), '.', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'TRIGGER': + echo '<li>'; + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + $destination = $this->container->utils->getDestinationWithLastTab('table'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&table=", \urlencode($rs->fields['relname']), '&schema=', \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; + echo "<a href=\"triggers?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&table=', \urlencode($rs->fields['relname']), '">', + $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'RULETABLE': + echo '<li>'; + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + $destination = $this->container->utils->getDestinationWithLastTab('table'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&table=", \urlencode($rs->fields['relname']), '&schema=', \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; + echo "<a href=\"rules?subject=table&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&reltype=table&table=', + \urlencode($rs->fields['relname']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'RULEVIEW': + echo '<li>'; + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + $destination = $this->container->utils->getDestinationWithLastTab('view'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&view=", \urlencode($rs->fields['relname']), '&schema=', \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['relname']), '</a>.'; + echo "<a href=\"rules?subject=view&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&reltype=view&view=', + \urlencode($rs->fields['relname']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'FUNCTION': + echo '<li>'; + echo "<a href=\"functions?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"functions?action=properties&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&function=', + \urlencode($rs->fields['name']), '&function_oid=', \urlencode($rs->fields['oid']), '">', + $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'TYPE': + echo '<li>'; + echo "<a href=\"types?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"types?action=properties&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&type=', + \urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'DOMAIN': + echo '<li>'; + echo "<a href=\"domains?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"domains?action=properties&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&domain=', + \urlencode($rs->fields['name']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'OPERATOR': + echo '<li>'; + echo "<a href=\"operators?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"operators?action=properties&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '&operator=', + \urlencode($rs->fields['name']), '&operator_oid=', \urlencode($rs->fields['oid']), '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'CONVERSION': + echo '<li>'; + echo "<a href=\"conversions?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"conversions?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), + '">', $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'LANGUAGE': + echo "<li><a href=\"languages?{$this->misc->href}\">", $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'AGGREGATE': + echo '<li>'; + echo "<a href=\"aggregates?subject=schema&{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"aggregates?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', + $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + case 'OPCLASS': + echo '<li>'; + $destination = $this->container->utils->getDestinationWithLastTab('schema'); + echo '<a href="' . self::SUBFOLDER . "{$destination}?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', $this->misc->printVal($rs->fields['schemaname']), '</a>.'; + echo "<a href=\"opclasses?{$this->misc->href}&schema=", \urlencode($rs->fields['schemaname']), '">', + $this->_highlight($this->misc->printVal($rs->fields['name']), $_REQUEST['term']), '</a></li>' . \PHP_EOL; + + break; + } + //$this->dump(['curr' => $curr, 'destination' => $destination]); + } } diff --git a/src/controllers/DataexportController.php b/src/controllers/DataexportController.php index 97d290b1..f91593b8 100644 --- a/src/controllers/DataexportController.php +++ b/src/controllers/DataexportController.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class DataexportController extends BaseController { @@ -21,6 +22,7 @@ class DataexportController extends BaseController 'html' => 'html', 'xml' => 'xml', ]; + public $controller_title = 'strexport'; /** @@ -28,7 +30,7 @@ class DataexportController extends BaseController */ public function render() { - set_time_limit(0); + \set_time_limit(0); // if (!isset($_REQUEST['table']) && !isset($_REQUEST['query'])) // What must we do in this case? Maybe redirect to the homepage? @@ -36,7 +38,7 @@ class DataexportController extends BaseController $format = 'N/A'; // force behavior to assume there is no pg_dump in the system - $forcemimic = isset($_REQUEST['forcemimic']) ? $_REQUEST['forcemimic'] : false; + $forcemimic = $_REQUEST['forcemimic'] ?? false; // If format is set, then perform the export if (!isset($_REQUEST['what'])) { @@ -49,11 +51,12 @@ class DataexportController extends BaseController $this->setNoOutput(true); $clean = false; $oids = false; + switch ($_REQUEST['what']) { case 'dataonly': // Check to see if they have pg_dump set up and if they do, use that // instead of custom dump code - if (!$forcemimic && $this->misc->isDumpEnabled() && ('copy' == $_REQUEST['d_format'] || 'sql' == $_REQUEST['d_format'])) { + if (!$forcemimic && $this->misc->isDumpEnabled() && ('copy' === $_REQUEST['d_format'] || 'sql' === $_REQUEST['d_format'])) { $this->prtrace('DUMP ENABLED, d_format is', $_REQUEST['d_format']); $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer()); @@ -94,11 +97,68 @@ class DataexportController extends BaseController return $this->mimicDumpFeature($format, $cleanprefix, $oids); } + public function doDefault($msg = ''): void + { + if (!isset($_REQUEST['query']) || empty($_REQUEST['query'])) { + $_REQUEST['query'] = $_SESSION['sqlquery']; + } + + $this->printHeader(); + $this->printBody(); + $this->printTrail($_REQUEST['subject'] ?? 'database'); + $this->printTitle($this->lang['strexport']); + + if (isset($msg)) { + $this->printMsg($msg); + } + + echo '<form action="' . self::SUBFOLDER . '/src/views/dataexport" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data\">{$this->lang['strformat']}:</th><td><select name=\"d_format\">" . \PHP_EOL; + // COPY and SQL require a table + if (isset($_REQUEST['table'])) { + echo '<option value="copy">COPY</option>' . \PHP_EOL; + echo '<option value="sql">SQL</option>' . \PHP_EOL; + } + echo '<option value="csv">CSV</option>' . \PHP_EOL; + echo "<option value=\"tab\">{$this->lang['strtabbed']}</option>" . \PHP_EOL; + echo '<option value="html">XHTML</option>' . \PHP_EOL; + echo '<option value="xml">XML</option>' . \PHP_EOL; + echo '</select></td></tr>'; + echo '</table>' . \PHP_EOL; + + echo "<h3>{$this->lang['stroptions']}</h3>" . \PHP_EOL; + echo "<p><input type=\"radio\" id=\"output1\" name=\"output\" value=\"show\" checked=\"checked\" /><label for=\"output1\">{$this->lang['strshow']}</label>" . \PHP_EOL; + echo "<br/><input type=\"radio\" id=\"output2\" name=\"output\" value=\"download\" /><label for=\"output2\">{$this->lang['strdownload']}</label></p>" . \PHP_EOL; + + echo '<p><input type="hidden" name="action" value="export" />' . \PHP_EOL; + echo '<input type="hidden" name="what" value="dataonly" />' . \PHP_EOL; + + if (isset($_REQUEST['table'])) { + echo '<input type="hidden" name="subject" value="table" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + } else { + echo '<input type="hidden" name="subject" value="table" />' . \PHP_EOL; + } + $this->prtrace('$_REQUEST[query]', $_REQUEST['query'], \htmlspecialchars(\urlencode($_REQUEST['query']))); + $this->prtrace('$_SESSION[sqlquery]', $_SESSION['sqlquery'], \htmlspecialchars(\urlencode($_SESSION['sqlquery']))); + echo '<input type="hidden" name="query" value="', \htmlspecialchars(\urlencode($_REQUEST['query'])), '" />' . \PHP_EOL; + + if (isset($_REQUEST['search_path'])) { + echo '<input type="hidden" name="search_path" value="', \htmlspecialchars($_REQUEST['search_path']), '" />' . \PHP_EOL; + } + echo $this->misc->form; + echo "<input type=\"submit\" value=\"{$this->lang['strexport']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; + + $this->printFooter(); + } + protected function mimicDumpFeature($format, $cleanprefix, $oids) { $data = $this->misc->getDatabaseAccessor(); - set_time_limit(0); + \set_time_limit(0); // if (!isset($_REQUEST['table']) && !isset($_REQUEST['query'])) // What must we do in this case? Maybe redirect to the homepage? @@ -117,11 +177,11 @@ class DataexportController extends BaseController $this->coalesceArr($_REQUEST, 'query', ''); - $_REQUEST['query'] = trim(urldecode($_REQUEST['query'])); + $_REQUEST['query'] = \trim(\urldecode($_REQUEST['query'])); // Set the schema search path if (isset($_REQUEST['search_path'])) { - $data->setSearchPath(array_map('trim', explode(',', $_REQUEST['search_path']))); + $data->setSearchPath(\array_map('trim', \explode(',', $_REQUEST['search_path']))); } elseif (isset($_REQUEST['schema'])) { $data->setSearchPath($_REQUEST['schema']); } @@ -138,14 +198,14 @@ class DataexportController extends BaseController $tabledefsuffix = ''; // If the dump is not dataonly then dump the structure prefix - if ('dataonly' != $_REQUEST['what']) { + if ('dataonly' !== $_REQUEST['what']) { $tabledefprefix = $data->getTableDefPrefix($object, $cleanprefix); $this->prtrace('tabledefprefix', $tabledefprefix); echo $tabledefprefix; } // If the dump is not structureonly then dump the actual data - if ('structureonly' != $_REQUEST['what']) { + if ('structureonly' !== $_REQUEST['what']) { // Get database encoding //$dbEncoding = $data->getDatabaseEncoding(); @@ -157,7 +217,8 @@ class DataexportController extends BaseController $response = $this->pickFormat($data, $object, $oids, $rs, $format, $response); } - if ('dataonly' != $_REQUEST['what']) { + + if ('dataonly' !== $_REQUEST['what']) { $data->conn->setFetchMode(\ADODB_FETCH_ASSOC); $tabledefsuffix = $data->getTableDefSuffix($object); $this->prtrace('tabledefsuffix', $tabledefsuffix); @@ -194,7 +255,7 @@ class DataexportController extends BaseController } // Set headers. MSIE is totally broken for SSL downloading, so // we need to have it download in-place as plain text - if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS'])) { + if (\mb_strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS'])) { return $response ->withHeader('Content-type', 'text/plain'); } @@ -202,27 +263,28 @@ class DataexportController extends BaseController ->withHeader('Content-type', 'application/download'); $ext = 'txt'; + if (isset($this->extensions[$format])) { $ext = $this->extensions[$format]; } return $response - ->withHeader('Content-Disposition', 'attachment; filename=dump.'.$ext); + ->withHeader('Content-Disposition', 'attachment; filename=dump.' . $ext); } private function pickFormat($data, $object, $oids, $rs, $format, $response) { - if ('copy' == $format) { + if ('copy' === $format) { $this->_mimicCopy($data, $object, $oids, $rs); - } elseif ('html' == $format) { + } elseif ('html' === $format) { $response = $response ->withHeader('Content-type', 'text/html'); $this->_mimicHtml($data, $object, $oids, $rs); - } elseif ('xml' == $format) { + } elseif ('xml' === $format) { $response = $response ->withHeader('Content-type', 'application/xml'); $this->_mimicXml($data, $object, $oids, $rs); - } elseif ('sql' == $format) { + } elseif ('sql' === $format) { $this->_mimicSQL($data, $object, $oids, $rs); } $this->_csvOrTab($data, $object, $oids, $rs, $format); @@ -230,69 +292,17 @@ class DataexportController extends BaseController return $response; } - public function doDefault($msg = '') - { - if (!isset($_REQUEST['query']) || empty($_REQUEST['query'])) { - $_REQUEST['query'] = $_SESSION['sqlquery']; - } - - $this->printHeader(); - $this->printBody(); - $this->printTrail(isset($_REQUEST['subject']) ? $_REQUEST['subject'] : 'database'); - $this->printTitle($this->lang['strexport']); - if (isset($msg)) { - $this->printMsg($msg); - } - - echo '<form action="'.\SUBFOLDER.'/src/views/dataexport" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data\">{$this->lang['strformat']}:</th><td><select name=\"d_format\">".PHP_EOL; - // COPY and SQL require a table - if (isset($_REQUEST['table'])) { - echo '<option value="copy">COPY</option>'.PHP_EOL; - echo '<option value="sql">SQL</option>'.PHP_EOL; - } - echo '<option value="csv">CSV</option>'.PHP_EOL; - echo "<option value=\"tab\">{$this->lang['strtabbed']}</option>".PHP_EOL; - echo '<option value="html">XHTML</option>'.PHP_EOL; - echo '<option value="xml">XML</option>'.PHP_EOL; - echo '</select></td></tr>'; - echo '</table>'.PHP_EOL; - - echo "<h3>{$this->lang['stroptions']}</h3>".PHP_EOL; - echo "<p><input type=\"radio\" id=\"output1\" name=\"output\" value=\"show\" checked=\"checked\" /><label for=\"output1\">{$this->lang['strshow']}</label>".PHP_EOL; - echo "<br/><input type=\"radio\" id=\"output2\" name=\"output\" value=\"download\" /><label for=\"output2\">{$this->lang['strdownload']}</label></p>".PHP_EOL; - - echo '<p><input type="hidden" name="action" value="export" />'.PHP_EOL; - echo '<input type="hidden" name="what" value="dataonly" />'.PHP_EOL; - if (isset($_REQUEST['table'])) { - echo '<input type="hidden" name="subject" value="table" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - } else { - echo '<input type="hidden" name="subject" value="table" />'.PHP_EOL; - } - $this->prtrace('$_REQUEST[query]', $_REQUEST['query'], htmlspecialchars(urlencode($_REQUEST['query']))); - $this->prtrace('$_SESSION[sqlquery]', $_SESSION['sqlquery'], htmlspecialchars(urlencode($_SESSION['sqlquery']))); - echo '<input type="hidden" name="query" value="', htmlspecialchars(urlencode($_REQUEST['query'])), '" />'.PHP_EOL; - if (isset($_REQUEST['search_path'])) { - echo '<input type="hidden" name="search_path" value="', htmlspecialchars($_REQUEST['search_path']), '" />'.PHP_EOL; - } - echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strexport']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; - - $this->printFooter(); - } - - private function _mimicCopy($data, $object, $oids, $rs) + private function _mimicCopy($data, $object, $oids, $rs): void { $data->fieldClean($object); echo "COPY \"{$_REQUEST['table']}\""; + if ($oids) { echo ' WITH OIDS'; } echo " FROM stdin;\n"; + while (!$rs->EOF) { $first = true; //while (list($k, $v) = each($rs->fields)) { @@ -301,21 +311,22 @@ class DataexportController extends BaseController $v = $data->escapeBytea($v); // We add an extra escaping slash onto octal encoded characters - $v = preg_replace('/\\\\([0-7]{3})/', '\\\\\1', $v); + $v = \preg_replace('/\\\\([0-7]{3})/', '\\\\\1', $v); + if ($first) { - echo (is_null($v)) ? '\\N' : $v; + echo (null === $v) ? '\\N' : $v; $first = false; } else { - echo "\t", (is_null($v)) ? '\\N' : $v; + echo "\t", (null === $v) ? '\\N' : $v; } } - echo PHP_EOL; + echo \PHP_EOL; $rs->moveNext(); } echo "\\.\n"; } - private function _mimicHtml($data, $object, $oids, $rs) + private function _mimicHtml($data, $object, $oids, $rs): void { echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n"; echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n"; @@ -326,12 +337,15 @@ class DataexportController extends BaseController echo "<body>\r\n"; echo "<table class=\"phppgadmin\">\r\n"; echo "\t<tr>\r\n"; + if (!$rs->EOF) { // Output header row $j = 0; + foreach ($rs->fields as $k => $v) { $finfo = $rs->fetchField($j++); - if ($finfo->name == $data->id && !$oids) { + + if ($finfo->name === $data->id && !$oids) { continue; } @@ -339,12 +353,15 @@ class DataexportController extends BaseController } } echo "\t</tr>\r\n"; + while (!$rs->EOF) { echo "\t<tr>\r\n"; $j = 0; + foreach ($rs->fields as $k => $v) { $finfo = $rs->fetchField($j++); - if ($finfo->name == $data->id && !$oids) { + + if ($finfo->name === $data->id && !$oids) { continue; } @@ -358,50 +375,57 @@ class DataexportController extends BaseController echo "</html>\r\n"; } - private function _mimicXml($data, $object, $oids, $rs) + private function _mimicXml($data, $object, $oids, $rs): void { - echo '<?xml version="1.0" encoding="utf-8" ?>'.PHP_EOL; - echo '<data>'.PHP_EOL; + echo '<?xml version="1.0" encoding="utf-8" ?>' . \PHP_EOL; + echo '<data>' . \PHP_EOL; + if (!$rs->EOF) { // Output header row $j = 0; - echo "\t<header>".PHP_EOL; + echo "\t<header>" . \PHP_EOL; + foreach ($rs->fields as $k => $v) { $finfo = $rs->fetchField($j++); - $name = htmlspecialchars($finfo->name); - $type = htmlspecialchars($finfo->type); - echo "\t\t<column name=\"{$name}\" type=\"{$type}\" />".PHP_EOL; + $name = \htmlspecialchars($finfo->name); + $type = \htmlspecialchars($finfo->type); + echo "\t\t<column name=\"{$name}\" type=\"{$type}\" />" . \PHP_EOL; } - echo "\t</header>".PHP_EOL; + echo "\t</header>" . \PHP_EOL; } - echo "\t<records>".PHP_EOL; + echo "\t<records>" . \PHP_EOL; + while (!$rs->EOF) { $j = 0; - echo "\t\t<row>".PHP_EOL; + echo "\t\t<row>" . \PHP_EOL; + foreach ($rs->fields as $k => $v) { $finfo = $rs->fetchField($j++); - $name = htmlspecialchars($finfo->name); - if (!is_null($v)) { - $v = htmlspecialchars($v); + $name = \htmlspecialchars($finfo->name); + + if (null !== $v) { + $v = \htmlspecialchars($v); } - echo "\t\t\t<column name=\"{$name}\"", (is_null($v) ? ' null="null"' : ''), ">{$v}</column>".PHP_EOL; + echo "\t\t\t<column name=\"{$name}\"", (null === $v ? ' null="null"' : ''), ">{$v}</column>" . \PHP_EOL; } - echo "\t\t</row>".PHP_EOL; + echo "\t\t</row>" . \PHP_EOL; $rs->moveNext(); } - echo "\t</records>".PHP_EOL; - echo '</data>'.PHP_EOL; + echo "\t</records>" . \PHP_EOL; + echo '</data>' . \PHP_EOL; } - private function _mimicSQL($data, $object, $oids, $rs) + private function _mimicSQL($data, $object, $oids, $rs): void { $data->fieldClean($object); $values = ''; + while (!$rs->EOF) { echo "INSERT INTO \"{$object}\" ("; $first = true; $j = 0; + foreach ($rs->fields as $k => $v) { $finfo = $rs->fetchField($j++); $k = $finfo->name; @@ -409,27 +433,29 @@ class DataexportController extends BaseController // if ($k == $data->id) continue; // Output field $data->fieldClean($k); + if ($first) { echo "\"{$k}\""; } else { echo ", \"{$k}\""; } - if (!is_null($v)) { + if (null !== $v) { // Output value // addCSlashes converts all weird ASCII characters to octal representation, // EXCEPT the 'special' ones like \r \n \t, etc. - $v = addcslashes($v, "\0..\37\177..\377"); + $v = \addcslashes($v, "\0..\37\177..\377"); // We add an extra escaping slash onto octal encoded characters - $v = preg_replace('/\\\\([0-7]{3})/', '\\\1', $v); + $v = \preg_replace('/\\\\([0-7]{3})/', '\\\1', $v); // Finally, escape all apostrophes - $v = str_replace("'", "''", $v); + $v = \str_replace("'", "''", $v); } + if ($first) { - $values = (is_null($v) ? 'NULL' : "'{$v}'"); + $values = (null === $v ? 'NULL' : "'{$v}'"); $first = false; } else { - $values .= ', '.((is_null($v) ? 'NULL' : "'{$v}'")); + $values .= ', ' . ((null === $v ? 'NULL' : "'{$v}'")); } } echo ") VALUES ({$values});\n"; @@ -437,7 +463,7 @@ class DataexportController extends BaseController } } - private function _csvOrTab($data, $object, $oids, $rs, $format) + private function _csvOrTab($data, $object, $oids, $rs, $format): void { switch ($format) { case 'tab': @@ -450,14 +476,17 @@ class DataexportController extends BaseController break; } + if (!$rs->EOF) { // Output header row $first = true; + foreach ($rs->fields as $k => $v) { $finfo = $rs->fetchField($k); $v = $finfo->name; - if (!is_null($v)) { - $v = str_replace('"', '""', $v); + + if (null !== $v) { + $v = \str_replace('"', '""', $v); } if ($first) { @@ -469,18 +498,20 @@ class DataexportController extends BaseController } echo "\r\n"; } + while (!$rs->EOF) { $first = true; + foreach ($rs->fields as $k => $v) { - if (!is_null($v)) { - $v = str_replace('"', '""', $v); + if (null !== $v) { + $v = \str_replace('"', '""', $v); } if ($first) { - echo (is_null($v)) ? '"\\N"' : "\"{$v}\""; + echo (null === $v) ? '"\\N"' : "\"{$v}\""; $first = false; } else { - echo is_null($v) ? "{$sep}\"\\N\"" : "{$sep}\"{$v}\""; + echo null === $v ? "{$sep}\"\\N\"" : "{$sep}\"{$v}\""; } } echo "\r\n"; diff --git a/src/controllers/DataimportController.php b/src/controllers/DataimportController.php index 129bb2fa..2afd6853 100644 --- a/src/controllers/DataimportController.php +++ b/src/controllers/DataimportController.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class DataimportController extends BaseController { @@ -23,7 +24,7 @@ class DataimportController extends BaseController $data = $this->misc->getDatabaseAccessor(); // Prevent timeouts on large exports - set_time_limit(0); + \set_time_limit(0); $this->printHeader(); $this->printTrail('table'); @@ -42,8 +43,8 @@ class DataimportController extends BaseController * @param $parser * @param $cdata */ - $_charHandler = function ($parser, $cdata) use (&$state, &$curr_col_val) { - if ('COLUMN' == $state) { + $_charHandler = static function ($parser, $cdata) use (&$state, &$curr_col_val): void { + if ('COLUMN' === $state) { $curr_col_val .= $cdata; } }; @@ -56,10 +57,10 @@ class DataimportController extends BaseController * @param string $name * @param array $attrs */ - $_startElement = function ($parser, $name, $attrs) use ($curr_row, $data, &$state, &$curr_col_name, &$curr_col_null, $lang) { + $_startElement = function ($parser, $name, $attrs) use ($curr_row, $data, &$state, &$curr_col_name, &$curr_col_null, $lang): void { switch ($name) { case 'DATA': - if ('XML' != $state) { + if ('XML' !== $state) { $data->rollbackTransaction(); $this->halt($lang['strimporterror']); } @@ -67,7 +68,7 @@ class DataimportController extends BaseController break; case 'HEADER': - if ('DATA' != $state) { + if ('DATA' !== $state) { $data->rollbackTransaction(); $this->halt($lang['strimporterror']); } @@ -75,7 +76,7 @@ class DataimportController extends BaseController break; case 'RECORDS': - if ('READ_HEADER' != $state) { + if ('READ_HEADER' !== $state) { $data->rollbackTransaction(); $this->halt($lang['strimporterror']); } @@ -83,7 +84,7 @@ class DataimportController extends BaseController break; case 'ROW': - if ('RECORDS' != $state) { + if ('RECORDS' !== $state) { $data->rollbackTransaction(); $this->halt($lang['strimporterror']); } @@ -93,11 +94,11 @@ class DataimportController extends BaseController break; case 'COLUMN': // We handle columns in rows - if ('ROW' == $state) { + if ('ROW' === $state) { $state = 'COLUMN'; $curr_col_name = $attrs['NAME']; $curr_col_null = isset($attrs['NULL']); - } elseif ('HEADER' != $state) { + } elseif ('HEADER' !== $state) { // And we ignore columns in headers and fail in any other context $data->rollbackTransaction(); $this->halt($lang['strimporterror']); @@ -117,7 +118,7 @@ class DataimportController extends BaseController * @param resource $parser * @param string $name */ - $_endElement = function ($parser, $name) use ($curr_row, $data, &$state, &$curr_col_name, &$curr_col_null, &$curr_col_val, $lang) { + $_endElement = function ($parser, $name) use ($curr_row, $data, &$state, &$curr_col_name, &$curr_col_null, &$curr_col_val, $lang): void { switch ($name) { case 'DATA': $state = 'READ_DATA'; @@ -139,6 +140,7 @@ class DataimportController extends BaseController $format = []; $types = []; $i = 0; + foreach ($curr_row as $k => $v) { $fields[$i] = $k; // Check for nulls @@ -155,7 +157,8 @@ class DataimportController extends BaseController ++$i; } $status = $data->insertRow($_REQUEST['table'], $fields, $vars, $nulls, $format, $types); - if (0 != $status) { + + if (0 !== $status) { $data->rollbackTransaction(); $this->halt($lang['strimporterror']); } @@ -179,13 +182,13 @@ class DataimportController extends BaseController }; // Check that file is specified and is an uploaded file - if (!isset($_FILES['source']) || !is_uploaded_file($_FILES['source']['tmp_name']) || !is_readable($_FILES['source']['tmp_name'])) { + if (!isset($_FILES['source']) || !\is_uploaded_file($_FILES['source']['tmp_name']) || !\is_readable($_FILES['source']['tmp_name'])) { // Upload went wrong $this->printMsg($this->lang['strimporterror-uploadedfile']); return $this->printFooter(); } - $fd = fopen($_FILES['source']['tmp_name'], 'rb'); + $fd = \fopen($_FILES['source']['tmp_name'], 'rb'); // Check that file was opened successfully if (false === $fd) { // File could not be opened @@ -195,13 +198,15 @@ class DataimportController extends BaseController } $null_array = self::loadNULLArray(); $status = $data->beginTransaction(); - if (0 != $status) { + + if (0 !== $status) { $this->halt($this->lang['strimporterror']); } // If format is set to 'auto', then determine format automatically from file name - if ('auto' == $_REQUEST['format']) { - $extension = substr(strrchr($_FILES['source']['name'], '.'), 1); + if ('auto' === $_REQUEST['format']) { + $extension = \mb_substr(\mb_strrchr($_FILES['source']['name'], '.'), 1); + switch ($extension) { case 'csv': $_REQUEST['format'] = 'csv'; @@ -228,16 +233,16 @@ class DataimportController extends BaseController // XXX: Length of CSV lines limited to 100k $csv_max_line = 100000; // Set delimiter to tabs or commas - if ('csv' == $_REQUEST['format']) { + if ('csv' === $_REQUEST['format']) { $csv_delimiter = ','; } else { $csv_delimiter = "\t"; } // Get first line of field names - $fields = fgetcsv($fd, $csv_max_line, $csv_delimiter); + $fields = \fgetcsv($fd, $csv_max_line, $csv_delimiter); $row = 2; //We start on the line AFTER the field names - while ($line = fgetcsv($fd, $csv_max_line, $csv_delimiter)) { + while ($line = \fgetcsv($fd, $csv_max_line, $csv_delimiter)) { // Build value map $t_fields = []; $vars = []; @@ -245,10 +250,11 @@ class DataimportController extends BaseController $format = []; $types = []; $i = 0; + foreach ($fields as $f) { // Check that there is a column if (!isset($line[$i])) { - $this->halt(sprintf($this->lang['strimporterrorline-badcolumnnum'], $row)); + $this->halt(\sprintf($this->lang['strimporterrorline-badcolumnnum'], $row)); } $t_fields[$i] = $f; @@ -266,25 +272,26 @@ class DataimportController extends BaseController } $status = $data->insertRow($_REQUEST['table'], $t_fields, $vars, $nulls, $format, $types); - if (0 != $status) { + + if (0 !== $status) { $data->rollbackTransaction(); - $this->halt(sprintf($this->lang['strimporterrorline'], $row)); + $this->halt(\sprintf($this->lang['strimporterrorline'], $row)); } ++$row; } break; case 'xml': - $parser = xml_parser_create(); - xml_set_element_handler($parser, $_startElement, $_endElement); - xml_set_character_data_handler($parser, $_charHandler); + $parser = \xml_parser_create(); + \xml_set_element_handler($parser, $_startElement, $_endElement); + \xml_set_character_data_handler($parser, $_charHandler); - while (!feof($fd)) { - $line = fgets($fd, 4096); - xml_parse($parser, $line); + while (!\feof($fd)) { + $line = \fgets($fd, 4096); + \xml_parse($parser, $line); } - xml_parser_free($parser); + \xml_parser_free($parser); break; default: @@ -294,10 +301,11 @@ class DataimportController extends BaseController } $status = $data->endTransaction(); - if (0 != $status) { + + if (0 !== $status) { $this->printMsg($this->lang['strimporterror']); } - fclose($fd); + \fclose($fd); $this->printMsg($this->lang['strfileimported']); @@ -307,6 +315,7 @@ class DataimportController extends BaseController public static function loadNULLArray() { $array = []; + if (isset($_POST['allowednulls'])) { foreach ($_POST['allowednulls'] as $null_char) { $array[] = $null_char; @@ -318,6 +327,6 @@ class DataimportController extends BaseController public static function determineNull($field, $null_array) { - return in_array($field, $null_array, true); + return \in_array($field, $null_array, true); } } diff --git a/src/controllers/DbexportController.php b/src/controllers/DbexportController.php index ae7ecfde..45e09e6f 100644 --- a/src/controllers/DbexportController.php +++ b/src/controllers/DbexportController.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class DbexportController extends BaseController { @@ -21,7 +22,7 @@ class DbexportController extends BaseController $data = $this->misc->getDatabaseAccessor(); // Prevent timeouts on large exports - set_time_limit(0); + \set_time_limit(0); $response = $this ->container @@ -31,10 +32,10 @@ class DbexportController extends BaseController $f_schema = $f_object = ''; $this->setNoOutput(true); - ini_set('memory_limit', '768M'); + \ini_set('memory_limit', '768M'); // Are we doing a cluster-wide dump or just a per-database dump - $dumpall = ('server' == $_REQUEST['subject']); + $dumpall = ('server' === $_REQUEST['subject']); $this->prtrace('REQUEST[subject]', $_REQUEST['subject']); // Check that database dumps are enabled. @@ -48,14 +49,15 @@ class DbexportController extends BaseController // Obtain the pg_dump version number and check if the path is good $version = []; - preg_match('/(\\d+(?:\\.\\d+)?)(?:\\.\\d+)?.*$/', exec($exe.' --version'), $version); + \preg_match('/(\\d+(?:\\.\\d+)?)(?:\\.\\d+)?.*$/', \exec($exe . ' --version'), $version); if (empty($version)) { $this->prtrace('$exe', $exe, 'version', $version[1]); + if ($dumpall) { - printf($this->lang['strbadpgdumpallpath'], $server_info['pg_dumpall_path']); + \printf($this->lang['strbadpgdumpallpath'], $server_info['pg_dumpall_path']); } else { - printf($this->lang['strbadpgdumppath'], $server_info['pg_dump_path']); + \printf($this->lang['strbadpgdumppath'], $server_info['pg_dump_path']); } return; @@ -68,7 +70,7 @@ class DbexportController extends BaseController // Make it do a download, if necessary switch ($_REQUEST['output']) { case 'show': - header('Content-Type: text/plain'); + \header('Content-Type: text/plain'); $response = $response ->withHeader('Content-type', 'text/plain'); @@ -76,8 +78,8 @@ class DbexportController extends BaseController case 'download': // Set headers. MSIE is totally broken for SSL downloading, so // we need to have it download in-place as plain text - if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS'])) { - header('Content-Type: text/plain'); + if (\mb_strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS'])) { + \header('Content-Type: text/plain'); $response = $response ->withHeader('Content-type', 'text/plain'); } else { @@ -97,15 +99,17 @@ class DbexportController extends BaseController } // Set environmental variables that pg_dump uses - putenv('PGPASSWORD='.$server_info['password']); - putenv('PGUSER='.$server_info['username']); + \putenv('PGPASSWORD=' . $server_info['password']); + \putenv('PGUSER=' . $server_info['username']); $hostname = $server_info['host']; - if (null !== $hostname && '' != $hostname) { - putenv('PGHOST='.$hostname); + + if (null !== $hostname && '' !== $hostname) { + \putenv('PGHOST=' . $hostname); } $port = $server_info['port']; - if (null !== $port && '' != $port) { - putenv('PGPORT='.$port); + + if (null !== $port && '' !== $port) { + \putenv('PGPORT=' . $port); } $cmd = $exe; // Build command for executing pg_dump. '-i' means ignore version differences. @@ -128,7 +132,7 @@ class DbexportController extends BaseController switch ($_REQUEST['subject']) { case 'schema': // This currently works for 8.2+ (due to the orthoganl -t -n issue introduced then) - $cmd .= ' -n '.$this->misc->escapeShellArg("\"{$f_schema}\""); + $cmd .= ' -n ' . $this->misc->escapeShellArg("\"{$f_schema}\""); break; case 'table': @@ -140,26 +144,27 @@ class DbexportController extends BaseController // Starting in 8.2, -n and -t are orthagonal, so we now schema qualify // the table name in the -t argument and quote both identifiers - if (((float) $version[1]) >= 8.2) { - $cmd .= ' -t '.$this->misc->escapeShellArg("\"{$f_schema}\".\"{$f_object}\""); + if (8.2 <= ((float) $version[1])) { + $cmd .= ' -t ' . $this->misc->escapeShellArg("\"{$f_schema}\".\"{$f_object}\""); } else { // If we are 7.4 or higher, assume they are using 7.4 pg_dump and // set dump schema as well. Also, mixed case dumping has been fixed // then.. - $cmd .= ' -t '.$this->misc->escapeShellArg($f_object) - .' -n '.$this->misc->escapeShellArg($f_schema); + $cmd .= ' -t ' . $this->misc->escapeShellArg($f_object) + . ' -n ' . $this->misc->escapeShellArg($f_schema); } } // Check for GZIP compression specified - if ('gzipped' == $_REQUEST['output'] && !$dumpall) { + if ('gzipped' === $_REQUEST['output'] && !$dumpall) { $cmd .= ' -Z 9'; } switch ($_REQUEST['what']) { case 'dataonly': $cmd .= ' -a'; - if ('sql' == $_REQUEST['d_format']) { + + if ('sql' === $_REQUEST['d_format']) { $cmd .= ' --inserts'; } elseif (isset($_REQUEST['d_oids'])) { $cmd .= ' -o'; @@ -168,13 +173,14 @@ class DbexportController extends BaseController break; case 'structureonly': $cmd .= ' -s'; + if (isset($_REQUEST['s_clean'])) { $cmd .= ' -c'; } break; case 'structureanddata': - if ('sql' == $_REQUEST['sd_format']) { + if ('sql' === $_REQUEST['sd_format']) { $cmd .= ' --inserts'; } elseif (isset($_REQUEST['sd_oids'])) { $cmd .= ' -o'; @@ -188,26 +194,26 @@ class DbexportController extends BaseController } if (!$dumpall) { - putenv('PGDATABASE='.$_REQUEST['database']); + \putenv('PGDATABASE=' . $_REQUEST['database']); } else { //$cmd .= ' --no-role-password'; - putenv('PGDATABASE'); + \putenv('PGDATABASE'); } $this->prtrace( 'ENV VARS', [ - 'PGUSER' => getenv('PGUSER'), - 'PGPASSWORD' => getenv('PGPASSWORD'), - 'PGHOST' => getenv('PGHOST'), - 'PGPORT' => getenv('PGPORT'), - 'PGDATABASE' => getenv('PGDATABASE'), + 'PGUSER' => \getenv('PGUSER'), + 'PGPASSWORD' => \getenv('PGPASSWORD'), + 'PGHOST' => \getenv('PGHOST'), + 'PGPORT' => \getenv('PGPORT'), + 'PGDATABASE' => \getenv('PGDATABASE'), ] ); $this->prtrace('cmd', $cmd); // Execute command and return the output to the screen - passthru($cmd); + \passthru($cmd); //\Kint::dump($cmd); return $response; diff --git a/src/controllers/DisplayController.php b/src/controllers/DisplayController.php index 895b0c20..2212c1d5 100644 --- a/src/controllers/DisplayController.php +++ b/src/controllers/DisplayController.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class DisplayController extends BaseController { @@ -22,28 +23,30 @@ class DisplayController extends BaseController { $this->misc = $this->misc; - if ('dobrowsefk' == $this->action) { + if ('dobrowsefk' === $this->action) { return $this->doBrowseFK(); } - set_time_limit(0); + \set_time_limit(0); - $scripts = '<script src="'.\SUBFOLDER.'/assets/js/display.js" type="text/javascript"></script>'; + $scripts = '<script src="' . self::SUBFOLDER . '/assets/js/display.js" type="text/javascript"></script>'; - $scripts .= '<script type="text/javascript">'.PHP_EOL; + $scripts .= '<script type="text/javascript">' . \PHP_EOL; $scripts .= "var Display = {\n"; - $scripts .= "errmsg: '".str_replace("'", "\\'", $this->lang['strconnectionfail'])."'\n"; + $scripts .= "errmsg: '" . \str_replace("'", "\\'", $this->lang['strconnectionfail']) . "'\n"; $scripts .= "};\n"; - $scripts .= '</script>'.PHP_EOL; + $scripts .= '</script>' . \PHP_EOL; $footer_template = 'footer.twig'; $header_template = 'header.twig'; - ob_start(); + \ob_start(); + switch ($this->action) { case 'editrow': $header_template = 'header_sqledit.twig'; $footer_template = 'footer_sqledit.twig'; + if (isset($_POST['save'])) { $this->doEditRow(); } else { @@ -58,6 +61,7 @@ class DisplayController extends BaseController case 'delrow': $header_template = 'header_sqledit.twig'; $footer_template = 'footer_sqledit.twig'; + if (isset($_POST['yes'])) { $this->doDelRow(false); } else { @@ -76,7 +80,7 @@ class DisplayController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $subject = $this->coalesceArr($_REQUEST, 'subject', 'table')['subject']; @@ -84,13 +88,13 @@ class DisplayController extends BaseController $object = $this->setIfIsset($object, $_REQUEST[$subject]); // Set the title based on the subject of the request - if ('table' == $subject) { + if ('table' === $subject) { $title = $this->headerTitle('strtables', '', $object); - } elseif ('view' == $subject) { + } elseif ('view' === $subject) { $title = $this->headerTitle('strviews', '', $object); - } elseif ('matview' == $subject) { + } elseif ('matview' === $subject) { $title = $this->headerTitle('strviews', 'M', $object); - } elseif ('column' == $subject) { + } elseif ('column' === $subject) { $title = $this->headerTitle('strcolumn', '', $object); } else { $title = $this->headerTitle('strqueryresults'); @@ -124,7 +128,7 @@ class DisplayController extends BaseController $object = $this->coalesceArr($_REQUEST, $subject)[$subject]; - if ($subject === 'column' && $object && isset($_REQUEST['f_schema'], $_REQUEST['f_table'])) { + if ('column' === $subject && $object && isset($_REQUEST['f_schema'], $_REQUEST['f_table'])) { $f_schema = $_REQUEST['f_schema']; $f_table = $_REQUEST['f_table']; @@ -132,13 +136,13 @@ class DisplayController extends BaseController count(*) AS \"count\" FROM \"{$f_schema}\".\"{$f_table}\" GROUP BY \"{$object}\" ORDER BY \"{$object}\""; - } elseif ($subject === 'table' && !isset($_REQUEST['query'])) { + } elseif ('table' === $subject && !isset($_REQUEST['query'])) { $show = $this->getPostParam('show', []); $values = $this->getPostParam('values', []); $ops = $this->getPostParam('ops', []); $query = $data->getSelectSQL( $_REQUEST['table'], - array_keys($show), + \array_keys($show), $values, $ops ); @@ -151,9 +155,10 @@ class DisplayController extends BaseController $this->printTrail($subject); $tabsPosition = 'browse'; - if ($subject === 'database') { + + if ('database' === $subject) { $tabsPosition = 'sql'; - } elseif ($subject === 'column') { + } elseif ('column' === $subject) { $tabsPosition = 'colproperties'; } @@ -179,7 +184,7 @@ class DisplayController extends BaseController $search_path = $this->coalesceArr($_REQUEST, 'search_path')['search_path']; // Set the schema search path - if (isset($search_path) && (0 != $data->setSearchPath(array_map('trim', explode(',', $search_path))))) { + if (isset($search_path) && (0 !== $data->setSearchPath(\array_map('trim', \explode(',', $search_path))))) { return; } @@ -224,25 +229,26 @@ class DisplayController extends BaseController $_gets['sortdir'] = $sortdir; $_gets['strings'] = $strings; - if ($save_history && is_object($resultset) && ('QUERY' == $type)) { + if ($save_history && \is_object($resultset) && ('QUERY' === $type)) { //{ $this->misc->saveScriptHistory($_REQUEST['query']); } - $query = $query ? $query : sprintf('SELECT * FROM %s.%s', $_REQUEST['schema'], $object); + $query = $query ? $query : \sprintf('SELECT * FROM %s.%s', $_REQUEST['schema'], $object); //$query = isset($_REQUEST['query'])? $_REQUEST['query'] : "select * from {$_REQUEST['schema']}.{$_REQUEST['table']};"; //$this->prtrace($query); //die(htmlspecialchars($query)); - echo '<form method="post" id="sqlform" action="'.$_SERVER['REQUEST_URI'].'">'; + echo '<form method="post" id="sqlform" action="' . $_SERVER['REQUEST_URI'] . '">'; echo $this->misc->form; + if ($object) { - echo '<input type="hidden" name="'.$subject.'" value="', htmlspecialchars($object), '" />'.PHP_EOL; + echo '<input type="hidden" name="' . $subject . '" value="', \htmlspecialchars($object), '" />' . \PHP_EOL; } echo '<textarea width="90%" name="query" id="query" rows="5" cols="100" resizable="true">'; - echo htmlspecialchars($query); + echo \htmlspecialchars($query); echo '</textarea><br><input type="submit"/>'; echo '</form>'; @@ -251,7 +257,7 @@ class DisplayController extends BaseController // Navigation links $navlinks = $this->getBrowseNavLinks($type, $_gets, $page, $subject, $object, $resultset); - $this->printNavLinks($navlinks, 'display-browse', get_defined_vars()); + $this->printNavLinks($navlinks, 'display-browse', \get_defined_vars()); } public function getQueryTitleAndType($data, $object) @@ -262,7 +268,8 @@ class DisplayController extends BaseController // This code is used when browsing FK in pure-xHTML (without js) if ($fkey) { $ops = []; - foreach (array_keys($fkey) as $x) { + + foreach (\array_keys($fkey) as $x) { $ops[$x] = '='; } $query = $data->getSelectSQL($_REQUEST['table'], [], $fkey, $ops); @@ -313,12 +320,12 @@ class DisplayController extends BaseController } // Edit SQL link - if ('QUERY' == $type) { + if ('QUERY' === $type) { $navlinks['edit'] = [ 'attr' => [ 'href' => [ 'url' => 'database', - 'urlvars' => array_merge( + 'urlvars' => \array_merge( $fields, [ 'action' => 'sql', @@ -335,7 +342,7 @@ class DisplayController extends BaseController 'attr' => [ 'href' => [ 'url' => 'display', - 'urlvars' => array_merge( + 'urlvars' => \array_merge( $_gets, [ 'strings' => 'expanded', @@ -347,12 +354,12 @@ class DisplayController extends BaseController 'content' => $this->lang['strexpand'], ]; // Expand/Collapse - if ('expanded' == $strings) { + if ('expanded' === $strings) { $navlinks['collapse'] = [ 'attr' => [ 'href' => [ 'url' => 'display', - 'urlvars' => array_merge( + 'urlvars' => \array_merge( $_gets, [ 'strings' => 'collapsed', @@ -366,14 +373,14 @@ class DisplayController extends BaseController } // Create view and download - if (isset($_REQUEST['query'], $resultset) && is_object($resultset) && $resultset->recordCount() > 0) { + if (isset($_REQUEST['query'], $resultset) && \is_object($resultset) && 0 < $resultset->recordCount()) { // Report views don't set a schema, so we need to disable create view in that case if (isset($_REQUEST['schema'])) { $navlinks['createview'] = [ 'attr' => [ 'href' => [ 'url' => 'views', - 'urlvars' => array_merge( + 'urlvars' => \array_merge( $fields, [ 'action' => 'create', @@ -394,7 +401,7 @@ class DisplayController extends BaseController 'attr' => [ 'href' => [ 'url' => 'dataexport', - 'urlvars' => array_merge($fields, $urlvars), + 'urlvars' => \array_merge($fields, $urlvars), ], ], 'content' => $this->lang['strdownload'], @@ -402,12 +409,12 @@ class DisplayController extends BaseController } // Insert - if (isset($object) && (isset($subject) && 'table' == $subject)) { + if (isset($object) && (isset($subject) && 'table' === $subject)) { $navlinks['insert'] = [ 'attr' => [ 'href' => [ 'url' => 'tables', - 'urlvars' => array_merge( + 'urlvars' => \array_merge( $fields, [ 'action' => 'confinsertrow', @@ -425,7 +432,7 @@ class DisplayController extends BaseController 'attr' => [ 'href' => [ 'url' => 'display', - 'urlvars' => array_merge( + 'urlvars' => \array_merge( $_gets, [ 'strings' => $strings, @@ -440,81 +447,10 @@ class DisplayController extends BaseController return $navlinks; } - private function _getKeyAndActions($resultset, $object, $data, $page, $_gets) - { - $key = []; - $strings = $_gets['strings']; - - // Fetch unique row identifier, if this is a table browse request. - if ($object) { - $key = $data->getRowIdentifier($object); - } - // Check that the key is actually in the result set. This can occur for select - // operations where the key fields aren't part of the select. XXX: We should - // be able to support this, somehow. - foreach ($key as $v) { - // If a key column is not found in the record set, then we - // can't use the key. - if (!array_key_exists($v, $resultset->fields)) { - $key = []; - - break; - } - } - - $buttons = [ - 'edit' => [ - 'content' => $this->lang['stredit'], - 'attr' => [ - 'href' => [ - 'url' => 'display', - 'urlvars' => array_merge( - [ - 'action' => 'confeditrow', - 'strings' => $strings, - 'page' => $page, - ], - $_gets - ), - ], - ], - ], - 'delete' => [ - 'content' => $this->lang['strdelete'], - 'attr' => [ - 'href' => [ - 'url' => 'display', - 'urlvars' => array_merge( - [ - 'action' => 'confdelrow', - 'strings' => $strings, - 'page' => $page, - ], - $_gets - ), - ], - ], - ], - ]; - $actions = [ - 'actionbuttons' => &$buttons, - 'place' => 'display-browse', - ]; - - foreach (array_keys($actions['actionbuttons']) as $action) { - $actions['actionbuttons'][$action]['attr']['href']['urlvars'] = array_merge( - $actions['actionbuttons'][$action]['attr']['href']['urlvars'], - $_gets - ); - } - - return [$actions, $key]; - } - - public function printResultsTable($resultset, $page, $max_pages, $_gets, $object) + public function printResultsTable($resultset, $page, $max_pages, $_gets, $object): void { - if (!is_object($resultset) || $resultset->recordCount() <= 0) { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + if (!\is_object($resultset) || 0 >= $resultset->recordCount()) { + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; return; } @@ -528,91 +464,44 @@ class DisplayController extends BaseController $paginator = $this->_printPages($page, $max_pages, $_gets); echo $paginator; - echo '<table id="data">'.PHP_EOL; + echo '<table id="data">' . \PHP_EOL; echo '<tr>'; // Display edit and delete actions if we have a key - $display_action_column = (count($actions['actionbuttons']) > 0 && count($key) > 0); + $display_action_column = (0 < \count($actions['actionbuttons']) && 0 < \count($key)); - echo $display_action_column ? "<th class=\"data\">{$this->lang['stractions']}</th>".PHP_EOL : ''; + echo $display_action_column ? "<th class=\"data\">{$this->lang['stractions']}</th>" . \PHP_EOL : ''; // we show OIDs only if we are in TABLE or SELECT type browsing $this->printTableHeaderCells($resultset, $_gets, isset($object)); - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; - reset($resultset->fields); + \reset($resultset->fields); $trclass = 'data2'; $buttonclass = 'opbutton2'; while (!$resultset->EOF) { - $trclass = ($trclass === 'data2') ? 'data1' : 'data2'; - $buttonclass = ($buttonclass === 'opbutton2') ? 'opbutton1' : 'opbutton2'; + $trclass = ('data2' === $trclass) ? 'data1' : 'data2'; + $buttonclass = ('opbutton2' === $buttonclass) ? 'opbutton1' : 'opbutton2'; - echo sprintf('<tr class="%s">', $trclass).PHP_EOL; + echo \sprintf('<tr class="%s">', $trclass) . \PHP_EOL; $this->_printResultsTableActionButtons($resultset, $key, $actions, $display_action_column, $buttonclass); $this->printTableRowCells($resultset, $fkey_information, isset($object)); - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; $resultset->moveNext(); } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; - echo '<p>', $resultset->recordCount(), " {$this->lang['strrows']}</p>".PHP_EOL; + echo '<p>', $resultset->recordCount(), " {$this->lang['strrows']}</p>" . \PHP_EOL; // Show page navigation echo $paginator; } - private function _printResultsTableActionButtons($resultset, $key, $actions, $display_action_column, $buttonclass) - { - if (!$display_action_column) { - return; - } - - $edit_params = isset($actions['actionbuttons']['edit']) ? $actions['actionbuttons']['edit'] : []; - $delete_params = isset($actions['actionbuttons']['delete']) ? $actions['actionbuttons']['delete'] : []; - - $keys_array = []; - $has_nulls = false; - foreach ($key as $v) { - if (null === $resultset->fields[$v]) { - $has_nulls = true; - - break; - } - $keys_array["key[{$v}]"] = $resultset->fields[$v]; - } - if ($has_nulls) { - echo '<td> </td>'.PHP_EOL; - - return; - } - // Display edit and delete links if we have a key - if (isset($actions['actionbuttons']['edit'])) { - $actions['actionbuttons']['edit'] = $edit_params; - $actions['actionbuttons']['edit']['attr']['href']['urlvars'] = array_merge( - $actions['actionbuttons']['edit']['attr']['href']['urlvars'], - $keys_array - ); - } - - if (isset($actions['actionbuttons']['delete'])) { - $actions['actionbuttons']['delete'] = $delete_params; - $actions['actionbuttons']['delete']['attr']['href']['urlvars'] = array_merge( - $actions['actionbuttons']['delete']['attr']['href']['urlvars'], - $keys_array - ); - } - echo sprintf('<td class="%s" style="white-space:nowrap">', $buttonclass); - foreach ($actions['actionbuttons'] as $action) { - $this->printLink($action, true, __METHOD__); - } - echo '</td>'.PHP_EOL; - } - /** * Print table header cells. * @@ -620,42 +509,43 @@ class DisplayController extends BaseController * @param array|bool $args - associative array for sort link parameters, or false if there isn't any * @param bool $withOid either to display OIDs or not */ - public function printTableHeaderCells(&$resultset, $args, $withOid) + public function printTableHeaderCells(&$resultset, $args, $withOid): void { $data = $this->misc->getDatabaseAccessor(); - if (!is_object($resultset) || $resultset->recordCount() <= 0) { + if (!\is_object($resultset) || 0 >= $resultset->recordCount()) { return; } - foreach (array_keys($resultset->fields) as $index => $key) { + foreach (\array_keys($resultset->fields) as $index => $key) { if (($key === $data->id) && (!($withOid && $this->conf['show_oids']))) { continue; } $finfo = $resultset->fetchField($index); if (false === $args) { - echo '<th class="data">', $this->misc->printVal($finfo->name), '</th>'.PHP_EOL; + echo '<th class="data">', $this->misc->printVal($finfo->name), '</th>' . \PHP_EOL; continue; } $args['page'] = $_REQUEST['page']; $args['sortkey'] = $index + 1; // Sort direction opposite to current direction, unless it's currently '' - $args['sortdir'] = ('asc' == $_REQUEST['sortdir'] && $_REQUEST['sortkey'] == ($index + 1)) ? 'desc' : 'asc'; + $args['sortdir'] = ('asc' === $_REQUEST['sortdir'] && ($index + 1) === $_REQUEST['sortkey']) ? 'desc' : 'asc'; - $sortLink = http_build_query($args); + $sortLink = \http_build_query($args); echo "<th class=\"data\"><a href=\"?{$sortLink}\">"; echo $this->misc->printVal($finfo->name); - if ($_REQUEST['sortkey'] == ($index + 1)) { - $icon = ('asc' == $_REQUEST['sortdir']) ? $this->misc->icon('RaiseArgument') : $this->misc->icon('LowerArgument'); - echo sprintf('<img src="%s" alt="%s">', $icon, $_REQUEST['sortdir']); + + if (($index + 1) === $_REQUEST['sortkey']) { + $icon = ('asc' === $_REQUEST['sortdir']) ? $this->misc->icon('RaiseArgument') : $this->misc->icon('LowerArgument'); + echo \sprintf('<img src="%s" alt="%s">', $icon, $_REQUEST['sortdir']); } - echo '</a></th>'.PHP_EOL; + echo '</a></th>' . \PHP_EOL; } - reset($resultset->fields); + \reset($resultset->fields); } /** @@ -665,7 +555,7 @@ class DisplayController extends BaseController * @param array $fkey_information The fkey information * @param bool $withOid either to display OIDs or not */ - public function printTableRowCells(&$resultset, &$fkey_information, $withOid) + public function printTableRowCells(&$resultset, &$fkey_information, $withOid): void { $data = $this->misc->getDatabaseAccessor(); $j = 0; @@ -678,8 +568,9 @@ class DisplayController extends BaseController if (($k === $data->id) && (!($withOid && $this->conf['show_oids']))) { continue; } - $printvalOpts = ['null' => true, 'clip' => ('collapsed' == $_REQUEST['strings'])]; - if (null !== $v && '' == $v) { + $printvalOpts = ['null' => true, 'clip' => ('collapsed' === $_REQUEST['strings'])]; + + if (null !== $v && '' === $v) { echo '<td> </td>'; } else { echo '<td style="white-space:nowrap;">'; @@ -694,49 +585,12 @@ class DisplayController extends BaseController } } - private function _printFKLinks($resultset, $fkey_information, $k, $v, &$printvalOpts) - { - if ((null === $v) || !isset($fkey_information['byfield'][$k])) { - return; - } - - foreach ($fkey_information['byfield'][$k] as $conid) { - $query_params = $fkey_information['byconstr'][$conid]['url_data']; - - foreach ($fkey_information['byconstr'][$conid]['fkeys'] as $p_field => $f_field) { - $query_params .= '&'.urlencode("fkey[{$f_field}]").'='.urlencode($resultset->fields[$p_field]); - } - - // $fkey_information['common_url'] is already urlencoded - $query_params .= '&'.$fkey_information['common_url']; - $title = htmlentities($fkey_information['byconstr'][$conid]['consrc'], ENT_QUOTES, 'UTF-8'); - echo '<div style="display:inline-block;">'; - echo sprintf('<a class="fk fk_%s" href="display?%s">', htmlentities($conid, ENT_QUOTES, 'UTF-8'), $query_params); - echo sprintf('<img src="%s" style="vertical-align:middle;" alt="[fk]" title="%s" />', $this->misc->icon('ForeignKey'), $title); - echo '</a>'; - echo '</div>'; - } - $printvalOpts['class'] = 'fk_value'; - } - - private function _unserializeIfNotArray($the_array, $key) - { - if (!isset($the_array[$key])) { - return []; - } - if (is_array($the_array[$key])) { - return $the_array[$key]; - } - - return unserialize(urldecode($the_array[$key])); - } - /** * Show form to edit row. * * @param string $msg message to display on top of the form or after performing edition */ - public function formEditRow($msg = '') + public function formEditRow($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -751,54 +605,56 @@ class DisplayController extends BaseController $fksprops = $this->_getFKProps(); - echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post" id="ac_form">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/display" method="post" id="ac_form">' . \PHP_EOL; $elements = 0; $error = true; - if (1 == $resultset->recordCount() && $attrs->recordCount() > 0) { - echo '<table>'.PHP_EOL; + + if (1 === $resultset->recordCount() && 0 < $attrs->recordCount()) { + echo '<table>' . \PHP_EOL; // Output table header echo "<tr><th class=\"data\">{$this->lang['strcolumn']}</th><th class=\"data\">{$this->lang['strtype']}</th>"; - echo "<th class=\"data\">{$this->lang['strformat']}</th>".PHP_EOL; + echo "<th class=\"data\">{$this->lang['strformat']}</th>" . \PHP_EOL; echo "<th class=\"data\">{$this->lang['strnull']}</th><th class=\"data\">{$this->lang['strvalue']}</th></tr>"; $i = 0; + while (!$attrs->EOF) { $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']); - $id = (0 == ($i % 2) ? '1' : '2'); + $id = (0 === ($i % 2) ? '1' : '2'); // Initialise variables if (!isset($_REQUEST['format'][$attrs->fields['attname']])) { $_REQUEST['format'][$attrs->fields['attname']] = 'VALUE'; } - echo "<tr class=\"data{$id}\">".PHP_EOL; + echo "<tr class=\"data{$id}\">" . \PHP_EOL; echo '<td style="white-space:nowrap;">', $this->misc->printVal($attrs->fields['attname']), '</td>'; - echo '<td style="white-space:nowrap;">'.PHP_EOL; + echo '<td style="white-space:nowrap;">' . \PHP_EOL; echo $this->misc->printVal($data->formatType($attrs->fields['type'], $attrs->fields['atttypmod'])); - echo '<input type="hidden" name="types[', htmlspecialchars($attrs->fields['attname']), ']" value="', - htmlspecialchars($attrs->fields['type']), '" /></td>'; + echo '<input type="hidden" name="types[', \htmlspecialchars($attrs->fields['attname']), ']" value="', + \htmlspecialchars($attrs->fields['type']), '" /></td>'; ++$elements; - echo '<td style="white-space:nowrap;">'.PHP_EOL; - echo '<select name="format['.htmlspecialchars($attrs->fields['attname']), ']">'.PHP_EOL; - echo '<option value="VALUE"', ($_REQUEST['format'][$attrs->fields['attname']] == 'VALUE') ? ' selected="selected"' : '', ">{$this->lang['strvalue']}</option>".PHP_EOL; - $selected = ($_REQUEST['format'][$attrs->fields['attname']] == 'EXPRESSION') ? ' selected="selected"' : ''; - echo '<option value="EXPRESSION"'.$selected.">{$this->lang['strexpression']}</option>".PHP_EOL; - echo "</select>\n</td>".PHP_EOL; + echo '<td style="white-space:nowrap;">' . \PHP_EOL; + echo '<select name="format[' . \htmlspecialchars($attrs->fields['attname']), ']">' . \PHP_EOL; + echo '<option value="VALUE"', ($_REQUEST['format'][$attrs->fields['attname']] === 'VALUE') ? ' selected="selected"' : '', ">{$this->lang['strvalue']}</option>" . \PHP_EOL; + $selected = ($_REQUEST['format'][$attrs->fields['attname']] === 'EXPRESSION') ? ' selected="selected"' : ''; + echo '<option value="EXPRESSION"' . $selected . ">{$this->lang['strexpression']}</option>" . \PHP_EOL; + echo "</select>\n</td>" . \PHP_EOL; ++$elements; echo '<td style="white-space:nowrap;">'; // Output null box if the column allows nulls (doesn't look at CHECKs or ASSERTIONS) if (!$attrs->fields['attnotnull']) { // Set initial null values if ( - 'confeditrow' == $_REQUEST['action'] + 'confeditrow' === $_REQUEST['action'] && null === $resultset->fields[$attrs->fields['attname']] ) { $_REQUEST['nulls'][$attrs->fields['attname']] = 'on'; } echo "<label><span><input type=\"checkbox\" class=\"nullcheckbox\" name=\"nulls[{$attrs->fields['attname']}]\"", - isset($_REQUEST['nulls'][$attrs->fields['attname']]) ? ' checked="checked"' : '', ' /></span></label></td>'.PHP_EOL; + isset($_REQUEST['nulls'][$attrs->fields['attname']]) ? ' checked="checked"' : '', ' /></span></label></td>' . \PHP_EOL; ++$elements; } else { echo ' </td>'; @@ -825,54 +681,56 @@ class DisplayController extends BaseController echo '</td>'; ++$elements; - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; ++$i; $attrs->moveNext(); } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; $error = false; - } elseif (1 != $resultset->recordCount()) { - echo "<p>{$this->lang['strrownotunique']}</p>".PHP_EOL; + } elseif (1 !== $resultset->recordCount()) { + echo "<p>{$this->lang['strrownotunique']}</p>" . \PHP_EOL; } else { - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } - echo '<input type="hidden" name="action" value="editrow" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="editrow" />' . \PHP_EOL; echo $this->misc->form; - echo isset($_REQUEST['table']) ? sprintf('<input type="hidden" name="table" value="%s" />%s', htmlspecialchars($_REQUEST['table']), PHP_EOL) : ''; + echo isset($_REQUEST['table']) ? \sprintf('<input type="hidden" name="table" value="%s" />%s', \htmlspecialchars($_REQUEST['table']), \PHP_EOL) : ''; - echo isset($_REQUEST['subject']) ? sprintf('<input type="hidden" name="subject" value="%s" />%s', htmlspecialchars($_REQUEST['subject']), PHP_EOL) : ''; + echo isset($_REQUEST['subject']) ? \sprintf('<input type="hidden" name="subject" value="%s" />%s', \htmlspecialchars($_REQUEST['subject']), \PHP_EOL) : ''; - echo isset($_REQUEST['query']) ? sprintf('<input type="hidden" name="query" value="%s" />%s', htmlspecialchars($_REQUEST['query']), PHP_EOL) : ''; + echo isset($_REQUEST['query']) ? \sprintf('<input type="hidden" name="query" value="%s" />%s', \htmlspecialchars($_REQUEST['query']), \PHP_EOL) : ''; - echo isset($_REQUEST['count']) ? sprintf('<input type="hidden" name="count" value="%s" />%s', htmlspecialchars($_REQUEST['count']), PHP_EOL) : ''; + echo isset($_REQUEST['count']) ? \sprintf('<input type="hidden" name="count" value="%s" />%s', \htmlspecialchars($_REQUEST['count']), \PHP_EOL) : ''; - echo isset($_REQUEST['return']) ? sprintf('<input type="hidden" name="return" value="%s" />%s', htmlspecialchars($_REQUEST['return']), PHP_EOL) : ''; + echo isset($_REQUEST['return']) ? \sprintf('<input type="hidden" name="return" value="%s" />%s', \htmlspecialchars($_REQUEST['return']), \PHP_EOL) : ''; - echo '<input type="hidden" name="page" value="', htmlspecialchars($_REQUEST['page']), '" />'.PHP_EOL; - echo '<input type="hidden" name="sortkey" value="', htmlspecialchars($_REQUEST['sortkey']), '" />'.PHP_EOL; - echo '<input type="hidden" name="sortdir" value="', htmlspecialchars($_REQUEST['sortdir']), '" />'.PHP_EOL; - echo '<input type="hidden" name="strings" value="', htmlspecialchars($_REQUEST['strings']), '" />'.PHP_EOL; - echo '<input type="hidden" name="key" value="', htmlspecialchars(urlencode(serialize($key))), '" />'.PHP_EOL; + echo '<input type="hidden" name="page" value="', \htmlspecialchars($_REQUEST['page']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="sortkey" value="', \htmlspecialchars($_REQUEST['sortkey']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="sortdir" value="', \htmlspecialchars($_REQUEST['sortdir']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="strings" value="', \htmlspecialchars($_REQUEST['strings']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="key" value="', \htmlspecialchars(\urlencode(\serialize($key))), '" />' . \PHP_EOL; echo '<p>'; + if (!$error) { - echo "<input type=\"submit\" name=\"save\" accesskey=\"r\" value=\"{$this->lang['strsave']}\" />".PHP_EOL; + echo "<input type=\"submit\" name=\"save\" accesskey=\"r\" value=\"{$this->lang['strsave']}\" />" . \PHP_EOL; } - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; if (false !== $fksprops) { $autocomplete_string = "<input type=\"checkbox\" id=\"no_ac\" value=\"0\" /><label for=\"no_ac\">{$this->lang['strac']}</label>"; - if ('default off' != $this->conf['autocomplete']) { + + if ('default off' !== $this->conf['autocomplete']) { $autocomplete_string = "<input type=\"checkbox\" id=\"no_ac\" value=\"1\" checked=\"checked\" /><label for=\"no_ac\">{$this->lang['strac']}</label>"; } - echo $autocomplete_string.PHP_EOL; + echo $autocomplete_string . \PHP_EOL; } - echo '</p>'.PHP_EOL; - echo '</form>'.PHP_EOL; - echo '<script src="'.\SUBFOLDER.'/assets/js/insert_or_edit_row.js" type="text/javascript"></script>'; + echo '</p>' . \PHP_EOL; + echo '</form>' . \PHP_EOL; + echo '<script src="' . self::SUBFOLDER . '/assets/js/insert_or_edit_row.js" type="text/javascript"></script>'; } /** @@ -896,10 +754,12 @@ class DisplayController extends BaseController $_POST['types'], $key ); - if (0 == $status) { + + if (0 === $status) { return $this->doBrowse($this->lang['strrowupdated']); } - if ($status == -2) { + + if (-2 === $status) { return $this->formEditRow($this->lang['strrownotunique']); } @@ -911,7 +771,7 @@ class DisplayController extends BaseController * * @param mixed $confirm */ - public function doDelRow($confirm) + public function doDelRow($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -921,63 +781,65 @@ class DisplayController extends BaseController $resultset = $data->browseRow($_REQUEST['table'], $_REQUEST['key']); - echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/display" method="post">' . \PHP_EOL; echo $this->misc->form; - if (1 == $resultset->recordCount()) { - echo "<p>{$this->lang['strconfdeleterow']}</p>".PHP_EOL; + if (1 === $resultset->recordCount()) { + echo "<p>{$this->lang['strconfdeleterow']}</p>" . \PHP_EOL; $fkinfo = []; echo '<table><tr>'; $this->printTableHeaderCells($resultset, false, true); echo '</tr>'; - echo '<tr class="data1">'.PHP_EOL; + echo '<tr class="data1">' . \PHP_EOL; $this->printTableRowCells($resultset, $fkinfo, true); - echo '</tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<br />'.PHP_EOL; - - echo '<input type="hidden" name="action" value="delrow" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />".PHP_EOL; - } elseif (1 != $resultset->recordCount()) { - echo "<p>{$this->lang['strrownotunique']}</p>".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo '</tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<br />' . \PHP_EOL; + + echo '<input type="hidden" name="action" value="delrow" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />" . \PHP_EOL; + } elseif (1 !== $resultset->recordCount()) { + echo "<p>{$this->lang['strrownotunique']}</p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; } else { - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; } + if (isset($_REQUEST['table'])) { - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; } if (isset($_REQUEST['subject'])) { - echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['subject']), '" />'.PHP_EOL; + echo '<input type="hidden" name="subject" value="', \htmlspecialchars($_REQUEST['subject']), '" />' . \PHP_EOL; } if (isset($_REQUEST['query'])) { - echo '<input type="hidden" name="query" value="', htmlspecialchars($_REQUEST['query']), '" />'.PHP_EOL; + echo '<input type="hidden" name="query" value="', \htmlspecialchars($_REQUEST['query']), '" />' . \PHP_EOL; } if (isset($_REQUEST['count'])) { - echo '<input type="hidden" name="count" value="', htmlspecialchars($_REQUEST['count']), '" />'.PHP_EOL; + echo '<input type="hidden" name="count" value="', \htmlspecialchars($_REQUEST['count']), '" />' . \PHP_EOL; } if (isset($_REQUEST['return'])) { - echo '<input type="hidden" name="return" value="', htmlspecialchars($_REQUEST['return']), '" />'.PHP_EOL; + echo '<input type="hidden" name="return" value="', \htmlspecialchars($_REQUEST['return']), '" />' . \PHP_EOL; } - echo '<input type="hidden" name="page" value="', htmlspecialchars($_REQUEST['page']), '" />'.PHP_EOL; - echo '<input type="hidden" name="sortkey" value="', htmlspecialchars($_REQUEST['sortkey']), '" />'.PHP_EOL; - echo '<input type="hidden" name="sortdir" value="', htmlspecialchars($_REQUEST['sortdir']), '" />'.PHP_EOL; - echo '<input type="hidden" name="strings" value="', htmlspecialchars($_REQUEST['strings']), '" />'.PHP_EOL; - echo '<input type="hidden" name="key" value="', htmlspecialchars(urlencode(serialize($_REQUEST['key']))), '" />'.PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="page" value="', \htmlspecialchars($_REQUEST['page']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="sortkey" value="', \htmlspecialchars($_REQUEST['sortkey']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="sortdir" value="', \htmlspecialchars($_REQUEST['sortdir']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="strings" value="', \htmlspecialchars($_REQUEST['strings']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="key" value="', \htmlspecialchars(\urlencode(\serialize($_REQUEST['key']))), '" />' . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - $status = $data->deleteRow($_POST['table'], unserialize(urldecode($_POST['key']))); - if (0 == $status) { + $status = $data->deleteRow($_POST['table'], \unserialize(\urldecode($_POST['key']))); + + if (0 === $status) { $this->doBrowse($this->lang['strrowdeleted']); - } elseif ($status == -2) { + } elseif (-2 === $status) { $this->doBrowse($this->lang['strrownotunique']); } else { $this->doBrowse($this->lang['strrowdeletedbad']); @@ -1000,16 +862,18 @@ class DisplayController extends BaseController if (isset($_REQUEST['table'])) { $constraints = $data->getConstraintsWithFields($_REQUEST['table']); - if ($constraints->recordCount() > 0) { - $fkey_information['common_url'] = $this->misc->getHREF('schema').'&subject=table'; + + if (0 < $constraints->recordCount()) { + $fkey_information['common_url'] = $this->misc->getHREF('schema') . '&subject=table'; // build the FK constraints data structure while (!$constraints->EOF) { $constr = &$constraints->fields; - if ('f' == $constr['contype']) { + + if ('f' === $constr['contype']) { if (!isset($fkey_information['byconstr'][$constr['conid']])) { $fkey_information['byconstr'][$constr['conid']] = [ - 'url_data' => 'table='.urlencode($constr['f_table']).'&schema='.urlencode($constr['f_schema']), + 'url_data' => 'table=' . \urlencode($constr['f_table']) . '&schema=' . \urlencode($constr['f_schema']), 'fkeys' => [], 'consrc' => $constr['consrc'], ]; @@ -1032,11 +896,12 @@ class DisplayController extends BaseController } // Print the FK row, used in ajax requests - public function doBrowseFK() + public function doBrowseFK(): void { $data = $this->misc->getDatabaseAccessor(); $ops = []; + foreach ($_REQUEST['fkey'] as $x => $y) { $ops[$x] = '='; } @@ -1058,10 +923,10 @@ class DisplayController extends BaseController $max_pages ); - echo '<a href="javascript:void(0);" style="display:table-cell;" class="fk_delete"><img alt="[delete]" src="'.$this->misc->icon('Delete').'" /></a>'.PHP_EOL; + echo '<a href="javascript:void(0);" style="display:table-cell;" class="fk_delete"><img alt="[delete]" src="' . $this->misc->icon('Delete') . '" /></a>' . \PHP_EOL; echo '<div style="display:table-cell;">'; - if (is_object($resultset) && $resultset->recordCount() > 0) { + if (\is_object($resultset) && 0 < $resultset->recordCount()) { /* we are browsing a referenced table here * we should show OID if show_oids is true * so we give true to withOid in functions bellow @@ -1069,23 +934,183 @@ class DisplayController extends BaseController echo '<table><tr>'; $this->printTableHeaderCells($resultset, false, true); echo '</tr>'; - echo '<tr class="data1">'.PHP_EOL; + echo '<tr class="data1">' . \PHP_EOL; $this->printTableRowCells($resultset, $fkinfo, true); - echo '</tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; } else { echo $this->lang['strnodata']; } echo '</div>'; } + private function _getKeyAndActions($resultset, $object, $data, $page, $_gets) + { + $key = []; + $strings = $_gets['strings']; + + // Fetch unique row identifier, if this is a table browse request. + if ($object) { + $key = $data->getRowIdentifier($object); + } + // Check that the key is actually in the result set. This can occur for select + // operations where the key fields aren't part of the select. XXX: We should + // be able to support this, somehow. + foreach ($key as $v) { + // If a key column is not found in the record set, then we + // can't use the key. + if (!\array_key_exists($v, $resultset->fields)) { + $key = []; + + break; + } + } + + $buttons = [ + 'edit' => [ + 'content' => $this->lang['stredit'], + 'attr' => [ + 'href' => [ + 'url' => 'display', + 'urlvars' => \array_merge( + [ + 'action' => 'confeditrow', + 'strings' => $strings, + 'page' => $page, + ], + $_gets + ), + ], + ], + ], + 'delete' => [ + 'content' => $this->lang['strdelete'], + 'attr' => [ + 'href' => [ + 'url' => 'display', + 'urlvars' => \array_merge( + [ + 'action' => 'confdelrow', + 'strings' => $strings, + 'page' => $page, + ], + $_gets + ), + ], + ], + ], + ]; + $actions = [ + 'actionbuttons' => &$buttons, + 'place' => 'display-browse', + ]; + + foreach (\array_keys($actions['actionbuttons']) as $action) { + $actions['actionbuttons'][$action]['attr']['href']['urlvars'] = \array_merge( + $actions['actionbuttons'][$action]['attr']['href']['urlvars'], + $_gets + ); + } + + return [$actions, $key]; + } + + private function _printResultsTableActionButtons($resultset, $key, $actions, $display_action_column, $buttonclass): void + { + if (!$display_action_column) { + return; + } + + $edit_params = $actions['actionbuttons']['edit'] ?? []; + $delete_params = $actions['actionbuttons']['delete'] ?? []; + + $keys_array = []; + $has_nulls = false; + + foreach ($key as $v) { + if (null === $resultset->fields[$v]) { + $has_nulls = true; + + break; + } + $keys_array["key[{$v}]"] = $resultset->fields[$v]; + } + + if ($has_nulls) { + echo '<td> </td>' . \PHP_EOL; + + return; + } + // Display edit and delete links if we have a key + if (isset($actions['actionbuttons']['edit'])) { + $actions['actionbuttons']['edit'] = $edit_params; + $actions['actionbuttons']['edit']['attr']['href']['urlvars'] = \array_merge( + $actions['actionbuttons']['edit']['attr']['href']['urlvars'], + $keys_array + ); + } + + if (isset($actions['actionbuttons']['delete'])) { + $actions['actionbuttons']['delete'] = $delete_params; + $actions['actionbuttons']['delete']['attr']['href']['urlvars'] = \array_merge( + $actions['actionbuttons']['delete']['attr']['href']['urlvars'], + $keys_array + ); + } + echo \sprintf('<td class="%s" style="white-space:nowrap">', $buttonclass); + + foreach ($actions['actionbuttons'] as $action) { + $this->printLink($action, true, __METHOD__); + } + echo '</td>' . \PHP_EOL; + } + + private function _printFKLinks($resultset, $fkey_information, $k, $v, &$printvalOpts): void + { + if ((null === $v) || !isset($fkey_information['byfield'][$k])) { + return; + } + + foreach ($fkey_information['byfield'][$k] as $conid) { + $query_params = $fkey_information['byconstr'][$conid]['url_data']; + + foreach ($fkey_information['byconstr'][$conid]['fkeys'] as $p_field => $f_field) { + $query_params .= '&' . \urlencode("fkey[{$f_field}]") . '=' . \urlencode($resultset->fields[$p_field]); + } + + // $fkey_information['common_url'] is already urlencoded + $query_params .= '&' . $fkey_information['common_url']; + $title = \htmlentities($fkey_information['byconstr'][$conid]['consrc'], \ENT_QUOTES, 'UTF-8'); + echo '<div style="display:inline-block;">'; + echo \sprintf('<a class="fk fk_%s" href="display?%s">', \htmlentities($conid, \ENT_QUOTES, 'UTF-8'), $query_params); + echo \sprintf('<img src="%s" style="vertical-align:middle;" alt="[fk]" title="%s" />', $this->misc->icon('ForeignKey'), $title); + echo '</a>'; + echo '</div>'; + } + $printvalOpts['class'] = 'fk_value'; + } + + private function _unserializeIfNotArray($the_array, $key) + { + if (!isset($the_array[$key])) { + return []; + } + + if (\is_array($the_array[$key])) { + return $the_array[$key]; + } + + return \unserialize(\urldecode($the_array[$key])); + } + private function _getMinMaxPages($page, $pages) { $window = 10; + if ($page <= $window) { $min_page = 1; - $max_page = min(2 * $window, $pages); - } elseif ($page > $window && $pages >= $page + $window) { + $max_page = \min(2 * $window, $pages); + } elseif ($page > $window && $page + $window <= $pages) { $min_page = ($page - $window) + 1; $max_page = $page + $window; } else { @@ -1095,8 +1120,8 @@ class DisplayController extends BaseController // Make sure min_page is always at least 1 // and max_page is never greater than $pages - $min_page = max($min_page, 1); - $max_page = min($max_page, $pages); + $min_page = \max($min_page, 1); + $max_page = \min($max_page, $pages); return [$min_page, $max_page]; } @@ -1116,30 +1141,31 @@ class DisplayController extends BaseController $lang = $this->lang; $page = (int) $page; - if ($page < 0 || $page > $pages || $pages <= 1 || $max_width <= 0) { + if (0 > $page || $page > $pages || 1 >= $pages || 0 >= $max_width) { return; } unset($gets['page']); - $url = http_build_query($gets); + $url = \http_build_query($gets); + + $result = '<p style="text-align: center">' . \PHP_EOL; - $result = '<p style="text-align: center">'.PHP_EOL; - if ($page != 1) { - $result .= sprintf('<a class="pagenav" href="?%s&page=1">%s</a>%s ', $url, $lang['strfirst'], PHP_EOL); - $result .= sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page - 1, $lang['strprev'], PHP_EOL); + if (1 !== $page) { + $result .= \sprintf('<a class="pagenav" href="?%s&page=1">%s</a>%s ', $url, $lang['strfirst'], \PHP_EOL); + $result .= \sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page - 1, $lang['strprev'], \PHP_EOL); } list($min_page, $max_page) = $this->_getMinMaxPages($page, $pages); for ($i = $min_page; $i <= $max_page; ++$i) { - $result .= (($i === $page) ? $i : sprintf('<a class="pagenav" href="display?%s&page=%s">%s</a>', $url, $i, $i)).PHP_EOL; + $result .= (($i === $page) ? $i : \sprintf('<a class="pagenav" href="display?%s&page=%s">%s</a>', $url, $i, $i)) . \PHP_EOL; } - if ($page != $pages) { - $result .= sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page + 1, $lang['strnext'], PHP_EOL); - $result .= sprintf(' <a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $pages, $lang['strlast'], PHP_EOL); + if ($page !== $pages) { + $result .= \sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page + 1, $lang['strnext'], \PHP_EOL); + $result .= \sprintf(' <a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $pages, $lang['strlast'], \PHP_EOL); } - $result .= '</p>'.PHP_EOL; + $result .= '</p>' . \PHP_EOL; return $result; } diff --git a/src/controllers/DomainsController.php b/src/controllers/DomainsController.php index 551b1d58..41b7231e 100644 --- a/src/controllers/DomainsController.php +++ b/src/controllers/DomainsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class DomainsController extends BaseController { @@ -22,7 +23,7 @@ class DomainsController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -108,7 +109,7 @@ class DomainsController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -201,7 +202,7 @@ class DomainsController extends BaseController 'content' => $this->lang['strcreatedomain'], ], ]; - $this->printNavLinks($navlinks, 'domains-domains', get_defined_vars()); + $this->printNavLinks($navlinks, 'domains-domains', \get_defined_vars()); } /** @@ -235,7 +236,7 @@ class DomainsController extends BaseController /** * Function to save after altering a domain. */ - public function doSaveAlter() + public function doSaveAlter(): void { $data = $this->misc->getDatabaseAccessor(); @@ -245,7 +246,8 @@ class DomainsController extends BaseController isset($_POST['domnotnull']), $_POST['domowner'] ); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strdomainaltered']); } else { $this->doAlter($this->lang['strdomainalteredbad']); @@ -257,7 +259,7 @@ class DomainsController extends BaseController * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -270,11 +272,12 @@ class DomainsController extends BaseController // Fetch all users $users = $data->getUsers(); - if ($domaindata->recordCount() > 0) { + if (0 < $domaindata->recordCount()) { if (!isset($_POST['domname'])) { $_POST['domtype'] = $domaindata->fields['domtype']; $_POST['domdefault'] = $domaindata->fields['domdef']; $domaindata->fields['domnotnull'] = $data->phpBool($domaindata->fields['domnotnull']); + if ($domaindata->fields['domnotnull']) { $_POST['domnotnull'] = 'on'; } @@ -283,35 +286,36 @@ class DomainsController extends BaseController } // Display domain info - echo '<form action="'.\SUBFOLDER.'/src/views/domains" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\" style=\"width: 70px\">{$this->lang['strname']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domname']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strtype']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domtype']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\"><label for=\"domnotnull\">{$this->lang['strnotnull']}</label></th>".PHP_EOL; - echo '<td class="data1"><input type="checkbox" id="domnotnull" name="domnotnull"', (isset($_POST['domnotnull']) ? ' checked="checked"' : ''), ' /></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strdefault']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/domains" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\" style=\"width: 70px\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domname']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strtype']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domtype']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\"><label for=\"domnotnull\">{$this->lang['strnotnull']}</label></th>" . \PHP_EOL; + echo '<td class="data1"><input type="checkbox" id="domnotnull" name="domnotnull"', (isset($_POST['domnotnull']) ? ' checked="checked"' : ''), ' /></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strdefault']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="domdefault" size="32" value="', - htmlspecialchars($_POST['domdefault']), '" /></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; + \htmlspecialchars($_POST['domdefault']), '" /></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="domowner">'; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $_POST['domowner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $_POST['domowner']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_alter" />'.PHP_EOL; - echo '<input type="hidden" name="domain" value="', htmlspecialchars($_REQUEST['domain']), '" />'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_alter" />' . \PHP_EOL; + echo '<input type="hidden" name="domain" value="', \htmlspecialchars($_REQUEST['domain']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } @@ -321,7 +325,7 @@ class DomainsController extends BaseController * @param mixed $confirm * @param mixed $msg */ - public function addCheck($confirm, $msg = '') + public function addCheck($confirm, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -334,26 +338,26 @@ class DomainsController extends BaseController $this->printTitle($this->lang['straddcheck'], 'pg.constraint.check'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/domains" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data\">{$this->lang['strname']}</th>".PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strdefinition']}</th></tr>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/domains" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strdefinition']}</th></tr>" . \PHP_EOL; echo "<tr><td class=\"data1\"><input name=\"name\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_POST['name']), '" /></td>' . \PHP_EOL; echo '<td class="data1">(<input name="definition" size="32" value="', - htmlspecialchars($_POST['definition']), '" />)</td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; + \htmlspecialchars($_POST['definition']), '" />)</td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_add_check" />'.PHP_EOL; - echo '<input type="hidden" name="domain" value="', htmlspecialchars($_REQUEST['domain']), '" />'.PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_add_check" />' . \PHP_EOL; + echo '<input type="hidden" name="domain" value="', \htmlspecialchars($_REQUEST['domain']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"add\" value=\"{$this->lang['stradd']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"add\" value=\"{$this->lang['stradd']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - if ('' == trim($_POST['definition'])) { + if ('' === \trim($_POST['definition'])) { $this->addCheck(true, $this->lang['strcheckneedsdefinition']); } else { $status = $data->addDomainCheckConstraint( @@ -361,7 +365,8 @@ class DomainsController extends BaseController $_POST['definition'], $_POST['name'] ); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strcheckadded']); } else { $this->addCheck(true, $this->lang['strcheckaddedbad']); @@ -376,7 +381,7 @@ class DomainsController extends BaseController * @param mixed $confirm * @param mixed $msg */ - public function doDropConstraint($confirm, $msg = '') + public function doDropConstraint($confirm, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -385,23 +390,24 @@ class DomainsController extends BaseController $this->printTitle($this->lang['strdrop'], 'pg.constraint.drop'); $this->printMsg($msg); - echo '<p>', sprintf( + echo '<p>', \sprintf( $this->lang['strconfdropconstraint'], $this->misc->printVal($_REQUEST['constraint']), $this->misc->printVal($_REQUEST['domain']) - ), '</p>'.PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/domains" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="drop_con" />'.PHP_EOL; - echo '<input type="hidden" name="domain" value="', htmlspecialchars($_REQUEST['domain']), '" />'.PHP_EOL; - echo '<input type="hidden" name="constraint" value="', htmlspecialchars($_REQUEST['constraint']), '" />'.PHP_EOL; + ), '</p>' . \PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/domains" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="drop_con" />' . \PHP_EOL; + echo '<input type="hidden" name="domain" value="', \htmlspecialchars($_REQUEST['domain']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="constraint" value="', \htmlspecialchars($_REQUEST['constraint']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropDomainConstraint($_POST['domain'], $_POST['constraint'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strconstraintdropped']); } else { $this->doDropConstraint(true, $this->lang['strconstraintdroppedbad']); @@ -414,7 +420,7 @@ class DomainsController extends BaseController * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -424,29 +430,30 @@ class DomainsController extends BaseController $domaindata = $data->getDomain($_REQUEST['domain']); - if ($domaindata->recordCount() > 0) { + if (0 < $domaindata->recordCount()) { // Show comment if any if (null !== $domaindata->fields['domcomment']) { - echo '<p class="comment">', $this->misc->printVal($domaindata->fields['domcomment']), '</p>'.PHP_EOL; + echo '<p class="comment">', $this->misc->printVal($domaindata->fields['domcomment']), '</p>' . \PHP_EOL; } // Display domain info $domaindata->fields['domnotnull'] = $data->phpBool($domaindata->fields['domnotnull']); - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left\" style=\"width: 70px\">{$this->lang['strname']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domname']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strtype']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domtype']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strnotnull']}</th>".PHP_EOL; - echo '<td class="data1">', ($domaindata->fields['domnotnull'] ? 'NOT NULL' : ''), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strdefault']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domdef']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strowner']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domowner']), '</td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left\" style=\"width: 70px\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domname']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strtype']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domtype']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strnotnull']}</th>" . \PHP_EOL; + echo '<td class="data1">', ($domaindata->fields['domnotnull'] ? 'NOT NULL' : ''), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strdefault']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domdef']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strowner']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($domaindata->fields['domowner']), '</td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; // Display domain constraints - echo "<h3>{$this->lang['strconstraints']}</h3>".PHP_EOL; + echo "<h3>{$this->lang['strconstraints']}</h3>" . \PHP_EOL; + if ($data->hasDomainConstraints()) { $domaincons = $data->getDomainConstraints($_REQUEST['domain']); @@ -484,7 +491,7 @@ class DomainsController extends BaseController echo $this->printTable($domaincons, $columns, $actions, 'domains-properties', $this->lang['strnodata']); } } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } $navlinks = [ @@ -504,6 +511,7 @@ class DomainsController extends BaseController 'content' => $this->lang['strdrop'], ], ]; + if ($data->hasAlterDomains()) { $navlinks['addcheck'] = [ 'attr' => [ @@ -537,7 +545,7 @@ class DomainsController extends BaseController ]; } - $this->printNavLinks($navlinks, 'domains-properties', get_defined_vars()); + $this->printNavLinks($navlinks, 'domains-properties', \get_defined_vars()); } /** @@ -545,7 +553,7 @@ class DomainsController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -553,18 +561,19 @@ class DomainsController extends BaseController $this->printTrail('domain'); $this->printTitle($this->lang['strdrop'], 'pg.domain.drop'); - echo '<p>', sprintf($this->lang['strconfdropdomain'], $this->misc->printVal($_REQUEST['domain'])), '</p>'.PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/domains" method="post">'.PHP_EOL; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /><label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo '<p><input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="domain" value="', htmlspecialchars($_REQUEST['domain']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropdomain'], $this->misc->printVal($_REQUEST['domain'])), '</p>' . \PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/domains" method="post">' . \PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /><label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="domain" value="', \htmlspecialchars($_REQUEST['domain']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropDomain($_POST['domain'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strdomaindropped']); } else { $this->doDefault($this->lang['strdomaindroppedbad']); @@ -577,7 +586,7 @@ class DomainsController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -599,74 +608,77 @@ class DomainsController extends BaseController $this->printTitle($this->lang['strcreatedomain'], 'pg.domain.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/domains" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\" style=\"width: 70px\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/domains" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\" style=\"width: 70px\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "<td class=\"data1\"><input name=\"domname\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['domname']), '" /></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strtype']}</th>".PHP_EOL; - echo '<td class="data1">'.PHP_EOL; + \htmlspecialchars($_POST['domname']), '" /></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strtype']}</th>" . \PHP_EOL; + echo '<td class="data1">' . \PHP_EOL; // Output return type list - echo '<select name="domtype">'.PHP_EOL; + echo '<select name="domtype">' . \PHP_EOL; + while (!$types->EOF) { - echo '<option value="', htmlspecialchars($types->fields['typname']), '"', - ($types->fields['typname'] == $_POST['domtype']) ? ' selected="selected"' : '', '>', - $this->misc->printVal($types->fields['typname']), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($types->fields['typname']), '"', + ($types->fields['typname'] === $_POST['domtype']) ? ' selected="selected"' : '', '>', + $this->misc->printVal($types->fields['typname']), '</option>' . \PHP_EOL; $types->moveNext(); } - echo '</select>'.PHP_EOL; + echo '</select>' . \PHP_EOL; // Type length - echo '<input type="text" size="4" name="domlength" value="', htmlspecialchars($_POST['domlength']), '" />'; + echo '<input type="text" size="4" name="domlength" value="', \htmlspecialchars($_POST['domlength']), '" />'; // Output array type selector - echo '<select name="domarray">'.PHP_EOL; - echo '<option value=""', ('' == $_POST['domarray']) ? ' selected="selected"' : '', '></option>'.PHP_EOL; - echo '<option value="[]"', ('[]' == $_POST['domarray']) ? ' selected="selected"' : '', '>[ ]</option>'.PHP_EOL; - echo '</select></td></tr>'.PHP_EOL; + echo '<select name="domarray">' . \PHP_EOL; + echo '<option value=""', ('' === $_POST['domarray']) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; + echo '<option value="[]"', ('[]' === $_POST['domarray']) ? ' selected="selected"' : '', '>[ ]</option>' . \PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\"><label for=\"domnotnull\">{$this->lang['strnotnull']}</label></th>".PHP_EOL; + echo "<tr><th class=\"data left\"><label for=\"domnotnull\">{$this->lang['strnotnull']}</label></th>" . \PHP_EOL; echo '<td class="data1"><input type="checkbox" id="domnotnull" name="domnotnull"', - (isset($_POST['domnotnull']) ? ' checked="checked"' : ''), ' /></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strdefault']}</th>".PHP_EOL; + (isset($_POST['domnotnull']) ? ' checked="checked"' : ''), ' /></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strdefault']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="domdefault" size="32" value="', - htmlspecialchars($_POST['domdefault']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['domdefault']), '" /></td></tr>' . \PHP_EOL; + if ($data->hasDomainConstraints()) { - echo "<tr><th class=\"data left\">{$this->lang['strconstraints']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strconstraints']}</th>" . \PHP_EOL; echo '<td class="data1">CHECK (<input name="domcheck" size="32" value="', - htmlspecialchars($_POST['domcheck']), '" />)</td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['domcheck']), '" />)</td></tr>' . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new domain in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); $this->coalesceArr($_POST, 'domcheck', ''); // Check that they've given a name and a definition - if ('' == $_POST['domname']) { + if ('' === $_POST['domname']) { $this->doCreate($this->lang['strdomainneedsname']); } else { $status = $data->createDomain( $_POST['domname'], $_POST['domtype'], $_POST['domlength'], - '' != $_POST['domarray'], + '' !== $_POST['domarray'], isset($_POST['domnotnull']), $_POST['domdefault'], $_POST['domcheck'] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strdomaincreated']); } else { $this->doCreate($this->lang['strdomaincreatedbad']); diff --git a/src/controllers/FulltextController.php b/src/controllers/FulltextController.php index 21d47adf..1c291b66 100644 --- a/src/controllers/FulltextController.php +++ b/src/controllers/FulltextController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class FulltextController extends BaseController { @@ -22,10 +23,11 @@ class FulltextController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } - if ('subtree' == $this->action) { + + if ('subtree' === $this->action) { return $this->doSubTree($_REQUEST['what']); } @@ -134,7 +136,7 @@ class FulltextController extends BaseController return $this->printFooter(); } - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -211,7 +213,7 @@ class FulltextController extends BaseController ], ]; - $this->printNavLinks($navlinks, 'fulltext-fulltext', get_defined_vars()); + $this->printNavLinks($navlinks, 'fulltext-fulltext', \get_defined_vars()); } /** @@ -294,10 +296,10 @@ class FulltextController extends BaseController ), ]; - return $this->printTree($items, $attrs, strtolower($what)); + return $this->printTree($items, $attrs, \mb_strtolower($what)); } - public function doDropConfig($confirm) + public function doDropConfig($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -305,20 +307,21 @@ class FulltextController extends BaseController $this->printTrail('ftscfg'); $this->printTitle($this->lang['strdrop'], 'pg.ftscfg.drop'); - echo '<p>', sprintf($this->lang['strconfdropftsconfig'], $this->misc->printVal($_REQUEST['ftscfg'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropftsconfig'], $this->misc->printVal($_REQUEST['ftscfg'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo '<p><input type="hidden" name="action" value="dropconfig" />'.PHP_EOL; - echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), '" />'.PHP_EOL; - echo '<input type="hidden" name="ftscfg" value="', htmlspecialchars($_REQUEST['ftscfg']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="dropconfig" />' . \PHP_EOL; + echo '<input type="hidden" name="database" value="', \htmlspecialchars($_REQUEST['database']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="ftscfg" value="', \htmlspecialchars($_REQUEST['ftscfg']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropFtsConfiguration($_POST['ftscfg'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strftsconfigdropped']); } else { @@ -327,7 +330,7 @@ class FulltextController extends BaseController } } - public function doDropDict($confirm) + public function doDropDict($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -335,22 +338,23 @@ class FulltextController extends BaseController $this->printTrail('ftscfg'); // TODO: change to smth related to dictionary $this->printTitle($this->lang['strdrop'], 'pg.ftsdict.drop'); - echo '<p>', sprintf($this->lang['strconfdropftsdict'], $this->misc->printVal($_REQUEST['ftsdict'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropftsdict'], $this->misc->printVal($_REQUEST['ftsdict'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo '<p><input type="hidden" name="action" value="dropdict" />'.PHP_EOL; - echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), '" />'.PHP_EOL; - echo '<input type="hidden" name="ftsdict" value="', htmlspecialchars($_REQUEST['ftsdict']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="dropdict" />' . \PHP_EOL; + echo '<input type="hidden" name="database" value="', \htmlspecialchars($_REQUEST['database']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="ftsdict" value="', \htmlspecialchars($_REQUEST['ftsdict']), '" />' . \PHP_EOL; //echo "<input type=\"hidden\" name=\"ftscfg\" value=\"", htmlspecialchars($_REQUEST['ftscfg']), "\" />".PHP_EOL; - echo '<input type="hidden" name="prev_action" value="viewdicts" /></p>'.PHP_EOL; + echo '<input type="hidden" name="prev_action" value="viewdicts" /></p>' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropFtsDictionary($_POST['ftsdict'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doViewDicts($this->lang['strftsdictdropped']); } else { @@ -364,7 +368,7 @@ class FulltextController extends BaseController * * @param mixed $msg */ - public function doCreateConfig($msg = '') + public function doCreateConfig($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -387,71 +391,75 @@ class FulltextController extends BaseController $this->printTitle($this->lang['strftscreateconfig'], 'pg.ftscfg.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; // conf name - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input name=\"formName\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['formName']), "\" /></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formName']), "\" /></td>\n\t</tr>" . \PHP_EOL; // Template - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftstemplate']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftstemplate']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; $tpls = []; $tplsel = ''; + while (!$ftscfgs->EOF) { $data->fieldClean($ftscfgs->fields['schema']); $data->fieldClean($ftscfgs->fields['name']); - $tplname = $ftscfgs->fields['schema'].'.'.$ftscfgs->fields['name']; - $tpls[$tplname] = serialize([ + $tplname = $ftscfgs->fields['schema'] . '.' . $ftscfgs->fields['name']; + $tpls[$tplname] = \serialize([ 'name' => $ftscfgs->fields['name'], 'schema' => $ftscfgs->fields['schema'], ]); - if ($_POST['formTemplate'] == $tpls[$tplname]) { - $tplsel = htmlspecialchars($tpls[$tplname]); + + if ($_POST['formTemplate'] === $tpls[$tplname]) { + $tplsel = \htmlspecialchars($tpls[$tplname]); } $ftscfgs->moveNext(); } echo \PHPPgAdmin\XHtml\HTMLController::printCombo($tpls, 'formTemplate', true, $tplsel, false); - echo "\n\t\t</td>\n\t</tr>".PHP_EOL; + echo "\n\t\t</td>\n\t</tr>" . \PHP_EOL; // Parser - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftsparser']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftsparser']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">" . \PHP_EOL; $ftsparsers_ = []; $ftsparsel = ''; + while (!$ftsparsers->EOF) { $data->fieldClean($ftsparsers->fields['schema']); $data->fieldClean($ftsparsers->fields['name']); - $parsername = $ftsparsers->fields['schema'].'.'.$ftsparsers->fields['name']; + $parsername = $ftsparsers->fields['schema'] . '.' . $ftsparsers->fields['name']; - $ftsparsers_[$parsername] = serialize([ + $ftsparsers_[$parsername] = \serialize([ 'parser' => $ftsparsers->fields['name'], 'schema' => $ftsparsers->fields['schema'], ]); - if ($_POST['formParser'] == $ftsparsers_[$parsername]) { - $ftsparsel = htmlspecialchars($ftsparsers_[$parsername]); + + if ($_POST['formParser'] === $ftsparsers_[$parsername]) { + $ftsparsel = \htmlspecialchars($ftsparsers_[$parsername]); } $ftsparsers->moveNext(); } echo \PHPPgAdmin\XHtml\HTMLController::printCombo($ftsparsers_, 'formParser', true, $ftsparsel, false); - echo "\n\t\t</td>\n\t</tr>".PHP_EOL; + echo "\n\t\t</td>\n\t</tr>" . \PHP_EOL; // Comment - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><textarea name=\"formComment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p>'.PHP_EOL; - echo '<input type="hidden" name="action" value="createconfig" />'.PHP_EOL; - echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), '" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p>' . \PHP_EOL; + echo '<input type="hidden" name="action" value="createconfig" />' . \PHP_EOL; + echo '<input type="hidden" name="database" value="', \htmlspecialchars($_REQUEST['database']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</p>'.PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</p>' . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** @@ -463,32 +471,33 @@ class FulltextController extends BaseController $err = ''; // Check that they've given a name - if ('' == $_POST['formName']) { + if ('' === $_POST['formName']) { $err .= "{$this->lang['strftsconfigneedsname']}<br />"; } - if (('' != $_POST['formParser']) && ('' != $_POST['formTemplate'])) { + if (('' !== $_POST['formParser']) && ('' !== $_POST['formTemplate'])) { $err .= "{$this->lang['strftscantparsercopy']}<br />"; } - if ($err !== '') { + if ('' !== $err) { return $this->doCreateConfig($err); } - if ('' != $_POST['formParser']) { - $formParser = unserialize($_POST['formParser']); + if ('' !== $_POST['formParser']) { + $formParser = \unserialize($_POST['formParser']); } else { $formParser = ''; } - if ('' != $_POST['formTemplate']) { - $formTemplate = unserialize($_POST['formTemplate']); + if ('' !== $_POST['formTemplate']) { + $formTemplate = \unserialize($_POST['formTemplate']); } else { $formTemplate = ''; } $status = $data->createFtsConfiguration($_POST['formName'], $formParser, $formTemplate, $_POST['formComment']); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strftsconfigcreated']); } else { @@ -501,7 +510,7 @@ class FulltextController extends BaseController * * @param mixed $msg */ - public function doAlterConfig($msg = '') + public function doAlterConfig($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -510,7 +519,8 @@ class FulltextController extends BaseController $this->printMsg($msg); $ftscfg = $data->getFtsConfigurationByName($_REQUEST['ftscfg']); - if ($ftscfg->recordCount() > 0) { + + if (0 < $ftscfg->recordCount()) { $this->coalesceArr($_POST, 'formComment', $ftscfg->fields['comment']); $this->coalesceArr($_POST, 'ftscfg', $_REQUEST['ftscfg']); @@ -522,42 +532,43 @@ class FulltextController extends BaseController // Fetch all FTS parsers from the database $ftsparsers = $data->getFtsParsers(); - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; echo "\t\t\t<input name=\"formName\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['formName']), '" />'.PHP_EOL; - echo "\t\t</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formName']), '" />' . \PHP_EOL; + echo "\t\t</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; // Comment - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcomment']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><textarea cols=\"32\" rows=\"3\"name=\"formComment\">", htmlspecialchars($_POST['formComment']), '</textarea></td>'.PHP_EOL; - echo "\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="alterconfig" />'.PHP_EOL; - echo '<input type="hidden" name="ftscfg" value="', htmlspecialchars($_POST['ftscfg']), '" />'.PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcomment']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><textarea cols=\"32\" rows=\"3\"name=\"formComment\">", \htmlspecialchars($_POST['formComment']), '</textarea></td>' . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="alterconfig" />' . \PHP_EOL; + echo '<input type="hidden" name="ftscfg" value="', \htmlspecialchars($_POST['ftscfg']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } /** * Save the form submission containing changes to a FTS configuration. */ - public function doSaveAlterConfig() + public function doSaveAlterConfig(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->updateFtsConfiguration($_POST['ftscfg'], $_POST['formComment'], $_POST['formName']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strftsconfigaltered']); } else { $this->doAlterConfig($this->lang['strftsconfigalteredbad']); @@ -569,7 +580,7 @@ class FulltextController extends BaseController * * @param mixed $msg */ - public function doViewParsers($msg = '') + public function doViewParsers($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -607,7 +618,7 @@ class FulltextController extends BaseController * * @param mixed $msg */ - public function doViewDicts($msg = '') + public function doViewDicts($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -682,7 +693,7 @@ class FulltextController extends BaseController ], ]; - $this->printNavLinks($navlinks, 'fulltext-viewdicts', get_defined_vars()); + $this->printNavLinks($navlinks, 'fulltext-viewdicts', \get_defined_vars()); } /** @@ -691,7 +702,7 @@ class FulltextController extends BaseController * @param mixed $ftscfg * @param mixed $msg */ - public function doViewConfig($ftscfg, $msg = '') + public function doViewConfig($ftscfg, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -700,7 +711,7 @@ class FulltextController extends BaseController $this->printTabs('fulltext', 'ftsconfigs'); $this->printMsg($msg); - echo "<h3>{$this->lang['strftsconfigmap']}</h3>".PHP_EOL; + echo "<h3>{$this->lang['strftsconfigmap']}</h3>" . \PHP_EOL; $map = $data->getFtsConfigurationMap($ftscfg); @@ -778,7 +789,7 @@ class FulltextController extends BaseController ], ]; - $this->printNavLinks($navlinks, 'fulltext-viewconfig', get_defined_vars()); + $this->printNavLinks($navlinks, 'fulltext-viewconfig', \get_defined_vars()); } /** @@ -786,7 +797,7 @@ class FulltextController extends BaseController * * @param mixed $msg */ - public function doCreateDict($msg = '') + public function doCreateDict($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -812,68 +823,70 @@ class FulltextController extends BaseController $this->printTitle($this->lang['strftscreatedict'], 'pg.ftsdict.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input name=\"formName\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['formName']), '" /> ', + \htmlspecialchars($_POST['formName']), '" /> ', '<input type="checkbox" name="formIsTemplate" id="formIsTemplate"', $_POST['formIsTemplate'] ? ' checked="checked" ' : '', " />\n", - "<label for=\"formIsTemplate\">{$this->lang['strftscreatedicttemplate']}</label></td>\n\t</tr>".PHP_EOL; + "<label for=\"formIsTemplate\">{$this->lang['strftscreatedicttemplate']}</label></td>\n\t</tr>" . \PHP_EOL; // Template - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftstemplate']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftstemplate']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; $tpls = []; $tplsel = ''; + while (!$ftstpls->EOF) { $data->fieldClean($ftstpls->fields['schema']); $data->fieldClean($ftstpls->fields['name']); - $tplname = $ftstpls->fields['schema'].'.'.$ftstpls->fields['name']; - $tpls[$tplname] = serialize([ + $tplname = $ftstpls->fields['schema'] . '.' . $ftstpls->fields['name']; + $tpls[$tplname] = \serialize([ 'name' => $ftstpls->fields['name'], 'schema' => $ftstpls->fields['schema'], ]); - if ($_POST['formTemplate'] == $tpls[$tplname]) { - $tplsel = htmlspecialchars($tpls[$tplname]); + + if ($_POST['formTemplate'] === $tpls[$tplname]) { + $tplsel = \htmlspecialchars($tpls[$tplname]); } $ftstpls->moveNext(); } echo \PHPPgAdmin\XHtml\HTMLController::printCombo($tpls, 'formTemplate', true, $tplsel, false); - echo "\n\t\t</td>\n\t</tr>".PHP_EOL; + echo "\n\t\t</td>\n\t</tr>" . \PHP_EOL; // TODO: what about maxlengths? // Lexize - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftslexize']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftslexize']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input name=\"formLexize\" size=\"32\" maxlength=\"1000\" value=\"", - htmlspecialchars($_POST['formLexize']), '" ', isset($_POST['formIsTemplate']) ? '' : ' disabled="disabled" ', - "/></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formLexize']), '" ', isset($_POST['formIsTemplate']) ? '' : ' disabled="disabled" ', + "/></td>\n\t</tr>" . \PHP_EOL; // Init - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftsinit']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftsinit']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input name=\"formInit\" size=\"32\" maxlength=\"1000\" value=\"", - htmlspecialchars($_POST['formInit']), '"', @$_POST['formIsTemplate'] ? '' : ' disabled="disabled" ', - "/></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formInit']), '"', $_POST['formIsTemplate'] ? '' : ' disabled="disabled" ', + "/></td>\n\t</tr>" . \PHP_EOL; // Option - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftsoptionsvalues']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strftsoptionsvalues']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input name=\"formOption\" size=\"32\" maxlength=\"1000\" value=\"", - htmlspecialchars($_POST['formOption']), "\" /></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formOption']), "\" /></td>\n\t</tr>" . \PHP_EOL; // Comment - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><textarea name=\"formComment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p>'.PHP_EOL; - echo '<input type="hidden" name="action" value="createdict" />'.PHP_EOL; - echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), '" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p>' . \PHP_EOL; + echo '<input type="hidden" name="action" value="createdict" />' . \PHP_EOL; + echo '<input type="hidden" name="database" value="', \htmlspecialchars($_REQUEST['database']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</p>'.PHP_EOL; + echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</p>' . \PHP_EOL; echo "</form>\n", - "<script type=\"text/javascript\"> + "<script type=\"text/javascript\"> function templateOpts() { isTpl = document.getElementsByName('formIsTemplate')[0].checked; document.getElementsByName('formTemplate')[0].disabled = isTpl; @@ -885,24 +898,24 @@ class FulltextController extends BaseController document.getElementsByName('formIsTemplate')[0].onchange = templateOpts; templateOpts(); - </script>".PHP_EOL; + </script>" . \PHP_EOL; } /** * Actually creates the new FTS dictionary in the database. */ - public function doSaveCreateDict() + public function doSaveCreateDict(): void { $data = $this->misc->getDatabaseAccessor(); // Check that they've given a name - if ('' == $_POST['formName']) { + if ('' === $_POST['formName']) { $this->doCreateDict($this->lang['strftsdictneedsname']); } else { $this->coalesceArr($_POST, 'formIsTemplate', false); if (isset($_POST['formTemplate'])) { - $formTemplate = unserialize($_POST['formTemplate']); + $formTemplate = \unserialize($_POST['formTemplate']); } else { $formTemplate = ''; } @@ -923,7 +936,7 @@ class FulltextController extends BaseController $_POST['formComment'] ); - if (0 == $status) { + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doViewDicts($this->lang['strftsdictcreated']); } else { @@ -937,7 +950,7 @@ class FulltextController extends BaseController * * @param mixed $msg */ - public function doAlterDict($msg = '') + public function doAlterDict($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -946,51 +959,53 @@ class FulltextController extends BaseController $this->printMsg($msg); $ftsdict = $data->getFtsDictionaryByName($_REQUEST['ftsdict']); - if ($ftsdict->recordCount() > 0) { + + if (0 < $ftsdict->recordCount()) { $this->coalesceArr($_POST, 'formComment', $ftsdict->fields['comment']); $this->coalesceArr($_POST, 'ftsdict', $_REQUEST['ftsdict']); $this->coalesceArr($_POST, 'formName', $_REQUEST['ftsdict']); - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; echo "\t\t\t<input name=\"formName\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['formName']), '" />'.PHP_EOL; - echo "\t\t</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formName']), '" />' . \PHP_EOL; + echo "\t\t</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; // Comment - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcomment']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><textarea cols=\"32\" rows=\"3\"name=\"formComment\">", htmlspecialchars($_POST['formComment']), '</textarea></td>'.PHP_EOL; - echo "\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="alterdict" />'.PHP_EOL; - echo '<input type="hidden" name="ftsdict" value="', htmlspecialchars($_POST['ftsdict']), '" />'.PHP_EOL; - echo '<input type="hidden" name="prev_action" value="viewdicts" /></p>'.PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcomment']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><textarea cols=\"32\" rows=\"3\"name=\"formComment\">", \htmlspecialchars($_POST['formComment']), '</textarea></td>' . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="alterdict" />' . \PHP_EOL; + echo '<input type="hidden" name="ftsdict" value="', \htmlspecialchars($_POST['ftsdict']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="prev_action" value="viewdicts" /></p>' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } /** * Save the form submission containing changes to a FTS dictionary. */ - public function doSaveAlterDict() + public function doSaveAlterDict(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->updateFtsDictionary($_POST['ftsdict'], $_POST['formComment'], $_POST['formName']); - if (0 == $status) { + + if (0 === $status) { $this->doViewDicts($this->lang['strftsdictaltered']); } else { $this->doAlterDict($this->lang['strftsdictalteredbad']); @@ -1002,7 +1017,7 @@ class FulltextController extends BaseController * * @param mixed $confirm */ - public function doDropMapping($confirm) + public function doDropMapping($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -1022,32 +1037,33 @@ class FulltextController extends BaseController $this->printTrail('ftscfg'); // TODO: proper breadcrumbs $this->printTitle($this->lang['strdrop'], 'pg.ftscfg.alter'); - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; // Case of multiaction drop if (isset($_REQUEST['ma'])) { foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfdropftsmapping'], $this->misc->printVal($a['mapping']), $this->misc->printVal($_REQUEST['ftscfg'])), '</p>'.PHP_EOL; - printf('<input type="hidden" name="mapping[]" value="%s" />', htmlspecialchars($a['mapping'])); + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfdropftsmapping'], $this->misc->printVal($a['mapping']), $this->misc->printVal($_REQUEST['ftscfg'])), '</p>' . \PHP_EOL; + \printf('<input type="hidden" name="mapping[]" value="%s" />', \htmlspecialchars($a['mapping'])); } } else { - echo '<p>', sprintf($this->lang['strconfdropftsmapping'], $this->misc->printVal($_REQUEST['mapping']), $this->misc->printVal($_REQUEST['ftscfg'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="mapping" value="', htmlspecialchars($_REQUEST['mapping']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropftsmapping'], $this->misc->printVal($_REQUEST['mapping']), $this->misc->printVal($_REQUEST['ftscfg'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="mapping" value="', \htmlspecialchars($_REQUEST['mapping']), '" />' . \PHP_EOL; } - echo "<input type=\"hidden\" name=\"ftscfg\" value=\"{$_REQUEST['ftscfg']}\" />".PHP_EOL; - echo '<input type="hidden" name="action" value="dropmapping" />'.PHP_EOL; - echo '<input type="hidden" name="prev_action" value="viewconfig" /></p>'.PHP_EOL; + echo "<input type=\"hidden\" name=\"ftscfg\" value=\"{$_REQUEST['ftscfg']}\" />" . \PHP_EOL; + echo '<input type="hidden" name="action" value="dropmapping" />' . \PHP_EOL; + echo '<input type="hidden" name="prev_action" value="viewconfig" /></p>' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { // Case of multiaction drop - if (is_array($_REQUEST['mapping'])) { + if (\is_array($_REQUEST['mapping'])) { $status = $data->changeFtsMapping($_REQUEST['ftscfg'], $_REQUEST['mapping'], 'drop'); - if (0 != $status) { + + if (0 !== $status) { $this->doViewConfig($_REQUEST['ftscfg'], $this->lang['strftsmappingdroppedbad']); return; @@ -1055,7 +1071,8 @@ class FulltextController extends BaseController $this->doViewConfig($_REQUEST['ftscfg'], $this->lang['strftsmappingdropped']); } else { $status = $data->changeFtsMapping($_REQUEST['ftscfg'], [$_REQUEST['mapping']], 'drop'); - if (0 == $status) { + + if (0 === $status) { $this->doViewConfig($_REQUEST['ftscfg'], $this->lang['strftsmappingdropped']); } else { $this->doViewConfig($_REQUEST['ftscfg'], $this->lang['strftsmappingdroppedbad']); @@ -1064,7 +1081,7 @@ class FulltextController extends BaseController } } - public function doAlterMapping($msg = '') + public function doAlterMapping($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $this->printTrail('ftscfg'); @@ -1072,83 +1089,87 @@ class FulltextController extends BaseController $this->printMsg($msg); $ftsdicts = $data->getFtsDictionaries(); - if ($ftsdicts->recordCount() > 0) { - $this->coalesceArr($_POST, 'formMapping', @$_REQUEST['mapping']); + + if (0 < $ftsdicts->recordCount()) { + $this->coalesceArr($_POST, 'formMapping', $_REQUEST['mapping']); $this->coalesceArr($_POST, 'formDictionary', ''); $this->coalesceArr($_POST, 'ftscfg', $_REQUEST['ftscfg']); - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data left required\">{$this->lang['strftsmapping']}</th>".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data left required\">{$this->lang['strftsmapping']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; $ma_mappings = []; // Case of multiaction drop if (isset($_REQUEST['ma'])) { $ma_mappings_names = []; + foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - printf('<input type="hidden" name="formMapping[]" value="%s" />', htmlspecialchars($a['mapping'])); + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + \printf('<input type="hidden" name="formMapping[]" value="%s" />', \htmlspecialchars($a['mapping'])); $ma_mappings[] = $data->getFtsMappingByName($_POST['ftscfg'], $a['mapping']); $ma_mappings_names[] = $a['mapping']; } - echo implode(', ', $ma_mappings_names); + echo \implode(', ', $ma_mappings_names); } else { $mapping = $data->getFtsMappingByName($_POST['ftscfg'], $_POST['formMapping']); echo $mapping->fields['name']; - echo '<input type="hidden" name="formMapping" value="', htmlspecialchars($_POST['formMapping']), '" />'.PHP_EOL; + echo '<input type="hidden" name="formMapping" value="', \htmlspecialchars($_POST['formMapping']), '" />' . \PHP_EOL; } - echo "\t\t</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "\t\t</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; // Dictionary - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data left required\">{$this->lang['strftsdict']}</th>".PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data left required\">{$this->lang['strftsdict']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; - echo "\t\t\t<select name=\"formDictionary\">".PHP_EOL; + echo "\t\t\t<select name=\"formDictionary\">" . \PHP_EOL; + while (!$ftsdicts->EOF) { - $ftsdict = htmlspecialchars($ftsdicts->fields['name']); + $ftsdict = \htmlspecialchars($ftsdicts->fields['name']); echo "\t\t\t\t<option value=\"{$ftsdict}\"", ( - $ftsdict == $_POST['formDictionary'] - || $ftsdict == @$mapping->fields['dictionaries'] - || $ftsdict == @$ma_mappings[0]->fields['dictionaries'] - ) ? ' selected="selected"' : '', ">{$ftsdict}</option>".PHP_EOL; + $ftsdict === $_POST['formDictionary'] + || $ftsdict === $mapping->fields['dictionaries'] + || $ftsdict === $ma_mappings[0]->fields['dictionaries'] + ) ? ' selected="selected"' : '', ">{$ftsdict}</option>" . \PHP_EOL; $ftsdicts->moveNext(); } - echo "\t\t</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "\t\t</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="altermapping" />'.PHP_EOL; - echo '<input type="hidden" name="ftscfg" value="', htmlspecialchars($_POST['ftscfg']), '" />'.PHP_EOL; - echo '<input type="hidden" name="prev_action" value="viewconfig" /></p>'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="altermapping" />' . \PHP_EOL; + echo '<input type="hidden" name="ftscfg" value="', \htmlspecialchars($_POST['ftscfg']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="prev_action" value="viewconfig" /></p>' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strftsnodictionaries']}</p>".PHP_EOL; + echo "<p>{$this->lang['strftsnodictionaries']}</p>" . \PHP_EOL; } } /** * Save the form submission containing changes to a FTS mapping. */ - public function doSaveAlterMapping() + public function doSaveAlterMapping(): void { $data = $this->misc->getDatabaseAccessor(); - $mappingArray = (is_array($_POST['formMapping']) ? $_POST['formMapping'] : [$_POST['formMapping']]); + $mappingArray = (\is_array($_POST['formMapping']) ? $_POST['formMapping'] : [$_POST['formMapping']]); $status = $data->changeFtsMapping($_POST['ftscfg'], $mappingArray, 'alter', $_POST['formDictionary']); - if (0 == $status) { + + if (0 === $status) { $this->doViewConfig($_POST['ftscfg'], $this->lang['strftsmappingaltered']); } else { $this->doAlterMapping($this->lang['strftsmappingalteredbad']); @@ -1160,7 +1181,7 @@ class FulltextController extends BaseController * * @param mixed $msg */ - public function doAddMapping($msg = '') + public function doAddMapping($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -1169,7 +1190,8 @@ class FulltextController extends BaseController $this->printMsg($msg); $ftsdicts = $data->getFtsDictionaries(); - if ($ftsdicts->recordCount() > 0) { + + if (0 < $ftsdicts->recordCount()) { $this->coalesceArr($_POST, 'formMapping', ''); $this->coalesceArr($_POST, 'formDictionary', ''); @@ -1178,60 +1200,63 @@ class FulltextController extends BaseController $mappings = $data->getFtsMappings($_POST['ftscfg']); - echo '<form action="'.\SUBFOLDER.'/src/views/fulltext" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data left required\">{$this->lang['strftsmapping']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/fulltext" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data left required\">{$this->lang['strftsmapping']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; - echo "\t\t\t<select name=\"formMapping\">".PHP_EOL; + echo "\t\t\t<select name=\"formMapping\">" . \PHP_EOL; + while (!$mappings->EOF) { - $mapping = htmlspecialchars($mappings->fields['name']); - $mapping_desc = htmlspecialchars($mappings->fields['description']); + $mapping = \htmlspecialchars($mappings->fields['name']); + $mapping_desc = \htmlspecialchars($mappings->fields['description']); echo "\t\t\t\t<option value=\"{$mapping}\"", - $mapping == $_POST['formMapping'] ? ' selected="selected"' : '', ">{$mapping}", $mapping_desc ? " - {$mapping_desc}" : '', '</option>'.PHP_EOL; + $mapping === $_POST['formMapping'] ? ' selected="selected"' : '', ">{$mapping}", $mapping_desc ? " - {$mapping_desc}" : '', '</option>' . \PHP_EOL; $mappings->moveNext(); } - echo "\t\t</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "\t\t</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; // Dictionary - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data left required\">{$this->lang['strftsdict']}</th>".PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data left required\">{$this->lang['strftsdict']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; - echo "\t\t\t<select name=\"formDictionary\">".PHP_EOL; + echo "\t\t\t<select name=\"formDictionary\">" . \PHP_EOL; + while (!$ftsdicts->EOF) { - $ftsdict = htmlspecialchars($ftsdicts->fields['name']); + $ftsdict = \htmlspecialchars($ftsdicts->fields['name']); echo "\t\t\t\t<option value=\"{$ftsdict}\"", - $ftsdict == $_POST['formDictionary'] ? ' selected="selected"' : '', ">{$ftsdict}</option>".PHP_EOL; + $ftsdict === $_POST['formDictionary'] ? ' selected="selected"' : '', ">{$ftsdict}</option>" . \PHP_EOL; $ftsdicts->moveNext(); } - echo "\t\t</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "\t\t</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="addmapping" />'.PHP_EOL; - echo '<input type="hidden" name="ftscfg" value="', htmlspecialchars($_POST['ftscfg']), '" />'.PHP_EOL; - echo '<input type="hidden" name="prev_action" value="viewconfig" /></p>'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="addmapping" />' . \PHP_EOL; + echo '<input type="hidden" name="ftscfg" value="', \htmlspecialchars($_POST['ftscfg']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="prev_action" value="viewconfig" /></p>' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"add\" value=\"{$this->lang['stradd']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"add\" value=\"{$this->lang['stradd']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strftsnodictionaries']}</p>".PHP_EOL; + echo "<p>{$this->lang['strftsnodictionaries']}</p>" . \PHP_EOL; } } /** * Save the form submission containing parameters of a new FTS mapping. */ - public function doSaveAddMapping() + public function doSaveAddMapping(): void { $data = $this->misc->getDatabaseAccessor(); - $mappingArray = (is_array($_POST['formMapping']) ? $_POST['formMapping'] : [$_POST['formMapping']]); + $mappingArray = (\is_array($_POST['formMapping']) ? $_POST['formMapping'] : [$_POST['formMapping']]); $status = $data->changeFtsMapping($_POST['ftscfg'], $mappingArray, 'add', $_POST['formDictionary']); - if (0 == $status) { + + if (0 === $status) { $this->doViewConfig($_POST['ftscfg'], $this->lang['strftsmappingadded']); } else { $this->doAddMapping($this->lang['strftsmappingaddedbad']); diff --git a/src/controllers/FunctionsController.php b/src/controllers/FunctionsController.php index 31747b9d..faeca0fc 100644 --- a/src/controllers/FunctionsController.php +++ b/src/controllers/FunctionsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,12 +13,11 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class FunctionsController extends BaseController { - public $table_place = 'functions-functions'; + public $table_place = 'functions-functions'; + public $controller_title = 'strfunctions'; /** @@ -23,13 +25,14 @@ class FunctionsController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } $header_template = 'header_datatables.twig'; $footer_template = 'footer.twig'; - ob_start(); + \ob_start(); + switch ($this->action) { case 'save_create': if (isset($_POST['cancel'])) { @@ -89,7 +92,7 @@ class FunctionsController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $this->printHeader($this->headerTitle(), null, true, $header_template); $this->printBody(); @@ -102,7 +105,7 @@ class FunctionsController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -116,7 +119,7 @@ class FunctionsController extends BaseController 'function' => [ 'title' => $this->lang['strfunction'], 'field' => Decorator::field('proproto'), - 'url' => \SUBFOLDER."/redirect/function?action=properties&{$this->misc->href}&", + 'url' => self::SUBFOLDER . "/redirect/function?action=properties&{$this->misc->href}&", 'vars' => ['function' => 'proproto', 'function_oid' => 'prooid'], ], 'returns' => [ @@ -192,110 +195,6 @@ class FunctionsController extends BaseController $this->_printNavLinks('functions-functions'); } - private function _printNavLinks($place, $func_full = '') - { - if ($place === 'functions-properties') { - $navlinks = [ - 'showall' => [ - 'attr' => [ - 'href' => [ - 'url' => 'functions', - 'urlvars' => [ - 'server' => $_REQUEST['server'], - 'database' => $_REQUEST['database'], - 'schema' => $_REQUEST['schema'], - ], - ], - ], - 'content' => $this->lang['strshowallfunctions'], - ], - 'alter' => [ - 'attr' => [ - 'href' => [ - 'url' => 'functions', - 'urlvars' => [ - 'action' => 'edit', - 'server' => $_REQUEST['server'], - 'database' => $_REQUEST['database'], - 'schema' => $_REQUEST['schema'], - 'function' => $_REQUEST['function'], - 'function_oid' => $_REQUEST['function_oid'], - ], - ], - ], - 'content' => $this->lang['stralter'], - ], - 'drop' => [ - 'attr' => [ - 'href' => [ - 'url' => 'functions', - 'urlvars' => [ - 'action' => 'confirm_drop', - 'server' => $_REQUEST['server'], - 'database' => $_REQUEST['database'], - 'schema' => $_REQUEST['schema'], - 'function' => $func_full, - 'function_oid' => $_REQUEST['function_oid'], - ], - ], - ], - 'content' => $this->lang['strdrop'], - ], - ]; - } elseif ($place === 'functions-functions') { - $navlinks = [ - 'createpl' => [ - 'attr' => [ - 'href' => [ - 'url' => 'functions', - 'urlvars' => [ - 'action' => 'create', - 'server' => $_REQUEST['server'], - 'database' => $_REQUEST['database'], - 'schema' => $_REQUEST['schema'], - ], - ], - ], - 'content' => $this->lang['strcreateplfunction'], - ], - 'createinternal' => [ - 'attr' => [ - 'href' => [ - 'url' => 'functions', - 'urlvars' => [ - 'action' => 'create', - 'language' => 'internal', - 'server' => $_REQUEST['server'], - 'database' => $_REQUEST['database'], - 'schema' => $_REQUEST['schema'], - ], - ], - ], - 'content' => $this->lang['strcreateinternalfunction'], - ], - 'createc' => [ - 'attr' => [ - 'href' => [ - 'url' => 'functions', - 'urlvars' => [ - 'action' => 'create', - 'language' => 'C', - 'server' => $_REQUEST['server'], - 'database' => $_REQUEST['database'], - 'schema' => $_REQUEST['schema'], - ], - ], - ], - 'content' => $this->lang['strcreatecfunction'], - ], - ]; - } else { - return; - } - - $this->printNavLinks($navlinks, $place, get_defined_vars()); - } - /** * Generate XML for the browser tree. */ @@ -330,19 +229,20 @@ class FunctionsController extends BaseController /** * Function to save after editing a function. */ - public function doSaveEdit() + public function doSaveEdit(): void { $data = $this->misc->getDatabaseAccessor(); - $fnlang = strtolower($_POST['original_lang']); + $fnlang = \mb_strtolower($_POST['original_lang']); - if ('c' == $fnlang) { + if ('c' === $fnlang) { $def = [$_POST['formObjectFile'], $_POST['formLinkSymbol']]; - } elseif ('internal' == $fnlang) { + } elseif ('internal' === $fnlang) { $def = $_POST['formLinkSymbol']; } else { $def = $_POST['formDefinition']; } + if (!$data->hasFunctionAlterSchema()) { $_POST['formFuncSchema'] = ''; } @@ -360,15 +260,15 @@ class FunctionsController extends BaseController $_POST['formFuncOwn'], $_POST['original_schema'], $_POST['formFuncSchema'], - isset($_POST['formCost']) ? $_POST['formCost'] : null, - isset($_POST['formRows']) ? $_POST['formRows'] : 0, + $_POST['formCost'] ?? null, + $_POST['formRows'] ?? 0, $_POST['formComment'] ); - if (0 == $status) { + if (0 === $status) { // If function has had schema altered, need to change to the new schema // and reload the browser frame. - if (!empty($_POST['formFuncSchema']) && ($_POST['formFuncSchema'] != $_POST['original_schema'])) { + if (!empty($_POST['formFuncSchema']) && ($_POST['formFuncSchema'] !== $_POST['original_schema'])) { // Jump them to the new function schema $this->misc->setCurrentSchema($_POST['formFuncSchema']); // Force a browser reload @@ -380,62 +280,12 @@ class FunctionsController extends BaseController } } - private function _getNamedParamsArgs($data, $fndata) - { - if (isset($fndata->fields['proallarguments'])) { - $args_arr = $data->phpArray($fndata->fields['proallarguments']); - } else { - $args_arr = explode(', ', $fndata->fields['proarguments']); - } - $names_arr = $data->phpArray($fndata->fields['proargnames']); - $modes_arr = $data->phpArray($fndata->fields['proargmodes']); - $args = ''; - $args_arr_size = sizeof($args_arr); - for ($i = 0; $i < $args_arr_size; ++$i) { - if (0 != $i) { - $args .= ', '; - } - - if (isset($modes_arr[$i])) { - switch ($modes_arr[$i]) { - case 'i': - $args .= ' IN '; - - break; - case 'o': - $args .= ' OUT '; - - break; - case 'b': - $args .= ' INOUT '; - - break; - case 'v': - $args .= ' VARIADIC '; - - break; - case 't': - $args .= ' TABLE '; - - break; - } - } - if (isset($names_arr[$i]) && '' != $names_arr[$i]) { - $data->fieldClean($names_arr[$i]); - $args .= '"'.$names_arr[$i].'" '; - } - $args .= $args_arr[$i]; - } - - return $args; - } - /** * Function to allow editing of a Function. * * @param mixed $msg */ - public function doEdit($msg = '') + public function doEdit($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -446,8 +296,8 @@ class FunctionsController extends BaseController $fndata = $data->getFunction($_REQUEST['function_oid']); - if ($fndata->recordCount() <= 0) { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + if (0 >= $fndata->recordCount()) { + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; return; } @@ -483,138 +333,146 @@ class FunctionsController extends BaseController $args = $fndata->fields['proarguments']; } - echo '<form action="'.\SUBFOLDER.'/src/views/functions" method="post">'.PHP_EOL; - echo '<table style="width: 95%">'.PHP_EOL; - echo '<tr>'.PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strschema']}</th>".PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strfunction']}</th>".PHP_EOL; - echo "<th class=\"data\">{$this->lang['strarguments']}</th>".PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strreturns']}</th>".PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strproglanguage']}</th>".PHP_EOL; - echo '</tr>'.PHP_EOL; - - echo '<tr>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/functions" method="post">' . \PHP_EOL; + echo '<table style="width: 95%">' . \PHP_EOL; + echo '<tr>' . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strschema']}</th>" . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strfunction']}</th>" . \PHP_EOL; + echo "<th class=\"data\">{$this->lang['strarguments']}</th>" . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strreturns']}</th>" . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strproglanguage']}</th>" . \PHP_EOL; + echo '</tr>' . \PHP_EOL; + + echo '<tr>' . \PHP_EOL; echo '<td class="data1">'; - echo '<input type="hidden" name="original_schema" value="', htmlspecialchars($fndata->fields['proschema']), '" />'.PHP_EOL; + echo '<input type="hidden" name="original_schema" value="', \htmlspecialchars($fndata->fields['proschema']), '" />' . \PHP_EOL; + if ($data->hasFunctionAlterSchema()) { $schemas = $data->getSchemas(); echo '<select name="formFuncSchema">'; + while (!$schemas->EOF) { $schema = $schemas->fields['nspname']; - echo '<option value="', htmlspecialchars($schema), '"', - ($schema == $_POST['formFuncSchema']) ? ' selected="selected"' : '', '>', htmlspecialchars($schema), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($schema), '"', + ($schema === $_POST['formFuncSchema']) ? ' selected="selected"' : '', '>', \htmlspecialchars($schema), '</option>' . \PHP_EOL; $schemas->moveNext(); } - echo '</select>'.PHP_EOL; + echo '</select>' . \PHP_EOL; } else { echo $fndata->fields['proschema']; } - echo '</td>'.PHP_EOL; + echo '</td>' . \PHP_EOL; echo '<td class="data1">'; - echo '<input type="hidden" name="original_function" value="', htmlspecialchars($fndata->fields['proname']), '" />'.PHP_EOL; - echo "<input name=\"formFunction\" style=\"width: 100%; box-sizing: border-box;\" maxlength=\"{$data->_maxNameLen}\" value=\"", htmlspecialchars($_POST['formFunction']), '" />'; - echo '</td>'.PHP_EOL; + echo '<input type="hidden" name="original_function" value="', \htmlspecialchars($fndata->fields['proname']), '" />' . \PHP_EOL; + echo "<input name=\"formFunction\" style=\"width: 100%; box-sizing: border-box;\" maxlength=\"{$data->_maxNameLen}\" value=\"", \htmlspecialchars($_POST['formFunction']), '" />'; + echo '</td>' . \PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($args), PHP_EOL; - echo '<input type="hidden" name="original_arguments" value="', htmlspecialchars($args), '" />'.PHP_EOL; - echo '</td>'.PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($args), \PHP_EOL; + echo '<input type="hidden" name="original_arguments" value="', \htmlspecialchars($args), '" />' . \PHP_EOL; + echo '</td>' . \PHP_EOL; echo '<td class="data1">'; + if ($fndata->fields['proretset']) { echo 'setof '; } - echo $this->misc->printVal($fndata->fields['proresult']), PHP_EOL; - echo '<input type="hidden" name="original_returns" value="', htmlspecialchars($fndata->fields['proresult']), '" />'.PHP_EOL; + echo $this->misc->printVal($fndata->fields['proresult']), \PHP_EOL; + echo '<input type="hidden" name="original_returns" value="', \htmlspecialchars($fndata->fields['proresult']), '" />' . \PHP_EOL; + if ($fndata->fields['proretset']) { - echo '<input type="hidden" name="original_setof" value="yes" />'.PHP_EOL; + echo '<input type="hidden" name="original_setof" value="yes" />' . \PHP_EOL; } - echo '</td>'.PHP_EOL; + echo '</td>' . \PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($fndata->fields['prolanguage']), PHP_EOL; - echo '<input type="hidden" name="original_lang" value="', htmlspecialchars($fndata->fields['prolanguage']), '" />'.PHP_EOL; - echo '</td>'.PHP_EOL; - echo '</tr>'.PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($fndata->fields['prolanguage']), \PHP_EOL; + echo '<input type="hidden" name="original_lang" value="', \htmlspecialchars($fndata->fields['prolanguage']), '" />' . \PHP_EOL; + echo '</td>' . \PHP_EOL; + echo '</tr>' . \PHP_EOL; - $fnlang = strtolower($fndata->fields['prolanguage']); - if ('c' == $fnlang) { - echo "<tr><th class=\"data required\" colspan=\"2\">{$this->lang['strobjectfile']}</th>".PHP_EOL; - echo "<th class=\"data\" colspan=\"2\">{$this->lang['strlinksymbol']}</th></tr>".PHP_EOL; + $fnlang = \mb_strtolower($fndata->fields['prolanguage']); + + if ('c' === $fnlang) { + echo "<tr><th class=\"data required\" colspan=\"2\">{$this->lang['strobjectfile']}</th>" . \PHP_EOL; + echo "<th class=\"data\" colspan=\"2\">{$this->lang['strlinksymbol']}</th></tr>" . \PHP_EOL; echo '<tr><td class="data1" colspan="2"><input type="text" name="formObjectFile" style="width:100%" value="', - htmlspecialchars($_POST['formObjectFile']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_POST['formObjectFile']), '" /></td>' . \PHP_EOL; echo '<td class="data1" colspan="2"><input type="text" name="formLinkSymbol" style="width:100%" value="', - htmlspecialchars($_POST['formLinkSymbol']), '" /></td></tr>'.PHP_EOL; - } elseif ('internal' == $fnlang) { - echo "<tr><th class=\"data\" colspan=\"5\">{$this->lang['strlinksymbol']}</th></tr>".PHP_EOL; + \htmlspecialchars($_POST['formLinkSymbol']), '" /></td></tr>' . \PHP_EOL; + } elseif ('internal' === $fnlang) { + echo "<tr><th class=\"data\" colspan=\"5\">{$this->lang['strlinksymbol']}</th></tr>" . \PHP_EOL; echo '<tr><td class="data1" colspan="5"><input type="text" name="formLinkSymbol" style="width:100%" value="', - htmlspecialchars($_POST['formLinkSymbol']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formLinkSymbol']), '" /></td></tr>' . \PHP_EOL; } else { - echo "<tr><th class=\"data required\" colspan=\"5\">{$this->lang['strdefinition']}</th></tr>".PHP_EOL; + echo "<tr><th class=\"data required\" colspan=\"5\">{$this->lang['strdefinition']}</th></tr>" . \PHP_EOL; echo '<tr><td class="data1" colspan="5">'; - $textarea_id = ($fnlang === 'sql' || $fnlang === 'plpgsql') ? 'query' : 'formDefinition'; - echo '<textarea style="width:100%;" rows="20" cols="50" id="'.$textarea_id.'" name="formDefinition">'; - echo htmlspecialchars($_POST['formDefinition']); - echo '</textarea></td></tr>'.PHP_EOL; + $textarea_id = ('sql' === $fnlang || 'plpgsql' === $fnlang) ? 'query' : 'formDefinition'; + echo '<textarea style="width:100%;" rows="20" cols="50" id="' . $textarea_id . '" name="formDefinition">'; + echo \htmlspecialchars($_POST['formDefinition']); + echo '</textarea></td></tr>' . \PHP_EOL; } // Display function comment - echo "<tr><th class=\"data\" colspan=\"5\">{$this->lang['strcomment']}</th></tr>".PHP_EOL; + echo "<tr><th class=\"data\" colspan=\"5\">{$this->lang['strcomment']}</th></tr>" . \PHP_EOL; echo '<tr><td class="data1" colspan="5">'; echo '<textarea style="width:100%;" name="formComment" rows="3" cols="50">'; - echo htmlspecialchars($_POST['formComment']); - echo '</textarea></td></tr>'.PHP_EOL; + echo \htmlspecialchars($_POST['formComment']); + echo '</textarea></td></tr>' . \PHP_EOL; // Display function cost options if ($data->hasFunctionCosting()) { - echo "<tr><th class=\"data required\" colspan=\"5\">{$this->lang['strfunctioncosting']}</th></tr>".PHP_EOL; - echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strexecutioncost']}: <input name=\"formCost\" size=\"16\" value=\"". - htmlspecialchars($_POST['formCost']).'" /></td>'; + echo "<tr><th class=\"data required\" colspan=\"5\">{$this->lang['strfunctioncosting']}</th></tr>" . \PHP_EOL; + echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strexecutioncost']}: <input name=\"formCost\" size=\"16\" value=\"" . + \htmlspecialchars($_POST['formCost']) . '" /></td>'; echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strresultrows']}: <input name=\"formRows\" size=\"16\" value=\"", - htmlspecialchars($_POST['formRows']), '"', (!$fndata->fields['proretset']) ? 'disabled' : '', '/></td>'; + \htmlspecialchars($_POST['formRows']), '"', (!$fndata->fields['proretset']) ? 'disabled' : '', '/></td>'; } // Display function properties - if (is_array($data->funcprops) && sizeof($data->funcprops) > 0) { - echo "<tr><th class=\"data\" colspan=\"5\">{$this->lang['strproperties']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1" colspan="5">'.PHP_EOL; + if (\is_array($data->funcprops) && 0 < \count($data->funcprops)) { + echo "<tr><th class=\"data\" colspan=\"5\">{$this->lang['strproperties']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1" colspan="5">' . \PHP_EOL; $i = 0; + foreach ($data->funcprops as $k => $v) { - echo "<select name=\"formProperties[{$i}]\">".PHP_EOL; + echo "<select name=\"formProperties[{$i}]\">" . \PHP_EOL; + foreach ($v as $p) { - echo '<option value="', htmlspecialchars($p), '"', - ($_POST['formProperties'][$i] == $p) ? ' selected="selected"' : '', - '>', $this->misc->printVal($p), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($p), '"', + ($_POST['formProperties'][$i] === $p) ? ' selected="selected"' : '', + '>', $this->misc->printVal($p), '</option>' . \PHP_EOL; } - echo '</select><br />'.PHP_EOL; + echo '</select><br />' . \PHP_EOL; ++$i; } - echo '</td></tr>'.PHP_EOL; + echo '</td></tr>' . \PHP_EOL; } // function owner if ($data->hasFunctionAlterOwner()) { $users = $data->getUsers(); echo "<tr><td class=\"data1\" colspan=\"5\">{$this->lang['strowner']}: <select name=\"formFuncOwn\">"; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $_POST['formFuncOwn']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $_POST['formFuncOwn']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select>'.PHP_EOL; - echo '<input type="hidden" name="original_owner" value="', htmlspecialchars($fndata->fields['proowner']), '" />'.PHP_EOL; - echo '</td></tr>'.PHP_EOL; + echo '</select>' . \PHP_EOL; + echo '<input type="hidden" name="original_owner" value="', \htmlspecialchars($fndata->fields['proowner']), '" />' . \PHP_EOL; + echo '</td></tr>' . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_edit" />'.PHP_EOL; - echo '<input type="hidden" name="function" value="', htmlspecialchars($_REQUEST['function']), '" />'.PHP_EOL; - echo '<input type="hidden" name="function_oid" value="', htmlspecialchars($_REQUEST['function_oid']), '" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_edit" />' . \PHP_EOL; + echo '<input type="hidden" name="function" value="', \htmlspecialchars($_REQUEST['function']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="function_oid" value="', \htmlspecialchars($_REQUEST['function_oid']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** @@ -633,43 +491,44 @@ class FunctionsController extends BaseController $this->printTabs('function', 'export'); $this->printTitle($this->lang['strproperties'], 'pg.function'); - $fname = str_replace(' ', '', $f); + $fname = \str_replace(' ', '', $f); $funcdata = $data->getFunctionDef($function_oid); $func_full = ''; - if ($funcdata->recordCount() <= 0) { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + + if (0 >= $funcdata->recordCount()) { + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; return $this->_printNavLinks('functions-properties', $func_full); } - echo '<table style="width: 95%">'.PHP_EOL; + echo '<table style="width: 95%">' . \PHP_EOL; - $fnlang = strtolower($funcdata->fields['prolanguage']); + $fnlang = \mb_strtolower($funcdata->fields['prolanguage']); echo '<tr><td class="data1" colspan="4">'; - echo sprintf('<pre><code class="sql hljs">%s', PHP_EOL); + echo \sprintf('<pre><code class="sql hljs">%s', \PHP_EOL); - echo sprintf('%s--%s', PHP_EOL, PHP_EOL); - echo sprintf('-- Name: %s; Type: FUNCTION; Schema: %s; Owner: %s', $fname, $funcdata->fields['nspname'], $funcdata->fields['relowner']); - echo sprintf('%s--%s%s', PHP_EOL, PHP_EOL, PHP_EOL); + echo \sprintf('%s--%s', \PHP_EOL, \PHP_EOL); + echo \sprintf('-- Name: %s; Type: FUNCTION; Schema: %s; Owner: %s', $fname, $funcdata->fields['nspname'], $funcdata->fields['relowner']); + echo \sprintf('%s--%s%s', \PHP_EOL, \PHP_EOL, \PHP_EOL); - echo sprintf('%s;', $funcdata->fields['pg_get_functiondef']); + echo \sprintf('%s;', $funcdata->fields['pg_get_functiondef']); - echo sprintf('%s%sALTER FUNCTION %s OWNER TO %s;%s', PHP_EOL, PHP_EOL, $fname, $funcdata->fields['relowner'], PHP_EOL); + echo \sprintf('%s%sALTER FUNCTION %s OWNER TO %s;%s', \PHP_EOL, \PHP_EOL, $fname, $funcdata->fields['relowner'], \PHP_EOL); // Show comment if any if (null !== $funcdata->fields['relcomment']) { - echo sprintf('%s--%s', PHP_EOL, PHP_EOL); - echo sprintf('-- Name: %s; Type: COMMENT; Schema: %s; Owner: %s', $fname, $funcdata->fields['nspname'], $funcdata->fields['relowner']); - echo sprintf('%s--%s%s', PHP_EOL, PHP_EOL, PHP_EOL); - echo sprintf("%sCOMMENT ON FUNCTION %s.%s IS '%s';%s", PHP_EOL, $funcdata->fields['nspname'], $fname, $funcdata->fields['relcomment'], PHP_EOL); + echo \sprintf('%s--%s', \PHP_EOL, \PHP_EOL); + echo \sprintf('-- Name: %s; Type: COMMENT; Schema: %s; Owner: %s', $fname, $funcdata->fields['nspname'], $funcdata->fields['relowner']); + echo \sprintf('%s--%s%s', \PHP_EOL, \PHP_EOL, \PHP_EOL); + echo \sprintf("%sCOMMENT ON FUNCTION %s.%s IS '%s';%s", \PHP_EOL, $funcdata->fields['nspname'], $fname, $funcdata->fields['relcomment'], \PHP_EOL); //echo '<p class="comment">', $this->misc->printVal($funcdata->fields['relcomment']), '</p>' . PHP_EOL; } - echo sprintf('%s</code></pre>', PHP_EOL); + echo \sprintf('%s</code></pre>', \PHP_EOL); - echo '</td></tr>'.PHP_EOL; + echo '</td></tr>' . \PHP_EOL; - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; return $this->_printNavLinks('functions-properties', $func_full); } @@ -690,8 +549,9 @@ class FunctionsController extends BaseController $funcdata = $data->getFunction($_REQUEST['function_oid']); $func_full = ''; - if ($funcdata->recordCount() <= 0) { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + + if (0 >= $funcdata->recordCount()) { + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; return $this->_printNavLinks('functions-properties', $func_full); } @@ -700,66 +560,69 @@ class FunctionsController extends BaseController // Show comment if any if (null !== $funcdata->fields['procomment']) { - echo '<p class="comment">', $this->misc->printVal($funcdata->fields['procomment']), '</p>'.PHP_EOL; + echo '<p class="comment">', $this->misc->printVal($funcdata->fields['procomment']), '</p>' . \PHP_EOL; } $funcdata->fields['proretset'] = $data->phpBool($funcdata->fields['proretset']); - $func_full = $funcdata->fields['proname'].'('.$funcdata->fields['proarguments'].')'; + $func_full = $funcdata->fields['proname'] . '(' . $funcdata->fields['proarguments'] . ')'; - echo '<table style="width: 95%">'.PHP_EOL; + echo '<table style="width: 95%">' . \PHP_EOL; - echo sprintf('<tr><th class="data">%s</th>%s', $this->lang['strfunction'], PHP_EOL); - echo sprintf('<th class="data">%s</th>%s', $this->lang['strarguments'], PHP_EOL); - echo sprintf('<th class="data">%s</th>%s', $this->lang['strreturns'], PHP_EOL); - echo sprintf('<th class="data">%s</th></tr>%s', $this->lang['strproglanguage'], PHP_EOL); + echo \sprintf('<tr><th class="data">%s</th>%s', $this->lang['strfunction'], \PHP_EOL); + echo \sprintf('<th class="data">%s</th>%s', $this->lang['strarguments'], \PHP_EOL); + echo \sprintf('<th class="data">%s</th>%s', $this->lang['strreturns'], \PHP_EOL); + echo \sprintf('<th class="data">%s</th></tr>%s', $this->lang['strproglanguage'], \PHP_EOL); - echo '<tr><td class="data1">', $this->misc->printVal($funcdata->fields['proname']), '</td>'.PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($args), '</td>'.PHP_EOL; + echo '<tr><td class="data1">', $this->misc->printVal($funcdata->fields['proname']), '</td>' . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($args), '</td>' . \PHP_EOL; echo '<td class="data1">'; + if ($funcdata->fields['proretset']) { echo 'setof '; } - echo $this->misc->printVal($funcdata->fields['proresult']), '</td>'.PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($funcdata->fields['prolanguage']), '</td></tr>'.PHP_EOL; - - $fnlang = strtolower($funcdata->fields['prolanguage']); - if ('c' == $fnlang) { - echo "<tr><th class=\"data\" colspan=\"2\">{$this->lang['strobjectfile']}</th>".PHP_EOL; - echo "<th class=\"data\" colspan=\"2\">{$this->lang['strlinksymbol']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1" colspan="2">', $this->misc->printVal($funcdata->fields['probin']), '</td>'.PHP_EOL; - echo '<td class="data1" colspan="2">', $this->misc->printVal($funcdata->fields['prosrc']), '</td></tr>'.PHP_EOL; - } elseif ('internal' == $fnlang) { - echo "<tr><th class=\"data\" colspan=\"4\">{$this->lang['strlinksymbol']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1" colspan="4">', $this->misc->printVal($funcdata->fields['prosrc']), '</td></tr>'.PHP_EOL; + echo $this->misc->printVal($funcdata->fields['proresult']), '</td>' . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($funcdata->fields['prolanguage']), '</td></tr>' . \PHP_EOL; + + $fnlang = \mb_strtolower($funcdata->fields['prolanguage']); + + if ('c' === $fnlang) { + echo "<tr><th class=\"data\" colspan=\"2\">{$this->lang['strobjectfile']}</th>" . \PHP_EOL; + echo "<th class=\"data\" colspan=\"2\">{$this->lang['strlinksymbol']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1" colspan="2">', $this->misc->printVal($funcdata->fields['probin']), '</td>' . \PHP_EOL; + echo '<td class="data1" colspan="2">', $this->misc->printVal($funcdata->fields['prosrc']), '</td></tr>' . \PHP_EOL; + } elseif ('internal' === $fnlang) { + echo "<tr><th class=\"data\" colspan=\"4\">{$this->lang['strlinksymbol']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1" colspan="4">', $this->misc->printVal($funcdata->fields['prosrc']), '</td></tr>' . \PHP_EOL; } else { echo '<tr><td class="data1" colspan="4">'; - echo sprintf('<pre><code class="%s hljs">%s</code></pre>', $fnlang, $funcdata->fields['prosrc']); - echo '</td></tr>'.PHP_EOL; + echo \sprintf('<pre><code class="%s hljs">%s</code></pre>', $fnlang, $funcdata->fields['prosrc']); + echo '</td></tr>' . \PHP_EOL; } // Display function cost options if ($data->hasFunctionCosting()) { - echo "<tr><th class=\"data required\" colspan=\"4\">{$this->lang['strfunctioncosting']}</th></tr>".PHP_EOL; + echo "<tr><th class=\"data required\" colspan=\"4\">{$this->lang['strfunctioncosting']}</th></tr>" . \PHP_EOL; echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strexecutioncost']}: ", $this->misc->printVal($funcdata->fields['procost']), ' </td>'; echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strresultrows']}: ", $this->misc->printVal($funcdata->fields['prorows']), ' </td>'; } // Show flags - if (is_array($data->funcprops) && sizeof($data->funcprops) > 0) { + if (\is_array($data->funcprops) && 0 < \count($data->funcprops)) { // Fetch an array of the function properties $funcprops = $data->getFunctionProperties($funcdata->fields); - echo "<tr><th class=\"data\" colspan=\"4\">{$this->lang['strproperties']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1" colspan="4">'.PHP_EOL; + echo "<tr><th class=\"data\" colspan=\"4\">{$this->lang['strproperties']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1" colspan="4">' . \PHP_EOL; + foreach ($funcprops as $v) { - echo $this->misc->printVal($v), '<br />'.PHP_EOL; + echo $this->misc->printVal($v), '<br />' . \PHP_EOL; } - echo '</td></tr>'.PHP_EOL; + echo '</td></tr>' . \PHP_EOL; } - echo "<tr><td class=\"data1\" colspan=\"5\">{$this->lang['strowner']}: ", htmlspecialchars($funcdata->fields['proowner']), PHP_EOL; - echo '</td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; + echo "<tr><td class=\"data1\" colspan=\"5\">{$this->lang['strowner']}: ", \htmlspecialchars($funcdata->fields['proowner']), \PHP_EOL; + echo '</td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; return $this->_printNavLinks('functions-properties', $func_full); } @@ -782,47 +645,50 @@ class FunctionsController extends BaseController $this->printTabs('function', 'definition'); $this->printTitle($this->lang['strdrop'], 'pg.function.drop'); - echo '<form action="'.\SUBFOLDER.'/src/views/functions" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/functions" method="post">' . \PHP_EOL; //If multi drop if (isset($_REQUEST['ma'])) { foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfdropfunction'], $this->misc->printVal($a['function'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="function[]" value="', htmlspecialchars($a['function']), '" />'.PHP_EOL; - echo '<input type="hidden" name="function_oid[]" value="', htmlspecialchars($a['function_oid']), '" />'.PHP_EOL; + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfdropfunction'], $this->misc->printVal($a['function'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="function[]" value="', \htmlspecialchars($a['function']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="function_oid[]" value="', \htmlspecialchars($a['function_oid']), '" />' . \PHP_EOL; } } else { - echo '<p>', sprintf($this->lang['strconfdropfunction'], $this->misc->printVal($_REQUEST['function'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="function" value="', htmlspecialchars($_REQUEST['function']), '" />'.PHP_EOL; - echo '<input type="hidden" name="function_oid" value="', htmlspecialchars($_REQUEST['function_oid']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropfunction'], $this->misc->printVal($_REQUEST['function'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="function" value="', \htmlspecialchars($_REQUEST['function']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="function_oid" value="', \htmlspecialchars($_REQUEST['function_oid']), '" />' . \PHP_EOL; } - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /><label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /><label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - if (is_array($_POST['function_oid'])) { + if (\is_array($_POST['function_oid'])) { $msg = ''; $status = $data->beginTransaction(); - if (0 == $status) { + + if (0 === $status) { foreach ($_POST['function_oid'] as $k => $s) { $status = $data->dropFunction($s, isset($_POST['cascade'])); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($_POST['function'][$k], ENT_QUOTES, 'UTF-8'), $this->lang['strfunctiondropped']); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($_POST['function'][$k], \ENT_QUOTES, 'UTF-8'), $this->lang['strfunctiondropped']); } else { $data->endTransaction(); - $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($_POST['function'][$k], ENT_QUOTES, 'UTF-8'), $this->lang['strfunctiondroppedbad'])); + $this->doDefault(\sprintf('%s%s: %s<br />', $msg, \htmlentities($_POST['function'][$k], \ENT_QUOTES, 'UTF-8'), $this->lang['strfunctiondroppedbad'])); return; } } } - if (0 == $data->endTransaction()) { + + if (0 === $data->endTransaction()) { // Everything went fine, back to the Default page.... $this->misc->setReloadBrowser(true); $this->doDefault($msg); @@ -831,7 +697,8 @@ class FunctionsController extends BaseController } } else { $status = $data->dropFunction($_POST['function_oid'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strfunctiondropped']); } else { @@ -847,7 +714,7 @@ class FunctionsController extends BaseController * @param string $msg message to display * @param mixed $szJS */ - public function doCreate($msg = '', $szJS = '') + public function doCreate($msg = '', $szJS = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -858,7 +725,7 @@ class FunctionsController extends BaseController $_POST['formReturns'] = $this->getPostParam('formReturns', ''); - $this->coalesceArr($_POST, 'formLanguage', isset($_REQUEST['language']) ? $_REQUEST['language'] : 'sql'); + $this->coalesceArr($_POST, 'formLanguage', $_REQUEST['language'] ?? 'sql'); $_POST['formDefinition'] = $this->getPostParam('formDefinition', ''); @@ -880,7 +747,7 @@ class FunctionsController extends BaseController $types = $data->getTypes(true, true, true); $langs = $data->getLanguages(true); - $fnlang = strtolower($_POST['formLanguage']); + $fnlang = \mb_strtolower($_POST['formLanguage']); switch ($fnlang) { case 'c': @@ -900,28 +767,31 @@ class FunctionsController extends BaseController // Create string for return type list $szTypes = ''; + while (!$types->EOF) { $szSelected = ''; - if ($types->fields['typname'] == $_POST['formReturns']) { + + if ($types->fields['typname'] === $_POST['formReturns']) { $szSelected = ' selected="selected"'; } // this variable is include in the JS code bellow, so we need to ENT_QUOTES - $szTypes .= '<option value="'.htmlspecialchars($types->fields['typname'], ENT_QUOTES)."\"{$szSelected}>"; - $szTypes .= htmlspecialchars($types->fields['typname'], ENT_QUOTES).'</option>'; + $szTypes .= '<option value="' . \htmlspecialchars($types->fields['typname'], \ENT_QUOTES) . "\"{$szSelected}>"; + $szTypes .= \htmlspecialchars($types->fields['typname'], \ENT_QUOTES) . '</option>'; $types->moveNext(); } - $szFunctionName = "<td class=\"data1\"><input name=\"formFunction\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"". - htmlspecialchars($_POST['formFunction']).'" /></td>'; + $szFunctionName = "<td class=\"data1\"><input name=\"formFunction\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"" . + \htmlspecialchars($_POST['formFunction']) . '" /></td>'; - $szArguments = '<td class="data1"><input name="formArguments" style="width:100%;" size="16" value="'. - htmlspecialchars($_POST['formArguments']).'" /></td>'; + $szArguments = '<td class="data1"><input name="formArguments" style="width:100%;" size="16" value="' . + \htmlspecialchars($_POST['formArguments']) . '" /></td>'; $szSetOfSelected = ''; $szNotSetOfSelected = ''; - if ('' == $_POST['formSetOf']) { + + if ('' === $_POST['formSetOf']) { $szNotSetOfSelected = ' selected="selected"'; - } elseif ('SETOF' == $_POST['formSetOf']) { + } elseif ('SETOF' === $_POST['formSetOf']) { $szSetOfSelected = ' selected="selected"'; } $szReturns = '<td class="data1" colspan="2">'; @@ -930,15 +800,16 @@ class FunctionsController extends BaseController $szReturns .= "<option value=\"SETOF\"{$szSetOfSelected}>SETOF</option>"; $szReturns .= '</select>'; - $szReturns .= '<select class="select2" name="formReturns">'.$szTypes.'</select>'; + $szReturns .= '<select class="select2" name="formReturns">' . $szTypes . '</select>'; // Create string array type selector $szArraySelected = ''; $szNotArraySelected = ''; - if ('' == $_POST['formArray']) { + + if ('' === $_POST['formArray']) { $szNotArraySelected = ' selected="selected"'; - } elseif ('[]' == $_POST['formArray']) { + } elseif ('[]' === $_POST['formArray']) { $szArraySelected = ' selected="selected"'; } @@ -949,30 +820,35 @@ class FunctionsController extends BaseController // Create string for language $szLanguage = '<td class="data1">'; - if ('c' == $fnlang || 'internal' == $fnlang) { - $szLanguage .= $_POST['formLanguage'].PHP_EOL; - $szLanguage .= "<input type=\"hidden\" name=\"formLanguage\" value=\"{$_POST['formLanguage']}\" />".PHP_EOL; + + if ('c' === $fnlang || 'internal' === $fnlang) { + $szLanguage .= $_POST['formLanguage'] . \PHP_EOL; + $szLanguage .= "<input type=\"hidden\" name=\"formLanguage\" value=\"{$_POST['formLanguage']}\" />" . \PHP_EOL; } else { - $szLanguage .= '<select name="formLanguage">'.PHP_EOL; + $szLanguage .= '<select name="formLanguage">' . \PHP_EOL; + while (!$langs->EOF) { $szSelected = ''; - if ($langs->fields['lanname'] == $_POST['formLanguage']) { + + if ($langs->fields['lanname'] === $_POST['formLanguage']) { $szSelected = ' selected="selected"'; } - if ('c' != strtolower($langs->fields['lanname']) && 'internal' != strtolower($langs->fields['lanname'])) { - $szLanguage .= '<option value="'.htmlspecialchars($langs->fields['lanname'])."\"{$szSelected}>\n". - $this->misc->printVal($langs->fields['lanname']).'</option>'; + + if ('c' !== \mb_strtolower($langs->fields['lanname']) && 'internal' !== \mb_strtolower($langs->fields['lanname'])) { + $szLanguage .= '<option value="' . \htmlspecialchars($langs->fields['lanname']) . "\"{$szSelected}>\n" . + $this->misc->printVal($langs->fields['lanname']) . '</option>'; } $langs->moveNext(); } - $szLanguage .= '</select>'.PHP_EOL; + $szLanguage .= '</select>' . \PHP_EOL; } $szLanguage .= '</td>'; $szJSArguments = "<tr><th class=\"data\" colspan=\"7\">{$this->lang['strarguments']}</th></tr>"; $arrayModes = ['IN', 'OUT', 'INOUT']; $szModes = '<select name="formArgModes[]" style="width:100%;">'; + foreach ($arrayModes as $pV) { $szModes .= "<option value=\"{$pV}\">{$pV}</option>"; } @@ -981,130 +857,134 @@ class FunctionsController extends BaseController $szArgReturns .= '<option value=""></option>'; $szArgReturns .= '<option value="[]">[]</option>'; $szArgReturns .= '</select>'; - $subfolder = \SUBFOLDER; + $subfolder = self::SUBFOLDER; + if (!empty($this->conf['theme'])) { - $szImgPath = \SUBFOLDER."/assets/images/themes/{$this->conf['theme']}"; + $szImgPath = self::SUBFOLDER . "/assets/images/themes/{$this->conf['theme']}"; } else { - $szImgPath = \SUBFOLDER.'/assets/images/themes/default'; + $szImgPath = self::SUBFOLDER . '/assets/images/themes/default'; } + if (empty($msg)) { // $this->prtrace($subfolder); - $szJSTRArg = "<script type=\"text/javascript\" >addArg('{$subfolder}');</script>".PHP_EOL; + $szJSTRArg = "<script type=\"text/javascript\" >addArg('{$subfolder}');</script>" . \PHP_EOL; } else { $szJSTRArg = ''; } - $szJSAddTR = "<tr id=\"parent_add_tr\" onclick=\"addArg('{$subfolder}');\" onmouseover=\"this.style.cursor='pointer'\">".PHP_EOL; + $szJSAddTR = "<tr id=\"parent_add_tr\" onclick=\"addArg('{$subfolder}');\" onmouseover=\"this.style.cursor='pointer'\">" . \PHP_EOL; $szJSAddTR .= '<td style="text-align: right" colspan="6" class="data3"><table><tr><td class="data3">'; $szJSAddTR .= "<img src=\"{$szImgPath}/AddArguments.png\" alt=\"Add Argument\" /></td>"; - $szJSAddTR .= "<td class=\"data3\"><span style=\"font-size: 8pt\">{$this->lang['strargadd']}</span></td></tr></table></td>\n</tr>".PHP_EOL; + $szJSAddTR .= "<td class=\"data3\"><span style=\"font-size: 8pt\">{$this->lang['strargadd']}</span></td></tr></table></td>\n</tr>" . \PHP_EOL; - echo '<script src="'.\SUBFOLDER."/assets/js/functions.js\" type=\"text/javascript\"></script> + echo '<script src="' . self::SUBFOLDER . "/assets/js/functions.js\" type=\"text/javascript\"></script> <script type=\"text/javascript\"> //<![CDATA[ var g_types_select = '<select class=\"select2\" name=\"formArgType[]\">{$szTypes}</select>{$szArgReturns}'; var g_modes_select = '{$szModes}'; var g_name = ''; - var g_lang_strargremove = '", htmlspecialchars($this->lang['strargremove'], ENT_QUOTES), "'; - var g_lang_strargnoargs = '", htmlspecialchars($this->lang['strargnoargs'], ENT_QUOTES), "'; - var g_lang_strargenableargs = '", htmlspecialchars($this->lang['strargenableargs'], ENT_QUOTES), "'; - var g_lang_strargnorowabove = '", htmlspecialchars($this->lang['strargnorowabove'], ENT_QUOTES), "'; - var g_lang_strargnorowbelow = '", htmlspecialchars($this->lang['strargnorowbelow'], ENT_QUOTES), "'; - var g_lang_strargremoveconfirm = '", htmlspecialchars($this->lang['strargremoveconfirm'], ENT_QUOTES), "'; - var g_lang_strargraise = '", htmlspecialchars($this->lang['strargraise'], ENT_QUOTES), "'; - var g_lang_strarglower = '", htmlspecialchars($this->lang['strarglower'], ENT_QUOTES), "'; + var g_lang_strargremove = '", \htmlspecialchars($this->lang['strargremove'], \ENT_QUOTES), "'; + var g_lang_strargnoargs = '", \htmlspecialchars($this->lang['strargnoargs'], \ENT_QUOTES), "'; + var g_lang_strargenableargs = '", \htmlspecialchars($this->lang['strargenableargs'], \ENT_QUOTES), "'; + var g_lang_strargnorowabove = '", \htmlspecialchars($this->lang['strargnorowabove'], \ENT_QUOTES), "'; + var g_lang_strargnorowbelow = '", \htmlspecialchars($this->lang['strargnorowbelow'], \ENT_QUOTES), "'; + var g_lang_strargremoveconfirm = '", \htmlspecialchars($this->lang['strargremoveconfirm'], \ENT_QUOTES), "'; + var g_lang_strargraise = '", \htmlspecialchars($this->lang['strargraise'], \ENT_QUOTES), "'; + var g_lang_strarglower = '", \htmlspecialchars($this->lang['strarglower'], \ENT_QUOTES), "'; //]]> </script> "; - echo '<form action="'.\SUBFOLDER.'/src/views/functions" method="post">'.PHP_EOL; - echo '<table><tbody id="args_table">'.PHP_EOL; - echo "<tr><th class=\"data required\">{$this->lang['strname']}</th>".PHP_EOL; - echo "<th class=\"data required\" colspan=\"2\">{$this->lang['strreturns']}</th>".PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strproglanguage']}</th></tr>".PHP_EOL; - echo '<tr>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/functions" method="post">' . \PHP_EOL; + echo '<table><tbody id="args_table">' . \PHP_EOL; + echo "<tr><th class=\"data required\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "<th class=\"data required\" colspan=\"2\">{$this->lang['strreturns']}</th>" . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strproglanguage']}</th></tr>" . \PHP_EOL; + echo '<tr>' . \PHP_EOL; echo "{$szFunctionName}\n"; echo "{$szReturns}\n"; echo "{$szLanguage}\n"; - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; echo "{$szJSArguments}\n"; - echo '<tr>'.PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strargmode']}</th>".PHP_EOL; - echo "<th class=\"data required\">{$this->lang['strname']}</th>".PHP_EOL; - echo "<th class=\"data required\" colspan=\"2\">{$this->lang['strargtype']}</th>".PHP_EOL; - echo '</tr>'.PHP_EOL; + echo '<tr>' . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strargmode']}</th>" . \PHP_EOL; + echo "<th class=\"data required\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "<th class=\"data required\" colspan=\"2\">{$this->lang['strargtype']}</th>" . \PHP_EOL; + echo '</tr>' . \PHP_EOL; echo "{$szJSAddTR}\n"; - if ('c' == $fnlang) { - echo "<tr><th class=\"data required\" colspan=\"2\">{$this->lang['strobjectfile']}</th>".PHP_EOL; - echo "<th class=\"data\" colspan=\"2\">{$this->lang['strlinksymbol']}</th></tr>".PHP_EOL; + if ('c' === $fnlang) { + echo "<tr><th class=\"data required\" colspan=\"2\">{$this->lang['strobjectfile']}</th>" . \PHP_EOL; + echo "<th class=\"data\" colspan=\"2\">{$this->lang['strlinksymbol']}</th></tr>" . \PHP_EOL; echo '<tr><td class="data1" colspan="2"><input type="text" name="formObjectFile" style="width:100%" value="', - htmlspecialchars($_POST['formObjectFile']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_POST['formObjectFile']), '" /></td>' . \PHP_EOL; echo '<td class="data1" colspan="2"><input type="text" name="formLinkSymbol" style="width:100%" value="', - htmlspecialchars($_POST['formLinkSymbol']), '" /></td></tr>'.PHP_EOL; - } elseif ('internal' == $fnlang) { - echo "<tr><th class=\"data\" colspan=\"4\">{$this->lang['strlinksymbol']}</th></tr>".PHP_EOL; + \htmlspecialchars($_POST['formLinkSymbol']), '" /></td></tr>' . \PHP_EOL; + } elseif ('internal' === $fnlang) { + echo "<tr><th class=\"data\" colspan=\"4\">{$this->lang['strlinksymbol']}</th></tr>" . \PHP_EOL; echo '<tr><td class="data1" colspan="4"><input type="text" name="formLinkSymbol" style="width:100%" value="', - htmlspecialchars($_POST['formLinkSymbol']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formLinkSymbol']), '" /></td></tr>' . \PHP_EOL; } else { - echo "<tr><th class=\"data required\" colspan=\"4\">{$this->lang['strdefinition']}</th></tr>".PHP_EOL; + echo "<tr><th class=\"data required\" colspan=\"4\">{$this->lang['strdefinition']}</th></tr>" . \PHP_EOL; echo '<tr><td class="data1" colspan="4">'; echo '<textarea style="width:100%;" rows="20" cols="50" name="formDefinition">'; - echo htmlspecialchars($_POST['formDefinition']); - echo '</textarea></td></tr>'.PHP_EOL; + echo \htmlspecialchars($_POST['formDefinition']); + echo '</textarea></td></tr>' . \PHP_EOL; } // Display function comment - echo "<tr><th class=\"data\" colspan=\"4\">{$this->lang['strcomment']}</th></tr>".PHP_EOL; + echo "<tr><th class=\"data\" colspan=\"4\">{$this->lang['strcomment']}</th></tr>" . \PHP_EOL; echo '<tr><td class="data1" colspan="4"><textarea style="width:100%;" name="formComment" rows="3" cols="50">', - htmlspecialchars($_POST['formComment']), '</textarea></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formComment']), '</textarea></td></tr>' . \PHP_EOL; // Display function cost options if ($data->hasFunctionCosting()) { - echo "<tr><th class=\"data required\" colspan=\"4\">{$this->lang['strfunctioncosting']}</th></tr>".PHP_EOL; - echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strexecutioncost']}: <input name=\"formCost\" size=\"16\" value=\"". - htmlspecialchars($_POST['formCost']).'" /></td>'; - echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strresultrows']}: <input name=\"formRows\" size=\"16\" value=\"". - htmlspecialchars($_POST['formRows']).'" /></td>'; + echo "<tr><th class=\"data required\" colspan=\"4\">{$this->lang['strfunctioncosting']}</th></tr>" . \PHP_EOL; + echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strexecutioncost']}: <input name=\"formCost\" size=\"16\" value=\"" . + \htmlspecialchars($_POST['formCost']) . '" /></td>'; + echo "<td class=\"data1\" colspan=\"2\">{$this->lang['strresultrows']}: <input name=\"formRows\" size=\"16\" value=\"" . + \htmlspecialchars($_POST['formRows']) . '" /></td>'; } // Display function properties - if (is_array($data->funcprops) && sizeof($data->funcprops) > 0) { - echo "<tr><th class=\"data required\" colspan=\"4\">{$this->lang['strproperties']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1" colspan="4">'.PHP_EOL; + if (\is_array($data->funcprops) && 0 < \count($data->funcprops)) { + echo "<tr><th class=\"data required\" colspan=\"4\">{$this->lang['strproperties']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1" colspan="4">' . \PHP_EOL; $i = 0; + foreach ($data->funcprops as $k => $v) { - echo "<select name=\"formProperties[{$i}]\">".PHP_EOL; + echo "<select name=\"formProperties[{$i}]\">" . \PHP_EOL; + foreach ($v as $p) { - echo '<option value="', htmlspecialchars($p), '"', - ($_POST['formProperties'][$i] == $p) ? ' selected="selected"' : '', - '>', $this->misc->printVal($p), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($p), '"', + ($_POST['formProperties'][$i] === $p) ? ' selected="selected"' : '', + '>', $this->misc->printVal($p), '</option>' . \PHP_EOL; } - echo '</select><br />'.PHP_EOL; + echo '</select><br />' . \PHP_EOL; ++$i; } - echo '</td></tr>'.PHP_EOL; + echo '</td></tr>' . \PHP_EOL; } - echo '</tbody></table>'.PHP_EOL; + echo '</tbody></table>' . \PHP_EOL; echo $szJSTRArg; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; echo $szJS; } /** * Actually creates the new function in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); - $fnlang = strtolower($_POST['formLanguage']); + $fnlang = \mb_strtolower($_POST['formLanguage']); - if ('c' == $fnlang) { + if ('c' === $fnlang) { $def = [$_POST['formObjectFile'], $_POST['formLinkSymbol']]; - } elseif ('internal' == $fnlang) { + } elseif ('internal' === $fnlang) { $def = $_POST['formLinkSymbol']; } else { $def = $_POST['formDefinition']; @@ -1112,47 +992,51 @@ class FunctionsController extends BaseController $szJS = ''; - echo '<script src="'.\SUBFOLDER.'/assets/js/functions.js" type="text/javascript"></script>'; - echo '<script type="text/javascript">'.$this->_buildJSData().'</script>'; + echo '<script src="' . self::SUBFOLDER . '/assets/js/functions.js" type="text/javascript"></script>'; + echo '<script type="text/javascript">' . $this->_buildJSData() . '</script>'; + if (!empty($_POST['formArgName'])) { $szJS = $this->_buildJSRows($this->_buildFunctionArguments($_POST)); } else { - $subfolder = \SUBFOLDER; + $subfolder = self::SUBFOLDER; // $this->prtrace($subfolder); - $szJS = '<script type="text/javascript" src="'.\SUBFOLDER.'/assets/js/functions.js">noArgsRebuild(addArg("'.$subfolder.'"));</script>'; + $szJS = '<script type="text/javascript" src="' . self::SUBFOLDER . '/assets/js/functions.js">noArgsRebuild(addArg("' . $subfolder . '"));</script>'; } $cost = (isset($_POST['formCost'])) ? $_POST['formCost'] : null; - if ('' == $cost || !is_numeric($cost) || $cost != (int) $cost || $cost < 0) { + + if ('' === $cost || !\is_numeric($cost) || (int) $cost !== $cost || 0 > $cost) { $cost = null; } $rows = (isset($_POST['formRows'])) ? $_POST['formRows'] : null; - if ('' == $rows || !is_numeric($rows) || $rows != (int) $rows) { + + if ('' === $rows || !\is_numeric($rows) || (int) $rows !== $rows) { $rows = null; } // Check that they've given a name and a definition - if ('' == $_POST['formFunction']) { + if ('' === $_POST['formFunction']) { $this->doCreate($this->lang['strfunctionneedsname'], $szJS); - } elseif ('internal' != $fnlang && !$def) { + } elseif ('internal' !== $fnlang && !$def) { $this->doCreate($this->lang['strfunctionneedsdef'], $szJS); } else { // Append array symbol to type if chosen $status = $data->createFunction( $_POST['formFunction'], empty($_POST['nojs']) ? $this->_buildFunctionArguments($_POST) : $_POST['formArguments'], - $_POST['formReturns'].$_POST['formArray'], + $_POST['formReturns'] . $_POST['formArray'], $def, $_POST['formLanguage'], $_POST['formProperties'], - 'SETOF' == $_POST['formSetOf'], + 'SETOF' === $_POST['formSetOf'], $cost, $rows, $_POST['formComment'], false ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strfunctioncreated']); } else { $this->doCreate($this->lang['strfunctioncreatedbad'], $szJS); @@ -1160,6 +1044,162 @@ class FunctionsController extends BaseController } } + private function _printNavLinks($place, $func_full = ''): void + { + if ('functions-properties' === $place) { + $navlinks = [ + 'showall' => [ + 'attr' => [ + 'href' => [ + 'url' => 'functions', + 'urlvars' => [ + 'server' => $_REQUEST['server'], + 'database' => $_REQUEST['database'], + 'schema' => $_REQUEST['schema'], + ], + ], + ], + 'content' => $this->lang['strshowallfunctions'], + ], + 'alter' => [ + 'attr' => [ + 'href' => [ + 'url' => 'functions', + 'urlvars' => [ + 'action' => 'edit', + 'server' => $_REQUEST['server'], + 'database' => $_REQUEST['database'], + 'schema' => $_REQUEST['schema'], + 'function' => $_REQUEST['function'], + 'function_oid' => $_REQUEST['function_oid'], + ], + ], + ], + 'content' => $this->lang['stralter'], + ], + 'drop' => [ + 'attr' => [ + 'href' => [ + 'url' => 'functions', + 'urlvars' => [ + 'action' => 'confirm_drop', + 'server' => $_REQUEST['server'], + 'database' => $_REQUEST['database'], + 'schema' => $_REQUEST['schema'], + 'function' => $func_full, + 'function_oid' => $_REQUEST['function_oid'], + ], + ], + ], + 'content' => $this->lang['strdrop'], + ], + ]; + } elseif ('functions-functions' === $place) { + $navlinks = [ + 'createpl' => [ + 'attr' => [ + 'href' => [ + 'url' => 'functions', + 'urlvars' => [ + 'action' => 'create', + 'server' => $_REQUEST['server'], + 'database' => $_REQUEST['database'], + 'schema' => $_REQUEST['schema'], + ], + ], + ], + 'content' => $this->lang['strcreateplfunction'], + ], + 'createinternal' => [ + 'attr' => [ + 'href' => [ + 'url' => 'functions', + 'urlvars' => [ + 'action' => 'create', + 'language' => 'internal', + 'server' => $_REQUEST['server'], + 'database' => $_REQUEST['database'], + 'schema' => $_REQUEST['schema'], + ], + ], + ], + 'content' => $this->lang['strcreateinternalfunction'], + ], + 'createc' => [ + 'attr' => [ + 'href' => [ + 'url' => 'functions', + 'urlvars' => [ + 'action' => 'create', + 'language' => 'C', + 'server' => $_REQUEST['server'], + 'database' => $_REQUEST['database'], + 'schema' => $_REQUEST['schema'], + ], + ], + ], + 'content' => $this->lang['strcreatecfunction'], + ], + ]; + } else { + return; + } + + $this->printNavLinks($navlinks, $place, \get_defined_vars()); + } + + private function _getNamedParamsArgs($data, $fndata) + { + if (isset($fndata->fields['proallarguments'])) { + $args_arr = $data->phpArray($fndata->fields['proallarguments']); + } else { + $args_arr = \explode(', ', $fndata->fields['proarguments']); + } + $names_arr = $data->phpArray($fndata->fields['proargnames']); + $modes_arr = $data->phpArray($fndata->fields['proargmodes']); + $args = ''; + $args_arr_size = \count($args_arr); + + for ($i = 0; $i < $args_arr_size; ++$i) { + if (0 !== $i) { + $args .= ', '; + } + + if (isset($modes_arr[$i])) { + switch ($modes_arr[$i]) { + case 'i': + $args .= ' IN '; + + break; + case 'o': + $args .= ' OUT '; + + break; + case 'b': + $args .= ' INOUT '; + + break; + case 'v': + $args .= ' VARIADIC '; + + break; + case 't': + $args .= ' TABLE '; + + break; + } + } + + if (isset($names_arr[$i]) && '' !== $names_arr[$i]) { + $data->fieldClean($names_arr[$i]); + $args .= '"' . $names_arr[$i] . '" '; + } + $args .= $args_arr[$i]; + } + + return $args; + } + /** * Build out the function arguments string. * @@ -1171,11 +1211,12 @@ class FunctionsController extends BaseController { if (isset($_POST['formArgName'])) { $arrayArgs = []; + foreach ($arrayVars['formArgName'] as $pK => $pV) { - $arrayArgs[] = $arrayVars['formArgModes'][$pK].' '.trim($pV).' '.trim($arrayVars['formArgType'][$pK]).$arrayVars['formArgArray'][$pK]; + $arrayArgs[] = $arrayVars['formArgModes'][$pK] . ' ' . \trim($pV) . ' ' . \trim($arrayVars['formArgType'][$pK]) . $arrayVars['formArgArray'][$pK]; } - return implode(',', $arrayArgs); + return \implode(',', $arrayArgs); } return ''; @@ -1189,27 +1230,30 @@ class FunctionsController extends BaseController private function _buildJSRows($szArgs) { $arrayModes = ['IN', 'OUT', 'INOUT']; - $arrayArgs = explode(',', $szArgs); + $arrayArgs = \explode(',', $szArgs); $arrayProperArgs = []; $nC = 0; $szReturn = ''; $szMode = []; + foreach ($arrayArgs as $pV) { - $arrayWords = explode(' ', $pV); - if (true === in_array($arrayWords[0], $arrayModes, true)) { + $arrayWords = \explode(' ', $pV); + + if (true === \in_array($arrayWords[0], $arrayModes, true)) { $szMode = $arrayWords[0]; - array_shift($arrayWords); + \array_shift($arrayWords); } - $szArgName = array_shift($arrayWords); - if (false === strpos($arrayWords[count($arrayWords) - 1], '[]')) { - $szArgType = implode(' ', $arrayWords); + $szArgName = \array_shift($arrayWords); + + if (false === \mb_strpos($arrayWords[\count($arrayWords) - 1], '[]')) { + $szArgType = \implode(' ', $arrayWords); $bArgIsArray = 'false'; } else { - $szArgType = str_replace('[]', '', implode(' ', $arrayWords)); + $szArgType = \str_replace('[]', '', \implode(' ', $arrayWords)); $bArgIsArray = 'true'; } $arrayProperArgs[] = [$szMode, $szArgName, $szArgType, $bArgIsArray]; - $subfolder = \SUBFOLDER; + $subfolder = self::SUBFOLDER; // $this->prtrace($subfolder); $szReturn .= '<script type="text/javascript">'; $szReturn .= "RebuildArgTR('{$szMode}','{$szArgName}','{$szArgType}',new Boolean({$bArgIsArray},{$subfolder}));"; @@ -1230,7 +1274,7 @@ class FunctionsController extends BaseController $arrayPModes = []; while (!$arrayTypes->EOF) { - $arrayPTypes[] = "'".$arrayTypes->fields['typname']."'"; + $arrayPTypes[] = "'" . $arrayTypes->fields['typname'] . "'"; $arrayTypes->moveNext(); } @@ -1238,10 +1282,10 @@ class FunctionsController extends BaseController $arrayPModes[] = "'{$pV}'"; } - $szTypes = 'g_main_types = new Array('.implode(',', $arrayPTypes).');'; - $szModes = 'g_main_modes = new Array('.implode(',', $arrayPModes).');'; + $szTypes = 'g_main_types = new Array(' . \implode(',', $arrayPTypes) . ');'; + $szModes = 'g_main_modes = new Array(' . \implode(',', $arrayPModes) . ');'; - return $szTypes.$szModes; + return $szTypes . $szModes; } /** @@ -1259,14 +1303,15 @@ class FunctionsController extends BaseController if (isset($funcdata->fields['proallarguments'])) { $args_arr = $data->phpArray($funcdata->fields['proallarguments']); } else { - $args_arr = explode(', ', $funcdata->fields['proarguments']); + $args_arr = \explode(', ', $funcdata->fields['proarguments']); } $names_arr = $data->phpArray($funcdata->fields['proargnames']); $modes_arr = $data->phpArray($funcdata->fields['proargmodes']); $args = ''; - $args_arr_size = sizeof($args_arr); + $args_arr_size = \count($args_arr); + for ($i = 0; $i < $args_arr_size; ++$i) { - if (0 != $i) { + if (0 !== $i) { $args .= ', '; } @@ -1294,9 +1339,10 @@ class FunctionsController extends BaseController break; } } - if (isset($names_arr[$i]) && '' != $names_arr[$i]) { + + if (isset($names_arr[$i]) && '' !== $names_arr[$i]) { $data->fieldClean($names_arr[$i]); - $args .= '"'.$names_arr[$i].'" '; + $args .= '"' . $names_arr[$i] . '" '; } $args .= $args_arr[$i]; } diff --git a/src/controllers/GroupsController.php b/src/controllers/GroupsController.php index 4bd7dd91..86fab642 100644 --- a/src/controllers/GroupsController.php +++ b/src/controllers/GroupsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class GroupsController extends BaseController { @@ -20,7 +21,7 @@ class GroupsController extends BaseController /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { $this->printHeader(); $this->printBody(); @@ -92,7 +93,7 @@ class GroupsController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -142,18 +143,19 @@ class GroupsController extends BaseController ], ], 'content' => $this->lang['strcreategroup'], - ]], 'groups-groups', get_defined_vars()); + ]], 'groups-groups', \get_defined_vars()); } /** * Add user to a group. */ - public function doAddMember() + public function doAddMember(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->addGroupMember($_REQUEST['group'], $_REQUEST['user']); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strmemberadded']); } else { $this->doProperties($this->lang['strmemberaddedbad']); @@ -166,7 +168,7 @@ class GroupsController extends BaseController * @param mixed $confirm * @param mixed $msg */ - public function doDropMember($confirm, $msg = '') + public function doDropMember($confirm, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -178,19 +180,20 @@ class GroupsController extends BaseController $this->printTrail('group'); $this->printTitle($this->lang['strdropmember'], 'pg.group.alter'); - echo '<p>', sprintf($this->lang['strconfdropmember'], $this->misc->printVal($_REQUEST['user']), $this->misc->printVal($_REQUEST['group'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropmember'], $this->misc->printVal($_REQUEST['user']), $this->misc->printVal($_REQUEST['group'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/groups" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/groups" method="post">' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="action" value="drop_member" />'.PHP_EOL; - echo '<input type="hidden" name="group" value="', htmlspecialchars($_REQUEST['group']), '" />'.PHP_EOL; - echo '<input type="hidden" name="user" value="', htmlspecialchars($_REQUEST['user']), '" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="action" value="drop_member" />' . \PHP_EOL; + echo '<input type="hidden" name="group" value="', \htmlspecialchars($_REQUEST['group']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="user" value="', \htmlspecialchars($_REQUEST['user']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropGroupMember($_REQUEST['group'], $_REQUEST['user']); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strmemberdropped']); } else { $this->doDropMember(true, $this->lang['strmemberdroppedbad']); @@ -203,7 +206,7 @@ class GroupsController extends BaseController * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -216,7 +219,7 @@ class GroupsController extends BaseController $groupdata = $data->getGroup($_REQUEST['group']); $users = $data->getUsers(); - if ($groupdata->recordCount() > 0) { + if (0 < $groupdata->recordCount()) { $columns = [ 'members' => [ 'title' => $this->lang['strmembers'], @@ -247,20 +250,21 @@ class GroupsController extends BaseController } // Display form for adding a user to the group - echo '<form action="'.\SUBFOLDER.'/src/views/groups" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/groups" method="post">' . \PHP_EOL; echo '<select name="user">'; + while (!$users->EOF) { $uname = $this->misc->printVal($users->fields['usename']); echo "<option value=\"{$uname}\"", - ($uname == $_POST['user']) ? ' selected="selected"' : '', ">{$uname}</option>".PHP_EOL; + ($uname === $_POST['user']) ? ' selected="selected"' : '', ">{$uname}</option>" . \PHP_EOL; $users->moveNext(); } - echo '</select>'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['straddmember']}\" />".PHP_EOL; + echo '</select>' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['straddmember']}\" />" . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="group" value="', htmlspecialchars($_REQUEST['group']), '" />'.PHP_EOL; - echo '<input type="hidden" name="action" value="add_member" />'.PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="group" value="', \htmlspecialchars($_REQUEST['group']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="action" value="add_member" />' . \PHP_EOL; + echo '</form>' . \PHP_EOL; $this->printNavLinks(['showall' => [ 'attr' => [ @@ -272,7 +276,7 @@ class GroupsController extends BaseController ], ], 'content' => $this->lang['strshowallgroups'], - ]], 'groups-properties', get_defined_vars()); + ]], 'groups-properties', \get_defined_vars()); } /** @@ -280,7 +284,7 @@ class GroupsController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -288,18 +292,19 @@ class GroupsController extends BaseController $this->printTrail('group'); $this->printTitle($this->lang['strdrop'], 'pg.group.drop'); - echo '<p>', sprintf($this->lang['strconfdropgroup'], $this->misc->printVal($_REQUEST['group'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropgroup'], $this->misc->printVal($_REQUEST['group'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/groups" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/groups" method="post">' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="group" value="', htmlspecialchars($_REQUEST['group']), '" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="group" value="', \htmlspecialchars($_REQUEST['group']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropGroup($_REQUEST['group']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strgroupdropped']); } else { $this->doDefault($this->lang['strgroupdroppedbad']); @@ -312,7 +317,7 @@ class GroupsController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $this->coalesceArr($_POST, 'name', ''); @@ -326,47 +331,50 @@ class GroupsController extends BaseController $this->printTitle($this->lang['strcreategroup'], 'pg.group.create'); $this->printMsg($msg); - echo '<form action="" method="post">'.PHP_EOL; + echo '<form action="" method="post">' . \PHP_EOL; echo $this->misc->form; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\"><input size=\"32\" maxlength=\"{$data->_maxNameLen}\" name=\"name\" value=\"", htmlspecialchars($_POST['name']), "\" /></td>\n\t</tr>".PHP_EOL; - if ($users->recordCount() > 0) { - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmembers']}</th>".PHP_EOL; - - echo "\t\t<td class=\"data\">".PHP_EOL; - echo "\t\t\t<select name=\"members[]\" multiple=\"multiple\" size=\"", min(40, $users->recordCount()), '">'.PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\"><input size=\"32\" maxlength=\"{$data->_maxNameLen}\" name=\"name\" value=\"", \htmlspecialchars($_POST['name']), "\" /></td>\n\t</tr>" . \PHP_EOL; + + if (0 < $users->recordCount()) { + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmembers']}</th>" . \PHP_EOL; + + echo "\t\t<td class=\"data\">" . \PHP_EOL; + echo "\t\t\t<select name=\"members[]\" multiple=\"multiple\" size=\"", \min(40, $users->recordCount()), '">' . \PHP_EOL; + while (!$users->EOF) { $username = $users->fields['usename']; echo "\t\t\t\t<option value=\"{$username}\"", - (in_array($username, $_POST['members'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($username), '</option>'.PHP_EOL; + (\in_array($username, $_POST['members'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($username), '</option>' . \PHP_EOL; $users->moveNext(); } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new group in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); $this->coalesceArr($_POST, 'members', []); // Check form vars - if ('' == trim($_POST['name'])) { + if ('' === \trim($_POST['name'])) { $this->doCreate($this->lang['strgroupneedsname']); } else { $status = $data->createGroup($_POST['name'], $_POST['members']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strgroupcreated']); } else { $this->doCreate($this->lang['strgroupcreatedbad']); diff --git a/src/controllers/HelpController.php b/src/controllers/HelpController.php index 640528ce..f5e748bc 100644 --- a/src/controllers/HelpController.php +++ b/src/controllers/HelpController.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class HelpController extends BaseController { @@ -18,7 +19,7 @@ class HelpController extends BaseController /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { switch ($this->action) { case 'browse': @@ -32,21 +33,21 @@ class HelpController extends BaseController } } - public function doDefault() + public function doDefault(): void { $data = $this->misc->getDatabaseAccessor(); if (isset($_REQUEST['help'])) { $url = $data->getHelp($_REQUEST['help']); - if (is_array($url)) { + if (\is_array($url)) { $this->doChoosePage($url); return; } if ($url) { - header("Location: ${url}"); + \header("Location: {$url}"); return; } @@ -55,7 +56,7 @@ class HelpController extends BaseController $this->doBrowse($this->lang['strinvalidhelppage']); } - public function doBrowse($msg = '') + public function doBrowse($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -66,39 +67,42 @@ class HelpController extends BaseController echo $this->printMsg($msg); - echo '<dl>'.PHP_EOL; + echo '<dl>' . \PHP_EOL; $pages = $data->getHelpPages(); + foreach ($pages as $page => $dummy) { - echo "<dt>{$page}</dt>".PHP_EOL; + echo "<dt>{$page}</dt>" . \PHP_EOL; $urls = $data->getHelp($page); - if (!is_array($urls)) { + + if (!\is_array($urls)) { $urls = [$urls]; } foreach ($urls as $url) { - echo "<dd><a href=\"{$url}\">{$url}</a></dd>".PHP_EOL; + echo "<dd><a href=\"{$url}\">{$url}</a></dd>" . \PHP_EOL; } } - echo '</dl>'.PHP_EOL; + echo '</dl>' . \PHP_EOL; $this->printFooter(); } - public function doChoosePage($urls) + public function doChoosePage($urls): void { $this->printHeader(); $this->printBody(); $this->printTitle($this->lang['strselecthelppage']); - echo '<ul>'.PHP_EOL; + echo '<ul>' . \PHP_EOL; + foreach ($urls as $url) { - echo "<li><a href=\"{$url}\">{$url}</a></li>".PHP_EOL; + echo "<li><a href=\"{$url}\">{$url}</a></li>" . \PHP_EOL; } - echo '</ul>'.PHP_EOL; + echo '</ul>' . \PHP_EOL; $this->printFooter(); } diff --git a/src/controllers/HistoryController.php b/src/controllers/HistoryController.php index b3fa98f8..6d47d0b1 100644 --- a/src/controllers/HistoryController.php +++ b/src/controllers/HistoryController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,15 +13,17 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class HistoryController extends BaseController { use \PHPPgAdmin\Traits\ServersTrait; + public $EOF; + public $fields; - public $scripts = '<script type="text/javascript">window.inPopUp=true;</script>'; + + public $scripts = '<script type="text/javascript">window.inPopUp=true;</script>'; + public $controller_title = 'strhistory'; /** @@ -63,21 +68,21 @@ class HistoryController extends BaseController return $this->printFooter(true, 'footer_sqledit.twig'); } - public function doDefault() + public function doDefault(): void { $data = $this->misc->getDatabaseAccessor(); $this->printHeader($this->headerTitle(), $this->scripts, true, 'header.twig'); // Bring to the front always - echo '<body onload="window.focus();">'.PHP_EOL; + echo '<body onload="window.focus();">' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/history" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/history" method="post">' . \PHP_EOL; $this->printConnection('history'); echo '</form><br />'; if (!isset($_REQUEST['database'])) { - echo "<p>{$this->lang['strnodatabaseselected']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodatabaseselected']}</p>" . \PHP_EOL; return; } @@ -133,7 +138,7 @@ class HistoryController extends BaseController echo $this->printTable($history, $columns, $actions, 'history-history', $this->lang['strnohistory']); } else { - echo "<p>{$this->lang['strnohistory']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnohistory']}</p>" . \PHP_EOL; } $navlinks = [ @@ -153,7 +158,7 @@ class HistoryController extends BaseController ]; if (isset($_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']]) - && count($_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']])) { + && \count($_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']])) { $navlinks['download'] = [ 'attr' => [ 'href' => [ @@ -182,69 +187,70 @@ class HistoryController extends BaseController ]; } - $this->printNavLinks($navlinks, 'history-history', get_defined_vars()); + $this->printNavLinks($navlinks, 'history-history', \get_defined_vars()); } - public function doDelHistory($qid, $confirm) + public function doDelHistory($qid, $confirm): void { if ($confirm) { $this->printHeader($this->headerTitle(), $this->scripts); // Bring to the front always - echo '<body onload="window.focus();">'.PHP_EOL; + echo '<body onload="window.focus();">' . \PHP_EOL; - echo "<h3>{$this->lang['strdelhistory']}</h3>".PHP_EOL; - echo "<p>{$this->lang['strconfdelhistory']}</p>".PHP_EOL; + echo "<h3>{$this->lang['strdelhistory']}</h3>" . \PHP_EOL; + echo "<p>{$this->lang['strconfdelhistory']}</p>" . \PHP_EOL; - echo '<pre>', htmlentities($_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']][$qid]['query'], ENT_QUOTES, 'UTF-8'), '</pre>'; - echo '<form action="'.\SUBFOLDER.'/src/views/history" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="delhistory" />'.PHP_EOL; - echo "<input type=\"hidden\" name=\"queryid\" value=\"${qid}\" />".PHP_EOL; + echo '<pre>', \htmlentities($_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']][$qid]['query'], \ENT_QUOTES, 'UTF-8'), '</pre>'; + echo '<form action="' . self::SUBFOLDER . '/src/views/history" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="delhistory" />' . \PHP_EOL; + echo "<input type=\"hidden\" name=\"queryid\" value=\"{$qid}\" />" . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { unset($_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']][$qid]); } } - public function doClearHistory($confirm) + public function doClearHistory($confirm): void { if ($confirm) { $this->printHeader($this->headerTitle(), $this->scripts); // Bring to the front always - echo '<body onload="window.focus();">'.PHP_EOL; + echo '<body onload="window.focus();">' . \PHP_EOL; - echo "<h3>{$this->lang['strclearhistory']}</h3>".PHP_EOL; - echo "<p>{$this->lang['strconfclearhistory']}</p>".PHP_EOL; + echo "<h3>{$this->lang['strclearhistory']}</h3>" . \PHP_EOL; + echo "<p>{$this->lang['strconfclearhistory']}</p>" . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/history" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="clearhistory" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/history" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="clearhistory" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { unset($_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']]); } } - public function doDownloadHistory() + public function doDownloadHistory(): void { - header('Content-Type: application/download'); - $datetime = date('YmdHis'); - header("Content-Disposition: attachment; filename=history{$datetime}.sql"); + \header('Content-Type: application/download'); + $datetime = \date('YmdHis'); + \header("Content-Disposition: attachment; filename=history{$datetime}.sql"); foreach ($_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']] as $queries) { - $query = rtrim($queries['query']); + $query = \rtrim($queries['query']); echo $query; - if (';' != substr($query, -1)) { + + if (';' !== \mb_substr($query, -1)) { echo ';'; } - echo PHP_EOL; + echo \PHP_EOL; } } } diff --git a/src/controllers/IndexesController.php b/src/controllers/IndexesController.php index 7e278bab..852a5402 100644 --- a/src/controllers/IndexesController.php +++ b/src/controllers/IndexesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,27 +13,27 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class IndexesController extends BaseController { public $controller_title = 'strindexes'; - public $scripts = '<script src="'.\SUBFOLDER.'/assets/js/indexes.js" type="text/javascript"></script>'; + + public $scripts = '<script src="' . self::SUBFOLDER . '/assets/js/indexes.js" type="text/javascript"></script>'; /** * Default method to render the controller according to the action parameter. */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } $this->printHeader($this->headerTitle(), $this->scripts); $onloadInit = false; - if ('create_index' == $this->action || 'save_create_index' == $this->action) { + + if ('create_index' === $this->action || 'save_create_index' === $this->action) { $onloadInit = true; } $this->printBody(true, 'detailbody', $onloadInit); @@ -85,12 +88,12 @@ class IndexesController extends BaseController return $this->printFooter(); } - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $lang = $this->lang; - $indPre = function (&$rowdata, $actions) use ($data, $lang) { + $indPre = static function (&$rowdata, $actions) use ($data, $lang) { if ($data->phpBool($rowdata->fields['indisprimary'])) { $rowdata->fields['+constraints'] = $lang['strprimarykey']; $actions['drop']['disable'] = true; @@ -105,8 +108,8 @@ class IndexesController extends BaseController }; $this->coalesceArr($_REQUEST, 'subject', 'table'); - $subject = urlencode($this->getRequestParam('subject', 'table')); - $object = urlencode($this->getRequestParam($subject)); + $subject = \urlencode($this->getRequestParam('subject', 'table')); + $object = \urlencode($this->getRequestParam($subject)); $this->printTrail($subject); $this->printTabs($subject, 'indexes'); @@ -143,7 +146,7 @@ class IndexesController extends BaseController ], ]; - $url = \SUBFOLDER.'/src/views/indexes'; + $url = self::SUBFOLDER . '/src/views/indexes'; $actions = [ 'cluster' => [ @@ -209,7 +212,7 @@ class IndexesController extends BaseController ], 'content' => $this->lang['strcreateindex'], ], - ], 'indexes-indexes', get_defined_vars()); + ], 'indexes-indexes', \get_defined_vars()); } public function doTree() @@ -217,17 +220,17 @@ class IndexesController extends BaseController $data = $this->misc->getDatabaseAccessor(); $this->coalesceArr($_REQUEST, 'subject', 'table'); - $subject = urlencode($_REQUEST['subject']); - $object = urlencode($_REQUEST[$subject]); + $subject = \urlencode($_REQUEST['subject']); + $object = \urlencode($_REQUEST[$subject]); $indexes = $data->getIndexes($object); - $getIcon = function ($f) { - if ('t' == $f['indisprimary']) { + $getIcon = static function ($f) { + if ('t' === $f['indisprimary']) { return 'PrimaryKey'; } - if ('t' == $f['indisunique']) { + if ('t' === $f['indisunique']) { return 'UniqueConstraint'; } @@ -247,13 +250,13 @@ class IndexesController extends BaseController * * @param mixed $confirm */ - public function doClusterIndex($confirm) + public function doClusterIndex($confirm): void { $data = $this->misc->getDatabaseAccessor(); $this->coalesceArr($_REQUEST, 'subject', 'table'); - $subject = urlencode($_REQUEST['subject']); - $object = urlencode($_REQUEST[$subject]); + $subject = \urlencode($_REQUEST['subject']); + $object = \urlencode($_REQUEST[$subject]); //$this->printTrail($subject); @@ -265,44 +268,47 @@ class IndexesController extends BaseController $this->printTabs($subject, 'indexes'); $this->printTitle($this->lang['strclusterindex'], 'pg.index.cluster'); - echo '<p>', sprintf($this->lang['strconfcluster'], $this->misc->printVal($_REQUEST['index'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfcluster'], $this->misc->printVal($_REQUEST['index'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/indexes" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/indexes" method="post">' . \PHP_EOL; echo '<p><input type="checkbox" id="analyze" name="analyze"', (isset($_REQUEST['analyze']) ? ' checked="checked"' : ''), ' />'; - echo "<label for=\"analyze\">{$this->lang['stranalyze']}</label></p>".PHP_EOL; - echo '<input type="hidden" name="action" value="cluster_index" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($object), '" />'.PHP_EOL; - echo '<input type="hidden" name="index" value="', htmlspecialchars($_REQUEST['index']), '" />'.PHP_EOL; + echo "<label for=\"analyze\">{$this->lang['stranalyze']}</label></p>" . \PHP_EOL; + echo '<input type="hidden" name="action" value="cluster_index" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($object), '" />' . \PHP_EOL; + echo '<input type="hidden" name="index" value="', \htmlspecialchars($_REQUEST['index']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"cluster\" value=\"{$this->lang['strclusterindex']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"cluster\" value=\"{$this->lang['strclusterindex']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - set_time_limit(0); + \set_time_limit(0); list($status, $sql) = $data->clusterIndex($object, $_POST['index']); - if (0 == $status) { + + if (0 === $status) { if (isset($_POST['analyze'])) { $status = $data->analyzeDB($object); - if (0 == $status) { - $this->doDefault($sql.'<br>'.$this->lang['strclusteredgood'].' '.$this->lang['stranalyzegood']); + + if (0 === $status) { + $this->doDefault($sql . '<br>' . $this->lang['strclusteredgood'] . ' ' . $this->lang['stranalyzegood']); } else { - $this->doDefault($sql.'<br>'.$this->lang['stranalyzebad']); + $this->doDefault($sql . '<br>' . $this->lang['stranalyzebad']); } } else { - $this->doDefault($sql.'<br>'.$this->lang['strclusteredgood']); + $this->doDefault($sql . '<br>' . $this->lang['strclusteredgood']); } } else { - $this->doDefault($sql.'<br>'.$this->lang['strclusteredbad']); + $this->doDefault($sql . '<br>' . $this->lang['strclusteredbad']); } } } - public function doReindex() + public function doReindex(): void { $data = $this->misc->getDatabaseAccessor(); - set_time_limit(0); + \set_time_limit(0); $status = $data->reindex('INDEX', $_REQUEST['index']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strreindexgood']); } else { $this->doDefault($this->lang['strreindexbad']); @@ -314,12 +320,12 @@ class IndexesController extends BaseController * * @param mixed $msg */ - public function doCreateIndex($msg = '') + public function doCreateIndex($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); - $subject = urlencode($this->getRequestParam('subject', 'table')); - $object = urlencode($this->getRequestParam($subject)); + $subject = \urlencode($this->getRequestParam('subject', 'table')); + $object = \urlencode($this->getRequestParam($subject)); $formIndexName = $this->getPostParam('formIndexName', ''); $formIndexType = $this->getPostParam('formIndexType'); @@ -343,7 +349,7 @@ class IndexesController extends BaseController $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10); $selColumns->set_style('width: 14em;'); - if ($attrs->recordCount() > 0) { + if (0 < $attrs->recordCount()) { while (!$attrs->EOF) { $attname = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']); $selColumns->add($attname); @@ -362,61 +368,62 @@ class IndexesController extends BaseController $buttonRemove->set_attribute('onclick', 'buttonPressed(this);'); $buttonRemove->set_attribute('type', 'button'); - echo '<form onsubmit="doSelectAll();" name="formIndex" action="indexes" method="post">'.PHP_EOL; + echo '<form onsubmit="doSelectAll();" name="formIndex" action="indexes" method="post">' . \PHP_EOL; - echo '<table>'.PHP_EOL; - echo '<tr><th class="data required" colspan="3">'.$this->lang['strindexname'].'</th></tr>'; + echo '<table>' . \PHP_EOL; + echo '<tr><th class="data required" colspan="3">' . $this->lang['strindexname'] . '</th></tr>'; echo '<tr>'; echo '<td class="data1" colspan="3">'; - echo 'Index name cannot exceed '.$data->_maxNameLen.' characters<br>'; - echo '<input type="text" name="formIndexName" size="32" placeholder="Index Name" maxlength="'. - $data->_maxNameLen.'" value="'. - htmlspecialchars($formIndexName).'" />'; + echo 'Index name cannot exceed ' . $data->_maxNameLen . ' characters<br>'; + echo '<input type="text" name="formIndexName" size="32" placeholder="Index Name" maxlength="' . + $data->_maxNameLen . '" value="' . + \htmlspecialchars($formIndexName) . '" />'; echo '</td>'; echo '</tr>'; echo '<tr>'; - echo '<th class="data">'.$this->lang['strtablecolumnlist'].'</th><th class="data"> </th>'; - echo '<th class="data required">'.$this->lang['strindexcolumnlist'].'</th>'; - echo '</tr>'.PHP_EOL; + echo '<th class="data">' . $this->lang['strtablecolumnlist'] . '</th><th class="data"> </th>'; + echo '<th class="data required">' . $this->lang['strindexcolumnlist'] . '</th>'; + echo '</tr>' . \PHP_EOL; - echo '<tr><td class="data1">'.$selColumns->fetch().'</td>'.PHP_EOL; - echo '<td class="data1">'.$buttonRemove->fetch().$buttonAdd->fetch().'</td>'; - echo '<td class="data1">'.$selIndex->fetch().'</td></tr>'.PHP_EOL; + echo '<tr><td class="data1">' . $selColumns->fetch() . '</td>' . \PHP_EOL; + echo '<td class="data1">' . $buttonRemove->fetch() . $buttonAdd->fetch() . '</td>'; + echo '<td class="data1">' . $selIndex->fetch() . '</td></tr>' . \PHP_EOL; echo '<tr>'; - echo '<th class="data left required" scope="row">'.$this->lang['strindextype'].'</th>'; + echo '<th class="data left required" scope="row">' . $this->lang['strindextype'] . '</th>'; echo '<td colspan="2" class="data1"><select name="formIndexType">'; + foreach ($data->typIndexes as $v) { - echo '<option value="', htmlspecialchars($v), '"', - ($v == $formIndexType) ? ' selected="selected"' : '', '>', htmlspecialchars($v), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($v), '"', + ($v === $formIndexType) ? ' selected="selected"' : '', '>', \htmlspecialchars($v), '</option>' . \PHP_EOL; } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; echo '<tr>'; echo "<th class=\"data left\" scope=\"row\"><label for=\"formUnique\">{$this->lang['strunique']}</label></th>"; echo '<td colspan="2" class="data1"><input type="checkbox" id="formUnique" name="formUnique"', ($formUnique ? 'checked="checked"' : ''), ' /></td>'; echo '</tr>'; echo '<tr>'; echo "<th class=\"data left\" scope=\"row\">{$this->lang['strwhere']}</th>"; - echo '<td colspan="2" class="data1">(<input name="formWhere" size="32" maxlength="'.$data->_maxNameLen.'" value="'.htmlspecialchars($formWhere).'" />)</td>'; + echo '<td colspan="2" class="data1">(<input name="formWhere" size="32" maxlength="' . $data->_maxNameLen . '" value="' . \htmlspecialchars($formWhere) . '" />)</td>'; echo '</tr>'; // Tablespace (if there are any) - if ($data->hasTablespaces() && $tablespaces->recordCount() > 0) { - echo '<tr>'.PHP_EOL; - echo "<th class=\"data left\">{$this->lang['strtablespace']}</th>".PHP_EOL; + if ($data->hasTablespaces() && 0 < $tablespaces->recordCount()) { + echo '<tr>' . \PHP_EOL; + echo "<th class=\"data left\">{$this->lang['strtablespace']}</th>" . \PHP_EOL; echo '<td colspan="2" class="data1">'; - echo "\n\t\t\t<select name=\"formSpc\">".PHP_EOL; + echo "\n\t\t\t<select name=\"formSpc\">" . \PHP_EOL; // Always offer the default (empty) option echo "\t\t\t\t<option value=\"\"", - ('' == $formSpc) ? ' selected="selected"' : '', '></option>'.PHP_EOL; + ('' === $formSpc) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; // Display all other tablespaces while (!$tablespaces->EOF) { - $spcname = htmlspecialchars($tablespaces->fields['spcname']); + $spcname = \htmlspecialchars($tablespaces->fields['spcname']); echo "\t\t\t\t<option value=\"{$spcname}\"", - ($spcname == $formSpc) ? ' selected="selected"' : '', ">{$spcname}</option>".PHP_EOL; + ($spcname === $formSpc) ? ' selected="selected"' : '', ">{$spcname}</option>" . \PHP_EOL; $tablespaces->moveNext(); } - echo "\t\t\t</select>\n\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>\n\t\t</td>\n\t</tr>" . \PHP_EOL; } if ($data->hasConcurrentIndexBuild()) { @@ -428,13 +435,13 @@ class IndexesController extends BaseController echo '</table>'; - echo '<p><input type="hidden" name="action" value="save_create_index" />'.PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create_index" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="subject" value="', htmlspecialchars($subject), '" />'.PHP_EOL; - echo '<input type="hidden" name="'.$subject.'" value="', htmlspecialchars($object), '" />'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="subject" value="', \htmlspecialchars($subject), '" />' . \PHP_EOL; + echo '<input type="hidden" name="' . $subject . '" value="', \htmlspecialchars($object), '" />' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** @@ -442,13 +449,13 @@ class IndexesController extends BaseController * * @@ Note: this function can't handle columns with commas in them */ - public function doSaveCreateIndex() + public function doSaveCreateIndex(): void { $data = $this->misc->getDatabaseAccessor(); $this->coalesceArr($_POST, 'subject', 'table'); - $subject = urlencode($_POST['subject']); - $object = urlencode($_POST[$subject]); + $subject = \urlencode($_POST['subject']); + $object = \urlencode($_POST[$subject]); // Handle databases that don't have partial indexes $formWhere = $this->getPostParam('formWhere', ''); @@ -459,7 +466,7 @@ class IndexesController extends BaseController $IndexColumnList = $this->getPostParam('IndexColumnList', ''); // Check that they've given a name and at least one column - if ('' == $IndexColumnList) { + if ('' === $IndexColumnList) { $this->doCreateIndex($this->lang['strindexneedscols']); } else { list($status, $sql) = $data->createIndex( @@ -473,8 +480,8 @@ class IndexesController extends BaseController $this->getPostParam('formConcur') ); - if (0 == $status) { - $this->doDefault($sql.'<br>'.$this->lang['strindexcreated']); + if (0 === $status) { + $this->doDefault($sql . '<br>' . $this->lang['strindexcreated']); } else { $this->doCreateIndex($this->lang['strindexcreatedbad']); } @@ -486,35 +493,36 @@ class IndexesController extends BaseController * * @param mixed $confirm */ - public function doDropIndex($confirm) + public function doDropIndex($confirm): void { $data = $this->misc->getDatabaseAccessor(); - $subject = urlencode($this->getRequestParam('subject', 'table')); - $object = urlencode($this->getRequestParam($subject)); + $subject = \urlencode($this->getRequestParam('subject', 'table')); + $object = \urlencode($this->getRequestParam($subject)); if ($confirm) { $this->printTrail('index'); $this->printTitle($this->lang['strdrop'], 'pg.index.drop'); - echo '<p>', sprintf($this->lang['strconfdropindex'], $this->misc->printVal($this->getRequestParam('index'))), '</p>'.PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/indexes" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="drop_index" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($object), '" />'.PHP_EOL; - echo '<input type="hidden" name="index" value="', htmlspecialchars($this->getRequestParam('index')), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropindex'], $this->misc->printVal($this->getRequestParam('index'))), '</p>' . \PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/indexes" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="drop_index" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($object), '" />' . \PHP_EOL; + echo '<input type="hidden" name="index" value="', \htmlspecialchars($this->getRequestParam('index')), '" />' . \PHP_EOL; echo $this->misc->form; echo '<p><input type="checkbox" id="cascade" name="cascade" value="1" />'; - echo '<label for="cascade">'.$this->lang['strcascade'].'</label></p>'.PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<label for="cascade">' . $this->lang['strcascade'] . '</label></p>' . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { try { list($status, $sql) = $data->dropIndex($this->getPostParam('index'), $this->getPostParam('cascade')); - if (0 == $status) { - $this->doDefault($sql.PHP_EOL.$this->lang['strindexdropped']); + + if (0 === $status) { + $this->doDefault($sql . \PHP_EOL . $this->lang['strindexdropped']); } else { - $this->doDefault($sql.PHP_EOL.$this->lang['strindexdroppedbad']); + $this->doDefault($sql . \PHP_EOL . $this->lang['strindexdroppedbad']); } } catch (\PHPPgAdmin\ADOdbException $e) { $this->doDefault($this->lang['strindexdroppedbad']); diff --git a/src/controllers/InfoController.php b/src/controllers/InfoController.php index 3d4a31a6..2e1f6a60 100644 --- a/src/controllers/InfoController.php +++ b/src/controllers/InfoController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class InfoController extends BaseController { @@ -20,9 +21,9 @@ class InfoController extends BaseController /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { - $this->printHeader($this->headerTitle('', '', $_REQUEST['table'].' - '.$this->lang['strinfo'])); + $this->printHeader($this->headerTitle('', '', $_REQUEST['table'] . ' - ' . $this->lang['strinfo'])); $this->printBody(); switch ($this->action) { @@ -63,53 +64,53 @@ class InfoController extends BaseController $indexstatsio = $data->getStatsIndexIO($_REQUEST['table']); // Check that there is some info - if (($referrers === -99 || ($referrers !== -99 && 0 == $referrers->recordCount())) - && 0 == $parents->recordCount() && 0 == $children->recordCount() - && (0 == $tablestatstups->recordCount() && 0 == $tablestatsio->recordCount() - && 0 == $indexstatstups->recordCount() && 0 == $indexstatsio->recordCount())) { + if ((-99 === $referrers || (-99 !== $referrers && 0 === $referrers->recordCount())) + && 0 === $parents->recordCount() && 0 === $children->recordCount() + && (0 === $tablestatstups->recordCount() && 0 === $tablestatsio->recordCount() + && 0 === $indexstatstups->recordCount() && 0 === $indexstatsio->recordCount())) { $this->printMsg($this->lang['strnoinfo']); return; } // Referring foreign tables - if ($referrers !== -99 && $referrers->recordCount() > 0) { + if (-99 !== $referrers && 0 < $referrers->recordCount()) { $this->_printReferring($referrers); } // Parent tables - if ($parents->recordCount() > 0) { + if (0 < $parents->recordCount()) { $this->_printParents($parents); } // Child tables - if ($children->recordCount() > 0) { + if (0 < $children->recordCount()) { $this->_printChildren($children); } // Row performance - if ($tablestatstups->recordCount() > 0) { + if (0 < $tablestatstups->recordCount()) { $this->_printTablestatstups($tablestatstups); } // I/O performance - if ($tablestatsio->recordCount() > 0) { + if (0 < $tablestatsio->recordCount()) { $this->_printTablestatsio($tablestatsio); } // Index row performance - if ($indexstatstups->recordCount() > 0) { + if (0 < $indexstatstups->recordCount()) { $this->_printIndexstatstups($indexstatstups); } // Index I/0 performance - if ($indexstatsio->recordCount() > 0) { + if (0 < $indexstatsio->recordCount()) { $this->_printIndexstatsio($indexstatsio); } } - private function _printChildren($children) + private function _printChildren($children): void { - echo "<h3>{$this->lang['strchildtables']}</h3>".PHP_EOL; + echo "<h3>{$this->lang['strchildtables']}</h3>" . \PHP_EOL; $columns = [ 'schema' => [ @@ -143,193 +144,198 @@ class InfoController extends BaseController echo $this->printTable($children, $columns, $actions, 'info-children', $this->lang['strnodata']); } - private function _printTablestatstups($tablestatstups) + private function _printTablestatstups($tablestatstups): void { - echo "<h3>{$this->lang['strrowperf']}</h3>".PHP_EOL; - - echo '<table>'.PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\" colspan=\"2\">{$this->lang['strsequential']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\" colspan=\"2\">{$this->lang['strindex']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strrows2']}</th>".PHP_EOL; - echo "\t</tr>".PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strscan']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strread']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strscan']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strfetch']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strinsert']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strupdate']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strdelete']}</th>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "<h3>{$this->lang['strrowperf']}</h3>" . \PHP_EOL; + + echo '<table>' . \PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\" colspan=\"2\">{$this->lang['strsequential']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\" colspan=\"2\">{$this->lang['strindex']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strrows2']}</th>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strscan']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strread']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strscan']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strfetch']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strinsert']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strupdate']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strdelete']}</th>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; $i = 0; while (!$tablestatstups->EOF) { - $id = (0 == ($i % 2) ? '1' : '2'); - echo "\t<tr class=\"data{$id}\">".PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['seq_scan'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['seq_tup_read'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['idx_scan'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['idx_tup_fetch'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['n_tup_ins'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['n_tup_upd'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['n_tup_del'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t</tr>".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "\t<tr class=\"data{$id}\">" . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['seq_scan'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['seq_tup_read'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['idx_scan'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['idx_tup_fetch'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['n_tup_ins'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['n_tup_upd'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatstups->fields['n_tup_del'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; $tablestatstups->movenext(); ++$i; } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; } - private function _printTablestatsio($tablestatsio) + private function _printTablestatsio($tablestatsio): void { - echo "<h3>{$this->lang['strioperf']}</h3>".PHP_EOL; - - echo '<table>'.PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strheap']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strindex']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strtoast']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strtoastindex']}</th>".PHP_EOL; - echo "\t</tr>".PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "<h3>{$this->lang['strioperf']}</h3>" . \PHP_EOL; + + echo '<table>' . \PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strheap']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strindex']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strtoast']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\" colspan=\"3\">{$this->lang['strtoastindex']}</th>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; $i = 0; while (!$tablestatsio->EOF) { - $id = (0 == ($i % 2) ? '1' : '2'); - echo "\t<tr class=\"data{$id}\">".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "\t<tr class=\"data{$id}\">" . \PHP_EOL; $total = $tablestatsio->fields['heap_blks_hit'] + $tablestatsio->fields['heap_blks_read']; - if ($total > 0) { - $percentage = round(($tablestatsio->fields['heap_blks_hit'] / $total) * 100); + + if (0 < $total) { + $percentage = \round(($tablestatsio->fields['heap_blks_hit'] / $total) * 100); } else { $percentage = 0; } - echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['heap_blks_read'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['heap_blks_hit'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>".PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['heap_blks_read'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['heap_blks_hit'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>" . \PHP_EOL; $total = $tablestatsio->fields['idx_blks_hit'] + $tablestatsio->fields['idx_blks_read']; - if ($total > 0) { - $percentage = round(($tablestatsio->fields['idx_blks_hit'] / $total) * 100); + + if (0 < $total) { + $percentage = \round(($tablestatsio->fields['idx_blks_hit'] / $total) * 100); } else { $percentage = 0; } - echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['idx_blks_read'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['idx_blks_hit'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>".PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['idx_blks_read'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['idx_blks_hit'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>" . \PHP_EOL; $total = $tablestatsio->fields['toast_blks_hit'] + $tablestatsio->fields['toast_blks_read']; - if ($total > 0) { - $percentage = round(($tablestatsio->fields['toast_blks_hit'] / $total) * 100); + + if (0 < $total) { + $percentage = \round(($tablestatsio->fields['toast_blks_hit'] / $total) * 100); } else { $percentage = 0; } - echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['toast_blks_read'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['toast_blks_hit'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>".PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['toast_blks_read'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['toast_blks_hit'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>" . \PHP_EOL; $total = $tablestatsio->fields['tidx_blks_hit'] + $tablestatsio->fields['tidx_blks_read']; - if ($total > 0) { - $percentage = round(($tablestatsio->fields['tidx_blks_hit'] / $total) * 100); + + if (0 < $total) { + $percentage = \round(($tablestatsio->fields['tidx_blks_hit'] / $total) * 100); } else { $percentage = 0; } - echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['tidx_blks_read'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['tidx_blks_hit'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['tidx_blks_read'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($tablestatsio->fields['tidx_blks_hit'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; $tablestatsio->movenext(); ++$i; } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; } - private function _printIndexstatstups($indexstatstups) + private function _printIndexstatstups($indexstatstups): void { - echo "<h3>{$this->lang['stridxrowperf']}</h3>".PHP_EOL; - - echo '<table>'.PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strindex']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strscan']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strread']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strfetch']}</th>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "<h3>{$this->lang['stridxrowperf']}</h3>" . \PHP_EOL; + + echo '<table>' . \PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strindex']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strscan']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strread']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strfetch']}</th>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; $i = 0; while (!$indexstatstups->EOF) { - $id = (0 == ($i % 2) ? '1' : '2'); - echo "\t<tr class=\"data{$id}\">".PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($indexstatstups->fields['indexrelname']), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($indexstatstups->fields['idx_scan'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($indexstatstups->fields['idx_tup_read'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($indexstatstups->fields['idx_tup_fetch'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t</tr>".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "\t<tr class=\"data{$id}\">" . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($indexstatstups->fields['indexrelname']), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($indexstatstups->fields['idx_scan'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($indexstatstups->fields['idx_tup_read'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($indexstatstups->fields['idx_tup_fetch'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; $indexstatstups->movenext(); ++$i; } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; } - private function _printIndexstatsio($indexstatsio) + private function _printIndexstatsio($indexstatsio): void { - echo "<h3>{$this->lang['stridxioperf']}</h3>".PHP_EOL; - - echo '<table>'.PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strindex']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "<h3>{$this->lang['stridxioperf']}</h3>" . \PHP_EOL; + + echo '<table>' . \PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strindex']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strdisk']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcache']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strpercent']}</th>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; $i = 0; while (!$indexstatsio->EOF) { - $id = (0 == ($i % 2) ? '1' : '2'); - echo "\t<tr class=\"data{$id}\">".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "\t<tr class=\"data{$id}\">" . \PHP_EOL; $total = $indexstatsio->fields['idx_blks_hit'] + $indexstatsio->fields['idx_blks_read']; - if ($total > 0) { - $percentage = round(($indexstatsio->fields['idx_blks_hit'] / $total) * 100); + + if (0 < $total) { + $percentage = \round(($indexstatsio->fields['idx_blks_hit'] / $total) * 100); } else { $percentage = 0; } - echo "\t\t<td>", $this->misc->printVal($indexstatsio->fields['indexrelname']), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($indexstatsio->fields['idx_blks_read'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>", $this->misc->printVal($indexstatsio->fields['idx_blks_hit'], 'int4', $this->shownull), '</td>'.PHP_EOL; - echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($indexstatsio->fields['indexrelname']), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($indexstatsio->fields['idx_blks_read'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>", $this->misc->printVal($indexstatsio->fields['idx_blks_hit'], 'int4', $this->shownull), '</td>' . \PHP_EOL; + echo "\t\t<td>({$percentage}{$this->lang['strpercent']})</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; $indexstatsio->movenext(); ++$i; } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; } - private function _printParents($parents) + private function _printParents($parents): void { - echo "<h3>{$this->lang['strparenttables']}</h3>".PHP_EOL; + echo "<h3>{$this->lang['strparenttables']}</h3>" . \PHP_EOL; $columns = [ 'schema' => [ @@ -363,9 +369,9 @@ class InfoController extends BaseController echo $this->printTable($parents, $columns, $actions, 'info-parents', $this->lang['strnodata']); } - private function _printReferring($referrers) + private function _printReferring($referrers): void { - echo "<h3>{$this->lang['strreferringtables']}</h3>".PHP_EOL; + echo "<h3>{$this->lang['strreferringtables']}</h3>" . \PHP_EOL; $columns = [ 'schema' => [ diff --git a/src/controllers/IntroController.php b/src/controllers/IntroController.php index 5f3e9420..baf2d912 100644 --- a/src/controllers/IntroController.php +++ b/src/controllers/IntroController.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class IntroController extends BaseController { @@ -44,48 +45,49 @@ class IntroController extends BaseController $intro_html .= $this->printTabs('root', 'intro', false); - $intro_html .= '<h1 style="margin-top:2em">'.$this->appName.' '.$this->appVersion.'</h1>'; - $intro_html .= '<h3>(PHP '.PHP_VERSION.')</h3>'; + $intro_html .= '<h1 style="margin-top:2em">' . $this->appName . ' ' . $this->appVersion . '</h1>'; + $intro_html .= '<h3>(PHP ' . \PHP_VERSION . ')</h3>'; $intro_html .= '<form method="get" action="intro">'; $intro_html .= '<table>'; $intro_html .= '<tr class="data1">'; - $intro_html .= '<th class="data">'.$this->lang['strlanguage'].'</th>'; + $intro_html .= '<th class="data">' . $this->lang['strlanguage'] . '</th>'; $intro_html .= '<td>'; $intro_html .= '<select name="language" onchange="this.form.submit()">'; - $language = isset($_SESSION['webdbLanguage']) ? $_SESSION['webdbLanguage'] : 'english'; + $language = $_SESSION['webdbLanguage'] ?? 'english'; + foreach ($this->appLangFiles as $k => $v) { - $selected = ($k == $language) ? ' selected="selected"' : ''; - $intro_html .= "\t<option value=\"{$k}\"".$selected.">{$v}</option>".PHP_EOL; + $selected = ($k === $language) ? ' selected="selected"' : ''; + $intro_html .= "\t<option value=\"{$k}\"" . $selected . ">{$v}</option>" . \PHP_EOL; } $intro_html .= '</select>'; $intro_html .= '</td>'; $intro_html .= '</tr>'; $intro_html .= '<tr class="data2">'; - $intro_html .= '<th class="data">'.$this->lang['strtheme'].'</th>'; + $intro_html .= '<th class="data">' . $this->lang['strtheme'] . '</th>'; $intro_html .= '<td>'; $intro_html .= '<select name="theme" onchange="this.form.submit()">'; foreach ($this->appThemes as $k => $v) { - $selected = ($k == $this->conf['theme']) ? ' selected="selected"' : ''; - $intro_html .= "\t<option value=\"{$k}\"".$selected.">{$v}</option>".PHP_EOL; + $selected = ($k === $this->conf['theme']) ? ' selected="selected"' : ''; + $intro_html .= "\t<option value=\"{$k}\"" . $selected . ">{$v}</option>" . \PHP_EOL; } $intro_html .= '</select>'; $intro_html .= '</td>'; $intro_html .= '</tr>'; $intro_html .= '</table>'; - $intro_html .= '<noscript><p><input type="submit" value="'.$this->lang['stralter'].'" /></p></noscript>'; + $intro_html .= '<noscript><p><input type="submit" value="' . $this->lang['stralter'] . '" /></p></noscript>'; $intro_html .= '</form>'; - $intro_html .= '<p>'.$this->lang['strintro'].'</p>'; + $intro_html .= '<p>' . $this->lang['strintro'] . '</p>'; $intro_html .= '<ul class="intro">'; - $intro_html .= ' <li><a href="https://github.com/HuasoFoundries/phpPgAdmin6">'.$this->lang['strppahome'].'</a></li>'; - $intro_html .= '<li><a href="'.$this->lang['strpgsqlhome_url'].'">'.$this->lang['strpgsqlhome'].'</a></li>'; - $intro_html .= '<li><a href="https://github.com/HuasoFoundries/phpPgAdmin6/issues">'.$this->lang['strreportbug'].'</a></li>'; + $intro_html .= ' <li><a href="https://github.com/HuasoFoundries/phpPgAdmin6">' . $this->lang['strppahome'] . '</a></li>'; + $intro_html .= '<li><a href="' . $this->lang['strpgsqlhome_url'] . '">' . $this->lang['strpgsqlhome'] . '</a></li>'; + $intro_html .= '<li><a href="https://github.com/HuasoFoundries/phpPgAdmin6/issues">' . $this->lang['strreportbug'] . '</a></li>'; //$intro_html .= '<li><a href="' . $this->lang['strviewfaq_url'] . '">' . $this->lang['strviewfaq'] . '</a></li>'; $intro_html .= '</ul>'; diff --git a/src/controllers/LanguagesController.php b/src/controllers/LanguagesController.php index 691c67e3..4dbb5b95 100644 --- a/src/controllers/LanguagesController.php +++ b/src/controllers/LanguagesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class LanguagesController extends BaseController { @@ -22,7 +23,7 @@ class LanguagesController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -44,7 +45,7 @@ class LanguagesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); diff --git a/src/controllers/LoginController.php b/src/controllers/LoginController.php index 9f24d2cf..7ebde768 100644 --- a/src/controllers/LoginController.php +++ b/src/controllers/LoginController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -11,20 +14,34 @@ namespace PHPPgAdmin\Controller; */ class LoginController extends BaseController { + public $appLangFiles = []; + + public $appThemes = []; + + public $appName = ''; + + public $appVersion = ''; + + public $form = ''; + + public $href = ''; + + public $lang = []; + + public $controller_title = 'strlogin'; + protected $container; + protected $_connection; + protected $app; + protected $data; + protected $database; + protected $server_id; - public $appLangFiles = []; - public $appThemes = []; - public $appName = ''; - public $appVersion = ''; - public $form = ''; - public $href = ''; - public $lang = []; - public $controller_title = 'strlogin'; + protected $no_db_connection = true; /** @@ -63,15 +80,16 @@ class LoginController extends BaseController } else { $vars = &$_GET; } + foreach ($_REQUEST as $key => $val) { - if (false !== strpos($key, '?')) { - $namexploded = explode('?', $key); - $_REQUEST[$namexploded[1]] = htmlspecialchars($val); + if (false !== \mb_strpos($key, '?')) { + $namexploded = \explode('?', $key); + $_REQUEST[$namexploded[1]] = \htmlspecialchars($val); } } $server_info = $this->misc->getServerInfo($server_id); - $title = sprintf($this->lang['strlogintitle'], $server_info['desc']); + $title = \sprintf($this->lang['strlogintitle'], $server_info['desc']); $printTitle = $this->printTitle($title, null, false); @@ -81,45 +99,47 @@ class LoginController extends BaseController $login_html .= $this->printMsg($msg, false); } - $login_html .= '<form id="login_form" method="post" name="login_form" action="'.\SUBFOLDER.'/redirect/server?server='.htmlspecialchars($server_id).'">'; + $login_html .= '<form id="login_form" method="post" name="login_form" action="' . self::SUBFOLDER . '/redirect/server?server=' . \htmlspecialchars($server_id) . '">'; - $md5_server = md5($server_id); + $md5_server = \md5($server_id); // Pass request vars through form (is this a security risk???) foreach ($vars as $key => $val) { - if ('login' == substr($key, 0, 5)) { + if ('login' === \mb_substr($key, 0, 5)) { continue; } - if (false !== strpos($key, '?')) { - $key = explode('?', $key)[1]; + + if (false !== \mb_strpos($key, '?')) { + $key = \explode('?', $key)[1]; } - $login_html .= '<input type="hidden" name="'.htmlspecialchars($key).'" value="'.htmlspecialchars($val).'" />'.PHP_EOL; + $login_html .= '<input type="hidden" name="' . \htmlspecialchars($key) . '" value="' . \htmlspecialchars($val) . '" />' . \PHP_EOL; } - $login_html .= '<input type="hidden" name="loginServer" value="'.htmlspecialchars($server_id).'" />'; + $login_html .= '<input type="hidden" name="loginServer" value="' . \htmlspecialchars($server_id) . '" />'; $login_html .= '<table class="navbar" border="0" cellpadding="5" cellspacing="3">'; $login_html .= '<tr>'; - $login_html .= '<td>'.$this->lang['strusername'].'</td>'; - $loginusername = isset($_POST['loginUsername']) ? htmlspecialchars($_POST['loginUsername']) : ''; + $login_html .= '<td>' . $this->lang['strusername'] . '</td>'; + $loginusername = isset($_POST['loginUsername']) ? \htmlspecialchars($_POST['loginUsername']) : ''; - $login_html .= '<td><input type="text" name="loginUsername" value="'.$loginusername.'" size="24" /></td>'; + $login_html .= '<td><input type="text" name="loginUsername" value="' . $loginusername . '" size="24" /></td>'; $login_html .= '</tr>'; $login_html .= '<tr>'; - $login_html .= '<td>'.$this->lang['strpassword'].'</td>'; - $login_html .= '<td><input id="loginPassword" type="password" name="loginPassword_'.$md5_server.'" size="24" /></td>'; + $login_html .= '<td>' . $this->lang['strpassword'] . '</td>'; + $login_html .= '<td><input id="loginPassword" type="password" name="loginPassword_' . $md5_server . '" size="24" /></td>'; $login_html .= '</tr>'; $login_html .= '</table>'; - if (sizeof($this->conf['servers']) > 1) { + + if (1 < \count($this->conf['servers'])) { $checked = isset($_POST['loginShared']) ? 'checked="checked"' : ''; - $login_html .= '<p><input type="checkbox" id="loginShared" name="loginShared" '.$checked.' />'; - $login_html .= '<label for="loginShared">'.$this->lang['strtrycred'].'</label></p>'; + $login_html .= '<p><input type="checkbox" id="loginShared" name="loginShared" ' . $checked . ' />'; + $login_html .= '<label for="loginShared">' . $this->lang['strtrycred'] . '</label></p>'; } - $login_html .= '<p><input type="submit" name="loginSubmit" value="'.$this->lang['strlogin'].'" /></p>'; + $login_html .= '<p><input type="submit" name="loginSubmit" value="' . $this->lang['strlogin'] . '" /></p>'; $login_html .= '</form>'; $login_html .= '<script type="text/javascript">'; $login_html .= ' var uname = document.login_form.loginUsername;'; - $login_html .= ' var pword = document.login_form.loginPassword_'.$md5_server.';'; + $login_html .= ' var pword = document.login_form.loginPassword_' . $md5_server . ';'; $login_html .= ' if (uname.value == "") {'; $login_html .= ' uname.focus();'; $login_html .= ' } else {'; diff --git a/src/controllers/MaterializedviewpropertiesController.php b/src/controllers/MaterializedviewpropertiesController.php index 9f11ca41..b4174d06 100644 --- a/src/controllers/MaterializedviewpropertiesController.php +++ b/src/controllers/MaterializedviewpropertiesController.php @@ -1,29 +1,32 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class MaterializedviewpropertiesController extends BaseController { use \PHPPgAdmin\Traits\ExportTrait; use \PHPPgAdmin\Traits\ViewsMatViewsPropertiesTrait; + public $controller_title = 'strviews'; - public $subject = 'matview'; + + public $subject = 'matview'; /** * Default method to render the controller according to the action parameter. */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -99,12 +102,13 @@ class MaterializedviewpropertiesController extends BaseController /** * Function to save after editing a matview. */ - public function doSaveEdit() + public function doSaveEdit(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->setView($_POST[$this->subject], $_POST['formDefinition'], $_POST['formComment'], true); - if (0 == $status) { + + if (0 === $status) { $this->doDefinition($this->lang['strviewupdated']); } else { $this->doEdit($this->lang['strviewupdatedbad']); @@ -117,11 +121,11 @@ class MaterializedviewpropertiesController extends BaseController public function doRefresh() { $data = $this->misc->getDatabaseAccessor(); - $sql = 'REFRESH MATERIALIZED VIEW '.$_REQUEST[$this->subject]; + $sql = 'REFRESH MATERIALIZED VIEW ' . $_REQUEST[$this->subject]; $this->prtrace($sql); $status = $data->execute($sql); - if (0 == $status) { + if (0 === $status) { return $this->doDefault($this->lang['strviewupdated']); } @@ -133,7 +137,7 @@ class MaterializedviewpropertiesController extends BaseController * * @param mixed $msg */ - public function doEdit($msg = '') + public function doEdit($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -143,29 +147,29 @@ class MaterializedviewpropertiesController extends BaseController $viewdata = $data->getView($_REQUEST[$this->subject]); - if ($viewdata->recordCount() > 0) { + if (0 < $viewdata->recordCount()) { if (!isset($_POST['formDefinition'])) { $_POST['formDefinition'] = $viewdata->fields['vwdefinition']; $_POST['formComment'] = $viewdata->fields['relcomment']; } - echo '<form action="'.\SUBFOLDER.'/src/views/materializedviewproperties" method="post">'.PHP_EOL; - echo '<table style="width: 100%">'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strdefinition']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/materializedviewproperties" method="post">' . \PHP_EOL; + echo '<table style="width: 100%">' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strdefinition']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><textarea style=\"width: 100%;\" rows=\"20\" cols=\"50\" name=\"formDefinition\">", - htmlspecialchars($_POST['formDefinition']), "</textarea></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + \htmlspecialchars($_POST['formDefinition']), "</textarea></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><textarea rows=\"3\" cols=\"32\" name=\"formComment\">", - htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_edit" />'.PHP_EOL; - echo '<input type="hidden" name="matview" value="', htmlspecialchars($_REQUEST[$this->subject]), '" />'.PHP_EOL; + \htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_edit" />' . \PHP_EOL; + echo '<input type="hidden" name="matview" value="', \htmlspecialchars($_REQUEST[$this->subject]), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } @@ -174,7 +178,7 @@ class MaterializedviewpropertiesController extends BaseController * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -186,10 +190,10 @@ class MaterializedviewpropertiesController extends BaseController $this->printTitle($this->lang['stralter'], 'pg.column.alter'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/materializedviewproperties" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/materializedviewproperties" method="post">' . \PHP_EOL; // Output matview header - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data required\">{$this->lang['strname']}</th><th class=\"data required\">{$this->lang['strtype']}</th>"; echo "<th class=\"data\">{$this->lang['strdefault']}</th><th class=\"data\">{$this->lang['strcomment']}</th></tr>"; @@ -202,29 +206,29 @@ class MaterializedviewpropertiesController extends BaseController } echo '<tr><td><input name="field" size="32" value="', - htmlspecialchars($_REQUEST['field']), '" /></td>'; + \htmlspecialchars($_REQUEST['field']), '" /></td>'; echo '<td>', $this->misc->printVal($data->formatType($column->fields['type'], $column->fields['atttypmod'])), '</td>'; echo '<td><input name="default" size="20" value="', - htmlspecialchars($_REQUEST['default']), '" /></td>'; + \htmlspecialchars($_REQUEST['default']), '" /></td>'; echo '<td><input name="comment" size="32" value="', - htmlspecialchars($_REQUEST['comment']), '" /></td>'; + \htmlspecialchars($_REQUEST['comment']), '" /></td>'; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="properties" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="2" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="properties" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="2" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="matview" value="', htmlspecialchars($_REQUEST[$this->subject]), '" />'.PHP_EOL; - echo '<input type="hidden" name="column" value="', htmlspecialchars($_REQUEST['column']), '" />'.PHP_EOL; - echo '<input type="hidden" name="olddefault" value="', htmlspecialchars($_REQUEST['olddefault']), '" />'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="matview" value="', \htmlspecialchars($_REQUEST[$this->subject]), '" />' . \PHP_EOL; + echo '<input type="hidden" name="column" value="', \htmlspecialchars($_REQUEST['column']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="olddefault" value="', \htmlspecialchars($_REQUEST['olddefault']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; break; case 2: // Check inputs - if ('' == trim($_REQUEST['field'])) { + if ('' === \trim($_REQUEST['field'])) { $_REQUEST['stage'] = 1; $this->doProperties($this->lang['strcolneedsname']); @@ -246,7 +250,8 @@ class MaterializedviewpropertiesController extends BaseController '', $_REQUEST['comment'] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strcolumnaltered']); } else { $_REQUEST['stage'] = 1; @@ -257,11 +262,11 @@ class MaterializedviewpropertiesController extends BaseController break; default: - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } } - public function doAlter($confirm = false, $msg = '') + public function doAlter($confirm = false, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -273,7 +278,7 @@ class MaterializedviewpropertiesController extends BaseController // Fetch matview info $matview = $data->getView($_REQUEST[$this->subject]); - if ($matview->recordCount() > 0) { + if (0 < $matview->recordCount()) { $this->coalesceArr($_POST, 'name', $matview->fields['relname']); $this->coalesceArr($_POST, 'owner', $matview->fields['relowner']); @@ -282,54 +287,56 @@ class MaterializedviewpropertiesController extends BaseController $this->coalesceArr($_POST, 'comment', $matview->fields['relcomment']); - echo '<form action="'.\SUBFOLDER.'/src/views/materializedviewproperties" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/materializedviewproperties" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo "<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['name']), '" /></td></tr>' . \PHP_EOL; if ($data->isSuperUser()) { // Fetch all users $users = $data->getUsers(); - echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="owner">'; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $_POST['owner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $_POST['owner']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } if ($data->hasAlterTableSchema()) { $schemas = $data->getSchemas(); - echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="newschema">'; + while (!$schemas->EOF) { $schema = $schemas->fields['nspname']; - echo '<option value="', htmlspecialchars($schema), '"', - ($schema == $_POST['newschema']) ? ' selected="selected"' : '', '>', htmlspecialchars($schema), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($schema), '"', + ($schema === $_POST['newschema']) ? ' selected="selected"' : '', '>', \htmlspecialchars($schema), '</option>' . \PHP_EOL; $schemas->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } - echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo '<textarea rows="3" cols="32" name="comment">'; - echo htmlspecialchars($_POST['comment']), '</textarea></td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<input type="hidden" name="action" value="alter" />'.PHP_EOL; - echo '<input type="hidden" name="matview" value="', htmlspecialchars($_REQUEST[$this->subject]), '" />'.PHP_EOL; + echo \htmlspecialchars($_POST['comment']), '</textarea></td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<input type="hidden" name="action" value="alter" />' . \PHP_EOL; + echo '<input type="hidden" name="matview" value="', \htmlspecialchars($_REQUEST[$this->subject]), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } else { // For databases that don't allow owner change @@ -338,17 +345,18 @@ class MaterializedviewpropertiesController extends BaseController $this->coalesceArr($_POST, 'newschema', null); $status = $data->alterMatView($_POST[$this->subject], $_POST['name'], $_POST['owner'], $_POST['newschema'], $_POST['comment']); - if (0 == $status) { + + if (0 === $status) { // If matview has been renamed, need to change to the new name and // reload the browser frame. - if ($_POST[$this->subject] != $_POST['name']) { + if ($_POST[$this->subject] !== $_POST['name']) { // Jump them to the new matview name $_REQUEST[$this->subject] = $_POST['name']; // Force a browser reload $this->misc->setReloadBrowser(true); } // If schema has changed, need to change to the new schema and reload the browser - if (!empty($_POST['newschema']) && ($_POST['newschema'] != $data->_schema)) { + if (!empty($_POST['newschema']) && ($_POST['newschema'] !== $data->_schema)) { // Jump them to the new sequence schema $this->misc->setCurrentSchema($_POST['newschema']); $this->misc->setReloadBrowser(true); diff --git a/src/controllers/MaterializedviewsController.php b/src/controllers/MaterializedviewsController.php index 981da273..0bc71bcf 100644 --- a/src/controllers/MaterializedviewsController.php +++ b/src/controllers/MaterializedviewsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,14 +13,13 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class MaterializedviewsController extends BaseController { use \PHPPgAdmin\Traits\ViewsMatviewsTrait; - public $table_place = 'matviews-matviews'; + public $table_place = 'matviews-matviews'; + public $controller_title = 'strviews'; // this member variable is view for views and matview for materialized views @@ -28,14 +30,15 @@ class MaterializedviewsController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } - if ('subtree' == $this->action) { + + if ('subtree' === $this->action) { return $this->doSubTree(); } - $this->printHeader('M '.$this->lang['strviews']); + $this->printHeader('M ' . $this->lang['strviews']); $this->printBody(); switch ($this->action) { @@ -109,7 +112,7 @@ class MaterializedviewsController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -121,9 +124,9 @@ class MaterializedviewsController extends BaseController $columns = [ $this->keystring => [ - 'title' => 'M '.$this->lang['strview'], + 'title' => 'M ' . $this->lang['strview'], 'field' => Decorator::field('relname'), - 'url' => \SUBFOLDER."/redirect/matview?{$this->misc->href}&", + 'url' => self::SUBFOLDER . "/redirect/matview?{$this->misc->href}&", 'vars' => [$this->keystring => 'relname'], ], 'owner' => [ @@ -237,7 +240,7 @@ class MaterializedviewsController extends BaseController 'content' => $this->lang['strcreatematviewwiz'], ], ]; - $this->printNavLinks($navlinks, $this->table_place, get_defined_vars()); + $this->printNavLinks($navlinks, $this->table_place, \get_defined_vars()); } /** @@ -280,45 +283,48 @@ class MaterializedviewsController extends BaseController $this->printTrail('getTrail'); $this->printTitle($this->lang['strdrop'], 'pg.matview.drop'); - echo '<form action="'.\SUBFOLDER.'/src/views/materializedviews" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/materializedviews" method="post">' . \PHP_EOL; //If multi drop if (isset($_REQUEST['ma'])) { foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfdropview'], $this->misc->printVal($a['view'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="view[]" value="', htmlspecialchars($a['view']), '" />'.PHP_EOL; + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfdropview'], $this->misc->printVal($a['view'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="view[]" value="', \htmlspecialchars($a['view']), '" />' . \PHP_EOL; } } else { - echo '<p>', sprintf($this->lang['strconfdropview'], $this->misc->printVal($_REQUEST['matview'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="view" value="', htmlspecialchars($_REQUEST['matview']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropview'], $this->misc->printVal($_REQUEST['matview'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="view" value="', \htmlspecialchars($_REQUEST['matview']), '" />' . \PHP_EOL; } - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - if (is_array($_POST['view'])) { + if (\is_array($_POST['view'])) { $msg = ''; $status = $data->beginTransaction(); - if (0 == $status) { + + if (0 === $status) { foreach ($_POST['view'] as $s) { $status = $data->dropView($s, isset($_POST['cascade'])); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strviewdropped']); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($s, \ENT_QUOTES, 'UTF-8'), $this->lang['strviewdropped']); } else { $data->endTransaction(); - $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strviewdroppedbad'])); + $this->doDefault(\sprintf('%s%s: %s<br />', $msg, \htmlentities($s, \ENT_QUOTES, 'UTF-8'), $this->lang['strviewdroppedbad'])); return; } } } - if (0 == $data->endTransaction()) { + + if (0 === $data->endTransaction()) { // Everything went fine, back to the Default page.... $this->misc->setReloadBrowser(true); $this->doDefault($msg); @@ -327,7 +333,8 @@ class MaterializedviewsController extends BaseController } } else { $status = $data->dropView($_POST['view'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strviewdropped']); } else { @@ -365,7 +372,7 @@ class MaterializedviewsController extends BaseController * * @param mixed $msg */ - public function doWizardCreate($msg = '') + public function doWizardCreate($msg = ''): void { $this->printTrail('schema'); $this->printTitle($this->lang['strcreatematviewwiz'], 'pg.matview.create'); @@ -379,7 +386,7 @@ class MaterializedviewsController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -398,40 +405,41 @@ class MaterializedviewsController extends BaseController $this->printTitle($this->lang['strcreateview'], 'pg.matview.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER."/src/views/{$this->view_name}\" method=\"post\">".PHP_EOL; - echo '<table style="width: 100%">'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . "/src/views/{$this->view_name}\" method=\"post\">" . \PHP_EOL; + echo '<table style="width: 100%">' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t<td class=\"data1\"><input name=\"formView\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['formView']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strdefinition']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['formView']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strdefinition']}</th>" . \PHP_EOL; echo "\t<td class=\"data1\"><textarea style=\"width:100%;\" rows=\"10\" cols=\"50\" name=\"formDefinition\">", - htmlspecialchars($_REQUEST['formDefinition']), "</textarea></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['formDefinition']), "</textarea></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><textarea name=\"formComment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_REQUEST['formComment']), "</textarea></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + \htmlspecialchars($_REQUEST['formComment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new view in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); // Check that they've given a name and a definition - if ('' == $_POST['formView']) { + if ('' === $_POST['formView']) { $this->doCreate($this->lang['strviewneedsname']); - } elseif ('' == $_POST['formDefinition']) { + } elseif ('' === $_POST['formDefinition']) { $this->doCreate($this->lang['strviewneedsdef']); } else { $status = $data->createView($_POST['formView'], $_POST['formDefinition'], false, $_POST['formComment'], true); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strviewcreated']); } else { diff --git a/src/controllers/OpclassesController.php b/src/controllers/OpclassesController.php index 7e27a373..75662a40 100644 --- a/src/controllers/OpclassesController.php +++ b/src/controllers/OpclassesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class OpclassesController extends BaseController { @@ -22,7 +23,7 @@ class OpclassesController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } diff --git a/src/controllers/OperatorsController.php b/src/controllers/OperatorsController.php index 23fa889a..c24dab4d 100644 --- a/src/controllers/OperatorsController.php +++ b/src/controllers/OperatorsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class OperatorsController extends BaseController { @@ -22,7 +23,7 @@ class OperatorsController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -104,7 +105,7 @@ class OperatorsController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -171,7 +172,7 @@ class OperatorsController extends BaseController * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -182,42 +183,42 @@ class OperatorsController extends BaseController $oprdata = $data->getOperator($_REQUEST['operator_oid']); $oprdata->fields['oprcanhash'] = $data->phpBool($oprdata->fields['oprcanhash']); - if ($oprdata->recordCount() > 0) { - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strname']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprname']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strleftarg']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprleftname']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strrightarg']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprrightname']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strcommutator']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprcom']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strnegator']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprnegate']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strjoin']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprjoin']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strhashes']}</th>".PHP_EOL; - echo '<td class="data1">', ($oprdata->fields['oprcanhash']) ? $this->lang['stryes'] : $this->lang['strno'], '</td></tr>'.PHP_EOL; + if (0 < $oprdata->recordCount()) { + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprname']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strleftarg']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprleftname']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strrightarg']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprrightname']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcommutator']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprcom']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strnegator']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprnegate']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strjoin']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprjoin']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strhashes']}</th>" . \PHP_EOL; + echo '<td class="data1">', ($oprdata->fields['oprcanhash']) ? $this->lang['stryes'] : $this->lang['strno'], '</td></tr>' . \PHP_EOL; // these field only exists in 8.2 and before in pg_catalog if (isset($oprdata->fields['oprlsortop'])) { - echo "<tr><th class=\"data left\">{$this->lang['strmerges']}</th>".PHP_EOL; - echo '<td class="data1">', ('0' !== $oprdata->fields['oprlsortop'] && '0' !== $oprdata->fields['oprrsortop']) ? $this->lang['stryes'] : $this->lang['strno'], '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strrestrict']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprrest']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strleftsort']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprlsortop']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strrightsort']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprrsortop']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strlessthan']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprltcmpop']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strgreaterthan']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprgtcmpop']), '</td></tr>'.PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strmerges']}</th>" . \PHP_EOL; + echo '<td class="data1">', ('0' !== $oprdata->fields['oprlsortop'] && '0' !== $oprdata->fields['oprrsortop']) ? $this->lang['stryes'] : $this->lang['strno'], '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strrestrict']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprrest']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strleftsort']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprlsortop']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strrightsort']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprrsortop']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strlessthan']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprltcmpop']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strgreaterthan']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($oprdata->fields['oprgtcmpop']), '</td></tr>' . \PHP_EOL; } else { - echo "<tr><th class=\"data left\">{$this->lang['strmerges']}</th>".PHP_EOL; - echo '<td class="data1">', $data->phpBool($oprdata->fields['oprcanmerge']) ? $this->lang['stryes'] : $this->lang['strno'], '</td></tr>'.PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strmerges']}</th>" . \PHP_EOL; + echo '<td class="data1">', $data->phpBool($oprdata->fields['oprcanmerge']) ? $this->lang['stryes'] : $this->lang['strno'], '</td></tr>' . \PHP_EOL; } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; $this->printNavLinks( [ @@ -233,9 +234,9 @@ class OperatorsController extends BaseController ], ], 'content' => $this->lang['strshowalloperators'], - ], ], + ]], 'operators-properties', - get_defined_vars() + \get_defined_vars() ); } else { $this->doDefault($this->lang['strinvalidparam']); @@ -247,7 +248,7 @@ class OperatorsController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -255,20 +256,21 @@ class OperatorsController extends BaseController $this->printTrail('operator'); $this->printTitle($this->lang['strdrop'], 'pg.operator.drop'); - echo '<p>', sprintf($this->lang['strconfdropoperator'], $this->misc->printVal($_REQUEST['operator'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropoperator'], $this->misc->printVal($_REQUEST['operator'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/operators" method="post">'.PHP_EOL; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo '<p><input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="operator" value="', htmlspecialchars($_REQUEST['operator']), '" />'.PHP_EOL; - echo '<input type="hidden" name="operator_oid" value="', htmlspecialchars($_REQUEST['operator_oid']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/operators" method="post">' . \PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="operator" value="', \htmlspecialchars($_REQUEST['operator']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="operator_oid" value="', \htmlspecialchars($_REQUEST['operator_oid']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropOperator($_POST['operator_oid'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['stroperatordropped']); } else { $this->doDefault($this->lang['stroperatordroppedbad']); diff --git a/src/controllers/PrivilegesController.php b/src/controllers/PrivilegesController.php index 17a45a4e..3c34b23c 100644 --- a/src/controllers/PrivilegesController.php +++ b/src/controllers/PrivilegesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -11,13 +14,14 @@ namespace PHPPgAdmin\Controller; */ class PrivilegesController extends BaseController { - public $table_place = 'privileges-privileges'; + public $table_place = 'privileges-privileges'; + public $controller_title = 'strprivileges'; /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { $this->printHeader(); $this->printBody(); @@ -49,7 +53,7 @@ class PrivilegesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $subject = $_REQUEST['subject']; @@ -60,7 +64,7 @@ class PrivilegesController extends BaseController // need a better way, maybe every type of object should // have a tab bar??? - if (in_array($subject, [ + if (\in_array($subject, [ 'server', 'database', 'schema', @@ -75,28 +79,30 @@ class PrivilegesController extends BaseController } $this->printMsg($msg); + if (!isset($data->privlist[$subject])) { - $this->container->utils->halt('No privileges defined for subject '.$subject); + $this->container->utils->halt('No privileges defined for subject ' . $subject); return; } // Determine whether object should be ref'd by name or oid. - if (isset($_REQUEST[$subject.'_oid'])) { - $object = $_REQUEST[$subject.'_oid']; + if (isset($_REQUEST[$subject . '_oid'])) { + $object = $_REQUEST[$subject . '_oid']; } else { $object = $_REQUEST[$subject]; } // Get the privileges on the object, given its type - if ('column' == $subject) { + if ('column' === $subject) { $privileges = $data->getPrivileges($object, 'column', $_REQUEST['table']); } else { $privileges = $data->getPrivileges($object, $subject); } - if (sizeof($privileges) > 0) { - echo '<table>'.PHP_EOL; + if (0 < \count($privileges)) { + echo '<table>' . \PHP_EOL; + if ($data->hasRoles()) { echo "<tr><th class=\"data\">{$this->lang['strrole']}</th>"; } else { @@ -105,62 +111,68 @@ class PrivilegesController extends BaseController foreach ($data->privlist[$subject] as $v2) { // Skip over ALL PRIVILEGES - if ('ALL PRIVILEGES' == $v2) { + if ('ALL PRIVILEGES' === $v2) { continue; } - echo "<th class=\"data\">{$v2}</th>".PHP_EOL; + echo "<th class=\"data\">{$v2}</th>" . \PHP_EOL; } + if ($data->hasGrantOption()) { echo "<th class=\"data\">{$this->lang['strgrantor']}</th>"; } - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; // Loop over privileges, outputting them $i = 0; + foreach ($privileges as $v) { - $id = (0 == ($i % 2) ? '1' : '2'); - echo "<tr class=\"data{$id}\">".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "<tr class=\"data{$id}\">" . \PHP_EOL; + if (!$data->hasRoles()) { - echo '<td>', $this->misc->printVal($v[0]), '</td>'.PHP_EOL; + echo '<td>', $this->misc->printVal($v[0]), '</td>' . \PHP_EOL; } - echo '<td>', $this->misc->printVal($v[1]), '</td>'.PHP_EOL; + echo '<td>', $this->misc->printVal($v[1]), '</td>' . \PHP_EOL; + foreach ($data->privlist[$subject] as $v2) { // Skip over ALL PRIVILEGES - if ('ALL PRIVILEGES' == $v2) { + if ('ALL PRIVILEGES' === $v2) { continue; } echo '<td>'; - if (in_array($v2, $v[2], true)) { + + if (\in_array($v2, $v[2], true)) { echo $this->lang['stryes']; } else { echo $this->lang['strno']; } // If we have grant option for this, end mark - if ($data->hasGrantOption() && in_array($v2, $v[4], true)) { + if ($data->hasGrantOption() && \in_array($v2, $v[4], true)) { echo $this->lang['strasterisk']; } - echo '</td>'.PHP_EOL; + echo '</td>' . \PHP_EOL; } + if ($data->hasGrantOption()) { - echo '<td>', $this->misc->printVal($v[3]), '</td>'.PHP_EOL; + echo '<td>', $this->misc->printVal($v[3]), '</td>' . \PHP_EOL; } - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; ++$i; } echo '</table>'; } else { - echo "<p>{$this->lang['strnoprivileges']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnoprivileges']}</p>" . \PHP_EOL; } $this->printGrantLinks(); } - public function printGrantLinks() + public function printGrantLinks(): void { $data = $this->misc->getDatabaseAccessor(); $subject = $_REQUEST['subject']; @@ -194,8 +206,8 @@ class PrivilegesController extends BaseController $object = $_REQUEST[$subject]; - if ('function' == $subject) { - $objectoid = $_REQUEST[$subject.'_oid']; + if ('function' === $subject) { + $objectoid = $_REQUEST[$subject . '_oid']; $urlvars = [ 'action' => 'alter', 'server' => $_REQUEST['server'], @@ -205,7 +217,7 @@ class PrivilegesController extends BaseController "{$subject}_oid" => $objectoid, 'subject' => $subject, ]; - } elseif ('column' == $subject) { + } elseif ('column' === $subject) { $urlvars = [ 'action' => 'alter', 'server' => $_REQUEST['server'], @@ -230,6 +242,7 @@ class PrivilegesController extends BaseController $subject => $object, 'subject' => $subject, ]; + if (isset($_REQUEST['schema'])) { $urlvars['schema'] = $_REQUEST['schema']; } @@ -240,7 +253,7 @@ class PrivilegesController extends BaseController 'attr' => [ 'href' => [ 'url' => 'privileges', - 'urlvars' => array_merge($urlvars, ['mode' => 'grant']), + 'urlvars' => \array_merge($urlvars, ['mode' => 'grant']), ], ], 'content' => $this->lang['strgrant'], @@ -249,7 +262,7 @@ class PrivilegesController extends BaseController 'attr' => [ 'href' => [ 'url' => 'privileges', - 'urlvars' => array_merge($urlvars, ['mode' => 'revoke']), + 'urlvars' => \array_merge($urlvars, ['mode' => 'revoke']), ], ], 'content' => $this->lang['strrevoke'], @@ -269,12 +282,13 @@ class PrivilegesController extends BaseController ], 'content' => $alltxt, ]; + if (isset($_REQUEST['schema'])) { $navlinks[$alllabel]['attr']['href']['urlvars']['schema'] = $_REQUEST['schema']; } } - $this->printNavLinks($navlinks, $this->table_place, get_defined_vars()); + $this->printNavLinks($navlinks, $this->table_place, \get_defined_vars()); } /** @@ -283,7 +297,7 @@ class PrivilegesController extends BaseController * @param string $mode either grant or revoke * @param string $msg The message */ - public function formAlter($mode, $msg = '') + public function formAlter($mode, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -300,81 +314,87 @@ class PrivilegesController extends BaseController $this->printTrail($_REQUEST['subject']); - $this->printTitle($this->lang['str'.$mode], 'pg.privilege.'.$mode); + $this->printTitle($this->lang['str' . $mode], 'pg.privilege.' . $mode); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/privileges" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strusers']}</th>".PHP_EOL; - echo '<td class="data1"><select name="username[]" multiple="multiple" size="', min(6, $users->recordCount()), '">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/privileges" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strusers']}</th>" . \PHP_EOL; + echo '<td class="data1"><select name="username[]" multiple="multiple" size="', \min(6, $users->recordCount()), '">' . \PHP_EOL; + while (!$users->EOF) { - $uname = htmlspecialchars($users->fields['usename']); + $uname = \htmlspecialchars($users->fields['usename']); echo "<option value=\"{$uname}\"", - in_array($users->fields['usename'], $_REQUEST['username'], true) ? ' selected="selected"' : '', ">{$uname}</option>".PHP_EOL; + \in_array($users->fields['usename'], $_REQUEST['username'], true) ? ' selected="selected"' : '', ">{$uname}</option>" . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strgroups']}</th>".PHP_EOL; - echo '<td class="data1">'.PHP_EOL; - echo '<input type="checkbox" id="public" name="public"', (isset($_REQUEST['public']) ? ' checked="checked"' : ''), ' /><label for="public">PUBLIC</label>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strgroups']}</th>" . \PHP_EOL; + echo '<td class="data1">' . \PHP_EOL; + echo '<input type="checkbox" id="public" name="public"', (isset($_REQUEST['public']) ? ' checked="checked"' : ''), ' /><label for="public">PUBLIC</label>' . \PHP_EOL; // Only show groups if there are groups! - if ($groups->recordCount() > 0) { - echo '<br /><select name="groupname[]" multiple="multiple" size="', min(6, $groups->recordCount()), '">'.PHP_EOL; + if (0 < $groups->recordCount()) { + echo '<br /><select name="groupname[]" multiple="multiple" size="', \min(6, $groups->recordCount()), '">' . \PHP_EOL; + while (!$groups->EOF) { - $gname = htmlspecialchars($groups->fields['groname']); + $gname = \htmlspecialchars($groups->fields['groname']); echo "<option value=\"{$gname}\"", - in_array($groups->fields['groname'], $_REQUEST['groupname'], true) ? ' selected="selected"' : '', ">{$gname}</option>".PHP_EOL; + \in_array($groups->fields['groname'], $_REQUEST['groupname'], true) ? ' selected="selected"' : '', ">{$gname}</option>" . \PHP_EOL; $groups->moveNext(); } - echo '</select>'.PHP_EOL; + echo '</select>' . \PHP_EOL; } - echo '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strprivileges']}</th>".PHP_EOL; - echo '<td class="data1">'.PHP_EOL; + echo '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strprivileges']}</th>" . \PHP_EOL; + echo '<td class="data1">' . \PHP_EOL; + foreach ($data->privlist[$_REQUEST['subject']] as $v) { - $v = htmlspecialchars($v); - echo "<input type=\"checkbox\" id=\"privilege[${v}]\" name=\"privilege[${v}]\"", - isset($_REQUEST['privilege'][$v]) ? ' checked="checked"' : '', " /><label for=\"privilege[${v}]\">{$v}</label><br />".PHP_EOL; + $v = \htmlspecialchars($v); + echo "<input type=\"checkbox\" id=\"privilege[{$v}]\" name=\"privilege[{$v}]\"", + isset($_REQUEST['privilege'][$v]) ? ' checked="checked"' : '', " /><label for=\"privilege[{$v}]\">{$v}</label><br />" . \PHP_EOL; } - echo '</td></tr>'.PHP_EOL; + echo '</td></tr>' . \PHP_EOL; // Grant option if ($data->hasGrantOption()) { - echo "<tr><th class=\"data left\">{$this->lang['stroptions']}</th>".PHP_EOL; - echo '<td class="data1">'.PHP_EOL; - if ('grant' == $mode) { + echo "<tr><th class=\"data left\">{$this->lang['stroptions']}</th>" . \PHP_EOL; + echo '<td class="data1">' . \PHP_EOL; + + if ('grant' === $mode) { echo '<input type="checkbox" id="grantoption" name="grantoption"', - isset($_REQUEST['grantoption']) ? ' checked="checked"' : '', ' /><label for="grantoption">GRANT OPTION</label>'.PHP_EOL; - } elseif ('revoke' == $mode) { + isset($_REQUEST['grantoption']) ? ' checked="checked"' : '', ' /><label for="grantoption">GRANT OPTION</label>' . \PHP_EOL; + } elseif ('revoke' === $mode) { echo '<input type="checkbox" id="grantoption" name="grantoption"', - isset($_REQUEST['grantoption']) ? ' checked="checked"' : '', ' /><label for="grantoption">GRANT OPTION FOR</label><br />'.PHP_EOL; + isset($_REQUEST['grantoption']) ? ' checked="checked"' : '', ' /><label for="grantoption">GRANT OPTION FOR</label><br />' . \PHP_EOL; echo '<input type="checkbox" id="cascade" name="cascade"', - isset($_REQUEST['cascade']) ? ' checked="checked"' : '', ' /><label for="cascade">CASCADE</label><br />'.PHP_EOL; + isset($_REQUEST['cascade']) ? ' checked="checked"' : '', ' /><label for="cascade">CASCADE</label><br />' . \PHP_EOL; } - echo '</td></tr>'.PHP_EOL; + echo '</td></tr>' . \PHP_EOL; } - echo '</table>'.PHP_EOL; - - echo '<p><input type="hidden" name="action" value="save" />'.PHP_EOL; - echo '<input type="hidden" name="mode" value="', htmlspecialchars($mode), '" />'.PHP_EOL; - echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['subject']), '" />'.PHP_EOL; - if (isset($_REQUEST[$_REQUEST['subject'].'_oid'])) { - echo '<input type="hidden" name="', htmlspecialchars($_REQUEST['subject'].'_oid'), - '" value="', htmlspecialchars($_REQUEST[$_REQUEST['subject'].'_oid']), '" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + + echo '<p><input type="hidden" name="action" value="save" />' . \PHP_EOL; + echo '<input type="hidden" name="mode" value="', \htmlspecialchars($mode), '" />' . \PHP_EOL; + echo '<input type="hidden" name="subject" value="', \htmlspecialchars($_REQUEST['subject']), '" />' . \PHP_EOL; + + if (isset($_REQUEST[$_REQUEST['subject'] . '_oid'])) { + echo '<input type="hidden" name="', \htmlspecialchars($_REQUEST['subject'] . '_oid'), + '" value="', \htmlspecialchars($_REQUEST[$_REQUEST['subject'] . '_oid']), '" />' . \PHP_EOL; } - echo '<input type="hidden" name="', htmlspecialchars($_REQUEST['subject']), - '" value="', htmlspecialchars($_REQUEST[$_REQUEST['subject']]), '" />'.PHP_EOL; - if ('column' == $_REQUEST['subject']) { + echo '<input type="hidden" name="', \htmlspecialchars($_REQUEST['subject']), + '" value="', \htmlspecialchars($_REQUEST[$_REQUEST['subject']]), '" />' . \PHP_EOL; + + if ('column' === $_REQUEST['subject']) { echo '<input type="hidden" name="table" value="', - htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; + \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; } echo $this->misc->form; - echo sprintf('<input type="submit" name="%s" value="%s" />%s', $mode, $this->lang['str'.$mode], PHP_EOL); + echo \sprintf('<input type="submit" name="%s" value="%s" />%s', $mode, $this->lang['str' . $mode], \PHP_EOL); echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>"; - echo '</form>'.PHP_EOL; + echo '</form>' . \PHP_EOL; } /** @@ -382,7 +402,7 @@ class PrivilegesController extends BaseController * * @param string $mode 'grant' or 'revoke' */ - public function doAlter($mode) + public function doAlter($mode): void { $data = $this->misc->getDatabaseAccessor(); @@ -393,8 +413,8 @@ class PrivilegesController extends BaseController $this->coalesceArr($_REQUEST, 'privilege', []); // Determine whether object should be ref'd by name or oid. - if (isset($_REQUEST[$_REQUEST['subject'].'_oid'])) { - $object = $_REQUEST[$_REQUEST['subject'].'_oid']; + if (isset($_REQUEST[$_REQUEST['subject'] . '_oid'])) { + $object = $_REQUEST[$_REQUEST['subject'] . '_oid']; } else { $object = $_REQUEST[$_REQUEST['subject']]; } @@ -406,21 +426,21 @@ class PrivilegesController extends BaseController } $status = $data->setPrivileges( - ('grant' == $mode) ? 'GRANT' : 'REVOKE', + ('grant' === $mode) ? 'GRANT' : 'REVOKE', $_REQUEST['subject'], $object, isset($_REQUEST['public']), $_REQUEST['username'], $_REQUEST['groupname'], - array_keys($_REQUEST['privilege']), + \array_keys($_REQUEST['privilege']), isset($_REQUEST['grantoption']), isset($_REQUEST['cascade']), $table ); - if (0 == $status) { + if (0 === $status) { $this->doDefault($this->lang['strgranted']); - } elseif ($status == -3 || $status == -4) { + } elseif (-3 === $status || -4 === $status) { $this->formAlter($_REQUEST['mode'], $this->lang['strgrantbad']); } else { $this->formAlter($_REQUEST['mode'], $this->lang['strgrantfailed']); diff --git a/src/controllers/RolesController.php b/src/controllers/RolesController.php index 782359c5..5c7e9113 100644 --- a/src/controllers/RolesController.php +++ b/src/controllers/RolesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class RolesController extends BaseController { @@ -20,7 +21,7 @@ class RolesController extends BaseController /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { $this->printHeader(); $this->printBody(); @@ -94,17 +95,17 @@ class RolesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $lang = $this->lang; - $renderRoleConnLimit = function ($val) use ($lang) { - return '-1' == $val ? $lang['strnolimit'] : htmlspecialchars($val); + $renderRoleConnLimit = static function ($val) use ($lang) { + return '-1' === $val ? $lang['strnolimit'] : \htmlspecialchars($val); }; - $renderRoleExpires = function ($val) use ($lang) { - return 'infinity' == $val ? $lang['strnever'] : htmlspecialchars($val); + $renderRoleExpires = static function ($val) use ($lang) { + return 'infinity' === $val ? $lang['strnever'] : \htmlspecialchars($val); }; $this->printTrail('server'); @@ -117,7 +118,7 @@ class RolesController extends BaseController 'role' => [ 'title' => $this->lang['strrole'], 'field' => Decorator::field('rolname'), - 'url' => \SUBFOLDER."/redirect/role?action=properties&{$this->misc->href}&", + 'url' => self::SUBFOLDER . "/redirect/role?action=properties&{$this->misc->href}&", 'vars' => ['rolename' => 'rolname'], ], 'group' => [ @@ -209,7 +210,7 @@ class RolesController extends BaseController 'content' => $this->lang['strcreaterole'], ], ]; - $this->printNavLinks($navlinks, 'roles-roles', get_defined_vars()); + $this->printNavLinks($navlinks, 'roles-roles', \get_defined_vars()); } /** @@ -217,7 +218,7 @@ class RolesController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -241,87 +242,91 @@ class RolesController extends BaseController $this->printTitle($this->lang['strcreaterole'], 'pg.role.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/roles" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\" style=\"width: 130px\">{$this->lang['strname']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"15\" maxlength=\"{$data->_maxNameLen}\" name=\"formRolename\" value=\"", htmlspecialchars($_POST['formRolename']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strpassword']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"15\" type=\"password\" name=\"formPassword\" value=\"", htmlspecialchars($_POST['formPassword']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconfirm']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"15\" type=\"password\" name=\"formConfirm\" value=\"", htmlspecialchars($_POST['formConfirm']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formSuper\">{$this->lang['strsuper']}</label></th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/roles" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\" style=\"width: 130px\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"15\" maxlength=\"{$data->_maxNameLen}\" name=\"formRolename\" value=\"", \htmlspecialchars($_POST['formRolename']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strpassword']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"15\" type=\"password\" name=\"formPassword\" value=\"", \htmlspecialchars($_POST['formPassword']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconfirm']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"15\" type=\"password\" name=\"formConfirm\" value=\"", \htmlspecialchars($_POST['formConfirm']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formSuper\">{$this->lang['strsuper']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formSuper\" name=\"formSuper\"", - (isset($_POST['formSuper'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateDB\">{$this->lang['strcreatedb']}</label></th>".PHP_EOL; + (isset($_POST['formSuper'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateDB\">{$this->lang['strcreatedb']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formCreateDB\" name=\"formCreateDB\"", - (isset($_POST['formCreateDB'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateRole\">{$this->lang['strcancreaterole']}</label></th>".PHP_EOL; + (isset($_POST['formCreateDB'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateRole\">{$this->lang['strcancreaterole']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formCreateRole\" name=\"formCreateRole\"", - (isset($_POST['formCreateRole'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formInherits\">{$this->lang['strinheritsprivs']}</label></th>".PHP_EOL; + (isset($_POST['formCreateRole'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formInherits\">{$this->lang['strinheritsprivs']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formInherits\" name=\"formInherits\"", - (isset($_POST['formInherits'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCanLogin\">{$this->lang['strcanlogin']}</label></th>".PHP_EOL; + (isset($_POST['formInherits'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCanLogin\">{$this->lang['strcanlogin']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formCanLogin\" name=\"formCanLogin\"", - (isset($_POST['formCanLogin'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconnlimit']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"4\" name=\"formConnLimit\" value=\"", htmlspecialchars($_POST['formConnLimit']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strexpires']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"23\" name=\"formExpires\" value=\"", htmlspecialchars($_POST['formExpires']), "\" /></td>\n\t</tr>".PHP_EOL; + (isset($_POST['formCanLogin'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconnlimit']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"4\" name=\"formConnLimit\" value=\"", \htmlspecialchars($_POST['formConnLimit']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strexpires']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"23\" name=\"formExpires\" value=\"", \htmlspecialchars($_POST['formExpires']), "\" /></td>\n\t</tr>" . \PHP_EOL; $roles = $data->getRoles(); - if ($roles->recordCount() > 0) { - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmemberof']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\">".PHP_EOL; - echo "\t\t\t<select name=\"memberof[]\" multiple=\"multiple\" size=\"", min(20, $roles->recordCount()), '">'.PHP_EOL; + + if (0 < $roles->recordCount()) { + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmemberof']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\">" . \PHP_EOL; + echo "\t\t\t<select name=\"memberof[]\" multiple=\"multiple\" size=\"", \min(20, $roles->recordCount()), '">' . \PHP_EOL; + while (!$roles->EOF) { $rolename = $roles->fields['rolname']; echo "\t\t\t\t<option value=\"{$rolename}\"", - (in_array($rolename, $_POST['memberof'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>'.PHP_EOL; + (\in_array($rolename, $_POST['memberof'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>' . \PHP_EOL; $roles->moveNext(); } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; $roles->moveFirst(); - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmembers']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\">".PHP_EOL; - echo "\t\t\t<select name=\"members[]\" multiple=\"multiple\" size=\"", min(20, $roles->recordCount()), '">'.PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmembers']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\">" . \PHP_EOL; + echo "\t\t\t<select name=\"members[]\" multiple=\"multiple\" size=\"", \min(20, $roles->recordCount()), '">' . \PHP_EOL; + while (!$roles->EOF) { $rolename = $roles->fields['rolname']; echo "\t\t\t\t<option value=\"{$rolename}\"", - (in_array($rolename, $_POST['members'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>'.PHP_EOL; + (\in_array($rolename, $_POST['members'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>' . \PHP_EOL; $roles->moveNext(); } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; $roles->moveFirst(); - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['stradminmembers']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\">".PHP_EOL; - echo "\t\t\t<select name=\"adminmembers[]\" multiple=\"multiple\" size=\"", min(20, $roles->recordCount()), '">'.PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['stradminmembers']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\">" . \PHP_EOL; + echo "\t\t\t<select name=\"adminmembers[]\" multiple=\"multiple\" size=\"", \min(20, $roles->recordCount()), '">' . \PHP_EOL; + while (!$roles->EOF) { $rolename = $roles->fields['rolname']; echo "\t\t\t\t<option value=\"{$rolename}\"", - (in_array($rolename, $_POST['adminmembers'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>'.PHP_EOL; + (\in_array($rolename, $_POST['adminmembers'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>' . \PHP_EOL; $roles->moveNext(); } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new role in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); @@ -332,9 +337,9 @@ class RolesController extends BaseController $this->coalesceArr($_POST, 'adminmembers', []); // Check data - if ('' == $_POST['formRolename']) { + if ('' === $_POST['formRolename']) { $this->doCreate($this->lang['strroleneedsname']); - } elseif ($_POST['formPassword'] != $_POST['formConfirm']) { + } elseif ($_POST['formPassword'] !== $_POST['formConfirm']) { $this->doCreate($this->lang['strpasswordconfirm']); } else { $status = $data->createRole( @@ -351,7 +356,8 @@ class RolesController extends BaseController $_POST['members'], $_POST['adminmembers'] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strrolecreated']); } else { $this->doCreate($this->lang['strrolecreatedbad']); @@ -360,100 +366,11 @@ class RolesController extends BaseController } /** - * Adjusts the content of the $_POST superglobal according to role data. - * - * @param \PHPPgAdmin\ADORecordSet $roledata The roledata - * @param bool $canRename Indicates if role can be renamed - */ - private function _adjustPostVars($roledata, $canRename) - { - if (isset($_POST['formExpires'])) { - return; - } - - if ($canRename) { - $_POST['formNewRoleName'] = $roledata->fields['rolname']; - } - - if ($roledata->fields['rolsuper']) { - $_POST['formSuper'] = ''; - } - - if ($roledata->fields['rolcreatedb']) { - $_POST['formCreateDB'] = ''; - } - - if ($roledata->fields['rolcreaterole']) { - $_POST['formCreateRole'] = ''; - } - - if ($roledata->fields['rolinherit']) { - $_POST['formInherits'] = ''; - } - - if ($roledata->fields['rolcanlogin']) { - $_POST['formCanLogin'] = ''; - } - - $_POST['formConnLimit'] = '-1' == $roledata->fields['rolconnlimit'] ? '' : $roledata->fields['rolconnlimit']; - $_POST['formExpires'] = 'infinity' == $roledata->fields['rolvaliduntil'] ? '' : $roledata->fields['rolvaliduntil']; - $_POST['formPassword'] = ''; - } - - private function _populateMemberof($data) - { - if (!isset($_POST['memberof'])) { - $memberof = $data->getMemberOf($_REQUEST['rolename']); - if ($memberof->recordCount() > 0) { - $i = 0; - while (!$memberof->EOF) { - $_POST['memberof'][$i++] = $memberof->fields['rolname']; - $memberof->moveNext(); - } - } else { - $_POST['memberof'] = []; - } - } - } - - private function _populateMembers($data) - { - if (!isset($_POST['members'])) { - $members = $data->getMembers($_REQUEST['rolename']); - if ($members->recordCount() > 0) { - $i = 0; - while (!$members->EOF) { - $_POST['members'][$i++] = $members->fields['rolname']; - $members->moveNext(); - } - } else { - $_POST['members'] = []; - } - } - } - - private function _populateAdminmembers($data) - { - if (!isset($_POST['adminmembers'])) { - $adminmembers = $data->getMembers($_REQUEST['rolename'], 't'); - if ($adminmembers->recordCount() > 0) { - $i = 0; - while (!$adminmembers->EOF) { - $_POST['adminmembers'][$i++] = $adminmembers->fields['rolname']; - $adminmembers->moveNext(); - } - } else { - $_POST['adminmembers'] = []; - } - } - } - - /** * Function to allow alter a role. * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -463,13 +380,13 @@ class RolesController extends BaseController $roledata = $data->getRole($_REQUEST['rolename']); - if ($roledata->recordCount() <= 0) { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + if (0 >= $roledata->recordCount()) { + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; return; } $server_info = $this->misc->getServerInfo(); - $canRename = $data->hasUserRename() && ($_REQUEST['rolename'] != $server_info['username']); + $canRename = $data->hasUserRename() && ($_REQUEST['rolename'] !== $server_info['username']); $roledata->fields['rolsuper'] = $data->phpBool($roledata->fields['rolsuper']); $roledata->fields['rolcreatedb'] = $data->phpBool($roledata->fields['rolcreatedb']); $roledata->fields['rolcreaterole'] = $data->phpBool($roledata->fields['rolcreaterole']); @@ -478,100 +395,104 @@ class RolesController extends BaseController $this->_adjustPostVars($roledata, $canRename); - echo '<form action="'.\SUBFOLDER.'/src/views/roles" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\" style=\"width: 130px\">{$this->lang['strname']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">", ($canRename ? "<input name=\"formNewRoleName\" size=\"15\" maxlength=\"{$data->_maxNameLen}\" value=\"".htmlspecialchars($_POST['formNewRoleName']).'" />' : $this->misc->printVal($roledata->fields['rolname'])), "</td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strpassword']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input type=\"password\" size=\"15\" name=\"formPassword\" value=\"", htmlspecialchars($_POST['formPassword']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconfirm']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input type=\"password\" size=\"15\" name=\"formConfirm\" value=\"\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formSuper\">{$this->lang['strsuper']}</label></th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/roles" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\" style=\"width: 130px\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">", ($canRename ? "<input name=\"formNewRoleName\" size=\"15\" maxlength=\"{$data->_maxNameLen}\" value=\"" . \htmlspecialchars($_POST['formNewRoleName']) . '" />' : $this->misc->printVal($roledata->fields['rolname'])), "</td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strpassword']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input type=\"password\" size=\"15\" name=\"formPassword\" value=\"", \htmlspecialchars($_POST['formPassword']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconfirm']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input type=\"password\" size=\"15\" name=\"formConfirm\" value=\"\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formSuper\">{$this->lang['strsuper']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formSuper\" name=\"formSuper\"", - (isset($_POST['formSuper'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateDB\">{$this->lang['strcreatedb']}</label></th>".PHP_EOL; + (isset($_POST['formSuper'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateDB\">{$this->lang['strcreatedb']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formCreateDB\" name=\"formCreateDB\"", - (isset($_POST['formCreateDB'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateRole\">{$this->lang['strcancreaterole']}</label></th>".PHP_EOL; + (isset($_POST['formCreateDB'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateRole\">{$this->lang['strcancreaterole']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formCreateRole\" name=\"formCreateRole\"", - (isset($_POST['formCreateRole'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formInherits\">{$this->lang['strinheritsprivs']}</label></th>".PHP_EOL; + (isset($_POST['formCreateRole'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formInherits\">{$this->lang['strinheritsprivs']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formInherits\" name=\"formInherits\"", - (isset($_POST['formInherits'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCanLogin\">{$this->lang['strcanlogin']}</label></th>".PHP_EOL; + (isset($_POST['formInherits'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCanLogin\">{$this->lang['strcanlogin']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formCanLogin\" name=\"formCanLogin\"", - (isset($_POST['formCanLogin'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconnlimit']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"4\" name=\"formConnLimit\" value=\"", htmlspecialchars($_POST['formConnLimit']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strexpires']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"23\" name=\"formExpires\" value=\"", htmlspecialchars($_POST['formExpires']), "\" /></td>\n\t</tr>".PHP_EOL; + (isset($_POST['formCanLogin'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconnlimit']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"4\" name=\"formConnLimit\" value=\"", \htmlspecialchars($_POST['formConnLimit']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strexpires']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"23\" name=\"formExpires\" value=\"", \htmlspecialchars($_POST['formExpires']), "\" /></td>\n\t</tr>" . \PHP_EOL; $this->_populateMemberof($data); - $memberofold = implode(',', $_POST['memberof']); + $memberofold = \implode(',', $_POST['memberof']); $this->_populateMembers($data); - $membersold = implode(',', $_POST['members']); + $membersold = \implode(',', $_POST['members']); $this->_populateAdminmembers($data); - $adminmembersold = implode(',', $_POST['adminmembers']); + $adminmembersold = \implode(',', $_POST['adminmembers']); $roles = $data->getRoles($_REQUEST['rolename']); - if ($roles->recordCount() > 0) { - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmemberof']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\">".PHP_EOL; - echo "\t\t\t<select name=\"memberof[]\" multiple=\"multiple\" size=\"", min(20, $roles->recordCount()), '">'.PHP_EOL; + + if (0 < $roles->recordCount()) { + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmemberof']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\">" . \PHP_EOL; + echo "\t\t\t<select name=\"memberof[]\" multiple=\"multiple\" size=\"", \min(20, $roles->recordCount()), '">' . \PHP_EOL; + while (!$roles->EOF) { $rolename = $roles->fields['rolname']; echo "\t\t\t\t<option value=\"{$rolename}\"", - (in_array($rolename, $_POST['memberof'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>'.PHP_EOL; + (\in_array($rolename, $_POST['memberof'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>' . \PHP_EOL; $roles->moveNext(); } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; $roles->moveFirst(); - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmembers']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\">".PHP_EOL; - echo "\t\t\t<select name=\"members[]\" multiple=\"multiple\" size=\"", min(20, $roles->recordCount()), '">'.PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strmembers']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\">" . \PHP_EOL; + echo "\t\t\t<select name=\"members[]\" multiple=\"multiple\" size=\"", \min(20, $roles->recordCount()), '">' . \PHP_EOL; + while (!$roles->EOF) { $rolename = $roles->fields['rolname']; echo "\t\t\t\t<option value=\"{$rolename}\"", - (in_array($rolename, $_POST['members'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>'.PHP_EOL; + (\in_array($rolename, $_POST['members'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>' . \PHP_EOL; $roles->moveNext(); } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; $roles->moveFirst(); - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['stradminmembers']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\">".PHP_EOL; - echo "\t\t\t<select name=\"adminmembers[]\" multiple=\"multiple\" size=\"", min(20, $roles->recordCount()), '">'.PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['stradminmembers']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\">" . \PHP_EOL; + echo "\t\t\t<select name=\"adminmembers[]\" multiple=\"multiple\" size=\"", \min(20, $roles->recordCount()), '">' . \PHP_EOL; + while (!$roles->EOF) { $rolename = $roles->fields['rolname']; echo "\t\t\t\t<option value=\"{$rolename}\"", - (in_array($rolename, $_POST['adminmembers'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>'.PHP_EOL; + (\in_array($rolename, $_POST['adminmembers'], true) ? ' selected="selected"' : ''), '>', $this->misc->printVal($rolename), '</option>' . \PHP_EOL; $roles->moveNext(); } - echo "\t\t\t</select>".PHP_EOL; - echo "\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>" . \PHP_EOL; + echo "\t\t</td>\n\t</tr>" . \PHP_EOL; } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_alter" />'.PHP_EOL; - echo '<input type="hidden" name="rolename" value="', htmlspecialchars($_REQUEST['rolename']), '" />'.PHP_EOL; - echo '<input type="hidden" name="memberofold" value="', isset($_POST['memberofold']) ? $_POST['memberofold'] : htmlspecialchars($memberofold), '" />'.PHP_EOL; - echo '<input type="hidden" name="membersold" value="', isset($_POST['membersold']) ? $_POST['membersold'] : htmlspecialchars($membersold), '" />'.PHP_EOL; - echo '<input type="hidden" name="adminmembersold" value="', isset($_POST['adminmembersold']) ? $_POST['adminmembersold'] : htmlspecialchars($adminmembersold), '" />'.PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_alter" />' . \PHP_EOL; + echo '<input type="hidden" name="rolename" value="', \htmlspecialchars($_REQUEST['rolename']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="memberofold" value="', $_POST['memberofold'] ?? \htmlspecialchars($memberofold), '" />' . \PHP_EOL; + echo '<input type="hidden" name="membersold" value="', $_POST['membersold'] ?? \htmlspecialchars($membersold), '" />' . \PHP_EOL; + echo '<input type="hidden" name="adminmembersold" value="', $_POST['adminmembersold'] ?? \htmlspecialchars($adminmembersold), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Function to save after editing a role. */ - public function doSaveAlter() + public function doSaveAlter(): void { $data = $this->misc->getDatabaseAccessor(); @@ -582,9 +503,9 @@ class RolesController extends BaseController $this->coalesceArr($_POST, 'adminmembers', []); // Check name and password - if (isset($_POST['formNewRoleName']) && '' == $_POST['formNewRoleName']) { + if (isset($_POST['formNewRoleName']) && '' === $_POST['formNewRoleName']) { $this->doAlter($this->lang['strroleneedsname']); - } elseif ($_POST['formPassword'] != $_POST['formConfirm']) { + } elseif ($_POST['formPassword'] !== $_POST['formConfirm']) { $this->doAlter($this->lang['strpasswordconfirm']); } else { if (isset($_POST['formNewRoleName'])) { @@ -593,7 +514,7 @@ class RolesController extends BaseController $status = $data->setRole($_POST['rolename'], $_POST['formPassword'], isset($_POST['formSuper']), isset($_POST['formCreateDB']), isset($_POST['formCreateRole']), isset($_POST['formInherits']), isset($_POST['formCanLogin']), $_POST['formConnLimit'], $_POST['formExpires'], $_POST['memberof'], $_POST['members'], $_POST['adminmembers'], $_POST['memberofold'], $_POST['membersold'], $_POST['adminmembersold']); } - if (0 == $status) { + if (0 === $status) { $this->doDefault($this->lang['strrolealtered']); } else { $this->doAlter($this->lang['strrolealteredbad']); @@ -606,7 +527,7 @@ class RolesController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -614,18 +535,19 @@ class RolesController extends BaseController $this->printTrail('role'); $this->printTitle($this->lang['strdroprole'], 'pg.role.drop'); - echo '<p>', sprintf($this->lang['strconfdroprole'], $this->misc->printVal($_REQUEST['rolename'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdroprole'], $this->misc->printVal($_REQUEST['rolename'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/roles" method="post">'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="rolename" value="', htmlspecialchars($_REQUEST['rolename']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/roles" method="post">' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="rolename" value="', \htmlspecialchars($_REQUEST['rolename']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropRole($_REQUEST['rolename']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strroledropped']); } else { $this->doDefault($this->lang['strroledroppedbad']); @@ -638,7 +560,7 @@ class RolesController extends BaseController * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -647,67 +569,71 @@ class RolesController extends BaseController $this->printMsg($msg); $roledata = $data->getRole($_REQUEST['rolename']); - if ($roledata->recordCount() > 0) { + + if (0 < $roledata->recordCount()) { $roledata->fields['rolsuper'] = $data->phpBool($roledata->fields['rolsuper']); $roledata->fields['rolcreatedb'] = $data->phpBool($roledata->fields['rolcreatedb']); $roledata->fields['rolcreaterole'] = $data->phpBool($roledata->fields['rolcreaterole']); $roledata->fields['rolinherit'] = $data->phpBool($roledata->fields['rolinherit']); $roledata->fields['rolcanlogin'] = $data->phpBool($roledata->fields['rolcanlogin']); - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data\" style=\"width: 130px\">Description</th>".PHP_EOL; - echo "\t\t<th class=\"data\" style=\"width: 120\">Value</th>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strname']}</td>".PHP_EOL; - echo "\t\t<td class=\"data1\">", htmlspecialchars($_REQUEST['rolename']), "</td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strsuper']}</td>".PHP_EOL; - echo "\t\t<td class=\"data2\">", (($roledata->fields['rolsuper']) ? $this->lang['stryes'] : $this->lang['strno']), "</td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strcreatedb']}</td>".PHP_EOL; - echo "\t\t<td class=\"data1\">", (($roledata->fields['rolcreatedb']) ? $this->lang['stryes'] : $this->lang['strno']), '</td>'.PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strcancreaterole']}</td>".PHP_EOL; - echo "\t\t<td class=\"data2\">", (($roledata->fields['rolcreaterole']) ? $this->lang['stryes'] : $this->lang['strno']), '</td>'.PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strinheritsprivs']}</td>".PHP_EOL; - echo "\t\t<td class=\"data1\">", (($roledata->fields['rolinherit']) ? $this->lang['stryes'] : $this->lang['strno']), '</td>'.PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strcanlogin']}</td>".PHP_EOL; - echo "\t\t<td class=\"data2\">", (($roledata->fields['rolcanlogin']) ? $this->lang['stryes'] : $this->lang['strno']), '</td>'.PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strconnlimit']}</td>".PHP_EOL; - echo "\t\t<td class=\"data1\">", ('-1' == $roledata->fields['rolconnlimit'] ? $this->lang['strnolimit'] : $this->misc->printVal($roledata->fields['rolconnlimit'])), '</td>'.PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strexpires']}</td>".PHP_EOL; - echo "\t\t<td class=\"data2\">", ('infinity' == $roledata->fields['rolvaliduntil'] || is_null($roledata->fields['rolvaliduntil']) ? $this->lang['strnever'] : $this->misc->printVal($roledata->fields['rolvaliduntil'])), '</td>'.PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strsessiondefaults']}</td>".PHP_EOL; - echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolconfig']), '</td>'.PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strmemberof']}</td>".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data\" style=\"width: 130px\">Description</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\" style=\"width: 120\">Value</th>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strname']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">", \htmlspecialchars($_REQUEST['rolename']), "</td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strsuper']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data2\">", (($roledata->fields['rolsuper']) ? $this->lang['stryes'] : $this->lang['strno']), "</td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strcreatedb']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">", (($roledata->fields['rolcreatedb']) ? $this->lang['stryes'] : $this->lang['strno']), '</td>' . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strcancreaterole']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data2\">", (($roledata->fields['rolcreaterole']) ? $this->lang['stryes'] : $this->lang['strno']), '</td>' . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strinheritsprivs']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">", (($roledata->fields['rolinherit']) ? $this->lang['stryes'] : $this->lang['strno']), '</td>' . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strcanlogin']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data2\">", (($roledata->fields['rolcanlogin']) ? $this->lang['stryes'] : $this->lang['strno']), '</td>' . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strconnlimit']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">", ('-1' === $roledata->fields['rolconnlimit'] ? $this->lang['strnolimit'] : $this->misc->printVal($roledata->fields['rolconnlimit'])), '</td>' . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strexpires']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data2\">", ('infinity' === $roledata->fields['rolvaliduntil'] || null === $roledata->fields['rolvaliduntil'] ? $this->lang['strnever'] : $this->misc->printVal($roledata->fields['rolvaliduntil'])), '</td>' . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strsessiondefaults']}</td>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolconfig']), '</td>' . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['strmemberof']}</td>" . \PHP_EOL; echo "\t\t<td class=\"data2\">"; $memberof = $data->getMemberOf($_REQUEST['rolename']); - if ($memberof->recordCount() > 0) { + + if (0 < $memberof->recordCount()) { while (!$memberof->EOF) { - echo $this->misc->printVal($memberof->fields['rolname']), '<br />'.PHP_EOL; + echo $this->misc->printVal($memberof->fields['rolname']), '<br />' . \PHP_EOL; $memberof->moveNext(); } } - echo "</td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strmembers']}</td>".PHP_EOL; + echo "</td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data1\">{$this->lang['strmembers']}</td>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; $members = $data->getMembers($_REQUEST['rolename']); - if ($members->recordCount() > 0) { + + if (0 < $members->recordCount()) { while (!$members->EOF) { - echo $this->misc->printVal($members->fields['rolname']), '<br />'.PHP_EOL; + echo $this->misc->printVal($members->fields['rolname']), '<br />' . \PHP_EOL; $members->moveNext(); } } - echo "</td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['stradminmembers']}</td>".PHP_EOL; + echo "</td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data2\">{$this->lang['stradminmembers']}</td>" . \PHP_EOL; echo "\t\t<td class=\"data2\">"; $adminmembers = $data->getMembers($_REQUEST['rolename'], 't'); - if ($adminmembers->recordCount() > 0) { + + if (0 < $adminmembers->recordCount()) { while (!$adminmembers->EOF) { - echo $this->misc->printVal($adminmembers->fields['rolname']), '<br />'.PHP_EOL; + echo $this->misc->printVal($adminmembers->fields['rolname']), '<br />' . \PHP_EOL; $adminmembers->moveNext(); } } - echo "</td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; + echo "</td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } $navlinks = [ @@ -750,7 +676,7 @@ class RolesController extends BaseController ], ]; - $this->printNavLinks($navlinks, 'roles-properties', get_defined_vars()); + $this->printNavLinks($navlinks, 'roles-properties', \get_defined_vars()); } /** @@ -761,7 +687,7 @@ class RolesController extends BaseController * * @param mixed $msg */ - public function doAccount($msg = '') + public function doAccount($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -774,32 +700,32 @@ class RolesController extends BaseController $this->printTabs('server', 'account'); $this->printMsg($msg); - if ($roledata->recordCount() > 0) { + if (0 < $roledata->recordCount()) { $roledata->fields['rolsuper'] = $data->phpBool($roledata->fields['rolsuper']); $roledata->fields['rolcreatedb'] = $data->phpBool($roledata->fields['rolcreatedb']); $roledata->fields['rolcreaterole'] = $data->phpBool($roledata->fields['rolcreaterole']); $roledata->fields['rolinherit'] = $data->phpBool($roledata->fields['rolinherit']); - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data\">{$this->lang['strname']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strsuper']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcreatedb']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcancreaterole']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strinheritsprivs']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strconnlimit']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strexpires']}</th>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strsessiondefaults']}</th>".PHP_EOL; - echo "\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolname']), '</td>'.PHP_EOL; - echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolsuper'], 'yesno'), '</td>'.PHP_EOL; - echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolcreatedb'], 'yesno'), '</td>'.PHP_EOL; - echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolcreaterole'], 'yesno'), '</td>'.PHP_EOL; - echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolinherit'], 'yesno'), '</td>'.PHP_EOL; - echo "\t\t<td class=\"data1\">", ('-1' == $roledata->fields['rolconnlimit'] ? $this->lang['strnolimit'] : $this->misc->printVal($roledata->fields['rolconnlimit'])), '</td>'.PHP_EOL; - echo "\t\t<td class=\"data1\">", ('infinity' == $roledata->fields['rolvaliduntil'] || is_null($roledata->fields['rolvaliduntil']) ? $this->lang['strnever'] : $this->misc->printVal($roledata->fields['rolvaliduntil'])), '</td>'.PHP_EOL; - echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolconfig']), '</td>'.PHP_EOL; - echo "\t</tr>\n</table>".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strsuper']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcreatedb']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcancreaterole']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strinheritsprivs']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strconnlimit']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strexpires']}</th>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strsessiondefaults']}</th>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolname']), '</td>' . \PHP_EOL; + echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolsuper'], 'yesno'), '</td>' . \PHP_EOL; + echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolcreatedb'], 'yesno'), '</td>' . \PHP_EOL; + echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolcreaterole'], 'yesno'), '</td>' . \PHP_EOL; + echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolinherit'], 'yesno'), '</td>' . \PHP_EOL; + echo "\t\t<td class=\"data1\">", ('-1' === $roledata->fields['rolconnlimit'] ? $this->lang['strnolimit'] : $this->misc->printVal($roledata->fields['rolconnlimit'])), '</td>' . \PHP_EOL; + echo "\t\t<td class=\"data1\">", ('infinity' === $roledata->fields['rolvaliduntil'] || null === $roledata->fields['rolvaliduntil'] ? $this->lang['strnever'] : $this->misc->printVal($roledata->fields['rolvaliduntil'])), '</td>' . \PHP_EOL; + echo "\t\t<td class=\"data1\">", $this->misc->printVal($roledata->fields['rolconfig']), '</td>' . \PHP_EOL; + echo "\t</tr>\n</table>" . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } $this->printNavLinks(['changepassword' => [ @@ -813,7 +739,7 @@ class RolesController extends BaseController ], ], 'content' => $this->lang['strchangepassword'], - ]], 'roles-account', get_defined_vars()); + ]], 'roles-account', \get_defined_vars()); } /** @@ -822,7 +748,7 @@ class RolesController extends BaseController * @param mixed $confirm * @param mixed $msg */ - public function doChangePassword($confirm, $msg = '') + public function doChangePassword($confirm, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -838,29 +764,30 @@ class RolesController extends BaseController $this->coalesceArr($_POST, 'confirm', ''); - echo '<form action="'.\SUBFOLDER.'/src/views/roles" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strpassword']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/roles" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strpassword']}</th>" . \PHP_EOL; echo "\t\t<td><input type=\"password\" name=\"password\" size=\"32\" value=\"", - htmlspecialchars($_POST['password']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strconfirm']}</th>".PHP_EOL; - echo "\t\t<td><input type=\"password\" name=\"confirm\" size=\"32\" value=\"\" /></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="changepassword" />'.PHP_EOL; + \htmlspecialchars($_POST['password']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strconfirm']}</th>" . \PHP_EOL; + echo "\t\t<td><input type=\"password\" name=\"confirm\" size=\"32\" value=\"\" /></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="changepassword" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"ok\" value=\"{$this->lang['strok']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</p></form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"ok\" value=\"{$this->lang['strok']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</p></form>' . \PHP_EOL; } else { // Check that password is minimum length - if (strlen($_POST['password']) < $this->conf['min_password_length']) { + if (\mb_strlen($_POST['password']) < $this->conf['min_password_length']) { $this->doChangePassword(true, $this->lang['strpasswordshort']); - } elseif ($_POST['password'] != $_POST['confirm']) { + } elseif ($_POST['password'] !== $_POST['confirm']) { // Check that password matches confirmation password $this->doChangePassword(true, $this->lang['strpasswordconfirm']); } else { $status = $data->changePassword($server_info['username'], $_POST['password']); - if (0 == $status) { + + if (0 === $status) { $this->doAccount($this->lang['strpasswordchanged']); } else { $this->doAccount($this->lang['strpasswordchangedbad']); @@ -868,4 +795,99 @@ class RolesController extends BaseController } } } + + /** + * Adjusts the content of the $_POST superglobal according to role data. + * + * @param \PHPPgAdmin\ADORecordSet $roledata The roledata + * @param bool $canRename Indicates if role can be renamed + */ + private function _adjustPostVars($roledata, $canRename): void + { + if (isset($_POST['formExpires'])) { + return; + } + + if ($canRename) { + $_POST['formNewRoleName'] = $roledata->fields['rolname']; + } + + if ($roledata->fields['rolsuper']) { + $_POST['formSuper'] = ''; + } + + if ($roledata->fields['rolcreatedb']) { + $_POST['formCreateDB'] = ''; + } + + if ($roledata->fields['rolcreaterole']) { + $_POST['formCreateRole'] = ''; + } + + if ($roledata->fields['rolinherit']) { + $_POST['formInherits'] = ''; + } + + if ($roledata->fields['rolcanlogin']) { + $_POST['formCanLogin'] = ''; + } + + $_POST['formConnLimit'] = '-1' === $roledata->fields['rolconnlimit'] ? '' : $roledata->fields['rolconnlimit']; + $_POST['formExpires'] = 'infinity' === $roledata->fields['rolvaliduntil'] ? '' : $roledata->fields['rolvaliduntil']; + $_POST['formPassword'] = ''; + } + + private function _populateMemberof($data): void + { + if (!isset($_POST['memberof'])) { + $memberof = $data->getMemberOf($_REQUEST['rolename']); + + if (0 < $memberof->recordCount()) { + $i = 0; + + while (!$memberof->EOF) { + $_POST['memberof'][$i++] = $memberof->fields['rolname']; + $memberof->moveNext(); + } + } else { + $_POST['memberof'] = []; + } + } + } + + private function _populateMembers($data): void + { + if (!isset($_POST['members'])) { + $members = $data->getMembers($_REQUEST['rolename']); + + if (0 < $members->recordCount()) { + $i = 0; + + while (!$members->EOF) { + $_POST['members'][$i++] = $members->fields['rolname']; + $members->moveNext(); + } + } else { + $_POST['members'] = []; + } + } + } + + private function _populateAdminmembers($data): void + { + if (!isset($_POST['adminmembers'])) { + $adminmembers = $data->getMembers($_REQUEST['rolename'], 't'); + + if (0 < $adminmembers->recordCount()) { + $i = 0; + + while (!$adminmembers->EOF) { + $_POST['adminmembers'][$i++] = $adminmembers->fields['rolname']; + $adminmembers->moveNext(); + } + } else { + $_POST['adminmembers'] = []; + } + } + } } diff --git a/src/controllers/RulesController.php b/src/controllers/RulesController.php index 3571db78..759042ad 100644 --- a/src/controllers/RulesController.php +++ b/src/controllers/RulesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class RulesController extends BaseController { @@ -20,12 +21,12 @@ class RulesController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } // Different header if we're view rules or table rules - $this->printHeader($_REQUEST[$_REQUEST['subject']].' - '.$this->lang['strrules']); + $this->printHeader($_REQUEST[$_REQUEST['subject']] . ' - ' . $this->lang['strrules']); $this->printBody(); switch ($this->action) { @@ -67,7 +68,7 @@ class RulesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -91,8 +92,8 @@ class RulesController extends BaseController ], ]; - $subject = urlencode($_REQUEST['subject']); - $object = urlencode($_REQUEST[$_REQUEST['subject']]); + $subject = \urlencode($_REQUEST['subject']); + $object = \urlencode($_REQUEST[$_REQUEST['subject']]); $actions = [ 'drop' => [ @@ -129,7 +130,7 @@ class RulesController extends BaseController ], ], 'content' => $this->lang['strcreaterule'], - ]], 'rules-rules', get_defined_vars()); + ]], 'rules-rules', \get_defined_vars()); } public function doTree() @@ -152,7 +153,7 @@ class RulesController extends BaseController * @param mixed $confirm * @param mixed $msg */ - public function createRule($confirm, $msg = '') + public function createRule($confirm, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -171,43 +172,44 @@ class RulesController extends BaseController $this->printTitle($this->lang['strcreaterule'], 'pg.rule.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/rules" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/rules" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "<td class=\"data1\"><input name=\"name\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" /></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strevent']}</th>".PHP_EOL; - echo '<td class="data1"><select name="event">'.PHP_EOL; + \htmlspecialchars($_POST['name']), '" /></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strevent']}</th>" . \PHP_EOL; + echo '<td class="data1"><select name="event">' . \PHP_EOL; + foreach ($data->rule_events as $v) { - echo "<option value=\"{$v}\"", ($v == $_POST['event']) ? ' selected="selected"' : '', - ">{$v}</option>".PHP_EOL; + echo "<option value=\"{$v}\"", ($v === $_POST['event']) ? ' selected="selected"' : '', + ">{$v}</option>" . \PHP_EOL; } - echo '</select></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strwhere']}</th>".PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strwhere']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="where" size="32" value="', - htmlspecialchars($_POST['where']), '" /></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\"><label for=\"instead\">{$this->lang['strinstead']}</label></th>".PHP_EOL; + \htmlspecialchars($_POST['where']), '" /></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\"><label for=\"instead\">{$this->lang['strinstead']}</label></th>" . \PHP_EOL; echo '<td class="data1">'; - echo '<input type="checkbox" id="instead" name="instead" ', (isset($_POST['instead'])) ? ' checked="checked"' : '', ' />'.PHP_EOL; - echo '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['straction']}</th>".PHP_EOL; + echo '<input type="checkbox" id="instead" name="instead" ', (isset($_POST['instead'])) ? ' checked="checked"' : '', ' />' . \PHP_EOL; + echo '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['straction']}</th>" . \PHP_EOL; echo '<td class="data1">'; - echo '<input type="radio" id="type1" name="type" value="NOTHING"', ('NOTHING' == $_POST['type']) ? ' checked="checked"' : '', ' /> <label for="type1">NOTHING</label><br />'.PHP_EOL; - echo '<input type="radio" name="type" value="SOMETHING"', ('SOMETHING' == $_POST['type']) ? ' checked="checked"' : '', ' />'.PHP_EOL; + echo '<input type="radio" id="type1" name="type" value="NOTHING"', ('NOTHING' === $_POST['type']) ? ' checked="checked"' : '', ' /> <label for="type1">NOTHING</label><br />' . \PHP_EOL; + echo '<input type="radio" name="type" value="SOMETHING"', ('SOMETHING' === $_POST['type']) ? ' checked="checked"' : '', ' />' . \PHP_EOL; echo '(<input name="raction" size="32" value="', - htmlspecialchars($_POST['raction']), '" />)</td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; + \htmlspecialchars($_POST['raction']), '" />)</td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; - echo '<input type="hidden" name="action" value="save_create_rule" />'.PHP_EOL; - echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['subject']), '" />'.PHP_EOL; - echo '<input type="hidden" name="', htmlspecialchars($_REQUEST['subject']), - '" value="', htmlspecialchars($_REQUEST[$_REQUEST['subject']]), '" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="save_create_rule" />' . \PHP_EOL; + echo '<input type="hidden" name="subject" value="', \htmlspecialchars($_REQUEST['subject']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="', \htmlspecialchars($_REQUEST['subject']), + '" value="', \htmlspecialchars($_REQUEST[$_REQUEST['subject']]), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"submit\" name=\"ok\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"submit\" name=\"ok\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - if ('' == trim($_POST['name'])) { + if ('' === \trim($_POST['name'])) { $this->createRule(true, $this->lang['strruleneedsname']); } else { $status = $data->createRule( @@ -219,7 +221,8 @@ class RulesController extends BaseController $_POST['type'], $_POST['raction'] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strrulecreated']); } else { $this->createRule(true, $this->lang['strrulecreatedbad']); @@ -233,7 +236,7 @@ class RulesController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -241,26 +244,27 @@ class RulesController extends BaseController $this->printTrail($_REQUEST['subject']); $this->printTitle($this->lang['strdrop'], 'pg.rule.drop'); - echo '<p>', sprintf( + echo '<p>', \sprintf( $this->lang['strconfdroprule'], $this->misc->printVal($_REQUEST['rule']), $this->misc->printVal($_REQUEST[$_REQUEST['reltype']]) - ), '</p>'.PHP_EOL; - - echo '<form action="'.\SUBFOLDER.'/src/views/rules" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['reltype']), '" />'.PHP_EOL; - echo '<input type="hidden" name="', htmlspecialchars($_REQUEST['reltype']), - '" value="', htmlspecialchars($_REQUEST[$_REQUEST['reltype']]), '" />'.PHP_EOL; - echo '<input type="hidden" name="rule" value="', htmlspecialchars($_REQUEST['rule']), '" />'.PHP_EOL; + ), '</p>' . \PHP_EOL; + + echo '<form action="' . self::SUBFOLDER . '/src/views/rules" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="subject" value="', \htmlspecialchars($_REQUEST['reltype']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="', \htmlspecialchars($_REQUEST['reltype']), + '" value="', \htmlspecialchars($_REQUEST[$_REQUEST['reltype']]), '" />' . \PHP_EOL; + echo '<input type="hidden" name="rule" value="', \htmlspecialchars($_REQUEST['rule']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropRule($_POST['rule'], $_POST[$_POST['subject']], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strruledropped']); } else { $this->doDefault($this->lang['strruledroppedbad']); diff --git a/src/controllers/SchemasController.php b/src/controllers/SchemasController.php index 9a0d52e0..de921ffb 100644 --- a/src/controllers/SchemasController.php +++ b/src/controllers/SchemasController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,12 +13,11 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class SchemasController extends BaseController { use \PHPPgAdmin\Traits\ExportTrait; + public $controller_title = 'strschemas'; /** @@ -23,10 +25,11 @@ class SchemasController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } - if ('subtree' == $this->action) { + + if ('subtree' === $this->action) { return $this->doSubTree(); } @@ -36,7 +39,8 @@ class SchemasController extends BaseController $header_template = 'header.twig'; - ob_start(); + \ob_start(); + switch ($this->action) { case 'create': if (isset($_POST['create'])) { @@ -73,7 +77,7 @@ class SchemasController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $this->printHeader($this->headerTitle(), null, true, $header_template); $this->printBody(); @@ -88,7 +92,7 @@ class SchemasController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -104,7 +108,7 @@ class SchemasController extends BaseController 'schema' => [ 'title' => $this->lang['strschema'], 'field' => Decorator::field('nspname'), - 'url' => \SUBFOLDER."{$destination}&", + 'url' => self::SUBFOLDER . "{$destination}&", 'vars' => ['schema' => 'nspname'], ], 'owner' => [ @@ -186,7 +190,7 @@ class SchemasController extends BaseController ], ], 'content' => $this->lang['strcreateschema'], - ]], 'schemas-schemas', get_defined_vars()); + ]], 'schemas-schemas', \get_defined_vars()); } /** @@ -261,7 +265,7 @@ class SchemasController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -282,49 +286,51 @@ class SchemasController extends BaseController $this->printTitle($this->lang['strcreateschema'], 'pg.schema.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/schemas" method="post">'.PHP_EOL; - echo '<table style="width: 100%">'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/schemas" method="post">' . \PHP_EOL; + echo '<table style="width: 100%">' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input name=\"formName\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['formName']), "\" /></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formName']), "\" /></td>\n\t</tr>" . \PHP_EOL; // Owner - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"formAuth\">".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"formAuth\">" . \PHP_EOL; + while (!$users->EOF) { - $uname = htmlspecialchars($users->fields['usename']); + $uname = \htmlspecialchars($users->fields['usename']); echo "\t\t\t\t<option value=\"{$uname}\"", - ($uname == $_POST['formAuth']) ? ' selected="selected"' : '', ">{$uname}</option>".PHP_EOL; + ($uname === $_POST['formAuth']) ? ' selected="selected"' : '', ">{$uname}</option>" . \PHP_EOL; $users->moveNext(); } - echo "\t\t\t</select>\n\t\t</td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t\t\t</select>\n\t\t</td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><textarea name=\"formComment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p>'.PHP_EOL; - echo '<input type="hidden" name="action" value="create" />'.PHP_EOL; - echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), '" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p>' . \PHP_EOL; + echo '<input type="hidden" name="action" value="create" />' . \PHP_EOL; + echo '<input type="hidden" name="database" value="', \htmlspecialchars($_REQUEST['database']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</p>'.PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</p>' . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new schema in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); // Check that they've given a name - if ('' == $_POST['formName']) { + if ('' === $_POST['formName']) { $this->doCreate($this->lang['strschemaneedsname']); } else { $status = $data->createSchema($_POST['formName'], $_POST['formAuth'], $_POST['formComment']); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strschemacreated']); } else { @@ -339,7 +345,7 @@ class SchemasController extends BaseController * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -348,7 +354,8 @@ class SchemasController extends BaseController $this->printMsg($msg); $schema = $data->getSchemaByName($_REQUEST['schema']); - if ($schema->recordCount() > 0) { + + if (0 < $schema->recordCount()) { $this->coalesceArr($_POST, 'comment', $schema->fields['nspcomment']); $this->coalesceArr($_POST, 'schema', $_REQUEST['schema']); @@ -357,45 +364,46 @@ class SchemasController extends BaseController $this->coalesceArr($_POST, 'owner', $schema->fields['ownername']); - echo '<form action="'.\SUBFOLDER.'/src/views/schemas" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/schemas" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\">"; echo "\t\t\t<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" />'.PHP_EOL; - echo "\t\t</td>".PHP_EOL; - echo "\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['name']), '" />' . \PHP_EOL; + echo "\t\t</td>" . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; if ($data->hasAlterSchemaOwner()) { $users = $data->getUsers(); - echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; echo '<td class="data2"><select name="owner">'; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $_POST['owner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $_POST['owner']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } else { echo "<input name=\"owner\" value=\"{$_POST['owner']}\" type=\"hidden\" />"; } - echo "\t<tr>".PHP_EOL; - echo "\t\t<th class=\"data\">{$this->lang['strcomment']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><textarea cols=\"32\" rows=\"3\" name=\"comment\">", htmlspecialchars($_POST['comment']), '</textarea></td>'.PHP_EOL; - echo "\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="alter" />'.PHP_EOL; - echo '<input type="hidden" name="schema" value="', htmlspecialchars($_POST['schema']), '" />'.PHP_EOL; + echo "\t<tr>" . \PHP_EOL; + echo "\t\t<th class=\"data\">{$this->lang['strcomment']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><textarea cols=\"32\" rows=\"3\" name=\"comment\">", \htmlspecialchars($_POST['comment']), '</textarea></td>' . \PHP_EOL; + echo "\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="alter" />' . \PHP_EOL; + echo '<input type="hidden" name="schema" value="', \htmlspecialchars($_POST['schema']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } @@ -404,12 +412,13 @@ class SchemasController extends BaseController * * @param mixed $msg */ - public function doSaveAlter() + public function doSaveAlter(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->updateSchema($_POST['schema'], $_POST['comment'], $_POST['name'], $_POST['owner']); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strschemaaltered']); } else { @@ -434,44 +443,47 @@ class SchemasController extends BaseController $this->printTrail('schema'); $this->printTitle($this->lang['strdrop'], 'pg.schema.drop'); - echo '<form action="'.\SUBFOLDER.'/src/views/schemas" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/schemas" method="post">' . \PHP_EOL; //If multi drop if (isset($_REQUEST['ma'])) { foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfdropschema'], $this->misc->printVal($a['nsp'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="nsp[]" value="', htmlspecialchars($a['nsp']), '" />'.PHP_EOL; + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfdropschema'], $this->misc->printVal($a['nsp'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="nsp[]" value="', \htmlspecialchars($a['nsp']), '" />' . \PHP_EOL; } } else { - echo '<p>', sprintf($this->lang['strconfdropschema'], $this->misc->printVal($_REQUEST['nsp'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="nsp" value="', htmlspecialchars($_REQUEST['nsp']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropschema'], $this->misc->printVal($_REQUEST['nsp'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="nsp" value="', \htmlspecialchars($_REQUEST['nsp']), '" />' . \PHP_EOL; } - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo '<p><input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), '" />'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="database" value="', \htmlspecialchars($_REQUEST['database']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - if (is_array($_POST['nsp'])) { + if (\is_array($_POST['nsp'])) { $msg = ''; $status = $data->beginTransaction(); - if (0 == $status) { + + if (0 === $status) { foreach ($_POST['nsp'] as $s) { $status = $data->dropSchema($s, isset($_POST['cascade'])); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strschemadropped']); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($s, \ENT_QUOTES, 'UTF-8'), $this->lang['strschemadropped']); } else { $data->endTransaction(); - $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strschemadroppedbad'])); + $this->doDefault(\sprintf('%s%s: %s<br />', $msg, \htmlentities($s, \ENT_QUOTES, 'UTF-8'), $this->lang['strschemadroppedbad'])); return; } } } - if (0 == $data->endTransaction()) { + + if (0 === $data->endTransaction()) { // Everything went fine, back to the Default page.... $this->misc->setReloadBrowser(true); $this->doDefault($msg); @@ -480,7 +492,8 @@ class SchemasController extends BaseController } } else { $status = $data->dropSchema($_POST['nsp'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strschemadropped']); } else { @@ -495,7 +508,7 @@ class SchemasController extends BaseController * * @param mixed $msg */ - public function doExport($msg = '') + public function doExport($msg = ''): void { $this->printTrail('schema'); $this->printTabs('schema', 'export'); @@ -512,7 +525,7 @@ class SchemasController extends BaseController echo $this->structureAndData(true); - echo $this->displayOrDownload(!(strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS']))); + echo $this->displayOrDownload(!(\mb_strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS']))); echo $this->formFooter($subject, $object); } diff --git a/src/controllers/SequencesController.php b/src/controllers/SequencesController.php index 6b090387..f4dea85c 100644 --- a/src/controllers/SequencesController.php +++ b/src/controllers/SequencesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class SequencesController extends BaseController { @@ -22,7 +23,7 @@ class SequencesController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -111,7 +112,7 @@ class SequencesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -202,7 +203,7 @@ class SequencesController extends BaseController ], ], 'content' => $this->lang['strcreatesequence'], - ]], 'sequences-sequences', get_defined_vars()); + ]], 'sequences-sequences', \get_defined_vars()); } /** @@ -238,7 +239,7 @@ class SequencesController extends BaseController * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $this->printTrail('sequence'); @@ -248,17 +249,18 @@ class SequencesController extends BaseController // Fetch the sequence information $sequence = $data->getSequence($_REQUEST['sequence']); - if (is_object($sequence) && $sequence->recordCount() > 0) { + if (\is_object($sequence) && 0 < $sequence->recordCount()) { $sequence->fields['is_cycled'] = $data->phpBool($sequence->fields['is_cycled']); $sequence->fields['is_called'] = $data->phpBool($sequence->fields['is_called']); // Show comment if any if (null !== $sequence->fields['seqcomment']) { - echo '<p class="comment">', $this->misc->printVal($sequence->fields['seqcomment']), '</p>'.PHP_EOL; + echo '<p class="comment">', $this->misc->printVal($sequence->fields['seqcomment']), '</p>' . \PHP_EOL; } echo '<table border="0">'; echo "<tr><th class=\"data\">{$this->lang['strname']}</th>"; + if ($data->hasAlterSequenceStart()) { echo "<th class=\"data\">{$this->lang['strstartvalue']}</th>"; } @@ -272,6 +274,7 @@ class SequencesController extends BaseController echo "<th class=\"data\">{$this->lang['striscalled']}</th></tr>"; echo '<tr>'; echo '<td class="data1">', $this->misc->printVal($sequence->fields['seqname']), '</td>'; + if ($data->hasAlterSequenceStart()) { echo '<td class="data1">', $this->misc->printVal($sequence->fields['start_value']), '</td>'; } @@ -381,9 +384,9 @@ class SequencesController extends BaseController unset($navlinks['restart']); } - $this->printNavLinks($navlinks, 'sequences-properties', get_defined_vars()); + $this->printNavLinks($navlinks, 'sequences-properties', \get_defined_vars()); } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } @@ -406,44 +409,47 @@ class SequencesController extends BaseController $this->printTitle($this->lang['strdrop'], 'pg.sequence.drop'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/sequences" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/sequences" method="post">' . \PHP_EOL; //If multi drop if (isset($_REQUEST['ma'])) { foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfdropsequence'], $this->misc->printVal($a['sequence'])), '</p>'.PHP_EOL; - printf('<input type="hidden" name="sequence[]" value="%s" />', htmlspecialchars($a['sequence'])); + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfdropsequence'], $this->misc->printVal($a['sequence'])), '</p>' . \PHP_EOL; + \printf('<input type="hidden" name="sequence[]" value="%s" />', \htmlspecialchars($a['sequence'])); } } else { - echo '<p>', sprintf($this->lang['strconfdropsequence'], $this->misc->printVal($_REQUEST['sequence'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="sequence" value="', htmlspecialchars($_REQUEST['sequence']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropsequence'], $this->misc->printVal($_REQUEST['sequence'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="sequence" value="', \htmlspecialchars($_REQUEST['sequence']), '" />' . \PHP_EOL; } - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo '<p><input type="hidden" name="action" value="drop" />'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="drop" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - if (is_array($_POST['sequence'])) { + if (\is_array($_POST['sequence'])) { $msg = ''; $status = $data->beginTransaction(); - if (0 == $status) { + + if (0 === $status) { foreach ($_POST['sequence'] as $s) { $status = $data->dropSequence($s, isset($_POST['cascade'])); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strsequencedropped']); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($s, \ENT_QUOTES, 'UTF-8'), $this->lang['strsequencedropped']); } else { $data->endTransaction(); - $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strsequencedroppedbad'])); + $this->doDefault(\sprintf('%s%s: %s<br />', $msg, \htmlentities($s, \ENT_QUOTES, 'UTF-8'), $this->lang['strsequencedroppedbad'])); return; } } } - if (0 == $data->endTransaction()) { + + if (0 === $data->endTransaction()) { // Everything went fine, back to the Default page.... $this->misc->setReloadBrowser(true); $this->doDefault($msg); @@ -452,7 +458,8 @@ class SequencesController extends BaseController } } else { $status = $data->dropSequence($_POST['sequence'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strsequencedropped']); } else { @@ -467,7 +474,7 @@ class SequencesController extends BaseController * * @param mixed $msg */ - public function doCreateSequence($msg = '') + public function doCreateSequence($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -487,54 +494,54 @@ class SequencesController extends BaseController $this->printTitle($this->lang['strcreatesequence'], 'pg.sequence.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/sequences" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/sequences" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "<td class=\"data1\"><input name=\"formSequenceName\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['formSequenceName']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formSequenceName']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strincrementby']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strincrementby']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formIncrement" size="5" value="', - htmlspecialchars($_POST['formIncrement']), '" /> </td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formIncrement']), '" /> </td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strminvalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strminvalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formMinValue" size="5" value="', - htmlspecialchars($_POST['formMinValue']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formMinValue']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strmaxvalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strmaxvalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formMaxValue" size="5" value="', - htmlspecialchars($_POST['formMaxValue']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formMaxValue']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strstartvalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strstartvalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formStartValue" size="5" value="', - htmlspecialchars($_POST['formStartValue']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formStartValue']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strcachevalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcachevalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formCacheValue" size="5" value="', - htmlspecialchars($_POST['formCacheValue']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['formCacheValue']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\"><label for=\"formCycledValue\">{$this->lang['strcancycle']}</label></th>".PHP_EOL; + echo "<tr><th class=\"data left\"><label for=\"formCycledValue\">{$this->lang['strcancycle']}</label></th>" . \PHP_EOL; echo '<td class="data1"><input type="checkbox" id="formCycledValue" name="formCycledValue" ', - (isset($_POST['formCycledValue']) ? ' checked="checked"' : ''), ' /></td></tr>'.PHP_EOL; + (isset($_POST['formCycledValue']) ? ' checked="checked"' : ''), ' /></td></tr>' . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create_sequence" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create_sequence" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new sequence in the database. */ - public function doSaveCreateSequence() + public function doSaveCreateSequence(): void { $data = $this->misc->getDatabaseAccessor(); // Check that they've given a name and at least one column - if ('' == $_POST['formSequenceName']) { + if ('' === $_POST['formSequenceName']) { $this->doCreateSequence($this->lang['strsequenceneedsname']); } else { $status = $data->createSequence( @@ -546,7 +553,8 @@ class SequencesController extends BaseController $_POST['formCacheValue'], isset($_POST['formCycledValue']) ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strsequencecreated']); } else { $this->doCreateSequence($this->lang['strsequencecreatedbad']); @@ -557,12 +565,13 @@ class SequencesController extends BaseController /** * Restarts a sequence. */ - public function doRestart() + public function doRestart(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->restartSequence($_REQUEST['sequence']); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strsequencerestart']); } else { $this->doProperties($this->lang['strsequencerestartbad']); @@ -572,12 +581,13 @@ class SequencesController extends BaseController /** * Resets a sequence. */ - public function doReset() + public function doReset(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->resetSequence($_REQUEST['sequence']); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strsequencereset']); } else { $this->doProperties($this->lang['strsequenceresetbad']); @@ -587,12 +597,13 @@ class SequencesController extends BaseController /** * Set Nextval of a sequence. */ - public function doNextval() + public function doNextval(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->nextvalSequence($_REQUEST['sequence']); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strsequencenextval']); } else { $this->doProperties($this->lang['strsequencenextvalbad']); @@ -602,12 +613,13 @@ class SequencesController extends BaseController /** * Function to save after 'setval'ing a sequence. */ - public function doSaveSetval() + public function doSaveSetval(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->setvalSequence($_POST['sequence'], $_POST['nextvalue']); - if (0 == $status) { + + if (0 === $status) { $this->doProperties($this->lang['strsequencesetval']); } else { $this->doProperties($this->lang['strsequencesetvalbad']); @@ -619,7 +631,7 @@ class SequencesController extends BaseController * * @param mixed $msg */ - public function doSetval($msg = '') + public function doSetval($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -630,29 +642,29 @@ class SequencesController extends BaseController // Fetch the sequence information $sequence = $data->getSequence($_REQUEST['sequence']); - if (is_object($sequence) && $sequence->recordCount() > 0) { - echo '<form action="'.\SUBFOLDER.'/src/views/sequences" method="post">'.PHP_EOL; + if (\is_object($sequence) && 0 < $sequence->recordCount()) { + echo '<form action="' . self::SUBFOLDER . '/src/views/sequences" method="post">' . \PHP_EOL; echo '<table border="0">'; - echo "<tr><th class=\"data left required\">{$this->lang['strlastvalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strlastvalue']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo "<input name=\"nextvalue\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - $this->misc->printVal($sequence->fields['last_value']), '" /></td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="setval" />'.PHP_EOL; - echo '<input type="hidden" name="sequence" value="', htmlspecialchars($_REQUEST['sequence']), '" />'.PHP_EOL; + $this->misc->printVal($sequence->fields['last_value']), '" /></td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="setval" />' . \PHP_EOL; + echo '<input type="hidden" name="sequence" value="', \htmlspecialchars($_REQUEST['sequence']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"setval\" value=\"{$this->lang['strsetval']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"setval\" value=\"{$this->lang['strsetval']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } /** * Function to save after altering a sequence. */ - public function doSaveAlter() + public function doSaveAlter(): void { $data = $this->misc->getDatabaseAccessor(); @@ -689,14 +701,15 @@ class SequencesController extends BaseController $_POST['formStartValue'] ); - if (0 == $status) { - if ($_POST['sequence'] != $_POST['name']) { + if (0 === $status) { + if ($_POST['sequence'] !== $_POST['name']) { // Jump them to the new view name $_REQUEST['sequence'] = $_POST['name']; // Force a browser reload $this->misc->setReloadBrowser(true); } - if (!empty($_POST['newschema']) && ($_POST['newschema'] != $data->_schema)) { + + if (!empty($_POST['newschema']) && ($_POST['newschema'] !== $data->_schema)) { // Jump them to the new sequence schema $this->misc->setCurrentSchema($_POST['newschema']); $this->misc->setReloadBrowser(true); @@ -712,7 +725,7 @@ class SequencesController extends BaseController * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -723,7 +736,7 @@ class SequencesController extends BaseController // Fetch the sequence information $sequence = $data->getSequence($_REQUEST['sequence']); - if (is_object($sequence) && $sequence->recordCount() > 0) { + if (\is_object($sequence) && 0 < $sequence->recordCount()) { $this->coalesceArr($_POST, 'name', $_REQUEST['sequence']); $this->coalesceArr($_POST, 'comment', $sequence->fields['seqcomment']); @@ -734,90 +747,93 @@ class SequencesController extends BaseController // Handle Checkbox Value $sequence->fields['is_cycled'] = $data->phpBool($sequence->fields['is_cycled']); + if ($sequence->fields['is_cycled']) { $_POST['formCycledValue'] = 'on'; } - echo '<form action="'.\SUBFOLDER.'/src/views/sequences" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/sequences" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo "<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['name']), '" /></td></tr>' . \PHP_EOL; if ($data->isSuperUser()) { // Fetch all users $users = $data->getUsers(); - echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="owner">'; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $_POST['owner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $_POST['owner']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } if ($data->hasAlterSequenceSchema()) { $schemas = $data->getSchemas(); - echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="newschema">'; + while (!$schemas->EOF) { $schema = $schemas->fields['nspname']; - echo '<option value="', htmlspecialchars($schema), '"', - ($schema == $_POST['newschema']) ? ' selected="selected"' : '', '>', htmlspecialchars($schema), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($schema), '"', + ($schema === $_POST['newschema']) ? ' selected="selected"' : '', '>', \htmlspecialchars($schema), '</option>' . \PHP_EOL; $schemas->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } - echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo '<textarea rows="3" cols="32" name="comment">', - htmlspecialchars($_POST['comment']), '</textarea></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['comment']), '</textarea></td></tr>' . \PHP_EOL; if ($data->hasAlterSequenceStart()) { - echo "<tr><th class=\"data left\">{$this->lang['strstartvalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strstartvalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formStartValue" size="5" value="', - htmlspecialchars($sequence->fields['start_value']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($sequence->fields['start_value']), '" /></td></tr>' . \PHP_EOL; } - echo "<tr><th class=\"data left\">{$this->lang['strrestartvalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strrestartvalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formRestartValue" size="5" value="', - htmlspecialchars($sequence->fields['last_value']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($sequence->fields['last_value']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strincrementby']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strincrementby']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formIncrement" size="5" value="', - htmlspecialchars($sequence->fields['increment_by']), '" /> </td></tr>'.PHP_EOL; + \htmlspecialchars($sequence->fields['increment_by']), '" /> </td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strmaxvalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strmaxvalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formMaxValue" size="5" value="', - htmlspecialchars($sequence->fields['max_value']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($sequence->fields['max_value']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strminvalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strminvalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formMinValue" size="5" value="', - htmlspecialchars($sequence->fields['min_value']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($sequence->fields['min_value']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strcachevalue']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcachevalue']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="formCacheValue" size="5" value="', - htmlspecialchars($sequence->fields['cache_value']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($sequence->fields['cache_value']), '" /></td></tr>' . \PHP_EOL; - echo "<tr><th class=\"data left\"><label for=\"formCycledValue\">{$this->lang['strcancycle']}</label></th>".PHP_EOL; + echo "<tr><th class=\"data left\"><label for=\"formCycledValue\">{$this->lang['strcancycle']}</label></th>" . \PHP_EOL; echo '<td class="data1"><input type="checkbox" id="formCycledValue" name="formCycledValue" ', - (isset($_POST['formCycledValue']) ? ' checked="checked"' : ''), ' /></td></tr>'.PHP_EOL; + (isset($_POST['formCycledValue']) ? ' checked="checked"' : ''), ' /></td></tr>' . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="alter" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="alter" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="sequence" value="', htmlspecialchars($_REQUEST['sequence']), '" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="sequence" value="', \htmlspecialchars($_REQUEST['sequence']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } } diff --git a/src/controllers/ServersController.php b/src/controllers/ServersController.php index ac348e4c..65a493b1 100644 --- a/src/controllers/ServersController.php +++ b/src/controllers/ServersController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,19 +13,23 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class ServersController extends BaseController { use \PHPPgAdmin\Traits\ServersTrait; public $table_place = 'servers-servers'; - public $section = 'servers'; - public $query = ''; - public $subject = ''; + + public $section = 'servers'; + + public $query = ''; + + public $subject = ''; + public $start_time; + public $duration; + public $controller_title = 'strservers'; protected $no_db_connection = true; @@ -32,7 +39,7 @@ class ServersController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -42,7 +49,8 @@ class ServersController extends BaseController $server_html .= $this->printBody(false); $server_html .= $this->printTrail('root', false); - ob_start(); + \ob_start(); + switch ($this->action) { case 'logout': $this->doLogout(); @@ -54,7 +62,7 @@ class ServersController extends BaseController break; } - $server_html .= ob_get_clean(); + $server_html .= \ob_get_clean(); $server_html .= $this->printFooter(false); @@ -68,11 +76,11 @@ class ServersController extends BaseController } } - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $this->printTabs('root', 'servers'); $this->printMsg($msg); - $group = isset($_GET['group']) ? $_GET['group'] : false; + $group = $_GET['group'] ?? false; $groups = $this->getServersGroups(true, $group); $columns = [ @@ -84,11 +92,12 @@ class ServersController extends BaseController ], ]; $actions = []; + if ((false !== $group) && (isset($this->conf['srv_groups'][$group])) && - ($groups->recordCount() > 0) + (0 < $groups->recordCount()) ) { - $this->printTitle(sprintf($this->lang['strgroupgroups'], htmlentities($this->conf['srv_groups'][$group]['desc'], ENT_QUOTES, 'UTF-8'))); + $this->printTitle(\sprintf($this->lang['strgroupgroups'], \htmlentities($this->conf['srv_groups'][$group]['desc'], \ENT_QUOTES, 'UTF-8'))); echo $this->printTable($groups, $columns, $actions, $this->table_place); } @@ -98,7 +107,7 @@ class ServersController extends BaseController 'server' => [ 'title' => $this->lang['strserver'], 'field' => Decorator::field('desc'), - 'url' => \SUBFOLDER.'/redirect/server?', + 'url' => self::SUBFOLDER . '/redirect/server?', 'vars' => ['server' => 'sha'], ], 'host' => [ @@ -133,7 +142,7 @@ class ServersController extends BaseController ], ]; - $svPre = function (&$rowdata) use ($actions) { + $svPre = static function (&$rowdata) use ($actions) { $actions['logout']['disable'] = empty($rowdata->fields['username']); return $actions; @@ -142,7 +151,7 @@ class ServersController extends BaseController if ((false !== $group) && isset($this->conf['srv_groups'][$group]) ) { - $this->printTitle(sprintf($this->lang['strgroupservers'], htmlentities($this->conf['srv_groups'][$group]['desc'], ENT_QUOTES, 'UTF-8')), null); + $this->printTitle(\sprintf($this->lang['strgroupservers'], \htmlentities($this->conf['srv_groups'][$group]['desc'], \ENT_QUOTES, 'UTF-8')), null); $actions['logout']['attr']['href']['urlvars']['group'] = $group; } echo $this->printTable($servers, $columns, $actions, $this->table_place, $this->lang['strnoobjects'], $svPre); @@ -151,19 +160,19 @@ class ServersController extends BaseController public function doTree() { $nodes = []; - $group_id = isset($_GET['group']) ? $_GET['group'] : false; + $group_id = $_GET['group'] ?? false; // root with srv_groups - if (isset($this->conf['srv_groups']) and count($this->conf['srv_groups']) > 0 - and false === $group_id) { + if (isset($this->conf['srv_groups']) && 0 < \count($this->conf['srv_groups']) + && false === $group_id) { $nodes = $this->getServersGroups(true); - } elseif (isset($this->conf['srv_groups']) and false !== $group_id) { + } elseif (isset($this->conf['srv_groups']) && false !== $group_id) { // group subtree if ('all' !== $group_id) { $nodes = $this->getServersGroups(false, $group_id); } - $nodes = array_merge($nodes, $this->getServers(false, $group_id)); + $nodes = \array_merge($nodes, $this->getServers(false, $group_id)); $nodes = new \PHPPgAdmin\ArrayRecordSet($nodes); } else { // no srv_group @@ -188,7 +197,7 @@ class ServersController extends BaseController return $this->printTree($nodes, $attrs, $this->section); } - public function doLogout() + public function doLogout(): void { $server_info = $this->misc->getServerInfo($_REQUEST['logoutServer']); $this->misc->setServerInfo(null, null, $_REQUEST['logoutServer']); @@ -197,7 +206,7 @@ class ServersController extends BaseController $this->misc->setReloadBrowser(true); - echo sprintf($this->lang['strlogoutmsg'], $server_info['desc']); + echo \sprintf($this->lang['strlogoutmsg'], $server_info['desc']); } /** @@ -214,14 +223,14 @@ class ServersController extends BaseController if (isset($this->conf['srv_groups'])) { foreach ($this->conf['srv_groups'] as $i => $group) { - if ((($group_id === false) && (!isset($group['parents']))) || - ($group_id !== false) && + if (((false === $group_id) && (!isset($group['parents']))) || + (false !== $group_id) && isset($group['parents']) && - in_array( + \in_array( $group_id, - explode( + \explode( ',', - preg_replace('/\s/', '', $group['parents']) + \preg_replace('/\s/', '', $group['parents']) ), true ) @@ -247,7 +256,7 @@ class ServersController extends BaseController } } - if ($group_id === false) { + if (false === $group_id) { $grps['all'] = [ 'id' => 'all', 'desc' => $this->lang['strallservers'], diff --git a/src/controllers/SqlController.php b/src/controllers/SqlController.php index a989b737..9072e616 100644 --- a/src/controllers/SqlController.php +++ b/src/controllers/SqlController.php @@ -1,22 +1,27 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class SqlController extends BaseController { - public $query = ''; + public $query = ''; + public $subject = ''; + public $start_time; + public $duration; + public $controller_title = 'strqueryresults'; /** @@ -26,11 +31,11 @@ class SqlController extends BaseController { $data = $this->misc->getDatabaseAccessor(); - set_time_limit(0); + \set_time_limit(0); // We need to store the query in a session for editing purposes // We avoid GPC vars to avoid truncating long queries - if (isset($_REQUEST['subject']) && 'history' == $_REQUEST['subject']) { + if (isset($_REQUEST['subject']) && 'history' === $_REQUEST['subject']) { // Or maybe we came from the history popup $_SESSION['sqlquery'] = $_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']][$_GET['queryid']]['query']; $this->query = $_SESSION['sqlquery']; @@ -44,7 +49,7 @@ class SqlController extends BaseController // Pagination maybe set by a get link that has it as FALSE, // if that's the case, unset the variable. - if (isset($_REQUEST['paginate']) && 'f' == $_REQUEST['paginate']) { + if (isset($_REQUEST['paginate']) && 'f' === $_REQUEST['paginate']) { unset($_REQUEST['paginate'], $_POST['paginate'], $_GET['paginate']); } @@ -56,8 +61,8 @@ class SqlController extends BaseController // script for pagination // if a file is given or the request is an explain, do not paginate if (isset($_REQUEST['paginate']) && - !(isset($_FILES['script']) && $_FILES['script']['size'] > 0) && - (0 == preg_match('/^\s*explain/i', $this->query))) { + !(isset($_FILES['script']) && 0 < $_FILES['script']['size']) && + (0 === \preg_match('/^\s*explain/i', $this->query))) { //if (!(isset($_FILES['script']) && $_FILES['script']['size'] > 0)) { $display_controller = new DisplayController($this->getContainer()); @@ -72,14 +77,14 @@ class SqlController extends BaseController // Set the schema search path if (isset($_REQUEST['search_path'])) { - if (0 != $data->setSearchPath(array_map('trim', explode(',', $_REQUEST['search_path'])))) { + if (0 !== $data->setSearchPath(\array_map('trim', \explode(',', $_REQUEST['search_path'])))) { return $this->printFooter(); } } // May as well try to time the query - if (function_exists('microtime')) { - list($usec, $sec) = explode(' ', microtime()); + if (\function_exists('microtime')) { + list($usec, $sec) = \explode(' ', \microtime()); $this->start_time = ((float) $usec + (float) $sec); } @@ -94,7 +99,7 @@ class SqlController extends BaseController try { // Execute the query. If it's a script upload, special handling is necessary - if (isset($_FILES['script']) && $_FILES['script']['size'] > 0) { + if (isset($_FILES['script']) && 0 < $_FILES['script']['size']) { return $this->execute_script(); } @@ -120,45 +125,48 @@ class SqlController extends BaseController * * @param ADORecordSet $rs The recordset returned by the script execetor */ - $sqlCallback = function ($query, $rs, $lineno) use ($data, $misc, $lang, $_connection) { + $sqlCallback = static function ($query, $rs, $lineno) use ($data, $misc, $lang, $_connection): void { // Check if $rs is false, if so then there was a fatal error if (false === $rs) { - echo htmlspecialchars($_FILES['script']['name']), ':', $lineno, ': ', nl2br(htmlspecialchars($_connection->getLastError())), '<br/>'.PHP_EOL; + echo \htmlspecialchars($_FILES['script']['name']), ':', $lineno, ': ', \nl2br(\htmlspecialchars($_connection->getLastError())), '<br/>' . \PHP_EOL; } else { // Print query results - switch (pg_result_status($rs)) { + switch (\pg_result_status($rs)) { case \PGSQL_TUPLES_OK: // If rows returned, then display the results - $num_fields = pg_numfields($rs); + $num_fields = \pg_numfields($rs); echo "<p><table>\n<tr>"; + for ($k = 0; $k < $num_fields; ++$k) { - echo '<th class="data">', $misc->printVal(pg_fieldname($rs, $k)), '</th>'; + echo '<th class="data">', $misc->printVal(\pg_fieldname($rs, $k)), '</th>'; } $i = 0; - $row = pg_fetch_row($rs); + $row = \pg_fetch_row($rs); + while (false !== $row) { - $id = (0 == ($i % 2) ? '1' : '2'); - echo "<tr class=\"data{$id}\">".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "<tr class=\"data{$id}\">" . \PHP_EOL; + foreach ($row as $k => $v) { - echo '<td style="white-space:nowrap;">', $misc->printVal($v, pg_fieldtype($rs, $k), ['null' => true]), '</td>'; + echo '<td style="white-space:nowrap;">', $misc->printVal($v, \pg_fieldtype($rs, $k), ['null' => true]), '</td>'; } - echo '</tr>'.PHP_EOL; - $row = pg_fetch_row($rs); + echo '</tr>' . \PHP_EOL; + $row = \pg_fetch_row($rs); ++$i; } - echo '</table><br/>'.PHP_EOL; - echo $i, " {$lang['strrows']}</p>".PHP_EOL; + echo '</table><br/>' . \PHP_EOL; + echo $i, " {$lang['strrows']}</p>" . \PHP_EOL; break; case \PGSQL_COMMAND_OK: // If we have the command completion tag - if (version_compare(PHP_VERSION, '4.3', '>=')) { - echo htmlspecialchars(pg_result_status($rs, PGSQL_STATUS_STRING)), '<br/>'.PHP_EOL; - } elseif ($data->conn->Affected_Rows() > 0) { + if (\version_compare(\PHP_VERSION, '4.3', '>=')) { + echo \htmlspecialchars(\pg_result_status($rs, \PGSQL_STATUS_STRING)), '<br/>' . \PHP_EOL; + } elseif (0 < $data->conn->Affected_Rows()) { // Otherwise if any rows have been affected - echo $data->conn->Affected_Rows(), " {$lang['strrowsaff']}<br/>".PHP_EOL; + echo $data->conn->Affected_Rows(), " {$lang['strrowsaff']}<br/>" . \PHP_EOL; } // Otherwise output nothing... break; @@ -179,20 +187,20 @@ class SqlController extends BaseController // Set fetch mode to NUM so that duplicate field names are properly returned $data->conn->setFetchMode(\ADODB_FETCH_NUM); - set_time_limit(25000); + \set_time_limit(25000); $rs = $data->conn->Execute($this->query); - echo '<form method="post" id="sqlform" action="'.$_SERVER['REQUEST_URI'].'">'; + echo '<form method="post" id="sqlform" action="' . $_SERVER['REQUEST_URI'] . '">'; echo '<textarea width="90%" name="query" id="query" rows="5" cols="100" resizable="true">'; - echo htmlspecialchars($this->query); + echo \htmlspecialchars($this->query); echo '</textarea><br>'; echo $this->misc->setForm(); echo '<input type="submit"/></form>'; // $rs will only be an object if there is no error - if (is_object($rs)) { + if (\is_object($rs)) { // Request was run, saving it in history if (!isset($_REQUEST['nohistory'])) { $this->misc->saveScriptHistory($this->query); @@ -201,33 +209,36 @@ class SqlController extends BaseController // Now, depending on what happened do various things // First, if rows returned, then display the results - if ($rs->recordCount() > 0) { + if (0 < $rs->recordCount()) { echo "<table>\n<tr>"; + foreach ($rs->fields as $k => $v) { $finfo = $rs->fetchField($k); echo '<th class="data">', $this->misc->printVal($finfo->name), '</th>'; } - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; $i = 0; + while (!$rs->EOF) { - $id = (0 == ($i % 2) ? '1' : '2'); - echo "<tr class=\"data{$id}\">".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "<tr class=\"data{$id}\">" . \PHP_EOL; + foreach ($rs->fields as $k => $v) { $finfo = $rs->fetchField($k); echo '<td style="white-space:nowrap;">', $this->misc->printVal($v, $finfo->type, ['null' => true]), '</td>'; } - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; $rs->moveNext(); ++$i; } - echo '</table>'.PHP_EOL; - echo '<p>', $rs->recordCount(), " {$this->lang['strrows']}</p>".PHP_EOL; - } elseif ($data->conn->Affected_Rows() > 0) { + echo '</table>' . \PHP_EOL; + echo '<p>', $rs->recordCount(), " {$this->lang['strrows']}</p>" . \PHP_EOL; + } elseif (0 < $data->conn->Affected_Rows()) { // Otherwise if any rows have been affected - echo '<p>', $data->conn->Affected_Rows(), " {$this->lang['strrowsaff']}</p>".PHP_EOL; + echo '<p>', $data->conn->Affected_Rows(), " {$this->lang['strrowsaff']}</p>" . \PHP_EOL; } else { // Otherwise nodata to print - echo '<p>', $this->lang['strnodata'], '</p>'.PHP_EOL; + echo '<p>', $this->lang['strnodata'], '</p>' . \PHP_EOL; } return $rs; @@ -240,10 +251,10 @@ class SqlController extends BaseController // May as well try to time the query if (null !== $this->start_time) { - list($usec, $sec) = explode(' ', microtime()); + list($usec, $sec) = \explode(' ', \microtime()); $end_time = ((float) $usec + (float) $sec); // Get duration in milliseconds, round to 3dp's - $this->duration = number_format(($end_time - $this->start_time) * 1000, 3); + $this->duration = \number_format(($end_time - $this->start_time) * 1000, 3); } // Reload the browser as we may have made schema changes @@ -251,10 +262,10 @@ class SqlController extends BaseController // Display duration if we know it if (null !== $this->duration) { - echo '<p>', sprintf($this->lang['strruntime'], $this->duration), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strruntime'], $this->duration), '</p>' . \PHP_EOL; } - echo "<p>{$this->lang['strsqlexecuted']}</p>".PHP_EOL; + echo "<p>{$this->lang['strsqlexecuted']}</p>" . \PHP_EOL; $navlinks = []; $fields = [ @@ -285,7 +296,7 @@ class SqlController extends BaseController 'attr' => [ 'href' => [ 'url' => 'database', - 'urlvars' => array_merge($fields, [ + 'urlvars' => \array_merge($fields, [ 'action' => 'sql', ]), ], @@ -294,14 +305,14 @@ class SqlController extends BaseController ]; // Create view and download - if ('' !== $this->query && isset($rs) && is_object($rs) && $rs->recordCount() > 0) { + if ('' !== $this->query && isset($rs) && \is_object($rs) && 0 < $rs->recordCount()) { // Report views don't set a schema, so we need to disable create view in that case if (isset($_REQUEST['schema'])) { $navlinks['createview'] = [ 'attr' => [ 'href' => [ 'url' => 'views', - 'urlvars' => array_merge($fields, [ + 'urlvars' => \array_merge($fields, [ 'action' => 'create', ]), ], @@ -325,7 +336,7 @@ class SqlController extends BaseController ]; } - $this->printNavLinks($navlinks, 'sql-form', get_defined_vars()); + $this->printNavLinks($navlinks, 'sql-form', \get_defined_vars()); return $this->printFooter($doBody, $template); } diff --git a/src/controllers/SqleditController.php b/src/controllers/SqleditController.php index a104b0ef..d99cacea 100644 --- a/src/controllers/SqleditController.php +++ b/src/controllers/SqleditController.php @@ -1,29 +1,33 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class SqleditController extends BaseController { use \PHPPgAdmin\Traits\ServersTrait; - public $query = ''; + public $query = ''; + public $subject = ''; + public $start_time; + public $duration; /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { switch ($this->action) { case 'find': @@ -61,105 +65,73 @@ class SqleditController extends BaseController $_SESSION['sqlquery'] = ''; } - $this->coalesceArr($_REQUEST, 'search_path', implode(',', $data->getSearchPath())); - $search_path = htmlspecialchars($_REQUEST['search_path']); - $sqlquery = htmlspecialchars($_SESSION['sqlquery']); + $this->coalesceArr($_REQUEST, 'search_path', \implode(',', $data->getSearchPath())); + $search_path = \htmlspecialchars($_REQUEST['search_path']); + $sqlquery = \htmlspecialchars($_SESSION['sqlquery']); $default_html = $this->printTabs($this->misc->getNavTabs('popup'), 'sql', false); - $default_html .= '<form action="'.\SUBFOLDER.'/src/views/sql" method="post" enctype="multipart/form-data" class="sqlform" id="sqlform" target="detail">'; - $default_html .= PHP_EOL; + $default_html .= '<form action="' . self::SUBFOLDER . '/src/views/sql" method="post" enctype="multipart/form-data" class="sqlform" id="sqlform" target="detail">'; + $default_html .= \PHP_EOL; $default_html .= $this->printConnection('sql', false); - $default_html .= PHP_EOL; + $default_html .= \PHP_EOL; $default_html .= ' <div class="searchpath">'; $default_html .= '<label>'; $default_html .= $this->misc->printHelp($this->lang['strsearchpath'], 'pg.schema.search_path', false); - $default_html .= ': <input type="text" name="search_path" id="search_path" size="45" value="'.$search_path.'" />'; - $default_html .= '</label>'.PHP_EOL; + $default_html .= ': <input type="text" name="search_path" id="search_path" size="45" value="' . $search_path . '" />'; + $default_html .= '</label>' . \PHP_EOL; - $default_html .= '</div>'.PHP_EOL; + $default_html .= '</div>' . \PHP_EOL; $default_html .= '<div id="queryedition" style="padding:1%;width:98%;float:left;">'; - $default_html .= PHP_EOL; - $default_html .= '<textarea style="width:98%;" rows="10" cols="50" name="query" id="query" resizable="true">'.$sqlquery.'</textarea>'; - $default_html .= PHP_EOL; - $default_html .= '</div>'.PHP_EOL; + $default_html .= \PHP_EOL; + $default_html .= '<textarea style="width:98%;" rows="10" cols="50" name="query" id="query" resizable="true">' . $sqlquery . '</textarea>'; + $default_html .= \PHP_EOL; + $default_html .= '</div>' . \PHP_EOL; $default_html .= '<div class="sqledit_bottom_inputs" >'; - if (ini_get('file_uploads')) { + if (\ini_get('file_uploads')) { // Don't show upload option if max size of uploads is zero - $max_size = $this->misc->inisizeToBytes(ini_get('upload_max_filesize')); - if (is_double($max_size) && $max_size > 0) { + $max_size = $this->misc->inisizeToBytes(\ini_get('upload_max_filesize')); + + if (\is_float($max_size) && 0 < $max_size) { $default_html .= '<p class="upload_sql_script">'; - $default_html .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.$max_size.'" />'; - $default_html .= PHP_EOL; - $default_html .= '<label for="script">'.$this->lang['struploadscript'].'</label>'; + $default_html .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . $max_size . '" />'; + $default_html .= \PHP_EOL; + $default_html .= '<label for="script">' . $this->lang['struploadscript'] . '</label>'; $default_html .= ' <input class="btn btn-small" id="script" name="script" type="file" /></p>'; - $default_html .= '</p>'.PHP_EOL; + $default_html .= '</p>' . \PHP_EOL; } } // Check that file uploads are enabled $checked = (isset($_REQUEST['paginate']) ? ' checked="checked"' : ''); - $default_html .= '<p><input type="submit" class="btn btn-small" name="execute" accesskey="r" value="'.$this->lang['strexecute'].'" />'; - $default_html .= PHP_EOL; + $default_html .= '<p><input type="submit" class="btn btn-small" name="execute" accesskey="r" value="' . $this->lang['strexecute'] . '" />'; + $default_html .= \PHP_EOL; - $default_html .= '<input type="reset" class="btn btn-small" accesskey="q" value="'.$this->lang['strreset'].'" /></p>'; - $default_html .= PHP_EOL; + $default_html .= '<input type="reset" class="btn btn-small" accesskey="q" value="' . $this->lang['strreset'] . '" /></p>'; + $default_html .= \PHP_EOL; $default_html .= '<p>'; $default_html .= '<label for="paginate">'; - $default_html .= '<input type="checkbox" id="paginate" name="paginate"'.$checked.' /> '.$this->lang['strpaginate'].' '; - $default_html .= '</label>'.PHP_EOL; - $default_html .= '</p>'.PHP_EOL; + $default_html .= '<input type="checkbox" id="paginate" name="paginate"' . $checked . ' /> ' . $this->lang['strpaginate'] . ' '; + $default_html .= '</label>' . \PHP_EOL; + $default_html .= '</p>' . \PHP_EOL; - $default_html .= '</div>'.PHP_EOL; + $default_html .= '</div>' . \PHP_EOL; $default_html .= '</form>'; - $default_html .= PHP_EOL; + $default_html .= \PHP_EOL; // Default focus //$this->setFocus('forms[0].query'); return $default_html; } - private function _getFilters() - { - $filters = [ - 'SCHEMA' => ['langkey' => 'strschemas', 'selected' => ''], - 'TABLE' => ['langkey' => 'strtables', 'selected' => ''], - 'VIEW' => ['langkey' => 'strviews', 'selected' => ''], - 'SEQUENCE' => ['langkey' => 'strsequences', 'selected' => ''], - 'COLUMN' => ['langkey' => 'strcolumns', 'selected' => ''], - 'RULE' => ['langkey' => 'strrules', 'selected' => ''], - 'INDEX' => ['langkey' => 'strindexes', 'selected' => ''], - 'TRIGGER' => ['langkey' => 'strtriggers', 'selected' => ''], - 'CONSTRAINT' => ['langkey' => 'strconstraints', 'selected' => ''], - 'FUNCTION' => ['langkey' => 'strfunctions', 'selected' => ''], - 'DOMAIN' => ['langkey' => 'strdomains', 'selected' => ''], - ]; - - return $filters; - } - - private function _getAdvancedFilters() - { - $advanced_filters = [ - 'AGGREGATE' => ['langkey' => 'straggregates', 'selected' => ''], - 'TYPE' => ['langkey' => 'strtypes', 'selected' => ''], - 'OPERATOR' => ['langkey' => 'stroperators', 'selected' => ''], - 'OPCLASS' => ['langkey' => 'stropclasses', 'selected' => ''], - 'CONVERSION' => ['langkey' => 'strconversions', 'selected' => ''], - 'LANGUAGE' => ['langkey' => 'strlanguages', 'selected' => ''], - ]; - - return $advanced_filters; - } - /** * Searches for a named database object. */ @@ -173,9 +145,9 @@ class SqleditController extends BaseController $default_html = $this->printTabs($this->misc->getNavTabs('popup'), 'find', false); - $default_html .= '<form action="database" method="post" target="detail">'.PHP_EOL; + $default_html .= '<form action="database" method="post" target="detail">' . \PHP_EOL; $default_html .= $this->printConnection('find', false); - $default_html .= '<p><input class="focusme" name="term" id="term" value="'.htmlspecialchars($_REQUEST['term'])."\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" />".PHP_EOL; + $default_html .= '<p><input class="focusme" name="term" id="term" value="' . \htmlspecialchars($_REQUEST['term']) . "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" />" . \PHP_EOL; $filters = $this->_getFilters(); $advanced_filters = $this->_getAdvancedFilters(); @@ -189,26 +161,56 @@ class SqleditController extends BaseController } // Output list of filters. This is complex due to all the 'has' and 'conf' feature possibilities - $default_html .= "<select id='filter' name=\"filter\">".PHP_EOL; - $default_html .= sprintf('%s<option value=""'.('' == $_REQUEST['filter'] ? ' selected="selected" ' : '').">{$this->lang['strallobjects']}</option>".PHP_EOL, "\t"); + $default_html .= "<select id='filter' name=\"filter\">" . \PHP_EOL; + $default_html .= \sprintf('%s<option value=""' . ('' === $_REQUEST['filter'] ? ' selected="selected" ' : '') . ">{$this->lang['strallobjects']}</option>" . \PHP_EOL, "\t"); + foreach ($filters as $type => $props) { - $default_html .= sprintf('%s<option value="%s" %s >%s</option>'.PHP_EOL, "\t", $type, $props['selected'], $this->lang[$props['langkey']]); + $default_html .= \sprintf('%s<option value="%s" %s >%s</option>' . \PHP_EOL, "\t", $type, $props['selected'], $this->lang[$props['langkey']]); } if ($this->conf['show_advanced']) { foreach ($advanced_filters as $type => $props) { - $default_html .= sprintf('%s<option value="%s" %s >%s</option>'.PHP_EOL, "\t", $type, $props['selected'], $this->lang[$props['langkey']]); + $default_html .= \sprintf('%s<option value="%s" %s >%s</option>' . \PHP_EOL, "\t", $type, $props['selected'], $this->lang[$props['langkey']]); } } - $default_html .= '</select>'.PHP_EOL; + $default_html .= '</select>' . \PHP_EOL; - $default_html .= "<input type=\"submit\" value=\"{$this->lang['strfind']}\" />".PHP_EOL; - $default_html .= '<input type="hidden" name="action" value="find" /></p>'.PHP_EOL; - $default_html .= '</form>'.PHP_EOL; + $default_html .= "<input type=\"submit\" value=\"{$this->lang['strfind']}\" />" . \PHP_EOL; + $default_html .= '<input type="hidden" name="action" value="find" /></p>' . \PHP_EOL; + $default_html .= '</form>' . \PHP_EOL; // Default focus $this->setFocus('forms[0].term'); return $default_html; } + + private function _getFilters() + { + return [ + 'SCHEMA' => ['langkey' => 'strschemas', 'selected' => ''], + 'TABLE' => ['langkey' => 'strtables', 'selected' => ''], + 'VIEW' => ['langkey' => 'strviews', 'selected' => ''], + 'SEQUENCE' => ['langkey' => 'strsequences', 'selected' => ''], + 'COLUMN' => ['langkey' => 'strcolumns', 'selected' => ''], + 'RULE' => ['langkey' => 'strrules', 'selected' => ''], + 'INDEX' => ['langkey' => 'strindexes', 'selected' => ''], + 'TRIGGER' => ['langkey' => 'strtriggers', 'selected' => ''], + 'CONSTRAINT' => ['langkey' => 'strconstraints', 'selected' => ''], + 'FUNCTION' => ['langkey' => 'strfunctions', 'selected' => ''], + 'DOMAIN' => ['langkey' => 'strdomains', 'selected' => ''], + ]; + } + + private function _getAdvancedFilters() + { + return [ + 'AGGREGATE' => ['langkey' => 'straggregates', 'selected' => ''], + 'TYPE' => ['langkey' => 'strtypes', 'selected' => ''], + 'OPERATOR' => ['langkey' => 'stroperators', 'selected' => ''], + 'OPCLASS' => ['langkey' => 'stropclasses', 'selected' => ''], + 'CONVERSION' => ['langkey' => 'strconversions', 'selected' => ''], + 'LANGUAGE' => ['langkey' => 'strlanguages', 'selected' => ''], + ]; + } } diff --git a/src/controllers/TablesController.php b/src/controllers/TablesController.php index eda5bacf..94f34918 100644 --- a/src/controllers/TablesController.php +++ b/src/controllers/TablesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,15 +13,14 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class TablesController extends BaseController { use \PHPPgAdmin\Traits\AdminTrait; use \PHPPgAdmin\Traits\InsertEditRowTrait; - public $table_place = 'tables-tables'; + public $table_place = 'tables-tables'; + public $controller_title = 'strtables'; /** @@ -26,19 +28,21 @@ class TablesController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } - if ('subtree' == $this->action) { + + if ('subtree' === $this->action) { return $this->doSubTree(); } - if ('json' == $this->action) { + + if ('json' === $this->action) { return $this->displayJson(); } $header_template = 'header.twig'; - ob_start(); + \ob_start(); switch ($this->action) { case 'create': @@ -126,7 +130,7 @@ class TablesController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $this->printHeader($this->headerTitle(), null, true, $header_template); $this->printBody(); @@ -136,178 +140,12 @@ class TablesController extends BaseController return $this->printFooter(); } - private function _getColumns() - { - $columns = [ - 'table' => [ - 'title' => $this->lang['strtable'], - 'field' => Decorator::field('relname'), - 'url' => \SUBFOLDER."/redirect/table?{$this->misc->href}&", - 'vars' => ['table' => 'relname'], - ], - 'owner' => [ - 'title' => $this->lang['strowner'], - 'field' => Decorator::field('relowner'), - ], - 'tablespace' => [ - 'title' => $this->lang['strtablespace'], - 'field' => Decorator::field('tablespace'), - ], - 'tuples' => [ - 'title' => $this->lang['strestimatedrowcount'], - 'field' => Decorator::field('reltuples'), - 'type' => 'numeric', - ], - 'table_size' => [ - 'title' => $this->lang['strsize'], - 'field' => Decorator::field('table_size'), - ], - 'actions' => [ - 'title' => $this->lang['stractions'], - ], - 'comment' => [ - 'title' => $this->lang['strcomment'], - 'field' => Decorator::field('relcomment'), - ], - ]; - - return $columns; - } - - private function _getActions() - { - $actions = [ - 'multiactions' => [ - 'keycols' => ['table' => 'relname'], - 'url' => 'tables', - 'default' => 'analyze', - ], - 'browse' => [ - 'content' => $this->lang['strbrowse'], - 'attr' => [ - 'href' => [ - 'url' => 'display', - 'urlvars' => [ - 'subject' => 'table', - 'return' => 'table', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - 'select' => [ - 'content' => $this->lang['strselect'], - 'attr' => [ - 'href' => [ - 'url' => 'tables', - 'urlvars' => [ - 'action' => 'confselectrows', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - 'insert' => [ - 'content' => $this->lang['strinsert'], - 'attr' => [ - 'href' => [ - 'url' => 'tables', - 'urlvars' => [ - 'action' => 'confinsertrow', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - 'empty' => [ - 'multiaction' => 'confirm_empty', - 'content' => $this->lang['strempty'], - 'attr' => [ - 'href' => [ - 'url' => 'tables', - 'urlvars' => [ - 'action' => 'confirm_empty', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - 'alter' => [ - 'content' => $this->lang['stralter'], - 'attr' => [ - 'href' => [ - 'url' => 'tblproperties', - 'urlvars' => [ - 'action' => 'confirm_alter', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - 'drop' => [ - 'multiaction' => 'confirm_drop', - 'content' => $this->lang['strdrop'], - 'attr' => [ - 'href' => [ - 'url' => 'tables', - 'urlvars' => [ - 'action' => 'confirm_drop', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - 'vacuum' => [ - 'multiaction' => 'confirm_vacuum', - 'content' => $this->lang['strvacuum'], - 'attr' => [ - 'href' => [ - 'url' => 'tables', - 'urlvars' => [ - 'action' => 'confirm_vacuum', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - 'analyze' => [ - 'multiaction' => 'confirm_analyze', - 'content' => $this->lang['stranalyze'], - 'attr' => [ - 'href' => [ - 'url' => 'tables', - 'urlvars' => [ - 'action' => 'confirm_analyze', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - 'reindex' => [ - 'multiaction' => 'confirm_reindex', - 'content' => $this->lang['strreindex'], - 'attr' => [ - 'href' => [ - 'url' => 'tables', - 'urlvars' => [ - 'action' => 'confirm_reindex', - 'table' => Decorator::field('relname'), - ], - ], - ], - ], - //'cluster' TODO ? - ]; - - return $actions; - } - /** * Show default list of tables in the database. * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -342,7 +180,7 @@ class TablesController extends BaseController ], ]; - if (($tables->recordCount() > 0) && $data->hasCreateTableLike()) { + if ((0 < $tables->recordCount()) && $data->hasCreateTableLike()) { $navlinks['createlike'] = [ 'attr' => [ 'href' => [ @@ -358,7 +196,7 @@ class TablesController extends BaseController 'content' => $this->lang['strcreatetablelike'], ]; } - $this->printNavLinks($navlinks, 'tables-tables', get_defined_vars()); + $this->printNavLinks($navlinks, 'tables-tables', \get_defined_vars()); } public function displayJson() @@ -443,7 +281,8 @@ class TablesController extends BaseController if (!isset($_REQUEST['stage'])) { $_REQUEST['stage'] = 1; $default_with_oids = $data->getDefaultWithOid(); - if ('off' == $default_with_oids) { + + if ('off' === $default_with_oids) { $_REQUEST['withoutoids'] = 'on'; } } @@ -469,58 +308,60 @@ class TablesController extends BaseController $this->printTitle($this->lang['strcreatetable'], 'pg.table.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/'.$this->script.'" method="post">'; - echo PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/' . $this->script . '" method="post">'; + echo \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strnumcols']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strnumcols']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"fields\" size=\"5\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['fields']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['stroptions']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\"><label for=\"withoutoids\"><input type=\"checkbox\" id=\"withoutoids\" name=\"withoutoids\"", isset($_REQUEST['withoutoids']) ? ' checked="checked"' : '', " />WITHOUT OIDS</label></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['fields']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['stroptions']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\"><label for=\"withoutoids\"><input type=\"checkbox\" id=\"withoutoids\" name=\"withoutoids\"", isset($_REQUEST['withoutoids']) ? ' checked="checked"' : '', " />WITHOUT OIDS</label></td>\n\t</tr>" . \PHP_EOL; // Tablespace (if there are any) - if ($data->hasTablespaces() && $tablespaces->recordCount() > 0) { - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"spcname\">".PHP_EOL; + if ($data->hasTablespaces() && 0 < $tablespaces->recordCount()) { + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"spcname\">" . \PHP_EOL; // Always offer the default (empty) option echo "\t\t\t\t<option value=\"\"", - ('' == $_REQUEST['spcname']) ? ' selected="selected"' : '', '></option>'.PHP_EOL; + ('' === $_REQUEST['spcname']) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; // Display all other tablespaces while (!$tablespaces->EOF) { - $spcname = htmlspecialchars($tablespaces->fields['spcname']); + $spcname = \htmlspecialchars($tablespaces->fields['spcname']); echo "\t\t\t\t<option value=\"{$spcname}\"", - ($tablespaces->fields['spcname'] == $_REQUEST['spcname']) ? ' selected="selected"' : '', ">{$spcname}</option>".PHP_EOL; + ($tablespaces->fields['spcname'] === $_REQUEST['spcname']) ? ' selected="selected"' : '', ">{$spcname}</option>" . \PHP_EOL; $tablespaces->moveNext(); } - echo "\t\t\t</select>\n\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>\n\t\t</td>\n\t</tr>" . \PHP_EOL; } - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td><textarea name=\"tblcomment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_REQUEST['tblcomment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['tblcomment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="create" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="2" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="create" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="2" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strnext']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strnext']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; break; case 2: // Check inputs - $fields = trim($_REQUEST['fields']); - if ('' == trim($_REQUEST['name'])) { + $fields = \trim($_REQUEST['fields']); + + if ('' === \trim($_REQUEST['name'])) { $_REQUEST['stage'] = 1; $this->doCreate($this->lang['strtableneedsname']); return; } - if ('' == $fields || !is_numeric($fields) || $fields != (int) $fields || $fields < 1) { + + if ('' === $fields || !\is_numeric($fields) || (int) $fields !== $fields || 1 > $fields) { $_REQUEST['stage'] = 1; $this->doCreate($this->lang['strtableneedscols']); @@ -534,15 +375,15 @@ class TablesController extends BaseController $this->printTitle($this->lang['strcreatetable'], 'pg.table.create'); $this->printMsg($msg); - echo '<script src="'.\SUBFOLDER.'/assets/js/tables.js" type="text/javascript"></script>'; - echo '<form action="'.\SUBFOLDER.'/src/views/tables" method="post">'.PHP_EOL; + echo '<script src="' . self::SUBFOLDER . '/assets/js/tables.js" type="text/javascript"></script>'; + echo '<form action="' . self::SUBFOLDER . '/src/views/tables" method="post">' . \PHP_EOL; // Output table header - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "\t<tr><th colspan=\"2\" class=\"data required\">{$this->lang['strcolumn']}</th><th colspan=\"2\" class=\"data required\">{$this->lang['strtype']}</th>"; echo "<th class=\"data\">{$this->lang['strlength']}</th><th class=\"data\">{$this->lang['strnotnull']}</th>"; echo "<th class=\"data\">{$this->lang['struniquekey']}</th><th class=\"data\">{$this->lang['strprimarykey']}</th>"; - echo "<th class=\"data\">{$this->lang['strdefault']}</th><th class=\"data\">{$this->lang['strcomment']}</th></tr>".PHP_EOL; + echo "<th class=\"data\">{$this->lang['strdefault']}</th><th class=\"data\">{$this->lang['strcomment']}</th></tr>" . \PHP_EOL; for ($i = 0; $i < $_REQUEST['fields']; ++$i) { if (!isset($_REQUEST['field'][$i])) { @@ -561,74 +402,78 @@ class TablesController extends BaseController $_REQUEST['colcomment'][$i] = ''; } - echo "\t<tr>\n\t\t<td>", $i + 1, '. </td>'.PHP_EOL; + echo "\t<tr>\n\t\t<td>", $i + 1, '. </td>' . \PHP_EOL; echo "\t\t<td><input name=\"field[{$i}]\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['field'][$i]), '" /></td>'.PHP_EOL; - echo "\t\t<td>\n\t\t\t<select name=\"type[{$i}]\" class=\"select2\" id=\"types{$i}\" onchange=\"checkLengths(this.options[this.selectedIndex].value,{$i});\">".PHP_EOL; + \htmlspecialchars($_REQUEST['field'][$i]), '" /></td>' . \PHP_EOL; + echo "\t\t<td>\n\t\t\t<select name=\"type[{$i}]\" class=\"select2\" id=\"types{$i}\" onchange=\"checkLengths(this.options[this.selectedIndex].value,{$i});\">" . \PHP_EOL; // Output any "magic" types foreach ($data->extraTypes as $v) { - $types_for_js[strtolower($v)] = 1; - echo "\t\t\t\t<option value=\"", htmlspecialchars($v), '"', - (isset($_REQUEST['type'][$i]) && $_REQUEST['type'][$i] == $v) ? ' selected="selected"' : '', '>', - $this->misc->printVal($v), '</option>'.PHP_EOL; + $types_for_js[\mb_strtolower($v)] = 1; + echo "\t\t\t\t<option value=\"", \htmlspecialchars($v), '"', + (isset($_REQUEST['type'][$i]) && $_REQUEST['type'][$i] === $v) ? ' selected="selected"' : '', '>', + $this->misc->printVal($v), '</option>' . \PHP_EOL; } $types->moveFirst(); + while (!$types->EOF) { $typname = $types->fields['typname']; $types_for_js[$typname] = 1; - echo "\t\t\t\t<option value=\"", htmlspecialchars($typname), '"', - (isset($_REQUEST['type'][$i]) && $_REQUEST['type'][$i] == $typname) ? ' selected="selected"' : '', '>', - $this->misc->printVal($typname), '</option>'.PHP_EOL; + echo "\t\t\t\t<option value=\"", \htmlspecialchars($typname), '"', + (isset($_REQUEST['type'][$i]) && $_REQUEST['type'][$i] === $typname) ? ' selected="selected"' : '', '>', + $this->misc->printVal($typname), '</option>' . \PHP_EOL; $types->moveNext(); } echo "\t\t\t</select>\n\t\t\n"; - if (0 == $i) { + + if (0 === $i) { // only define js types array once - $predefined_size_types = array_intersect($data->predefined_size_types, array_keys($types_for_js)); + $predefined_size_types = \array_intersect($data->predefined_size_types, \array_keys($types_for_js)); $escaped_predef_types = []; // the JS escaped array elements foreach ($predefined_size_types as $value) { $escaped_predef_types[] = "'{$value}'"; } - echo '<script type="text/javascript">predefined_lengths = new Array('.implode(',', $escaped_predef_types).");</script>\n\t</td>"; + echo '<script type="text/javascript">predefined_lengths = new Array(' . \implode(',', $escaped_predef_types) . ");</script>\n\t</td>"; } // Output array type selector - echo "\t\t<td>\n\t\t\t<select name=\"array[{$i}]\">".PHP_EOL; - echo "\t\t\t\t<option value=\"\"", (isset($_REQUEST['array'][$i]) && $_REQUEST['array'][$i] == '') ? ' selected="selected"' : '', '></option>'.PHP_EOL; - echo "\t\t\t\t<option value=\"[]\"", (isset($_REQUEST['array'][$i]) && $_REQUEST['array'][$i] == '[]') ? ' selected="selected"' : '', '>[ ]</option>'.PHP_EOL; - echo "\t\t\t</select>\n\t\t</td>".PHP_EOL; + echo "\t\t<td>\n\t\t\t<select name=\"array[{$i}]\">" . \PHP_EOL; + echo "\t\t\t\t<option value=\"\"", (isset($_REQUEST['array'][$i]) && '' === $_REQUEST['array'][$i]) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; + echo "\t\t\t\t<option value=\"[]\"", (isset($_REQUEST['array'][$i]) && '[]' === $_REQUEST['array'][$i]) ? ' selected="selected"' : '', '>[ ]</option>' . \PHP_EOL; + echo "\t\t\t</select>\n\t\t</td>" . \PHP_EOL; echo "\t\t<td><input name=\"length[{$i}]\" id=\"lengths{$i}\" size=\"10\" value=\"", - htmlspecialchars($_REQUEST['length'][$i]), '" /></td>'.PHP_EOL; - echo "\t\t<td><input type=\"checkbox\" name=\"notnull[{$i}]\"", (isset($_REQUEST['notnull'][$i])) ? ' checked="checked"' : '', ' /></td>'.PHP_EOL; + \htmlspecialchars($_REQUEST['length'][$i]), '" /></td>' . \PHP_EOL; + echo "\t\t<td><input type=\"checkbox\" name=\"notnull[{$i}]\"", (isset($_REQUEST['notnull'][$i])) ? ' checked="checked"' : '', ' /></td>' . \PHP_EOL; echo "\t\t<td style=\"text-align: center\"><input type=\"checkbox\" name=\"uniquekey[{$i}]\"" - .(isset($_REQUEST['uniquekey'][$i]) ? ' checked="checked"' : '').' /></td>'.PHP_EOL; + . (isset($_REQUEST['uniquekey'][$i]) ? ' checked="checked"' : '') . ' /></td>' . \PHP_EOL; echo "\t\t<td style=\"text-align: center\"><input type=\"checkbox\" name=\"primarykey[{$i}]\" " - .(isset($_REQUEST['primarykey'][$i]) ? ' checked="checked"' : '') - .' /></td>'.PHP_EOL; + . (isset($_REQUEST['primarykey'][$i]) ? ' checked="checked"' : '') + . ' /></td>' . \PHP_EOL; echo "\t\t<td><input name=\"default[{$i}]\" size=\"20\" value=\"", - htmlspecialchars($_REQUEST['default'][$i]), '" /></td>'.PHP_EOL; + \htmlspecialchars($_REQUEST['default'][$i]), '" /></td>' . \PHP_EOL; echo "\t\t<td><input name=\"colcomment[{$i}]\" size=\"40\" value=\"", - htmlspecialchars($_REQUEST['colcomment'][$i]), "\" /> + \htmlspecialchars($_REQUEST['colcomment'][$i]), "\" /> <script type=\"text/javascript\">checkLengths(document.getElementById('types{$i}').value,{$i});</script> - </td>\n\t</tr>".PHP_EOL; + </td>\n\t</tr>" . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="create" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="3" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="create" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="3" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="name" value="', htmlspecialchars($_REQUEST['name']), '" />'.PHP_EOL; - echo '<input type="hidden" name="fields" value="', htmlspecialchars($_REQUEST['fields']), '" />'.PHP_EOL; + echo '<input type="hidden" name="name" value="', \htmlspecialchars($_REQUEST['name']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="fields" value="', \htmlspecialchars($_REQUEST['fields']), '" />' . \PHP_EOL; + if (isset($_REQUEST['withoutoids'])) { - echo '<input type="hidden" name="withoutoids" value="true" />'.PHP_EOL; + echo '<input type="hidden" name="withoutoids" value="true" />' . \PHP_EOL; } - echo '<input type="hidden" name="tblcomment" value="', htmlspecialchars($_REQUEST['tblcomment']), '" />'.PHP_EOL; + echo '<input type="hidden" name="tblcomment" value="', \htmlspecialchars($_REQUEST['tblcomment']), '" />' . \PHP_EOL; + if (isset($_REQUEST['spcname'])) { - echo '<input type="hidden" name="spcname" value="', htmlspecialchars($_REQUEST['spcname']), '" />'.PHP_EOL; + echo '<input type="hidden" name="spcname" value="', \htmlspecialchars($_REQUEST['spcname']), '" />' . \PHP_EOL; } - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; break; case 3: @@ -644,14 +489,16 @@ class TablesController extends BaseController $this->coalesceArr($_REQUEST, 'spcname', null); // Check inputs - $fields = trim($_REQUEST['fields']); - if ('' == trim($_REQUEST['name'])) { + $fields = \trim($_REQUEST['fields']); + + if ('' === \trim($_REQUEST['name'])) { $_REQUEST['stage'] = 1; $this->doCreate($this->lang['strtableneedsname']); return; } - if ('' == $fields || !is_numeric($fields) || $fields != (int) $fields || $fields <= 0) { + + if ('' === $fields || !\is_numeric($fields) || (int) $fields !== $fields || 0 >= $fields) { $_REQUEST['stage'] = 1; $this->doCreate($this->lang['strtableneedscols']); @@ -675,12 +522,13 @@ class TablesController extends BaseController $_REQUEST['primarykey'] ); - if (0 == $status) { + if (0 === $status) { $this->misc->setReloadBrowser(true); return $this->doDefault($this->lang['strtablecreated']); } - if ($status == -1) { + + if (-1 === $status) { $_REQUEST['stage'] = 2; $this->doCreate($this->lang['strtableneedsfield']); @@ -693,7 +541,7 @@ class TablesController extends BaseController break; default: - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } } @@ -725,68 +573,76 @@ class TablesController extends BaseController $tables = []; $tblsel = ''; + foreach ($tbltmp as $a) { $data->fieldClean($a['nspname']); $data->fieldClean($a['relname']); - $tables["\"{$a['nspname']}\".\"{$a['relname']}\""] = serialize(['schema' => $a['nspname'], 'table' => $a['relname']]); - if ($_REQUEST['like'] == $tables["\"{$a['nspname']}\".\"{$a['relname']}\""]) { - $tblsel = htmlspecialchars($tables["\"{$a['nspname']}\".\"{$a['relname']}\""]); + $tables["\"{$a['nspname']}\".\"{$a['relname']}\""] = \serialize(['schema' => $a['nspname'], 'table' => $a['relname']]); + + if ($_REQUEST['like'] === $tables["\"{$a['nspname']}\".\"{$a['relname']}\""]) { + $tblsel = \htmlspecialchars($tables["\"{$a['nspname']}\".\"{$a['relname']}\""]); } } unset($tbltmp); - echo '<form action="'.\SUBFOLDER.'/src/views/tables" method="post">'.PHP_EOL; - echo "<table>\n\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; - echo "\t\t<td class=\"data\"><input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strcreatetablelikeparent']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tables" method="post">' . \PHP_EOL; + echo "<table>\n\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data\"><input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", \htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strcreatetablelikeparent']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\">"; echo \PHPPgAdmin\XHtml\HTMLController::printCombo($tables, 'like', true, $tblsel, false); - echo "</td>\n\t</tr>".PHP_EOL; + echo "</td>\n\t</tr>" . \PHP_EOL; + if ($data->hasTablespaces()) { $tblsp_ = $data->getTablespaces(); - if ($tblsp_->recordCount() > 0) { + + if (0 < $tblsp_->recordCount()) { $tblsp_ = $tblsp_->getArray(); $tblsp = []; + foreach ($tblsp_ as $a) { $tblsp[$a['spcname']] = $a['spcname']; } - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\">"; echo \PHPPgAdmin\XHtml\HTMLController::printCombo($tblsp, 'tablespace', true, $_REQUEST['tablespace'], false); - echo "</td>\n\t</tr>".PHP_EOL; + echo "</td>\n\t</tr>" . \PHP_EOL; } } echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['stroptions']}</th>\n\t\t<td class=\"data\">"; echo '<label for="withdefaults"><input type="checkbox" id="withdefaults" name="withdefaults"', isset($_REQUEST['withdefaults']) ? ' checked="checked"' : '', "/>{$this->lang['strcreatelikewithdefaults']}</label>"; + if ($data->hasCreateTableLikeWithConstraints()) { echo '<br /><label for="withconstraints"><input type="checkbox" id="withconstraints" name="withconstraints"', isset($_REQUEST['withconstraints']) ? ' checked="checked"' : '', "/>{$this->lang['strcreatelikewithconstraints']}</label>"; } + if ($data->hasCreateTableLikeWithIndexes()) { echo '<br /><label for="withindexes"><input type="checkbox" id="withindexes" name="withindexes"', isset($_REQUEST['withindexes']) ? ' checked="checked"' : '', "/>{$this->lang['strcreatelikewithindexes']}</label>"; } - echo "</td>\n\t</tr>".PHP_EOL; + echo "</td>\n\t</tr>" . \PHP_EOL; echo '</table>'; - echo '<input type="hidden" name="action" value="confcreatelike" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="confcreatelike" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - if ('' == trim($_REQUEST['name'])) { + if ('' === \trim($_REQUEST['name'])) { $this->doCreateLike(false, $this->lang['strtableneedsname']); return; } - if ('' == trim($_REQUEST['like'])) { + + if ('' === \trim($_REQUEST['like'])) { $this->doCreateLike(false, $this->lang['strtablelikeneedslike']); return; @@ -796,14 +652,14 @@ class TablesController extends BaseController $status = $data->createTableLike( $_REQUEST['name'], - unserialize($_REQUEST['like']), + \unserialize($_REQUEST['like']), isset($_REQUEST['withdefaults']), isset($_REQUEST['withconstraints']), isset($_REQUEST['withindexes']), $_REQUEST['tablespace'] ); - if (0 == $status) { + if (0 === $status) { $this->misc->setReloadBrowser(true); return $this->doDefault($this->lang['strtablecreated']); @@ -831,10 +687,11 @@ class TablesController extends BaseController $attrs = $data->getTableAttributes($_REQUEST['table']); - echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post" id="selectform">'.PHP_EOL; - if ($attrs->recordCount() > 0) { + echo '<form action="' . self::SUBFOLDER . '/src/views/display" method="post" id="selectform">' . \PHP_EOL; + + if (0 < $attrs->recordCount()) { // JavaScript for select all feature - echo '<script type="text/javascript">'.PHP_EOL; + echo '<script type="text/javascript">' . \PHP_EOL; echo "//<![CDATA[\n"; echo " function selectAll() {\n"; echo " for (var i=0; i<document.getElementById('selectform').elements.length; i++) {\n"; @@ -842,10 +699,10 @@ class TablesController extends BaseController echo " if (e.name.indexOf('show') == 0) e.checked = document.getElementById('selectform').selectall.checked;\n"; echo " }\n"; echo " }\n"; - echo '//]]>'.PHP_EOL; - echo '</script>'.PHP_EOL; + echo '//]]>' . \PHP_EOL; + echo '</script>' . \PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; // Output table header echo "<tr><th class=\"data\">{$this->lang['strshow']}</th><th class=\"data\">{$this->lang['strcolumn']}</th>"; @@ -853,6 +710,7 @@ class TablesController extends BaseController echo "<th class=\"data\">{$this->lang['strvalue']}</th></tr>"; $i = 0; + while (!$attrs->EOF) { $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']); // Set up default value if there isn't one already @@ -865,43 +723,44 @@ class TablesController extends BaseController } // Continue drawing row - $id = (0 == ($i % 2) ? '1' : '2'); - echo "<tr class=\"data{$id}\">".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "<tr class=\"data{$id}\">" . \PHP_EOL; echo '<td style="white-space:nowrap;">'; - echo '<input type="checkbox" name="show[', htmlspecialchars($attrs->fields['attname']), ']"', + echo '<input type="checkbox" name="show[', \htmlspecialchars($attrs->fields['attname']), ']"', isset($_REQUEST['show'][$attrs->fields['attname']]) ? ' checked="checked"' : '', ' /></td>'; echo '<td style="white-space:nowrap;">', $this->misc->printVal($attrs->fields['attname']), '</td>'; echo '<td style="white-space:nowrap;">', $this->misc->printVal($data->formatType($attrs->fields['type'], $attrs->fields['atttypmod'])), '</td>'; echo '<td style="white-space:nowrap;">'; - echo "<select name=\"ops[{$attrs->fields['attname']}]\">".PHP_EOL; - foreach (array_keys($data->selectOps) as $v) { - echo '<option value="', htmlspecialchars($v), '"', ($_REQUEST['ops'][$attrs->fields['attname']] == $v) ? ' selected="selected"' : '', - '>', htmlspecialchars($v), '</option>'.PHP_EOL; + echo "<select name=\"ops[{$attrs->fields['attname']}]\">" . \PHP_EOL; + + foreach (\array_keys($data->selectOps) as $v) { + echo '<option value="', \htmlspecialchars($v), '"', ($_REQUEST['ops'][$attrs->fields['attname']] === $v) ? ' selected="selected"' : '', + '>', \htmlspecialchars($v), '</option>' . \PHP_EOL; } - echo "</select>\n</td>".PHP_EOL; + echo "</select>\n</td>" . \PHP_EOL; echo '<td style="white-space:nowrap;">', $data->printField( "values[{$attrs->fields['attname']}]", $_REQUEST['values'][$attrs->fields['attname']], $attrs->fields['type'] ), '</td>'; - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; ++$i; $attrs->moveNext(); } // Select all checkbox echo "<tr><td colspan=\"5\"><input type=\"checkbox\" id=\"selectall\" name=\"selectall\" accesskey=\"a\" onclick=\"javascript:selectAll()\" /><label for=\"selectall\">{$this->lang['strselectallfields']}</label></td>"; - echo '</tr></table>'.PHP_EOL; + echo '</tr></table>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } - echo '<p><input type="hidden" name="action" value="selectrows" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo '<input type="hidden" name="subject" value="table" />'.PHP_EOL; + echo '<p><input type="hidden" name="action" value="selectrows" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="subject" value="table" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"select\" accesskey=\"r\" value=\"{$this->lang['strselect']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"select\" accesskey=\"r\" value=\"{$this->lang['strselect']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; return; } @@ -913,20 +772,20 @@ class TablesController extends BaseController // Verify that they haven't supplied a value for unary operators foreach ($_POST['ops'] as $k => $v) { - if ('p' == $data->selectOps[$v] && $_POST['values'][$k] != '') { + if ('p' === $data->selectOps[$v] && '' !== $_POST['values'][$k]) { $this->doSelectRows(true, $this->lang['strselectunary']); return; } } - if (0 == sizeof($_POST['show'])) { + if (0 === \count($_POST['show'])) { $this->doSelectRows(true, $this->lang['strselectneedscol']); } else { // Generate query SQL $query = $data->getSelectSQL( $_REQUEST['table'], - array_keys($_POST['show']), + \array_keys($_POST['show']), $_POST['values'], $_POST['ops'] ); @@ -946,7 +805,7 @@ class TablesController extends BaseController * * @param mixed $msg */ - public function formInsertRow($msg = '') + public function formInsertRow($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -963,9 +822,10 @@ class TablesController extends BaseController $this->coalesceArr($_REQUEST, 'nulls', []); $this->coalesceArr($_REQUEST, 'format', []); - echo '<form action="'.\SUBFOLDER.'/src/views/tables" method="post" id="ac_form">'.PHP_EOL; - if ($attrs->recordCount() > 0) { - echo '<table>'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tables" method="post" id="ac_form">' . \PHP_EOL; + + if (0 < $attrs->recordCount()) { + echo '<table>' . \PHP_EOL; // Output table header echo "<tr><th class=\"data\">{$this->lang['strcolumn']}</th><th class=\"data\">{$this->lang['strtype']}</th>"; @@ -974,13 +834,15 @@ class TablesController extends BaseController $i = 0; $fields = []; + while (!$attrs->EOF) { $fields[$attrs->fields['attnum']] = $attrs->fields['attname']; $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']); // Set up default value if there isn't one already if (!isset($_REQUEST['values'][$attrs->fields['attnum']])) { $_REQUEST['values'][$attrs->fields['attnum']] = $attrs->fields['adsrc']; - if ($attrs->fields['adsrc'] === null && !$attrs->fields['attnotnull']) { + + if (null === $attrs->fields['adsrc'] && !$attrs->fields['attnotnull']) { $_REQUEST['nulls'][$attrs->fields['attnum']] = true; } } @@ -993,10 +855,10 @@ class TablesController extends BaseController $requested_format = $_REQUEST['format'][$attrs->fields['attnum']]; // Continue drawing row - $id = (0 == ($i % 2) ? '1' : '2'); - echo "<tr class=\"data{$id}\">".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "<tr class=\"data{$id}\">" . \PHP_EOL; echo '<td style="white-space:nowrap;">', $this->misc->printVal($attrs->fields['attname']), '</td>'; - echo '<td style="white-space:nowrap;">'.PHP_EOL; + echo '<td style="white-space:nowrap;">' . \PHP_EOL; echo $this->misc->printVal( $data->formatType( $attrs->fields['type'], @@ -1004,30 +866,30 @@ class TablesController extends BaseController ) ); echo "<input type=\"hidden\" name=\"types[{$attrs->fields['attnum']}]\" value=\"", - htmlspecialchars($attrs->fields['type']), '" /></td>'; - echo '<td style="white-space:nowrap;">'.PHP_EOL; + \htmlspecialchars($attrs->fields['type']), '" /></td>'; + echo '<td style="white-space:nowrap;">' . \PHP_EOL; - echo "<select name=\"format[{$attrs->fields['attnum']}]\">".PHP_EOL; - echo sprintf( + echo "<select name=\"format[{$attrs->fields['attnum']}]\">" . \PHP_EOL; + echo \sprintf( '<option value="VALUE" %s >%s</option> %s', - ($requested_format == 'VALUE') ? ' selected="selected" ' : '', + ('VALUE' === $requested_format) ? ' selected="selected" ' : '', $this->lang['strvalue'], - PHP_EOL + \PHP_EOL ); - echo sprintf( + echo \sprintf( '<option value="EXPRESSION" %s >%s</option> %s', - ($requested_format == 'EXPRESSION') ? ' selected="selected" ' : '', + ('EXPRESSION' === $requested_format) ? ' selected="selected" ' : '', $this->lang['strexpression'], - PHP_EOL + \PHP_EOL ); - echo "</select>\n</td>".PHP_EOL; + echo "</select>\n</td>" . \PHP_EOL; echo '<td style="white-space:nowrap;">'; // Output null box if the column allows nulls // Edit: if it can be null, then null it is. if (!$attrs->fields['attnotnull']) { echo '<label><span>'; - echo sprintf( + echo \sprintf( '<input type="checkbox" class="nullcheckbox" name="nulls[%s]" %s />', $attrs->fields['attnum'], ' checked="checked"' @@ -1052,40 +914,40 @@ class TablesController extends BaseController } else { echo $data->printField("values[{$attrs->fields['attnum']}]", $_REQUEST['values'][$attrs->fields['attnum']], $attrs->fields['type'], ['class' => 'insert_row_input']); } - echo '</td>'.PHP_EOL; - echo '</tr>'.PHP_EOL; + echo '</td>' . \PHP_EOL; + echo '</tr>' . \PHP_EOL; ++$i; $attrs->moveNext(); } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; if (!isset($_SESSION['counter'])) { $_SESSION['counter'] = 0; } - echo '<input type="hidden" name="action" value="insertrow" />'.PHP_EOL; - echo '<input type="hidden" name="fields" value="', htmlentities(serialize($fields), ENT_QUOTES, 'UTF-8'), '" />'.PHP_EOL; - echo '<input type="hidden" name="protection_counter" value="'.$_SESSION['counter'].'" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo "<p><input type=\"submit\" name=\"insert\" value=\"{$this->lang['strinsert']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"insertandrepeat\" accesskey=\"r\" value=\"{$this->lang['strinsertandrepeat']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo '<input type="hidden" name="action" value="insertrow" />' . \PHP_EOL; + echo '<input type="hidden" name="fields" value="', \htmlentities(\serialize($fields), \ENT_QUOTES, 'UTF-8'), '" />' . \PHP_EOL; + echo '<input type="hidden" name="protection_counter" value="' . $_SESSION['counter'] . '" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo "<p><input type=\"submit\" name=\"insert\" value=\"{$this->lang['strinsert']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"insertandrepeat\" accesskey=\"r\" value=\"{$this->lang['strinsertandrepeat']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; if (false !== $fksprops) { - if ('default off' != $this->conf['autocomplete']) { - echo "<input type=\"checkbox\" id=\"no_ac\" value=\"1\" checked=\"checked\" /><label for=\"no_ac\">{$this->lang['strac']}</label>".PHP_EOL; + if ('default off' !== $this->conf['autocomplete']) { + echo "<input type=\"checkbox\" id=\"no_ac\" value=\"1\" checked=\"checked\" /><label for=\"no_ac\">{$this->lang['strac']}</label>" . \PHP_EOL; } else { - echo "<input type=\"checkbox\" id=\"no_ac\" value=\"0\" /><label for=\"no_ac\">{$this->lang['strac']}</label>".PHP_EOL; + echo "<input type=\"checkbox\" id=\"no_ac\" value=\"0\" /><label for=\"no_ac\">{$this->lang['strac']}</label>" . \PHP_EOL; } } - echo '</p>'.PHP_EOL; + echo '</p>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnofieldsforinsert']}</p>".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<p>{$this->lang['strnofieldsforinsert']}</p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; } echo $this->misc->form; - echo '</form>'.PHP_EOL; - echo '<script src="'.\SUBFOLDER.'/assets/js/insert_or_edit_row.js" type="text/javascript"></script>'; + echo '</form>' . \PHP_EOL; + echo '<script src="' . self::SUBFOLDER . '/assets/js/insert_or_edit_row.js" type="text/javascript"></script>'; } /** @@ -1099,11 +961,12 @@ class TablesController extends BaseController $this->coalesceArr($_POST, 'nulls', []); - $_POST['fields'] = unserialize(htmlspecialchars_decode($_POST['fields'], ENT_QUOTES)); + $_POST['fields'] = \unserialize(\htmlspecialchars_decode($_POST['fields'], \ENT_QUOTES)); - if ($_SESSION['counter']++ == $_POST['protection_counter']) { + if ($_SESSION['counter']++ === $_POST['protection_counter']) { $status = $data->insertRow($_POST['table'], $_POST['fields'], $_POST['values'], $_POST['nulls'], $_POST['format'], $_POST['types']); - if (0 == $status) { + + if (0 === $status) { if (isset($_POST['insert'])) { return $this->doDefault($this->lang['strrowinserted']); } @@ -1137,41 +1000,44 @@ class TablesController extends BaseController $this->printTrail('schema'); $this->printTitle($this->lang['strempty'], 'pg.table.empty'); - echo '<form action="'.\SUBFOLDER.'/src/views/tables" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tables" method="post">' . \PHP_EOL; + foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>'.sprintf($this->lang['strconfemptytable'], $this->misc->printVal($a['table'])); + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>' . \sprintf($this->lang['strconfemptytable'], $this->misc->printVal($a['table'])); - echo '</p>'.PHP_EOL; - printf('<input type="hidden" name="table[]" value="%s" />', htmlspecialchars($a['table'])); + echo '</p>' . \PHP_EOL; + \printf('<input type="hidden" name="table[]" value="%s" />', \htmlspecialchars($a['table'])); } // END mutli empty } else { $this->printTrail('table'); $this->printTitle($this->lang['strempty'], 'pg.table.empty'); - echo '<p>', sprintf($this->lang['strconfemptytable'], $this->misc->printVal($_REQUEST['table'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfemptytable'], $this->misc->printVal($_REQUEST['table'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/tables" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tables" method="post">' . \PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; // END not mutli empty } echo "<input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label>"; - echo '<input type="hidden" name="action" value="empty" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="empty" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"empty\" value=\"{$this->lang['strempty']}\" /> <input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<input type=\"submit\" name=\"empty\" value=\"{$this->lang['strempty']}\" /> <input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; echo "</form>\n"; // END if confirm } else { // Do Empty $msg = ''; - if (is_array($_REQUEST['table'])) { + + if (\is_array($_REQUEST['table'])) { foreach ($_REQUEST['table'] as $t) { list($status, $sql) = $data->emptyTable($t, isset($_POST['cascade'])); - if (0 == $status) { - $msg .= sprintf('%s<br />', $sql); - $msg .= sprintf('%s: %s<br />', htmlentities($t, ENT_QUOTES, 'UTF-8'), $this->lang['strtableemptied']); + + if (0 === $status) { + $msg .= \sprintf('%s<br />', $sql); + $msg .= \sprintf('%s: %s<br />', \htmlentities($t, \ENT_QUOTES, 'UTF-8'), $this->lang['strtableemptied']); } else { - $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($t, ENT_QUOTES, 'UTF-8'), $this->lang['strtableemptiedbad'])); + $this->doDefault(\sprintf('%s%s: %s<br />', $msg, \htmlentities($t, \ENT_QUOTES, 'UTF-8'), $this->lang['strtableemptiedbad'])); return; } @@ -1179,14 +1045,15 @@ class TablesController extends BaseController $this->doDefault($msg); // END mutli empty } else { list($status, $sql) = $data->emptyTable($_POST['table'], isset($_POST['cascade'])); - if (0 == $status) { - $msg .= sprintf('%s<br />', $sql); - $msg .= sprintf('%s: %s<br />', htmlentities($_POST['table'], ENT_QUOTES, 'UTF-8'), $this->lang['strtableemptied']); + + if (0 === $status) { + $msg .= \sprintf('%s<br />', $sql); + $msg .= \sprintf('%s: %s<br />', \htmlentities($_POST['table'], \ENT_QUOTES, 'UTF-8'), $this->lang['strtableemptied']); return $this->doDefault($msg); } - return $this->doDefault($sql.'<br>'.$this->lang['strtableemptiedbad']); + return $this->doDefault($sql . '<br>' . $this->lang['strtableemptiedbad']); // END not mutli empty } // END do Empty @@ -1212,47 +1079,51 @@ class TablesController extends BaseController $this->printTrail('schema'); $this->printTitle($this->lang['strdrop'], 'pg.table.drop'); - echo '<form action="'.\SUBFOLDER.'/src/views/tables" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tables" method="post">' . \PHP_EOL; + foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfdroptable'], $this->misc->printVal($a['table'])), '</p>'.PHP_EOL; - printf('<input type="hidden" name="table[]" value="%s" />', htmlspecialchars($a['table'])); + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfdroptable'], $this->misc->printVal($a['table'])), '</p>' . \PHP_EOL; + \printf('<input type="hidden" name="table[]" value="%s" />', \htmlspecialchars($a['table'])); } } else { $this->printTrail('table'); $this->printTitle($this->lang['strdrop'], 'pg.table.drop'); - echo '<p>', sprintf($this->lang['strconfdroptable'], $this->misc->printVal($_REQUEST['table'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdroptable'], $this->misc->printVal($_REQUEST['table'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/tables" method="post">'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tables" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; // END if multi drop } - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; echo "</form>\n"; // END confirm } else { //If multi drop - if (is_array($_REQUEST['table'])) { + if (\is_array($_REQUEST['table'])) { $msg = ''; $status = $data->beginTransaction(); - if (0 == $status) { + + if (0 === $status) { foreach ($_REQUEST['table'] as $t) { $status = $data->dropTable($t, isset($_POST['cascade'])); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($t, ENT_QUOTES, 'UTF-8'), $this->lang['strtabledropped']); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($t, \ENT_QUOTES, 'UTF-8'), $this->lang['strtabledropped']); } else { $data->endTransaction(); - return $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($t, ENT_QUOTES, 'UTF-8'), $this->lang['strtabledroppedbad'])); + return $this->doDefault(\sprintf('%s%s: %s<br />', $msg, \htmlentities($t, \ENT_QUOTES, 'UTF-8'), $this->lang['strtabledroppedbad'])); } } } - if (0 == $data->endTransaction()) { + + if (0 === $data->endTransaction()) { // Everything went fine, back to the Default page.... $this->misc->setReloadBrowser(true); @@ -1262,7 +1133,8 @@ class TablesController extends BaseController return $this->doDefault($this->lang['strtabledroppedbad']); } $status = $data->dropTable($_POST['table'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); return $this->doDefault($this->lang['strtabledropped']); @@ -1273,5 +1145,167 @@ class TablesController extends BaseController } } + private function _getColumns() + { + return [ + 'table' => [ + 'title' => $this->lang['strtable'], + 'field' => Decorator::field('relname'), + 'url' => self::SUBFOLDER . "/redirect/table?{$this->misc->href}&", + 'vars' => ['table' => 'relname'], + ], + 'owner' => [ + 'title' => $this->lang['strowner'], + 'field' => Decorator::field('relowner'), + ], + 'tablespace' => [ + 'title' => $this->lang['strtablespace'], + 'field' => Decorator::field('tablespace'), + ], + 'tuples' => [ + 'title' => $this->lang['strestimatedrowcount'], + 'field' => Decorator::field('reltuples'), + 'type' => 'numeric', + ], + 'table_size' => [ + 'title' => $this->lang['strsize'], + 'field' => Decorator::field('table_size'), + ], + 'actions' => [ + 'title' => $this->lang['stractions'], + ], + 'comment' => [ + 'title' => $this->lang['strcomment'], + 'field' => Decorator::field('relcomment'), + ], + ]; + } + + private function _getActions() + { + return [ + 'multiactions' => [ + 'keycols' => ['table' => 'relname'], + 'url' => 'tables', + 'default' => 'analyze', + ], + 'browse' => [ + 'content' => $this->lang['strbrowse'], + 'attr' => [ + 'href' => [ + 'url' => 'display', + 'urlvars' => [ + 'subject' => 'table', + 'return' => 'table', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + 'select' => [ + 'content' => $this->lang['strselect'], + 'attr' => [ + 'href' => [ + 'url' => 'tables', + 'urlvars' => [ + 'action' => 'confselectrows', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + 'insert' => [ + 'content' => $this->lang['strinsert'], + 'attr' => [ + 'href' => [ + 'url' => 'tables', + 'urlvars' => [ + 'action' => 'confinsertrow', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + 'empty' => [ + 'multiaction' => 'confirm_empty', + 'content' => $this->lang['strempty'], + 'attr' => [ + 'href' => [ + 'url' => 'tables', + 'urlvars' => [ + 'action' => 'confirm_empty', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + 'alter' => [ + 'content' => $this->lang['stralter'], + 'attr' => [ + 'href' => [ + 'url' => 'tblproperties', + 'urlvars' => [ + 'action' => 'confirm_alter', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + 'drop' => [ + 'multiaction' => 'confirm_drop', + 'content' => $this->lang['strdrop'], + 'attr' => [ + 'href' => [ + 'url' => 'tables', + 'urlvars' => [ + 'action' => 'confirm_drop', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + 'vacuum' => [ + 'multiaction' => 'confirm_vacuum', + 'content' => $this->lang['strvacuum'], + 'attr' => [ + 'href' => [ + 'url' => 'tables', + 'urlvars' => [ + 'action' => 'confirm_vacuum', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + 'analyze' => [ + 'multiaction' => 'confirm_analyze', + 'content' => $this->lang['stranalyze'], + 'attr' => [ + 'href' => [ + 'url' => 'tables', + 'urlvars' => [ + 'action' => 'confirm_analyze', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + 'reindex' => [ + 'multiaction' => 'confirm_reindex', + 'content' => $this->lang['strreindex'], + 'attr' => [ + 'href' => [ + 'url' => 'tables', + 'urlvars' => [ + 'action' => 'confirm_reindex', + 'table' => Decorator::field('relname'), + ], + ], + ], + ], + //'cluster' TODO ? + ]; + } + // END Function } diff --git a/src/controllers/TablespacesController.php b/src/controllers/TablespacesController.php index 2a000ac7..d4b1270e 100644 --- a/src/controllers/TablespacesController.php +++ b/src/controllers/TablespacesController.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class TablespacesController extends BaseController { @@ -18,7 +19,7 @@ class TablespacesController extends BaseController /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { $this->printHeader(); $this->printBody(); @@ -74,7 +75,7 @@ class TablespacesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -161,7 +162,7 @@ class TablespacesController extends BaseController ], ], 'content' => $this->lang['strcreatetablespace'], - ]], 'tablespaces-tablespaces', get_defined_vars()); + ]], 'tablespaces-tablespaces', \get_defined_vars()); } /** @@ -169,7 +170,7 @@ class TablespacesController extends BaseController * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -182,61 +183,64 @@ class TablespacesController extends BaseController // Fetch all users $users = $data->getUsers(); - if ($tablespace->recordCount() > 0) { + if (0 < $tablespace->recordCount()) { $this->coalesceArr($_POST, 'name', $tablespace->fields['spcname']); $this->coalesceArr($_POST, 'owner', $tablespace->fields['spcowner']); $this->coalesceArr($_POST, 'comment', ($data->hasSharedComments()) ? $tablespace->fields['spccomment'] : ''); - echo '<form action="'.\SUBFOLDER.'/src/views/tablespaces" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tablespaces" method="post">' . \PHP_EOL; echo $this->misc->form; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo "<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" /></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; + \htmlspecialchars($_POST['name']), '" /></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="owner">'; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $_POST['owner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $_POST['owner']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + if ($data->hasSharedComments()) { - echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo '<textarea rows="3" cols="32" name="comment">', - htmlspecialchars($_POST['comment']), '</textarea></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['comment']), '</textarea></td></tr>' . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_edit" />'.PHP_EOL; - echo '<input type="hidden" name="tablespace" value="', htmlspecialchars($_REQUEST['tablespace']), '" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_edit" />' . \PHP_EOL; + echo '<input type="hidden" name="tablespace" value="', \htmlspecialchars($_REQUEST['tablespace']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } /** * Function to save after altering a tablespace. */ - public function doSaveAlter() + public function doSaveAlter(): void { $data = $this->misc->getDatabaseAccessor(); // Check data - if ('' == trim($_POST['name'])) { + if ('' === \trim($_POST['name'])) { $this->doAlter($this->lang['strtablespaceneedsname']); } else { $status = $data->alterTablespace($_POST['tablespace'], $_POST['name'], $_POST['owner'], $_POST['comment']); - if (0 == $status) { + + if (0 === $status) { // If tablespace has been renamed, need to change to the new name - if ($_POST['tablespace'] != $_POST['name']) { + if ($_POST['tablespace'] !== $_POST['name']) { // Jump them to the new table name $_REQUEST['tablespace'] = $_POST['name']; } @@ -252,7 +256,7 @@ class TablespacesController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -260,18 +264,19 @@ class TablespacesController extends BaseController $this->printTrail('tablespace'); $this->printTitle($this->lang['strdrop'], 'pg.tablespace.drop'); - echo '<p>', sprintf($this->lang['strconfdroptablespace'], $this->misc->printVal($_REQUEST['tablespace'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdroptablespace'], $this->misc->printVal($_REQUEST['tablespace'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/tablespaces" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tablespaces" method="post">' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="tablespace" value="', htmlspecialchars($_REQUEST['tablespace']), '" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="tablespace" value="', \htmlspecialchars($_REQUEST['tablespace']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->droptablespace($_REQUEST['tablespace']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtablespacedropped']); } else { $this->doDefault($this->lang['strtablespacedroppedbad']); @@ -284,7 +289,7 @@ class TablespacesController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -305,53 +310,55 @@ class TablespacesController extends BaseController $this->printTitle($this->lang['strcreatetablespace'], 'pg.tablespace.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/tablespaces" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tablespaces" method="post">' . \PHP_EOL; echo $this->misc->form; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"32\" name=\"formSpcname\" maxlength=\"{$data->_maxNameLen}\" value=\"", htmlspecialchars($_POST['formSpcname']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><select name=\"formOwner\">".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"32\" name=\"formSpcname\" maxlength=\"{$data->_maxNameLen}\" value=\"", \htmlspecialchars($_POST['formSpcname']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><select name=\"formOwner\">" . \PHP_EOL; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo "\t\t\t<option value=\"", htmlspecialchars($uname), '"', - ($uname == $_POST['formOwner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo "\t\t\t<option value=\"", \htmlspecialchars($uname), '"', + ($uname === $_POST['formOwner']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo "\t\t</select></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strlocation']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"32\" name=\"formLoc\" value=\"", htmlspecialchars($_POST['formLoc']), "\" /></td>\n\t</tr>".PHP_EOL; + echo "\t\t</select></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strlocation']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"32\" name=\"formLoc\" value=\"", \htmlspecialchars($_POST['formLoc']), "\" /></td>\n\t</tr>" . \PHP_EOL; // Comments (if available) if ($data->hasSharedComments()) { - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td><textarea name=\"formComment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new tablespace in the cluster. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); // Check data - if ('' == trim($_POST['formSpcname'])) { + if ('' === \trim($_POST['formSpcname'])) { $this->doCreate($this->lang['strtablespaceneedsname']); - } elseif ('' == trim($_POST['formLoc'])) { + } elseif ('' === \trim($_POST['formLoc'])) { $this->doCreate($this->lang['strtablespaceneedsloc']); } else { // Default comment to blank if it isn't set $this->coalesceArr($_POST, 'formComment', null); $status = $data->createTablespace($_POST['formSpcname'], $_POST['formOwner'], $_POST['formLoc'], $_POST['formComment']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtablespacecreated']); } else { $this->doCreate($this->lang['strtablespacecreatedbad']); diff --git a/src/controllers/TblpropertiesController.php b/src/controllers/TblpropertiesController.php index c5ec032f..af6a6326 100644 --- a/src/controllers/TblpropertiesController.php +++ b/src/controllers/TblpropertiesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,12 +13,11 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class TblpropertiesController extends BaseController { use \PHPPgAdmin\Traits\ExportTrait; + public $controller_title = 'strtables'; /** @@ -23,13 +25,14 @@ class TblpropertiesController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } $header_template = 'header.twig'; - ob_start(); + \ob_start(); + switch ($this->action) { case 'alter': if (isset($_POST['alter'])) { @@ -86,7 +89,7 @@ class TblpropertiesController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $this->printHeader($this->headerTitle('', '', $_REQUEST['table']), null, true, $header_template); $this->printBody(); @@ -101,7 +104,7 @@ class TblpropertiesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $misc = $this->misc; $this->data = $misc->getDatabaseAccessor(); @@ -119,7 +122,7 @@ class TblpropertiesController extends BaseController // Show comment if any if (null !== $tdata->fields['relcomment']) { - echo '<p class="comment">', $misc->printVal($tdata->fields['relcomment']), '</p>'.PHP_EOL; + echo '<p class="comment">', $misc->printVal($tdata->fields['relcomment']), '</p>' . \PHP_EOL; } $this->_printTable($ck, $attrs); @@ -231,7 +234,7 @@ class TblpropertiesController extends BaseController 'content' => $this->lang['stralter'], ], ]; - $this->printNavLinks($navlinks, 'tblproperties-tblproperties', get_defined_vars()); + $this->printNavLinks($navlinks, 'tblproperties-tblproperties', \get_defined_vars()); } public function doTree() @@ -274,7 +277,7 @@ class TblpropertiesController extends BaseController return $this->printTree($columns, $attrs, 'tblcolumns'); } - public function doSaveAlter() + public function doSaveAlter(): void { $misc = $this->misc; $data = $misc->getDatabaseAccessor(); @@ -288,17 +291,18 @@ class TblpropertiesController extends BaseController $this->coalesceArr($_POST, 'newschema', null); $status = $data->alterTable($_POST['table'], $_POST['name'], $_POST['owner'], $_POST['newschema'], $_POST['comment'], $_POST['tablespace']); - if (0 == $status) { + + if (0 === $status) { // If table has been renamed, need to change to the new name and // reload the browser frame. - if ($_POST['table'] != $_POST['name']) { + if ($_POST['table'] !== $_POST['name']) { // Jump them to the new table name $_REQUEST['table'] = $_POST['name']; // Force a browser reload $misc->setReloadBrowser(true); } // If schema has changed, need to change to the new schema and reload the browser - if (!empty($_POST['newschema']) && ($_POST['newschema'] != $data->_schema)) { + if (!empty($_POST['newschema']) && ($_POST['newschema'] !== $data->_schema)) { // Jump them to the new sequence schema $misc->setCurrentSchema($_POST['newschema']); $misc->setReloadBrowser(true); @@ -314,7 +318,7 @@ class TblpropertiesController extends BaseController * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $misc = $this->misc; $data = $misc->getDatabaseAccessor(); @@ -333,7 +337,7 @@ class TblpropertiesController extends BaseController $tablespaces = $data->getTablespaces(true); } - if ($table->recordCount() > 0) { + if (0 < $table->recordCount()) { $this->coalesceArr($_POST, 'name', $table->fields['relname']); $this->coalesceArr($_POST, 'owner', $table->fields['relowner']); @@ -346,72 +350,74 @@ class TblpropertiesController extends BaseController $_POST['tablespace'] = $table->fields['tablespace']; } - echo '<form action="'.\SUBFOLDER.'/src/views/tblproperties" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tblproperties" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo "<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name'], ENT_QUOTES), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['name'], \ENT_QUOTES), '" /></td></tr>' . \PHP_EOL; if ($data->isSuperUser()) { - echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="owner">'; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $_POST['owner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $_POST['owner']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } if ($data->hasAlterTableSchema()) { $schemas = $data->getSchemas(); - echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="newschema">'; + while (!$schemas->EOF) { $schema = $schemas->fields['nspname']; - echo '<option value="', htmlspecialchars($schema), '"', - ($schema == $_POST['newschema']) ? ' selected="selected"' : '', '>', htmlspecialchars($schema), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($schema), '"', + ($schema === $_POST['newschema']) ? ' selected="selected"' : '', '>', \htmlspecialchars($schema), '</option>' . \PHP_EOL; $schemas->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } // Tablespace (if there are any) - if ($data->hasTablespaces() && $tablespaces->recordCount() > 0) { - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"tablespace\">".PHP_EOL; + if ($data->hasTablespaces() && 0 < $tablespaces->recordCount()) { + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"tablespace\">" . \PHP_EOL; // Always offer the default (empty) option echo "\t\t\t\t<option value=\"\"", - ('' == $_POST['tablespace']) ? ' selected="selected"' : '', '></option>'.PHP_EOL; + ('' === $_POST['tablespace']) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; // Display all other tablespaces while (!$tablespaces->EOF) { - $spcname = htmlspecialchars($tablespaces->fields['spcname']); + $spcname = \htmlspecialchars($tablespaces->fields['spcname']); echo "\t\t\t\t<option value=\"{$spcname}\"", - ($spcname == $_POST['tablespace']) ? ' selected="selected"' : '', ">{$spcname}</option>".PHP_EOL; + ($spcname === $_POST['tablespace']) ? ' selected="selected"' : '', ">{$spcname}</option>" . \PHP_EOL; $tablespaces->moveNext(); } - echo "\t\t\t</select>\n\t\t</td>\n\t</tr>".PHP_EOL; + echo "\t\t\t</select>\n\t\t</td>\n\t</tr>" . \PHP_EOL; } - echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo '<textarea rows="3" cols="32" name="comment">', - htmlspecialchars($_POST['comment']), '</textarea></td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="alter" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; + \htmlspecialchars($_POST['comment']), '</textarea></td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="alter" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; echo $misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } - public function doExport($msg = '') + public function doExport($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $subject = 'table'; @@ -438,7 +444,7 @@ class TblpropertiesController extends BaseController echo $this->formFooter($subject, $object); } - public function doImport($msg = '') + public function doImport($msg = ''): void { $misc = $this->misc; @@ -447,38 +453,40 @@ class TblpropertiesController extends BaseController $this->printMsg($msg); // Check that file uploads are enabled - if (!ini_get('file_uploads')) { - echo "<p>{$this->lang['strnouploads']}</p>".PHP_EOL; + if (!\ini_get('file_uploads')) { + echo "<p>{$this->lang['strnouploads']}</p>" . \PHP_EOL; return; } // Don't show upload option if max size of uploads is zero - $max_size = $misc->inisizeToBytes(ini_get('upload_max_filesize')); - if (is_double($max_size) && $max_size > 0) { - echo '<form action="'.\SUBFOLDER.'/src/views/dataimport" method="post" enctype="multipart/form-data">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strformat']}</th>".PHP_EOL; - echo "\t\t<td><select name=\"format\">".PHP_EOL; - echo "\t\t\t<option value=\"auto\">{$this->lang['strauto']}</option>".PHP_EOL; - echo "\t\t\t<option value=\"csv\">CSV</option>".PHP_EOL; - echo "\t\t\t<option value=\"tab\">{$this->lang['strtabbed']}</option>".PHP_EOL; - if (function_exists('xml_parser_create')) { - echo "\t\t\t<option value=\"xml\">XML</option>".PHP_EOL; + $max_size = $misc->inisizeToBytes(\ini_get('upload_max_filesize')); + + if (\is_float($max_size) && 0 < $max_size) { + echo '<form action="' . self::SUBFOLDER . '/src/views/dataimport" method="post" enctype="multipart/form-data">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strformat']}</th>" . \PHP_EOL; + echo "\t\t<td><select name=\"format\">" . \PHP_EOL; + echo "\t\t\t<option value=\"auto\">{$this->lang['strauto']}</option>" . \PHP_EOL; + echo "\t\t\t<option value=\"csv\">CSV</option>" . \PHP_EOL; + echo "\t\t\t<option value=\"tab\">{$this->lang['strtabbed']}</option>" . \PHP_EOL; + + if (\function_exists('xml_parser_create')) { + echo "\t\t\t<option value=\"xml\">XML</option>" . \PHP_EOL; } - echo "\t\t</select></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strallowednulls']}</th>".PHP_EOL; - echo "\t\t<td><label><input type=\"checkbox\" name=\"allowednulls[0]\" value=\"\\N\" checked=\"checked\" />{$this->lang['strbackslashn']}</label><br />".PHP_EOL; - echo "\t\t<label><input type=\"checkbox\" name=\"allowednulls[1]\" value=\"NULL\" />NULL</label><br />".PHP_EOL; - echo "\t\t<label><input type=\"checkbox\" name=\"allowednulls[2]\" value=\"\" />{$this->lang['stremptystring']}</label></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strfile']}</th>".PHP_EOL; + echo "\t\t</select></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strallowednulls']}</th>" . \PHP_EOL; + echo "\t\t<td><label><input type=\"checkbox\" name=\"allowednulls[0]\" value=\"\\N\" checked=\"checked\" />{$this->lang['strbackslashn']}</label><br />" . \PHP_EOL; + echo "\t\t<label><input type=\"checkbox\" name=\"allowednulls[1]\" value=\"NULL\" />NULL</label><br />" . \PHP_EOL; + echo "\t\t<label><input type=\"checkbox\" name=\"allowednulls[2]\" value=\"\" />{$this->lang['stremptystring']}</label></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strfile']}</th>" . \PHP_EOL; echo "\t\t<td><input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"{$max_size}\" />"; - echo "<input type=\"file\" name=\"source\" /></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="import" />'.PHP_EOL; + echo "<input type=\"file\" name=\"source\" /></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="import" />' . \PHP_EOL; echo $misc->form; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['strimport']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strimport']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } } @@ -487,7 +495,7 @@ class TblpropertiesController extends BaseController * * @param mixed $msg */ - public function doAddColumn($msg = '') + public function doAddColumn($msg = ''): void { $misc = $this->misc; $data = $misc->getDatabaseAccessor(); @@ -517,79 +525,82 @@ class TblpropertiesController extends BaseController $this->printTitle($this->lang['straddcolumn'], 'pg.column.add'); $this->printMsg($msg); - echo '<script src="'.\SUBFOLDER.'/assets/js/tables.js" type="text/javascript"></script>'; - echo '<form action="'.\SUBFOLDER.'/src/views/tblproperties" method="post">'.PHP_EOL; + echo '<script src="' . self::SUBFOLDER . '/assets/js/tables.js" type="text/javascript"></script>'; + echo '<form action="' . self::SUBFOLDER . '/src/views/tblproperties" method="post">' . \PHP_EOL; // Output table header - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data required\">{$this->lang['strname']}</th>\n<th colspan=\"2\" class=\"data required\">{$this->lang['strtype']}</th>".PHP_EOL; - echo "<th class=\"data\">{$this->lang['strlength']}</th>".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data required\">{$this->lang['strname']}</th>\n<th colspan=\"2\" class=\"data required\">{$this->lang['strtype']}</th>" . \PHP_EOL; + echo "<th class=\"data\">{$this->lang['strlength']}</th>" . \PHP_EOL; + if ($data->hasCreateFieldWithConstraints()) { - echo "<th class=\"data\">{$this->lang['strnotnull']}</th>\n<th class=\"data\">{$this->lang['strdefault']}</th>".PHP_EOL; + echo "<th class=\"data\">{$this->lang['strnotnull']}</th>\n<th class=\"data\">{$this->lang['strdefault']}</th>" . \PHP_EOL; } - echo "<th class=\"data\">{$this->lang['strcomment']}</th></tr>".PHP_EOL; + echo "<th class=\"data\">{$this->lang['strcomment']}</th></tr>" . \PHP_EOL; echo "<tr><td><input name=\"field\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['field']), '" /></td>'.PHP_EOL; - echo "<td><select class=\"select2\" name=\"type\" id=\"type\" onchange=\"checkLengths(document.getElementById('type').value,'');\">".PHP_EOL; + \htmlspecialchars($_POST['field']), '" /></td>' . \PHP_EOL; + echo "<td><select class=\"select2\" name=\"type\" id=\"type\" onchange=\"checkLengths(document.getElementById('type').value,'');\">" . \PHP_EOL; // Output any "magic" types. This came in with the alter column type so we'll check that if ($data->hasMagicTypes()) { foreach ($data->extraTypes as $v) { - $types_for_js[] = strtolower($v); - echo "\t<option value=\"", htmlspecialchars($v), '"', - ($v == $_POST['type']) ? ' selected="selected"' : '', '>', - $misc->printVal($v), '</option>'.PHP_EOL; + $types_for_js[] = \mb_strtolower($v); + echo "\t<option value=\"", \htmlspecialchars($v), '"', + ($v === $_POST['type']) ? ' selected="selected"' : '', '>', + $misc->printVal($v), '</option>' . \PHP_EOL; } } + while (!$types->EOF) { $typname = $types->fields['typname']; $types_for_js[] = $typname; - echo "\t<option value=\"", htmlspecialchars($typname), '"', ($typname == $_POST['type']) ? ' selected="selected"' : '', '>', - $misc->printVal($typname), '</option>'.PHP_EOL; + echo "\t<option value=\"", \htmlspecialchars($typname), '"', ($typname === $_POST['type']) ? ' selected="selected"' : '', '>', + $misc->printVal($typname), '</option>' . \PHP_EOL; $types->moveNext(); } - echo '</select></td>'.PHP_EOL; + echo '</select></td>' . \PHP_EOL; // Output array type selector - echo '<td><select name="array">'.PHP_EOL; - echo "\t<option value=\"\"", ('' == $_POST['array']) ? ' selected="selected"' : '', '></option>'.PHP_EOL; - echo "\t<option value=\"[]\"", ('[]' == $_POST['array']) ? ' selected="selected"' : '', '>[ ]</option>'.PHP_EOL; - echo '</select></td>'.PHP_EOL; - $predefined_size_types = array_intersect($data->predefined_size_types, $types_for_js); + echo '<td><select name="array">' . \PHP_EOL; + echo "\t<option value=\"\"", ('' === $_POST['array']) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; + echo "\t<option value=\"[]\"", ('[]' === $_POST['array']) ? ' selected="selected"' : '', '>[ ]</option>' . \PHP_EOL; + echo '</select></td>' . \PHP_EOL; + $predefined_size_types = \array_intersect($data->predefined_size_types, $types_for_js); $escaped_predef_types = []; // the JS escaped array elements foreach ($predefined_size_types as $value) { $escaped_predef_types[] = "'{$value}'"; } echo '<td><input name="length" id="lengths" size="8" value="', - htmlspecialchars($_POST['length']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_POST['length']), '" /></td>' . \PHP_EOL; // Support for adding column with not null and default if ($data->hasCreateFieldWithConstraints()) { echo '<td><input type="checkbox" name="notnull"', - (isset($_REQUEST['notnull'])) ? ' checked="checked"' : '', ' /></td>'.PHP_EOL; + (isset($_REQUEST['notnull'])) ? ' checked="checked"' : '', ' /></td>' . \PHP_EOL; echo '<td><input name="default" size="20" value="', - htmlspecialchars($_POST['default']), '" /></td>'.PHP_EOL; + \htmlspecialchars($_POST['default']), '" /></td>' . \PHP_EOL; } echo '<td><input name="comment" size="40" value="', - htmlspecialchars($_POST['comment']), '" /></td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="add_column" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="2" />'.PHP_EOL; + \htmlspecialchars($_POST['comment']), '" /></td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="add_column" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="2" />' . \PHP_EOL; echo $misc->form; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + if (!$data->hasCreateFieldWithConstraints()) { - echo '<input type="hidden" name="default" value="" />'.PHP_EOL; + echo '<input type="hidden" name="default" value="" />' . \PHP_EOL; } - echo "<input type=\"submit\" value=\"{$this->lang['stradd']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; - echo '<script type="text/javascript">predefined_lengths = new Array('.implode(',', $escaped_predef_types).");checkLengths(document.getElementById('type').value,'');</script>".PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['stradd']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; + echo '<script type="text/javascript">predefined_lengths = new Array(' . \implode(',', $escaped_predef_types) . ");checkLengths(document.getElementById('type').value,'');</script>" . \PHP_EOL; break; case 2: // Check inputs - if ('' == trim($_POST['field'])) { + if ('' === \trim($_POST['field'])) { $_REQUEST['stage'] = 1; $this->doAddColumn($this->lang['strcolneedsname']); @@ -601,15 +612,16 @@ class TblpropertiesController extends BaseController $_POST['table'], $_POST['field'], $_POST['type'], - '' != $_POST['array'], + '' !== $_POST['array'], $_POST['length'], isset($_POST['notnull']), $_POST['default'], $_POST['comment'] ); - if (0 == $status) { + + if (0 === $status) { $misc->setReloadBrowser(true); - $this->doDefault(sprintf('%s %s %s', $sql, PHP_EOL, $this->lang['strcolumnadded'])); + $this->doDefault(\sprintf('%s %s %s', $sql, \PHP_EOL, $this->lang['strcolumnadded'])); } else { $_REQUEST['stage'] = 1; $this->doAddColumn($this->lang['strcolumnaddedbad']); @@ -619,7 +631,7 @@ class TblpropertiesController extends BaseController break; default: - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } } @@ -628,7 +640,7 @@ class TblpropertiesController extends BaseController * * @param bool $confirm true to ask for confirmation, false to actually drop */ - public function doDrop($confirm = true) + public function doDrop($confirm = true): void { $misc = $this->misc; $data = $misc->getDatabaseAccessor(); @@ -637,22 +649,23 @@ class TblpropertiesController extends BaseController $this->printTrail('column'); $this->printTitle($this->lang['strdrop'], 'pg.column.drop'); - echo '<p>'.sprintf($this->lang['strconfdropcolumn'], $misc->printVal($_REQUEST['column']), $misc->printVal($_REQUEST['table'])).'</p>'.PHP_EOL; + echo '<p>' . \sprintf($this->lang['strconfdropcolumn'], $misc->printVal($_REQUEST['column']), $misc->printVal($_REQUEST['table'])) . '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/tblproperties" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo '<input type="hidden" name="column" value="', htmlspecialchars($_REQUEST['column']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/tblproperties" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="column" value="', \htmlspecialchars($_REQUEST['column']), '" />' . \PHP_EOL; echo $misc->form; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\"> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\"> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { list($status, $sql) = $data->dropColumn($_POST['table'], $_POST['column'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $misc->setReloadBrowser(true); - $this->doDefault(sprintf('%s %s %s', $sql, PHP_EOL, $this->lang['strcolumndropped'])); + $this->doDefault(\sprintf('%s %s %s', $sql, \PHP_EOL, $this->lang['strcolumndropped'])); } else { $this->doDefault($this->lang['strcolumndroppedbad']); } @@ -661,7 +674,7 @@ class TblpropertiesController extends BaseController private function _getAttPre($data) { - $attPre = function (&$rowdata, $actions) use ($data) { + $attPre = static function (&$rowdata, $actions) use ($data) { $rowdata->fields['+type'] = $data->formatType($rowdata->fields['type'], $rowdata->fields['atttypmod']); $attname = $rowdata->fields['attname']; $table = $_REQUEST['table']; @@ -679,34 +692,35 @@ class TblpropertiesController extends BaseController private function _getCstrRender($misc, $data) { - $cstrRender = function ($s, $p) use ($misc, $data) { + $cstrRender = static function ($s, $p) use ($misc, $data) { $str = ''; + foreach ($p['keys'] as $k => $c) { - if (is_null($p['keys'][$k]['consrc'])) { - $atts = $data->getAttributeNames($_REQUEST['table'], explode(' ', $p['keys'][$k]['indkey'])); - $c['consrc'] = ('u' == $c['contype'] ? 'UNIQUE (' : 'PRIMARY KEY (').join(',', $atts).')'; + if (null === $p['keys'][$k]['consrc']) { + $atts = $data->getAttributeNames($_REQUEST['table'], \explode(' ', $p['keys'][$k]['indkey'])); + $c['consrc'] = ('u' === $c['contype'] ? 'UNIQUE (' : 'PRIMARY KEY (') . \implode(',', $atts) . ')'; } - if ($c['p_field'] == $s) { + if ($c['p_field'] === $s) { switch ($c['contype']) { case 'p': - $str .= '<a href="constraints?'.$misc->href.'&table='.urlencode($c['p_table']).'&schema='.urlencode($c['p_schema']).'"><img src="'. - $misc->icon('PrimaryKey').'" alt="[pk]" title="'.htmlentities($c['consrc'], ENT_QUOTES, 'UTF-8').'" /></a>'; + $str .= '<a href="constraints?' . $misc->href . '&table=' . \urlencode($c['p_table']) . '&schema=' . \urlencode($c['p_schema']) . '"><img src="' . + $misc->icon('PrimaryKey') . '" alt="[pk]" title="' . \htmlentities($c['consrc'], \ENT_QUOTES, 'UTF-8') . '" /></a>'; break; case 'f': - $str .= '<a href="tblproperties?'.$misc->href.'&table='.urlencode($c['f_table']).'&schema='.urlencode($c['f_schema']).'"><img src="'. - $misc->icon('ForeignKey').'" alt="[fk]" title="'.htmlentities($c['consrc'], ENT_QUOTES, 'UTF-8').'" /></a>'; + $str .= '<a href="tblproperties?' . $misc->href . '&table=' . \urlencode($c['f_table']) . '&schema=' . \urlencode($c['f_schema']) . '"><img src="' . + $misc->icon('ForeignKey') . '" alt="[fk]" title="' . \htmlentities($c['consrc'], \ENT_QUOTES, 'UTF-8') . '" /></a>'; break; case 'u': - $str .= '<a href="constraints?'.$misc->href.'&table='.urlencode($c['p_table']).'&schema='.urlencode($c['p_schema']).'"><img src="'. - $misc->icon('UniqueConstraint').'" alt="[uniq]" title="'.htmlentities($c['consrc'], ENT_QUOTES, 'UTF-8').'" /></a>'; + $str .= '<a href="constraints?' . $misc->href . '&table=' . \urlencode($c['p_table']) . '&schema=' . \urlencode($c['p_schema']) . '"><img src="' . + $misc->icon('UniqueConstraint') . '" alt="[uniq]" title="' . \htmlentities($c['consrc'], \ENT_QUOTES, 'UTF-8') . '" /></a>'; break; case 'c': - $str .= '<a href="constraints?'.$misc->href.'&table='.urlencode($c['p_table']).'&schema='.urlencode($c['p_schema']).'"><img src="'. - $misc->icon('CheckConstraint').'" alt="[check]" title="'.htmlentities($c['consrc'], ENT_QUOTES, 'UTF-8').'" /></a>'; + $str .= '<a href="constraints?' . $misc->href . '&table=' . \urlencode($c['p_table']) . '&schema=' . \urlencode($c['p_schema']) . '"><img src="' . + $misc->icon('CheckConstraint') . '" alt="[check]" title="' . \htmlentities($c['consrc'], \ENT_QUOTES, 'UTF-8') . '" /></a>'; } } } @@ -717,7 +731,7 @@ class TblpropertiesController extends BaseController return $cstrRender; } - private function _printTable($ck, $attrs) + private function _printTable($ck, $attrs): void { $misc = $this->misc; @@ -731,7 +745,7 @@ class TblpropertiesController extends BaseController 'column' => [ 'title' => $this->lang['strcolumn'], 'field' => Decorator::field('attname'), - 'url' => "colproperties?subject=column&{$misc->href}&table=".urlencode($_REQUEST['table']).'&', + 'url' => "colproperties?subject=column&{$misc->href}&table=" . \urlencode($_REQUEST['table']) . '&', 'vars' => ['column' => 'attname'], ], 'type' => [ diff --git a/src/xhtml/TreeController.php b/src/controllers/TreeController.php index 4347b005..410f8c0f 100644 --- a/src/xhtml/TreeController.php +++ b/src/controllers/TreeController.php @@ -1,28 +1,61 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ -namespace PHPPgAdmin\XHtml; +namespace PHPPgAdmin\Controller; use PHPPgAdmin\Decorators\Decorator; /** * Base TreeController controller class. */ -class TreeController +class TreeController extends BaseController { use \PHPPgAdmin\Traits\HelperTrait; + /** + * @var string + */ + const BASE_PATH = BASE_PATH; + /** + * @var string + */ + const SUBFOLDER = SUBFOLDER; + /** + * @var string + */ + const DEBUGMODE = DEBUGMODE; + + public $form = ''; + + public $href = ''; + + public $lang = []; + + public $action = ''; + + public $controller_name = 'TreeController'; - protected $container; - public $form = ''; - public $href = ''; - public $lang = []; - public $action = ''; - public $controller_name = 'TreeController'; public $controller_title = 'base'; + public $misc; + + public $conf; + + public $appThemes; + + public $view; + + public $appVersion; + + public $appLangFiles; + + protected $container; + // Constructor public function __construct(\Slim\Container $container, $controller_name = null) { @@ -38,6 +71,7 @@ class TreeController $this->conf = $this->misc->getConf(); $this->appThemes = $container->get('appThemes'); $this->action = $container->get('action'); + if (null !== $controller_name) { $this->controller_name = $controller_name; } @@ -66,7 +100,7 @@ class TreeController { $treedata = []; - if ($_treedata->recordCount() > 0) { + if (0 < $_treedata->recordCount()) { while (!$_treedata->EOF) { $treedata[] = $_treedata->fields; $_treedata->moveNext(); @@ -83,6 +117,24 @@ class TreeController } /** + * Hides or show tree tabs according to their properties. + * + * @param array $tabs The tabs + * + * @return \PHPPgAdmin\ArrayRecordSet filtered tabs in the form of an ArrayRecordSet + */ + public function adjustTabsForTree(&$tabs) + { + foreach ($tabs as $i => $tab) { + if ((isset($tab['hide']) && true === $tab['hide']) || (isset($tab['tree']) && false === $tab['tree'])) { + unset($tabs[$i]); + } + } + + return new \PHPPgAdmin\ArrayRecordSet($tabs); + } + + /** * Produce JSON data for the browser tree. * * @param array $treedata a set of records to populate the tree @@ -108,22 +160,23 @@ class TreeController $parent = [ 'id' => 'root', 'children' => true, - 'icon' => \SUBFOLDER.'/assets/images/themes/default/Servers.png', + 'icon' => \SUBFOLDER . '/assets/images/themes/default/Servers.png', 'state' => ['opened' => true], - 'a_attr' => ['href' => str_replace('//', '/', \SUBFOLDER.'/src/views/servers')], - 'url' => str_replace('//', '/', \SUBFOLDER.'/src/views/servers?action=tree'), + 'a_attr' => ['href' => \str_replace('//', '/', \SUBFOLDER . '/src/views/servers')], + 'url' => \str_replace('//', '/', \SUBFOLDER . '/src/views/servers?action=tree'), 'text' => 'Servers', ]; - } elseif (count($treedata) > 0) { + } elseif (0 < \count($treedata)) { foreach ($treedata as $rec) { $icon = $this->misc->icon(Decorator::get_sanitized_value($attrs['icon'], $rec)); + if (!empty($attrs['openicon'])) { $icon = $this->misc->icon(Decorator::get_sanitized_value($attrs['openIcon'], $rec)); } $tree = [ 'text' => Decorator::get_sanitized_value($attrs['text'], $rec), - 'id' => sha1(Decorator::get_sanitized_value($attrs['action'], $rec)), + 'id' => \sha1(Decorator::get_sanitized_value($attrs['action'], $rec)), 'icon' => Decorator::get_sanitized_value($icon, $rec), 'iconaction' => Decorator::get_sanitized_value($attrs['iconAction'], $rec), 'openicon' => Decorator::get_sanitized_value($icon, $rec), @@ -132,9 +185,11 @@ class TreeController 'children' => false, ]; $url = Decorator::get_sanitized_value($attrs['branch'], $rec); - if ($url && strpos($url, '/src/views') === false) { - $url = str_replace('//', '/', \SUBFOLDER.'/src/views/'.$url); + + if ($url && false === \mb_strpos($url, '/src/views')) { + $url = \str_replace('//', '/', \SUBFOLDER . '/src/views/' . $url); } + if ($url) { $tree['url'] = $url; $tree['children'] = true; @@ -163,22 +218,4 @@ class TreeController return $parent; } - - /** - * Hides or show tree tabs according to their properties. - * - * @param array $tabs The tabs - * - * @return \PHPPgAdmin\ArrayRecordSet filtered tabs in the form of an ArrayRecordSet - */ - public function adjustTabsForTree(&$tabs) - { - foreach ($tabs as $i => $tab) { - if ((isset($tab['hide']) && true === $tab['hide']) || (isset($tab['tree']) && false === $tab['tree'])) { - unset($tabs[$i]); - } - } - - return new \PHPPgAdmin\ArrayRecordSet($tabs); - } } diff --git a/src/controllers/TriggersController.php b/src/controllers/TriggersController.php index 6d4d4a97..370dbc73 100644 --- a/src/controllers/TriggersController.php +++ b/src/controllers/TriggersController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class TriggersController extends BaseController { @@ -22,11 +23,11 @@ class TriggersController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } - $this->printHeader($this->headerTitle('', '', $_REQUEST['table'].' - '.$this->lang['strtriggers'])); + $this->printHeader($this->headerTitle('', '', $_REQUEST['table'] . ' - ' . $this->lang['strtriggers'])); $this->printBody(); switch ($this->action) { @@ -104,11 +105,11 @@ class TriggersController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); - $tgPre = function (&$rowdata, $actions) use ($data) { + $tgPre = static function (&$rowdata, $actions) use ($data) { // toggle enable/disable trigger per trigger if (!$data->phpBool($rowdata->fields['tgenabled'])) { unset($actions['disable']); @@ -177,6 +178,7 @@ class TriggersController extends BaseController ], ], ]; + if ($data->hasDisableTriggers()) { $actions['enable'] = [ 'content' => $this->lang['strenable'], @@ -222,7 +224,7 @@ class TriggersController extends BaseController ], ], 'content' => $this->lang['strcreatetrigger'], - ]], 'triggers-triggers', get_defined_vars()); + ]], 'triggers-triggers', \get_defined_vars()); } public function doTree() @@ -242,12 +244,13 @@ class TriggersController extends BaseController /** * Function to save after altering a trigger. */ - public function doSaveAlter() + public function doSaveAlter(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->alterTrigger($_POST['table'], $_POST['trigger'], $_POST['name']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtriggeraltered']); } else { $this->doAlter($this->lang['strtriggeralteredbad']); @@ -259,7 +262,7 @@ class TriggersController extends BaseController * * @param mixed $msg */ - public function doAlter($msg = '') + public function doAlter($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -269,25 +272,25 @@ class TriggersController extends BaseController $triggerdata = $data->getTrigger($_REQUEST['table'], $_REQUEST['trigger']); - if ($triggerdata->recordCount() > 0) { + if (0 < $triggerdata->recordCount()) { $this->coalesceArr($_POST, 'name', $triggerdata->fields['tgname']); - echo '<form action="'.\SUBFOLDER.'/src/views/triggers" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/triggers" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data\">{$this->lang['strname']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo "<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" />'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="alter" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo '<input type="hidden" name="trigger" value="', htmlspecialchars($_REQUEST['trigger']), '" />'.PHP_EOL; + \htmlspecialchars($_POST['name']), '" />' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="alter" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="trigger" value="', \htmlspecialchars($_REQUEST['trigger']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['strok']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['strok']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } @@ -296,7 +299,7 @@ class TriggersController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -304,24 +307,25 @@ class TriggersController extends BaseController $this->printTrail('trigger'); $this->printTitle($this->lang['strdrop'], 'pg.trigger.drop'); - echo '<p>', sprintf( + echo '<p>', \sprintf( $this->lang['strconfdroptrigger'], $this->misc->printVal($_REQUEST['trigger']), $this->misc->printVal($_REQUEST['table']) - ), '</p>'.PHP_EOL; + ), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/triggers" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo '<input type="hidden" name="trigger" value="', htmlspecialchars($_REQUEST['trigger']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/triggers" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="trigger" value="', \htmlspecialchars($_REQUEST['trigger']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropTrigger($_POST['trigger'], $_POST['table'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtriggerdropped']); } else { $this->doDefault($this->lang['strtriggerdroppedbad']); @@ -334,7 +338,7 @@ class TriggersController extends BaseController * * @param mixed $confirm */ - public function doEnable($confirm) + public function doEnable($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -342,23 +346,24 @@ class TriggersController extends BaseController $this->printTrail('trigger'); $this->printTitle($this->lang['strenable'], 'pg.table.alter'); - echo '<p>', sprintf( + echo '<p>', \sprintf( $this->lang['strconfenabletrigger'], $this->misc->printVal($_REQUEST['trigger']), $this->misc->printVal($_REQUEST['table']) - ), '</p>'.PHP_EOL; + ), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/triggers" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="enable" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo '<input type="hidden" name="trigger" value="', htmlspecialchars($_REQUEST['trigger']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/triggers" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="enable" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="trigger" value="', \htmlspecialchars($_REQUEST['trigger']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->enableTrigger($_POST['trigger'], $_POST['table']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtriggerenabled']); } else { $this->doDefault($this->lang['strtriggerenabledbad']); @@ -371,7 +376,7 @@ class TriggersController extends BaseController * * @param mixed $confirm */ - public function doDisable($confirm) + public function doDisable($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -379,23 +384,24 @@ class TriggersController extends BaseController $this->printTrail('trigger'); $this->printTitle($this->lang['strdisable'], 'pg.table.alter'); - echo '<p>', sprintf( + echo '<p>', \sprintf( $this->lang['strconfdisabletrigger'], $this->misc->printVal($_REQUEST['trigger']), $this->misc->printVal($_REQUEST['table']) - ), '</p>'.PHP_EOL; + ), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/triggers" method="post">'.PHP_EOL; - echo '<input type="hidden" name="action" value="disable" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo '<input type="hidden" name="trigger" value="', htmlspecialchars($_REQUEST['trigger']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/triggers" method="post">' . \PHP_EOL; + echo '<input type="hidden" name="action" value="disable" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="trigger" value="', \htmlspecialchars($_REQUEST['trigger']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->disableTrigger($_POST['trigger'], $_POST['table']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtriggerdisabled']); } else { $this->doDefault($this->lang['strtriggerdisabledbad']); @@ -408,7 +414,7 @@ class TriggersController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -418,7 +424,8 @@ class TriggersController extends BaseController // Get all the functions that can be used in triggers $funcs = $data->getTriggerFunctions(); - if (0 == $funcs->recordCount()) { + + if (0 === $funcs->recordCount()) { $this->doDefault($this->lang['strnofunctions']); return; @@ -426,6 +433,7 @@ class TriggersController extends BaseController // Populate functions $sel0 = new \PHPPgAdmin\XHtml\XHtmlSelect('formFunction'); + while (!$funcs->EOF) { $sel0->add(new \PHPPgAdmin\XHtml\XHtmlOption($funcs->fields['proname'])); $funcs->moveNext(); @@ -443,51 +451,51 @@ class TriggersController extends BaseController $sel3 = new \PHPPgAdmin\XHtml\XHtmlSelect('formFrequency'); $sel3->set_data($data->triggerFrequency); - echo '<form action="'.\SUBFOLDER.'/src/views/triggers" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo '<tr>'.PHP_EOL; - echo " <th class=\"data\">{$this->lang['strname']}</th>".PHP_EOL; - echo " <th class=\"data\">{$this->lang['strwhen']}</th>".PHP_EOL; - echo '</tr>'.PHP_EOL; - echo '<tr>'.PHP_EOL; - echo ' <td class="data1"> <input type="text" name="formTriggerName" size="32" /></td>'.PHP_EOL; - echo ' <td class="data1"> ', $sel1->fetch(), '</td>'.PHP_EOL; - echo '</tr>'.PHP_EOL; - echo '<tr>'.PHP_EOL; - echo " <th class=\"data\">{$this->lang['strevent']}</th>".PHP_EOL; - echo " <th class=\"data\">{$this->lang['strforeach']}</th>".PHP_EOL; - echo '</tr>'.PHP_EOL; - echo '<tr>'.PHP_EOL; - echo ' <td class="data1"> ', $sel2->fetch(), '</td>'.PHP_EOL; - echo ' <td class="data1"> ', $sel3->fetch(), '</td>'.PHP_EOL; - echo '</tr>'.PHP_EOL; - echo "<tr><th class=\"data\"> {$this->lang['strfunction']}</th>".PHP_EOL; - echo "<th class=\"data\"> {$this->lang['strarguments']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1">', $sel0->fetch(), '</td>'.PHP_EOL; - echo '<td class="data1">(<input type="text" name="formTriggerArgs" size="32" />)</td>'.PHP_EOL; - echo '</tr></table>'.PHP_EOL; - echo "<p><input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '<input type="hidden" name="action" value="save_create" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/triggers" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo '<tr>' . \PHP_EOL; + echo " <th class=\"data\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo " <th class=\"data\">{$this->lang['strwhen']}</th>" . \PHP_EOL; + echo '</tr>' . \PHP_EOL; + echo '<tr>' . \PHP_EOL; + echo ' <td class="data1"> <input type="text" name="formTriggerName" size="32" /></td>' . \PHP_EOL; + echo ' <td class="data1"> ', $sel1->fetch(), '</td>' . \PHP_EOL; + echo '</tr>' . \PHP_EOL; + echo '<tr>' . \PHP_EOL; + echo " <th class=\"data\">{$this->lang['strevent']}</th>" . \PHP_EOL; + echo " <th class=\"data\">{$this->lang['strforeach']}</th>" . \PHP_EOL; + echo '</tr>' . \PHP_EOL; + echo '<tr>' . \PHP_EOL; + echo ' <td class="data1"> ', $sel2->fetch(), '</td>' . \PHP_EOL; + echo ' <td class="data1"> ', $sel3->fetch(), '</td>' . \PHP_EOL; + echo '</tr>' . \PHP_EOL; + echo "<tr><th class=\"data\"> {$this->lang['strfunction']}</th>" . \PHP_EOL; + echo "<th class=\"data\"> {$this->lang['strarguments']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1">', $sel0->fetch(), '</td>' . \PHP_EOL; + echo '<td class="data1">(<input type="text" name="formTriggerArgs" size="32" />)</td>' . \PHP_EOL; + echo '</tr></table>' . \PHP_EOL; + echo "<p><input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '<input type="hidden" name="action" value="save_create" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; echo $this->misc->form; - echo '</form>'.PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new trigger in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); // Check that they've given a name and a definition - if ('' == $_POST['formFunction']) { + if ('' === $_POST['formFunction']) { $this->doCreate($this->lang['strtriggerneedsfunc']); - } elseif ('' == $_POST['formTriggerName']) { + } elseif ('' === $_POST['formTriggerName']) { $this->doCreate($this->lang['strtriggerneedsname']); - } elseif ('' == $_POST['formEvent']) { + } elseif ('' === $_POST['formEvent']) { $this->doCreate(); } else { $status = $data->createTrigger( @@ -499,7 +507,8 @@ class TriggersController extends BaseController $_POST['formFrequency'], $_POST['formTriggerArgs'] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtriggercreated']); } else { $this->doCreate($this->lang['strtriggercreatedbad']); diff --git a/src/controllers/TypesController.php b/src/controllers/TypesController.php index b48ed94a..96ba9b70 100644 --- a/src/controllers/TypesController.php +++ b/src/controllers/TypesController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class TypesController extends BaseController { @@ -22,7 +23,7 @@ class TypesController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } @@ -88,7 +89,7 @@ class TypesController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -203,7 +204,7 @@ class TypesController extends BaseController unset($navlinks['enum']); } - $this->printNavLinks($navlinks, 'types-types', get_defined_vars()); + $this->printNavLinks($navlinks, 'types-types', \get_defined_vars()); } /** @@ -239,7 +240,7 @@ class TypesController extends BaseController * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); // Get type (using base name) @@ -249,12 +250,13 @@ class TypesController extends BaseController $this->printTitle($this->lang['strproperties'], 'pg.type'); $this->printMsg($msg); - $attPre = function (&$rowdata) use ($data) { + $attPre = static function (&$rowdata) use ($data): void { $rowdata->fields['+type'] = $data->formatType($rowdata->fields['type'], $rowdata->fields['atttypmod']); }; - if ($typedata->recordCount() > 0) { + if (0 < $typedata->recordCount()) { $vals = false; + switch ($typedata->fields['typtype']) { case 'c': $attrs = $data->getTableAttributes($_REQUEST['type']); @@ -284,29 +286,31 @@ class TypesController extends BaseController // no break default: $byval = $data->phpBool($typedata->fields['typbyval']); - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strname']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($typedata->fields['typname']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strinputfn']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($typedata->fields['typin']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['stroutputfn']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($typedata->fields['typout']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strlength']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($typedata->fields['typlen']), '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strpassbyval']}</th>".PHP_EOL; - echo '<td class="data1">', ($byval) ? $this->lang['stryes'] : $this->lang['strno'], '</td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['stralignment']}</th>".PHP_EOL; - echo '<td class="data1">', $this->misc->printVal($typedata->fields['typalign']), '</td></tr>'.PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strname']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($typedata->fields['typname']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strinputfn']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($typedata->fields['typin']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['stroutputfn']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($typedata->fields['typout']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strlength']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($typedata->fields['typlen']), '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strpassbyval']}</th>" . \PHP_EOL; + echo '<td class="data1">', ($byval) ? $this->lang['stryes'] : $this->lang['strno'], '</td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['stralignment']}</th>" . \PHP_EOL; + echo '<td class="data1">', $this->misc->printVal($typedata->fields['typalign']), '</td></tr>' . \PHP_EOL; + if ($data->hasEnumTypes() && $vals) { $vals = $vals->getArray(); - $nbVals = count($vals); - echo "<tr>\n\t<th class=\"data left\" rowspan=\"${nbVals}\">{$this->lang['strenumvalues']}</th>".PHP_EOL; - echo "<td class=\"data2\">{$vals[0]['enumval']}</td></tr>".PHP_EOL; + $nbVals = \count($vals); + echo "<tr>\n\t<th class=\"data left\" rowspan=\"{$nbVals}\">{$this->lang['strenumvalues']}</th>" . \PHP_EOL; + echo "<td class=\"data2\">{$vals[0]['enumval']}</td></tr>" . \PHP_EOL; + for ($i = 1; $i < $nbVals; ++$i) { - echo '<td class="data', 2 - ($i % 2), "\">{$vals[$i]['enumval']}</td></tr>".PHP_EOL; + echo '<td class="data', 2 - ($i % 2), "\">{$vals[$i]['enumval']}</td></tr>" . \PHP_EOL; } } - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; } $this->printNavLinks(['showall' => [ @@ -321,7 +325,7 @@ class TypesController extends BaseController ], ], 'content' => $this->lang['strshowalltypes'], - ]], 'types-properties', get_defined_vars()); + ]], 'types-properties', \get_defined_vars()); } else { $this->doDefault($this->lang['strinvalidparam']); } @@ -332,7 +336,7 @@ class TypesController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -340,19 +344,20 @@ class TypesController extends BaseController $this->printTrail('type'); $this->printTitle($this->lang['strdrop'], 'pg.type.drop'); - echo '<p>', sprintf($this->lang['strconfdroptype'], $this->misc->printVal($_REQUEST['type'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdroptype'], $this->misc->printVal($_REQUEST['type'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/types" method="post">'.PHP_EOL; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo '<p><input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="type" value="', htmlspecialchars($_REQUEST['type']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/types" method="post">' . \PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="type" value="', \htmlspecialchars($_REQUEST['type']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropType($_POST['type'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtypedropped']); } else { $this->doDefault($this->lang['strtypedroppedbad']); @@ -365,7 +370,7 @@ class TypesController extends BaseController * * @param mixed $msg */ - public function doCreateComposite($msg = '') + public function doCreateComposite($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -383,38 +388,40 @@ class TypesController extends BaseController $this->printTitle($this->lang['strcreatecomptype'], 'pg.type.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/types" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/types" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strnumfields']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strnumfields']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"fields\" size=\"5\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['fields']), "\" /></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['fields']), "\" /></td>\n\t</tr>" . \PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td><textarea name=\"typcomment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_REQUEST['typcomment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['typcomment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="create_comp" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="2" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="create_comp" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="2" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strnext']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strnext']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; break; case 2: // Check inputs - $fields = trim($_REQUEST['fields']); - if ('' == trim($_REQUEST['name'])) { + $fields = \trim($_REQUEST['fields']); + + if ('' === \trim($_REQUEST['name'])) { $_REQUEST['stage'] = 1; $this->doCreateComposite($this->lang['strtypeneedsname']); return; } - if ('' == $fields || !is_numeric($fields) || $fields != (int) $fields || $fields < 1) { + + if ('' === $fields || !\is_numeric($fields) || (int) $fields !== $fields || 1 > $fields) { $_REQUEST['stage'] = 1; $this->doCreateComposite($this->lang['strtypeneedscols']); @@ -427,12 +434,12 @@ class TypesController extends BaseController $this->printTitle($this->lang['strcreatecomptype'], 'pg.type.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/types" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/types" method="post">' . \PHP_EOL; // Output table header - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "\t<tr><th colspan=\"2\" class=\"data required\">{$this->lang['strfield']}</th><th colspan=\"2\" class=\"data required\">{$this->lang['strtype']}</th>"; - echo "<th class=\"data\">{$this->lang['strlength']}</th><th class=\"data\">{$this->lang['strcomment']}</th></tr>".PHP_EOL; + echo "<th class=\"data\">{$this->lang['strlength']}</th><th class=\"data\">{$this->lang['strcomment']}</th></tr>" . \PHP_EOL; for ($i = 0; $i < $_REQUEST['fields']; ++$i) { if (!isset($_REQUEST['field'][$i])) { @@ -447,53 +454,56 @@ class TypesController extends BaseController $_REQUEST['colcomment'][$i] = ''; } - echo "\t<tr>\n\t\t<td>", $i + 1, '. </td>'.PHP_EOL; + echo "\t<tr>\n\t\t<td>", $i + 1, '. </td>' . \PHP_EOL; echo "\t\t<td><input name=\"field[{$i}]\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['field'][$i]), '" /></td>'.PHP_EOL; - echo "\t\t<td>\n\t\t\t<select name=\"type[{$i}]\">".PHP_EOL; + \htmlspecialchars($_REQUEST['field'][$i]), '" /></td>' . \PHP_EOL; + echo "\t\t<td>\n\t\t\t<select name=\"type[{$i}]\">" . \PHP_EOL; $types->moveFirst(); + while (!$types->EOF) { $typname = $types->fields['typname']; - echo "\t\t\t\t<option value=\"", htmlspecialchars($typname), '"', - (isset($_REQUEST['type'][$i]) && $_REQUEST['type'][$i] == $typname) ? ' selected="selected"' : '', '>', - $this->misc->printVal($typname), '</option>'.PHP_EOL; + echo "\t\t\t\t<option value=\"", \htmlspecialchars($typname), '"', + (isset($_REQUEST['type'][$i]) && $_REQUEST['type'][$i] === $typname) ? ' selected="selected"' : '', '>', + $this->misc->printVal($typname), '</option>' . \PHP_EOL; $types->moveNext(); } - echo "\t\t\t</select>\n\t\t</td>".PHP_EOL; + echo "\t\t\t</select>\n\t\t</td>" . \PHP_EOL; // Output array type selector - echo "\t\t<td>\n\t\t\t<select name=\"array[{$i}]\">".PHP_EOL; - echo "\t\t\t\t<option value=\"\"", (isset($_REQUEST['array'][$i]) && $_REQUEST['array'][$i] == '') ? ' selected="selected"' : '', '></option>'.PHP_EOL; - echo "\t\t\t\t<option value=\"[]\"", (isset($_REQUEST['array'][$i]) && $_REQUEST['array'][$i] == '[]') ? ' selected="selected"' : '', '>[ ]</option>'.PHP_EOL; - echo "\t\t\t</select>\n\t\t</td>".PHP_EOL; + echo "\t\t<td>\n\t\t\t<select name=\"array[{$i}]\">" . \PHP_EOL; + echo "\t\t\t\t<option value=\"\"", (isset($_REQUEST['array'][$i]) && '' === $_REQUEST['array'][$i]) ? ' selected="selected"' : '', '></option>' . \PHP_EOL; + echo "\t\t\t\t<option value=\"[]\"", (isset($_REQUEST['array'][$i]) && '[]' === $_REQUEST['array'][$i]) ? ' selected="selected"' : '', '>[ ]</option>' . \PHP_EOL; + echo "\t\t\t</select>\n\t\t</td>" . \PHP_EOL; echo "\t\t<td><input name=\"length[{$i}]\" size=\"10\" value=\"", - htmlspecialchars($_REQUEST['length'][$i]), '" /></td>'.PHP_EOL; + \htmlspecialchars($_REQUEST['length'][$i]), '" /></td>' . \PHP_EOL; echo "\t\t<td><input name=\"colcomment[{$i}]\" size=\"40\" value=\"", - htmlspecialchars($_REQUEST['colcomment'][$i]), "\" /></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['colcomment'][$i]), "\" /></td>\n\t</tr>" . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="create_comp" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="3" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="create_comp" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="3" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="name" value="', htmlspecialchars($_REQUEST['name']), '" />'.PHP_EOL; - echo '<input type="hidden" name="fields" value="', htmlspecialchars($_REQUEST['fields']), '" />'.PHP_EOL; - echo '<input type="hidden" name="typcomment" value="', htmlspecialchars($_REQUEST['typcomment']), '" />'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="name" value="', \htmlspecialchars($_REQUEST['name']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="fields" value="', \htmlspecialchars($_REQUEST['fields']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="typcomment" value="', \htmlspecialchars($_REQUEST['typcomment']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; break; case 3: // Check inputs - $fields = trim($_REQUEST['fields']); - if ('' == trim($_REQUEST['name'])) { + $fields = \trim($_REQUEST['fields']); + + if ('' === \trim($_REQUEST['name'])) { $_REQUEST['stage'] = 1; $this->doCreateComposite($this->lang['strtypeneedsname']); return; } - if ('' == $fields || !is_numeric($fields) || $fields != (int) $fields || $fields <= 0) { + + if ('' === $fields || !\is_numeric($fields) || (int) $fields !== $fields || 0 >= $fields) { $_REQUEST['stage'] = 1; $this->doCreateComposite($this->lang['strtypeneedscols']); @@ -511,9 +521,9 @@ class TypesController extends BaseController $_REQUEST['typcomment'] ); - if (0 == $status) { + if (0 === $status) { $this->doDefault($this->lang['strtypecreated']); - } elseif ($status == -1) { + } elseif (-1 === $status) { $_REQUEST['stage'] = 2; $this->doCreateComposite($this->lang['strtypeneedsfield']); @@ -527,7 +537,7 @@ class TypesController extends BaseController break; default: - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } } @@ -536,7 +546,7 @@ class TypesController extends BaseController * * @param mixed $msg */ - public function doCreateEnum($msg = '') + public function doCreateEnum($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -554,38 +564,40 @@ class TypesController extends BaseController $this->printTitle($this->lang['strcreateenumtype'], 'pg.type.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/types" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/types" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strnumvalues']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['name']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strnumvalues']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data\"><input name=\"values\" size=\"5\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['values']), "\" /></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['values']), "\" /></td>\n\t</tr>" . \PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td><textarea name=\"typcomment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_REQUEST['typcomment']), "</textarea></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['typcomment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="create_enum" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="2" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="create_enum" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="2" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strnext']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strnext']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; break; case 2: // Check inputs - $values = trim($_REQUEST['values']); - if ('' == trim($_REQUEST['name'])) { + $values = \trim($_REQUEST['values']); + + if ('' === \trim($_REQUEST['name'])) { $_REQUEST['stage'] = 1; $this->doCreateEnum($this->lang['strtypeneedsname']); return; } - if ('' == $values || !is_numeric($values) || $values != (int) $values || $values < 1) { + + if ('' === $values || !\is_numeric($values) || (int) $values !== $values || 1 > $values) { $_REQUEST['stage'] = 1; $this->doCreateEnum($this->lang['strtypeneedsvals']); @@ -596,43 +608,45 @@ class TypesController extends BaseController $this->printTitle($this->lang['strcreateenumtype'], 'pg.type.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/types" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/types" method="post">' . \PHP_EOL; // Output table header - echo '<table>'.PHP_EOL; - echo "\t<tr><th colspan=\"2\" class=\"data required\">{$this->lang['strvalue']}</th></tr>".PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr><th colspan=\"2\" class=\"data required\">{$this->lang['strvalue']}</th></tr>" . \PHP_EOL; for ($i = 0; $i < $_REQUEST['values']; ++$i) { if (!isset($_REQUEST['value'][$i])) { $_REQUEST['value'][$i] = ''; } - echo "\t<tr>\n\t\t<td>", $i + 1, '. </td>'.PHP_EOL; + echo "\t<tr>\n\t\t<td>", $i + 1, '. </td>' . \PHP_EOL; echo "\t\t<td><input name=\"value[{$i}]\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['value'][$i]), "\" /></td>\n\t</tr>".PHP_EOL; + \htmlspecialchars($_REQUEST['value'][$i]), "\" /></td>\n\t</tr>" . \PHP_EOL; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="create_enum" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="3" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="create_enum" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="3" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="name" value="', htmlspecialchars($_REQUEST['name']), '" />'.PHP_EOL; - echo '<input type="hidden" name="values" value="', htmlspecialchars($_REQUEST['values']), '" />'.PHP_EOL; - echo '<input type="hidden" name="typcomment" value="', htmlspecialchars($_REQUEST['typcomment']), '" />'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="name" value="', \htmlspecialchars($_REQUEST['name']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="values" value="', \htmlspecialchars($_REQUEST['values']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="typcomment" value="', \htmlspecialchars($_REQUEST['typcomment']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; break; case 3: // Check inputs - $values = trim($_REQUEST['values']); - if ('' == trim($_REQUEST['name'])) { + $values = \trim($_REQUEST['values']); + + if ('' === \trim($_REQUEST['name'])) { $_REQUEST['stage'] = 1; $this->doCreateEnum($this->lang['strtypeneedsname']); return; } - if ('' == $values || !is_numeric($values) || $values != (int) $values || $values <= 0) { + + if ('' === $values || !\is_numeric($values) || (int) $values !== $values || 0 >= $values) { $_REQUEST['stage'] = 1; $this->doCreateEnum($this->lang['strtypeneedsvals']); @@ -641,9 +655,9 @@ class TypesController extends BaseController $status = $data->createEnumType($_REQUEST['name'], $_REQUEST['value'], $_REQUEST['typcomment']); - if (0 == $status) { + if (0 === $status) { $this->doDefault($this->lang['strtypecreated']); - } elseif ($status == -1) { + } elseif (-1 === $status) { $_REQUEST['stage'] = 2; $this->doCreateEnum($this->lang['strtypeneedsvalue']); @@ -657,7 +671,7 @@ class TypesController extends BaseController break; default: - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } } @@ -666,7 +680,7 @@ class TypesController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -696,87 +710,92 @@ class TypesController extends BaseController $this->printTitle($this->lang['strcreatetype'], 'pg.type.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/types" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/types" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "<td class=\"data1\"><input name=\"typname\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['typname']), '" /></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strinputfn']}</th>".PHP_EOL; + \htmlspecialchars($_POST['typname']), '" /></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strinputfn']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="typin">'; + while (!$funcs->EOF) { - $proname = htmlspecialchars($funcs->fields['proname']); + $proname = \htmlspecialchars($funcs->fields['proname']); echo "<option value=\"{$proname}\"", - ($proname == $_POST['typin']) ? ' selected="selected"' : '', ">{$proname}</option>".PHP_EOL; + ($proname === $_POST['typin']) ? ' selected="selected"' : '', ">{$proname}</option>" . \PHP_EOL; $funcs->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['stroutputfn']}</th>".PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['stroutputfn']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="typout">'; $funcs->moveFirst(); + while (!$funcs->EOF) { - $proname = htmlspecialchars($funcs->fields['proname']); + $proname = \htmlspecialchars($funcs->fields['proname']); echo "<option value=\"{$proname}\"", - ($proname == $_POST['typout']) ? ' selected="selected"' : '', ">{$proname}</option>".PHP_EOL; + ($proname === $_POST['typout']) ? ' selected="selected"' : '', ">{$proname}</option>" . \PHP_EOL; $funcs->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; - echo '<tr><th class="data left'.(version_compare($data->major_version, '7.4', '<') ? ' required' : '')."\">{$this->lang['strlength']}</th>".PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + echo '<tr><th class="data left' . (\version_compare($data->major_version, '7.4', '<') ? ' required' : '') . "\">{$this->lang['strlength']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="typlen" size="8" value="', - htmlspecialchars($_POST['typlen']), '" /></td></tr>'; - echo "<tr><th class=\"data left\">{$this->lang['strdefault']}</th>".PHP_EOL; + \htmlspecialchars($_POST['typlen']), '" /></td></tr>'; + echo "<tr><th class=\"data left\">{$this->lang['strdefault']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="typdef" size="8" value="', - htmlspecialchars($_POST['typdef']), '" /></td></tr>'; - echo "<tr><th class=\"data left\">{$this->lang['strelement']}</th>".PHP_EOL; + \htmlspecialchars($_POST['typdef']), '" /></td></tr>'; + echo "<tr><th class=\"data left\">{$this->lang['strelement']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="typelem">'; - echo '<option value=""></option>'.PHP_EOL; + echo '<option value=""></option>' . \PHP_EOL; + while (!$types->EOF) { - $currname = htmlspecialchars($types->fields['typname']); + $currname = \htmlspecialchars($types->fields['typname']); echo "<option value=\"{$currname}\"", - ($currname == $_POST['typelem']) ? ' selected="selected"' : '', ">{$currname}</option>".PHP_EOL; + ($currname === $_POST['typelem']) ? ' selected="selected"' : '', ">{$currname}</option>" . \PHP_EOL; $types->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strdelimiter']}</th>".PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strdelimiter']}</th>" . \PHP_EOL; echo '<td class="data1"><input name="typdelim" size="1" maxlength="1" value="', - htmlspecialchars($_POST['typdelim']), '" /></td></tr>'; - echo "<tr><th class=\"data left\"><label for=\"typbyval\">{$this->lang['strpassbyval']}</label></th>".PHP_EOL; + \htmlspecialchars($_POST['typdelim']), '" /></td></tr>'; + echo "<tr><th class=\"data left\"><label for=\"typbyval\">{$this->lang['strpassbyval']}</label></th>" . \PHP_EOL; echo '<td class="data1"><input type="checkbox" id="typbyval" name="typbyval"', isset($_POST['typbyval']) ? ' checked="checked"' : '', ' /></td></tr>'; - echo "<tr><th class=\"data left\">{$this->lang['stralignment']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['stralignment']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="typalign">'; + foreach ($data->typAligns as $v) { echo "<option value=\"{$v}\"", - ($v == $_POST['typalign']) ? ' selected="selected"' : '', ">{$v}</option>".PHP_EOL; + ($v === $_POST['typalign']) ? ' selected="selected"' : '', ">{$v}</option>" . \PHP_EOL; } - echo '</select></td></tr>'.PHP_EOL; - echo "<tr><th class=\"data left\">{$this->lang['strstorage']}</th>".PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strstorage']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="typstorage">'; + foreach ($data->typStorages as $v) { echo "<option value=\"{$v}\"", - ($v == $_POST['typstorage']) ? ' selected="selected"' : '', ">{$v}</option>".PHP_EOL; + ($v === $_POST['typstorage']) ? ' selected="selected"' : '', ">{$v}</option>" . \PHP_EOL; } - echo '</select></td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new type in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); // Check that they've given a name and a length. // Note: We're assuming they've given in and out functions here // which might be unwise... - if ('' == $_POST['typname']) { + if ('' === $_POST['typname']) { $this->doCreate($this->lang['strtypeneedsname']); - } elseif ('' == $_POST['typlen']) { + } elseif ('' === $_POST['typlen']) { $this->doCreate($this->lang['strtypeneedslen']); } else { $status = $data->createType( @@ -791,7 +810,8 @@ class TypesController extends BaseController $_POST['typalign'], $_POST['typstorage'] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strtypecreated']); } else { $this->doCreate($this->lang['strtypecreatedbad']); diff --git a/src/controllers/UsersController.php b/src/controllers/UsersController.php index c082a477..45b422a7 100644 --- a/src/controllers/UsersController.php +++ b/src/controllers/UsersController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,8 +13,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class UsersController extends BaseController { @@ -20,7 +21,7 @@ class UsersController extends BaseController /** * Default method to render the controller according to the action parameter. */ - public function render() + public function render(): void { $this->printHeader(); $this->printBody(); @@ -92,13 +93,13 @@ class UsersController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); $lang = $this->lang; - $renderUseExpires = function ($val) use ($lang) { - return 'infinity' == $val ? $lang['strnever'] : htmlspecialchars($val); + $renderUseExpires = static function ($val) use ($lang) { + return 'infinity' === $val ? $lang['strnever'] : \htmlspecialchars($val); }; $this->printTrail('server'); @@ -181,7 +182,7 @@ class UsersController extends BaseController ], ], 'content' => $this->lang['strcreateuser'], - ]], 'users-users', get_defined_vars()); + ]], 'users-users', \get_defined_vars()); } /** @@ -192,7 +193,7 @@ class UsersController extends BaseController * * @param mixed $msg */ - public function doAccount($msg = '') + public function doAccount($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -205,21 +206,21 @@ class UsersController extends BaseController $this->printTabs('server', 'account'); $this->printMsg($msg); - if ($userdata->recordCount() > 0) { + if (0 < $userdata->recordCount()) { $userdata->fields['usesuper'] = $data->phpBool($userdata->fields['usesuper']); $userdata->fields['usecreatedb'] = $data->phpBool($userdata->fields['usecreatedb']); - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data\">{$this->lang['strusername']}</th><th class=\"data\">{$this->lang['strsuper']}</th><th class=\"data\">{$this->lang['strcreatedb']}</th><th class=\"data\">{$this->lang['strexpires']}</th>"; echo "<th class=\"data\">{$this->lang['strsessiondefaults']}</th>"; - echo '</tr>'.PHP_EOL; - echo "<tr>\n\t<td class=\"data1\">", $this->misc->printVal($userdata->fields['usename']), '</td>'.PHP_EOL; - echo "\t<td class=\"data1\">", $this->misc->printVal($userdata->fields['usesuper'], 'yesno'), '</td>'.PHP_EOL; - echo "\t<td class=\"data1\">", $this->misc->printVal($userdata->fields['usecreatedb'], 'yesno'), '</td>'.PHP_EOL; - echo "\t<td class=\"data1\">", ('infinity' == $userdata->fields['useexpires'] || is_null($userdata->fields['useexpires']) ? $this->lang['strnever'] : $this->misc->printVal($userdata->fields['useexpires'])), '</td>'.PHP_EOL; - echo "\t<td class=\"data1\">", $this->misc->printVal($userdata->fields['useconfig']), '</td>'.PHP_EOL; - echo "</tr>\n</table>".PHP_EOL; + echo '</tr>' . \PHP_EOL; + echo "<tr>\n\t<td class=\"data1\">", $this->misc->printVal($userdata->fields['usename']), '</td>' . \PHP_EOL; + echo "\t<td class=\"data1\">", $this->misc->printVal($userdata->fields['usesuper'], 'yesno'), '</td>' . \PHP_EOL; + echo "\t<td class=\"data1\">", $this->misc->printVal($userdata->fields['usecreatedb'], 'yesno'), '</td>' . \PHP_EOL; + echo "\t<td class=\"data1\">", ('infinity' === $userdata->fields['useexpires'] || null === $userdata->fields['useexpires'] ? $this->lang['strnever'] : $this->misc->printVal($userdata->fields['useexpires'])), '</td>' . \PHP_EOL; + echo "\t<td class=\"data1\">", $this->misc->printVal($userdata->fields['useconfig']), '</td>' . \PHP_EOL; + echo "</tr>\n</table>" . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } $this->printNavLinks(['changepassword' => [ @@ -233,7 +234,7 @@ class UsersController extends BaseController ], ], 'content' => $this->lang['strchangepassword'], - ]], 'users-account', get_defined_vars()); + ]], 'users-account', \get_defined_vars()); } /** @@ -242,7 +243,7 @@ class UsersController extends BaseController * @param mixed $confirm * @param mixed $msg */ - public function doChangePassword($confirm, $msg = '') + public function doChangePassword($confirm, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -258,24 +259,24 @@ class UsersController extends BaseController $this->coalesceArr($_POST, 'confirm', ''); - echo '<form action="'.\SUBFOLDER.'/src/views/users" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strpassword']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/users" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strpassword']}</th>" . \PHP_EOL; echo "\t\t<td><input type=\"password\" name=\"password\" size=\"32\" value=\"", - htmlspecialchars($_POST['password']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strconfirm']}</th>".PHP_EOL; - echo "\t\t<td><input type=\"password\" name=\"confirm\" size=\"32\" value=\"\" /></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="changepassword" />'.PHP_EOL; + \htmlspecialchars($_POST['password']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strconfirm']}</th>" . \PHP_EOL; + echo "\t\t<td><input type=\"password\" name=\"confirm\" size=\"32\" value=\"\" /></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="changepassword" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"ok\" value=\"{$this->lang['strok']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</p></form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"ok\" value=\"{$this->lang['strok']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</p></form>' . \PHP_EOL; } else { // Check that password is minimum length - if (strlen($_POST['password']) < $this->conf['min_password_length']) { + if (\mb_strlen($_POST['password']) < $this->conf['min_password_length']) { $this->doChangePassword(true, $this->lang['strpasswordshort']); - } elseif ($_POST['password'] != $_POST['confirm']) { + } elseif ($_POST['password'] !== $_POST['confirm']) { // Check that password matches confirmation password $this->doChangePassword(true, $this->lang['strpasswordconfirm']); } else { @@ -283,7 +284,8 @@ class UsersController extends BaseController $server_info['username'], $_POST['password'] ); - if (0 == $status) { + + if (0 === $status) { $this->doAccount($this->lang['strpasswordchanged']); } else { $this->doAccount($this->lang['strpasswordchangedbad']); @@ -297,7 +299,7 @@ class UsersController extends BaseController * * @param mixed $msg */ - public function doEdit($msg = '') + public function doEdit($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -307,9 +309,9 @@ class UsersController extends BaseController $userdata = $data->getUser($_REQUEST['username']); - if ($userdata->recordCount() > 0) { + if (0 < $userdata->recordCount()) { $server_info = $this->misc->getServerInfo(); - $canRename = $data->hasUserRename() && ($_REQUEST['username'] != $server_info['username']); + $canRename = $data->hasUserRename() && ($_REQUEST['username'] !== $server_info['username']); $userdata->fields['usesuper'] = $data->phpBool($userdata->fields['usesuper']); $userdata->fields['usecreatedb'] = $data->phpBool($userdata->fields['usecreatedb']); @@ -326,49 +328,49 @@ class UsersController extends BaseController $_POST['formCreateDB'] = ''; } - $_POST['formExpires'] = 'infinity' == $userdata->fields['useexpires'] ? '' : $userdata->fields['useexpires']; + $_POST['formExpires'] = 'infinity' === $userdata->fields['useexpires'] ? '' : $userdata->fields['useexpires']; $_POST['formPassword'] = ''; } - echo '<form action="'.\SUBFOLDER.'/src/views/users" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strusername']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\">", ($canRename ? "<input name=\"newname\" size=\"15\" maxlength=\"{$data->_maxNameLen}\" value=\"".htmlspecialchars($_POST['newname']).'" />' : $this->misc->printVal($userdata->fields['usename'])), "</td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formSuper\">{$this->lang['strsuper']}</label></th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/users" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strusername']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\">", ($canRename ? "<input name=\"newname\" size=\"15\" maxlength=\"{$data->_maxNameLen}\" value=\"" . \htmlspecialchars($_POST['newname']) . '" />' : $this->misc->printVal($userdata->fields['usename'])), "</td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formSuper\">{$this->lang['strsuper']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formSuper\" name=\"formSuper\"", - (isset($_POST['formSuper'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateDB\">{$this->lang['strcreatedb']}</label></th>".PHP_EOL; + (isset($_POST['formSuper'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateDB\">{$this->lang['strcreatedb']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formCreateDB\" name=\"formCreateDB\"", - (isset($_POST['formCreateDB'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strexpires']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"16\" name=\"formExpires\" value=\"", htmlspecialchars($_POST['formExpires']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strpassword']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input type=\"password\" size=\"16\" name=\"formPassword\" value=\"", htmlspecialchars($_POST['formPassword']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconfirm']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input type=\"password\" size=\"16\" name=\"formConfirm\" value=\"\" /></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_edit" />'.PHP_EOL; - echo '<input type="hidden" name="username" value="', htmlspecialchars($_REQUEST['username']), '" />'.PHP_EOL; + (isset($_POST['formCreateDB'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strexpires']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"16\" name=\"formExpires\" value=\"", \htmlspecialchars($_POST['formExpires']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strpassword']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input type=\"password\" size=\"16\" name=\"formPassword\" value=\"", \htmlspecialchars($_POST['formPassword']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconfirm']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input type=\"password\" size=\"16\" name=\"formConfirm\" value=\"\" /></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_edit" />' . \PHP_EOL; + echo '<input type="hidden" name="username" value="', \htmlspecialchars($_REQUEST['username']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } /** * Function to save after editing a user. */ - public function doSaveEdit() + public function doSaveEdit(): void { $data = $this->misc->getDatabaseAccessor(); // Check name and password - if (isset($_POST['newname']) && '' == $_POST['newname']) { + if (isset($_POST['newname']) && '' === $_POST['newname']) { $this->doEdit($this->lang['struserneedsname']); - } elseif ($_POST['formPassword'] != $_POST['formConfirm']) { + } elseif ($_POST['formPassword'] !== $_POST['formConfirm']) { $this->doEdit($this->lang['strpasswordconfirm']); } else { if (isset($_POST['newname'])) { @@ -377,7 +379,7 @@ class UsersController extends BaseController $status = $data->setUser($_POST['username'], $_POST['formPassword'], isset($_POST['formCreateDB']), isset($_POST['formSuper']), $_POST['formExpires']); } - if (0 == $status) { + if (0 === $status) { $this->doDefault($this->lang['struserupdated']); } else { $this->doEdit($this->lang['struserupdatedbad']); @@ -390,7 +392,7 @@ class UsersController extends BaseController * * @param mixed $confirm */ - public function doDrop($confirm) + public function doDrop($confirm): void { $data = $this->misc->getDatabaseAccessor(); @@ -398,18 +400,19 @@ class UsersController extends BaseController $this->printTrail('user'); $this->printTitle($this->lang['strdrop'], 'pg.user.drop'); - echo '<p>', sprintf($this->lang['strconfdropuser'], $this->misc->printVal($_REQUEST['username'])), '</p>'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropuser'], $this->misc->printVal($_REQUEST['username'])), '</p>' . \PHP_EOL; - echo '<form action="'.\SUBFOLDER.'/src/views/users" method="post">'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="drop" />'.PHP_EOL; - echo '<input type="hidden" name="username" value="', htmlspecialchars($_REQUEST['username']), '" />'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/users" method="post">' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="drop" />' . \PHP_EOL; + echo '<input type="hidden" name="username" value="', \htmlspecialchars($_REQUEST['username']), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { $status = $data->dropUser($_REQUEST['username']); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['struserdropped']); } else { $this->doDefault($this->lang['struserdroppedbad']); @@ -422,7 +425,7 @@ class UsersController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -438,41 +441,41 @@ class UsersController extends BaseController $this->printTitle($this->lang['strcreateuser'], 'pg.user.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/users" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strusername']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"15\" maxlength=\"{$data->_maxNameLen}\" name=\"formUsername\" value=\"", htmlspecialchars($_POST['formUsername']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strpassword']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"15\" type=\"password\" name=\"formPassword\" value=\"", htmlspecialchars($_POST['formPassword']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconfirm']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"15\" type=\"password\" name=\"formConfirm\" value=\"", htmlspecialchars($_POST['formConfirm']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formSuper\">{$this->lang['strsuper']}</label></th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/users" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strusername']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"15\" maxlength=\"{$data->_maxNameLen}\" name=\"formUsername\" value=\"", \htmlspecialchars($_POST['formUsername']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strpassword']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"15\" type=\"password\" name=\"formPassword\" value=\"", \htmlspecialchars($_POST['formPassword']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strconfirm']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"15\" type=\"password\" name=\"formConfirm\" value=\"", \htmlspecialchars($_POST['formConfirm']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formSuper\">{$this->lang['strsuper']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formSuper\" name=\"formSuper\"", - (isset($_POST['formSuper'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateDB\">{$this->lang['strcreatedb']}</label></th>".PHP_EOL; + (isset($_POST['formSuper'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\"><label for=\"formCreateDB\">{$this->lang['strcreatedb']}</label></th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><input type=\"checkbox\" id=\"formCreateDB\" name=\"formCreateDB\"", - (isset($_POST['formCreateDB'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strexpires']}</th>".PHP_EOL; - echo "\t\t<td class=\"data1\"><input size=\"30\" name=\"formExpires\" value=\"", htmlspecialchars($_POST['formExpires']), "\" /></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + (isset($_POST['formCreateDB'])) ? ' checked="checked"' : '', " /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strexpires']}</th>" . \PHP_EOL; + echo "\t\t<td class=\"data1\"><input size=\"30\" name=\"formExpires\" value=\"", \htmlspecialchars($_POST['formExpires']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new user in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); // Check data - if ('' == $_POST['formUsername']) { + if ('' === $_POST['formUsername']) { $this->doCreate($this->lang['struserneedsname']); - } elseif ($_POST['formPassword'] != $_POST['formConfirm']) { + } elseif ($_POST['formPassword'] !== $_POST['formConfirm']) { $this->doCreate($this->lang['strpasswordconfirm']); } else { $status = $data->createUser( @@ -483,7 +486,8 @@ class UsersController extends BaseController $_POST['formExpires'], [] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strusercreated']); } else { $this->doCreate($this->lang['strusercreatedbad']); diff --git a/src/controllers/ViewpropertiesController.php b/src/controllers/ViewpropertiesController.php index 64456bb1..008a36f4 100644 --- a/src/controllers/ViewpropertiesController.php +++ b/src/controllers/ViewpropertiesController.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; /** * Base controller class. - * - * @package PHPPgAdmin */ class ViewpropertiesController extends BaseController { @@ -17,22 +18,24 @@ class ViewpropertiesController extends BaseController use \PHPPgAdmin\Traits\ViewsMatViewsPropertiesTrait; public $controller_title = 'strviews'; - public $subject = 'view'; + + public $subject = 'view'; /** * Default method to render the controller according to the action parameter. */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } $footer_template = 'footer.twig'; $header_template = 'header.twig'; - ob_start(); + \ob_start(); $this->printFooter(true, $footer_template); + switch ($this->action) { case 'save_edit': if (isset($_POST['cancel'])) { @@ -93,7 +96,7 @@ class ViewpropertiesController extends BaseController break; } - $output = ob_get_clean(); + $output = \ob_get_clean(); $this->printHeader($this->headerTitle('', '', $_REQUEST[$this->subject]), null, true, $header_template); $this->printBody(); @@ -105,12 +108,13 @@ class ViewpropertiesController extends BaseController /** * Function to save after editing a view. */ - public function doSaveEdit() + public function doSaveEdit(): void { $data = $this->misc->getDatabaseAccessor(); $status = $data->setView($_POST[$this->subject], $_POST['formDefinition'], $_POST['formComment']); - if (0 == $status) { + + if (0 === $status) { $this->doDefinition($this->lang['strviewupdated']); } else { $this->doEdit($this->lang['strviewupdatedbad']); @@ -122,7 +126,7 @@ class ViewpropertiesController extends BaseController * * @param mixed $msg */ - public function doEdit($msg = '') + public function doEdit($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -133,19 +137,19 @@ class ViewpropertiesController extends BaseController $viewdata = $data->getView($_REQUEST[$this->subject]); $this->printHeader($this->headerTitle(), null, true, 'header_sqledit.twig'); - if ($viewdata->recordCount() > 0) { + if (0 < $viewdata->recordCount()) { if (!isset($_POST['formDefinition'])) { $_POST['formDefinition'] = $viewdata->fields['vwdefinition']; $_POST['formComment'] = $viewdata->fields['relcomment']; } $variables = (object) [ - 'subfolder' => \SUBFOLDER.'/src/views/viewproperties', + 'subfolder' => self::SUBFOLDER . '/src/views/viewproperties', - 'formDefinition' => htmlspecialchars($_POST['formDefinition']), + 'formDefinition' => \htmlspecialchars($_POST['formDefinition']), - 'formComment' => htmlspecialchars($_POST['formComment']), - 'subject' => htmlspecialchars($_REQUEST[$this->subject]), ]; + 'formComment' => \htmlspecialchars($_POST['formComment']), + 'subject' => \htmlspecialchars($_REQUEST[$this->subject])]; $edition_area = <<<EOT @@ -179,7 +183,7 @@ class ViewpropertiesController extends BaseController EOT; echo $edition_area; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } @@ -188,7 +192,7 @@ EOT; * * @param mixed $msg */ - public function doProperties($msg = '') + public function doProperties($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -200,10 +204,10 @@ EOT; $this->printTitle($this->lang['stralter'], 'pg.column.alter'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER.'/src/views/viewproperties" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/viewproperties" method="post">' . \PHP_EOL; // Output view header - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data required\">{$this->lang['strname']}</th><th class=\"data required\">{$this->lang['strtype']}</th>"; echo "<th class=\"data\">{$this->lang['strdefault']}</th><th class=\"data\">{$this->lang['strcomment']}</th></tr>"; @@ -216,29 +220,29 @@ EOT; } echo '<tr><td><input name="field" size="32" value="', - htmlspecialchars($_REQUEST['field']), '" /></td>'; + \htmlspecialchars($_REQUEST['field']), '" /></td>'; echo '<td>', $this->misc->printVal($data->formatType($column->fields['type'], $column->fields['atttypmod'])), '</td>'; echo '<td><input name="default" size="20" value="', - htmlspecialchars($_REQUEST['default']), '" /></td>'; + \htmlspecialchars($_REQUEST['default']), '" /></td>'; echo '<td><input name="comment" size="32" value="', - htmlspecialchars($_REQUEST['comment']), '" /></td>'; + \htmlspecialchars($_REQUEST['comment']), '" /></td>'; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="properties" />'.PHP_EOL; - echo '<input type="hidden" name="stage" value="2" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="properties" />' . \PHP_EOL; + echo '<input type="hidden" name="stage" value="2" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="view" value="', htmlspecialchars($_REQUEST[$this->subject]), '" />'.PHP_EOL; - echo '<input type="hidden" name="column" value="', htmlspecialchars($_REQUEST['column']), '" />'.PHP_EOL; - echo '<input type="hidden" name="olddefault" value="', htmlspecialchars($_REQUEST['olddefault']), '" />'.PHP_EOL; - echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="view" value="', \htmlspecialchars($_REQUEST[$this->subject]), '" />' . \PHP_EOL; + echo '<input type="hidden" name="column" value="', \htmlspecialchars($_REQUEST['column']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="olddefault" value="', \htmlspecialchars($_REQUEST['olddefault']), '" />' . \PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; break; case 2: // Check inputs - if ('' == trim($_REQUEST['field'])) { + if ('' === \trim($_REQUEST['field'])) { $_REQUEST['stage'] = 1; $this->doProperties($this->lang['strcolneedsname']); @@ -260,7 +264,8 @@ EOT; '', $_REQUEST['comment'] ); - if (0 == $status) { + + if (0 === $status) { $this->doDefault($this->lang['strcolumnaltered']); } else { $_REQUEST['stage'] = 1; @@ -271,11 +276,11 @@ EOT; break; default: - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } } - public function doAlter($confirm = false, $msg = '') + public function doAlter($confirm = false, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -287,7 +292,7 @@ EOT; // Fetch view info $view = $data->getView($_REQUEST[$this->subject]); - if ($view->recordCount() > 0) { + if (0 < $view->recordCount()) { $this->coalesceArr($_POST, 'name', $view->fields['relname']); $this->coalesceArr($_POST, 'owner', $view->fields['relowner']); @@ -296,54 +301,56 @@ EOT; $this->coalesceArr($_POST, 'comment', $view->fields['relcomment']); - echo '<form action="'.\SUBFOLDER.'/src/views/viewproperties" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; - echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/viewproperties" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo "<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_POST['name']), '" /></td></tr>'.PHP_EOL; + \htmlspecialchars($_POST['name']), '" /></td></tr>' . \PHP_EOL; if ($data->isSuperUser()) { // Fetch all users $users = $data->getUsers(); - echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="owner">'; + while (!$users->EOF) { $uname = $users->fields['usename']; - echo '<option value="', htmlspecialchars($uname), '"', - ($uname == $_POST['owner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($uname), '"', + ($uname === $_POST['owner']) ? ' selected="selected"' : '', '>', \htmlspecialchars($uname), '</option>' . \PHP_EOL; $users->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } if ($data->hasAlterTableSchema()) { $schemas = $data->getSchemas(); - echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>".PHP_EOL; + echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>" . \PHP_EOL; echo '<td class="data1"><select name="newschema">'; + while (!$schemas->EOF) { $schema = $schemas->fields['nspname']; - echo '<option value="', htmlspecialchars($schema), '"', - ($schema == $_POST['newschema']) ? ' selected="selected"' : '', '>', htmlspecialchars($schema), '</option>'.PHP_EOL; + echo '<option value="', \htmlspecialchars($schema), '"', + ($schema === $_POST['newschema']) ? ' selected="selected"' : '', '>', \htmlspecialchars($schema), '</option>' . \PHP_EOL; $schemas->moveNext(); } - echo '</select></td></tr>'.PHP_EOL; + echo '</select></td></tr>' . \PHP_EOL; } - echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo '<td class="data1">'; echo '<textarea rows="3" cols="32" name="comment">', - htmlspecialchars($_POST['comment']), '</textarea></td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<input type="hidden" name="action" value="alter" />'.PHP_EOL; - echo '<input type="hidden" name="view" value="', htmlspecialchars($_REQUEST[$this->subject]), '" />'.PHP_EOL; + \htmlspecialchars($_POST['comment']), '</textarea></td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<input type="hidden" name="action" value="alter" />' . \PHP_EOL; + echo '<input type="hidden" name="view" value="', \htmlspecialchars($_REQUEST[$this->subject]), '" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } } else { // For databases that don't allow owner change @@ -352,17 +359,18 @@ EOT; $this->coalesceArr($_POST, 'newschema', null); $status = $data->alterView($_POST[$this->subject], $_POST['name'], $_POST['owner'], $_POST['newschema'], $_POST['comment']); - if (0 == $status) { + + if (0 === $status) { // If view has been renamed, need to change to the new name and // reload the browser frame. - if ($_POST[$this->subject] != $_POST['name']) { + if ($_POST[$this->subject] !== $_POST['name']) { // Jump them to the new view name $_REQUEST[$this->subject] = $_POST['name']; // Force a browser reload $this->misc->setReloadBrowser(true); } // If schema has changed, need to change to the new schema and reload the browser - if (!empty($_POST['newschema']) && ($_POST['newschema'] != $data->_schema)) { + if (!empty($_POST['newschema']) && ($_POST['newschema'] !== $data->_schema)) { // Jump them to the new sequence schema $this->misc->setCurrentSchema($_POST['newschema']); $this->misc->setReloadBrowser(true); diff --git a/src/controllers/ViewsController.php b/src/controllers/ViewsController.php index 6b3afef8..012c6c03 100644 --- a/src/controllers/ViewsController.php +++ b/src/controllers/ViewsController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Controller; @@ -10,14 +13,13 @@ use PHPPgAdmin\Decorators\Decorator; /** * Base controller class. - * - * @package PHPPgAdmin */ class ViewsController extends BaseController { use \PHPPgAdmin\Traits\ViewsMatviewsTrait; - public $table_place = 'views-views'; + public $table_place = 'views-views'; + public $controller_title = 'strviews'; // this member variable is view for views and matview for materialized views @@ -28,10 +30,11 @@ class ViewsController extends BaseController */ public function render() { - if ('tree' == $this->action) { + if ('tree' === $this->action) { return $this->doTree(); } - if ('subtree' == $this->action) { + + if ('subtree' === $this->action) { return $this->doSubTree(); } @@ -109,7 +112,7 @@ class ViewsController extends BaseController * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -123,7 +126,7 @@ class ViewsController extends BaseController $this->keystring => [ 'title' => $this->lang['strview'], 'field' => Decorator::field('relname'), - 'url' => \SUBFOLDER."/redirect/view?{$this->misc->href}&", + 'url' => self::SUBFOLDER . "/redirect/view?{$this->misc->href}&", 'vars' => [$this->keystring => 'relname'], ], 'owner' => [ @@ -237,7 +240,7 @@ class ViewsController extends BaseController 'content' => $this->lang['strcreateviewwiz'], ], ]; - $this->printNavLinks($navlinks, $this->table_place, get_defined_vars()); + $this->printNavLinks($navlinks, $this->table_place, \get_defined_vars()); } /** @@ -280,45 +283,48 @@ class ViewsController extends BaseController $this->printTrail('view'); $this->printTitle($this->lang['strdrop'], 'pg.view.drop'); - echo '<form action="'.\SUBFOLDER.'/src/views/views" method="post">'.PHP_EOL; + echo '<form action="' . self::SUBFOLDER . '/src/views/views" method="post">' . \PHP_EOL; //If multi drop if (isset($_REQUEST['ma'])) { foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfdropview'], $this->misc->printVal($a['view'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="view[]" value="', htmlspecialchars($a['view']), '" />'.PHP_EOL; + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfdropview'], $this->misc->printVal($a['view'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="view[]" value="', \htmlspecialchars($a['view']), '" />' . \PHP_EOL; } } else { - echo '<p>', sprintf($this->lang['strconfdropview'], $this->misc->printVal($_REQUEST['view'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="view" value="', htmlspecialchars($_REQUEST['view']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfdropview'], $this->misc->printVal($_REQUEST['view'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="view" value="', \htmlspecialchars($_REQUEST['view']), '" />' . \PHP_EOL; } - echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="drop" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } else { - if (is_array($_POST['view'])) { + if (\is_array($_POST['view'])) { $msg = ''; $status = $data->beginTransaction(); - if (0 == $status) { + + if (0 === $status) { foreach ($_POST['view'] as $s) { $status = $data->dropView($s, isset($_POST['cascade'])); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strviewdropped']); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($s, \ENT_QUOTES, 'UTF-8'), $this->lang['strviewdropped']); } else { $data->endTransaction(); - $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strviewdroppedbad'])); + $this->doDefault(\sprintf('%s%s: %s<br />', $msg, \htmlentities($s, \ENT_QUOTES, 'UTF-8'), $this->lang['strviewdroppedbad'])); return; } } } - if (0 == $data->endTransaction()) { + + if (0 === $data->endTransaction()) { // Everything went fine, back to the Default page.... $this->misc->setReloadBrowser(true); $this->doDefault($msg); @@ -327,7 +333,8 @@ class ViewsController extends BaseController } } else { $status = $data->dropView($_POST['view'], isset($_POST['cascade'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strviewdropped']); } else { @@ -365,7 +372,7 @@ class ViewsController extends BaseController * * @param mixed $msg */ - public function doWizardCreate($msg = '') + public function doWizardCreate($msg = ''): void { $this->printTrail('schema'); $this->printTitle($this->lang['strcreateviewwiz'], 'pg.view.create'); @@ -379,7 +386,7 @@ class ViewsController extends BaseController * * @param mixed $msg */ - public function doCreate($msg = '') + public function doCreate($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -398,40 +405,41 @@ class ViewsController extends BaseController $this->printTitle($this->lang['strcreateview'], 'pg.view.create'); $this->printMsg($msg); - echo '<form action="'.\SUBFOLDER."/src/views/{$this->view_name}\" method=\"post\">".PHP_EOL; - echo '<table style="width: 100%">'.PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL; + echo '<form action="' . self::SUBFOLDER . "/src/views/{$this->view_name}\" method=\"post\">" . \PHP_EOL; + echo '<table style="width: 100%">' . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>" . \PHP_EOL; echo "\t<td class=\"data1\"><input name=\"formView\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", - htmlspecialchars($_REQUEST['formView']), "\" /></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strdefinition']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['formView']), "\" /></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strdefinition']}</th>" . \PHP_EOL; echo "\t<td class=\"data1\"><textarea style=\"width:100%;\" rows=\"10\" cols=\"50\" name=\"formDefinition\">", - htmlspecialchars($_REQUEST['formDefinition']), "</textarea></td>\n\t</tr>".PHP_EOL; - echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL; + \htmlspecialchars($_REQUEST['formDefinition']), "</textarea></td>\n\t</tr>" . \PHP_EOL; + echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>" . \PHP_EOL; echo "\t\t<td class=\"data1\"><textarea name=\"formComment\" rows=\"3\" cols=\"32\">", - htmlspecialchars($_REQUEST['formComment']), "</textarea></td>\n\t</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create" />'.PHP_EOL; + \htmlspecialchars($_REQUEST['formComment']), "</textarea></td>\n\t</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** * Actually creates the new view in the database. */ - public function doSaveCreate() + public function doSaveCreate(): void { $data = $this->misc->getDatabaseAccessor(); // Check that they've given a name and a definition - if ('' == $_POST['formView']) { + if ('' === $_POST['formView']) { $this->doCreate($this->lang['strviewneedsname']); - } elseif ('' == $_POST['formDefinition']) { + } elseif ('' === $_POST['formDefinition']) { $this->doCreate($this->lang['strviewneedsdef']); } else { $status = $data->createView($_POST['formView'], $_POST['formDefinition'], false, $_POST['formComment']); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doDefault($this->lang['strviewcreated']); } else { diff --git a/src/database/ADOdbBase.php b/src/database/ADOdbBase.php index da3c3ccc..20625919 100644 --- a/src/database/ADOdbBase.php +++ b/src/database/ADOdbBase.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,8 +14,6 @@ namespace PHPPgAdmin\Database; * Parent class of all ADODB objects. * * Id: ADOdbBase.php,v 1.24 2008/02/20 20:43:10 ioguix Exp $ - * - * @package PHPPgAdmin */ class ADOdbBase { @@ -20,8 +21,11 @@ class ADOdbBase use \PHPPgAdmin\Database\Traits\HasTrait; public $lang; + public $conf; + protected $container; + protected $server_info; /** @@ -109,7 +113,7 @@ class ADOdbBase return -1; } - if ($comment != '') { + if ('' !== $comment) { $sql .= "'{$comment}';"; } else { $sql .= 'NULL;'; @@ -123,7 +127,7 @@ class ADOdbBase * * @param bool $debug True to turn on debugging, false otherwise */ - public function setDebug($debug) + public function setDebug($debug): void { $this->conn->debug = $debug; } @@ -138,11 +142,11 @@ class ADOdbBase public function fieldArrayClean(&$arr) { foreach ($arr as $k => $v) { - if ($v === null) { + if (null === $v) { continue; } - $arr[$k] = str_replace('"', '""', $v); + $arr[$k] = \str_replace('"', '""', $v); } return $arr; @@ -158,10 +162,10 @@ class ADOdbBase public function arrayClean(&$arr) { foreach ($arr as $k => $v) { - if ($v === null) { + if (null === $v) { continue; } - $arr[$k] = pg_escape_string($v); + $arr[$k] = \pg_escape_string($v); } return $arr; @@ -190,7 +194,7 @@ class ADOdbBase * Closes the connection the database class * relies on. */ - public function close() + public function close(): void { $this->conn->close(); } @@ -206,9 +210,7 @@ class ADOdbBase { // Execute the statement try { - $rs = $this->conn->Execute($sql); - - return $rs; + return $this->conn->Execute($sql); } catch (\Exception $e) { return $e->getCode(); } @@ -234,7 +236,7 @@ class ADOdbBase return $this->conn->ErrorNo(); } - if ($rs->recordCount() == 0) { + if (0 === $rs->recordCount()) { return -1; } @@ -254,7 +256,7 @@ class ADOdbBase { $this->fieldClean($table); - reset($conditions); + \reset($conditions); if (!empty($schema)) { $this->fieldClean($schema); @@ -267,6 +269,7 @@ class ADOdbBase foreach ($conditions as $key => $value) { $this->clean($key); $this->clean($value); + if ($sql) { $sql .= " AND \"{$key}\"='{$value}'"; } else { @@ -277,13 +280,13 @@ class ADOdbBase // Check for failures if (!$this->conn->Execute($sql)) { // Check for referential integrity failure - if (stristr($this->conn->ErrorMsg(), 'referential')) { + if (\mb_stristr($this->conn->ErrorMsg(), 'referential')) { return -1; } } // Check for no rows modified - if ($this->conn->Affected_Rows() == 0) { + if (0 === $this->conn->Affected_Rows()) { return -2; } @@ -299,10 +302,10 @@ class ADOdbBase */ public function fieldClean(&$str) { - if ($str === null) { + if (null === $str) { return null; } - $str = str_replace('"', '""', $str); + $str = \str_replace('"', '""', $str); return $str; } @@ -316,11 +319,11 @@ class ADOdbBase */ public function clean(&$str) { - if ($str === null) { + if (null === $str) { return null; } - $str = str_replace("\r\n", "\n", $str); - $str = pg_escape_string($str); + $str = \str_replace("\r\n", "\n", $str); + $str = \pg_escape_string($str); return $str; } @@ -334,7 +337,7 @@ class ADOdbBase */ public function escapeBytea($data) { - return htmlentities($data, ENT_QUOTES, 'UTF-8'); + return \htmlentities($data, \ENT_QUOTES, 'UTF-8'); } /** @@ -350,9 +353,10 @@ class ADOdbBase $this->fieldClean($table); $sql = ''; // Build clause - if (sizeof($vars) > 0) { + if (0 < \count($vars)) { $fields = ''; $values = ''; + foreach ($vars as $key => $value) { $this->clean($key); $this->clean($value); @@ -369,17 +373,17 @@ class ADOdbBase $values = ") VALUES ('{$value}'"; } } - $sql .= $fields.$values.')'; + $sql .= $fields . $values . ')'; } // Check for failures if (!$this->conn->Execute($sql)) { // Check for unique constraint failure - if (stristr($this->conn->ErrorMsg(), 'unique')) { + if (\mb_stristr($this->conn->ErrorMsg(), 'unique')) { return -1; } - if (stristr($this->conn->ErrorMsg(), 'referential')) { + if (\mb_stristr($this->conn->ErrorMsg(), 'referential')) { return -2; } // Check for referential integrity failure } @@ -405,11 +409,12 @@ class ADOdbBase $whereClause = ''; // Populate the syntax arrays - reset($vars); + \reset($vars); //while (list($key, $value) = each($vars)) { foreach ($vars as $key => $value) { $this->fieldClean($key); $this->clean($value); + if ($setClause) { $setClause .= ", \"{$key}\"='{$value}'"; } else { @@ -417,10 +422,11 @@ class ADOdbBase } } - reset($nulls); + \reset($nulls); //while (list(, $value) = each($nulls)) { foreach ($nulls as $key => $value) { $this->fieldClean($value); + if ($setClause) { $setClause .= ", \"{$value}\"=NULL"; } else { @@ -428,11 +434,12 @@ class ADOdbBase } } - reset($where); + \reset($where); //while (list($key, $value) = each($where)) { foreach ($where as $key => $value) { $this->fieldClean($key); $this->clean($value); + if ($whereClause) { $whereClause .= " AND \"{$key}\"='{$value}'"; } else { @@ -441,19 +448,19 @@ class ADOdbBase } // Check for failures - if (!$this->conn->Execute($setClause.$whereClause)) { + if (!$this->conn->Execute($setClause . $whereClause)) { // Check for unique constraint failure - if (stristr($this->conn->ErrorMsg(), 'unique')) { + if (\mb_stristr($this->conn->ErrorMsg(), 'unique')) { return -1; } - if (stristr($this->conn->ErrorMsg(), 'referential')) { + if (\mb_stristr($this->conn->ErrorMsg(), 'referential')) { return -2; } // Check for referential integrity failure } // Check for no rows modified - if ($this->conn->Affected_Rows() == 0) { + if (0 === $this->conn->Affected_Rows()) { return -3; } @@ -535,7 +542,7 @@ class ADOdbBase */ public function phpBool($parameter) { - return $parameter === 't'; + return 't' === $parameter; } /** @@ -550,38 +557,41 @@ class ADOdbBase public function phpArray($dbarr) { // Take off the first and last characters (the braces) - $arr = substr($dbarr, 1, strlen($dbarr) - 2); + $arr = \mb_substr($dbarr, 1, \mb_strlen($dbarr) - 2); // Pick out array entries by carefully parsing. This is necessary in order // to cope with double quotes and commas, etc. $elements = []; $i = $j = 0; $in_quotes = false; - while ($i < strlen($arr)) { + + while (\mb_strlen($arr) > $i) { // If current char is a double quote and it's not escaped, then // enter quoted bit - $char = substr($arr, $i, 1); - if ($char == '"' && ($i == 0 || substr($arr, $i - 1, 1) != '\\')) { + $char = \mb_substr($arr, $i, 1); + + if ('"' === $char && (0 === $i || '\\' !== \mb_substr($arr, $i - 1, 1))) { $in_quotes = !$in_quotes; - } elseif ($char == ',' && !$in_quotes) { + } elseif (',' === $char && !$in_quotes) { // Add text so far to the array - $elements[] = substr($arr, $j, $i - $j); + $elements[] = \mb_substr($arr, $j, $i - $j); $j = $i + 1; } ++$i; } // Add final text to the array - $elements[] = substr($arr, $j); + $elements[] = \mb_substr($arr, $j); - $elementcount = sizeof($elements); + $elementcount = \count($elements); // Do one further loop over the elements array to remote double quoting // and escaping of double quotes and backslashes for ($i = 0; $i < $elementcount; ++$i) { $v = $elements[$i]; - if (strpos($v, '"') === 0) { - $v = substr($v, 1, strlen($v) - 2); - $v = str_replace('\\"', '"', $v); - $v = str_replace('\\\\', '\\', $v); + + if (0 === \mb_strpos($v, '"')) { + $v = \mb_substr($v, 1, \mb_strlen($v) - 2); + $v = \str_replace('\\"', '"', $v); + $v = \str_replace('\\\\', '\\', $v); $elements[$i] = $v; } } diff --git a/src/database/Connection.php b/src/database/Connection.php index 901fd1ef..64f360e6 100644 --- a/src/database/Connection.php +++ b/src/database/Connection.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,19 +14,17 @@ namespace PHPPgAdmin\Database; * Class to represent a database connection * * Id: Connection.php,v 1.15 2008/02/18 21:42:47 ioguix Exp $ - * - * @package PHPPgAdmin */ class Connection { use \PHPPgAdmin\Traits\HelperTrait; public $conn; + public $platform = 'UNKNOWN'; - // The backend platform. Set to UNKNOWN by default. - private $_connection_result; protected $container; + protected $server_info; protected $version_dictionary = [ @@ -48,6 +49,9 @@ class Connection '7.4' => 'Postgres74', ]; + // The backend platform. Set to UNKNOWN by default. + private $_connection_result; + /** * Creates a new connection. Will actually make a database connection. * @@ -73,9 +77,9 @@ class Connection $this->conn->setFetchMode($fetchMode); // Ignore host if null - if ($host === null || $host == '') { - if ($port !== null && $port != '') { - $pghost = ':'.$port; + if (null === $host || '' === $host) { + if (null !== $port && '' !== $port) { + $pghost = ':' . $port; } else { $pghost = ''; } @@ -84,9 +88,9 @@ class Connection } // Add sslmode to $pghost as needed - if (($sslmode == 'disable') || ($sslmode == 'allow') || ($sslmode == 'prefer') || ($sslmode == 'require')) { - $pghost .= ':'.$sslmode; - } elseif ($sslmode == 'legacy') { + if (('disable' === $sslmode) || ('allow' === $sslmode) || ('prefer' === $sslmode) || ('require' === $sslmode)) { + $pghost .= ':' . $sslmode; + } elseif ('legacy' === $sslmode) { $pghost .= ' requiressl=1'; } @@ -119,7 +123,7 @@ class Connection */ public function getDriver(&$description) { - $v = pg_version($this->conn->_connectionID); + $v = \pg_version($this->conn->_connectionID); //\PhpConsole\Handler::getInstance()->debug($v, 'pg_version'); @@ -135,11 +139,12 @@ class Connection $field = $adodb->selectField($sql, 'version'); // Check the platform, if it's mingw, set it - if (preg_match('/ mingw /i', $field)) { + if (\preg_match('/ mingw /i', $field)) { $this->platform = 'MINGW'; } - $params = explode(' ', $field); + $params = \explode(' ', $field); + if (!isset($params[1])) { return -3; } @@ -149,23 +154,24 @@ class Connection $description = "PostgreSQL {$version}"; - $version_parts = explode('.', $version); - if ((int) ($version_parts[0] >= 10)) { + $version_parts = \explode('.', $version); + + if ((int) (10 <= $version_parts[0])) { $major_version = $version_parts[0]; } else { - $major_version = implode('.', [$version_parts[0], $version_parts[1]]); + $major_version = \implode('.', [$version_parts[0], $version_parts[1]]); } //$this->prtrace(['pg_version' => pg_version($this->conn->_connectionID), 'version' => $version, 'major_version' => $major_version]); // Detect version and choose appropriate database driver - if (array_key_exists($major_version, $this->version_dictionary)) { + if (\array_key_exists($major_version, $this->version_dictionary)) { return $this->version_dictionary[$major_version]; } /* All <7.4 versions are not supported */ // if major version is 7 or less and wasn't cought in the // switch/case block, we have an unsupported version. - if ((int) substr($version, 0, 1) < 8) { + if (8 > (int) \mb_substr($version, 0, 1)) { return null; } @@ -180,6 +186,6 @@ class Connection */ public function getLastError() { - return pg_last_error($this->conn->_connectionID); + return \pg_last_error($this->conn->_connectionID); } } diff --git a/src/database/Postgres.php b/src/database/Postgres.php index 6da31d6c..be5f8bbc 100644 --- a/src/database/Postgres.php +++ b/src/database/Postgres.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,8 +14,6 @@ namespace PHPPgAdmin\Database; * Note: This Class uses ADODB and returns RecordSets. * * Id: Postgres.php,v 1.320 2008/02/20 20:43:09 ioguix Exp $ - * - * @package PHPPgAdmin */ class Postgres extends ADOdbBase { @@ -35,8 +36,11 @@ class Postgres extends ADOdbBase use \PHPPgAdmin\Database\Traits\PrivilegesTrait; public $lang; + public $conf; + protected $container; + protected $server_info; public function __construct(&$conn, $container, $server_info) @@ -62,16 +66,17 @@ class Postgres extends ADOdbBase $this->getHelpPages(); if (isset($this->help_page[$help])) { - if (is_array($this->help_page[$help])) { + if (\is_array($this->help_page[$help])) { $urls = []; + foreach ($this->help_page[$help] as $link) { - $urls[] = $this->help_base.$link; + $urls[] = $this->help_base . $link; } return $urls; } - return $this->help_base.$this->help_page[$help]; + return $this->help_base . $this->help_page[$help]; } return null; @@ -82,13 +87,13 @@ class Postgres extends ADOdbBase * get help page by instancing the corresponding help class * if $this->help_page and $this->help_base are set, this function is a noop. */ - public function getHelpPages() + public function getHelpPages(): void { - if ($this->help_page === null || $this->help_base === null) { - $help_classname = '\PHPPgAdmin\Help\PostgresDoc'.str_replace('.', '', $this->major_version); - - $help_class = new $help_classname($this->conf, $this->major_version); + if (null === $this->help_page || null === $this->help_base) { + $help_classname = '\PHPPgAdmin\Help\PostgresDoc' . \str_replace('.', '', $this->major_version); + $help_class = new $help_classname($this->conf, $this->major_version); + $this->help_page = $help_class->getHelpPage(); $this->help_base = $help_class->getHelpBase(); } } @@ -103,42 +108,43 @@ class Postgres extends ADOdbBase * @param string $type The database type of the field * @param array $extras An array of attributes name as key and attributes' values as value */ - public function printField($name, $value, $type, $extras = []) + public function printField($name, $value, $type, $extras = []): void { $lang = $this->lang; // Determine actions string $extra_str = ''; + foreach ($extras as $k => $v) { - $extra_str .= " {$k}=\"".htmlspecialchars($v).'"'; + $extra_str .= " {$k}=\"" . \htmlspecialchars($v) . '"'; } - switch (substr($type, 0, 9)) { + switch (\mb_substr($type, 0, 9)) { case 'bool': case 'boolean': - if ($value !== null && $value == '') { + if (null !== $value && '' === $value) { $value = null; - } elseif ($value == 'true') { + } elseif ('true' === $value) { $value = 't'; - } elseif ($value == 'false') { + } elseif ('false' === $value) { $value = 'f'; } // If value is null, 't' or 'f'... - if ($value === null || $value == 't' || $value == 'f') { - echo '<select name="', htmlspecialchars($name), "\"{$extra_str}>\n"; - echo '<option value=""', ($value === null) ? ' selected="selected"' : '', "></option>\n"; - echo '<option value="t"', ($value == 't') ? ' selected="selected"' : '', ">{$lang['strtrue']}</option>\n"; - echo '<option value="f"', ($value == 'f') ? ' selected="selected"' : '', ">{$lang['strfalse']}</option>\n"; + if (null === $value || 't' === $value || 'f' === $value) { + echo '<select name="', \htmlspecialchars($name), "\"{$extra_str}>\n"; + echo '<option value=""', (null === $value) ? ' selected="selected"' : '', "></option>\n"; + echo '<option value="t"', ('t' === $value) ? ' selected="selected"' : '', ">{$lang['strtrue']}</option>\n"; + echo '<option value="f"', ('f' === $value) ? ' selected="selected"' : '', ">{$lang['strfalse']}</option>\n"; echo "</select>\n"; } else { - echo '<input name="', htmlspecialchars($name), '" value="', htmlspecialchars($value), "\" size=\"35\"{$extra_str} />\n"; + echo '<input name="', \htmlspecialchars($name), '" value="', \htmlspecialchars($value), "\" size=\"35\"{$extra_str} />\n"; } break; case 'bytea': case 'bytea[]': - if (!is_null($value)) { + if (null !== $value) { $value = $this->escapeBytea($value); } // no break @@ -148,26 +154,26 @@ class Postgres extends ADOdbBase case 'jsonb': case 'xml': case 'xml[]': - $n = substr_count($value, "\n"); - $n = $n < 5 ? max(2, $n) : $n; - $n = $n > 20 ? 20 : $n; - echo '<textarea name="', htmlspecialchars($name), "\" rows=\"{$n}\" cols=\"85\"{$extra_str}>\n"; - echo htmlspecialchars($value); + $n = \mb_substr_count($value, "\n"); + $n = 5 > $n ? \max(2, $n) : $n; + $n = 20 < $n ? 20 : $n; + echo '<textarea name="', \htmlspecialchars($name), "\" rows=\"{$n}\" cols=\"85\"{$extra_str}>\n"; + echo \htmlspecialchars($value); echo "</textarea>\n"; break; case 'character': case 'character[]': - $n = substr_count($value, "\n"); - $n = $n < 5 ? 5 : $n; - $n = $n > 20 ? 20 : $n; - echo '<textarea name="', htmlspecialchars($name), "\" rows=\"{$n}\" cols=\"35\"{$extra_str}>\n"; - echo htmlspecialchars($value); + $n = \mb_substr_count($value, "\n"); + $n = 5 > $n ? 5 : $n; + $n = 20 < $n ? 20 : $n; + echo '<textarea name="', \htmlspecialchars($name), "\" rows=\"{$n}\" cols=\"35\"{$extra_str}>\n"; + echo \htmlspecialchars($value); echo "</textarea>\n"; break; default: - echo '<input name="', htmlspecialchars($name), '" value="', htmlspecialchars($value), "\" size=\"35\"{$extra_str} />\n"; + echo '<input name="', \htmlspecialchars($name), '" value="', \htmlspecialchars($value), "\" size=\"35\"{$extra_str} />\n"; break; } @@ -196,8 +202,8 @@ class Postgres extends ADOdbBase // Escape search term for ILIKE match $this->clean($term); $this->clean($filter); - $term = str_replace('_', '\_', $term); - $term = str_replace('%', '\%', $term); + $term = \str_replace('_', '\_', $term); + $term = \str_replace('%', '\%', $term); // Exclude system relations if necessary if (!$conf['show_system']) { @@ -212,7 +218,8 @@ class Postgres extends ADOdbBase // Apply outer filter $sql = ''; - if ($filter != '') { + + if ('' !== $filter) { $sql = 'SELECT * FROM ('; } @@ -316,7 +323,7 @@ class Postgres extends ADOdbBase "; } - if ($filter != '') { + if ('' !== $filter) { // We use like to make RULE, CONSTRAINT and COLUMN searches work $sql .= ") AS sub WHERE type LIKE '{$filter}%' "; } @@ -344,25 +351,27 @@ class Postgres extends ADOdbBase $this->clean($table); $this->arrayClean($atts); - if (!is_array($atts)) { + if (!\is_array($atts)) { return -1; } - if (sizeof($atts) == 0) { + if (0 === \count($atts)) { return []; } $sql = "SELECT attnum, attname FROM pg_catalog.pg_attribute WHERE attrelid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}' AND relnamespace=(SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='{$c_schema}')) - AND attnum IN ('".join("','", $atts)."')"; + AND attnum IN ('" . \implode("','", $atts) . "')"; $rs = $this->selectSet($sql); - if ($rs->recordCount() != sizeof($atts)) { + + if ($rs->recordCount() !== \count($atts)) { return -2; } $temp = []; + while (!$rs->EOF) { $temp[$rs->fields['attnum']] = $rs->fields['attname']; $rs->moveNext(); @@ -417,12 +426,14 @@ class Postgres extends ADOdbBase { // This whole function isn't very encapsulated, but hey... $conn = $this->conn->_connectionID; - if (!is_uploaded_file($_FILES[$name]['tmp_name'])) { + + if (!\is_uploaded_file($_FILES[$name]['tmp_name'])) { return false; } - $fd = fopen($_FILES[$name]['tmp_name'], 'rb'); - if ($fd === false) { + $fd = \fopen($_FILES[$name]['tmp_name'], 'rb'); + + if (false === $fd) { return false; } @@ -441,16 +452,16 @@ class Postgres extends ADOdbBase $lineno = 0; // Loop over each line in the file - while (!feof($fd)) { - $line = fgets($fd); + while (!\feof($fd)) { + $line = \fgets($fd); ++$lineno; // Nothing left on line? Then ignore... - if (trim($line) == '') { + if ('' === \trim($line)) { continue; } - $len = strlen($line); + $len = \mb_strlen($line); $query_start = 0; /** @@ -460,11 +471,11 @@ class Postgres extends ADOdbBase * - prevlen], the next character at line[i + thislen]. */ $prevlen = 0; - $thislen = ($len > 0) ? 1 : 0; + $thislen = (0 < $len) ? 1 : 0; for ($i = 0; $i < $len; $this->advance_1($i, $prevlen, $thislen)) { /* was the previous character a backslash? */ - if ($i > 0 && substr($line, $i - $prevlen, 1) == '\\') { + if (0 < $i && '\\' === \mb_substr($line, $i - $prevlen, 1)) { $this->prtrace('bslash_count', $bslash_count, $line); ++$bslash_count; } else { @@ -478,54 +489,59 @@ class Postgres extends ADOdbBase */ /* in quote? */ - if ($in_quote !== 0) { + if (0 !== $in_quote) { //$this->prtrace('in_quote', $in_quote, $line); /* * end of quote if matching non-backslashed character. * backslashes don't count for double quotes, though. */ - if (substr($line, $i, 1) == $in_quote && - ($bslash_count % 2 == 0 || $in_quote == '"') + if (\mb_substr($line, $i, 1) === $in_quote && + (0 === $bslash_count % 2 || '"' === $in_quote) ) { $in_quote = 0; } } elseif ($dol_quote) { $this->prtrace('dol_quote', $dol_quote, $line); - if (strncmp(substr($line, $i), $dol_quote, strlen($dol_quote)) == 0) { + + if (0 === \strncmp(\mb_substr($line, $i), $dol_quote, \mb_strlen($dol_quote))) { $this->advance_1($i, $prevlen, $thislen); - while (substr($line, $i, 1) != '$') { + + while ('$' !== \mb_substr($line, $i, 1)) { $this->advance_1($i, $prevlen, $thislen); } $dol_quote = ''; } - } elseif (substr($line, $i, 2) == '/*') { + } elseif ('/*' === \mb_substr($line, $i, 2)) { $this->prtrace('open_xcomment', $in_xcomment, $line, $i, $prevlen, $thislen); - if ($in_xcomment == 0) { + + if (0 === $in_xcomment) { ++$in_xcomment; - $finishpos = strpos(substr($line, $i, $len), '*/'); - if ($finishpos === false) { - $line = substr($line, 0, $i); /* remove comment */ + $finishpos = \mb_strpos(\mb_substr($line, $i, $len), '*/'); + + if (false === $finishpos) { + $line = \mb_substr($line, 0, $i); /* remove comment */ break; } - $pre = substr($line, 0, $i); - $post = substr($line, $i + 2 + $finishpos, $len); - $line = $pre.' '.$post; + $pre = \mb_substr($line, 0, $i); + $post = \mb_substr($line, $i + 2 + $finishpos, $len); + $line = $pre . ' ' . $post; $in_xcomment = 0; $i = 0; } } elseif ($in_xcomment) { - $position = strpos(substr($line, $i, $len), '*/'); - if ($position === false) { + $position = \mb_strpos(\mb_substr($line, $i, $len), '*/'); + + if (false === $position) { $line = ''; break; } - $substr = substr($line, $i, 2); + $substr = \mb_substr($line, $i, 2); - if ($substr == '*/' && !--$in_xcomment) { - $line = substr($line, $i + 2, $len); + if ('*/' === $substr && !--$in_xcomment) { + $line = \mb_substr($line, $i + 2, $len); $i += 2; $this->advance_1($i, $prevlen, $thislen); } @@ -540,59 +556,61 @@ class Postgres extends ADOdbBase // if ($substr == '*/' && !--$in_xcomment) { // $this->advance_1($i, $prevlen, $thislen); // } - } elseif (substr($line, $i, 1) == '\'' || substr($line, $i, 1) == '"') { - $in_quote = substr($line, $i, 1); - } elseif (!$dol_quote && $this->valid_dolquote(substr($line, $i))) { - $dol_end = strpos(substr($line, $i + 1), '$'); - $dol_quote = substr($line, $i, $dol_end + 1); + } elseif ('\'' === \mb_substr($line, $i, 1) || '"' === \mb_substr($line, $i, 1)) { + $in_quote = \mb_substr($line, $i, 1); + } elseif (!$dol_quote && $this->valid_dolquote(\mb_substr($line, $i))) { + $dol_end = \mb_strpos(\mb_substr($line, $i + 1), '$'); + $dol_quote = \mb_substr($line, $i, $dol_end + 1); $this->advance_1($i, $prevlen, $thislen); - while (substr($line, $i, 1) != '$') { + + while ('$' !== \mb_substr($line, $i, 1)) { $this->advance_1($i, $prevlen, $thislen); } } else { - if (substr($line, $i, 2) == '--') { - $line = substr($line, 0, $i); /* remove comment */ + if ('--' === \mb_substr($line, $i, 2)) { + $line = \mb_substr($line, 0, $i); /* remove comment */ break; } /* count nested parentheses */ - if (substr($line, $i, 1) == '(') { + if ('(' === \mb_substr($line, $i, 1)) { ++$paren_level; - } elseif (substr($line, $i, 1) == ')' && $paren_level > 0) { + } elseif (')' === \mb_substr($line, $i, 1) && 0 < $paren_level) { --$paren_level; - } elseif (substr($line, $i, 1) == ';' && !$bslash_count && !$paren_level) { - $subline = substr(substr($line, 0, $i), $query_start); + } elseif (';' === \mb_substr($line, $i, 1) && !$bslash_count && !$paren_level) { + $subline = \mb_substr(\mb_substr($line, 0, $i), $query_start); /* * insert a cosmetic newline, if this is not the first * line in the buffer */ - if (strlen($query_buf) > 0) { + if (0 < \mb_strlen($query_buf)) { $query_buf .= "\n"; } /* append the line to the query buffer */ $query_buf .= $subline; /* is there anything in the query_buf? */ - if (trim($query_buf)) { + if (\trim($query_buf)) { $query_buf .= ';'; // Execute the query. PHP cannot execute // empty queries, unlike libpq - $res = @pg_query($conn, $query_buf); + $res = \pg_query($conn, $query_buf); // Call the callback function for display - if ($callback !== null) { + if (null !== $callback) { $callback($query_buf, $res, $lineno); } // Check for COPY request - if (pg_result_status($res) == 4) { + if (4 === \pg_result_status($res)) { // 4 == PGSQL_COPY_FROM - while (!feof($fd)) { - $copy = fgets($fd, 32768); + while (!\feof($fd)) { + $copy = \fgets($fd, 32768); ++$lineno; - pg_put_line($conn, $copy); - if ($copy == "\\.\n" || $copy == "\\.\r\n") { - pg_end_copy($conn); + \pg_put_line($conn, $copy); + + if ("\\.\n" === $copy || "\\.\r\n" === $copy) { + \pg_end_copy($conn); break; } @@ -601,12 +619,13 @@ class Postgres extends ADOdbBase } $query_buf = null; $query_start = $i + $thislen; - } elseif (preg_match('/^[_[:alpha:]]$/', substr($line, $i, 1))) { - $sub = substr($line, $i, $thislen); - while (preg_match('/^[\$_A-Za-z0-9]$/', $sub)) { + } elseif (\preg_match('/^[_[:alpha:]]$/', \mb_substr($line, $i, 1))) { + $sub = \mb_substr($line, $i, $thislen); + + while (\preg_match('/^[\$_A-Za-z0-9]$/', $sub)) { /* keep going while we still have identifier chars */ $this->advance_1($i, $prevlen, $thislen); - $sub = substr($line, $i, $thislen); + $sub = \mb_substr($line, $i, $thislen); } // Since we're now over the next character to be examined, it is necessary // to move back one space. @@ -616,10 +635,10 @@ class Postgres extends ADOdbBase } // end for /* Put the rest of the line in the query buffer. */ - $subline = substr($line, $query_start); + $subline = \mb_substr($line, $query_start); - if ($in_quote || $dol_quote || strspn($subline, " \t\n\r") != strlen($subline)) { - if (strlen($query_buf) > 0) { + if ($in_quote || $dol_quote || \strspn($subline, " \t\n\r") !== \mb_strlen($subline)) { + if (0 < \mb_strlen($query_buf)) { $query_buf .= "\n"; } @@ -634,24 +653,25 @@ class Postgres extends ADOdbBase * Process query at the end of file without a semicolon, so long as * it's non-empty. */ - if (strlen($query_buf) > 0 && strspn($query_buf, " \t\n\r") != strlen($query_buf)) { + if (0 < \mb_strlen($query_buf) && \strspn($query_buf, " \t\n\r") !== \mb_strlen($query_buf)) { // Execute the query - $res = @pg_query($conn, $query_buf); + $res = \pg_query($conn, $query_buf); // Call the callback function for display - if ($callback !== null) { + if (null !== $callback) { $callback($query_buf, $res, $lineno); } // Check for COPY request - if (pg_result_status($res) == 4) { + if (4 === \pg_result_status($res)) { // 4 == PGSQL_COPY_FROM - while (!feof($fd)) { - $copy = fgets($fd, 32768); + while (!\feof($fd)) { + $copy = \fgets($fd, 32768); ++$lineno; - pg_put_line($conn, $copy); - if ($copy == "\\.\n" || $copy == "\\.\r\n") { - pg_end_copy($conn); + \pg_put_line($conn, $copy); + + if ("\\.\n" === $copy || "\\.\r\n" === $copy) { + \pg_end_copy($conn); break; } @@ -659,42 +679,11 @@ class Postgres extends ADOdbBase } } - fclose($fd); + \fclose($fd); return $res; } - /** - * A private helper method for executeScript that advances the - * character by 1. In psql this is careful to take into account - * multibyte languages, but we don't at the moment, so this function - * is someone redundant, since it will always advance by 1. - * - * @param int $i The current character position in the line - * @param int $prevlen Length of previous character (ie. 1) - * @param int $thislen Length of current character (ie. 1) - */ - protected function advance_1(&$i, &$prevlen, &$thislen) - { - $prevlen = $thislen; - $i += $thislen; - $thislen = 1; - } - - /** - * Private helper method to detect a valid $foo$ quote delimiter at - * the start of the parameter dquote. - * - * @param string $dquote - * - * @return bool true if valid, false otherwise - */ - protected function valid_dolquote($dquote) - { - // XXX: support multibyte - return preg_match('/^[$][$]/', $dquote) || preg_match('/^[$][_[:alpha:]][_[:alnum:]]*[$]/', $dquote); - } - // Capabilities /** @@ -720,14 +709,14 @@ class Postgres extends ADOdbBase public function browseQuery($type, $table, $query, $sortkey, $sortdir, $page, $page_size, &$max_pages) { // Check that we're not going to divide by zero - if (!is_numeric($page_size) || $page_size != (int) $page_size || $page_size <= 0) { + if (!\is_numeric($page_size) || (int) $page_size !== $page_size || 0 >= $page_size) { return -3; } // If $type is TABLE, then generate the query switch ($type) { case 'TABLE': - if (preg_match('/^[0-9]+$/', $sortkey) && $sortkey > 0) { + if (\preg_match('/^[0-9]+$/', $sortkey) && 0 < $sortkey) { $orderby = [$sortkey => $sortdir]; } else { $orderby = []; @@ -739,10 +728,10 @@ class Postgres extends ADOdbBase case 'QUERY': case 'SELECT': // Trim query - $query = trim($query); + $query = \trim($query); // Trim off trailing semi-colon if there is one - if (substr($query, strlen($query) - 1, 1) == ';') { - $query = substr($query, 0, strlen($query) - 1); + if (';' === \mb_substr($query, \mb_strlen($query) - 1, 1)) { + $query = \mb_substr($query, 0, \mb_strlen($query) - 1); } break; @@ -751,11 +740,12 @@ class Postgres extends ADOdbBase } // Generate count query - $count = "SELECT COUNT(*) AS total FROM (${query}) AS sub"; + $count = "SELECT COUNT(*) AS total FROM ({$query}) AS sub"; // Open a transaction $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } @@ -763,7 +753,8 @@ class Postgres extends ADOdbBase // to avoid side effects from repeating queries that do writes. if ($this->hasReadOnlyQueries()) { $status = $this->execute('SET TRANSACTION READ ONLY'); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -5; @@ -772,17 +763,18 @@ class Postgres extends ADOdbBase // Count the number of rows $total = $this->browseQueryCount($count); - if ($total < 0) { + + if (0 > $total) { $this->rollbackTransaction(); return -2; } // Calculate max pages - $max_pages = ceil($total / $page_size); + $max_pages = \ceil($total / $page_size); // Check that page is less than or equal to max pages - if (!is_numeric($page) || $page != (int) $page || $page > $max_pages || $page < 1) { + if (!\is_numeric($page) || (int) $page !== $page || $page > $max_pages || 1 > $page) { $this->rollbackTransaction(); return -3; @@ -791,16 +783,16 @@ class Postgres extends ADOdbBase // Set fetch mode to NUM so that duplicate field names are properly returned // for non-table queries. Since the SELECT feature only allows selecting one // table, duplicate fields shouldn't appear. - if ($type == 'QUERY') { + if ('QUERY' === $type) { $this->conn->setFetchMode(ADODB_FETCH_NUM); } // Figure out ORDER BY. Sort key is always the column number (based from one) // of the column to order by. Only need to do this for non-TABLE queries - if ($type != 'TABLE' && preg_match('/^[0-9]+$/', $sortkey) && $sortkey > 0) { + if ('TABLE' !== $type && \preg_match('/^[0-9]+$/', $sortkey) && 0 < $sortkey) { $orderby = " ORDER BY {$sortkey}"; // Add sort order - if ($sortdir == 'desc') { + if ('desc' === $sortdir) { $orderby .= ' DESC'; } else { $orderby .= ' ASC'; @@ -810,9 +802,10 @@ class Postgres extends ADOdbBase } // Actually retrieve the rows, with offset and limit - $rs = $this->selectSet("SELECT * FROM ({$query}) AS sub {$orderby} LIMIT {$page_size} OFFSET ".($page - 1) * $page_size); + $rs = $this->selectSet("SELECT * FROM ({$query}) AS sub {$orderby} LIMIT {$page_size} OFFSET " . ($page - 1) * $page_size); $status = $this->endTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -838,7 +831,7 @@ class Postgres extends ADOdbBase $this->fieldArrayClean($show); // If an empty array is passed in, then show all columns - if (sizeof($show) == 0) { + if (0 === \count($show)) { if ($this->hasObjectID($table)) { $sql = "SELECT \"{$this->id}\", * FROM "; } else { @@ -846,13 +839,13 @@ class Postgres extends ADOdbBase } } else { // Add oid column automatically to results for editing purposes - if (!in_array($this->id, $show, true) && $this->hasObjectID($table)) { + if (!\in_array($this->id, $show, true) && $this->hasObjectID($table)) { $sql = "SELECT \"{$this->id}\", \""; } else { $sql = 'SELECT "'; } - $sql .= join('","', $show).'" FROM '; + $sql .= \implode('","', $show) . '" FROM '; } $this->fieldClean($table); @@ -866,10 +859,12 @@ class Postgres extends ADOdbBase // If we have values specified, add them to the WHERE clause $first = true; - if (is_array($values) && sizeof($values) > 0) { + + if (\is_array($values) && 0 < \count($values)) { foreach ($values as $k => $v) { - if ($v != '' || $this->selectOps[$ops[$k]] == 'p') { + if ('' !== $v || 'p' === $this->selectOps[$ops[$k]]) { $this->fieldClean($k); + if ($first) { $sql .= ' WHERE '; $first = false; @@ -906,9 +901,10 @@ class Postgres extends ADOdbBase } // ORDER BY - if (is_array($orderby) && sizeof($orderby) > 0) { + if (\is_array($orderby) && 0 < \count($orderby)) { $sql .= ' ORDER BY '; $first = true; + foreach ($orderby as $k => $v) { if ($first) { $first = false; @@ -916,13 +912,14 @@ class Postgres extends ADOdbBase $sql .= ', '; } - if (preg_match('/^[0-9]+$/', $k)) { + if (\preg_match('/^[0-9]+$/', $k)) { $sql .= $k; } else { $this->fieldClean($k); - $sql .= '"'.$k.'"'; + $sql .= '"' . $k . '"'; } - if (strtoupper($v) == 'DESC') { + + if ('DESC' === \mb_strtoupper($v)) { $sql .= ' DESC'; } } @@ -943,4 +940,35 @@ class Postgres extends ADOdbBase { return $this->selectField($count, 'total'); } + + /** + * A private helper method for executeScript that advances the + * character by 1. In psql this is careful to take into account + * multibyte languages, but we don't at the moment, so this function + * is someone redundant, since it will always advance by 1. + * + * @param int $i The current character position in the line + * @param int $prevlen Length of previous character (ie. 1) + * @param int $thislen Length of current character (ie. 1) + */ + protected function advance_1(&$i, &$prevlen, &$thislen): void + { + $prevlen = $thislen; + $i += $thislen; + $thislen = 1; + } + + /** + * Private helper method to detect a valid $foo$ quote delimiter at + * the start of the parameter dquote. + * + * @param string $dquote + * + * @return bool true if valid, false otherwise + */ + protected function valid_dolquote($dquote) + { + // XXX: support multibyte + return \preg_match('/^[$][$]/', $dquote) || \preg_match('/^[$][_[:alpha:]][_[:alnum:]]*[$]/', $dquote); + } } diff --git a/src/database/Postgres10.php b/src/database/Postgres10.php index ec62e333..7ac9e4c7 100644 --- a/src/database/Postgres10.php +++ b/src/database/Postgres10.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; diff --git a/src/database/Postgres11.php b/src/database/Postgres11.php index bf108bbd..10a0ed4d 100644 --- a/src/database/Postgres11.php +++ b/src/database/Postgres11.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; diff --git a/src/database/Postgres12.php b/src/database/Postgres12.php index 03be9d00..b6aec6bd 100644 --- a/src/database/Postgres12.php +++ b/src/database/Postgres12.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; diff --git a/src/database/Postgres13.php b/src/database/Postgres13.php index 46622aab..5d81eca0 100644 --- a/src/database/Postgres13.php +++ b/src/database/Postgres13.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; diff --git a/src/database/Postgres74.php b/src/database/Postgres74.php index 405d709d..474eae90 100644 --- a/src/database/Postgres74.php +++ b/src/database/Postgres74.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -12,12 +15,11 @@ namespace PHPPgAdmin\Database; * Note: This class uses ADODB and returns RecordSets. * * Id: Postgres74.php,v 1.72 2008/02/20 21:06:18 ioguix Exp $ - * - * @package PHPPgAdmin */ class Postgres74 extends Postgres80 { public $major_version = 7.4; + // List of all legal privileges that can be applied to different types // of objects. public $privlist = [ @@ -51,7 +53,8 @@ class Postgres74 extends Postgres80 $this->clean($newName); $status = $this->alterDatabaseRename($dbName, $newName); - if ($status != 0) { + + if (0 !== $status) { return -3; } @@ -126,8 +129,8 @@ class Postgres74 extends Postgres80 */ // Escape search term for ILIKE match - $term = str_replace('_', '\\_', $term); - $term = str_replace('%', '\\%', $term); + $term = \str_replace('_', '\\_', $term); + $term = \str_replace('%', '\\%', $term); $this->clean($term); $this->clean($filter); @@ -144,7 +147,8 @@ class Postgres74 extends Postgres80 // Apply outer filter $sql = ''; - if ($filter != '') { + + if ('' !== $filter) { $sql = 'SELECT * FROM ('; } @@ -244,7 +248,7 @@ class Postgres74 extends Postgres80 "; } - if ($filter != '') { + if ('' !== $filter) { // We use like to make RULE, CONSTRAINT and COLUMN searches work $sql .= ") AS sub WHERE type LIKE '{$filter}%' "; } @@ -325,14 +329,16 @@ class Postgres74 extends Postgres80 ) { $sql = ''; $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } // @@ NEED TO HANDLE "NESTED" TRANSACTION HERE - if ($notnull != $oldnotnull) { + if ($notnull !== $oldnotnull) { $status = $this->setColumnNull($table, $column, !$notnull); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -2; @@ -340,14 +346,14 @@ class Postgres74 extends Postgres80 } // Set default, if it has changed - if ($default != $olddefault) { - if ($default == '') { + if ($default !== $olddefault) { + if ('' === $default) { $status = $this->dropColumnDefault($table, $column); } else { $status = $this->setColumnDefault($table, $column, $default); } - if ($status != 0) { + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -355,9 +361,10 @@ class Postgres74 extends Postgres80 } // Rename the column, if it has been changed - if ($column != $name) { + if ($column !== $name) { list($status, $sql) = $this->renameColumn($table, $column, $name); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -4; @@ -369,7 +376,8 @@ class Postgres74 extends Postgres80 $this->fieldClean($name); $this->fieldClean($table); $status = $this->setComment('COLUMN', $name, $table, $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -5; @@ -460,8 +468,9 @@ class Postgres74 extends Postgres80 pg_catalog.pg_constraint AS c JOIN pg_catalog.pg_class AS r1 ON (c.conrelid=r1.oid) JOIN pg_catalog.pg_attribute AS f1 ON (f1.attrelid=r1.oid AND (f1.attnum=c.conkey[1]'; + for ($i = 2; $i <= $rs->fields['nb']; ++$i) { - $sql .= " OR f1.attnum=c.conkey[${i}]"; + $sql .= " OR f1.attnum=c.conkey[{$i}]"; } $sql .= ')) JOIN pg_catalog.pg_namespace AS ns1 ON r1.relnamespace=ns1.oid @@ -470,11 +479,12 @@ class Postgres74 extends Postgres80 ) ON (c.confrelid=r2.oid) LEFT JOIN pg_catalog.pg_attribute AS f2 ON (f2.attrelid=r2.oid AND ((c.confkey[1]=f2.attnum AND c.conkey[1]=f1.attnum)'; + for ($i = 2; $i <= $rs->fields['nb']; ++$i) { - $sql .= " OR (c.confkey[${i}]=f2.attnum AND c.conkey[${i}]=f1.attnum)"; + $sql .= " OR (c.confkey[{$i}]=f2.attnum AND c.conkey[{$i}]=f1.attnum)"; } - $sql .= sprintf(")) + $sql .= \sprintf(")) WHERE r1.relname = '%s' AND ns1.nspname='%s' ORDER BY 1", $table, $c_schema); @@ -495,6 +505,7 @@ class Postgres74 extends Postgres80 { $c_schema = $this->_schema; $this->clean($c_schema); + if ($all) { // Exclude pg_catalog and information_schema tables $sql = "SELECT n.nspname, c.relname AS seqname, u.usename AS seqowner @@ -547,7 +558,7 @@ class Postgres74 extends Postgres80 FROM pg_catalog.pg_proc pc, pg_catalog.pg_language pl, pg_catalog.pg_namespace n WHERE - pc.oid = '${function_oid}'::oid + pc.oid = '{$function_oid}'::oid AND pc.prolang = pl.oid AND n.oid = pc.pronamespace "; @@ -669,21 +680,24 @@ class Postgres74 extends Postgres80 // Comment $status = $this->setComment('TABLE', '', $tblrs->fields['relname'], $comment); - if ($status != 0) { + + if (0 !== $status) { return -4; } // Owner $this->fieldClean($owner); $status = $this->alterTableOwner($tblrs, $owner); - if ($status != 0) { + + if (0 !== $status) { return -5; } // Rename $this->fieldClean($name); $status = $this->alterTableName($tblrs, $name); - if ($status != 0) { + + if (0 !== $status) { return -3; } diff --git a/src/database/Postgres80.php b/src/database/Postgres80.php index b0522c42..19116603 100644 --- a/src/database/Postgres80.php +++ b/src/database/Postgres80.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,12 +14,11 @@ namespace PHPPgAdmin\Database; * PostgreSQL 8.0 support * * Id: Postgres80.php,v 1.28 2007/12/12 04:11:10 xzilla Exp $ - * - * @package PHPPgAdmin */ class Postgres80 extends Postgres81 { public $major_version = 8.0; + // Map of database encoding names to HTTP encoding names. If a // database encoding does not appear in this list, then its HTTP // encoding name is the same as its database encoding name. @@ -258,6 +260,29 @@ class Postgres80 extends Postgres81 } /** + * Return all tables in current database (and schema). + * + * @return int|\PHPPgAdmin\ADORecordSet All tables, sorted alphabetically + */ + public function getTables() + { + $c_schema = $this->_schema; + $this->clean($c_schema); + $sql = "SELECT c.relname, pg_catalog.pg_get_userbyid(c.relowner) AS relowner, + pg_catalog.obj_description(c.oid, 'pg_class') AS relcomment, + reltuples::bigint as reltuples, + null tablespace, + 'N/A' as table_size + FROM pg_catalog.pg_class c + LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE c.relkind = 'r' + AND nspname='{$c_schema}' + ORDER BY c.relname"; + + return $this->selectSet($sql); + } + + /** * Protected method which alter a table * SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION. * @@ -276,28 +301,32 @@ class Postgres80 extends Postgres81 // Comment $status = $this->setComment('TABLE', '', $tblrs->fields['relname'], $comment); - if ($status != 0) { + + if (0 !== $status) { return -4; } // Owner $this->fieldClean($owner); $status = $this->alterTableOwner($tblrs, $owner); - if ($status != 0) { + + if (0 !== $status) { return -5; } // Tablespace $this->fieldClean($tablespace); $status = $this->alterTableTablespace($tblrs, $tablespace); - if ($status != 0) { + + if (0 !== $status) { return -6; } // Rename $this->fieldClean($name); $status = $this->alterTableName($tblrs, $name); - if ($status != 0) { + + if (0 !== $status) { return -3; } @@ -319,28 +348,31 @@ class Postgres80 extends Postgres81 protected function _alterView($vwrs, $name, $owner, $schema, $comment) { $type = 'VIEW'; - if ($vwrs->fields['relkind'] === 'm') { + + if ('m' === $vwrs->fields['relkind']) { $type = 'MATERIALIZED VIEW'; } /* $schema not supported in pg80- */ $this->fieldArrayClean($vwrs->fields); // Comment - if ($this->setComment($type, $vwrs->fields['relname'], '', $comment) != 0) { + if (0 !== $this->setComment($type, $vwrs->fields['relname'], '', $comment)) { return -4; } // Owner $this->fieldClean($owner); $status = $this->alterViewOwner($vwrs, $owner); - if ($status != 0) { + + if (0 !== $status) { return -5; } // Rename $this->fieldClean($name); $status = $this->alterViewName($vwrs, $name); - if ($status != 0) { + + if (0 !== $status) { return -3; } @@ -385,14 +417,16 @@ class Postgres80 extends Postgres81 // Comment $status = $this->setComment('SEQUENCE', $seqrs->fields['seqname'], '', $comment); - if ($status != 0) { + + if (0 !== $status) { return -4; } // Owner $this->fieldClean($owner); $status = $this->alterSequenceOwner($seqrs, $owner); - if ($status != 0) { + + if (0 !== $status) { return -5; } @@ -414,40 +448,19 @@ class Postgres80 extends Postgres81 $cycledvalue, null ); - if ($status != 0) { + + if (0 !== $status) { return -6; } // Rename $this->fieldClean($name); $status = $this->alterSequenceName($seqrs, $name); - if ($status != 0) { + + if (0 !== $status) { return -3; } return 0; } - - /** - * Return all tables in current database (and schema). - * - * @return int|\PHPPgAdmin\ADORecordSet All tables, sorted alphabetically - */ - public function getTables() - { - $c_schema = $this->_schema; - $this->clean($c_schema); - $sql = "SELECT c.relname, pg_catalog.pg_get_userbyid(c.relowner) AS relowner, - pg_catalog.obj_description(c.oid, 'pg_class') AS relcomment, - reltuples::bigint as reltuples, - null tablespace, - 'N/A' as table_size - FROM pg_catalog.pg_class c - LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace - WHERE c.relkind = 'r' - AND nspname='{$c_schema}' - ORDER BY c.relname"; - - return $this->selectSet($sql); - } } diff --git a/src/database/Postgres81.php b/src/database/Postgres81.php index 41b14a30..7f670cb4 100644 --- a/src/database/Postgres81.php +++ b/src/database/Postgres81.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,12 +14,11 @@ namespace PHPPgAdmin\Database; * PostgreSQL 8.1 support * * Id: Postgres81.php,v 1.21 2008/01/19 13:46:15 ioguix Exp $ - * - * @package PHPPgAdmin */ class Postgres81 extends Postgres82 { public $major_version = 8.1; + // List of all legal privileges that can be applied to different types // of objects. public $privlist = [ @@ -29,6 +31,7 @@ class Postgres81 extends Postgres82 'schema' => ['CREATE', 'USAGE', 'ALL PRIVILEGES'], 'tablespace' => ['CREATE', 'ALL PRIVILEGES'], ]; + // List of characters in acl lists and the privileges they // refer to. public $privmap = [ @@ -44,6 +47,7 @@ class Postgres81 extends Postgres82 'C' => 'CREATE', 'T' => 'TEMPORARY', ]; + // Array of allowed index types public $typIndexes = ['BTREE', 'RTREE', 'GIST', 'HASH']; @@ -69,7 +73,7 @@ class Postgres81 extends Postgres82 $clause = ''; } - if ($currentdatabase !== null) { + if (null !== $currentdatabase) { $this->clean($currentdatabase); $orderby = "ORDER BY pdb.datname = '{$currentdatabase}' DESC, pdb.datname"; } else { @@ -117,15 +121,17 @@ class Postgres81 extends Postgres82 //ignore $comment, not supported pre 8.2 $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } - if ($dbName != $newName) { + if ($dbName !== $newName) { $status = $this->alterDatabaseRename($dbName, $newName); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -133,7 +139,8 @@ class Postgres81 extends Postgres82 } $status = $this->alterDatabaseOwner($newName, $newOwner); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -2; @@ -215,9 +222,9 @@ class Postgres81 extends Postgres82 WHERE vacrelid = {$toid};"); $status = -1; // ini - if ($rs->recordCount() and ($rs->fields['vacrelid'] == $toid)) { + if ($rs->recordCount() && ($rs->fields['vacrelid'] === $toid)) { // table exists in pg_autovacuum, UPDATE - $sql = sprintf( + $sql = \sprintf( "UPDATE \"pg_catalog\".\"pg_autovacuum\" SET enabled = '%s', vac_base_thresh = %s, @@ -228,7 +235,7 @@ class Postgres81 extends Postgres82 vac_cost_limit = %s WHERE vacrelid = {$toid}; ", - ($_POST['autovacuum_enabled'] == 'on') ? 't' : 'f', + ('on' === $_POST['autovacuum_enabled']) ? 't' : 'f', $_POST['autovacuum_vacuum_threshold'], $_POST['autovacuum_vacuum_scale_factor'], $_POST['autovacuum_analyze_threshold'], @@ -239,11 +246,11 @@ class Postgres81 extends Postgres82 $status = $this->execute($sql); } else { // table doesn't exists in pg_autovacuum, INSERT - $sql = sprintf( + $sql = \sprintf( "INSERT INTO \"pg_catalog\".\"pg_autovacuum\" VALUES (%s, '%s', %s, %s, %s, %s, %s, %s)", $toid, - ($_POST['autovacuum_enabled'] == 'on') ? 't' : 'f', + ('on' === $_POST['autovacuum_enabled']) ? 't' : 'f', $_POST['autovacuum_vacuum_threshold'], $_POST['autovacuum_vacuum_scale_factor'], $_POST['autovacuum_analyze_threshold'], @@ -266,7 +273,7 @@ class Postgres81 extends Postgres82 */ public function getProcesses($database = null) { - if ($database === null) { + if (null === $database) { $sql = "SELECT datname, usename, procpid AS pid, current_query AS query, query_start, case when (select count(*) from pg_locks where pid=pg_stat_activity.procpid and granted is false) > 0 then 't' else 'f' end as waiting FROM pg_catalog.pg_stat_activity diff --git a/src/database/Postgres82.php b/src/database/Postgres82.php index addad441..86dc0e1e 100644 --- a/src/database/Postgres82.php +++ b/src/database/Postgres82.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,8 +14,6 @@ namespace PHPPgAdmin\Database; * PostgreSQL 8.2 support * * Id: Postgres82.php,v 1.10 2007/12/28 16:21:25 ioguix Exp $ - * - * @package PHPPgAdmin */ class Postgres82 extends Postgres83 { @@ -84,12 +85,13 @@ class Postgres82 extends Postgres83 public function alterSequenceName($seqrs, $name) { /* vars are cleaned in _alterSequence */ - if (!empty($name) && ($seqrs->fields['seqname'] != $name)) { + if (!empty($name) && ($seqrs->fields['seqname'] !== $name)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER TABLE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status == 0) { + + if (0 === $status) { $seqrs->fields['seqname'] = $name; } else { return $status; @@ -113,12 +115,13 @@ class Postgres82 extends Postgres83 { // Rename (only if name has changed) /* $vwrs and $name are cleaned in _alterView */ - if (!empty($name) && ($name != $vwrs->fields['relname'])) { + if (!empty($name) && ($name !== $vwrs->fields['relname'])) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER TABLE \"{$f_schema}\".\"{$vwrs->fields['relname']}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status == 0) { + + if (0 === $status) { $vwrs->fields['relname'] = $name; } else { return $status; @@ -223,7 +226,8 @@ class Postgres82 extends Postgres83 { // Begin a transaction $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -237,33 +241,36 @@ class Postgres82 extends Postgres83 $this->arrayClean($flags); $sql = 'CREATE'; + if ($replace) { $sql .= ' OR REPLACE'; } $sql .= " FUNCTION \"{$f_schema}\".\"{$funcname}\" ("; - if ($args != '') { + if ('' !== $args) { $sql .= $args; } // For some reason, the returns field cannot have quotes... $sql .= ') RETURNS '; + if ($setof) { $sql .= 'SETOF '; } $sql .= "{$returns} AS "; - if (is_array($definition)) { + if (\is_array($definition)) { $this->arrayClean($definition); - $sql .= "'".$definition[0]."'"; + $sql .= "'" . $definition[0] . "'"; + if ($definition[1]) { - $sql .= ",'".$definition[1]."'"; + $sql .= ",'" . $definition[1] . "'"; } } else { $this->clean($definition); - $sql .= "'".$definition."'"; + $sql .= "'" . $definition . "'"; } $sql .= " LANGUAGE \"{$language}\""; @@ -271,7 +278,7 @@ class Postgres82 extends Postgres83 // Add flags foreach ($flags as $v) { // Skip default flags - if ($v == '') { + if ('' === $v) { continue; } @@ -279,7 +286,8 @@ class Postgres82 extends Postgres83 } $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -287,7 +295,8 @@ class Postgres82 extends Postgres83 /* set the comment */ $status = $this->setComment('FUNCTION', "\"{$funcname}\"({$args})", null, $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -4; diff --git a/src/database/Postgres83.php b/src/database/Postgres83.php index fab378ce..62612e7a 100644 --- a/src/database/Postgres83.php +++ b/src/database/Postgres83.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,8 +14,6 @@ namespace PHPPgAdmin\Database; * PostgreSQL 8.3 support * * Id: Postgres82.php,v 1.10 2007/12/28 16:21:25 ioguix Exp $ - * - * @package PHPPgAdmin */ class Postgres83 extends Postgres84 { @@ -30,6 +31,7 @@ class Postgres83 extends Postgres84 'schema' => ['CREATE', 'USAGE', 'ALL PRIVILEGES'], 'tablespace' => ['CREATE', 'ALL PRIVILEGES'], ]; + // List of characters in acl lists and the privileges they // refer to. public $privmap = [ @@ -69,7 +71,7 @@ class Postgres83 extends Postgres84 $clause = ''; } - if ($currentdatabase != null) { + if (null !== $currentdatabase) { $this->clean($currentdatabase); $orderby = "ORDER BY pdb.datname = '{$currentdatabase}' DESC, pdb.datname"; } else { @@ -109,7 +111,7 @@ class Postgres83 extends Postgres84 { $sql = ''; - if ($table !== '') { + if ('' !== $table) { $this->clean($table); $c_schema = $this->_schema; $this->clean($c_schema); @@ -228,9 +230,9 @@ class Postgres83 extends Postgres84 WHERE vacrelid = {$toid};"); $status = -1; // ini - if ($rs->recordCount() and ($rs->fields['vacrelid'] == $toid)) { + if ($rs->recordCount() && ($rs->fields['vacrelid'] === $toid)) { // table exists in pg_autovacuum, UPDATE - $sql = sprintf( + $sql = \sprintf( "UPDATE \"pg_catalog\".\"pg_autovacuum\" SET enabled = '%s', vac_base_thresh = %s, @@ -243,7 +245,7 @@ class Postgres83 extends Postgres84 freeze_max_age = %s WHERE vacrelid = {$toid}; ", - ($_POST['autovacuum_enabled'] == 'on') ? 't' : 'f', + ('on' === $_POST['autovacuum_enabled']) ? 't' : 'f', $_POST['autovacuum_vacuum_threshold'], $_POST['autovacuum_vacuum_scale_factor'], $_POST['autovacuum_analyze_threshold'], @@ -256,11 +258,11 @@ class Postgres83 extends Postgres84 $status = $this->execute($sql); } else { // table doesn't exists in pg_autovacuum, INSERT - $sql = sprintf( + $sql = \sprintf( "INSERT INTO \"pg_catalog\".\"pg_autovacuum\" VALUES (%s, '%s', %s, %s, %s, %s, %s, %s, %s, %s )", $toid, - ($_POST['autovacuum_enabled'] == 'on') ? 't' : 'f', + ('on' === $_POST['autovacuum_enabled']) ? 't' : 'f', $_POST['autovacuum_vacuum_threshold'], $_POST['autovacuum_vacuum_scale_factor'], $_POST['autovacuum_analyze_threshold'], @@ -326,32 +328,32 @@ class Postgres83 extends Postgres84 ) { $sql = ''; /* vars are cleaned in _alterSequence */ - if (!empty($increment) && ($increment != $seqrs->fields['increment_by'])) { + if (!empty($increment) && ($increment !== $seqrs->fields['increment_by'])) { $sql .= " INCREMENT {$increment}"; } - if (!empty($minvalue) && ($minvalue != $seqrs->fields['min_value'])) { + if (!empty($minvalue) && ($minvalue !== $seqrs->fields['min_value'])) { $sql .= " MINVALUE {$minvalue}"; } - if (!empty($maxvalue) && ($maxvalue != $seqrs->fields['max_value'])) { + if (!empty($maxvalue) && ($maxvalue !== $seqrs->fields['max_value'])) { $sql .= " MAXVALUE {$maxvalue}"; } - if (!empty($restartvalue) && ($restartvalue != $seqrs->fields['last_value'])) { + if (!empty($restartvalue) && ($restartvalue !== $seqrs->fields['last_value'])) { $sql .= " RESTART {$restartvalue}"; } - if (!empty($cachevalue) && ($cachevalue != $seqrs->fields['cache_value'])) { + if (!empty($cachevalue) && ($cachevalue !== $seqrs->fields['cache_value'])) { $sql .= " CACHE {$cachevalue}"; } // toggle cycle yes/no - if (!is_null($cycledvalue)) { - $sql .= (!$cycledvalue ? ' NO ' : '').' CYCLE'; + if (null !== $cycledvalue) { + $sql .= (!$cycledvalue ? ' NO ' : '') . ' CYCLE'; } - if ($sql != '') { + if ('' !== $sql) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" {$sql}"; @@ -378,7 +380,7 @@ class Postgres83 extends Postgres84 // careful to avoid this generally as changing owner is a // superuser only function. /* vars are cleaned in _alterSequence */ - if (!empty($owner) && ($seqrs->fields['seqowner'] != $owner)) { + if (!empty($owner) && ($seqrs->fields['seqowner'] !== $owner)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER TABLE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" OWNER TO \"{$owner}\""; diff --git a/src/database/Postgres84.php b/src/database/Postgres84.php index 66f8d8de..6424310a 100644 --- a/src/database/Postgres84.php +++ b/src/database/Postgres84.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,8 +14,6 @@ namespace PHPPgAdmin\Database; * PostgreSQL 8.4 support * * Id: Postgres82.php,v 1.10 2007/12/28 16:21:25 ioguix Exp $ - * - * @package PHPPgAdmin */ class Postgres84 extends Postgres90 { @@ -88,8 +89,8 @@ class Postgres84 extends Postgres90 // Escape search term for ILIKE match $this->clean($term); $this->clean($filter); - $term = str_replace('_', '\_', $term); - $term = str_replace('%', '\%', $term); + $term = \str_replace('_', '\_', $term); + $term = \str_replace('%', '\%', $term); // Exclude system relations if necessary if (!$conf['show_system']) { @@ -104,7 +105,8 @@ class Postgres84 extends Postgres90 // Apply outer filter $sql = ''; - if ($filter != '') { + + if ('' !== $filter) { $sql = 'SELECT * FROM ('; } @@ -206,7 +208,7 @@ class Postgres84 extends Postgres90 "; } - if ($filter != '') { + if ('' !== $filter) { // We use like to make RULE, CONSTRAINT and COLUMN searches work $sql .= ") AS sub WHERE type LIKE '{$filter}%' "; } diff --git a/src/database/Postgres90.php b/src/database/Postgres90.php index 2f2616d7..6d85b222 100644 --- a/src/database/Postgres90.php +++ b/src/database/Postgres90.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -11,8 +14,6 @@ namespace PHPPgAdmin\Database; * PostgreSQL 9.0 support * * Id: Postgres82.php,v 1.10 2007/12/28 16:21:25 ioguix Exp $ - * - * @package PHPPgAdmin */ class Postgres90 extends Postgres91 { diff --git a/src/database/Postgres91.php b/src/database/Postgres91.php index 9c93bc97..cd8613f4 100644 --- a/src/database/Postgres91.php +++ b/src/database/Postgres91.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -13,8 +16,6 @@ namespace PHPPgAdmin\Database; /** * Id: Postgres82.php,v 1.10 2007/12/28 16:21:25 ioguix Exp $. - * - * @package PHPPgAdmin */ class Postgres91 extends Postgres92 { @@ -31,7 +32,7 @@ class Postgres91 extends Postgres92 */ public function getProcesses($database = null) { - if ($database === null) { + if (null === $database) { $sql = 'SELECT datname, usename, procpid AS pid, waiting, current_query AS query, query_start FROM pg_catalog.pg_stat_activity ORDER BY datname, usename, procpid'; diff --git a/src/database/Postgres92.php b/src/database/Postgres92.php index b7510952..a3ec9499 100644 --- a/src/database/Postgres92.php +++ b/src/database/Postgres92.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -12,7 +15,8 @@ namespace PHPPgAdmin\Database; */ class Postgres92 extends Postgres93 { - public $typIndexes = ['BTREE', 'RTREE', 'GIST', 'GIN', 'HASH']; + public $typIndexes = ['BTREE', 'RTREE', 'GIST', 'GIN', 'HASH']; + public $major_version = 9.2; /** @@ -24,7 +28,7 @@ class Postgres92 extends Postgres93 */ public function getProcesses($database = null) { - if ($database === null) { + if (null === $database) { $sql = "SELECT datname, usename, pid, waiting, state_change as query_start, case when state='idle in transaction' then '<IDLE> in transaction' when state = 'idle' then '<IDLE>' else query end as query FROM pg_catalog.pg_stat_activity diff --git a/src/database/Postgres93.php b/src/database/Postgres93.php index e7104eeb..8ad78a29 100644 --- a/src/database/Postgres93.php +++ b/src/database/Postgres93.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; diff --git a/src/database/Postgres94.php b/src/database/Postgres94.php index 85181fe9..ef634be2 100644 --- a/src/database/Postgres94.php +++ b/src/database/Postgres94.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -12,6 +15,7 @@ namespace PHPPgAdmin\Database; */ class Postgres94 extends Postgres95 { - public $typIndexes = ['BTREE', 'RTREE', 'GIST', 'GIN', 'HASH', 'SP-GIST']; + public $typIndexes = ['BTREE', 'RTREE', 'GIST', 'GIN', 'HASH', 'SP-GIST']; + public $major_version = 9.4; } diff --git a/src/database/Postgres95.php b/src/database/Postgres95.php index 4e1b0498..ca9f2505 100644 --- a/src/database/Postgres95.php +++ b/src/database/Postgres95.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -12,6 +15,7 @@ namespace PHPPgAdmin\Database; */ class Postgres95 extends Postgres96 { - public $typIndexes = ['BTREE', 'BRIN', 'RTREE', 'GIST', 'GIN', 'HASH']; + public $typIndexes = ['BTREE', 'BRIN', 'RTREE', 'GIST', 'GIN', 'HASH']; + public $major_version = 9.5; } diff --git a/src/database/Postgres96.php b/src/database/Postgres96.php index 46b771c2..fc3a20d0 100644 --- a/src/database/Postgres96.php +++ b/src/database/Postgres96.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database; @@ -12,7 +15,8 @@ namespace PHPPgAdmin\Database; */ class Postgres96 extends Postgres { - public $typIndexes = ['BTREE', 'BRIN', 'RTREE', 'GIST', 'GIN', 'HASH', 'SP-GIST']; + public $typIndexes = ['BTREE', 'BRIN', 'RTREE', 'GIST', 'GIN', 'HASH', 'SP-GIST']; + public $major_version = 9.6; // Administration functions @@ -26,7 +30,7 @@ class Postgres96 extends Postgres */ public function getProcesses($database = null) { - if ($database === null) { + if (null === $database) { $sql = "SELECT datid, datname, pid, usename, application_name, client_addr, state, wait_event_type, wait_event, state_change as query_start, CASE WHEN state='active' THEN query @@ -79,17 +83,19 @@ class Postgres96 extends Postgres $this->fieldArrayClean($groups); $sql = "CREATE USER \"{$username}\""; - if ($password != '') { + + if ('' !== $password) { $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'"; } $sql .= $createdb ? ' CREATEDB' : ' NOCREATEDB'; $sql .= $createrole ? ' CREATEROLE' : ' NOCREATEROLE'; - if (is_array($groups) && sizeof($groups) > 0) { - $sql .= ' IN GROUP "'.join('", "', $groups).'"'; + + if (\is_array($groups) && 0 < \count($groups)) { + $sql .= ' IN GROUP "' . \implode('", "', $groups) . '"'; } - if ($expiry != '') { + if ('' !== $expiry) { $sql .= " VALID UNTIL '{$expiry}'"; } else { $sql .= " VALID UNTIL 'infinity'"; diff --git a/src/database/databasetraits/AggregateTrait.php b/src/database/databasetraits/AggregateTrait.php index ab9c7f44..bf7ca655 100644 --- a/src/database/databasetraits/AggregateTrait.php +++ b/src/database/databasetraits/AggregateTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -40,29 +43,32 @@ trait AggregateTrait $this->beginTransaction(); $sql = "CREATE AGGREGATE \"{$f_schema}\".\"{$name}\" (BASETYPE = \"{$basetype}\", SFUNC = \"{$sfunc}\", STYPE = \"{$stype}\""; - if (trim($ffunc) != '') { + + if ('' !== \trim($ffunc)) { $sql .= ", FINALFUNC = \"{$ffunc}\""; } - if (trim($initcond) != '') { + if ('' !== \trim($initcond)) { $sql .= ", INITCOND = \"{$initcond}\""; } - if (trim($sortop) != '') { + if ('' !== \trim($sortop)) { $sql .= ", SORTOP = \"{$sortop}\""; } $sql .= ')'; $status = $this->execute($sql); + if ($status) { $this->rollbackTransaction(); return -1; } - if (trim($comment) != '') { + if ('' !== \trim($comment)) { $status = $this->setComment('AGGREGATE', $name, '', $comment, $basetype); + if ($status) { $this->rollbackTransaction(); @@ -90,6 +96,7 @@ trait AggregateTrait $this->fieldClean($aggrtype); $sql = "DROP AGGREGATE \"{$f_schema}\".\"{$aggrname}\" (\"{$aggrtype}\")"; + if ($cascade) { $sql .= ' CASCADE'; } @@ -121,11 +128,11 @@ trait AggregateTrait FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_user u, pg_catalog.pg_aggregate a WHERE n.oid = p.pronamespace AND p.proowner=u.usesysid AND p.oid=a.aggfnoid AND p.proisagg AND n.nspname='{$c_schema}' - AND p.proname='".$name."' + AND p.proname='" . $name . "' AND CASE p.proargtypes[0] WHEN 'pg_catalog.\"any\"'::pg_catalog.regtype THEN '' ELSE pg_catalog.format_type(p.proargtypes[0], NULL) - END ='".$basetype."'"; + END ='" . $basetype . "'"; return $this->selectSet($sql); } @@ -187,9 +194,10 @@ trait AggregateTrait $this->beginTransaction(); // Change the owner, if it has changed - if ($aggrowner != $newaggrowner) { + if ($aggrowner !== $newaggrowner) { $status = $this->changeAggregateOwner($aggrname, $aggrtype, $newaggrowner); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -197,8 +205,9 @@ trait AggregateTrait } // Set the comment, if it has changed - if ($aggrcomment != $newaggrcomment) { + if ($aggrcomment !== $newaggrcomment) { $status = $this->setComment('AGGREGATE', $aggrname, '', $newaggrcomment, $aggrtype); + if ($status) { $this->rollbackTransaction(); @@ -207,9 +216,10 @@ trait AggregateTrait } // Change the schema, if it has changed - if ($aggrschema != $newaggrschema) { + if ($aggrschema !== $newaggrschema) { $status = $this->changeAggregateSchema($aggrname, $aggrtype, $newaggrschema); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -217,9 +227,10 @@ trait AggregateTrait } // Rename the aggregate, if it has changed - if ($aggrname != $newaggrname) { + if ($aggrname !== $newaggrname) { $status = $this->renameAggregate($newaggrschema, $aggrname, $aggrtype, $newaggrname); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -4; @@ -282,7 +293,7 @@ trait AggregateTrait public function renameAggregate($aggrschema, $aggrname, $aggrtype, $newaggrname) { /* this function is called from alterAggregate where params are cleaned */ - $sql = "ALTER AGGREGATE \"{$aggrschema}\"".'.'."\"{$aggrname}\" (\"{$aggrtype}\") RENAME TO \"{$newaggrname}\""; + $sql = "ALTER AGGREGATE \"{$aggrschema}\"" . '.' . "\"{$aggrname}\" (\"{$aggrtype}\") RENAME TO \"{$newaggrname}\""; return $this->execute($sql); } diff --git a/src/database/databasetraits/ColumnTrait.php b/src/database/databasetraits/ColumnTrait.php index 017f93e2..fb32cf61 100644 --- a/src/database/databasetraits/ColumnTrait.php +++ b/src/database/databasetraits/ColumnTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -34,7 +37,7 @@ trait ColumnTrait $this->clean($type); $this->clean($length); - if ($length == '') { + if ('' === $length) { $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD COLUMN \"{$column}\" {$type}"; } else { switch ($type) { @@ -42,13 +45,13 @@ trait ColumnTrait // time zone types case 'timestamp with time zone': case 'timestamp without time zone': - $qual = substr($type, 9); + $qual = \mb_substr($type, 9); $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD COLUMN \"{$column}\" timestamp({$length}){$qual}"; break; case 'time with time zone': case 'time without time zone': - $qual = substr($type, 4); + $qual = \mb_substr($type, 4); $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD COLUMN \"{$column}\" time({$length}){$qual}"; break; @@ -70,25 +73,28 @@ trait ColumnTrait } // DEFAULT clause - if ($default != '') { - $sql .= ' DEFAULT '.$default; + if ('' !== $default) { + $sql .= ' DEFAULT ' . $default; } } $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return [-1, $sql]; } $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return [-1, $sql]; } $status = $this->setComment('COLUMN', $column, $table, $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return [-1, $sql]; @@ -135,16 +141,18 @@ trait ColumnTrait $status = $this->beginTransaction(); $sql = ''; $sqlrename = ''; - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return [-6, $sql]; } // Rename the column, if it has been changed - if ($column != $name) { + if ($column !== $name) { list($status, $sqlrename) = $this->renameColumn($table, $column, $name); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return [-4, $sql]; @@ -159,13 +167,13 @@ trait ColumnTrait $toAlter = []; // Create the command for changing nullability - if ($notnull != $oldnotnull) { - $toAlter[] = "ALTER COLUMN \"{$name}\" ".($notnull ? 'SET' : 'DROP').' NOT NULL'; + if ($notnull !== $oldnotnull) { + $toAlter[] = "ALTER COLUMN \"{$name}\" " . ($notnull ? 'SET' : 'DROP') . ' NOT NULL'; } // Add default, if it has changed - if ($default != $olddefault) { - if ($default == '') { + if ($default !== $olddefault) { + if ('' === $default) { $toAlter[] = "ALTER COLUMN \"{$name}\" DROP DEFAULT"; } else { $toAlter[] = "ALTER COLUMN \"{$name}\" SET DEFAULT {$default}"; @@ -173,7 +181,7 @@ trait ColumnTrait } // Add type, if it has changed - if ($length == '') { + if ('' === $length) { $ftype = $type; } else { switch ($type) { @@ -181,13 +189,13 @@ trait ColumnTrait // time zone types case 'timestamp with time zone': case 'timestamp without time zone': - $qual = substr($type, 9); + $qual = \mb_substr($type, 9); $ftype = "timestamp({$length}){$qual}"; break; case 'time with time zone': case 'time without time zone': - $qual = substr($type, 4); + $qual = \mb_substr($type, 4); $ftype = "time({$length}){$qual}"; break; @@ -201,7 +209,7 @@ trait ColumnTrait $ftype .= '[]'; } - if ($ftype != $oldtype) { + if ($ftype !== $oldtype) { $toAlter[] = "ALTER COLUMN \"{$name}\" TYPE {$ftype}"; } @@ -209,10 +217,11 @@ trait ColumnTrait if (!empty($toAlter)) { // Initialise an empty SQL string $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" " - .implode(',', $toAlter); + . \implode(',', $toAlter); $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return [-1, $sql]; @@ -221,13 +230,14 @@ trait ColumnTrait // Update the comment on the column $status = $this->setComment('COLUMN', $name, $table, $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return [-5, $sql]; } - return [$this->endTransaction(), $sqlrename.'<br>'.$sql]; + return [$this->endTransaction(), $sqlrename . '<br>' . $sql]; } /** @@ -291,7 +301,7 @@ trait ColumnTrait $this->fieldClean($table); $this->fieldClean($column); - $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ALTER COLUMN \"{$column}\" ".($state ? 'DROP' : 'SET').' NOT NULL'; + $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ALTER COLUMN \"{$column}\" " . ($state ? 'DROP' : 'SET') . ' NOT NULL'; return $this->execute($sql); } @@ -313,6 +323,7 @@ trait ColumnTrait $this->fieldClean($column); $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" DROP COLUMN \"{$column}\""; + if ($cascade) { $sql .= ' CASCADE'; } diff --git a/src/database/databasetraits/DatabaseTrait.php b/src/database/databasetraits/DatabaseTrait.php index 8868ec80..38e1637b 100644 --- a/src/database/databasetraits/DatabaseTrait.php +++ b/src/database/databasetraits/DatabaseTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -35,20 +38,22 @@ trait DatabaseTrait $this->clean($username); if (empty($username)) { - $val = pg_parameter_status($this->conn->_connectionID, 'is_superuser'); - if ($val !== false) { - return $val == 'on'; + $val = \pg_parameter_status($this->conn->_connectionID, 'is_superuser'); + + if (false !== $val) { + return 'on' === $val; } } $sql = "SELECT usesuper FROM pg_user WHERE usename='{$username}'"; $usesuper = $this->selectField($sql, 'usesuper'); - if ($usesuper == -1) { + + if (-1 === $usesuper) { return false; } - return $usesuper == 't'; + return 't' === $usesuper; } /** @@ -60,7 +65,7 @@ trait DatabaseTrait */ public function analyzeDB($table = '') { - if ($table != '') { + if ('' !== $table) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $this->fieldClean($table); @@ -109,6 +114,7 @@ trait DatabaseTrait } else { $clause = ''; } + if (isset($server_info['useonlydefaultdb']) && $server_info['useonlydefaultdb']) { $currentdatabase = $server_info['defaultdb']; $clause .= " AND pdb.datname = '{$currentdatabase}' "; @@ -117,11 +123,11 @@ trait DatabaseTrait if (isset($server_info['hiddendbs']) && $server_info['hiddendbs']) { $hiddendbs = $server_info['hiddendbs']; - $not_in = "('".implode("','", $hiddendbs)."')"; + $not_in = "('" . \implode("','", $hiddendbs) . "')"; $clause .= " AND pdb.datname NOT IN {$not_in} "; } - if ($currentdatabase != null) { + if (null !== $currentdatabase) { $this->clean($currentdatabase); $orderby = "ORDER BY pdb.datname = '{$currentdatabase}' DESC, pdb.datname"; } else { @@ -201,7 +207,7 @@ trait DatabaseTrait */ public function getDatabaseEncoding() { - return pg_parameter_status($this->conn->_connectionID, 'server_encoding'); + return \pg_parameter_status($this->conn->_connectionID, 'server_encoding'); } /** @@ -235,30 +241,32 @@ trait DatabaseTrait $sql = "CREATE DATABASE \"{$database}\" WITH TEMPLATE=\"{$template}\""; - if ($encoding != '') { + if ('' !== $encoding) { $sql .= " ENCODING='{$encoding}'"; } - if ($lc_collate != '') { + if ('' !== $lc_collate) { $sql .= " LC_COLLATE='{$lc_collate}'"; } - if ($lc_ctype != '') { + if ('' !== $lc_ctype) { $sql .= " LC_CTYPE='{$lc_ctype}'"; } - if ($tablespace != '' && $this->hasTablespaces()) { + if ('' !== $tablespace && $this->hasTablespaces()) { $sql .= " TABLESPACE \"{$tablespace}\""; } $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { return -1; } - if ($comment != '' && $this->hasSharedComments()) { + if ('' !== $comment && $this->hasSharedComments()) { $status = $this->setComment('DATABASE', $database, '', $comment); - if ($status != 0) { + + if (0 !== $status) { return -2; } } @@ -295,15 +303,17 @@ trait DatabaseTrait public function alterDatabase($dbName, $newName, $newOwner = '', $comment = '') { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } - if ($dbName != $newName) { + if ($dbName !== $newName) { $status = $this->alterDatabaseRename($dbName, $newName); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -311,9 +321,10 @@ trait DatabaseTrait $dbName = $newName; } - if ($newOwner != '') { + if ('' !== $newOwner) { $status = $this->alterDatabaseOwner($newName, $newOwner); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -2; @@ -322,7 +333,8 @@ trait DatabaseTrait $this->fieldClean($dbName); $status = $this->setComment('DATABASE', $dbName, '', $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -4; @@ -345,7 +357,7 @@ trait DatabaseTrait $this->fieldClean($oldName); $this->fieldClean($newName); - if ($oldName != $newName) { + if ($oldName !== $newName) { $sql = "ALTER DATABASE \"{$oldName}\" RENAME TO \"{$newName}\""; return $this->execute($sql); @@ -382,7 +394,7 @@ trait DatabaseTrait */ public function getPreparedXacts($database = null) { - if ($database === null) { + if (null === $database) { $sql = 'SELECT * FROM pg_prepared_xacts'; } else { $this->clean($database); @@ -402,7 +414,7 @@ trait DatabaseTrait */ public function getProcesses($database = null) { - if ($database === null) { + if (null === $database) { $sql = "SELECT datname, usename, pid, waiting, state_change as query_start, case when state='idle in transaction' then '<IDLE> in transaction' when state = 'idle' then '<IDLE>' else query end as query FROM pg_catalog.pg_stat_activity @@ -466,9 +478,9 @@ trait DatabaseTrait // Clean $pid = (int) $pid; - if ($signal == 'CANCEL') { + if ('CANCEL' === $signal) { $sql = "SELECT pg_catalog.pg_cancel_backend({$pid}) AS val"; - } elseif ($signal == 'KILL') { + } elseif ('KILL' === $signal) { $sql = "SELECT pg_catalog.pg_terminate_backend({$pid}) AS val"; } else { return -1; @@ -477,11 +489,11 @@ trait DatabaseTrait // Execute the query $val = $this->selectField($sql, 'val'); - if ($val === 'f') { + if ('f' === $val) { return -1; } - if ($val === 't') { + if ('t' === $val) { return 0; } @@ -501,6 +513,7 @@ trait DatabaseTrait public function vacuumDB($table = '', $analyze = false, $full = false, $freeze = false) { $sql = 'VACUUM'; + if ($full) { $sql .= ' FULL'; } @@ -513,7 +526,7 @@ trait DatabaseTrait $sql .= ' ANALYZE'; } - if ($table != '') { + if ('' !== $table) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $this->fieldClean($table); @@ -549,6 +562,7 @@ trait DatabaseTrait ); $ret = []; + while (!$_defaults->EOF) { $ret[$_defaults->fields['name']] = $_defaults->fields['setting']; $_defaults->moveNext(); diff --git a/src/database/databasetraits/DomainTrait.php b/src/database/databasetraits/DomainTrait.php index 90b030d3..39c9e729 100644 --- a/src/database/databasetraits/DomainTrait.php +++ b/src/database/databasetraits/DomainTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -126,7 +129,7 @@ trait DomainTrait $sql = "CREATE DOMAIN \"{$f_schema}\".\"{$domain}\" AS "; - if ($length == '') { + if ('' === $length) { $sql .= $type; } else { switch ($type) { @@ -134,13 +137,13 @@ trait DomainTrait // time zone types case 'timestamp with time zone': case 'timestamp without time zone': - $qual = substr($type, 9); + $qual = \mb_substr($type, 9); $sql .= "timestamp({$length}){$qual}"; break; case 'time with time zone': case 'time without time zone': - $qual = substr($type, 4); + $qual = \mb_substr($type, 4); $sql .= "time({$length}){$qual}"; break; @@ -158,11 +161,11 @@ trait DomainTrait $sql .= ' NOT NULL'; } - if ($default != '') { + if ('' !== $default) { $sql .= " DEFAULT {$default}"; } - if ($this->hasDomainConstraints() && $check != '') { + if ($this->hasDomainConstraints() && '' !== $check) { $sql .= " CHECK ({$check})"; } @@ -187,21 +190,23 @@ trait DomainTrait $this->fieldClean($domowner); $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } // Default - if ($domdefault == '') { + if ('' === $domdefault) { $sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" DROP DEFAULT"; } else { $sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" SET DEFAULT {$domdefault}"; } $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -2; @@ -215,7 +220,8 @@ trait DomainTrait } $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -225,7 +231,8 @@ trait DomainTrait $sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" OWNER TO \"{$domowner}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -4; @@ -249,6 +256,7 @@ trait DomainTrait $this->fieldClean($domain); $sql = "DROP DOMAIN \"{$f_schema}\".\"{$domain}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -273,7 +281,8 @@ trait DomainTrait $this->fieldClean($name); $sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" ADD "; - if ($name != '') { + + if ('' !== $name) { $sql .= "CONSTRAINT \"{$name}\" "; } @@ -299,6 +308,7 @@ trait DomainTrait $this->fieldClean($constraint); $sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" DROP CONSTRAINT \"{$constraint}\""; + if ($cascade) { $sql .= ' CASCADE'; } diff --git a/src/database/databasetraits/FtsTrait.php b/src/database/databasetraits/FtsTrait.php index 2df56e3a..080d39f7 100644 --- a/src/database/databasetraits/FtsTrait.php +++ b/src/database/databasetraits/FtsTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -32,38 +35,43 @@ trait FtsTrait $this->fieldClean($cfgname); $sql = "CREATE TEXT SEARCH CONFIGURATION \"{$f_schema}\".\"{$cfgname}\" ("; - if ($parser != '') { + + if ('' !== $parser) { $this->fieldClean($parser['schema']); $this->fieldClean($parser['parser']); $parser = "\"{$parser['schema']}\".\"{$parser['parser']}\""; $sql .= " PARSER = {$parser}"; } - if ($template != '') { + + if ('' !== $template) { $this->fieldClean($template['schema']); $this->fieldClean($template['name']); $sql .= " COPY = \"{$template['schema']}\".\"{$template['name']}\""; } $sql .= ')'; - if ($comment != '') { + if ('' !== $comment) { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } } // Create the FTS configuration $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } // Set the comment - if ($comment != '') { + if ('' !== $comment) { $status = $this->setComment('TEXT SEARCH CONFIGURATION', $cfgname, '', $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -251,6 +259,7 @@ trait FtsTrait $this->fieldClean($ftscfg); $sql = "DROP TEXT SEARCH CONFIGURATION \"{$f_schema}\".\"{$ftscfg}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -276,6 +285,7 @@ trait FtsTrait $sql = 'DROP TEXT SEARCH DICTIONARY'; $sql .= " \"{$f_schema}\".\"{$ftsdict}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -295,7 +305,8 @@ trait FtsTrait public function updateFtsConfiguration($cfgname, $comment, $name) { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -304,21 +315,23 @@ trait FtsTrait $this->fieldClean($cfgname); $status = $this->setComment('TEXT SEARCH CONFIGURATION', $cfgname, '', $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } // Only if the name has changed - if ($name != $cfgname) { + if ($name !== $cfgname) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $this->fieldClean($name); $sql = "ALTER TEXT SEARCH CONFIGURATION \"{$f_schema}\".\"{$cfgname}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -359,13 +372,15 @@ trait FtsTrait $this->fieldClean($option); $sql = 'CREATE TEXT SEARCH'; + if ($isTemplate) { $sql .= " TEMPLATE \"{$f_schema}\".\"{$dictname}\" ("; - if ($lexize != '') { + + if ('' !== $lexize) { $sql .= " LEXIZE = {$lexize}"; } - if ($init != '') { + if ('' !== $init) { $sql .= ", INIT = {$init}"; } @@ -373,14 +388,16 @@ trait FtsTrait $whatToComment = 'TEXT SEARCH TEMPLATE'; } else { $sql .= " DICTIONARY \"{$f_schema}\".\"{$dictname}\" ("; - if ($template != '') { + + if ('' !== $template) { $this->fieldClean($template['schema']); $this->fieldClean($template['name']); $template = "\"{$template['schema']}\".\"{$template['name']}\""; $sql .= " TEMPLATE = {$template}"; } - if ($option != '') { + + if ('' !== $option) { $sql .= ", {$option}"; } @@ -390,25 +407,28 @@ trait FtsTrait /* if comment, begin a transaction to * run both commands */ - if ($comment != '') { + if ('' !== $comment) { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } } // Create the FTS dictionary $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } // Set the comment - if ($comment != '') { + if ('' !== $comment) { $status = $this->setComment($whatToComment, $dictname, '', $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -432,7 +452,8 @@ trait FtsTrait public function updateFtsDictionary($dictname, $comment, $name) { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -440,21 +461,23 @@ trait FtsTrait $this->fieldClean($dictname); $status = $this->setComment('TEXT SEARCH DICTIONARY', $dictname, '', $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } // Only if the name has changed - if ($name != $dictname) { + if ($name !== $dictname) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $this->fieldClean($name); $sql = "ALTER TEXT SEARCH DICTIONARY \"{$f_schema}\".\"{$dictname}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -510,7 +533,7 @@ trait FtsTrait */ public function changeFtsMapping($ftscfg, $mapping, $action, $dictname = null) { - if (count($mapping) > 0) { + if (0 < \count($mapping)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $this->fieldClean($ftscfg); @@ -533,8 +556,9 @@ trait FtsTrait } $sql = "ALTER TEXT SEARCH CONFIGURATION \"{$f_schema}\".\"{$ftscfg}\" {$whatToDo} MAPPING FOR "; - $sql .= implode(',', $mapping); - if ($action != 'drop' && !empty($dictname)) { + $sql .= \implode(',', $mapping); + + if ('drop' !== $action && !empty($dictname)) { $sql .= " WITH {$dictname}"; } diff --git a/src/database/databasetraits/FunctionTrait.php b/src/database/databasetraits/FunctionTrait.php index d6e5eee6..7f1bb230 100644 --- a/src/database/databasetraits/FunctionTrait.php +++ b/src/database/databasetraits/FunctionTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -83,11 +86,11 @@ trait FunctionTrait $temp = []; // Volatility - if ($f['provolatile'] == 'v') { + if ('v' === $f['provolatile']) { $temp[] = 'VOLATILE'; - } elseif ($f['provolatile'] == 'i') { + } elseif ('i' === $f['provolatile']) { $temp[] = 'IMMUTABLE'; - } elseif ($f['provolatile'] == 's') { + } elseif ('s' === $f['provolatile']) { $temp[] = 'STABLE'; } else { return -1; @@ -95,6 +98,7 @@ trait FunctionTrait // Null handling $f['proisstrict'] = $this->phpBool($f['proisstrict']); + if ($f['proisstrict']) { $temp[] = 'RETURNS NULL ON NULL INPUT'; } else { @@ -103,6 +107,7 @@ trait FunctionTrait // Security $f['prosecdef'] = $this->phpBool($f['prosecdef']); + if ($f['prosecdef']) { $temp[] = 'SECURITY DEFINER'; } else { @@ -152,7 +157,8 @@ trait FunctionTrait ) { // Begin a transaction $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -160,7 +166,8 @@ trait FunctionTrait // Replace the existing function $status = $this->createFunction($funcname, $args, $returns, $definition, $language, $flags, $setof, $cost, $rows, $comment, true); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return $status; @@ -172,10 +179,11 @@ trait FunctionTrait // Rename the function, if necessary $this->fieldClean($newname); /* $funcname is escaped in createFunction */ - if ($funcname != $newname) { + if ($funcname !== $newname) { $sql = "ALTER FUNCTION \"{$f_schema}\".\"{$funcname}\"({$args}) RENAME TO \"{$newname}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -5; @@ -187,10 +195,12 @@ trait FunctionTrait // Alter the owner, if necessary if ($this->hasFunctionAlterOwner()) { $this->fieldClean($newown); - if ($funcown != $newown) { + + if ($funcown !== $newown) { $sql = "ALTER FUNCTION \"{$f_schema}\".\"{$funcname}\"({$args}) OWNER TO \"{$newown}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -6; @@ -202,10 +212,11 @@ trait FunctionTrait if ($this->hasFunctionAlterSchema()) { $this->fieldClean($newschema); /* $funcschema is escaped in createFunction */ - if ($funcschema != $newschema) { + if ($funcschema !== $newschema) { $sql = "ALTER FUNCTION \"{$f_schema}\".\"{$funcname}\"({$args}) SET SCHEMA \"{$newschema}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -7; @@ -238,7 +249,8 @@ trait FunctionTrait { // Begin a transaction $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -254,33 +266,36 @@ trait FunctionTrait $this->fieldClean($f_schema); $sql = 'CREATE'; + if ($replace) { $sql .= ' OR REPLACE'; } $sql .= " FUNCTION \"{$f_schema}\".\"{$funcname}\" ("; - if ($args != '') { + if ('' !== $args) { $sql .= $args; } // For some reason, the returns field cannot have quotes... $sql .= ') RETURNS '; + if ($setof) { $sql .= 'SETOF '; } $sql .= "{$returns} AS "; - if (is_array($definition)) { + if (\is_array($definition)) { $this->arrayClean($definition); - $sql .= "'".$definition[0]."'"; + $sql .= "'" . $definition[0] . "'"; + if ($definition[1]) { - $sql .= ",'".$definition[1]."'"; + $sql .= ",'" . $definition[1] . "'"; } } else { $this->clean($definition); - $sql .= "'".$definition."'"; + $sql .= "'" . $definition . "'"; } $sql .= " LANGUAGE \"{$language}\""; @@ -290,14 +305,14 @@ trait FunctionTrait $sql .= " COST {$cost}"; } - if ($rows != 0) { + if (0 !== $rows) { $sql .= " ROWS {$rows}"; } // Add flags foreach ($flags as $v) { // Skip default flags - if ($v == '') { + if ('' === $v) { continue; } @@ -305,7 +320,8 @@ trait FunctionTrait } $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -313,7 +329,8 @@ trait FunctionTrait /* set the comment */ $status = $this->setComment('FUNCTION', "\"{$funcname}\"({$args})", null, $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -4; @@ -339,6 +356,7 @@ trait FunctionTrait $this->fieldClean($fn->fields['proname']); $sql = "DROP FUNCTION \"{$f_schema}\".\"{$fn->fields['proname']}\"({$fn->fields['proarguments']})"; + if ($cascade) { $sql .= ' CASCADE'; } diff --git a/src/database/databasetraits/HasTrait.php b/src/database/databasetraits/HasTrait.php index c21fe877..f904b573 100644 --- a/src/database/databasetraits/HasTrait.php +++ b/src/database/databasetraits/HasTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -17,10 +20,13 @@ trait HasTrait public $platform = 'UNKNOWN'; public $major_version = 9.6; + // Max object name length public $_maxNameLen = 63; + // Store the current schema public $_schema; + // Map of database encoding names to HTTP encoding names. If a // database encoding does not appear in this list, then its HTTP // encoding name is the same as its database encoding name. @@ -60,14 +66,21 @@ trait HasTrait 'WIN1256' => 'CP1256', 'WIN1258' => 'CP1258', ]; + public $defaultprops = ['', '', '']; + // Extra "magic" types. BIGSERIAL was added in PostgreSQL 7.2. public $extraTypes = ['SERIAL', 'BIGSERIAL']; + // Foreign key stuff. First element MUST be the default. - public $fkactions = ['NO ACTION', 'RESTRICT', 'CASCADE', 'SET NULL', 'SET DEFAULT']; + public $fkactions = ['NO ACTION', 'RESTRICT', 'CASCADE', 'SET NULL', 'SET DEFAULT']; + public $fkdeferrable = ['NOT DEFERRABLE', 'DEFERRABLE']; - public $fkinitial = ['INITIALLY IMMEDIATE', 'INITIALLY DEFERRED']; - public $fkmatches = ['MATCH SIMPLE', 'MATCH FULL']; + + public $fkinitial = ['INITIALLY IMMEDIATE', 'INITIALLY DEFERRED']; + + public $fkmatches = ['MATCH SIMPLE', 'MATCH FULL']; + // Function properties public $funcprops = [ ['', 'VOLATILE', 'IMMUTABLE', 'STABLE'], @@ -77,13 +90,16 @@ trait HasTrait // Default help URL public $help_base; + // Help sub pages public $help_page; + // Name of id column public $id = 'oid'; // Supported join operations for use with view wizard public $joinOps = ['INNER JOIN' => 'INNER JOIN', 'LEFT JOIN' => 'LEFT JOIN', 'RIGHT JOIN' => 'RIGHT JOIN', 'FULL JOIN' => 'FULL JOIN']; + // Map of internal language name to syntax highlighting name public $langmap = [ 'sql' => 'SQL', @@ -111,6 +127,7 @@ trait HasTrait 'plruby' => 'Ruby', 'plrubyu' => 'Ruby', ]; + // Predefined size types public $predefined_size_types = [ 'abstime', @@ -153,6 +170,7 @@ trait HasTrait 'void', 'xid', ]; + // List of all legal privileges that can be applied to different types // of objects. public $privlist = [ @@ -166,6 +184,7 @@ trait HasTrait 'tablespace' => ['CREATE', 'ALL PRIVILEGES'], 'column' => ['SELECT', 'INSERT', 'UPDATE', 'REFERENCES', 'ALL PRIVILEGES'], ]; + // List of characters in acl lists and the privileges they // refer to. public $privmap = [ @@ -183,8 +202,10 @@ trait HasTrait 'T' => 'TEMPORARY', 'c' => 'CONNECT', ]; + // Rule action types public $rule_events = ['SELECT', 'INSERT', 'UPDATE', 'DELETE']; + // Select operators public $selectOps = [ '=' => 'i', @@ -224,6 +245,7 @@ trait HasTrait '@> plainto_tsquery' => 't', '<@ plainto_tsquery' => 't', ]; + // Array of allowed trigger events public $triggerEvents = [ 'INSERT', @@ -234,20 +256,28 @@ trait HasTrait 'DELETE OR UPDATE', 'INSERT OR DELETE OR UPDATE', ]; + // When to execute the trigger public $triggerExecTimes = ['BEFORE', 'AFTER']; + // How often to execute the trigger public $triggerFrequency = ['ROW', 'STATEMENT']; + // Array of allowed type alignments public $typAligns = ['char', 'int2', 'int4', 'double']; + // The default type alignment public $typAlignDef = 'int4'; + // Default index type public $typIndexDef = 'BTREE'; + // Array of allowed index types public $typIndexes = ['BTREE', 'RTREE', 'GIST', 'GIN', 'HASH']; + // Array of allowed type storage attributes public $typStorages = ['plain', 'external', 'extended', 'main']; + // The default type storage public $typStorageDef = 'plain'; diff --git a/src/database/databasetraits/IndexTrait.php b/src/database/databasetraits/IndexTrait.php index 1c47afd4..28b0d095 100644 --- a/src/database/databasetraits/IndexTrait.php +++ b/src/database/databasetraits/IndexTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -34,7 +37,7 @@ trait IndexTrait $v = $this->selectSet($sql); - return !($v->recordCount() == 0); + return !(0 === $v->recordCount()); } /** @@ -70,21 +73,21 @@ trait IndexTrait $sql .= " ON \"{$f_schema}\".\"{$table}\" USING {$type} "; - if (is_array($columns)) { + if (\is_array($columns)) { $this->arrayClean($columns); - $sql .= '("'.implode('","', $columns).'")'; + $sql .= '("' . \implode('","', $columns) . '")'; } else { - $sql .= '('.$columns.')'; + $sql .= '(' . $columns . ')'; } // Tablespace - if ($this->hasTablespaces() && $tablespace != '') { + if ($this->hasTablespaces() && '' !== $tablespace) { $this->fieldClean($tablespace); $sql .= " TABLESPACE \"{$tablespace}\""; } // Predicate - if (trim($where) != '') { + if ('' !== \trim($where)) { $sql .= " WHERE ({$where})"; } @@ -108,6 +111,7 @@ trait IndexTrait $this->fieldClean($index); $sql = "DROP INDEX \"{$f_schema}\".\"{$index}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -132,9 +136,11 @@ trait IndexTrait $f_schema = $this->_schema; $this->fieldClean($f_schema); $this->fieldClean($name); + switch ($type) { case 'DATABASE': $sql = "REINDEX {$type} \"{$name}\""; + if ($force) { $sql .= ' FORCE'; } @@ -143,6 +149,7 @@ trait IndexTrait case 'TABLE': case 'INDEX': $sql = "REINDEX {$type} \"{$f_schema}\".\"{$name}\""; + if ($force) { $sql .= ' FORCE'; } @@ -230,8 +237,9 @@ trait IndexTrait pg_catalog.pg_constraint AS c JOIN pg_catalog.pg_class AS r1 ON (c.conrelid=r1.oid) JOIN pg_catalog.pg_attribute AS f1 ON (f1.attrelid=r1.oid AND (f1.attnum=c.conkey[1]'; + for ($i = 2; $i <= $rs->fields['nb']; ++$i) { - $sql .= " OR f1.attnum=c.conkey[${i}]"; + $sql .= " OR f1.attnum=c.conkey[{$i}]"; } $sql .= ')) JOIN pg_catalog.pg_namespace AS ns1 ON r1.relnamespace=ns1.oid @@ -240,11 +248,12 @@ trait IndexTrait ) ON (c.confrelid=r2.oid) LEFT JOIN pg_catalog.pg_attribute AS f2 ON (f2.attrelid=r2.oid AND ((c.confkey[1]=f2.attnum AND c.conkey[1]=f1.attnum)'; + for ($i = 2; $i <= $rs->fields['nb']; ++$i) { - $sql .= " OR (c.confkey[${i}]=f2.attnum AND c.conkey[${i}]=f1.attnum)"; + $sql .= " OR (c.confkey[{$i}]=f2.attnum AND c.conkey[{$i}]=f1.attnum)"; } - $sql .= sprintf(")) + $sql .= \sprintf(")) WHERE r1.relname = '%s' AND ns1.nspname='%s' ORDER BY 1", $table, $c_schema); @@ -264,7 +273,7 @@ trait IndexTrait */ public function addPrimaryKey($table, $fields, $name = '', $tablespace = '') { - if (!is_array($fields) || sizeof($fields) == 0) { + if (!\is_array($fields) || 0 === \count($fields)) { return -1; } @@ -276,13 +285,14 @@ trait IndexTrait $this->fieldClean($tablespace); $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD "; - if ($name != '') { + + if ('' !== $name) { $sql .= "CONSTRAINT \"{$name}\" "; } - $sql .= 'PRIMARY KEY ("'.join('","', $fields).'")'; + $sql .= 'PRIMARY KEY ("' . \implode('","', $fields) . '")'; - if ($tablespace != '' && $this->hasTablespaces()) { + if ('' !== $tablespace && $this->hasTablespaces()) { $sql .= " USING INDEX TABLESPACE \"{$tablespace}\""; } @@ -301,7 +311,7 @@ trait IndexTrait */ public function addUniqueKey($table, $fields, $name = '', $tablespace = '') { - if (!is_array($fields) || sizeof($fields) == 0) { + if (!\is_array($fields) || 0 === \count($fields)) { return -1; } @@ -313,13 +323,14 @@ trait IndexTrait $this->fieldClean($tablespace); $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD "; - if ($name != '') { + + if ('' !== $name) { $sql .= "CONSTRAINT \"{$name}\" "; } - $sql .= 'UNIQUE ("'.join('","', $fields).'")'; + $sql .= 'UNIQUE ("' . \implode('","', $fields) . '")'; - if ($tablespace != '' && $this->hasTablespaces()) { + if ('' !== $tablespace && $this->hasTablespaces()) { $sql .= " USING INDEX TABLESPACE \"{$tablespace}\""; } @@ -346,7 +357,8 @@ trait IndexTrait // @@ How the heck do you clean a definition??? $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD "; - if ($name != '') { + + if ('' !== $name) { $sql .= "CONSTRAINT \"{$name}\" "; } @@ -376,14 +388,16 @@ trait IndexTrait // Begin transaction $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -2; } // Properly lock the table $sql = "LOCK TABLE \"{$f_schema}\".\"{$table}\" IN ACCESS EXCLUSIVE MODE"; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -394,7 +408,8 @@ trait IndexTrait AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = '{$c_schema}')) AND rcname='{$name}'"; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -4; @@ -407,7 +422,8 @@ trait IndexTrait nspname = '{$c_schema}'))) WHERE relname='{$c_table}'"; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -4; @@ -450,8 +466,8 @@ trait IndexTrait $initially, $name = '' ) { - if (!is_array($sfields) || sizeof($sfields) == 0 || - !is_array($tfields) || sizeof($tfields) == 0) { + if (!\is_array($sfields) || 0 === \count($sfields) || + !\is_array($tfields) || 0 === \count($tfields)) { return -1; } @@ -465,30 +481,32 @@ trait IndexTrait $this->fieldClean($name); $sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD "; - if ($name != '') { + + if ('' !== $name) { $sql .= "CONSTRAINT \"{$name}\" "; } - $sql .= 'FOREIGN KEY ("'.join('","', $sfields).'") '; + $sql .= 'FOREIGN KEY ("' . \implode('","', $sfields) . '") '; // Target table needs to be fully qualified - $sql .= "REFERENCES \"{$targschema}\".\"{$targtable}\"(\"".join('","', $tfields).'") '; - if ($match != $this->fkmatches[0]) { + $sql .= "REFERENCES \"{$targschema}\".\"{$targtable}\"(\"" . \implode('","', $tfields) . '") '; + + if ($match !== $this->fkmatches[0]) { $sql .= " {$match}"; } - if ($upd_action != $this->fkactions[0]) { + if ($upd_action !== $this->fkactions[0]) { $sql .= " ON UPDATE {$upd_action}"; } - if ($del_action != $this->fkactions[0]) { + if ($del_action !== $this->fkactions[0]) { $sql .= " ON DELETE {$del_action}"; } - if ($deferrable != $this->fkdeferrable[0]) { + if ($deferrable !== $this->fkdeferrable[0]) { $sql .= " {$deferrable}"; } - if ($initially != $this->fkinitial[0]) { + if ($initially !== $this->fkinitial[0]) { $sql .= " {$initially}"; } @@ -513,6 +531,7 @@ trait IndexTrait $this->fieldClean($relation); $sql = "ALTER TABLE \"{$f_schema}\".\"{$relation}\" DROP CONSTRAINT \"{$constraint}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -529,7 +548,7 @@ trait IndexTrait */ public function getLinkingKeys($tables) { - if (!is_array($tables)) { + if (!\is_array($tables)) { return -1; } @@ -538,7 +557,7 @@ trait IndexTrait $tables_list = "'{$tables[0]['tablename']}'"; $schema_list = "'{$tables[0]['schemaname']}'"; $schema_tables_list = "'{$tables[0]['schemaname']}.{$tables[0]['tablename']}'"; - $tablescount = sizeof($tables); + $tablescount = \count($tables); for ($i = 1; $i < $tablescount; ++$i) { $this->clean($tables[$i]['tablename']); @@ -560,14 +579,15 @@ trait IndexTrait WHERE pc.contype = 'f' AND (pc.conrelid = pgc1.relfilenode OR pc.confrelid = pgc1.relfilenode) - AND pgc1.relname IN (${tables_list}) + AND pgc1.relname IN ({$tables_list}) "; //parse our output to find the highest dimension of foreign keys since pc.conkey is stored in an array $rs = $this->selectSet($sql); + while (!$rs->EOF) { - $arrData = explode(':', $rs->fields['arr_dim']); - $strdimension = trim(substr($arrData[1], 0, strlen($arrData[1]) - 1)); + $arrData = \explode(':', $rs->fields['arr_dim']); + $strdimension = \trim(\mb_substr($arrData[1], 0, \mb_strlen($arrData[1]) - 1)); $tmpDimension = (int) $strdimension; $maxDimension = $tmpDimension > $maxDimension ? $tmpDimension : $maxDimension; $rs->MoveNext(); @@ -575,6 +595,7 @@ trait IndexTrait //we know the highest index for foreign keys that conkey goes up to, expand for us in an IN query $cons_str = '( (pfield.attnum = conkey[1] AND cfield.attnum = confkey[1]) '; + for ($i = 2; $i <= $maxDimension; ++$i) { $cons_str .= "OR (pfield.attnum = conkey[{$i}] AND cfield.attnum = confkey[{$i}]) "; } @@ -594,8 +615,8 @@ trait IndexTrait pg_catalog.pg_class AS pgc2, pg_catalog.pg_attribute AS pfield, pg_catalog.pg_attribute AS cfield, - (SELECT oid AS ns_id, nspname FROM pg_catalog.pg_namespace WHERE nspname IN (${schema_list}) ) AS pgns1, - (SELECT oid AS ns_id, nspname FROM pg_catalog.pg_namespace WHERE nspname IN (${schema_list}) ) AS pgns2 + (SELECT oid AS ns_id, nspname FROM pg_catalog.pg_namespace WHERE nspname IN ({$schema_list}) ) AS pgns1, + (SELECT oid AS ns_id, nspname FROM pg_catalog.pg_namespace WHERE nspname IN ({$schema_list}) ) AS pgns2 WHERE pc.contype = 'f' AND pgc1.relnamespace = pgns1.ns_id @@ -604,9 +625,9 @@ trait IndexTrait AND pc.confrelid = pgc2.relfilenode AND pfield.attrelid = pc.conrelid AND cfield.attrelid = pc.confrelid - AND ${cons_str} - AND pgns1.nspname || '.' || pgc1.relname IN (${schema_tables_list}) - AND pgns2.nspname || '.' || pgc2.relname IN (${schema_tables_list}) + AND {$cons_str} + AND pgns1.nspname || '.' || pgc1.relname IN ({$schema_tables_list}) + AND pgns2.nspname || '.' || pgc2.relname IN ({$schema_tables_list}) "; return $this->selectSet($sql); @@ -624,7 +645,8 @@ trait IndexTrait $this->clean($table); $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } diff --git a/src/database/databasetraits/OperatorTrait.php b/src/database/databasetraits/OperatorTrait.php index dfd82dd8..7d66c5b8 100644 --- a/src/database/databasetraits/OperatorTrait.php +++ b/src/database/databasetraits/OperatorTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -57,14 +60,14 @@ trait OperatorTrait $sql = "DROP OPERATOR \"{$f_schema}\".{$opr->fields['oprname']} ("; // Quoting or formatting here??? - if ($opr->fields['oprleftname'] !== null) { - $sql .= $opr->fields['oprleftname'].', '; + if (null !== $opr->fields['oprleftname']) { + $sql .= $opr->fields['oprleftname'] . ', '; } else { $sql .= 'NONE, '; } - if ($opr->fields['oprrightname'] !== null) { - $sql .= $opr->fields['oprrightname'].')'; + if (null !== $opr->fields['oprrightname']) { + $sql .= $opr->fields['oprrightname'] . ')'; } else { $sql .= 'NONE)'; } diff --git a/src/database/databasetraits/PrivilegesTrait.php b/src/database/databasetraits/PrivilegesTrait.php index b374a74c..431b951a 100644 --- a/src/database/databasetraits/PrivilegesTrait.php +++ b/src/database/databasetraits/PrivilegesTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -81,11 +84,12 @@ trait PrivilegesTrait // Fetch the ACL for object $acl = $this->selectField($sql, 'acl'); - if ($acl == -1) { + + if (-1 === $acl) { return -2; } - if ($acl == '' || $acl === null || !(bool) $acl) { + if ('' === $acl || null === $acl || !(bool) $acl) { return []; } @@ -93,140 +97,6 @@ trait PrivilegesTrait } /** - * Internal function used for parsing ACLs. - * - * @param string $acl The ACL to parse (of type aclitem[]) - * - * @return array|int Privileges array or integer with error code - * - * @internal bool $in_quotes toggles acl in_quotes attribute - */ - protected function parseACL($acl) - { - // Take off the first and last characters (the braces) - $acl = substr($acl, 1, strlen($acl) - 2); - - // Pick out individual ACE's by carefully parsing. This is necessary in order - // to cope with usernames and stuff that contain commas - $aces = []; - $i = $j = 0; - $in_quotes = false; - while ($i < strlen($acl)) { - // If current char is a double quote and it's not escaped, then - // enter quoted bit - $char = substr($acl, $i, 1); - if ($char == '"' && ($i == 0 || substr($acl, $i - 1, 1) != '\\')) { - $in_quotes = !$in_quotes; - } elseif ($char == ',' && !$in_quotes) { - // Add text so far to the array - $aces[] = substr($acl, $j, $i - $j); - $j = $i + 1; - } - ++$i; - } - // Add final text to the array - $aces[] = substr($acl, $j); - - // Create the array to be returned - $temp = []; - - // For each ACE, generate an entry in $temp - foreach ($aces as $v) { - // If the ACE begins with a double quote, strip them off both ends - // and unescape backslashes and double quotes - // $unquote = false; - if (strpos($v, '"') === 0) { - $v = substr($v, 1, strlen($v) - 2); - $v = str_replace('\\"', '"', $v); - $v = str_replace('\\\\', '\\', $v); - } - - // Figure out type of ACE (public, user or group) - if (strpos($v, '=') === 0) { - $atype = 'public'; - } else { - if ($this->hasRoles()) { - $atype = 'role'; - } else { - if (strpos($v, 'group ') === 0) { - $atype = 'group'; - // Tear off 'group' prefix - $v = substr($v, 6); - } else { - $atype = 'user'; - } - } - } - - // Break on unquoted equals sign... - $i = 0; - $in_quotes = false; - $entity = null; - $chars = null; - while ($i < strlen($v)) { - // If current char is a double quote and it's not escaped, then - // enter quoted bit - $char = substr($v, $i, 1); - $next_char = substr($v, $i + 1, 1); - if ($char == '"' && ($i == 0 || $next_char != '"')) { - $in_quotes = !$in_quotes; - } elseif ($char == '"' && $next_char == '"') { - // Skip over escaped double quotes - ++$i; - } elseif ($char == '=' && !$in_quotes) { - // Split on current equals sign - $entity = substr($v, 0, $i); - $chars = substr($v, $i + 1); - - break; - } - ++$i; - } - - // Check for quoting on entity name, and unescape if necessary - if (strpos($entity, '"') === 0) { - $entity = substr($entity, 1, strlen($entity) - 2); - $entity = str_replace('""', '"', $entity); - } - - // New row to be added to $temp - // (type, grantee, privileges, grantor, grant option? - $row = [$atype, $entity, [], '', []]; - - // Loop over chars and add privs to $row - for ($i = 0; $i < strlen($chars); ++$i) { - // Append to row's privs list the string representing - // the privilege - $char = substr($chars, $i, 1); - if ($char == '*') { - $row[4][] = $this->privmap[substr($chars, $i - 1, 1)]; - } elseif ($char == '/') { - $grantor = substr($chars, $i + 1); - // Check for quoting - if (strpos($grantor, '"') === 0) { - $grantor = substr($grantor, 1, strlen($grantor) - 2); - $grantor = str_replace('""', '"', $grantor); - } - $row[3] = $grantor; - - break; - } else { - if (!isset($this->privmap[$char])) { - return -3; - } - - $row[2][] = $this->privmap[$char]; - } - } - - // Append row to temp - $temp[] = $row; - } - - return $temp; - } - - /** * Grants a privilege to a user, group or public. * * @param string $mode 'GRANT' or 'REVOKE'; @@ -260,34 +130,34 @@ trait PrivilegesTrait $this->fieldArrayClean($groupnames); // Input checking - if (!is_array($privileges) || sizeof($privileges) == 0) { + if (!\is_array($privileges) || 0 === \count($privileges)) { return -3; } - if (!is_array($usernames) || !is_array($groupnames) || - (!$public && sizeof($usernames) == 0 && sizeof($groupnames) == 0)) { + if (!\is_array($usernames) || !\is_array($groupnames) || + (!$public && 0 === \count($usernames) && 0 === \count($groupnames))) { return -4; } - if ($mode != 'GRANT' && $mode != 'REVOKE') { + if ('GRANT' !== $mode && 'REVOKE' !== $mode) { return -5; } $sql = $mode; // Grant option - if ($this->hasGrantOption() && $mode == 'REVOKE' && $grantoption) { + if ($this->hasGrantOption() && 'REVOKE' === $mode && $grantoption) { $sql .= ' GRANT OPTION FOR'; } - if (in_array('ALL PRIVILEGES', $privileges, true)) { + if (\in_array('ALL PRIVILEGES', $privileges, true)) { $sql .= ' ALL PRIVILEGES'; } else { - if ($type == 'column') { + if ('column' === $type) { $this->fieldClean($object); - $sql .= ' '.join(" (\"{$object}\"), ", $privileges); + $sql .= ' ' . \implode(" (\"{$object}\"), ", $privileges); } else { - $sql .= ' '.join(', ', $privileges); + $sql .= ' ' . \implode(', ', $privileges); } } @@ -336,7 +206,8 @@ trait PrivilegesTrait // Dump $first = true; - $sql .= ($mode == 'GRANT') ? ' TO ' : ' FROM '; + $sql .= ('GRANT' === $mode) ? ' TO ' : ' FROM '; + if ($public) { $sql .= 'PUBLIC'; $first = false; @@ -361,12 +232,12 @@ trait PrivilegesTrait } // Grant option - if ($this->hasGrantOption() && $mode == 'GRANT' && $grantoption) { + if ($this->hasGrantOption() && 'GRANT' === $mode && $grantoption) { $sql .= ' WITH GRANT OPTION'; } // Cascade revoke - if ($this->hasGrantOption() && $mode == 'REVOKE' && $cascade) { + if ($this->hasGrantOption() && 'REVOKE' === $mode && $cascade) { $sql .= ' CASCADE'; } @@ -398,4 +269,143 @@ trait PrivilegesTrait abstract public function selectField($sql, $field); abstract public function hasRoles(); + + /** + * Internal function used for parsing ACLs. + * + * @param string $acl The ACL to parse (of type aclitem[]) + * + * @return array|int Privileges array or integer with error code + * + * @internal bool $in_quotes toggles acl in_quotes attribute + */ + protected function parseACL($acl) + { + // Take off the first and last characters (the braces) + $acl = \mb_substr($acl, 1, \mb_strlen($acl) - 2); + + // Pick out individual ACE's by carefully parsing. This is necessary in order + // to cope with usernames and stuff that contain commas + $aces = []; + $i = $j = 0; + $in_quotes = false; + + while (\mb_strlen($acl) > $i) { + // If current char is a double quote and it's not escaped, then + // enter quoted bit + $char = \mb_substr($acl, $i, 1); + + if ('"' === $char && (0 === $i || '\\' !== \mb_substr($acl, $i - 1, 1))) { + $in_quotes = !$in_quotes; + } elseif (',' === $char && !$in_quotes) { + // Add text so far to the array + $aces[] = \mb_substr($acl, $j, $i - $j); + $j = $i + 1; + } + ++$i; + } + // Add final text to the array + $aces[] = \mb_substr($acl, $j); + + // Create the array to be returned + $temp = []; + + // For each ACE, generate an entry in $temp + foreach ($aces as $v) { + // If the ACE begins with a double quote, strip them off both ends + // and unescape backslashes and double quotes + // $unquote = false; + if (0 === \mb_strpos($v, '"')) { + $v = \mb_substr($v, 1, \mb_strlen($v) - 2); + $v = \str_replace('\\"', '"', $v); + $v = \str_replace('\\\\', '\\', $v); + } + + // Figure out type of ACE (public, user or group) + if (0 === \mb_strpos($v, '=')) { + $atype = 'public'; + } else { + if ($this->hasRoles()) { + $atype = 'role'; + } else { + if (0 === \mb_strpos($v, 'group ')) { + $atype = 'group'; + // Tear off 'group' prefix + $v = \mb_substr($v, 6); + } else { + $atype = 'user'; + } + } + } + + // Break on unquoted equals sign... + $i = 0; + $in_quotes = false; + $entity = null; + $chars = null; + + while (\mb_strlen($v) > $i) { + // If current char is a double quote and it's not escaped, then + // enter quoted bit + $char = \mb_substr($v, $i, 1); + $next_char = \mb_substr($v, $i + 1, 1); + + if ('"' === $char && (0 === $i || '"' !== $next_char)) { + $in_quotes = !$in_quotes; + } elseif ('"' === $char && '"' === $next_char) { + // Skip over escaped double quotes + ++$i; + } elseif ('=' === $char && !$in_quotes) { + // Split on current equals sign + $entity = \mb_substr($v, 0, $i); + $chars = \mb_substr($v, $i + 1); + + break; + } + ++$i; + } + + // Check for quoting on entity name, and unescape if necessary + if (0 === \mb_strpos($entity, '"')) { + $entity = \mb_substr($entity, 1, \mb_strlen($entity) - 2); + $entity = \str_replace('""', '"', $entity); + } + + // New row to be added to $temp + // (type, grantee, privileges, grantor, grant option? + $row = [$atype, $entity, [], '', []]; + + // Loop over chars and add privs to $row + for ($i = 0;\mb_strlen($chars) > $i; ++$i) { + // Append to row's privs list the string representing + // the privilege + $char = \mb_substr($chars, $i, 1); + + if ('*' === $char) { + $row[4][] = $this->privmap[\mb_substr($chars, $i - 1, 1)]; + } elseif ('/' === $char) { + $grantor = \mb_substr($chars, $i + 1); + // Check for quoting + if (0 === \mb_strpos($grantor, '"')) { + $grantor = \mb_substr($grantor, 1, \mb_strlen($grantor) - 2); + $grantor = \str_replace('""', '"', $grantor); + } + $row[3] = $grantor; + + break; + } else { + if (!isset($this->privmap[$char])) { + return -3; + } + + $row[2][] = $this->privmap[$char]; + } + } + + // Append row to temp + $temp[] = $row; + } + + return $temp; + } } diff --git a/src/database/databasetraits/RoleTrait.php b/src/database/databasetraits/RoleTrait.php index 2a0e4e64..b77799db 100644 --- a/src/database/databasetraits/RoleTrait.php +++ b/src/database/databasetraits/RoleTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -36,6 +39,7 @@ trait RoleTrait LEFT JOIN pg_catalog.pg_auth_members m ON (m.member = r.oid) LEFT JOIN pg_roles r1 ON (m.roleid=r1.oid) '; + if ($rolename) { $sql .= " WHERE r.rolname!='{$rolename}'"; } @@ -163,7 +167,8 @@ trait RoleTrait $this->fieldArrayClean($new_admins_of_role); $sql = "CREATE ROLE \"{$rolename}\""; - if ($password != '') { + + if ('' !== $password) { $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'"; } @@ -172,28 +177,29 @@ trait RoleTrait $sql .= $createrole ? ' CREATEROLE' : ' NOCREATEROLE'; $sql .= $inherits ? ' INHERIT' : ' NOINHERIT'; $sql .= $login ? ' LOGIN' : ' NOLOGIN'; - if ($connlimit != '') { + + if ('' !== $connlimit) { $sql .= " CONNECTION LIMIT {$connlimit}"; } else { $sql .= ' CONNECTION LIMIT -1'; } - if ($expiry != '') { + if ('' !== $expiry) { $sql .= " VALID UNTIL '{$expiry}'"; } else { $sql .= " VALID UNTIL 'infinity'"; } - if (is_array($new_roles_to_add) && sizeof($new_roles_to_add) > 0) { - $sql .= ' IN ROLE "'.join('", "', $new_roles_to_add).'"'; + if (\is_array($new_roles_to_add) && 0 < \count($new_roles_to_add)) { + $sql .= ' IN ROLE "' . \implode('", "', $new_roles_to_add) . '"'; } - if (is_array($new_members_of_role) && sizeof($new_members_of_role) > 0) { - $sql .= ' ROLE "'.join('", "', $new_members_of_role).'"'; + if (\is_array($new_members_of_role) && 0 < \count($new_members_of_role)) { + $sql .= ' ROLE "' . \implode('", "', $new_members_of_role) . '"'; } - if (is_array($new_admins_of_role) && sizeof($new_admins_of_role) > 0) { - $sql .= ' ADMIN "'.join('", "', $new_admins_of_role).'"'; + if (\is_array($new_admins_of_role) && 0 < \count($new_admins_of_role)) { + $sql .= ' ADMIN "' . \implode('", "', $new_admins_of_role) . '"'; } return $this->execute($sql); @@ -209,7 +215,7 @@ trait RoleTrait */ public function _encryptPassword($username, $password) { - return 'md5'.md5($password.$username); + return 'md5' . \md5($password . $username); } /** @@ -253,13 +259,15 @@ trait RoleTrait $newrolename ) { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } - if ($rolename != $newrolename) { + if ($rolename !== $newrolename) { $status = $this->renameRole($rolename, $newrolename); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -284,7 +292,8 @@ trait RoleTrait $original_members, $original_admins ); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -2; @@ -311,116 +320,6 @@ trait RoleTrait return $this->execute($sql); } - private function _dealWithOldParentRoles($original_parent_roles, $new_roles_to_add, $rolename) - { - $old = explode(',', $original_parent_roles); - - // Grant the roles of the old role owners to the new owner - foreach ($new_roles_to_add as $m) { - if (!in_array($m, $old, true)) { - $status = $this->grantRole($m, $rolename); - if ($status != 0) { - return -1; - } - } - } - - // Revoke the new role to the old members if they don't have the requested role name - - foreach ($old as $o) { - if (!in_array($o, $new_roles_to_add, true)) { - $status = $this->revokeRole($o, $rolename, 0, 'CASCADE'); - if ($status != 0) { - return -1; - } - } - } - - return 0; - } - - private function _dealWithOriginalMembers($original_members, $new_members_of_role, $rolename) - { - //members - $old = explode(',', $original_members); - foreach ($new_members_of_role as $m) { - if (!in_array($m, $old, true)) { - $status = $this->grantRole($rolename, $m); - if ($status != 0) { - return -1; - } - } - } - if ($original_members) { - foreach ($old as $o) { - if (!in_array($o, $new_members_of_role, true)) { - $status = $this->revokeRole($rolename, $o, 0, 'CASCADE'); - if ($status != 0) { - return -1; - } - } - } - } - - return 0; - } - - private function _dealWithOriginalAdmins($original_admins, $new_admins_of_role, $rolename) - { - $old = explode(',', $original_admins); - foreach ($new_admins_of_role as $m) { - if (!in_array($m, $old, true)) { - $status = $this->grantRole($rolename, $m, 1); - if ($status != 0) { - return -1; - } - } - } - - foreach ($old as $o) { - if (!in_array($o, $new_admins_of_role, true)) { - $status = $this->revokeRole($rolename, $o, 1, 'CASCADE'); - if ($status != 0) { - return -1; - } - } - } - - return 0; - } - - private function _alterRole($rolename, $password, $connlimit, $expiry, $superuser, $createdb, $createrole, $inherits, $login) - { - $enc = $this->_encryptPassword($rolename, $password); - $this->clean($enc); - $this->clean($connlimit); - $this->clean($expiry); - - $sql = "ALTER ROLE \"{$rolename}\""; - if ($password != '') { - $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'"; - } - - $sql .= $superuser ? ' SUPERUSER' : ' NOSUPERUSER'; - $sql .= $createdb ? ' CREATEDB' : ' NOCREATEDB'; - $sql .= $createrole ? ' CREATEROLE' : ' NOCREATEROLE'; - $sql .= $inherits ? ' INHERIT' : ' NOINHERIT'; - $sql .= $login ? ' LOGIN' : ' NOLOGIN'; - if ($connlimit != '') { - $sql .= " CONNECTION LIMIT {$connlimit}"; - } else { - $sql .= ' CONNECTION LIMIT -1'; - } - - if ($expiry != '') { - $sql .= " VALID UNTIL '{$expiry}'"; - } else { - $sql .= " VALID UNTIL 'infinity'"; - } - - return $this->execute($sql); - } - /** * Adjusts a role's info. * @@ -466,7 +365,8 @@ trait RoleTrait $this->fieldArrayClean($new_admins_of_role); $status = $this->_alterRole($rolename, $password, $connlimit, $expiry, $superuser, $createdb, $createrole, $inherits, $login); - if ($status !== 0) { + + if (0 !== $status) { return -1; } @@ -475,21 +375,24 @@ trait RoleTrait // role from them if they are not among the new authorized members if ($original_parent_roles) { $status = $this->_dealWithOldParentRoles($original_parent_roles, $new_roles_to_add, $rolename); - if ($status !== 0) { + + if (0 !== $status) { return -1; } } if ($original_members) { $status = $this->_dealWithOriginalMembers($original_members, $new_members_of_role, $rolename); - if ($status !== 0) { + + if (0 !== $status) { return -1; } } if ($original_admins) { $status = $this->_dealWithOriginalAdmins($original_admins, $new_admins_of_role, $rolename); - if ($status !== 0) { + + if (0 !== $status) { return -1; } } @@ -512,7 +415,8 @@ trait RoleTrait $this->fieldClean($rolename); $sql = "GRANT \"{$role}\" TO \"{$rolename}\""; - if ($admin == 1) { + + if (1 === $admin) { $sql .= ' WITH ADMIN OPTION'; } @@ -535,7 +439,8 @@ trait RoleTrait $this->fieldClean($rolename); $sql = 'REVOKE '; - if ($admin == 1) { + + if (1 === $admin) { $sql .= 'ADMIN OPTION FOR '; } @@ -583,17 +488,19 @@ trait RoleTrait $this->fieldArrayClean($groups); $sql = "CREATE USER \"{$username}\""; - if ($password != '') { + + if ('' !== $password) { $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'"; } $sql .= $createdb ? ' CREATEDB' : ' NOCREATEDB'; $sql .= $createuser ? ' CREATEUSER' : ' NOCREATEUSER'; - if (is_array($groups) && sizeof($groups) > 0) { - $sql .= ' IN GROUP "'.join('", "', $groups).'"'; + + if (\is_array($groups) && 0 < \count($groups)) { + $sql .= ' IN GROUP "' . \implode('", "', $groups) . '"'; } - if ($expiry != '') { + if ('' !== $expiry) { $sql .= " VALID UNTIL '{$expiry}'"; } else { $sql .= " VALID UNTIL 'infinity'"; @@ -617,13 +524,15 @@ trait RoleTrait public function setRenameUser($username, $password, $createdb, $createuser, $expiry, $newname) { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } - if ($username != $newname) { + if ($username !== $newname) { $status = $this->renameUser($username, $newname); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -632,7 +541,8 @@ trait RoleTrait } $status = $this->setUser($username, $password, $createdb, $createuser, $expiry); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -2; @@ -680,13 +590,15 @@ trait RoleTrait $this->clean($expiry); $sql = "ALTER USER \"{$username}\""; - if ($password != '') { + + if ('' !== $password) { $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'"; } $sql .= $createdb ? ' CREATEDB' : ' NOCREATEDB'; $sql .= $createuser ? ' CREATEUSER' : ' NOCREATEUSER'; - if ($expiry != '') { + + if ('' !== $expiry) { $sql .= " VALID UNTIL '{$expiry}'"; } else { $sql .= " VALID UNTIL 'infinity'"; @@ -857,9 +769,9 @@ trait RoleTrait $sql = "CREATE GROUP \"{$groname}\""; - if (is_array($users) && sizeof($users) > 0) { + if (\is_array($users) && 0 < \count($users)) { $this->fieldArrayClean($users); - $sql .= ' WITH USER "'.join('", "', $users).'"'; + $sql .= ' WITH USER "' . \implode('", "', $users) . '"'; } return $this->execute($sql); @@ -902,4 +814,125 @@ trait RoleTrait abstract public function getFunction($function_oid); abstract public function fieldArrayClean(&$arr); + + private function _dealWithOldParentRoles($original_parent_roles, $new_roles_to_add, $rolename) + { + $old = \explode(',', $original_parent_roles); + + // Grant the roles of the old role owners to the new owner + foreach ($new_roles_to_add as $m) { + if (!\in_array($m, $old, true)) { + $status = $this->grantRole($m, $rolename); + + if (0 !== $status) { + return -1; + } + } + } + + // Revoke the new role to the old members if they don't have the requested role name + + foreach ($old as $o) { + if (!\in_array($o, $new_roles_to_add, true)) { + $status = $this->revokeRole($o, $rolename, 0, 'CASCADE'); + + if (0 !== $status) { + return -1; + } + } + } + + return 0; + } + + private function _dealWithOriginalMembers($original_members, $new_members_of_role, $rolename) + { + //members + $old = \explode(',', $original_members); + + foreach ($new_members_of_role as $m) { + if (!\in_array($m, $old, true)) { + $status = $this->grantRole($rolename, $m); + + if (0 !== $status) { + return -1; + } + } + } + + if ($original_members) { + foreach ($old as $o) { + if (!\in_array($o, $new_members_of_role, true)) { + $status = $this->revokeRole($rolename, $o, 0, 'CASCADE'); + + if (0 !== $status) { + return -1; + } + } + } + } + + return 0; + } + + private function _dealWithOriginalAdmins($original_admins, $new_admins_of_role, $rolename) + { + $old = \explode(',', $original_admins); + + foreach ($new_admins_of_role as $m) { + if (!\in_array($m, $old, true)) { + $status = $this->grantRole($rolename, $m, 1); + + if (0 !== $status) { + return -1; + } + } + } + + foreach ($old as $o) { + if (!\in_array($o, $new_admins_of_role, true)) { + $status = $this->revokeRole($rolename, $o, 1, 'CASCADE'); + + if (0 !== $status) { + return -1; + } + } + } + + return 0; + } + + private function _alterRole($rolename, $password, $connlimit, $expiry, $superuser, $createdb, $createrole, $inherits, $login) + { + $enc = $this->_encryptPassword($rolename, $password); + $this->clean($enc); + $this->clean($connlimit); + $this->clean($expiry); + + $sql = "ALTER ROLE \"{$rolename}\""; + + if ('' !== $password) { + $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'"; + } + + $sql .= $superuser ? ' SUPERUSER' : ' NOSUPERUSER'; + $sql .= $createdb ? ' CREATEDB' : ' NOCREATEDB'; + $sql .= $createrole ? ' CREATEROLE' : ' NOCREATEROLE'; + $sql .= $inherits ? ' INHERIT' : ' NOINHERIT'; + $sql .= $login ? ' LOGIN' : ' NOLOGIN'; + + if ('' !== $connlimit) { + $sql .= " CONNECTION LIMIT {$connlimit}"; + } else { + $sql .= ' CONNECTION LIMIT -1'; + } + + if ('' !== $expiry) { + $sql .= " VALID UNTIL '{$expiry}'"; + } else { + $sql .= " VALID UNTIL 'infinity'"; + } + + return $this->execute($sql); + } } diff --git a/src/database/databasetraits/RowTrait.php b/src/database/databasetraits/RowTrait.php index 73373a1f..d644045c 100644 --- a/src/database/databasetraits/RowTrait.php +++ b/src/database/databasetraits/RowTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -26,8 +29,10 @@ trait RowTrait $this->fieldClean($table); $sql = "SELECT * FROM \"{$f_schema}\".\"{$table}\""; - if (is_array($key) && sizeof($key) > 0) { + + if (\is_array($key) && 0 < \count($key)) { $sql .= ' WHERE true'; + foreach ($key as $k => $v) { $this->fieldClean($k); $this->clean($v); @@ -53,7 +58,8 @@ trait RowTrait $this->clean($table); $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } @@ -74,9 +80,10 @@ trait RowTrait // If none, check for an OID column. Even though OIDs can be duplicated, the edit and delete row // functions check that they're only modiying a single row. Otherwise, return empty array. - if ($rs->recordCount() == 0) { + if (0 === $rs->recordCount()) { // Check for OID column $temp = []; + if ($this->hasObjectID($table)) { $temp = ['oid']; } @@ -85,8 +92,9 @@ trait RowTrait return $temp; } // Otherwise find the names of the keys - $attnames = $this->getAttributeNames($oldtable, explode(' ', $rs->fields['indkey'])); - if (!is_array($attnames)) { + $attnames = $this->getAttributeNames($oldtable, \explode(' ', $rs->fields['indkey'])); + + if (!\is_array($attnames)) { $this->rollbackTransaction(); return -1; @@ -111,33 +119,34 @@ trait RowTrait */ public function insertRow($table, $fields, $values, $nulls, $format, $types) { - if (!is_array($fields) || !is_array($values) || !is_array($nulls) - || !is_array($format) || !is_array($types) - || (count($fields) != count($values)) + if (!\is_array($fields) || !\is_array($values) || !\is_array($nulls) + || !\is_array($format) || !\is_array($types) + || (\count($fields) !== \count($values)) ) { return -1; } // Build clause - if (count($values) > 0) { + if (0 < \count($values)) { // Escape all field names - $fields = array_map(['\PHPPgAdmin\Database\Postgres', 'fieldClean'], $fields); + $fields = \array_map(['\PHPPgAdmin\Database\Postgres', 'fieldClean'], $fields); $f_schema = $this->_schema; $this->fieldClean($table); $this->fieldClean($f_schema); $sql = ''; + foreach ($values as $i => $value) { // Handle NULL values if (isset($nulls[$i])) { $sql .= ',NULL'; } else { - $sql .= ','.$this->formatValue($types[$i], $format[$i], $value); + $sql .= ',' . $this->formatValue($types[$i], $format[$i], $value); } } - $sql = "INSERT INTO \"{$f_schema}\".\"{$table}\" (\"".implode('","', $fields).'") - VALUES ('.substr($sql, 1).')'; + $sql = "INSERT INTO \"{$f_schema}\".\"{$table}\" (\"" . \implode('","', $fields) . '") + VALUES (' . \mb_substr($sql, 1) . ')'; return $this->execute($sql); } @@ -159,14 +168,15 @@ trait RowTrait switch ($type) { case 'bool': case 'boolean': - if ($value == 't') { + if ('t' === $value) { return 'TRUE'; } - if ($value == 'f') { + if ('f' === $value) { return 'FALSE'; } - if ($value == '') { + + if ('' === $value) { return 'NULL'; } @@ -176,27 +186,29 @@ trait RowTrait default: // Checking variable fields is difficult as there might be a size // attribute... - if (strpos($type, 'time') === 0) { + if (0 === \mb_strpos($type, 'time')) { // Assume it's one of the time types... - if ($value == '') { + if ('' === $value) { return "''"; } - if (strcasecmp($value, 'CURRENT_TIMESTAMP') == 0 - || strcasecmp($value, 'CURRENT_TIME') == 0 - || strcasecmp($value, 'CURRENT_DATE') == 0 - || strcasecmp($value, 'LOCALTIME') == 0 - || strcasecmp($value, 'LOCALTIMESTAMP') == 0) { + if (0 === \strcasecmp($value, 'CURRENT_TIMESTAMP') + || 0 === \strcasecmp($value, 'CURRENT_TIME') + || 0 === \strcasecmp($value, 'CURRENT_DATE') + || 0 === \strcasecmp($value, 'LOCALTIME') + || 0 === \strcasecmp($value, 'LOCALTIMESTAMP')) { return $value; } - if ($format == 'EXPRESSION') { + + if ('EXPRESSION' === $format) { return $value; } $this->clean($value); return "'{$value}'"; } - if ($format == 'VALUE') { + + if ('VALUE' === $format) { $this->clean($value); return "'{$value}'"; @@ -222,7 +234,7 @@ trait RowTrait */ public function editRow($table, $vars, $nulls, $format, $types, $keyarr) { - if (!is_array($vars) || !is_array($nulls) || !is_array($format) || !is_array($types)) { + if (!\is_array($vars) || !\is_array($nulls) || !\is_array($format) || !\is_array($types)) { return -1; } @@ -231,7 +243,7 @@ trait RowTrait $this->fieldClean($table); $sql = ''; // Build clause - if (sizeof($vars) > 0) { + if (0 < \count($vars)) { foreach ($vars as $key => $value) { $this->fieldClean($key); @@ -242,16 +254,18 @@ trait RowTrait $tmp = $this->formatValue($types[$key], $format[$key], $value); } - if (strlen($sql) > 0) { + if (0 < \mb_strlen($sql)) { $sql .= ", \"{$key}\"={$tmp}"; } else { $sql = "UPDATE \"{$f_schema}\".\"{$table}\" SET \"{$key}\"={$tmp}"; } } $first = true; + foreach ($keyarr as $k => $v) { $this->fieldClean($k); $this->clean($v); + if ($first) { $sql .= " WHERE \"{$k}\"='{$v}'"; $first = false; @@ -264,20 +278,22 @@ trait RowTrait // Begin transaction. We do this so that we can ensure only one row is // edited $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { // update failed $this->rollbackTransaction(); return -1; } - if ($this->conn->Affected_Rows() != 1) { + if (1 !== $this->conn->Affected_Rows()) { // more than one row could be updated $this->rollbackTransaction(); @@ -299,25 +315,27 @@ trait RowTrait */ public function deleteRow($table, $key, $schema = '') { - if (!is_array($key)) { + if (!\is_array($key)) { return -1; } // Begin transaction. We do this so that we can ensure only one row is // deleted $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } - if ($schema === '') { + if ('' === $schema) { $schema = $this->_schema; } $status = $this->delete($table, $key, $schema); - if ($status != 0 || $this->conn->Affected_Rows() != 1) { + + if (0 !== $status || 1 !== $this->conn->Affected_Rows()) { $this->rollbackTransaction(); return -2; diff --git a/src/database/databasetraits/SchemaTrait.php b/src/database/databasetraits/SchemaTrait.php index 1cbbbc47..94ec11da 100644 --- a/src/database/databasetraits/SchemaTrait.php +++ b/src/database/databasetraits/SchemaTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -65,10 +68,10 @@ trait SchemaTrait // Get the current schema search path, including 'pg_catalog'. $search_path = $this->getSearchPath(); // Prepend $schema to search path - array_unshift($search_path, $schema); + \array_unshift($search_path, $schema); $status = $this->setSearchPath($search_path); - if ($status == 0) { + if (0 === $status) { $this->_schema = $schema; return 0; @@ -103,28 +106,30 @@ trait SchemaTrait */ public function setSearchPath($paths) { - if (!is_array($paths)) { + if (!\is_array($paths)) { return -1; } - if (sizeof($paths) == 0) { + if (0 === \count($paths)) { return -2; } - if (sizeof($paths) == 1 && $paths[0] == '') { + + if (1 === \count($paths) && '' === $paths[0]) { // Need to handle empty paths in some cases $paths[0] = 'pg_catalog'; } // Loop over all the paths to check that none are empty $temp = []; + foreach ($paths as $schema) { - if ($schema != '') { + if ('' !== $schema) { $temp[] = $schema; } } $this->fieldArrayClean($temp); - $sql = 'SET SEARCH_PATH TO "'.implode('","', $temp).'"'; + $sql = 'SET SEARCH_PATH TO "' . \implode('","', $temp) . '"'; return $this->execute($sql); } @@ -144,29 +149,33 @@ trait SchemaTrait $this->fieldClean($authorization); $sql = "CREATE SCHEMA \"{$schemaname}\""; - if ($authorization != '') { + + if ('' !== $authorization) { $sql .= " AUTHORIZATION \"{$authorization}\""; } - if ($comment != '') { + if ('' !== $comment) { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } } // Create the new schema $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } // Set the comment - if ($comment != '') { + if ('' !== $comment) { $status = $this->setComment('SCHEMA', $schemaname, '', $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -195,14 +204,16 @@ trait SchemaTrait $this->fieldClean($owner); $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; } $status = $this->setComment('SCHEMA', $schemaname, '', $comment); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -210,10 +221,11 @@ trait SchemaTrait $schema_rs = $this->getSchemaByName($schemaname); /* Only if the owner change */ - if ($schema_rs->fields['ownername'] != $owner) { + if ($schema_rs->fields['ownername'] !== $owner) { $sql = "ALTER SCHEMA \"{$schemaname}\" OWNER TO \"{$owner}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -221,10 +233,11 @@ trait SchemaTrait } // Only if the name has changed - if ($name != $schemaname) { + if ($name !== $schemaname) { $sql = "ALTER SCHEMA \"{$schemaname}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -269,6 +282,7 @@ trait SchemaTrait $this->fieldClean($schemaname); $sql = "DROP SCHEMA \"{$schemaname}\""; + if ($cascade) { $sql .= ' CASCADE'; } diff --git a/src/database/databasetraits/SequenceTrait.php b/src/database/databasetraits/SequenceTrait.php index 2a76a361..bf2b9f2f 100644 --- a/src/database/databasetraits/SequenceTrait.php +++ b/src/database/databasetraits/SequenceTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -114,7 +117,8 @@ trait SequenceTrait { // Get the minimum value of the sequence $seq = $this->getSequence($sequence); - if ($seq->recordCount() != 1) { + + if (1 !== $seq->recordCount()) { return -1; } @@ -190,23 +194,24 @@ trait SequenceTrait $this->clean($cachevalue); $sql = "CREATE SEQUENCE \"{$f_schema}\".\"{$sequence}\""; - if ($increment != '') { + + if ('' !== $increment) { $sql .= " INCREMENT {$increment}"; } - if ($minvalue != '') { + if ('' !== $minvalue) { $sql .= " MINVALUE {$minvalue}"; } - if ($maxvalue != '') { + if ('' !== $maxvalue) { $sql .= " MAXVALUE {$maxvalue}"; } - if ($startvalue != '') { + if ('' !== $startvalue) { $sql .= " START {$startvalue}"; } - if ($cachevalue != '') { + if ('' !== $cachevalue) { $sql .= " CACHE {$cachevalue}"; } @@ -253,12 +258,13 @@ trait SequenceTrait $data = $this->getSequence($sequence); - if ($data->recordCount() != 1) { + if (1 !== $data->recordCount()) { return -2; } $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -279,7 +285,7 @@ trait SequenceTrait $startvalue ); - if ($status != 0) { + if (0 !== $status) { $this->rollbackTransaction(); return $status; @@ -288,93 +294,6 @@ trait SequenceTrait return $this->endTransaction(); } - /** - * Protected method which alter a sequence - * SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION. - * - * @param \PHPPgAdmin\ADORecordSet $seqrs The sequence recordSet returned by getSequence() - * @param string $name The new name for the sequence - * @param string $comment The comment on the sequence - * @param string $owner The new owner for the sequence - * @param string $schema The new schema for the sequence - * @param string $increment The increment - * @param string $minvalue The min value - * @param string $maxvalue The max value - * @param string $restartvalue The starting value - * @param string $cachevalue The cache value - * @param null|bool $cycledvalue True if cycled, false otherwise - * @param string $startvalue The sequence start value when issueing a restart - * - * @return int 0 success - */ - protected function _alterSequence( - $seqrs, - $name, - $comment, - $owner, - $schema, - $increment, - $minvalue, - $maxvalue, - $restartvalue, - $cachevalue, - $cycledvalue, - $startvalue - ) { - $this->fieldArrayClean($seqrs->fields); - - // Comment - $status = $this->setComment('SEQUENCE', $seqrs->fields['seqname'], '', $comment); - if ($status != 0) { - return -4; - } - - // Owner - $this->fieldClean($owner); - $status = $this->alterSequenceOwner($seqrs, $owner); - if ($status != 0) { - return -5; - } - - // Props - $this->clean($increment); - $this->clean($minvalue); - $this->clean($maxvalue); - $this->clean($restartvalue); - $this->clean($cachevalue); - $this->clean($cycledvalue); - $this->clean($startvalue); - $status = $this->alterSequenceProps( - $seqrs, - $increment, - $minvalue, - $maxvalue, - $restartvalue, - $cachevalue, - $cycledvalue, - $startvalue - ); - if ($status != 0) { - return -6; - } - - // Rename - $this->fieldClean($name); - $status = $this->alterSequenceName($seqrs, $name); - if ($status != 0) { - return -3; - } - - // Schema - $this->clean($schema); - $status = $this->alterSequenceSchema($seqrs, $schema); - if ($status != 0) { - return -7; - } - - return 0; - } - // Index functions /** @@ -393,7 +312,7 @@ trait SequenceTrait // careful to avoid this generally as changing owner is a // superuser only function. /* vars are cleaned in _alterSequence */ - if (!empty($owner) && ($seqrs->fields['seqowner'] != $owner)) { + if (!empty($owner) && ($seqrs->fields['seqowner'] !== $owner)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" OWNER TO \"{$owner}\""; @@ -430,36 +349,36 @@ trait SequenceTrait ) { $sql = ''; /* vars are cleaned in _alterSequence */ - if (!empty($increment) && ($increment != $seqrs->fields['increment_by'])) { + if (!empty($increment) && ($increment !== $seqrs->fields['increment_by'])) { $sql .= " INCREMENT {$increment}"; } - if (!empty($minvalue) && ($minvalue != $seqrs->fields['min_value'])) { + if (!empty($minvalue) && ($minvalue !== $seqrs->fields['min_value'])) { $sql .= " MINVALUE {$minvalue}"; } - if (!empty($maxvalue) && ($maxvalue != $seqrs->fields['max_value'])) { + if (!empty($maxvalue) && ($maxvalue !== $seqrs->fields['max_value'])) { $sql .= " MAXVALUE {$maxvalue}"; } - if (!empty($restartvalue) && ($restartvalue != $seqrs->fields['last_value'])) { + if (!empty($restartvalue) && ($restartvalue !== $seqrs->fields['last_value'])) { $sql .= " RESTART {$restartvalue}"; } - if (!empty($cachevalue) && ($cachevalue != $seqrs->fields['cache_value'])) { + if (!empty($cachevalue) && ($cachevalue !== $seqrs->fields['cache_value'])) { $sql .= " CACHE {$cachevalue}"; } - if (!empty($startvalue) && ($startvalue != $seqrs->fields['start_value'])) { + if (!empty($startvalue) && ($startvalue !== $seqrs->fields['start_value'])) { $sql .= " START {$startvalue}"; } // toggle cycle yes/no - if (!is_null($cycledvalue)) { - $sql .= (!$cycledvalue ? ' NO ' : '').' CYCLE'; + if (null !== $cycledvalue) { + $sql .= (!$cycledvalue ? ' NO ' : '') . ' CYCLE'; } - if ($sql != '') { + if ('' !== $sql) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" {$sql}"; @@ -481,12 +400,13 @@ trait SequenceTrait public function alterSequenceName($seqrs, $name) { /* vars are cleaned in _alterSequence */ - if (!empty($name) && ($seqrs->fields['seqname'] != $name)) { + if (!empty($name) && ($seqrs->fields['seqname'] !== $name)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status == 0) { + + if (0 === $status) { $seqrs->fields['seqname'] = $name; } else { return $status; @@ -509,7 +429,7 @@ trait SequenceTrait public function alterSequenceSchema($seqrs, $schema) { /* vars are cleaned in _alterSequence */ - if (!empty($schema) && ($seqrs->fields['nspname'] != $schema)) { + if (!empty($schema) && ($seqrs->fields['nspname'] !== $schema)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" SET SCHEMA {$schema}"; @@ -535,6 +455,7 @@ trait SequenceTrait $this->fieldClean($sequence); $sql = "DROP SEQUENCE \"{$f_schema}\".\"{$sequence}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -559,4 +480,96 @@ trait SequenceTrait abstract public function clean(&$str); abstract public function fieldArrayClean(&$arr); + + /** + * Protected method which alter a sequence + * SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION. + * + * @param \PHPPgAdmin\ADORecordSet $seqrs The sequence recordSet returned by getSequence() + * @param string $name The new name for the sequence + * @param string $comment The comment on the sequence + * @param string $owner The new owner for the sequence + * @param string $schema The new schema for the sequence + * @param string $increment The increment + * @param string $minvalue The min value + * @param string $maxvalue The max value + * @param string $restartvalue The starting value + * @param string $cachevalue The cache value + * @param null|bool $cycledvalue True if cycled, false otherwise + * @param string $startvalue The sequence start value when issueing a restart + * + * @return int 0 success + */ + protected function _alterSequence( + $seqrs, + $name, + $comment, + $owner, + $schema, + $increment, + $minvalue, + $maxvalue, + $restartvalue, + $cachevalue, + $cycledvalue, + $startvalue + ) { + $this->fieldArrayClean($seqrs->fields); + + // Comment + $status = $this->setComment('SEQUENCE', $seqrs->fields['seqname'], '', $comment); + + if (0 !== $status) { + return -4; + } + + // Owner + $this->fieldClean($owner); + $status = $this->alterSequenceOwner($seqrs, $owner); + + if (0 !== $status) { + return -5; + } + + // Props + $this->clean($increment); + $this->clean($minvalue); + $this->clean($maxvalue); + $this->clean($restartvalue); + $this->clean($cachevalue); + $this->clean($cycledvalue); + $this->clean($startvalue); + $status = $this->alterSequenceProps( + $seqrs, + $increment, + $minvalue, + $maxvalue, + $restartvalue, + $cachevalue, + $cycledvalue, + $startvalue + ); + + if (0 !== $status) { + return -6; + } + + // Rename + $this->fieldClean($name); + $status = $this->alterSequenceName($seqrs, $name); + + if (0 !== $status) { + return -3; + } + + // Schema + $this->clean($schema); + $status = $this->alterSequenceSchema($seqrs, $schema); + + if (0 !== $status) { + return -7; + } + + return 0; + } } diff --git a/src/database/databasetraits/StatsTrait.php b/src/database/databasetraits/StatsTrait.php index e15d14ea..2d2c1e69 100644 --- a/src/database/databasetraits/StatsTrait.php +++ b/src/database/databasetraits/StatsTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; diff --git a/src/database/databasetraits/TableTrait.php b/src/database/databasetraits/TableTrait.php index cfb21ff7..6b14e9aa 100644 --- a/src/database/databasetraits/TableTrait.php +++ b/src/database/databasetraits/TableTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -135,11 +138,12 @@ trait TableTrait * @param string $table The table to define * @param string $cleanprefix set to '-- ' to avoid issuing DROP statement */ - public function getTableDefPrefix($table, $cleanprefix = ''): ?string + public function getTableDefPrefix($table, $cleanprefix = ''): ? string { // Fetch table $t = $this->getTable($table); - if (!is_object($t) || $t->recordCount() != 1) { + + if (!\is_object($t) || 1 !== $t->recordCount()) { $this->rollbackTransaction(); return null; @@ -149,7 +153,8 @@ trait TableTrait // Fetch attributes $atts = $this->getTableAttributes($table); - if (!is_object($atts)) { + + if (!\is_object($atts)) { $this->rollbackTransaction(); return null; @@ -157,14 +162,15 @@ trait TableTrait // Fetch constraints $cons = $this->getConstraints($table); - if (!is_object($cons)) { + + if (!\is_object($cons)) { $this->rollbackTransaction(); return null; } // Output a reconnect command to create the table as the correct user - $sql = "-- PHPPgAdmin\n".$this->getChangeUserSQL($t->fields['relowner'])."\n\n"; + $sql = "-- PHPPgAdmin\n" . $this->getChangeUserSQL($t->fields['relowner']) . "\n\n"; $sql = $this->_dumpCreate($t, $sql, $cleanprefix); @@ -177,7 +183,7 @@ trait TableTrait $consOutput = $this->_dumpConstraints($cons, $table, $sql, $i, $num); - if ($consOutput === null) { + if (null === $consOutput) { return null; } $sql = $consOutput; @@ -222,26 +228,27 @@ trait TableTrait $colStorage = $this->_dumpColStats($atts, $t, $sql); - if ($colStorage === null) { + if (null === $colStorage) { return null; } $sql = $colStorage; // Comment - if ($t->fields['relcomment'] !== null) { + if (null !== $t->fields['relcomment']) { $this->clean($t->fields['relcomment']); $sql .= "\n-- Comment\n\n"; $sql .= "COMMENT ON TABLE \"{$t->fields['nspname']}\".\"{$t->fields['relname']}\" IS '{$t->fields['relcomment']}';\n"; } // Add comments on columns, if any - if ($col_comments_sql != '') { + if ('' !== $col_comments_sql) { $sql .= $col_comments_sql; } // Privileges $privs = $this->getPrivileges($table, 'table'); - if (!is_array($privs)) { + + if (!\is_array($privs)) { $this->rollbackTransaction(); return null; @@ -249,7 +256,7 @@ trait TableTrait $privsOutput = $this->_dumpPrivileges($privs, $t, $sql); - if ($privsOutput === null) { + if (null === $privsOutput) { return null; } $sql = $privsOutput; @@ -261,318 +268,6 @@ trait TableTrait } /** - * Dumps serial-like columns in the table. - * - * @param \PHPPgAdmin\ADORecordSet $atts table attributes - * @param \PHPPgAdmin\ADORecordSet $tblfields table fields object - * @param string $sql The sql sentence - * generated so far - * @param string $col_comments_sql Column comments, - * passed by reference - * @param int $i current counter to - * know if we should - * append a comma to the - * sentence - * @param int $num Table attributes - * count + table - * constraints count - * - * @return string original $sql plus appended strings - */ - private function _dumpSerials($atts, $tblfields, $sql, &$col_comments_sql, $i, $num) - { - while (!$atts->EOF) { - $this->fieldClean($atts->fields['attname']); - $sql .= " \"{$atts->fields['attname']}\""; - // Dump SERIAL and BIGSERIAL columns correctly - if ($this->phpBool($atts->fields['attisserial']) && - ($atts->fields['type'] == 'integer' || $atts->fields['type'] == 'bigint')) { - if ($atts->fields['type'] == 'integer') { - $sql .= ' SERIAL'; - } else { - $sql .= ' BIGSERIAL'; - } - } else { - $sql .= ' '.$this->formatType($atts->fields['type'], $atts->fields['atttypmod']); - - // Add NOT NULL if necessary - if ($this->phpBool($atts->fields['attnotnull'])) { - $sql .= ' NOT NULL'; - } - - // Add default if necessary - if ($atts->fields['adsrc'] !== null) { - $sql .= " DEFAULT {$atts->fields['adsrc']}"; - } - } - - // Output comma or not - if ($i < $num) { - $sql .= ",\n"; - } else { - $sql .= "\n"; - } - - // Does this column have a comment? - if ($atts->fields['comment'] !== null) { - $this->clean($atts->fields['comment']); - $col_comments_sql .= "COMMENT ON COLUMN \"{$tblfields->fields['relname']}\".\"{$atts->fields['attname']}\" IS '{$atts->fields['comment']}';\n"; - } - - $atts->moveNext(); - ++$i; - } - - return $sql; - } - - /** - * Dumps constraints. - * - * @param \PHPPgAdmin\ADORecordSet $cons The table constraints - * @param string $table The table to define - * @param string $sql The sql sentence generated so - * far - * @param mixed $i - * @param int $num Table attributes count + table - * constraints count - */ - private function _dumpConstraints($cons, $table, $sql, $i, $num): ?string - { - // Output all table constraints - while (!$cons->EOF) { - $this->fieldClean($cons->fields['conname']); - $sql .= " CONSTRAINT \"{$cons->fields['conname']}\" "; - // Nasty hack to support pre-7.4 PostgreSQL - if ($cons->fields['consrc'] !== null) { - $sql .= $cons->fields['consrc']; - } else { - switch ($cons->fields['contype']) { - case 'p': - $keys = $this->getAttributeNames($table, explode(' ', $cons->fields['indkey'])); - $sql .= 'PRIMARY KEY ('.join(',', $keys).')'; - - break; - case 'u': - $keys = $this->getAttributeNames($table, explode(' ', $cons->fields['indkey'])); - $sql .= 'UNIQUE ('.join(',', $keys).')'; - - break; - default: - // Unrecognised constraint - $this->rollbackTransaction(); - - return null; - } - } - - // Output comma or not - if ($i < $num) { - $sql .= ",\n"; - } else { - $sql .= "\n"; - } - - $cons->moveNext(); - ++$i; - } - - return $sql; - } - - /** - * Dumps col statistics. - * - * @param \PHPPgAdmin\ADORecordSet $atts table attributes - * @param \PHPPgAdmin\ADORecordSet $tblfields table field attributes - * @param string $sql The sql sentence generated so far - */ - private function _dumpColStats($atts, $tblfields, $sql): ?string - { - // Column storage and statistics - $atts->moveFirst(); - $first = true; - while (!$atts->EOF) { - $this->fieldClean($atts->fields['attname']); - // Statistics first - if ($atts->fields['attstattarget'] >= 0) { - if ($first) { - $sql .= "\n"; - $first = false; - } - $sql .= "ALTER TABLE ONLY \"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\" ALTER COLUMN \"{$atts->fields['attname']}\" SET STATISTICS {$atts->fields['attstattarget']};\n"; - } - // Then storage - if ($atts->fields['attstorage'] != $atts->fields['typstorage']) { - switch ($atts->fields['attstorage']) { - case 'p': - $storage = 'PLAIN'; - - break; - case 'e': - $storage = 'EXTERNAL'; - - break; - case 'm': - $storage = 'MAIN'; - - break; - case 'x': - $storage = 'EXTENDED'; - - break; - default: - // Unknown storage type - $this->rollbackTransaction(); - - return null; - } - $sql .= "ALTER TABLE ONLY \"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\" ALTER COLUMN \"{$atts->fields['attname']}\" SET STORAGE {$storage};\n"; - } - - $atts->moveNext(); - } - - return $sql; - } - - /** - * Dumps privileges. - * - * @param \PHPPgAdmin\ADORecordSet $privs The table privileges - * @param \PHPPgAdmin\ADORecordSet $tblfields The table fields definition - * @param string $sql The sql sentence generated so far - */ - private function _dumpPrivileges($privs, $tblfields, $sql): ?string - { - if (sizeof($privs) <= 0) { - return $sql; - } - $sql .= "\n-- Privileges\n\n"; - /* - * Always start with REVOKE ALL FROM PUBLIC, so that we don't have to - * wire-in knowledge about the default public privileges for different - * kinds of objects. - */ - $sql .= "REVOKE ALL ON TABLE \"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\" FROM PUBLIC;\n"; - foreach ($privs as $v) { - // Get non-GRANT OPTION privs - $nongrant = array_diff($v[2], $v[4]); - - // Skip empty or owner ACEs - if (sizeof($v[2]) == 0 || ($v[0] == 'user' && $v[1] == $tblfields->fields['relowner'])) { - continue; - } - - // Change user if necessary - if ($this->hasGrantOption() && $v[3] != $tblfields->fields['relowner']) { - $grantor = $v[3]; - $this->clean($grantor); - $sql .= "SET SESSION AUTHORIZATION '{$grantor}';\n"; - } - - // Output privileges with no GRANT OPTION - $sql .= 'GRANT '.join(', ', $nongrant)." ON TABLE \"{$tblfields->fields['relname']}\" TO "; - switch ($v[0]) { - case 'public': - $sql .= "PUBLIC;\n"; - - break; - case 'user': - case 'role': - $this->fieldClean($v[1]); - $sql .= "\"{$v[1]}\";\n"; - - break; - case 'group': - $this->fieldClean($v[1]); - $sql .= "GROUP \"{$v[1]}\";\n"; - - break; - default: - // Unknown privilege type - fail - $this->rollbackTransaction(); - - return null; - } - - // Reset user if necessary - if ($this->hasGrantOption() && $v[3] != $tblfields->fields['relowner']) { - $sql .= "RESET SESSION AUTHORIZATION;\n"; - } - - // Output privileges with GRANT OPTION - - // Skip empty or owner ACEs - if (!$this->hasGrantOption() || sizeof($v[4]) == 0) { - continue; - } - - // Change user if necessary - if ($this->hasGrantOption() && $v[3] != $tblfields->fields['relowner']) { - $grantor = $v[3]; - $this->clean($grantor); - $sql .= "SET SESSION AUTHORIZATION '{$grantor}';\n"; - } - - $sql .= 'GRANT '.join(', ', $v[4])." ON \"{$tblfields->fields['relname']}\" TO "; - switch ($v[0]) { - case 'public': - $sql .= 'PUBLIC'; - - break; - case 'user': - case 'role': - $this->fieldClean($v[1]); - $sql .= "\"{$v[1]}\""; - - break; - case 'group': - $this->fieldClean($v[1]); - $sql .= "GROUP \"{$v[1]}\""; - - break; - default: - // Unknown privilege type - fail - return null; - } - $sql .= " WITH GRANT OPTION;\n"; - - // Reset user if necessary - if ($this->hasGrantOption() && $v[3] != $tblfields->fields['relowner']) { - $sql .= "RESET SESSION AUTHORIZATION;\n"; - } - } - - return $sql; - } - - /** - * Dumps a create. - * - * @param \PHPPgAdmin\ADORecordSet $tblfields table fields object - * @param string $sql The sql sentence generated so far - * @param string $cleanprefix set to '-- ' to avoid issuing DROP statement - * @param mixed $fields - * - * @return string original $sql plus appended strings - */ - private function _dumpCreate($tblfields, $sql, $cleanprefix) - { - // Set schema search path - $sql .= "SET search_path = \"{$tblfields->fields['nspname']}\", pg_catalog;\n\n"; - - // Begin CREATE TABLE definition - $sql .= "-- Definition\n\n"; - // DROP TABLE must be fully qualified in case a table with the same name exists - $sql .= $cleanprefix.'DROP TABLE '; - $sql .= "\"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\";\n"; - $sql .= "CREATE TABLE \"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\" (\n"; - - return $sql; - } - - /** * Returns table information. * * @param string $table The name of the table @@ -589,7 +284,7 @@ trait TableTrait SELECT c.relname, n.nspname, '; - $sql .= ($this->hasRoles() ? ' coalesce(u.usename,r.rolname) ' : ' u.usename')." AS relowner, + $sql .= ($this->hasRoles() ? ' coalesce(u.usename,r.rolname) ' : ' u.usename') . " AS relowner, pg_catalog.obj_description(c.oid, 'pg_class') AS relcomment, pt.spcname AS tablespace FROM pg_catalog.pg_class c @@ -597,7 +292,7 @@ trait TableTrait LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "; - $sql .= ($this->hasRoles() ? ' LEFT JOIN pg_catalog.pg_roles r ON c.relowner = r.oid ' : ''). + $sql .= ($this->hasRoles() ? ' LEFT JOIN pg_catalog.pg_roles r ON c.relowner = r.oid ' : '') . " WHERE c.relkind = 'r' AND n.nspname = '{$c_schema}' AND n.oid = c.relnamespace @@ -607,91 +302,6 @@ trait TableTrait } /** - * Retrieve all attributes definition of a table. - * - * @param string $table The name of the table - * @param string $c_schema The name of the schema - * - * @return int|\PHPPgAdmin\ADORecordSet - */ - private function _getTableAttributesAll($table, $c_schema) - { - $sql = " - SELECT - a.attname, - a.attnum, - pg_catalog.format_type(a.atttypid, a.atttypmod) AS TYPE, - a.atttypmod, - a.attnotnull, - a.atthasdef, - pg_catalog.pg_get_expr(adef.adbin, adef.adrelid, TRUE) AS adsrc, - a.attstattarget, - a.attstorage, - t.typstorage, - CASE - WHEN pc.oid IS NULL THEN FALSE - ELSE TRUE - END AS attisserial, - pg_catalog.col_description(a.attrelid, a.attnum) AS COMMENT - - FROM pg_catalog.pg_tables tbl - JOIN pg_catalog.pg_class tbl_class ON tbl.tablename=tbl_class.relname - JOIN pg_catalog.pg_attribute a ON tbl_class.oid = a.attrelid - JOIN pg_catalog.pg_namespace ON pg_namespace.oid = tbl_class.relnamespace - AND pg_namespace.nspname=tbl.schemaname - LEFT JOIN pg_catalog.pg_attrdef adef ON a.attrelid=adef.adrelid - AND a.attnum=adef.adnum - LEFT JOIN pg_catalog.pg_type t ON a.atttypid=t.oid - LEFT JOIN pg_catalog.pg_depend pd ON pd.refobjid=a.attrelid - AND pd.refobjsubid=a.attnum - AND pd.deptype='i' - LEFT JOIN pg_catalog.pg_class pc ON pd.objid=pc.oid - AND pd.classid=pc.tableoid - AND pd.refclassid=pc.tableoid - AND pc.relkind='S' - WHERE tbl.tablename='{$table}' - AND tbl.schemaname='{$c_schema}' - AND a.attnum > 0 AND NOT a.attisdropped - ORDER BY a.attnum"; - - return $this->selectSet($sql); - } - - /** - * Retrieve single attribute definition of a table. - * - * @param string $table The name of the table - * @param string $c_schema The schema of the table - * @param string $field (optional) The name of a field to return - * - * @return int|\PHPPgAdmin\ADORecordSet - */ - private function _getTableAttribute($table, $c_schema, $field) - { - $sql = " - SELECT - a.attname, a.attnum, - pg_catalog.format_type(a.atttypid, a.atttypmod) as type, - pg_catalog.format_type(a.atttypid, NULL) as base_type, - a.atttypmod, - a.attnotnull, a.atthasdef, pg_catalog.pg_get_expr(adef.adbin, adef.adrelid, true) as adsrc, - a.attstattarget, a.attstorage, t.typstorage, - pg_catalog.col_description(a.attrelid, a.attnum) AS comment - FROM - pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef adef - ON a.attrelid=adef.adrelid - AND a.attnum=adef.adnum - LEFT JOIN pg_catalog.pg_type t ON a.atttypid=t.oid - WHERE - a.attrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}' - AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE - nspname = '{$c_schema}')) - AND a.attname = '{$field}'"; - - return $this->selectSet($sql); - } - - /** * Retrieve the attribute definition of a table. * * @param string $table The name of the table @@ -705,7 +315,7 @@ trait TableTrait $this->clean($c_schema); $this->clean($table); - if ($field == '') { + if ('' === $field) { // This query is made much more complex by the addition of the 'attisserial' field. // The subquery to get that field checks to see if there is an internally dependent // sequence on the field. @@ -780,7 +390,8 @@ trait TableTrait AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='{$c_schema}')"; $rs = $this->selectSet($sql); - if ($rs->recordCount() != 1) { + + if (1 !== $rs->recordCount()) { return null; } @@ -795,22 +406,24 @@ trait TableTrait * * @param string $table The table to define */ - public function getTableDefSuffix($table): ?string + public function getTableDefSuffix($table) : ? string { $sql = ''; // Indexes $indexes = $this->getIndexes($table); - if (!is_object($indexes)) { + + if (!\is_object($indexes)) { $this->rollbackTransaction(); return null; } - if ($indexes->recordCount() > 0) { + if (0 < $indexes->recordCount()) { $sql .= "\n-- Indexes\n\n"; + while (!$indexes->EOF) { - $sql .= $indexes->fields['inddef'].";\n"; + $sql .= $indexes->fields['inddef'] . ";\n"; $indexes->moveNext(); } @@ -818,14 +431,16 @@ trait TableTrait // Triggers $triggers = $this->getTriggers($table); - if (!is_object($triggers)) { + + if (!\is_object($triggers)) { $this->rollbackTransaction(); return null; } - if ($triggers->recordCount() > 0) { + if (0 < $triggers->recordCount()) { $sql .= "\n-- Triggers\n\n"; + while (!$triggers->EOF) { $sql .= $triggers->fields['tgdef']; $sql .= ";\n"; @@ -836,16 +451,18 @@ trait TableTrait // Rules $rules = $this->getRules($table); - if (!is_object($rules)) { + + if (!\is_object($rules)) { $this->rollbackTransaction(); return null; } - if ($rules->recordCount() > 0) { + if (0 < $rules->recordCount()) { $sql .= "\n-- Rules\n\n"; + while (!$rules->EOF) { - $sql .= $rules->fields['definition']."\n"; + $sql .= $rules->fields['definition'] . "\n"; $rules->moveNext(); } @@ -873,6 +490,7 @@ trait TableTrait WHERE c.relname = '{$table}' AND pg_catalog.pg_table_is_visible(c.oid) AND c.oid = i.indrelid AND i.indexrelid = c2.oid "; + if ($unique) { $sql .= ' AND i.indisunique '; } @@ -978,7 +596,8 @@ trait TableTrait $this->fieldClean($name); $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } @@ -986,6 +605,7 @@ trait TableTrait $first = true; $comment_sql = ''; //Accumulate comments for the columns $sql = "CREATE TABLE \"{$f_schema}\".\"{$name}\" ("; + for ($i = 0; $i < $fields; ++$i) { $this->fieldClean($field[$i]); $this->clean($type[$i]); @@ -993,7 +613,7 @@ trait TableTrait $this->clean($colcomment[$i]); // Skip blank columns - for user convenience - if ($field[$i] == '' || $type[$i] == '') { + if ('' === $field[$i] || '' === $type[$i]) { continue; } @@ -1009,9 +629,10 @@ trait TableTrait // time zone types case 'timestamp with time zone': case 'timestamp without time zone': - $qual = substr($type[$i], 9); + $qual = \mb_substr($type[$i], 9); $sql .= "\"{$field[$i]}\" timestamp"; - if ($length[$i] != '') { + + if ('' !== $length[$i]) { $sql .= "({$length[$i]})"; } @@ -1020,9 +641,10 @@ trait TableTrait break; case 'time with time zone': case 'time without time zone': - $qual = substr($type[$i], 4); + $qual = \mb_substr($type[$i], 4); $sql .= "\"{$field[$i]}\" time"; - if ($length[$i] != '') { + + if ('' !== $length[$i]) { $sql .= "({$length[$i]})"; } @@ -1031,12 +653,13 @@ trait TableTrait break; default: $sql .= "\"{$field[$i]}\" {$type[$i]}"; - if ($length[$i] != '') { + + if ('' !== $length[$i]) { $sql .= "({$length[$i]})"; } } // Add array qualifier if necessary - if ($array[$i] == '[]') { + if ('[]' === $array[$i]) { $sql .= '[]'; } @@ -1050,11 +673,12 @@ trait TableTrait $sql .= ' NOT NULL'; } } - if ($default[$i] != '') { + + if ('' !== $default[$i]) { $sql .= " DEFAULT {$default[$i]}"; } - if ($colcomment[$i] != '') { + if ('' !== $colcomment[$i]) { $comment_sql .= "COMMENT ON COLUMN \"{$name}\".\"{$field[$i]}\" IS '{$colcomment[$i]}';\n"; } @@ -1067,13 +691,15 @@ trait TableTrait // PRIMARY KEY $primarykeycolumns = []; + for ($i = 0; $i < $fields; ++$i) { if (isset($primarykey[$i])) { $primarykeycolumns[] = "\"{$field[$i]}\""; } } - if (count($primarykeycolumns) > 0) { - $sql .= ', PRIMARY KEY ('.implode(', ', $primarykeycolumns).')'; + + if (0 < \count($primarykeycolumns)) { + $sql .= ', PRIMARY KEY (' . \implode(', ', $primarykeycolumns) . ')'; } $sql .= ')'; @@ -1086,20 +712,22 @@ trait TableTrait } // Tablespace - if ($this->hasTablespaces() && $tablespace != '') { + if ($this->hasTablespaces() && '' !== $tablespace) { $this->fieldClean($tablespace); $sql .= " TABLESPACE \"{$tablespace}\""; } $status = $this->execute($sql); + if ($status) { $this->rollbackTransaction(); return -1; } - if ($tblcomment != '') { + if ('' !== $tblcomment) { $status = $this->setComment('TABLE', '', $name, $tblcomment, true); + if ($status) { $this->rollbackTransaction(); @@ -1107,8 +735,9 @@ trait TableTrait } } - if ($comment_sql != '') { + if ('' !== $comment_sql) { $status = $this->execute($comment_sql); + if ($status) { $this->rollbackTransaction(); @@ -1145,7 +774,8 @@ trait TableTrait $like = "\"{$like['schema']}\".\"{$like['table']}\""; $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } @@ -1165,12 +795,13 @@ trait TableTrait $sql .= ')'; - if ($this->hasTablespaces() && $tablespace != '') { + if ($this->hasTablespaces() && '' !== $tablespace) { $this->fieldClean($tablespace); $sql .= " TABLESPACE \"{$tablespace}\""; } $status = $this->execute($sql); + if ($status) { $this->rollbackTransaction(); @@ -1196,12 +827,13 @@ trait TableTrait { $data = $this->getTable($table); - if ($data->recordCount() != 1) { + if (1 !== $data->recordCount()) { return -2; } $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -1209,7 +841,7 @@ trait TableTrait $status = $this->_alterTable($data, $name, $owner, $schema, $comment, $tablespace); - if ($status != 0) { + if (0 !== $status) { $this->rollbackTransaction(); return $status; @@ -1219,60 +851,6 @@ trait TableTrait } /** - * Protected method which alter a table - * SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION. - * - * @param \PHPPgAdmin\ADORecordSet $tblrs The table recordSet returned by getTable() - * @param string $name The new name for the table - * @param string $owner The new owner for the table - * @param string $schema The new schema for the table - * @param string $comment The comment on the table - * @param string $tablespace The new tablespace for the table ('' means leave as is) - * - * @return int 0 success - */ - protected function _alterTable($tblrs, $name, $owner, $schema, $comment, $tablespace) - { - $this->fieldArrayClean($tblrs->fields); - - // Comment - $status = $this->setComment('TABLE', '', $tblrs->fields['relname'], $comment); - if ($status != 0) { - return -4; - } - - // Owner - $this->fieldClean($owner); - $status = $this->alterTableOwner($tblrs, $owner); - if ($status != 0) { - return -5; - } - - // Tablespace - $this->fieldClean($tablespace); - $status = $this->alterTableTablespace($tblrs, $tablespace); - if ($status != 0) { - return -6; - } - - // Rename - $this->fieldClean($name); - $status = $this->alterTableName($tblrs, $name); - if ($status != 0) { - return -3; - } - - // Schema - $this->fieldClean($schema); - $status = $this->alterTableSchema($tblrs, $schema); - if ($status != 0) { - return -7; - } - - return 0; - } - - /** * Alter a table's owner * /!\ this function is called from _alterTable which take care of escaping fields. * @@ -1284,7 +862,7 @@ trait TableTrait public function alterTableOwner($tblrs, $owner = null) { /* vars cleaned in _alterTable */ - if (!empty($owner) && ($tblrs->fields['relowner'] != $owner)) { + if (!empty($owner) && ($tblrs->fields['relowner'] !== $owner)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); // If owner has been changed, then do the alteration. We are @@ -1310,7 +888,7 @@ trait TableTrait public function alterTableTablespace($tblrs, $tablespace = null) { /* vars cleaned in _alterTable */ - if (!empty($tablespace) && ($tblrs->fields['tablespace'] != $tablespace)) { + if (!empty($tablespace) && ($tblrs->fields['tablespace'] !== $tablespace)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); @@ -1337,13 +915,14 @@ trait TableTrait { /* vars cleaned in _alterTable */ // Rename (only if name has changed) - if (!empty($name) && ($name != $tblrs->fields['relname'])) { + if (!empty($name) && ($name !== $tblrs->fields['relname'])) { $f_schema = $this->_schema; $this->fieldClean($f_schema); $sql = "ALTER TABLE \"{$f_schema}\".\"{$tblrs->fields['relname']}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status == 0) { + + if (0 === $status) { $tblrs->fields['relname'] = $name; } else { return $status; @@ -1367,7 +946,7 @@ trait TableTrait public function alterTableSchema($tblrs, $schema = null) { /* vars cleaned in _alterTable */ - if (!empty($schema) && ($tblrs->fields['nspname'] != $schema)) { + if (!empty($schema) && ($tblrs->fields['nspname'] !== $schema)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); // If tablespace has been changed, then do the alteration. We @@ -1395,8 +974,9 @@ trait TableTrait $this->fieldClean($table); $sql = "TRUNCATE TABLE \"{$f_schema}\".\"{$table}\" "; + if ($cascade) { - $sql = $sql.' CASCADE'; + $sql = $sql . ' CASCADE'; } $status = $this->execute($sql); @@ -1419,6 +999,7 @@ trait TableTrait $this->fieldClean($table); $sql = "DROP TABLE \"{$f_schema}\".\"{$table}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -1436,14 +1017,16 @@ trait TableTrait { // Begin serializable transaction (to dump consistent data) $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } // Set serializable $sql = 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE'; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -1452,7 +1035,8 @@ trait TableTrait // Set datestyle to ISO $sql = 'SET DATESTYLE = ISO'; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -1461,7 +1045,8 @@ trait TableTrait // Set extra_float_digits to 2 $sql = 'SET extra_float_digits TO 2'; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -1496,7 +1081,7 @@ trait TableTrait // Actually retrieve the rows if ($oids) { - $oid_str = $this->id.', '; + $oid_str = $this->id . ', '; } else { $oid_str = ''; } @@ -1515,7 +1100,7 @@ trait TableTrait { $sql = ''; - if ($table !== '') { + if ('' !== $table) { $this->clean($table); $c_schema = $this->_schema; $this->clean($c_schema); @@ -1543,14 +1128,15 @@ trait TableTrait /* result aray to return as RS */ $autovacs = []; + while (!$_autovacs->EOF) { $_ = [ 'nspname' => $_autovacs->fields['nspname'], 'relname' => $_autovacs->fields['relname'], ]; - foreach (explode(',', $_autovacs->fields['reloptions']) as $var) { - list($o, $v) = explode('=', $var); + foreach (\explode(',', $_autovacs->fields['reloptions']) as $var) { + list($o, $v) = \explode('=', $var); $_[$o] = $v; } @@ -1612,32 +1198,38 @@ trait TableTrait $this->clean($vacenabled); $params[] = "autovacuum_enabled='{$vacenabled}'"; } + if (!empty($vacthreshold)) { $this->clean($vacthreshold); $params[] = "autovacuum_vacuum_threshold='{$vacthreshold}'"; } + if (!empty($vacscalefactor)) { $this->clean($vacscalefactor); $params[] = "autovacuum_vacuum_scale_factor='{$vacscalefactor}'"; } + if (!empty($anathresold)) { $this->clean($anathresold); $params[] = "autovacuum_analyze_threshold='{$anathresold}'"; } + if (!empty($anascalefactor)) { $this->clean($anascalefactor); $params[] = "autovacuum_analyze_scale_factor='{$anascalefactor}'"; } + if (!empty($vaccostdelay)) { $this->clean($vaccostdelay); $params[] = "autovacuum_vacuum_cost_delay='{$vaccostdelay}'"; } + if (!empty($vaccostlimit)) { $this->clean($vaccostlimit); $params[] = "autovacuum_vacuum_cost_limit='{$vaccostlimit}'"; } - $sql = $sql.implode(',', $params).');'; + $sql = $sql . \implode(',', $params) . ');'; return $this->execute($sql); } @@ -1703,4 +1295,464 @@ trait TableTrait abstract public function hasCreateFieldWithConstraints(); abstract public function getAttributeNames($table, $atts); + + /** + * Protected method which alter a table + * SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION. + * + * @param \PHPPgAdmin\ADORecordSet $tblrs The table recordSet returned by getTable() + * @param string $name The new name for the table + * @param string $owner The new owner for the table + * @param string $schema The new schema for the table + * @param string $comment The comment on the table + * @param string $tablespace The new tablespace for the table ('' means leave as is) + * + * @return int 0 success + */ + protected function _alterTable($tblrs, $name, $owner, $schema, $comment, $tablespace) + { + $this->fieldArrayClean($tblrs->fields); + + // Comment + $status = $this->setComment('TABLE', '', $tblrs->fields['relname'], $comment); + + if (0 !== $status) { + return -4; + } + + // Owner + $this->fieldClean($owner); + $status = $this->alterTableOwner($tblrs, $owner); + + if (0 !== $status) { + return -5; + } + + // Tablespace + $this->fieldClean($tablespace); + $status = $this->alterTableTablespace($tblrs, $tablespace); + + if (0 !== $status) { + return -6; + } + + // Rename + $this->fieldClean($name); + $status = $this->alterTableName($tblrs, $name); + + if (0 !== $status) { + return -3; + } + + // Schema + $this->fieldClean($schema); + $status = $this->alterTableSchema($tblrs, $schema); + + if (0 !== $status) { + return -7; + } + + return 0; + } + + /** + * Dumps serial-like columns in the table. + * + * @param \PHPPgAdmin\ADORecordSet $atts table attributes + * @param \PHPPgAdmin\ADORecordSet $tblfields table fields object + * @param string $sql The sql sentence + * generated so far + * @param string $col_comments_sql Column comments, + * passed by reference + * @param int $i current counter to + * know if we should + * append a comma to the + * sentence + * @param int $num Table attributes + * count + table + * constraints count + * + * @return string original $sql plus appended strings + */ + private function _dumpSerials($atts, $tblfields, $sql, &$col_comments_sql, $i, $num) + { + while (!$atts->EOF) { + $this->fieldClean($atts->fields['attname']); + $sql .= " \"{$atts->fields['attname']}\""; + // Dump SERIAL and BIGSERIAL columns correctly + if ($this->phpBool($atts->fields['attisserial']) && + ('integer' === $atts->fields['type'] || 'bigint' === $atts->fields['type'])) { + if ('integer' === $atts->fields['type']) { + $sql .= ' SERIAL'; + } else { + $sql .= ' BIGSERIAL'; + } + } else { + $sql .= ' ' . $this->formatType($atts->fields['type'], $atts->fields['atttypmod']); + + // Add NOT NULL if necessary + if ($this->phpBool($atts->fields['attnotnull'])) { + $sql .= ' NOT NULL'; + } + + // Add default if necessary + if (null !== $atts->fields['adsrc']) { + $sql .= " DEFAULT {$atts->fields['adsrc']}"; + } + } + + // Output comma or not + if ($i < $num) { + $sql .= ",\n"; + } else { + $sql .= "\n"; + } + + // Does this column have a comment? + if (null !== $atts->fields['comment']) { + $this->clean($atts->fields['comment']); + $col_comments_sql .= "COMMENT ON COLUMN \"{$tblfields->fields['relname']}\".\"{$atts->fields['attname']}\" IS '{$atts->fields['comment']}';\n"; + } + + $atts->moveNext(); + ++$i; + } + + return $sql; + } + + /** + * Dumps constraints. + * + * @param \PHPPgAdmin\ADORecordSet $cons The table constraints + * @param string $table The table to define + * @param string $sql The sql sentence generated so + * far + * @param mixed $i + * @param int $num Table attributes count + table + * constraints count + */ + private function _dumpConstraints($cons, $table, $sql, $i, $num): ? string + { + // Output all table constraints + while (!$cons->EOF) { + $this->fieldClean($cons->fields['conname']); + $sql .= " CONSTRAINT \"{$cons->fields['conname']}\" "; + // Nasty hack to support pre-7.4 PostgreSQL + if (null !== $cons->fields['consrc']) { + $sql .= $cons->fields['consrc']; + } else { + switch ($cons->fields['contype']) { + case 'p': + $keys = $this->getAttributeNames($table, \explode(' ', $cons->fields['indkey'])); + $sql .= 'PRIMARY KEY (' . \implode(',', $keys) . ')'; + + break; + case 'u': + $keys = $this->getAttributeNames($table, \explode(' ', $cons->fields['indkey'])); + $sql .= 'UNIQUE (' . \implode(',', $keys) . ')'; + + break; + default: + // Unrecognised constraint + $this->rollbackTransaction(); + + return null; + } + } + + // Output comma or not + if ($i < $num) { + $sql .= ",\n"; + } else { + $sql .= "\n"; + } + + $cons->moveNext(); + ++$i; + } + + return $sql; + } + + /** + * Dumps col statistics. + * + * @param \PHPPgAdmin\ADORecordSet $atts table attributes + * @param \PHPPgAdmin\ADORecordSet $tblfields table field attributes + * @param string $sql The sql sentence generated so far + */ + private function _dumpColStats($atts, $tblfields, $sql): ? string + { + // Column storage and statistics + $atts->moveFirst(); + $first = true; + + while (!$atts->EOF) { + $this->fieldClean($atts->fields['attname']); + // Statistics first + if (0 <= $atts->fields['attstattarget']) { + if ($first) { + $sql .= "\n"; + $first = false; + } + $sql .= "ALTER TABLE ONLY \"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\" ALTER COLUMN \"{$atts->fields['attname']}\" SET STATISTICS {$atts->fields['attstattarget']};\n"; + } + // Then storage + if ($atts->fields['attstorage'] !== $atts->fields['typstorage']) { + switch ($atts->fields['attstorage']) { + case 'p': + $storage = 'PLAIN'; + + break; + case 'e': + $storage = 'EXTERNAL'; + + break; + case 'm': + $storage = 'MAIN'; + + break; + case 'x': + $storage = 'EXTENDED'; + + break; + default: + // Unknown storage type + $this->rollbackTransaction(); + + return null; + } + $sql .= "ALTER TABLE ONLY \"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\" ALTER COLUMN \"{$atts->fields['attname']}\" SET STORAGE {$storage};\n"; + } + + $atts->moveNext(); + } + + return $sql; + } + + /** + * Dumps privileges. + * + * @param \PHPPgAdmin\ADORecordSet $privs The table privileges + * @param \PHPPgAdmin\ADORecordSet $tblfields The table fields definition + * @param string $sql The sql sentence generated so far + */ + private function _dumpPrivileges($privs, $tblfields, $sql): ? string + { + if (0 >= \count($privs)) { + return $sql; + } + $sql .= "\n-- Privileges\n\n"; + /* + * Always start with REVOKE ALL FROM PUBLIC, so that we don't have to + * wire-in knowledge about the default public privileges for different + * kinds of objects. + */ + $sql .= "REVOKE ALL ON TABLE \"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\" FROM PUBLIC;\n"; + + foreach ($privs as $v) { + // Get non-GRANT OPTION privs + $nongrant = \array_diff($v[2], $v[4]); + + // Skip empty or owner ACEs + if (0 === \count($v[2]) || ('user' === $v[0] && $v[1] === $tblfields->fields['relowner'])) { + continue; + } + + // Change user if necessary + if ($this->hasGrantOption() && $v[3] !== $tblfields->fields['relowner']) { + $grantor = $v[3]; + $this->clean($grantor); + $sql .= "SET SESSION AUTHORIZATION '{$grantor}';\n"; + } + + // Output privileges with no GRANT OPTION + $sql .= 'GRANT ' . \implode(', ', $nongrant) . " ON TABLE \"{$tblfields->fields['relname']}\" TO "; + + switch ($v[0]) { + case 'public': + $sql .= "PUBLIC;\n"; + + break; + case 'user': + case 'role': + $this->fieldClean($v[1]); + $sql .= "\"{$v[1]}\";\n"; + + break; + case 'group': + $this->fieldClean($v[1]); + $sql .= "GROUP \"{$v[1]}\";\n"; + + break; + default: + // Unknown privilege type - fail + $this->rollbackTransaction(); + + return null; + } + + // Reset user if necessary + if ($this->hasGrantOption() && $v[3] !== $tblfields->fields['relowner']) { + $sql .= "RESET SESSION AUTHORIZATION;\n"; + } + + // Output privileges with GRANT OPTION + + // Skip empty or owner ACEs + if (!$this->hasGrantOption() || 0 === \count($v[4])) { + continue; + } + + // Change user if necessary + if ($this->hasGrantOption() && $v[3] !== $tblfields->fields['relowner']) { + $grantor = $v[3]; + $this->clean($grantor); + $sql .= "SET SESSION AUTHORIZATION '{$grantor}';\n"; + } + + $sql .= 'GRANT ' . \implode(', ', $v[4]) . " ON \"{$tblfields->fields['relname']}\" TO "; + + switch ($v[0]) { + case 'public': + $sql .= 'PUBLIC'; + + break; + case 'user': + case 'role': + $this->fieldClean($v[1]); + $sql .= "\"{$v[1]}\""; + + break; + case 'group': + $this->fieldClean($v[1]); + $sql .= "GROUP \"{$v[1]}\""; + + break; + default: + // Unknown privilege type - fail + return null; + } + $sql .= " WITH GRANT OPTION;\n"; + + // Reset user if necessary + if ($this->hasGrantOption() && $v[3] !== $tblfields->fields['relowner']) { + $sql .= "RESET SESSION AUTHORIZATION;\n"; + } + } + + return $sql; + } + + /** + * Dumps a create. + * + * @param \PHPPgAdmin\ADORecordSet $tblfields table fields object + * @param string $sql The sql sentence generated so far + * @param string $cleanprefix set to '-- ' to avoid issuing DROP statement + * @param mixed $fields + * + * @return string original $sql plus appended strings + */ + private function _dumpCreate($tblfields, $sql, $cleanprefix) + { + // Set schema search path + $sql .= "SET search_path = \"{$tblfields->fields['nspname']}\", pg_catalog;\n\n"; + + // Begin CREATE TABLE definition + $sql .= "-- Definition\n\n"; + // DROP TABLE must be fully qualified in case a table with the same name exists + $sql .= $cleanprefix . 'DROP TABLE '; + $sql .= "\"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\";\n"; + $sql .= "CREATE TABLE \"{$tblfields->fields['nspname']}\".\"{$tblfields->fields['relname']}\" (\n"; + + return $sql; + } + + /** + * Retrieve all attributes definition of a table. + * + * @param string $table The name of the table + * @param string $c_schema The name of the schema + * + * @return int|\PHPPgAdmin\ADORecordSet + */ + private function _getTableAttributesAll($table, $c_schema) + { + $sql = " + SELECT + a.attname, + a.attnum, + pg_catalog.format_type(a.atttypid, a.atttypmod) AS TYPE, + a.atttypmod, + a.attnotnull, + a.atthasdef, + pg_catalog.pg_get_expr(adef.adbin, adef.adrelid, TRUE) AS adsrc, + a.attstattarget, + a.attstorage, + t.typstorage, + CASE + WHEN pc.oid IS NULL THEN FALSE + ELSE TRUE + END AS attisserial, + pg_catalog.col_description(a.attrelid, a.attnum) AS COMMENT + + FROM pg_catalog.pg_tables tbl + JOIN pg_catalog.pg_class tbl_class ON tbl.tablename=tbl_class.relname + JOIN pg_catalog.pg_attribute a ON tbl_class.oid = a.attrelid + JOIN pg_catalog.pg_namespace ON pg_namespace.oid = tbl_class.relnamespace + AND pg_namespace.nspname=tbl.schemaname + LEFT JOIN pg_catalog.pg_attrdef adef ON a.attrelid=adef.adrelid + AND a.attnum=adef.adnum + LEFT JOIN pg_catalog.pg_type t ON a.atttypid=t.oid + LEFT JOIN pg_catalog.pg_depend pd ON pd.refobjid=a.attrelid + AND pd.refobjsubid=a.attnum + AND pd.deptype='i' + LEFT JOIN pg_catalog.pg_class pc ON pd.objid=pc.oid + AND pd.classid=pc.tableoid + AND pd.refclassid=pc.tableoid + AND pc.relkind='S' + WHERE tbl.tablename='{$table}' + AND tbl.schemaname='{$c_schema}' + AND a.attnum > 0 AND NOT a.attisdropped + ORDER BY a.attnum"; + + return $this->selectSet($sql); + } + + /** + * Retrieve single attribute definition of a table. + * + * @param string $table The name of the table + * @param string $c_schema The schema of the table + * @param string $field (optional) The name of a field to return + * + * @return int|\PHPPgAdmin\ADORecordSet + */ + private function _getTableAttribute($table, $c_schema, $field) + { + $sql = " + SELECT + a.attname, a.attnum, + pg_catalog.format_type(a.atttypid, a.atttypmod) as type, + pg_catalog.format_type(a.atttypid, NULL) as base_type, + a.atttypmod, + a.attnotnull, a.atthasdef, pg_catalog.pg_get_expr(adef.adbin, adef.adrelid, true) as adsrc, + a.attstattarget, a.attstorage, t.typstorage, + pg_catalog.col_description(a.attrelid, a.attnum) AS comment + FROM + pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef adef + ON a.attrelid=adef.adrelid + AND a.attnum=adef.adnum + LEFT JOIN pg_catalog.pg_type t ON a.atttypid=t.oid + WHERE + a.attrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}' + AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE + nspname = '{$c_schema}')) + AND a.attname = '{$field}'"; + + return $this->selectSet($sql); + } } diff --git a/src/database/databasetraits/TablespaceTrait.php b/src/database/databasetraits/TablespaceTrait.php index 8ac8cfbb..f42f4f10 100644 --- a/src/database/databasetraits/TablespaceTrait.php +++ b/src/database/databasetraits/TablespaceTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -72,7 +75,7 @@ trait TablespaceTrait $sql = "CREATE TABLESPACE \"{$spcname}\""; - if ($spcowner != '') { + if ('' !== $spcowner) { $this->fieldClean($spcowner); $sql .= " OWNER \"{$spcowner}\""; } @@ -80,13 +83,15 @@ trait TablespaceTrait $sql .= " LOCATION '{$spcloc}'"; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { return -1; } - if ($comment != '' && $this->hasSharedComments()) { + if ('' !== $comment && $this->hasSharedComments()) { $status = $this->setComment('TABLESPACE', $spcname, '', $comment); - if ($status != 0) { + + if (0 !== $status) { return -2; } } @@ -112,24 +117,27 @@ trait TablespaceTrait // Begin transaction $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } // Owner $sql = "ALTER TABLESPACE \"{$spcname}\" OWNER TO \"{$owner}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -2; } // Rename (only if name has changed) - if ($name != $spcname) { + if ($name !== $spcname) { $sql = "ALTER TABLESPACE \"{$spcname}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -3; @@ -139,9 +147,10 @@ trait TablespaceTrait } // Set comment if it has changed - if (trim($comment) != '' && $this->hasSharedComments()) { + if ('' !== \trim($comment) && $this->hasSharedComments()) { $status = $this->setComment('TABLESPACE', $spcname, '', $comment); - if ($status != 0) { + + if (0 !== $status) { return -4; } } diff --git a/src/database/databasetraits/TriggerTrait.php b/src/database/databasetraits/TriggerTrait.php index b11ad1fa..a65e8ad9 100644 --- a/src/database/databasetraits/TriggerTrait.php +++ b/src/database/databasetraits/TriggerTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -104,6 +107,7 @@ trait TriggerTrait $this->fieldClean($table); $sql = "DROP TRIGGER \"{$tgname}\" ON \"{$f_schema}\".\"{$table}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -196,27 +200,30 @@ trait TriggerTrait $this->fieldClean($f_schema); $this->fieldClean($name); $this->fieldClean($table); - if (!in_array($event, $this->rule_events, true)) { + + if (!\in_array($event, $this->rule_events, true)) { return -1; } $sql = 'CREATE'; + if ($replace) { $sql .= ' OR REPLACE'; } $sql .= " RULE \"{$name}\" AS ON {$event} TO \"{$f_schema}\".\"{$table}\""; // Can't escape WHERE clause - if ($where != '') { + if ('' !== $where) { $sql .= " WHERE {$where}"; } $sql .= ' DO'; + if ($instead) { $sql .= ' INSTEAD'; } - if ($type == 'NOTHING') { + if ('NOTHING' === $type) { $sql .= ' NOTHING'; } else { $sql .= " ({$action})"; @@ -242,6 +249,7 @@ trait TriggerTrait $this->fieldClean($relation); $sql = "DROP RULE \"{$rule}\" ON \"{$f_schema}\".\"{$relation}\""; + if ($cascade) { $sql .= ' CASCADE'; } diff --git a/src/database/databasetraits/TypeTrait.php b/src/database/databasetraits/TypeTrait.php index a487603a..a8a677c6 100644 --- a/src/database/databasetraits/TypeTrait.php +++ b/src/database/databasetraits/TypeTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -27,26 +30,30 @@ trait TypeTrait // If the first character is an underscore, it's an array type $is_array = false; - if (substr($typname, 0, 1) == '_') { + + if ('_' === \mb_substr($typname, 0, 1)) { $is_array = true; - $typname = substr($typname, 1); + $typname = \mb_substr($typname, 1); } // Show lengths on bpchar and varchar - if ($typname == 'bpchar') { + if ('bpchar' === $typname) { $len = $typmod - $varhdrsz; $temp = 'character'; - if ($len > 1) { + + if (1 < $len) { $temp .= "({$len})"; } - } elseif ($typname == 'varchar') { + } elseif ('varchar' === $typname) { $temp = 'character varying'; - if ($typmod != -1) { - $temp .= '('.($typmod - $varhdrsz).')'; + + if (-1 !== $typmod) { + $temp .= '(' . ($typmod - $varhdrsz) . ')'; } - } elseif ($typname == 'numeric') { + } elseif ('numeric' === $typname) { $temp = 'numeric'; - if ($typmod != -1) { + + if (-1 !== $typmod) { $tmp_typmod = $typmod - $varhdrsz; $precision = ($tmp_typmod >> 16) & 0xffff; $scale = $tmp_typmod & 0xffff; @@ -104,6 +111,7 @@ trait TypeTrait // Create type filter $tqry = "'c'"; + if ($tabletypes) { $tqry .= ", 'r', 'v'"; } @@ -172,15 +180,16 @@ trait TypeTrait INPUT = \"{$typin}\", OUTPUT = \"{$typout}\", INTERNALLENGTH = {$typlen}"; - if ($typdef != '') { + + if ('' !== $typdef) { $sql .= ", DEFAULT = {$typdef}"; } - if ($typelem != '') { + if ('' !== $typelem) { $sql .= ", ELEMENT = {$typelem}"; } - if ($typdelim != '') { + if ('' !== $typdelim) { $sql .= ", DELIMITER = {$typdelim}"; } @@ -188,11 +197,11 @@ trait TypeTrait $sql .= ', PASSEDBYVALUE, '; } - if ($typalign != '') { + if ('' !== $typalign) { $sql .= ", ALIGNMENT = {$typalign}"; } - if ($typstorage != '') { + if ('' !== $typstorage) { $sql .= ", STORAGE = {$typstorage}"; } @@ -216,6 +225,7 @@ trait TypeTrait $this->fieldClean($typname); $sql = "DROP TYPE \"{$f_schema}\".\"{$typname}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -243,31 +253,34 @@ trait TypeTrait } $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } - $values = array_unique($values); + $values = \array_unique($values); - $nbval = count($values); + $nbval = \count($values); for ($i = 0; $i < $nbval; ++$i) { $this->clean($values[$i]); } $sql = "CREATE TYPE \"{$f_schema}\".\"{$name}\" AS ENUM ('"; - $sql .= implode("','", $values); + $sql .= \implode("','", $values); $sql .= "')"; $status = $this->execute($sql); + if ($status) { $this->rollbackTransaction(); return -1; } - if ($typcomment != '') { + if ('' !== $typcomment) { $status = $this->setComment('TYPE', $name, '', $typcomment, true); + if ($status) { $this->rollbackTransaction(); @@ -319,7 +332,8 @@ trait TypeTrait $this->fieldClean($name); $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } @@ -327,6 +341,7 @@ trait TypeTrait $first = true; $comment_sql = ''; // Accumulate comments for the columns $sql = "CREATE TYPE \"{$f_schema}\".\"{$name}\" AS ("; + for ($i = 0; $i < $fields; ++$i) { $this->fieldClean($field[$i]); $this->clean($type[$i]); @@ -334,7 +349,7 @@ trait TypeTrait $this->clean($colcomment[$i]); // Skip blank columns - for user convenience - if ($field[$i] == '' || $type[$i] == '') { + if ('' === $field[$i] || '' === $type[$i]) { continue; } @@ -350,9 +365,10 @@ trait TypeTrait // time zone types case 'timestamp with time zone': case 'timestamp without time zone': - $qual = substr($type[$i], 9); + $qual = \mb_substr($type[$i], 9); $sql .= "\"{$field[$i]}\" timestamp"; - if ($length[$i] != '') { + + if ('' !== $length[$i]) { $sql .= "({$length[$i]})"; } @@ -361,9 +377,10 @@ trait TypeTrait break; case 'time with time zone': case 'time without time zone': - $qual = substr($type[$i], 4); + $qual = \mb_substr($type[$i], 4); $sql .= "\"{$field[$i]}\" time"; - if ($length[$i] != '') { + + if ('' !== $length[$i]) { $sql .= "({$length[$i]})"; } @@ -372,16 +389,17 @@ trait TypeTrait break; default: $sql .= "\"{$field[$i]}\" {$type[$i]}"; - if ($length[$i] != '') { + + if ('' !== $length[$i]) { $sql .= "({$length[$i]})"; } } // Add array qualifier if necessary - if ($array[$i] == '[]') { + if ('[]' === $array[$i]) { $sql .= '[]'; } - if ($colcomment[$i] != '') { + if ('' !== $colcomment[$i]) { $comment_sql .= "COMMENT ON COLUMN \"{$f_schema}\".\"{$name}\".\"{$field[$i]}\" IS '{$colcomment[$i]}';\n"; } @@ -395,14 +413,16 @@ trait TypeTrait $sql .= ')'; $status = $this->execute($sql); + if ($status) { $this->rollbackTransaction(); return -1; } - if ($typcomment != '') { + if ('' !== $typcomment) { $status = $this->setComment('TYPE', $name, '', $typcomment, true); + if ($status) { $this->rollbackTransaction(); @@ -410,8 +430,9 @@ trait TypeTrait } } - if ($comment_sql != '') { + if ('' !== $comment_sql) { $status = $this->execute($comment_sql); + if ($status) { $this->rollbackTransaction(); diff --git a/src/database/databasetraits/ViewTrait.php b/src/database/databasetraits/ViewTrait.php index aab8218a..e7abc8db 100644 --- a/src/database/databasetraits/ViewTrait.php +++ b/src/database/databasetraits/ViewTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Database\Traits; @@ -80,7 +83,8 @@ trait ViewTrait public function createView($viewname, $definition, $replace, $comment, $materialized = false) { $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { return -1; } @@ -96,17 +100,19 @@ trait ViewTrait $obj_type = $materialized ? ' MATERIALIZED VIEW ' : ' VIEW '; - $sql .= $obj_type." \"{$f_schema}\".\"{$viewname}\" AS {$definition}"; + $sql .= $obj_type . " \"{$f_schema}\".\"{$viewname}\" AS {$definition}"; $status = $this->execute($sql); + if ($status) { $this->rollbackTransaction(); return -1; } - if ($comment != '') { + if ('' !== $comment) { $status = $this->setComment($obj_type, $viewname, '', $comment); + if ($status) { $this->rollbackTransaction(); @@ -132,12 +138,13 @@ trait ViewTrait { $data = $this->getView($view); - if ($data->recordCount() != 1) { + if (1 !== $data->recordCount()) { return -2; } $status = $this->beginTransaction(); - if ($status != 0) { + + if (0 !== $status) { $this->rollbackTransaction(); return -1; @@ -145,7 +152,7 @@ trait ViewTrait $status = $this->_alterView($data, $name, $owner, $schema, $comment); - if ($status != 0) { + if (0 !== $status) { $this->rollbackTransaction(); return $status; @@ -180,53 +187,6 @@ trait ViewTrait } /** - * Protected method which alter a view - * SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION. - * - * @param \PHPPgAdmin\ADORecordSet $vwrs The view recordSet returned by getView() - * @param string $name The new name for the view - * @param string $owner The new owner for the view - * @param string $schema Schema name - * @param string $comment The comment on the view - * - * @return int 0 success - */ - protected function _alterView($vwrs, $name, $owner, $schema, $comment) - { - $this->fieldArrayClean($vwrs->fields); - - $type = ($vwrs->fields['relkind'] === 'm') ? 'MATERIALIZED VIEW' : 'VIEW'; - // Comment - - if ($this->setComment($type, $vwrs->fields['relname'], '', $comment) != 0) { - return -4; - } - - // Owner - $this->fieldClean($owner); - $status = $this->alterViewOwner($vwrs, $owner); - if ($status != 0) { - return -5; - } - - // Rename - $this->fieldClean($name); - $status = $this->alterViewName($vwrs, $name); - if ($status != 0) { - return -3; - } - - // Schema - $this->fieldClean($schema); - $status = $this->alterViewSchema($vwrs, $schema); - if ($status != 0) { - return -6; - } - - return 0; - } - - /** * Alter a view's owner. * * @param \PHPPgAdmin\ADORecordSet $vwrs The view recordSet returned by getView() @@ -238,15 +198,15 @@ trait ViewTrait */ public function alterViewOwner($vwrs, $owner = null) { - $type = ($vwrs->fields['relkind'] === 'm') ? 'MATERIALIZED VIEW' : 'VIEW'; + $type = ('m' === $vwrs->fields['relkind']) ? 'MATERIALIZED VIEW' : 'VIEW'; /* $vwrs and $owner are cleaned in _alterView */ - if ((!empty($owner)) && ($vwrs->fields['relowner'] != $owner)) { + if ((!empty($owner)) && ($vwrs->fields['relowner'] !== $owner)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); // If owner has been changed, then do the alteration. We are // careful to avoid this generally as changing owner is a // superuser only function. - $sql = "ALTER ${type} \"{$f_schema}\".\"{$vwrs->fields['relname']}\" OWNER TO \"{$owner}\""; + $sql = "ALTER {$type} \"{$f_schema}\".\"{$vwrs->fields['relname']}\" OWNER TO \"{$owner}\""; return $this->execute($sql); } @@ -264,15 +224,16 @@ trait ViewTrait */ public function alterViewName($vwrs, $name) { - $type = ($vwrs->fields['relkind'] === 'm') ? 'MATERIALIZED VIEW' : 'VIEW'; + $type = ('m' === $vwrs->fields['relkind']) ? 'MATERIALIZED VIEW' : 'VIEW'; // Rename (only if name has changed) /* $vwrs and $name are cleaned in _alterView */ - if (!empty($name) && ($name != $vwrs->fields['relname'])) { + if (!empty($name) && ($name !== $vwrs->fields['relname'])) { $f_schema = $this->_schema; $this->fieldClean($f_schema); - $sql = "ALTER ${type} \"{$f_schema}\".\"{$vwrs->fields['relname']}\" RENAME TO \"{$name}\""; + $sql = "ALTER {$type} \"{$f_schema}\".\"{$vwrs->fields['relname']}\" RENAME TO \"{$name}\""; $status = $this->execute($sql); - if ($status == 0) { + + if (0 === $status) { $vwrs->fields['relname'] = $name; } else { return $status; @@ -294,15 +255,15 @@ trait ViewTrait */ public function alterViewSchema($vwrs, $schema) { - $type = ($vwrs->fields['relkind'] === 'm') ? 'MATERIALIZED VIEW' : 'VIEW'; + $type = ('m' === $vwrs->fields['relkind']) ? 'MATERIALIZED VIEW' : 'VIEW'; /* $vwrs and $schema are cleaned in _alterView */ - if (!empty($schema) && ($vwrs->fields['nspname'] != $schema)) { + if (!empty($schema) && ($vwrs->fields['nspname'] !== $schema)) { $f_schema = $this->_schema; $this->fieldClean($f_schema); // If tablespace has been changed, then do the alteration. We // don't want to do this unnecessarily. - $sql = "ALTER ${type} \"{$f_schema}\".\"{$vwrs->fields['relname']}\" SET SCHEMA \"{$schema}\""; + $sql = "ALTER {$type} \"{$f_schema}\".\"{$vwrs->fields['relname']}\" SET SCHEMA \"{$schema}\""; return $this->execute($sql); } @@ -321,13 +282,14 @@ trait ViewTrait public function dropView($viewname, $cascade) { $vwrs = $this->getView($viewname); - $type = ($vwrs->fields['relkind'] === 'm') ? 'MATERIALIZED VIEW' : 'VIEW'; + $type = ('m' === $vwrs->fields['relkind']) ? 'MATERIALIZED VIEW' : 'VIEW'; $f_schema = $this->_schema; $this->fieldClean($f_schema); $this->fieldClean($viewname); - $sql = "DROP ${type} \"{$f_schema}\".\"{$viewname}\""; + $sql = "DROP {$type} \"{$f_schema}\".\"{$viewname}\""; + if ($cascade) { $sql .= ' CASCADE'; } @@ -352,4 +314,54 @@ trait ViewTrait abstract public function clean(&$str); abstract public function fieldArrayClean(&$arr); + + /** + * Protected method which alter a view + * SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION. + * + * @param \PHPPgAdmin\ADORecordSet $vwrs The view recordSet returned by getView() + * @param string $name The new name for the view + * @param string $owner The new owner for the view + * @param string $schema Schema name + * @param string $comment The comment on the view + * + * @return int 0 success + */ + protected function _alterView($vwrs, $name, $owner, $schema, $comment) + { + $this->fieldArrayClean($vwrs->fields); + + $type = ('m' === $vwrs->fields['relkind']) ? 'MATERIALIZED VIEW' : 'VIEW'; + // Comment + + if (0 !== $this->setComment($type, $vwrs->fields['relname'], '', $comment)) { + return -4; + } + + // Owner + $this->fieldClean($owner); + $status = $this->alterViewOwner($vwrs, $owner); + + if (0 !== $status) { + return -5; + } + + // Rename + $this->fieldClean($name); + $status = $this->alterViewName($vwrs, $name); + + if (0 !== $status) { + return -3; + } + + // Schema + $this->fieldClean($schema); + $status = $this->alterViewSchema($vwrs, $schema); + + if (0 !== $status) { + return -6; + } + + return 0; + } } diff --git a/src/decorators/ActionUrlDecorator.php b/src/decorators/ActionUrlDecorator.php index 484e87ce..21d29900 100644 --- a/src/decorators/ActionUrlDecorator.php +++ b/src/decorators/ActionUrlDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -11,6 +11,7 @@ class ActionUrlDecorator extends Decorator public function __construct($base, $queryVars = null) { $this->base = $base; + if (null !== $queryVars) { $this->queryVars = $queryVars; } @@ -29,17 +30,18 @@ class ActionUrlDecorator extends Decorator $queryVars = Decorator::get_sanitized_value($this->queryVars, $fields); $sep = '?'; - ksort($queryVars); + \ksort($queryVars); + foreach ($queryVars as $var => $value) { - if (!is_scalar($value)) { + if (!\is_scalar($value)) { continue; } //dump($fields, $var, $value); - $url .= $sep.Decorator::value_url($var, $fields).'='.Decorator::value_url($value, $fields); + $url .= $sep . Decorator::value_url($var, $fields) . '=' . Decorator::value_url($value, $fields); $sep = '&'; } } - return \SUBFOLDER.'/src/views/'.str_replace('.php', '', $url); + return \SUBFOLDER . '/src/views/' . \str_replace('.php', '', $url); } } diff --git a/src/decorators/ArrayMergeDecorator.php b/src/decorators/ArrayMergeDecorator.php index fced29c7..868bc06c 100644 --- a/src/decorators/ArrayMergeDecorator.php +++ b/src/decorators/ArrayMergeDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -16,8 +16,9 @@ class ArrayMergeDecorator extends Decorator public function value($fields) { $accum = []; + foreach ($this->m as $var) { - $accum = array_merge($accum, Decorator::get_sanitized_value($var, $fields)); + $accum = \array_merge($accum, Decorator::get_sanitized_value($var, $fields)); } return $accum; diff --git a/src/decorators/BranchUrlDecorator.php b/src/decorators/BranchUrlDecorator.php index 7ff3cbd3..a629aa9e 100644 --- a/src/decorators/BranchUrlDecorator.php +++ b/src/decorators/BranchUrlDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -11,6 +11,7 @@ class BranchUrlDecorator extends Decorator public function __construct($base, $queryVars = null) { $this->base = $base; + if (null !== $queryVars) { $this->queryVars = $queryVars; } @@ -28,21 +29,24 @@ class BranchUrlDecorator extends Decorator $queryVars = Decorator::get_sanitized_value($this->queryVars, $fields); $sep = '?'; - ksort($queryVars); + \ksort($queryVars); + foreach ($queryVars as $var => $value) { - $varname = Decorator::value_url($var, $fields); + $varname = Decorator::value_url($var, $fields); $varvalue = Decorator::value_url($value, $fields); - $url .= $sep.$varname.'='.$varvalue; + $url .= $sep . $varname . '=' . $varvalue; $sep = '&'; } } - if (strpos($url, '/src/views') === false) { - $url = str_replace('//', '/', '/src/views/'.$url); + + if (false === \mb_strpos($url, '/src/views')) { + $url = \str_replace('//', '/', '/src/views/' . $url); } - if (\SUBFOLDER !== '' && (0 === strpos($url, '/')) && (0 !== strpos($url, \SUBFOLDER))) { - $url = str_replace('//', '/', \SUBFOLDER.'/'.$url); + + if (\SUBFOLDER !== '' && (0 === \mb_strpos($url, '/')) && (0 !== \mb_strpos($url, \SUBFOLDER))) { + $url = \str_replace('//', '/', \SUBFOLDER . '/' . $url); } - return str_replace('.php', '', $url); + return \str_replace('.php', '', $url); } } diff --git a/src/decorators/CallbackDecorator.php b/src/decorators/CallbackDecorator.php index 1f36b730..9e449f32 100644 --- a/src/decorators/CallbackDecorator.php +++ b/src/decorators/CallbackDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -11,11 +11,11 @@ class CallbackDecorator extends Decorator public function __construct($callback, $param = null) { $this->fn = $callback; - $this->p = $param; + $this->p = $param; } public function value($fields) { - return call_user_func($this->fn, $fields, $this->p); + return \call_user_func($this->fn, $fields, $this->p); } } diff --git a/src/decorators/ConcatDecorator.php b/src/decorators/ConcatDecorator.php index d76cf7d3..bf21e165 100644 --- a/src/decorators/ConcatDecorator.php +++ b/src/decorators/ConcatDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -16,10 +16,11 @@ class ConcatDecorator extends Decorator public function value($fields) { $accum = ''; + foreach ($this->c as $var) { $accum .= Decorator::get_sanitized_value($var, $fields); } - return trim($accum); + return \trim($accum); } } diff --git a/src/decorators/Decorator.php b/src/decorators/Decorator.php index 722dd8ef..13f80778 100644 --- a/src/decorators/Decorator.php +++ b/src/decorators/Decorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -22,16 +22,16 @@ class Decorator public static function get_sanitized_value(&$var, &$fields, $esc = null) { - if (is_a($var, 'PHPPgAdmin\Decorators\Decorator')) { + if (\is_a($var, 'PHPPgAdmin\Decorators\Decorator')) { $val = $var->value($fields); } else { $val = &$var; } - if (is_string($val)) { + if (\is_string($val)) { switch ($esc) { case 'xml': - return strtr($val, [ + return \strtr($val, [ '&' => '&', "'" => ''', '"' => '"', @@ -39,9 +39,9 @@ class Decorator '>' => '>', ]); case 'html': - return htmlentities($val, ENT_COMPAT, 'UTF-8'); + return \htmlentities($val, \ENT_COMPAT, 'UTF-8'); case 'url': - return urlencode($val); + return \urlencode($val); } } @@ -60,7 +60,7 @@ class Decorator public static function concat(/* ... */) { - return new \PHPPgAdmin\Decorators\ConcatDecorator(func_get_args()); + return new \PHPPgAdmin\Decorators\ConcatDecorator(\func_get_args()); } public static function replace($str, $params) @@ -78,9 +78,9 @@ class Decorator // If more than one array of vars is given, // use an ArrayMergeDecorator to have them merged // at value evaluation time. - if (func_num_args() > 2) { - $v = func_get_args(); - array_shift($v); + if (2 < \func_num_args()) { + $v = \func_get_args(); + \array_shift($v); return new BranchUrlDecorator($base, new ArrayMergeDecorator($v)); } @@ -93,9 +93,9 @@ class Decorator // If more than one array of vars is given, // use an ArrayMergeDecorator to have them merged // at value evaluation time. - if (func_num_args() > 2) { - $v = func_get_args(); - array_shift($v); + if (2 < \func_num_args()) { + $v = \func_get_args(); + \array_shift($v); return new ActionUrlDecorator($base, new ArrayMergeDecorator($v)); } @@ -108,9 +108,9 @@ class Decorator // If more than one array of vars is given, // use an ArrayMergeDecorator to have them merged // at value evaluation time. - if (func_num_args() > 2) { - $v = func_get_args(); - array_shift($v); + if (2 < \func_num_args()) { + $v = \func_get_args(); + \array_shift($v); return new RedirectUrlDecorator($base, new ArrayMergeDecorator($v)); } @@ -124,9 +124,9 @@ class Decorator // use an ArrayMergeDecorator to have them merged // at value evaluation time. - if (func_num_args() > 2) { - $v = func_get_args(); - $base = array_shift($v); + if (2 < \func_num_args()) { + $v = \func_get_args(); + $base = \array_shift($v); return new UrlDecorator($base, new ArrayMergeDecorator($v)); } diff --git a/src/decorators/FieldDecorator.php b/src/decorators/FieldDecorator.php index ed72ba16..1902b1d7 100644 --- a/src/decorators/FieldDecorator.php +++ b/src/decorators/FieldDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; diff --git a/src/decorators/IfEmptyDecorator.php b/src/decorators/IfEmptyDecorator.php index 14855238..35bf4e4e 100644 --- a/src/decorators/IfEmptyDecorator.php +++ b/src/decorators/IfEmptyDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -10,8 +10,9 @@ class IfEmptyDecorator extends Decorator { public function __construct($value, $empty, $full = null) { - $this->val = $value; + $this->val = $value; $this->empty = $empty; + if (null !== $full) { $this->full = $full; } @@ -20,6 +21,7 @@ class IfEmptyDecorator extends Decorator public function value($fields) { $val = Decorator::get_sanitized_value($this->val, $fields); + if (empty($val)) { return Decorator::get_sanitized_value($this->empty, $fields); } diff --git a/src/decorators/RedirectUrlDecorator.php b/src/decorators/RedirectUrlDecorator.php index 4d127871..1faa32f2 100644 --- a/src/decorators/RedirectUrlDecorator.php +++ b/src/decorators/RedirectUrlDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -11,6 +11,7 @@ class RedirectUrlDecorator extends Decorator public function __construct($base, $queryVars = null) { $this->base = $base; + if (null !== $queryVars) { $this->queryVars = $queryVars; } @@ -30,23 +31,26 @@ class RedirectUrlDecorator extends Decorator $queryVars = Decorator::get_sanitized_value($this->queryVars, $fields); $sep = '?'; - ksort($queryVars); + \ksort($queryVars); + foreach ($queryVars as $var => $value) { - $varname = Decorator::value_url($var, $fields); + $varname = Decorator::value_url($var, $fields); $varvalue = Decorator::value_url($value, $fields); - if ('subject' == $varname) { - $url = '/'.str_replace('redirect?', 'redirect/'.$varvalue.'?', $url); + + if ('subject' === $varname) { + $url = '/' . \str_replace('redirect?', 'redirect/' . $varvalue . '?', $url); } else { - $url .= $sep.$varname.'='.$varvalue; + $url .= $sep . $varname . '=' . $varvalue; } $sep = '&'; } } - if (\SUBFOLDER !== '' && (0 === strpos($url, '/')) && (false === strpos($url, \SUBFOLDER))) { - $url = str_replace('//', '/', \SUBFOLDER.'/'.$url); + + if (\SUBFOLDER !== '' && (0 === \mb_strpos($url, '/')) && (false === \mb_strpos($url, \SUBFOLDER))) { + $url = \str_replace('//', '/', \SUBFOLDER . '/' . $url); } - return str_replace('.php', '', $url); + return \str_replace('.php', '', $url); } } diff --git a/src/decorators/ReplaceDecorator.php b/src/decorators/ReplaceDecorator.php index f4f04be2..de4491ed 100644 --- a/src/decorators/ReplaceDecorator.php +++ b/src/decorators/ReplaceDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -17,8 +17,9 @@ class ReplaceDecorator extends Decorator public function value($fields) { $str = $this->s; + foreach ($this->p as $k => $v) { - $str = str_replace($k, Decorator::get_sanitized_value($v, $fields), $str); + $str = \str_replace($k, Decorator::get_sanitized_value($v, $fields), $str); } return $str; diff --git a/src/decorators/UrlDecorator.php b/src/decorators/UrlDecorator.php index b52924f1..4508ca7a 100644 --- a/src/decorators/UrlDecorator.php +++ b/src/decorators/UrlDecorator.php @@ -1,7 +1,7 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin v6.0.0-RC8-17-g0a6763af */ namespace PHPPgAdmin\Decorators; @@ -11,6 +11,7 @@ class UrlDecorator extends Decorator public function __construct($base, $queryVars = null) { $this->base = $base; + if (null !== $queryVars) { $this->queryVars = $queryVars; } @@ -28,15 +29,16 @@ class UrlDecorator extends Decorator $queryVars = Decorator::get_sanitized_value($this->queryVars, $fields); $sep = '?'; - ksort($queryVars); + \ksort($queryVars); + foreach ($queryVars as $var => $value) { - $url .= $sep.Decorator::value_url($var, $fields).'='.Decorator::value_url($value, $fields); + $url .= $sep . Decorator::value_url($var, $fields) . '=' . Decorator::value_url($value, $fields); $sep = '&'; } } //$this->prtrace('url before', $url); - if (\SUBFOLDER !== '' && (0 === strpos($url, '/')) && (false === strpos($url, \SUBFOLDER))) { - $url = str_replace('//', '/', \SUBFOLDER.'/'.$url); + if (\SUBFOLDER !== '' && (0 === \mb_strpos($url, '/')) && (false === \mb_strpos($url, \SUBFOLDER))) { + $url = \str_replace('//', '/', \SUBFOLDER . '/' . $url); } //$this->prtrace('url after', $url); return $url; diff --git a/src/help/PostgresDoc10.php b/src/help/PostgresDoc10.php index 87993f8c..b8312df4 100644 --- a/src/help/PostgresDoc10.php +++ b/src/help/PostgresDoc10.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc11.php b/src/help/PostgresDoc11.php new file mode 100644 index 00000000..8b4ade4d --- /dev/null +++ b/src/help/PostgresDoc11.php @@ -0,0 +1,21 @@ +<?php + +// declare(strict_types=1); + +/** + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * + */ + +namespace PHPPgAdmin\Help; + +/** + * Help links for PostgreSQL 11.x documentation. + */ +class PostgresDoc11 extends PostgresDoc10 +{ + public function __construct($conf, $major_version) + { + parent::__construct($conf, $major_version); + } +} diff --git a/src/help/PostgresDoc12.php b/src/help/PostgresDoc12.php new file mode 100644 index 00000000..aff0efff --- /dev/null +++ b/src/help/PostgresDoc12.php @@ -0,0 +1,21 @@ +<?php + +// declare(strict_types=1); + +/** + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * + */ + +namespace PHPPgAdmin\Help; + +/** + * Help links for PostgreSQL 12.x documentation. + */ +class PostgresDoc12 extends PostgresDoc11 +{ + public function __construct($conf, $major_version) + { + parent::__construct($conf, $major_version); + } +} diff --git a/src/help/PostgresDoc74.php b/src/help/PostgresDoc74.php index 76bcd9f8..bf7f54f4 100644 --- a/src/help/PostgresDoc74.php +++ b/src/help/PostgresDoc74.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; @@ -14,7 +17,9 @@ class PostgresDoc74 use \PHPPgAdmin\Traits\HelperTrait; protected $major_version; + protected $help_page; + protected $conf; public function __construct($conf, $major_version) @@ -167,7 +172,7 @@ class PostgresDoc74 public function getHelpBase() { - return sprintf(str_replace('http://', 'https://', $this->conf['help_base']), (string) ($this->major_version)); + return \sprintf(\str_replace('http://', 'https://', $this->conf['help_base']), (string) ($this->major_version)); } public function getHelpPage() diff --git a/src/help/PostgresDoc80.php b/src/help/PostgresDoc80.php index 662efef0..589690d5 100644 --- a/src/help/PostgresDoc80.php +++ b/src/help/PostgresDoc80.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc81.php b/src/help/PostgresDoc81.php index 5329dcef..f4dfb278 100644 --- a/src/help/PostgresDoc81.php +++ b/src/help/PostgresDoc81.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc82.php b/src/help/PostgresDoc82.php index 15cb62e6..3fa91b7b 100644 --- a/src/help/PostgresDoc82.php +++ b/src/help/PostgresDoc82.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc83.php b/src/help/PostgresDoc83.php index c9932e89..78bf4cd8 100644 --- a/src/help/PostgresDoc83.php +++ b/src/help/PostgresDoc83.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc84.php b/src/help/PostgresDoc84.php index 5fb1482e..7744bb32 100644 --- a/src/help/PostgresDoc84.php +++ b/src/help/PostgresDoc84.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc90.php b/src/help/PostgresDoc90.php index 88b03e14..fc6b7bc0 100644 --- a/src/help/PostgresDoc90.php +++ b/src/help/PostgresDoc90.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc91.php b/src/help/PostgresDoc91.php index bdec28eb..b522bad5 100644 --- a/src/help/PostgresDoc91.php +++ b/src/help/PostgresDoc91.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc92.php b/src/help/PostgresDoc92.php index 9c6d76ce..099bd9fd 100644 --- a/src/help/PostgresDoc92.php +++ b/src/help/PostgresDoc92.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc93.php b/src/help/PostgresDoc93.php index 57000af1..7411d3c3 100644 --- a/src/help/PostgresDoc93.php +++ b/src/help/PostgresDoc93.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc94.php b/src/help/PostgresDoc94.php index c73716e8..f49da9c3 100644 --- a/src/help/PostgresDoc94.php +++ b/src/help/PostgresDoc94.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc95.php b/src/help/PostgresDoc95.php index 44bfe3fd..c0d6bdd1 100644 --- a/src/help/PostgresDoc95.php +++ b/src/help/PostgresDoc95.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/help/PostgresDoc96.php b/src/help/PostgresDoc96.php index 6c828a80..6615d703 100644 --- a/src/help/PostgresDoc96.php +++ b/src/help/PostgresDoc96.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Help; diff --git a/src/lib.inc.php b/src/lib.inc.php index 630df349..f25d7911 100644 --- a/src/lib.inc.php +++ b/src/lib.inc.php @@ -1,96 +1,90 @@ <?php +//// declare(strict_types = 1); + /** - * Function library read in upon startup. - * - * Release: lib.inc.php,v 1.123 2008/04/06 01:10:35 xzilla Exp $ + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f */ -defined('BASE_PATH') or define('BASE_PATH', dirname(__DIR__)); -define('THEME_PATH', BASE_PATH . '/assets/themes'); +\defined('BASE_PATH') || \define('BASE_PATH', \dirname(__DIR__)); + +\define('THEME_PATH', BASE_PATH . '/assets/themes'); // Enforce PHP environment ini_set('arg_separator.output', '&'); -if (!is_writable(BASE_PATH . '/temp')) { +if (!\is_writable(BASE_PATH . '/temp')) { die('Your temp folder must have write permissions (use chmod 777 temp -R on linux)'); } + require_once BASE_PATH . '/vendor/autoload.php'; // Check to see if the configuration file exists, if not, explain -if (file_exists(BASE_PATH . '/config.inc.php')) { +if (\file_exists(BASE_PATH . '/config.inc.php')) { $conf = []; + include BASE_PATH . '/config.inc.php'; } else { die('Configuration error: Copy config.inc.php-dist to config.inc.php and edit appropriately.'); } -$shouldSetSession = (defined('PHP_SESSION_ACTIVE') ? session_status() != PHP_SESSION_ACTIVE : !session_id()) -&& !headers_sent() -&& !ini_get('session.auto_start'); - -if ($shouldSetSession && PHP_SAPI !== 'cli') { - session_set_cookie_params(0, '/', null, isset($_SERVER['HTTPS'])); - session_name('PPA_ID'); - session_start(); +$shouldSetSession = (\defined('PHP_SESSION_ACTIVE') ? \PHP_SESSION_ACTIVE !== \session_status() : !\session_id()) +&& !\headers_sent() +&& !\ini_get('session.auto_start'); + +if ($shouldSetSession && \PHP_SAPI !== 'cli') { + \session_set_cookie_params(0, '/', $_SERVER['HTTP_HOST'], isset($_SERVER['HTTPS'])); + \session_name('PPA_ID'); + \session_start(); } -$debugmode = (!isset($conf['debugmode'])) ? false : boolval($conf['debugmode']); -define('DEBUGMODE', $debugmode); +$debugmode = (!isset($conf['debugmode'])) ? false : (bool) ($conf['debugmode']); +defined('DEBUGMODE') || \define('DEBUGMODE', $debugmode); -if (!defined('ADODB_ERROR_HANDLER_TYPE')) { - define('ADODB_ERROR_HANDLER_TYPE', E_USER_ERROR); +if (!\defined('ADODB_ERROR_HANDLER_TYPE')) { + \define('ADODB_ERROR_HANDLER_TYPE', \E_USER_ERROR); } -if (!defined('ADODB_ERROR_HANDLER')) { - define('ADODB_ERROR_HANDLER', '\PHPPgAdmin\ADOdbException::adodb_throw'); +if (!\defined('ADODB_ERROR_HANDLER')) { + \define('ADODB_ERROR_HANDLER', '\PHPPgAdmin\ADOdbException::adodb_throw'); } - if (DEBUGMODE) { - ini_set('display_errors', 1); - ini_set('display_startup_errors', 1); - ini_set('opcache.revalidate_freq', 0); - error_reporting(E_ALL); - if (array_key_exists('register_debuggers', $conf) && is_callable($conf['register_debuggers'])) { + ini_set('display_errors', 'On'); + + ini_set('display_startup_errors', 'On'); + ini_set('opcache.revalidate_freq', '0'); + \error_reporting(\E_ALL); + + if (\array_key_exists('register_debuggers', $conf) && \is_callable($conf['register_debuggers'])) { $conf['register_debuggers'](); } } // Fetch App and DI Container -list($container, $app) = \PHPPgAdmin\ContainerUtils::createContainer($conf); -$subfolder = ''; -if ($container instanceof \Psr\Container\ContainerInterface) { - if (PHP_SAPI == 'cli-server') { - $subfolder = '/index.php'; - } elseif (isset($conf['subfolder']) && is_string($conf['subfolder'])) { - $subfolder = $conf['subfolder']; - } else { - $normalized_php_self = str_replace('/src/views', '', $container->environment->get('PHP_SELF')); - $subfolder = str_replace('/' . basename($normalized_php_self), '', $normalized_php_self); - } -} else { - trigger_error("App Container must be an instance of \Psr\Container\ContainerInterface", E_USER_ERROR); +[$container, $app] = \PHPPgAdmin\ContainerUtils::createContainer($conf); + +if (!$container instanceof \Psr\Container\ContainerInterface) { + \trigger_error('App Container must be an instance of \\Psr\\Container\\ContainerInterface', \E_USER_ERROR); } -define('SUBFOLDER', $subfolder); $container['requestobj'] = $container['request']; $container['responseobj'] = $container['response']; // This should be deprecated once we're sure no php scripts are required directly -$container->offsetSet('server', isset($_REQUEST['server']) ? $_REQUEST['server'] : null); -$container->offsetSet('database', isset($_REQUEST['database']) ? $_REQUEST['database'] : null); -$container->offsetSet('schema', isset($_REQUEST['schema']) ? $_REQUEST['schema'] : null); +$container->offsetSet('server', $_REQUEST['server'] ?? null); +$container->offsetSet('database', $_REQUEST['database'] ?? null); +$container->offsetSet('schema', $_REQUEST['schema'] ?? null); -$container['flash'] = function () { +$container['flash'] = static function () { return new \Slim\Flash\Messages(); }; -$container['lang'] = function ($c) { +$container['lang'] = static function ($c) { $translations = new \PHPPgAdmin\Translations($c); return $translations->lang; }; // Create Misc class references -$container['misc'] = function ($c) { +$container['misc'] = static function ($c) { $misc = new \PHPPgAdmin\Misc($c); $conf = $c->get('conf'); @@ -99,14 +93,15 @@ $container['misc'] = function ($c) { $_server_info = $misc->getServerInfo(); /* starting with PostgreSQL 9.0, we can set the application name */ - if (isset($_server_info['pgVersion']) && $_server_info['pgVersion'] >= 9) { - putenv('PGAPPNAME=' . $c->get('settings')['appName'] . '_' . $c->get('settings')['appVersion']); + if (isset($_server_info['pgVersion']) && 9 <= $_server_info['pgVersion']) { + \putenv('PGAPPNAME=' . $c->get('settings')['appName'] . '_' . $c->get('settings')['appVersion']); } $_theme = $c->utils->getTheme($conf, $_server_info); - if (!is_null($_theme)) { + + if (null !== $_theme) { /* save the selected theme in cookie for a year */ - setcookie('ppaTheme', $_theme, time() + 31536000, '/'); + \setcookie('ppaTheme', $_theme, \time() + 31536000, '/'); $_SESSION['ppaTheme'] = $_theme; $misc->setConf('theme', $_theme); } @@ -115,7 +110,7 @@ $container['misc'] = function ($c) { }; // Register Twig View helper -$container['view'] = function ($c) { +$container['view'] = static function ($c) { $conf = $c->get('conf'); $misc = $c->misc; @@ -125,14 +120,14 @@ $container['view'] = function ($c) { 'debug' => $c->get('settings')['debug'], ]); $environment = $c->get('environment'); - $base_script_trailing_str = substr($environment['SCRIPT_NAME'], 1); + $base_script_trailing_str = \mb_substr($environment['SCRIPT_NAME'], 1); $request_basepath = $c['request']->getUri()->getBasePath(); // Instantiate and add Slim specific extension - $basePath = rtrim(str_ireplace($base_script_trailing_str, '', $request_basepath), '/'); + $basePath = \rtrim(\str_ireplace($base_script_trailing_str, '', $request_basepath), '/'); $view->addExtension(new Slim\Views\TwigExtension($c['router'], $basePath)); - $view->offsetSet('subfolder', SUBFOLDER); + $view->offsetSet('subfolder', $c->subfolder); $view->offsetSet('theme', $c->misc->getConf('theme')); $view->offsetSet('Favicon', $c->misc->icon('Favicon')); $view->offsetSet('Introduction', $c->misc->icon('Introduction')); @@ -147,13 +142,13 @@ $container['view'] = function ($c) { return $view; }; -$container['haltHandler'] = function ($c) { - return function ($request, $response, $exits, $status = 500) use ($c) { +$container['haltHandler'] = static function ($c) { + return static function ($request, $response, $exits, $status = 500) use ($c) { $title = 'PHPPgAdmin Error'; $html = '<p>The application could not run because of the following error:</p>'; - $output = sprintf( + $output = \sprintf( "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" . '<title>%s</title><style>' . 'body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}' . @@ -163,7 +158,7 @@ $container['haltHandler'] = function ($c) { $title, $title, $html, - implode('<br>', $exits) + \implode('<br>', $exits) ); $body = $response->getBody(); //new \Slim\Http\Body(fopen('php://temp', 'r+')); @@ -180,10 +175,11 @@ $container['haltHandler'] = function ($c) { // as the value of $request and $response, which already contain the route $app->add(new \PHPPgAdmin\Middleware\PopulateRequestResponse($container)); -$container['action'] = isset($_REQUEST['action']) ? $_REQUEST['action'] : ''; +$container['action'] = $_REQUEST['action'] ?? ''; if (!isset($msg)) { $msg = ''; } $container['msg'] = $msg; +//ddd($container->misc); diff --git a/src/middleware/Middleware.php b/src/middleware/Middleware.php index c6314fb4..c763c165 100644 --- a/src/middleware/Middleware.php +++ b/src/middleware/Middleware.php @@ -1,11 +1,19 @@ <?php +// declare(strict_types=1); + +/** + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + */ + namespace PHPPgAdmin\Middleware; class Middleware { use \PHPPgAdmin\Traits\HelperTrait; + protected $container; + protected $router; public function __construct($container) diff --git a/src/middleware/PopulateRequestResponse.php b/src/middleware/PopulateRequestResponse.php index 7b92bc97..2d0dbadd 100644 --- a/src/middleware/PopulateRequestResponse.php +++ b/src/middleware/PopulateRequestResponse.php @@ -1,5 +1,11 @@ <?php +// declare(strict_types=1); + +/** + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + */ + namespace PHPPgAdmin\Middleware; /** @@ -28,6 +34,7 @@ class PopulateRequestResponse extends Middleware $misc->setForm(); $container->view->offsetSet('METHOD', $request->getMethod()); + if ($request->getAttribute('route')) { $container->view->offsetSet('subject', $request->getAttribute('route')->getArgument('subject')); } @@ -42,7 +49,7 @@ class PopulateRequestResponse extends Middleware $viewparams = []; foreach ($params as $key => $value) { - if (is_scalar($value)) { + if (\is_scalar($value)) { $viewparams[$key] = $value; } } @@ -55,12 +62,12 @@ class PopulateRequestResponse extends Middleware // remove tabs and linebreaks from query if (isset($params['query'])) { - $viewparams['query'] = str_replace(["\r", "\n", "\t"], ' ', $params['query']); + $viewparams['query'] = \str_replace(["\r", "\n", "\t"], ' ', $params['query']); } $container->view->offsetSet('params', $viewparams); $container->view->offsetSet('in_test', $in_test); - if (count($container['errors']) > 0) { + if (0 < \count($container['errors'])) { return ($container->haltHandler)($container->requestobj, $container->responseobj, $container['errors'], 412); } diff --git a/src/router.php b/src/router.php index d754ac9b..6be1a44c 100644 --- a/src/router.php +++ b/src/router.php @@ -1,4 +1,11 @@ <?php + +// declare(strict_types=1); + +/** + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + */ + require_once __DIR__ . '/lib.inc.php'; $app->get('/status', function ( /* @scrutinizer ignore-unused */ @@ -30,10 +37,10 @@ $app->post('/redirect/server', function ( $loginShared = $request->getParsedBodyParam('loginShared'); $loginServer = $request->getParsedBodyParam('loginServer'); $loginUsername = $request->getParsedBodyParam('loginUsername'); - $loginPassword = $request->getParsedBodyParam('loginPassword_' . md5($loginServer)); + $loginPassword = $request->getParsedBodyParam('loginPassword_' . \md5($loginServer)); // If login action is set, then set session variables - if ((bool) $loginServer && (bool) $loginUsername && $loginPassword !== null) { + if ((bool) $loginServer && (bool) $loginUsername && null !== $loginPassword) { $_server_info = $this->misc->getServerInfo($loginServer); $_server_info['username'] = $loginUsername; @@ -43,14 +50,14 @@ $app->post('/redirect/server', function ( $data = $misc->getDatabaseAccessor(); - if ($data === null) { + if (null === $data) { $login_controller = new \PHPPgAdmin\Controller\LoginController($this, true); $body->write($login_controller->doLoginForm($misc->getErrorMsg())); return $response; } // Check for shared credentials - if ($loginShared !== null) { + if (null !== $loginShared) { $_SESSION['sharedUsername'] = $loginUsername; $_SESSION['sharedPassword'] = $loginPassword; } @@ -58,6 +65,7 @@ $app->post('/redirect/server', function ( $misc->setReloadBrowser(true); $destinationurl = $this->utils->getDestinationWithLastTab('alldb'); + return $response->withStatus(302)->withHeader('Location', $destinationurl); } $_server_info = $this->misc->getServerInfo(); @@ -79,6 +87,7 @@ $app->get('/redirect[/{subject}]', function ( ) { $subject = (isset($args['subject'])) ? $args['subject'] : 'root'; $destinationurl = $this->utils->getDestinationWithLastTab($subject); + return $response->withStatus(302)->withHeader('Location', $destinationurl); }); @@ -91,24 +100,25 @@ $app->map(['GET', 'POST'], '/src/views/{subject}', function ( $args ) { $subject = $args['subject']; - if ($subject === 'server') { + + if ('server' === $subject) { $subject = 'servers'; } $_server_info = $this->misc->getServerInfo(); - $safe_subjects = ($subject === 'servers' || $subject === 'intro' || $subject === 'browser'); + $safe_subjects = ('servers' === $subject || 'intro' === $subject || 'browser' === $subject); - if ($this->misc->getServerId() === null && !$safe_subjects) { + if (null === $this->misc->getServerId() && !$safe_subjects) { return $response->withStatus(302)->withHeader('Location', SUBFOLDER . '/src/views/servers'); } - if (!isset($_server_info['username']) && $subject !== 'login' && !$safe_subjects) { + if (!isset($_server_info['username']) && 'login' !== $subject && !$safe_subjects) { $destinationurl = SUBFOLDER . '/src/views/login?server=' . $this->misc->getServerId(); return $response->withStatus(302)->withHeader('Location', $destinationurl); } - $className = '\PHPPgAdmin\Controller\\' . ucfirst($subject) . 'Controller'; + $className = '\PHPPgAdmin\Controller\\' . \ucfirst($subject) . 'Controller'; $controller = new $className($this); return $controller->render(); @@ -133,7 +143,7 @@ $app->get('/{subject:\w+}', function ( $subject = 'login'; } - if ($subject === 'login' && $server_id === null) { + if ('login' === $subject && null === $server_id) { $subject = 'servers'; } diff --git a/src/traits/AdminTrait.php b/src/traits/AdminTrait.php index 7e87f656..d6f3d458 100644 --- a/src/traits/AdminTrait.php +++ b/src/traits/AdminTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -18,13 +21,13 @@ trait AdminTrait * * @param mixed $type */ - public function confirmCluster($type) + public function confirmCluster($type): void { - $this->script = ('database' == $type) ? 'database' : 'tables'; + $this->script = ('database' === $type) ? 'database' : 'tables'; $script = $this->script; - if (('table' == $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { + if (('table' === $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { $this->doDefault($this->lang['strspecifytabletocluster']); return; @@ -34,32 +37,33 @@ trait AdminTrait $this->printTrail('schema'); $this->printTitle($this->lang['strclusterindex'], 'pg.index.cluster'); - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; + foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfclustertable'], $this->misc->printVal($a['table'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table[]" value="', htmlspecialchars($a['table']), '" />'.PHP_EOL; + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfclustertable'], $this->misc->printVal($a['table'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table[]" value="', \htmlspecialchars($a['table']), '" />' . \PHP_EOL; } // END if multi cluster } else { $this->printTrail($type); $this->printTitle($this->lang['strclusterindex'], 'pg.index.cluster'); - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; - if ('table' == $type) { - echo '<p>', sprintf($this->lang['strconfclustertable'], $this->misc->printVal($_REQUEST['object'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['object']), '" />'.PHP_EOL; + if ('table' === $type) { + echo '<p>', \sprintf($this->lang['strconfclustertable'], $this->misc->printVal($_REQUEST['object'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['object']), '" />' . \PHP_EOL; } else { - echo '<p>', sprintf($this->lang['strconfclusterdatabase'], $this->misc->printVal($_REQUEST['object'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table" value="" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfclusterdatabase'], $this->misc->printVal($_REQUEST['object'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table" value="" />' . \PHP_EOL; } } - echo '<input type="hidden" name="action" value="cluster" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="cluster" />' . \PHP_EOL; echo $this->misc->form; echo "<input type=\"submit\" name=\"cluster\" value=\"{$this->lang['strcluster']}\" />\n"; //TODO - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; echo "</form>\n"; // END single cluster } @@ -68,14 +72,14 @@ trait AdminTrait * * @param mixed $type */ - public function confirmReindex($type) + public function confirmReindex($type): void { - $this->script = ('database' == $type) ? 'database' : 'tables'; + $this->script = ('database' === $type) ? 'database' : 'tables'; $script = $this->script; $this->misc = $this->misc; $data = $this->misc->getDatabaseAccessor(); - if (('table' == $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { + if (('table' === $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { $this->doDefault($this->lang['strspecifytabletoreindex']); return; @@ -85,36 +89,37 @@ trait AdminTrait $this->printTrail('schema'); $this->printTitle($this->lang['strreindex'], 'pg.reindex'); - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; + foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfreindextable'], $this->misc->printVal($a['table'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table[]" value="', htmlspecialchars($a['table']), '" />'.PHP_EOL; + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfreindextable'], $this->misc->printVal($a['table'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table[]" value="', \htmlspecialchars($a['table']), '" />' . \PHP_EOL; } // END if multi reindex } else { $this->printTrail($type); $this->printTitle($this->lang['strreindex'], 'pg.reindex'); - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; - if ('table' == $type) { - echo '<p>', sprintf($this->lang['strconfreindextable'], $this->misc->printVal($_REQUEST['object'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['object']), '" />'.PHP_EOL; + if ('table' === $type) { + echo '<p>', \sprintf($this->lang['strconfreindextable'], $this->misc->printVal($_REQUEST['object'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['object']), '" />' . \PHP_EOL; } else { - echo '<p>', sprintf($this->lang['strconfreindexdatabase'], $this->misc->printVal($_REQUEST['object'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table" value="" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfreindexdatabase'], $this->misc->printVal($_REQUEST['object'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table" value="" />' . \PHP_EOL; } } - echo '<input type="hidden" name="action" value="reindex" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="reindex" />' . \PHP_EOL; if ($data->hasForceReindex()) { - echo "<p><input type=\"checkbox\" id=\"reindex_force\" name=\"reindex_force\" /><label for=\"reindex_force\">{$this->lang['strforce']}</label></p>".PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"reindex_force\" name=\"reindex_force\" /><label for=\"reindex_force\">{$this->lang['strforce']}</label></p>" . \PHP_EOL; } echo $this->misc->form; echo "<input type=\"submit\" name=\"reindex\" value=\"{$this->lang['strreindex']}\" />\n"; //TODO - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; echo "</form>\n"; // END single reindex } @@ -123,13 +128,13 @@ trait AdminTrait * * @param mixed $type */ - public function confirmAnalyze($type) + public function confirmAnalyze($type): void { - $this->script = ('database' == $type) ? 'database' : 'tables'; + $this->script = ('database' === $type) ? 'database' : 'tables'; $script = $this->script; - if (('table' == $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { + if (('table' === $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { $this->doDefault($this->lang['strspecifytabletoanalyze']); return; @@ -139,32 +144,33 @@ trait AdminTrait $this->printTrail('schema'); $this->printTitle($this->lang['stranalyze'], 'pg.analyze'); - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; + foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); //\Kint::dump($a); - echo '<p>', sprintf($this->lang['strconfanalyzetable'], $this->misc->printVal($a['table'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table[]" value="', htmlspecialchars($a['table']), '" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfanalyzetable'], $this->misc->printVal($a['table'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table[]" value="', \htmlspecialchars($a['table']), '" />' . \PHP_EOL; } // END if multi analyze } else { $this->printTrail($type); $this->printTitle($this->lang['stranalyze'], 'pg.analyze'); - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; - if ('table' == $type) { - echo '<p>', sprintf($this->lang['strconfanalyzetable'], $this->misc->printVal($_REQUEST['object'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['object']), '" />'.PHP_EOL; + if ('table' === $type) { + echo '<p>', \sprintf($this->lang['strconfanalyzetable'], $this->misc->printVal($_REQUEST['object'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['object']), '" />' . \PHP_EOL; } else { - echo '<p>', sprintf($this->lang['strconfanalyzedatabase'], $this->misc->printVal($_REQUEST['object'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table" value="" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfanalyzedatabase'], $this->misc->printVal($_REQUEST['object'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table" value="" />' . \PHP_EOL; } } - echo '<input type="hidden" name="action" value="analyze" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="analyze" />' . \PHP_EOL; echo $this->misc->form; echo "<input type=\"submit\" name=\"analyze\" value=\"{$this->lang['stranalyze']}\" />\n"; //TODO - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; echo "</form>\n"; // END single analyze } @@ -173,11 +179,11 @@ trait AdminTrait * * @param mixed $type */ - public function confirmVacuum($type) + public function confirmVacuum($type): void { - $script = ('database' == $type) ? 'database' : 'tables'; + $script = ('database' === $type) ? 'database' : 'tables'; - if (('table' == $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { + if (('table' === $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { $this->doDefault($this->lang['strspecifytabletovacuum']); return; @@ -187,34 +193,35 @@ trait AdminTrait $this->printTrail('schema'); $this->printTitle($this->lang['strvacuum'], 'pg.vacuum'); - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; + foreach ($_REQUEST['ma'] as $v) { - $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); - echo '<p>', sprintf($this->lang['strconfvacuumtable'], $this->misc->printVal($a['table'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table[]" value="', htmlspecialchars($a['table']), '" />'.PHP_EOL; + $a = \unserialize(\htmlspecialchars_decode($v, \ENT_QUOTES)); + echo '<p>', \sprintf($this->lang['strconfvacuumtable'], $this->misc->printVal($a['table'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table[]" value="', \htmlspecialchars($a['table']), '" />' . \PHP_EOL; } } else { // END if multi vacuum $this->printTrail($type); $this->printTitle($this->lang['strvacuum'], 'pg.vacuum'); - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; - if ('table' == $type) { - echo '<p>', sprintf($this->lang['strconfvacuumtable'], $this->misc->printVal($_REQUEST['object'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['object']), '" />'.PHP_EOL; + if ('table' === $type) { + echo '<p>', \sprintf($this->lang['strconfvacuumtable'], $this->misc->printVal($_REQUEST['object'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['object']), '" />' . \PHP_EOL; } else { - echo '<p>', sprintf($this->lang['strconfvacuumdatabase'], $this->misc->printVal($_REQUEST['object'])), '</p>'.PHP_EOL; - echo '<input type="hidden" name="table" value="" />'.PHP_EOL; + echo '<p>', \sprintf($this->lang['strconfvacuumdatabase'], $this->misc->printVal($_REQUEST['object'])), '</p>' . \PHP_EOL; + echo '<input type="hidden" name="table" value="" />' . \PHP_EOL; } } - echo '<input type="hidden" name="action" value="vacuum" />'.PHP_EOL; + echo '<input type="hidden" name="action" value="vacuum" />' . \PHP_EOL; echo $this->misc->form; - echo "<p><input type=\"checkbox\" id=\"vacuum_full\" name=\"vacuum_full\" /> <label for=\"vacuum_full\">{$this->lang['strfull']}</label></p>".PHP_EOL; - echo "<p><input type=\"checkbox\" id=\"vacuum_analyze\" name=\"vacuum_analyze\" /> <label for=\"vacuum_analyze\">{$this->lang['stranalyze']}</label></p>".PHP_EOL; - echo "<p><input type=\"checkbox\" id=\"vacuum_freeze\" name=\"vacuum_freeze\" /> <label for=\"vacuum_freeze\">{$this->lang['strfreeze']}</label></p>".PHP_EOL; - echo "<input type=\"submit\" name=\"vacuum\" value=\"{$this->lang['strvacuum']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"vacuum_full\" name=\"vacuum_full\" /> <label for=\"vacuum_full\">{$this->lang['strfull']}</label></p>" . \PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"vacuum_analyze\" name=\"vacuum_analyze\" /> <label for=\"vacuum_analyze\">{$this->lang['stranalyze']}</label></p>" . \PHP_EOL; + echo "<p><input type=\"checkbox\" id=\"vacuum_freeze\" name=\"vacuum_freeze\" /> <label for=\"vacuum_freeze\">{$this->lang['strfreeze']}</label></p>" . \PHP_EOL; + echo "<input type=\"submit\" name=\"vacuum\" value=\"{$this->lang['strvacuum']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; echo "</form>\n"; // END single vacuum } @@ -224,7 +231,7 @@ trait AdminTrait * @param mixed $type * @param mixed $msg */ - public function confirmEditAutovacuum($type, $msg = '') + public function confirmEditAutovacuum($type, $msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -234,11 +241,11 @@ trait AdminTrait return; } - $script = ('database' == $type) ? 'database' : 'tables'; + $script = ('database' === $type) ? 'database' : 'tables'; $this->printTrail($type); - $this->printTitle(sprintf($this->lang['streditvacuumtable'], $this->misc->printVal($_REQUEST['table']))); - $this->printMsg(sprintf($msg, $this->misc->printVal($_REQUEST['table']))); + $this->printTitle(\sprintf($this->lang['streditvacuumtable'], $this->misc->printVal($_REQUEST['table']))); + $this->printMsg(\sprintf($msg, $this->misc->printVal($_REQUEST['table']))); if (empty($_REQUEST['table'])) { $this->doAdmin($type, $this->lang['strspecifyeditvacuumtable']); @@ -250,7 +257,7 @@ trait AdminTrait $defaults = $data->getAutovacuum(); $old_val = $old_val->fields; - if (isset($old_val['autovacuum_enabled']) and ('off' == $old_val['autovacuum_enabled'])) { + if (isset($old_val['autovacuum_enabled']) && ('off' === $old_val['autovacuum_enabled'])) { $enabled = ''; $disabled = 'checked="checked"'; } else { @@ -282,44 +289,44 @@ trait AdminTrait $old_val['autovacuum_vacuum_cost_limit'] = ''; } - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="action" value="editautovac" />'.PHP_EOL; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - - echo "<br />\n<br />\n<table>".PHP_EOL; - echo "\t<tr><td> </td>".PHP_EOL; - echo "<th class=\"data\">{$this->lang['strnewvalues']}</th><th class=\"data\">{$this->lang['strdefaultvalues']}</th></tr>".PHP_EOL; - echo "\t<tr><th class=\"data left\">{$this->lang['strenable']}</th>".PHP_EOL; - echo '<td class="data1">'.PHP_EOL; - echo "<label for=\"on\">on</label><input type=\"radio\" name=\"autovacuum_enabled\" id=\"on\" value=\"on\" {$enabled} />".PHP_EOL; - echo "<label for=\"off\">off</label><input type=\"radio\" name=\"autovacuum_enabled\" id=\"off\" value=\"off\" {$disabled} /></td>".PHP_EOL; - echo "<th class=\"data left\">{$defaults['autovacuum']}</th></tr>".PHP_EOL; - echo "\t<tr><th class=\"data left\">{$this->lang['strvacuumbasethreshold']}</th>".PHP_EOL; - echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_vacuum_threshold\" value=\"{$old_val['autovacuum_vacuum_threshold']}\" /></td>".PHP_EOL; - echo "<th class=\"data left\">{$defaults['autovacuum_vacuum_threshold']}</th></tr>".PHP_EOL; - echo "\t<tr><th class=\"data left\">{$this->lang['strvacuumscalefactor']}</th>".PHP_EOL; - echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_vacuum_scale_factor\" value=\"{$old_val['autovacuum_vacuum_scale_factor']}\" /></td>".PHP_EOL; - echo "<th class=\"data left\">{$defaults['autovacuum_vacuum_scale_factor']}</th></tr>".PHP_EOL; - echo "\t<tr><th class=\"data left\">{$this->lang['stranalybasethreshold']}</th>".PHP_EOL; - echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_analyze_threshold\" value=\"{$old_val['autovacuum_analyze_threshold']}\" /></td>".PHP_EOL; - echo "<th class=\"data left\">{$defaults['autovacuum_analyze_threshold']}</th></tr>".PHP_EOL; - echo "\t<tr><th class=\"data left\">{$this->lang['stranalyzescalefactor']}</th>".PHP_EOL; - echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_analyze_scale_factor\" value=\"{$old_val['autovacuum_analyze_scale_factor']}\" /></td>".PHP_EOL; - echo "<th class=\"data left\">{$defaults['autovacuum_analyze_scale_factor']}</th></tr>".PHP_EOL; - echo "\t<tr><th class=\"data left\">{$this->lang['strvacuumcostdelay']}</th>".PHP_EOL; - echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_vacuum_cost_delay\" value=\"{$old_val['autovacuum_vacuum_cost_delay']}\" /></td>".PHP_EOL; - echo "<th class=\"data left\">{$defaults['autovacuum_vacuum_cost_delay']}</th></tr>".PHP_EOL; - echo "\t<tr><th class=\"data left\">{$this->lang['strvacuumcostlimit']}</th>".PHP_EOL; - echo "<td class=\"datat1\"><input type=\"text\" name=\"autovacuum_vacuum_cost_limit\" value=\"{$old_val['autovacuum_vacuum_cost_limit']}\" /></td>".PHP_EOL; - echo "<th class=\"data left\">{$defaults['autovacuum_vacuum_cost_limit']}</th></tr>".PHP_EOL; - echo '</table>'.PHP_EOL; + echo '<input type="hidden" name="action" value="editautovac" />' . \PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + + echo "<br />\n<br />\n<table>" . \PHP_EOL; + echo "\t<tr><td> </td>" . \PHP_EOL; + echo "<th class=\"data\">{$this->lang['strnewvalues']}</th><th class=\"data\">{$this->lang['strdefaultvalues']}</th></tr>" . \PHP_EOL; + echo "\t<tr><th class=\"data left\">{$this->lang['strenable']}</th>" . \PHP_EOL; + echo '<td class="data1">' . \PHP_EOL; + echo "<label for=\"on\">on</label><input type=\"radio\" name=\"autovacuum_enabled\" id=\"on\" value=\"on\" {$enabled} />" . \PHP_EOL; + echo "<label for=\"off\">off</label><input type=\"radio\" name=\"autovacuum_enabled\" id=\"off\" value=\"off\" {$disabled} /></td>" . \PHP_EOL; + echo "<th class=\"data left\">{$defaults['autovacuum']}</th></tr>" . \PHP_EOL; + echo "\t<tr><th class=\"data left\">{$this->lang['strvacuumbasethreshold']}</th>" . \PHP_EOL; + echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_vacuum_threshold\" value=\"{$old_val['autovacuum_vacuum_threshold']}\" /></td>" . \PHP_EOL; + echo "<th class=\"data left\">{$defaults['autovacuum_vacuum_threshold']}</th></tr>" . \PHP_EOL; + echo "\t<tr><th class=\"data left\">{$this->lang['strvacuumscalefactor']}</th>" . \PHP_EOL; + echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_vacuum_scale_factor\" value=\"{$old_val['autovacuum_vacuum_scale_factor']}\" /></td>" . \PHP_EOL; + echo "<th class=\"data left\">{$defaults['autovacuum_vacuum_scale_factor']}</th></tr>" . \PHP_EOL; + echo "\t<tr><th class=\"data left\">{$this->lang['stranalybasethreshold']}</th>" . \PHP_EOL; + echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_analyze_threshold\" value=\"{$old_val['autovacuum_analyze_threshold']}\" /></td>" . \PHP_EOL; + echo "<th class=\"data left\">{$defaults['autovacuum_analyze_threshold']}</th></tr>" . \PHP_EOL; + echo "\t<tr><th class=\"data left\">{$this->lang['stranalyzescalefactor']}</th>" . \PHP_EOL; + echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_analyze_scale_factor\" value=\"{$old_val['autovacuum_analyze_scale_factor']}\" /></td>" . \PHP_EOL; + echo "<th class=\"data left\">{$defaults['autovacuum_analyze_scale_factor']}</th></tr>" . \PHP_EOL; + echo "\t<tr><th class=\"data left\">{$this->lang['strvacuumcostdelay']}</th>" . \PHP_EOL; + echo "<td class=\"data1\"><input type=\"text\" name=\"autovacuum_vacuum_cost_delay\" value=\"{$old_val['autovacuum_vacuum_cost_delay']}\" /></td>" . \PHP_EOL; + echo "<th class=\"data left\">{$defaults['autovacuum_vacuum_cost_delay']}</th></tr>" . \PHP_EOL; + echo "\t<tr><th class=\"data left\">{$this->lang['strvacuumcostlimit']}</th>" . \PHP_EOL; + echo "<td class=\"datat1\"><input type=\"text\" name=\"autovacuum_vacuum_cost_limit\" value=\"{$old_val['autovacuum_vacuum_cost_limit']}\" /></td>" . \PHP_EOL; + echo "<th class=\"data left\">{$defaults['autovacuum_vacuum_cost_limit']}</th></tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; echo '<br />'; echo '<br />'; - echo "<input type=\"submit\" name=\"save\" value=\"{$this->lang['strsave']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; + echo "<input type=\"submit\" name=\"save\" value=\"{$this->lang['strsave']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; - echo '</form>'.PHP_EOL; + echo '</form>' . \PHP_EOL; } /** @@ -327,9 +334,9 @@ trait AdminTrait * * @param mixed $type */ - public function confirmDropAutovacuum($type) + public function confirmDropAutovacuum($type): void { - $script = ('database' == $type) ? 'database' : 'tables'; + $script = ('database' === $type) ? 'database' : 'tables'; if (empty($_REQUEST['table'])) { $this->doAdmin($type, $this->lang['strspecifydelvacuumtable']); @@ -340,19 +347,19 @@ trait AdminTrait $this->printTrail($type); $this->printTabs($type, 'admin'); - printf( + \printf( "<p>{$this->lang['strdelvacuumtable']}</p>\n", $this->misc->printVal("\"{$_GET['schema']}\".\"{$_GET['table']}\"") ); - echo "<form style=\"float: left\" action=\"{$script}\" method=\"post\">".PHP_EOL; - echo '<input type="hidden" name="action" value="delautovac" />'.PHP_EOL; + echo "<form style=\"float: left\" action=\"{$script}\" method=\"post\">" . \PHP_EOL; + echo '<input type="hidden" name="action" value="delautovac" />' . \PHP_EOL; echo $this->misc->form; - echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL; - echo '<input type="hidden" name="rel" value="', htmlspecialchars(serialize([$_REQUEST['schema'], $_REQUEST['table']])), '" />'.PHP_EOL; - echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL; - echo '</form>'.PHP_EOL; + echo '<input type="hidden" name="table" value="', \htmlspecialchars($_REQUEST['table']), '" />' . \PHP_EOL; + echo '<input type="hidden" name="rel" value="', \htmlspecialchars(\serialize([$_REQUEST['schema'], $_REQUEST['table']])), '" />' . \PHP_EOL; + echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** @@ -360,11 +367,11 @@ trait AdminTrait * * @param mixed $type */ - public function doCluster($type) + public function doCluster($type): void { $data = $this->misc->getDatabaseAccessor(); - if (('table' == $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { + if (('table' === $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { $this->doDefault($this->lang['strspecifytabletocluster']); return; @@ -372,16 +379,17 @@ trait AdminTrait $msg = ''; //If multi table cluster - if ('table' == $type) { + if ('table' === $type) { // cluster one or more table - if (is_array($_REQUEST['table'])) { + if (\is_array($_REQUEST['table'])) { foreach ($_REQUEST['table'] as $o) { list($status, $sql) = $data->clusterIndex($o); - $msg .= sprintf('%s<br />', $sql); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($o, ENT_QUOTES, 'UTF-8'), $this->lang['strclusteredgood']); + $msg .= \sprintf('%s<br />', $sql); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($o, \ENT_QUOTES, 'UTF-8'), $this->lang['strclusteredgood']); } else { - $this->doDefault(sprintf('%s %s%s: %s<br />', $type, $msg, htmlentities($o, ENT_QUOTES, 'UTF-8'), $this->lang['strclusteredbad'])); + $this->doDefault(\sprintf('%s %s%s: %s<br />', $type, $msg, \htmlentities($o, \ENT_QUOTES, 'UTF-8'), $this->lang['strclusteredbad'])); return; } @@ -390,21 +398,23 @@ trait AdminTrait $this->doDefault($msg); } else { list($status, $sql) = $data->clusterIndex($_REQUEST['object']); - $msg .= sprintf('%s<br />', $sql); - if (0 == $status) { - $this->doAdmin($type, $msg.$this->lang['strclusteredgood']); + $msg .= \sprintf('%s<br />', $sql); + + if (0 === $status) { + $this->doAdmin($type, $msg . $this->lang['strclusteredgood']); } else { - $this->doAdmin($type, $msg.$this->lang['strclusteredbad']); + $this->doAdmin($type, $msg . $this->lang['strclusteredbad']); } } } else { // Cluster all tables in database list($status, $sql) = $data->clusterIndex(); - $msg .= sprintf('%s<br />', $sql); - if (0 == $status) { - $this->doAdmin($type, $msg.$this->lang['strclusteredgood']); + $msg .= \sprintf('%s<br />', $sql); + + if (0 === $status) { + $this->doAdmin($type, $msg . $this->lang['strclusteredgood']); } else { - $this->doAdmin($type, $msg.$this->lang['strclusteredbad']); + $this->doAdmin($type, $msg . $this->lang['strclusteredbad']); } } } @@ -414,26 +424,28 @@ trait AdminTrait * * @param mixed $type */ - public function doReindex($type) + public function doReindex($type): void { $this->misc = $this->misc; $data = $this->misc->getDatabaseAccessor(); - if (('table' == $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { + if (('table' === $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { $this->doDefault($this->lang['strspecifytabletoreindex']); return; } //If multi table reindex - if (('table' == $type) && is_array($_REQUEST['table'])) { + if (('table' === $type) && \is_array($_REQUEST['table'])) { $msg = ''; + foreach ($_REQUEST['table'] as $o) { - $status = $data->reindex(strtoupper($type), $o, isset($_REQUEST['reindex_force'])); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($o, ENT_QUOTES, 'UTF-8'), $this->lang['strreindexgood']); + $status = $data->reindex(\mb_strtoupper($type), $o, isset($_REQUEST['reindex_force'])); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($o, \ENT_QUOTES, 'UTF-8'), $this->lang['strreindexgood']); } else { - $this->doDefault(sprintf('%s %s%s: %s<br />', $type, $msg, htmlentities($o, ENT_QUOTES, 'UTF-8'), $this->lang['strreindexbad'])); + $this->doDefault(\sprintf('%s %s%s: %s<br />', $type, $msg, \htmlentities($o, \ENT_QUOTES, 'UTF-8'), $this->lang['strreindexbad'])); return; } @@ -442,8 +454,9 @@ trait AdminTrait $this->misc->setReloadBrowser(true); $this->doDefault($msg); } else { - $status = $data->reindex(strtoupper($type), $_REQUEST['object'], isset($_REQUEST['reindex_force'])); - if (0 == $status) { + $status = $data->reindex(\mb_strtoupper($type), $_REQUEST['object'], isset($_REQUEST['reindex_force'])); + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doAdmin($type, $this->lang['strreindexgood']); } else { @@ -457,25 +470,27 @@ trait AdminTrait * * @param mixed $type */ - public function doAnalyze($type) + public function doAnalyze($type): void { $data = $this->misc->getDatabaseAccessor(); - if (('table' == $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { + if (('table' === $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { $this->doDefault($this->lang['strspecifytabletoanalyze']); return; } //If multi table analyze - if (('table' == $type) && is_array($_REQUEST['table'])) { + if (('table' === $type) && \is_array($_REQUEST['table'])) { $msg = ''; + foreach ($_REQUEST['table'] as $o) { $status = $data->analyzeDB($o); - if (0 == $status) { - $msg .= sprintf('%s: %s<br />', htmlentities($o, ENT_QUOTES, 'UTF-8'), $this->lang['stranalyzegood']); + + if (0 === $status) { + $msg .= \sprintf('%s: %s<br />', \htmlentities($o, \ENT_QUOTES, 'UTF-8'), $this->lang['stranalyzegood']); } else { - $this->doDefault(sprintf('%s %s%s: %s<br />', $type, $msg, htmlentities($o, ENT_QUOTES, 'UTF-8'), $this->lang['stranalyzebad'])); + $this->doDefault(\sprintf('%s %s%s: %s<br />', $type, $msg, \htmlentities($o, \ENT_QUOTES, 'UTF-8'), $this->lang['stranalyzebad'])); return; } @@ -486,7 +501,8 @@ trait AdminTrait } else { //we must pass table here. When empty, analyze the whole db $status = $data->analyzeDB($_REQUEST['table']); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); $this->doAdmin($type, $this->lang['stranalyzegood']); } else { @@ -504,21 +520,23 @@ trait AdminTrait { $data = $this->misc->getDatabaseAccessor(); - if (('table' == $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { + if (('table' === $type) && empty($_REQUEST['table']) && empty($_REQUEST['ma'])) { $this->doDefault($this->lang['strspecifytabletovacuum']); return; } //If multi drop - if (is_array($_REQUEST['table'])) { + if (\is_array($_REQUEST['table'])) { $msg = ''; + foreach ($_REQUEST['table'] as $t) { list($status, $sql) = $data->vacuumDB($t, isset($_REQUEST['vacuum_analyze']), isset($_REQUEST['vacuum_full']), isset($_REQUEST['vacuum_freeze'])); + if (0 !== $status) { - return $this->doDefault(sprintf('%s %s%s: %s<br />', $type, $msg, htmlentities($t, ENT_QUOTES, 'UTF-8'), $this->lang['strvacuumbad'])); + return $this->doDefault(\sprintf('%s %s%s: %s<br />', $type, $msg, \htmlentities($t, \ENT_QUOTES, 'UTF-8'), $this->lang['strvacuumbad'])); } - $msg .= sprintf('%s%s %s: %s<br />', $sql, PHP_EOL, htmlentities($t, ENT_QUOTES, 'UTF-8'), $this->lang['strvacuumgood']); + $msg .= \sprintf('%s%s %s: %s<br />', $sql, \PHP_EOL, \htmlentities($t, \ENT_QUOTES, 'UTF-8'), $this->lang['strvacuumgood']); } // Everything went fine, back to the Default page.... $this->misc->setReloadBrowser(true); @@ -527,10 +545,11 @@ trait AdminTrait } //we must pass table here. When empty, vacuum the whole db list($status, $sql) = $data->vacuumDB($_REQUEST['table'], isset($_REQUEST['vacuum_analyze']), isset($_REQUEST['vacuum_full']), isset($_REQUEST['vacuum_freeze'])); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); - return $this->doAdmin($type, sprintf('%s%s%s', $sql, PHP_EOL, $this->lang['strvacuumgood'])); + return $this->doAdmin($type, \sprintf('%s%s%s', $sql, \PHP_EOL, $this->lang['strvacuumgood'])); } return $this->doAdmin($type, $this->lang['strvacuumbad']); @@ -543,7 +562,7 @@ trait AdminTrait * @param mixed $confirm * @param mixed $msg */ - public function doEditAutovacuum($type) + public function doEditAutovacuum($type): void { $data = $this->misc->getDatabaseAccessor(); @@ -564,8 +583,8 @@ trait AdminTrait $_POST['autovacuum_vacuum_cost_limit'] ); - if (0 == $status) { - $this->doAdmin($type, sprintf($this->lang['strsetvacuumtablesaved'], $_REQUEST['table'])); + if (0 === $status) { + $this->doAdmin($type, \sprintf($this->lang['strsetvacuumtablesaved'], $_REQUEST['table'])); } else { $this->confirmEditAutovacuum($type, $this->lang['strsetvacuumtablefail']); } @@ -576,7 +595,7 @@ trait AdminTrait * * @param mixed $type */ - public function doDropAutovacuum($type) + public function doDropAutovacuum($type): void { $data = $this->misc->getDatabaseAccessor(); @@ -588,10 +607,10 @@ trait AdminTrait $status = $data->dropAutovacuum($_POST['table']); - if (0 == $status) { - $this->doAdmin($type, sprintf($this->lang['strvacuumtablereset'], $this->misc->printVal($_POST['table']))); + if (0 === $status) { + $this->doAdmin($type, \sprintf($this->lang['strvacuumtablereset'], $this->misc->printVal($_POST['table']))); } else { - $this->doAdmin($type, sprintf($this->lang['strdelvacuumtablefail'], $this->misc->printVal($_POST['table']))); + $this->doAdmin($type, \sprintf($this->lang['strdelvacuumtablefail'], $this->misc->printVal($_POST['table']))); } } @@ -603,9 +622,9 @@ trait AdminTrait * @param mixed $type * @param mixed $msg */ - public function doAdmin($type, $msg = '') + public function doAdmin($type, $msg = ''): void { - $this->script = ('database' == $type) ? 'database' : 'tables'; + $this->script = ('database' === $type) ? 'database' : 'tables'; $script = $this->script; @@ -615,23 +634,23 @@ trait AdminTrait $this->printTabs($type, 'admin'); $this->printMsg($msg); - if ('database' == $type) { - printf("<p>{$this->lang['stradminondatabase']}</p>\n", $this->misc->printVal($_REQUEST['object'])); + if ('database' === $type) { + \printf("<p>{$this->lang['stradminondatabase']}</p>\n", $this->misc->printVal($_REQUEST['object'])); } else { - printf("<p>{$this->lang['stradminontable']}</p>\n", $this->misc->printVal($_REQUEST['object'])); + \printf("<p>{$this->lang['stradminontable']}</p>\n", $this->misc->printVal($_REQUEST['object'])); } - echo '<table style="width: 50%">'.PHP_EOL; - echo '<tr>'.PHP_EOL; + echo '<table style="width: 50%">' . \PHP_EOL; + echo '<tr>' . \PHP_EOL; echo '<th class="data">'; - $this->misc->printHelp($this->lang['strvacuum'], 'pg.admin.vacuum').'</th>'.PHP_EOL; + $this->misc->printHelp($this->lang['strvacuum'], 'pg.admin.vacuum') . '</th>' . \PHP_EOL; echo '</th>'; echo '<th class="data">'; $this->misc->printHelp($this->lang['stranalyze'], 'pg.admin.analyze'); echo '</th>'; - $table_hidden_inputs = ($type === 'table') ? - sprintf('<input type="hidden" name="table" value="%s" />%s<input type="hidden" name="subject" value="table" />', htmlspecialchars($_REQUEST['object']), PHP_EOL, PHP_EOL) : ''; + $table_hidden_inputs = ('table' === $type) ? + \sprintf('<input type="hidden" name="table" value="%s" />%s<input type="hidden" name="subject" value="table" />', \htmlspecialchars($_REQUEST['object']), \PHP_EOL, \PHP_EOL) : ''; list($recluster_help, $reclusterconf) = $this->_getReclusterConf($data, $type, $table_hidden_inputs); @@ -643,41 +662,41 @@ trait AdminTrait echo '</tr>'; // Vacuum - echo '<tr class="row1">'.PHP_EOL; - echo '<td style="text-align: center; vertical-align: bottom">'.PHP_EOL; - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + echo '<tr class="row1">' . \PHP_EOL; + echo '<td style="text-align: center; vertical-align: bottom">' . \PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; - echo '<p><input type="hidden" name="action" value="confirm_vacuum" />'.PHP_EOL; + echo '<p><input type="hidden" name="action" value="confirm_vacuum" />' . \PHP_EOL; echo $this->misc->form; echo $table_hidden_inputs; - echo "<input type=\"submit\" value=\"{$this->lang['strvacuum']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; - echo '</td>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strvacuum']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; + echo '</td>' . \PHP_EOL; // Analyze - echo '<td style="text-align: center; vertical-align: bottom">'.PHP_EOL; - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; - echo '<p><input type="hidden" name="action" value="confirm_analyze" />'.PHP_EOL; + echo '<td style="text-align: center; vertical-align: bottom">' . \PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="confirm_analyze" />' . \PHP_EOL; echo $this->misc->form; echo $table_hidden_inputs; - echo "<input type=\"submit\" value=\"{$this->lang['stranalyze']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; - echo '</td>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['stranalyze']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; + echo '</td>' . \PHP_EOL; // Cluster echo $reclusterconf; // Reindex - echo '<td style="text-align: center; vertical-align: bottom">'.PHP_EOL; - echo '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; - echo '<p><input type="hidden" name="action" value="confirm_reindex" />'.PHP_EOL; + echo '<td style="text-align: center; vertical-align: bottom">' . \PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="confirm_reindex" />' . \PHP_EOL; echo $this->misc->form; echo $table_hidden_inputs; - echo "<input type=\"submit\" value=\"{$this->lang['strreindex']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; - echo '</td>'.PHP_EOL; - echo '</tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strreindex']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; + echo '</td>' . \PHP_EOL; + echo '</tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; // Autovacuum $this->_printAutoVacuumConf($data, $type); @@ -685,12 +704,13 @@ trait AdminTrait public function adminActions($action, $type) { - if ('database' == $type) { + if ('database' === $type) { $_REQUEST['object'] = $_REQUEST['database']; } else { // $_REQUEST['table'] is no set if we are in the schema page - $_REQUEST['object'] = (isset($_REQUEST['table']) ? $_REQUEST['table'] : ''); - if (is_array($_REQUEST['object'])) { + $_REQUEST['object'] = ($_REQUEST['table'] ?? ''); + + if (\is_array($_REQUEST['object'])) { return false; } } @@ -759,32 +779,45 @@ trait AdminTrait return true; } + abstract public function doDefault($msg = ''); + + abstract public function printTrail($trail = [], $do_print = true); + + abstract public function printTitle($title, $help = null, $do_print = true); + + abstract public function printMsg($msg, $do_print = true); + + abstract public function printTabs($tabs, $activetab, $do_print = true); + + abstract public function printTable(&$tabledata, &$columns, &$actions, $place, $nodata = '', $pre_fn = null); + private function _getReclusterConf($data, $type, $table_hidden_inputs) { if (!$data->hasRecluster()) { return ['', '']; } $script = $this->script; - $recluster_help = sprintf('<th class="data">%s</th>', $this->misc->printHelp($this->lang['strclusterindex'], 'pg.index.cluster', false)); + $recluster_help = \sprintf('<th class="data">%s</th>', $this->misc->printHelp($this->lang['strclusterindex'], 'pg.index.cluster', false)); $disabled = ''; - $reclusterconf = '<td style="text-align: center; vertical-align: bottom">'.PHP_EOL; - $reclusterconf .= '<form action="'.\SUBFOLDER."/src/views/{$script}\" method=\"post\">".PHP_EOL; + $reclusterconf = '<td style="text-align: center; vertical-align: bottom">' . \PHP_EOL; + $reclusterconf .= '<form action="' . \SUBFOLDER . "/src/views/{$script}\" method=\"post\">" . \PHP_EOL; $reclusterconf .= $this->misc->form; $reclusterconf .= $table_hidden_inputs; - if ('table' == $type && !$data->alreadyClustered($_REQUEST['object'])) { + + if ('table' === $type && !$data->alreadyClustered($_REQUEST['object'])) { $disabled = 'disabled="disabled" '; $reclusterconf .= "{$this->lang['strnoclusteravailable']}<br />"; } - $reclusterconf .= '<p><input type="hidden" name="action" value="confirm_cluster" />'.PHP_EOL; - $reclusterconf .= "<input type=\"submit\" value=\"{$this->lang['strclusterindex']}\" ${disabled}/></p>".PHP_EOL; - $reclusterconf .= '</form>'.PHP_EOL; - $reclusterconf .= '</td>'.PHP_EOL; + $reclusterconf .= '<p><input type="hidden" name="action" value="confirm_cluster" />' . \PHP_EOL; + $reclusterconf .= "<input type=\"submit\" value=\"{$this->lang['strclusterindex']}\" {$disabled}/></p>" . \PHP_EOL; + $reclusterconf .= '</form>' . \PHP_EOL; + $reclusterconf .= '</td>' . \PHP_EOL; return [$recluster_help, $reclusterconf]; } - private function _printAutoVacuumConf($data, $type) + private function _printAutoVacuumConf($data, $type): void { if (!$data->hasAutovacuum()) { return; @@ -793,35 +826,35 @@ trait AdminTrait // get defaults values for autovacuum $defaults = $data->getAutovacuum(); // Fetch the autovacuum properties from the database or table if != '' - if ('table' == $type) { + if ('table' === $type) { $autovac = $data->getTableAutovacuum($_REQUEST['table']); } else { $autovac = $data->getTableAutovacuum(); } echo "<br /><br /><h2>{$this->lang['strvacuumpertable']}</h2>"; - echo '<p>'.(('on' == $defaults['autovacuum']) ? $this->lang['strturnedon'] : $this->lang['strturnedoff']).'</p>'; + echo '<p>' . (('on' === $defaults['autovacuum']) ? $this->lang['strturnedon'] : $this->lang['strturnedoff']) . '</p>'; echo "<p class=\"message\">{$this->lang['strnotdefaultinred']}</p>"; - $enlight = function ($f, $p) { - if (isset($f[$p[0]]) and ($f[$p[0]] != $p[1])) { - return '<span style="color:#F33;font-weight:bold">'.htmlspecialchars($f[$p[0]]).'</span>'; + $enlight = static function ($f, $p) { + if (isset($f[$p[0]]) && ($f[$p[0]] !== $p[1])) { + return '<span style="color:#F33;font-weight:bold">' . \htmlspecialchars($f[$p[0]]) . '</span>'; } - return htmlspecialchars($p[1]); + return \htmlspecialchars($p[1]); }; $columns = [ 'namespace' => [ 'title' => $this->lang['strschema'], 'field' => Decorator::field('nspname'), - 'url' => \SUBFOLDER."/redirect/schema?{$this->misc->href}&", + 'url' => \SUBFOLDER . "/redirect/schema?{$this->misc->href}&", 'vars' => ['schema' => 'nspname'], ], 'relname' => [ 'title' => $this->lang['strtable'], 'field' => Decorator::field('relname'), - 'url' => \SUBFOLDER."/redirect/table?{$this->misc->href}&", + 'url' => \SUBFOLDER . "/redirect/table?{$this->misc->href}&", 'vars' => ['table' => 'relname', 'schema' => 'nspname'], ], 'autovacuum_enabled' => [ @@ -895,7 +928,7 @@ trait AdminTrait ], ]; - if ('table' == $type) { + if ('table' === $type) { unset($actions['edit']['vars']['schema'], $actions['delete']['vars']['schema'], $columns['namespace'], @@ -905,24 +938,12 @@ trait AdminTrait echo $this->printTable($autovac, $columns, $actions, 'admin-admin', $this->lang['strnovacuumconf']); - if (('table' == $type) and (0 == $autovac->recordCount())) { + if (('table' === $type) && (0 === $autovac->recordCount())) { echo '<br />'; - echo '<a href="'.\SUBFOLDER."/src/views/tables?action=confeditautovac&{$this->misc->href}&table="; - echo htmlspecialchars($_REQUEST['table']); + echo '<a href="' . \SUBFOLDER . "/src/views/tables?action=confeditautovac&{$this->misc->href}&table="; + echo \htmlspecialchars($_REQUEST['table']); echo "\">{$this->lang['straddvacuumtable']}</a>"; } } - - abstract public function doDefault($msg = ''); - - abstract public function printTrail($trail = [], $do_print = true); - - abstract public function printTitle($title, $help = null, $do_print = true); - - abstract public function printMsg($msg, $do_print = true); - - abstract public function printTabs($tabs, $activetab, $do_print = true); - - abstract public function printTable(&$tabledata, &$columns, &$actions, $place, $nodata = '', $pre_fn = null); } diff --git a/src/traits/ExportTrait.php b/src/traits/ExportTrait.php index f45f8f08..8fa0050c 100644 --- a/src/traits/ExportTrait.php +++ b/src/traits/ExportTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -12,6 +15,7 @@ namespace PHPPgAdmin\Traits; trait ExportTrait { public $href = ''; + public $misc; /** @@ -25,45 +29,45 @@ trait ExportTrait public function dataOnly($hasID, $onlyCopyAndSQL = false) { $content = '<tr>'; - $content .= '<th class="data left" rowspan="'.($hasID ? 2 : 1).'">'; + $content .= '<th class="data left" rowspan="' . ($hasID ? 2 : 1) . '">'; $content .= '<input type="radio" id="what1" name="what" value="dataonly" checked="checked" />'; - $content .= sprintf( + $content .= \sprintf( '<label for="what1">%s</label></th>%s', $this->lang['strdataonly'], - PHP_EOL + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<td>%s</td>%s', $this->lang['strformat'], - PHP_EOL + \PHP_EOL ); - $content .= '<td><select name="d_format">'.PHP_EOL; - $content .= '<option value="copy">COPY</option>'.PHP_EOL; - $content .= '<option value="sql">SQL</option>'.PHP_EOL; + $content .= '<td><select name="d_format">' . \PHP_EOL; + $content .= '<option value="copy">COPY</option>' . \PHP_EOL; + $content .= '<option value="sql">SQL</option>' . \PHP_EOL; if (!$onlyCopyAndSQL) { - $content .= '<option value="csv">CSV</option>'.PHP_EOL; - $content .= "<option value=\"tab\">{$this->lang['strtabbed']}</option>".PHP_EOL; - $content .= '<option value="html">XHTML</option>'.PHP_EOL; - $content .= '<option value="xml">XML</option>'.PHP_EOL; + $content .= '<option value="csv">CSV</option>' . \PHP_EOL; + $content .= "<option value=\"tab\">{$this->lang['strtabbed']}</option>" . \PHP_EOL; + $content .= '<option value="html">XHTML</option>' . \PHP_EOL; + $content .= '<option value="xml">XML</option>' . \PHP_EOL; } - $content .= sprintf( + $content .= \sprintf( '</select>%s</td>%s</tr>%s', - PHP_EOL, - PHP_EOL, - PHP_EOL + \PHP_EOL, + \PHP_EOL, + \PHP_EOL ); if ($hasID) { - $content .= sprintf( + $content .= \sprintf( '<tr><td><label for="d_oids">%s</td>', $this->lang['stroids'] ); - $content .= sprintf( + $content .= \sprintf( '<td><input type="checkbox" id="d_oids" name="d_oids" /></td>%s</tr>%s', - PHP_EOL, - PHP_EOL + \PHP_EOL, + \PHP_EOL ); } @@ -80,46 +84,47 @@ trait ExportTrait public function structureAndData($hasID) { $content = '<tr>'; - $content .= '<th class="data left" rowspan="'.($hasID ? 3 : 2).'">'; + $content .= '<th class="data left" rowspan="' . ($hasID ? 3 : 2) . '">'; $content .= '<input type="radio" id="what3" name="what" value="structureanddata" />'; - $content .= sprintf( + $content .= \sprintf( '<label for="what3">%s</label></th>%s', $this->lang['strstructureanddata'], - PHP_EOL + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<td>%s</td>%s', $this->lang['strformat'], - PHP_EOL + \PHP_EOL ); - $content .= '<td><select name="sd_format">'.PHP_EOL; - $content .= '<option value="copy">COPY</option>'.PHP_EOL; - $content .= '<option value="sql">SQL</option>'.PHP_EOL; - $content .= sprintf( + $content .= '<td><select name="sd_format">' . \PHP_EOL; + $content .= '<option value="copy">COPY</option>' . \PHP_EOL; + $content .= '<option value="sql">SQL</option>' . \PHP_EOL; + $content .= \sprintf( '</select>%s</td>%s</tr>%s', - PHP_EOL, - PHP_EOL, - PHP_EOL + \PHP_EOL, + \PHP_EOL, + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<tr><td><label for="sd_clean">%s</label></td>', $this->lang['strdrop'] ); - $content .= sprintf( + $content .= \sprintf( '<td><input type="checkbox" id="sd_clean" name="sd_clean" /></td>%s</tr>%s', - PHP_EOL, - PHP_EOL + \PHP_EOL, + \PHP_EOL ); + if ($hasID) { - $content .= sprintf( + $content .= \sprintf( '<tr><td><label for="sd_oids">%s</label></td>', $this->lang['stroids'] ); - $content .= sprintf( + $content .= \sprintf( '<td><input type="checkbox" id="sd_oids" name="sd_oids" /></td>%s</tr>%s', - PHP_EOL, - PHP_EOL + \PHP_EOL, + \PHP_EOL ); } @@ -137,23 +142,23 @@ trait ExportTrait public function structureOnly($checked = false) { $content = '<tr><th class="data left">'; - $content .= sprintf( + $content .= \sprintf( '<input type="radio" id="what2" name="what" value="structureonly" %s />', $checked ? 'checked="checked"' : '' ); - $content .= sprintf( + $content .= \sprintf( '<label for="what2">%s</label></th>', $this->lang['strstructureonly'], - PHP_EOL + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<td><label for="no_role_info">%s</label></td>', $this->lang['strdrop'] ); - $content .= sprintf( + $content .= \sprintf( '<td><input type="checkbox" id="no_role_info" name="no_role_info" /></td>%s</tr>%s', - PHP_EOL, - PHP_EOL + \PHP_EOL, + \PHP_EOL ); return $content; @@ -168,21 +173,21 @@ trait ExportTrait */ public function formHeader($endpoint = 'dataexport') { - $content = sprintf( + $content = \sprintf( '<form id="export_form" action="%s/%s" method="post">%s', - \SUBFOLDER.'/src/views', + \SUBFOLDER . '/src/views', $endpoint, - PHP_EOL + \PHP_EOL ); - $content .= '<table>'.PHP_EOL; - $content .= sprintf( + $content .= '<table>' . \PHP_EOL; + $content .= \sprintf( '<tr><th class="data">%s</th>', $this->lang['strformat'] ); - $content .= sprintf( + $content .= \sprintf( '<th class="data" colspan="2">%s</th></tr>%s', $this->lang['stroptions'], - PHP_EOL + \PHP_EOL ); return $content; @@ -198,28 +203,28 @@ trait ExportTrait */ public function formFooter($subject, $object) { - $content = '<p><input type="hidden" name="action" value="export" />'.PHP_EOL; + $content = '<p><input type="hidden" name="action" value="export" />' . \PHP_EOL; $content .= $this->misc->form; - $content .= sprintf( + $content .= \sprintf( '<input type="hidden" name="subject" value="%s" />%s', $subject, - PHP_EOL + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<input type="hidden" name="%s" value="%s" />', $subject, - htmlspecialchars($object), - PHP_EOL + \htmlspecialchars($object), + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<input type="submit" value="%s" /></p>%s', $this->lang['strexport'], - PHP_EOL + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '</form>%s', - PHP_EOL + \PHP_EOL ); return $content; @@ -234,38 +239,38 @@ trait ExportTrait */ public function displayOrDownload($offerGzip = false) { - $content = sprintf( + $content = \sprintf( '</table>%s', - PHP_EOL + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<h3>%s</h3>%s', $this->lang['stroptions'], - PHP_EOL + \PHP_EOL ); $content .= '<p><input type="radio" id="output1" name="output" value="show" checked="checked" />'; - $content .= sprintf( + $content .= \sprintf( '<label for="output1">%s</label>', $this->lang['strshow'], - PHP_EOL + \PHP_EOL ); $content .= '<br/><input type="radio" id="output2" name="output" value="download" />'; - $content .= sprintf( + $content .= \sprintf( '<label for="output2">%s</label>', $this->lang['strdownload'] ); if ($offerGzip) { $content .= '<br /><input type="radio" id="output3" name="output" value="gzipped" />'; - $content .= sprintf( + $content .= \sprintf( '<label for="output3">%s</label>%s', $this->lang['strdownloadgzipped'], - PHP_EOL + \PHP_EOL ); } - $content .= sprintf( + $content .= \sprintf( '</p>%s', - PHP_EOL + \PHP_EOL ); return $content; @@ -282,33 +287,34 @@ trait ExportTrait public function offerNoRoleExport($version10orMore) { $this->prtrace($version10orMore); + if (!$version10orMore) { return ''; } - $content = '<tr>'.PHP_EOL; - $content .= sprintf( + $content = '<tr>' . \PHP_EOL; + $content .= \sprintf( '<tr>%s<td colspan="3"> </td></tr>%s', - PHP_EOL, - PHP_EOL + \PHP_EOL, + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<tr>%s<th class="data left" colspan="3"><h3>%s <br> %s</h3></th></tr>%s', - PHP_EOL, + \PHP_EOL, 'Use the option below if your platform prevents dumping DBs', 'with role info (e.g. Amazon RDS)', - PHP_EOL + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<tr>%s<td colspan="2"><label for="no_role_passwords">%s</label><a href="%s">?</></td>%s', - PHP_EOL, + \PHP_EOL, 'Avoid dumping roles', 'https://www.postgresql.org/docs/10/app-pg-dumpall.html', - PHP_EOL + \PHP_EOL ); - $content .= sprintf( + $content .= \sprintf( '<td><input type="checkbox" id="no_role_passwords" name="no_role_passwords" /></td>%s</tr>%s', - PHP_EOL, - PHP_EOL + \PHP_EOL, + \PHP_EOL ); return $content; diff --git a/src/traits/FormTrait.php b/src/traits/FormTrait.php index 3b69e00a..af4b9c3d 100644 --- a/src/traits/FormTrait.php +++ b/src/traits/FormTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -24,10 +27,10 @@ trait FormTrait public function getActionTableAndButtons($action, $table, $add, $cancel) { $content = $this->misc->form; - $content .= sprintf('<input type="hidden" name="action" value="%s" />%s', $action, PHP_EOL); - $content .= sprintf('<input type="hidden" name="table" value="%s" />%s', $table, PHP_EOL); - $content .= sprintf('<input type="submit" value="%s" />%s', $add, PHP_EOL); - $content .= sprintf('<input type="submit" name="cancel" value="%s" />', $cancel); + $content .= \sprintf('<input type="hidden" name="action" value="%s" />%s', $action, \PHP_EOL); + $content .= \sprintf('<input type="hidden" name="table" value="%s" />%s', $table, \PHP_EOL); + $content .= \sprintf('<input type="submit" value="%s" />%s', $add, \PHP_EOL); + $content .= \sprintf('<input type="submit" name="cancel" value="%s" />', $cancel); return $content; } @@ -44,22 +47,23 @@ trait FormTrait $content = $this->misc->form; foreach ($cheboxes as $checkbox) { - $content .= sprintf('<p>%s', PHP_EOL); - $content .= sprintf('<input type="%s" name="%s" id="%s" %s />', $checkbox['type'], $checkbox['name'], $checkbox['id'], $checkbox['checked'] ? 'checked="checked"' : ''); - $content .= sprintf('<label for="%s">%s</label>', $checkbox['id'], $checkbox['labeltext']); - $content .= sprintf('</p>%s', PHP_EOL); + $content .= \sprintf('<p>%s', \PHP_EOL); + $content .= \sprintf('<input type="%s" name="%s" id="%s" %s />', $checkbox['type'], $checkbox['name'], $checkbox['id'], $checkbox['checked'] ? 'checked="checked"' : ''); + $content .= \sprintf('<label for="%s">%s</label>', $checkbox['id'], $checkbox['labeltext']); + $content .= \sprintf('</p>%s', \PHP_EOL); } foreach ($inputs as $input) { - $content .= sprintf('<input type="%s" name="%s" value="%s" />%s', $input['type'], $input['name'], $input['value'], PHP_EOL); + $content .= \sprintf('<input type="%s" name="%s" value="%s" />%s', $input['type'], $input['name'], $input['value'], \PHP_EOL); } - $content .= sprintf('<p>%s', PHP_EOL); + $content .= \sprintf('<p>%s', \PHP_EOL); + foreach ($buttons as $button) { - $content .= sprintf('<input type="%s" name="%s" value="%s" />%s', $button['type'], $button['name'], $button['value'], PHP_EOL); + $content .= \sprintf('<input type="%s" name="%s" value="%s" />%s', $button['type'], $button['name'], $button['value'], \PHP_EOL); } - $content .= sprintf('</p>%s', PHP_EOL); + $content .= \sprintf('</p>%s', \PHP_EOL); return $content; } diff --git a/src/traits/HelperTrait.php b/src/traits/HelperTrait.php index 1ef43d6a..b5aa6d4c 100644 --- a/src/traits/HelperTrait.php +++ b/src/traits/HelperTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -17,13 +20,36 @@ namespace PHPPgAdmin\Traits; trait HelperTrait { /** + * static reference to subfolder in which the app is running. + * + * @var null|string + */ + public static $subFolder = null; + + /** + * Gets the subfolder. + * + * @param string $path The path + * + * @return string the subfolder + */ + public function getSubfolder(string $path = ''): string + { + if (null === self::$subFolder) { + self::$subFolder = $this->container->subfolder; + } + + return \implode(\DIRECTORY_SEPARATOR, [self::$subFolder, $path]); + } + + /** * Halts the execution of the program. It's like calling exit() but using builtin Slim Exceptions. * * @param string $msg The message to show to the user * * @throws \Slim\Exception\SlimException (description) */ - public function halt($msg = 'An error has happened') + public function halt($msg = 'An error has happened'): void { $body = $this->container->responseobj->getBody(); $body->write($msg); @@ -38,9 +64,9 @@ trait HelperTrait * @param string $key The key to associate with the message. Defaults to the stack * trace of the closure or method that called addFlassh */ - public function addFlash($content, $key = '') + public function addFlash($content, $key = ''): void { - if ($key === '') { + if ('' === $key) { $key = self::getBackTrace(); } // $this->dump(__METHOD__ . ': addMessage ' . $key . ' ' . json_encode($content)); @@ -51,24 +77,22 @@ trait HelperTrait { $i0 = $offset; $i1 = $offset + 1; - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $offset + 3); + $backtrace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, $offset + 3); - $btarray0 = ([ - 'class' => $backtrace[$i1]['class'] === 'Closure' ? + return [ + 'class' => 'Closure' === $backtrace[$i1]['class'] ? $backtrace[$i0]['file'] : $backtrace[$i1]['class'], 'type' => $backtrace[$i1]['type'], - 'function' => $backtrace[$i1]['function'] === '{closure}' + 'function' => '{closure}' === $backtrace[$i1]['function'] ? $backtrace[$i0]['function'] : $backtrace[$i1]['function'], 'spacer4' => ' ', 'line' => $backtrace[$i0]['line'], - ]); - - return $btarray0; + ]; //dump($backtrace); } @@ -84,9 +108,10 @@ trait HelperTrait { $result = []; - if ($set->recordCount() <= 0) { + if (0 >= $set->recordCount()) { return $result; } + while (!$set->EOF) { $result[] = $field ? $set->fields[$field] : $set; $set->moveNext(); @@ -114,7 +139,8 @@ trait HelperTrait return $var1; } - if ($set === true) { + + if (true === $set) { $var1 = $default; return $var1; @@ -137,7 +163,7 @@ trait HelperTrait */ public function coalesceArr(&$array, $key, $default = null, $set = true) { - if (!isset($array[$key]) && $set === true) { + if (!isset($array[$key]) && true === $set) { $array[$key] = $default; } @@ -146,18 +172,18 @@ trait HelperTrait public static function formatSizeUnits($bytes, $lang) { - if ($bytes == -1) { + if (-1 === $bytes) { $bytes = $lang['strnoaccess']; - } elseif ($bytes >= 1099511627776) { - $bytes = sprintf('%s %s', number_format($bytes / 1099511627776, 0), $lang['strtb']); - } elseif ($bytes >= 1073741824) { - $bytes = sprintf('%s %s', number_format($bytes / 1073741824, 0), $lang['strgb']); - } elseif ($bytes >= 1048576) { - $bytes = sprintf('%s %s', number_format($bytes / 1048576, 0), $lang['strmb']); - } elseif ($bytes >= 1024) { - $bytes = sprintf('%s %s', number_format($bytes / 1024, 0), $lang['strkb']); + } elseif (1099511627776 <= $bytes) { + $bytes = \sprintf('%s %s', \number_format($bytes / 1099511627776, 0), $lang['strtb']); + } elseif (1073741824 <= $bytes) { + $bytes = \sprintf('%s %s', \number_format($bytes / 1073741824, 0), $lang['strgb']); + } elseif (1048576 <= $bytes) { + $bytes = \sprintf('%s %s', \number_format($bytes / 1048576, 0), $lang['strmb']); + } elseif (1024 <= $bytes) { + $bytes = \sprintf('%s %s', \number_format($bytes / 1024, 0), $lang['strkb']); } else { - $bytes = sprintf('%s %s', $bytes, $lang['strbytes']); + $bytes = \sprintf('%s %s', $bytes, $lang['strbytes']); } return $bytes; @@ -172,11 +198,13 @@ trait HelperTrait */ public static function br2ln($msg) { - return str_replace(['<br>', '<br/>', '<br />'], PHP_EOL, $msg); + return \str_replace(['<br>', '<br/>', '<br />'], \PHP_EOL, $msg); } /** * Receives N parameters and sends them to the console adding where was it called from. + * + * @param array $args */ public function prtrace(...$args) { @@ -188,6 +216,11 @@ trait HelperTrait return self::staticTrace($args); } + public function dumpAndDie(...$args) + { + return self::staticTrace($args); + } + /** * Receives N parameters and sends them to the console adding where was it * called from. @@ -199,28 +232,25 @@ trait HelperTrait $variablesToDump = [], string $whoCalledMe = '', $exitAfterwards = false - ) { + ): void { if (!$variablesToDump) { - $variablesToDump = func_get_args(); + $variablesToDump = \func_get_args(); } - if ($whoCalledMe === '') { - $whoCalledMe = str_replace(BASE_PATH, '', implode('', self::getBackTrace(2))); + + if ('' === $whoCalledMe) { + $whoCalledMe = \str_replace(BASE_PATH, '', \implode('', self::getBackTrace(2))); } - if ($exitAfterwards && function_exists('dd')) { + + if ($exitAfterwards && \function_exists('dd')) { dd([ 'args' => $variablesToDump, 'from' => $whoCalledMe, ]); - } elseif (function_exists('dump')) { + } elseif (\function_exists('dump')) { dump([ 'args' => $variablesToDump, 'from' => $whoCalledMe, ]); } } - - public function dumpAndDie(...$args) - { - return self::staticTrace($args); - } } diff --git a/src/traits/InsertEditRowTrait.php b/src/traits/InsertEditRowTrait.php index 8cf32982..7e117a14 100644 --- a/src/traits/InsertEditRowTrait.php +++ b/src/traits/InsertEditRowTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -12,22 +15,10 @@ namespace PHPPgAdmin\Traits; trait InsertEditRowTrait { public $href = ''; - public $conf; - public $misc; - private function _getFKProps() - { - if (('disable' != $this->conf['autocomplete'])) { - $fksprops = $this->getAutocompleteFKProperties($_REQUEST['table']); - if (false !== $fksprops) { - echo $fksprops['code']; - } - } else { - $fksprops = false; - } + public $conf; - return $fksprops; - } + public $misc; /** * Returns an array representing FKs definition for a table, sorted by fields @@ -68,7 +59,7 @@ trait InsertEditRowTrait if (!$constrs->EOF) { //$conrelid = $constrs->fields['conrelid']; while (!$constrs->EOF) { - if ($constrs->fields['contype'] == 'f') { + if ('f' === $constrs->fields['contype']) { if (!isset($fksprops['byconstr'][$constrs->fields['conid']])) { $fksprops['byconstr'][$constrs->fields['conid']] = [ 'confrelid' => $constrs->fields['confrelid'], @@ -93,42 +84,46 @@ trait InsertEditRowTrait $constrs->moveNext(); } - $fksprops['code'] = '<script type="text/javascript">'.PHP_EOL; + $fksprops['code'] = '<script type="text/javascript">' . \PHP_EOL; $fksprops['code'] .= "var constrs = {};\n"; + foreach ($fksprops['byconstr'] as $conid => $props) { $fksprops['code'] .= "constrs.constr_{$conid} = {\n"; - $fksprops['code'] .= 'pattnums: ['.implode(',', $props['pattnums'])."],\n"; - $fksprops['code'] .= "f_table:'".addslashes(htmlentities($props['f_table'], ENT_QUOTES, 'UTF-8'))."',\n"; - $fksprops['code'] .= "f_schema:'".addslashes(htmlentities($props['f_schema'], ENT_QUOTES, 'UTF-8'))."',\n"; + $fksprops['code'] .= 'pattnums: [' . \implode(',', $props['pattnums']) . "],\n"; + $fksprops['code'] .= "f_table:'" . \addslashes(\htmlentities($props['f_table'], \ENT_QUOTES, 'UTF-8')) . "',\n"; + $fksprops['code'] .= "f_schema:'" . \addslashes(\htmlentities($props['f_schema'], \ENT_QUOTES, 'UTF-8')) . "',\n"; $_ = ''; + foreach ($props['pattnames'] as $n) { - $_ .= ",'".htmlentities($n, ENT_QUOTES, 'UTF-8')."'"; + $_ .= ",'" . \htmlentities($n, \ENT_QUOTES, 'UTF-8') . "'"; } - $fksprops['code'] .= 'pattnames: ['.substr($_, 1)."],\n"; + $fksprops['code'] .= 'pattnames: [' . \mb_substr($_, 1) . "],\n"; $_ = ''; + foreach ($props['fattnames'] as $n) { - $_ .= ",'".htmlentities($n, ENT_QUOTES, 'UTF-8')."'"; + $_ .= ",'" . \htmlentities($n, \ENT_QUOTES, 'UTF-8') . "'"; } - $fksprops['code'] .= 'fattnames: ['.substr($_, 1)."]\n"; + $fksprops['code'] .= 'fattnames: [' . \mb_substr($_, 1) . "]\n"; $fksprops['code'] .= "};\n"; } $fksprops['code'] .= "var attrs = {};\n"; + foreach ($fksprops['byfield'] as $attnum => $cstrs) { - $fksprops['code'] .= "attrs.attr_{$attnum} = [".implode(',', $fksprops['byfield'][$attnum])."];\n"; + $fksprops['code'] .= "attrs.attr_{$attnum} = [" . \implode(',', $fksprops['byfield'][$attnum]) . "];\n"; } - $fksprops['code'] .= "var table='".addslashes(htmlentities($table, ENT_QUOTES, 'UTF-8'))."';"; - $fksprops['code'] .= "var server='".htmlentities($_REQUEST['server'], ENT_QUOTES, 'UTF-8')."';"; - $fksprops['code'] .= "var database='".addslashes(htmlentities($_REQUEST['database'], ENT_QUOTES, 'UTF-8'))."';"; - $fksprops['code'] .= "var subfolder='".SUBFOLDER."';"; - $fksprops['code'] .= '</script>'.PHP_EOL; + $fksprops['code'] .= "var table='" . \addslashes(\htmlentities($table, \ENT_QUOTES, 'UTF-8')) . "';"; + $fksprops['code'] .= "var server='" . \htmlentities($_REQUEST['server'], \ENT_QUOTES, 'UTF-8') . "';"; + $fksprops['code'] .= "var database='" . \addslashes(\htmlentities($_REQUEST['database'], \ENT_QUOTES, 'UTF-8')) . "';"; + $fksprops['code'] .= "var subfolder='" . SUBFOLDER . "';"; + $fksprops['code'] .= '</script>' . \PHP_EOL; $fksprops['code'] .= '<div id="fkbg"></div>'; $fksprops['code'] .= '<div id="fklist"></div>'; - $fksprops['code'] .= '<script src="'.SUBFOLDER.'/assets/js/ac_insert_row.js" type="text/javascript"></script>'; + $fksprops['code'] .= '<script src="' . SUBFOLDER . '/assets/js/ac_insert_row.js" type="text/javascript"></script>'; } else { /* we have no foreign keys on this table */ return false; @@ -136,4 +131,19 @@ trait InsertEditRowTrait return $fksprops; } + + private function _getFKProps() + { + if (('disable' !== $this->conf['autocomplete'])) { + $fksprops = $this->getAutocompleteFKProperties($_REQUEST['table']); + + if (false !== $fksprops) { + echo $fksprops['code']; + } + } else { + $fksprops = false; + } + + return $fksprops; + } } diff --git a/src/traits/MiscTrait.php b/src/traits/MiscTrait.php index a66ee5c2..f19dcb60 100644 --- a/src/traits/MiscTrait.php +++ b/src/traits/MiscTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -15,8 +18,6 @@ use PHPPgAdmin\Decorators\Decorator; /** * A trait to deal with nav tabs. - * - * @package PHPPgAdmin */ trait MiscTrait { @@ -25,15 +26,15 @@ trait MiscTrait $vars = []; $common_params = []; - if (array_key_exists('server', $_REQUEST)) { + if (\array_key_exists('server', $_REQUEST)) { $common_params['server'] = $_REQUEST['server']; } - if (array_key_exists('database', $_REQUEST)) { + if (\array_key_exists('database', $_REQUEST)) { $common_params['database'] = $_REQUEST['database']; } - if (array_key_exists('schema', $_REQUEST)) { + if (\array_key_exists('schema', $_REQUEST)) { $common_params['schema'] = $_REQUEST['schema']; } @@ -64,19 +65,19 @@ trait MiscTrait break; case 'database': - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'database', ])]; break; case 'schema': - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'schema', ])]; break; case 'table': - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'table', 'table' => $_REQUEST['table'], @@ -86,7 +87,7 @@ trait MiscTrait case 'selectrows': $vars = [ 'url' => 'tables', - 'params' => array_merge($common_params, [ + 'params' => \array_merge($common_params, [ 'subject' => 'table', 'table' => $_REQUEST['table'], 'action' => 'confselectrows', @@ -94,14 +95,14 @@ trait MiscTrait break; case 'view': - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'view', 'view' => $_REQUEST['view'], ])]; break; case 'matview': - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'matview', 'matview' => $_REQUEST['matview'], ])]; @@ -109,7 +110,7 @@ trait MiscTrait break; case 'fulltext': case 'ftscfg': - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'fulltext', 'action' => 'viewconfig', 'ftscfg' => $_REQUEST['ftscfg'], @@ -117,7 +118,7 @@ trait MiscTrait break; case 'function': - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'function', 'function' => $_REQUEST['function'], 'function_oid' => $_REQUEST['function_oid'], @@ -125,7 +126,7 @@ trait MiscTrait break; case 'aggregate': - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'aggregate', 'action' => 'properties', 'aggrname' => $_REQUEST['aggrname'], @@ -135,21 +136,21 @@ trait MiscTrait break; case 'column': if (isset($_REQUEST['table'])) { - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'column', 'table' => $_REQUEST['table'], 'column' => $_REQUEST['column'], ])]; } elseif (isset($_REQUEST['view'])) { - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'column', 'view' => $_REQUEST['view'], 'column' => $_REQUEST['column'], ])]; } elseif (isset($_REQUEST['matview'])) { - $vars = ['params' => array_merge($common_params, [ + $vars = ['params' => \array_merge($common_params, [ 'subject' => 'column', 'matview' => $_REQUEST['matview'], @@ -165,7 +166,8 @@ trait MiscTrait if (!isset($vars['url'])) { $vars['url'] = SUBFOLDER . '/redirect'; } - if ($vars['url'] == SUBFOLDER . '/redirect' && isset($vars['params']['subject'])) { + + if (SUBFOLDER . '/redirect' === $vars['url'] && isset($vars['params']['subject'])) { $vars['url'] = SUBFOLDER . '/redirect/' . $vars['params']['subject']; unset($vars['params']['subject']); } @@ -179,13 +181,14 @@ trait MiscTrait $str = $params['map'][$str]; } // Clip the value if the 'clip' parameter is true. - if (!isset($params['clip']) || $params['clip'] !== true) { + if (!isset($params['clip']) || true !== $params['clip']) { return $str; } - $maxlen = isset($params['cliplen']) && is_integer($params['cliplen']) ? $params['cliplen'] : $this->conf['max_chars']; - $ellipsis = isset($params['ellipsis']) ? $params['ellipsis'] : $this->lang['strellipsis']; - if (strlen($str) > $maxlen) { - $str = substr($str, 0, $maxlen - 1) . $ellipsis; + $maxlen = isset($params['cliplen']) && \is_int($params['cliplen']) ? $params['cliplen'] : $this->conf['max_chars']; + $ellipsis = $params['ellipsis'] ?? $this->lang['strellipsis']; + + if (\mb_strlen($str) > $maxlen) { + $str = \mb_substr($str, 0, $maxlen - 1) . $ellipsis; } return $str; @@ -193,30 +196,31 @@ trait MiscTrait public function printBoolean($type, &$str, $params) { - $lang = $this->$lang; - if ($type === 'yesno') { + $lang = $this->lang; + + if ('yesno' === $type) { $this->coalesceArr($params, 'true', $lang['stryes']); $this->coalesceArr($params, 'false', $lang['strno']); } - if (is_bool($str)) { + if (\is_bool($str)) { $str = $str ? 't' : 'f'; } switch ($str) { case 't': - $out = (isset($params['true']) ? $params['true'] : $lang['strtrue']); + $out = ($params['true'] ?? $lang['strtrue']); $align = 'center'; break; case 'f': - $out = (isset($params['false']) ? $params['false'] : $lang['strfalse']); + $out = ($params['false'] ?? $lang['strfalse']); $align = 'center'; break; default: $align = null; - $out = htmlspecialchars($str); + $out = \htmlspecialchars($str); } return [$str, $align, $out]; @@ -253,16 +257,17 @@ trait MiscTrait public function printVal($str, $type = null, $params = []) { $lang = $this->lang; - if ($this->_data === null) { + + if (null === $this->_data) { $data = $this->getDatabaseAccessor(); } else { $data = $this->_data; } // Shortcircuit for a NULL value - if (is_null($str)) { + if (null === $str) { return isset($params['null']) - ? ($params['null'] === true ? '<i>NULL</i>' : $params['null']) + ? (true === $params['null'] ? '<i>NULL</i>' : $params['null']) : ''; } @@ -284,7 +289,7 @@ trait MiscTrait case 'cid': case 'tid': $align = 'right'; - $out = nl2br(htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str))); + $out = \nl2br(\htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str))); break; case 'yesno': @@ -302,12 +307,12 @@ trait MiscTrait case 'errormsg': $tag = 'pre'; $class = 'error'; - $out = htmlspecialchars($str); + $out = \htmlspecialchars($str); break; case 'pre': $tag = 'pre'; - $out = htmlspecialchars($str); + $out = \htmlspecialchars($str); break; case 'prenoescape': @@ -316,7 +321,7 @@ trait MiscTrait break; case 'nbsp': - $out = nl2br(str_replace(' ', ' ', \PHPPgAdmin\Traits\HelperTrait::br2ln($str))); + $out = \nl2br(\str_replace(' ', ' ', \PHPPgAdmin\Traits\HelperTrait::br2ln($str))); break; case 'verbatim': @@ -335,37 +340,22 @@ trait MiscTrait // If the string contains at least one instance of >1 space in a row, a tab // character, a space at the start of a line, or a space at the start of // the whole string then render within a pre-formatted element (<pre>). - if (preg_match('/(^ | |\t|\n )/m', $str)) { + if (\preg_match('/(^ | |\t|\n )/m', $str)) { $tag = 'pre'; $class = 'data'; - $out = htmlspecialchars($str); + $out = \htmlspecialchars($str); } else { //$tag = 'span'; - $out = nl2br(htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str))); + $out = \nl2br(\htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str))); } } $this->adjustClassAlignTag($class, $align, $tag, $out, $params); - // Add line numbers if 'lineno' param is true - /*if (isset($params['lineno']) && $params['lineno'] === true) { - $lines = explode(PHP_EOL, $str); - $num = count($lines); - if ($num > 0) { - $temp = "<table>\n<tr><td class=\"{$class}\" style=\"vertical-align: top; padding-right: 10px;\"><pre class=\"{$class}\">"; - for ($i = 1; $i <= $num; ++$i) { - $temp .= $i . PHP_EOL; - } - $temp .= "</pre></td><td class=\"{$class}\" style=\"vertical-align: top;\">{$out}</td></tr></table>".PHP_EOL; - $out = $temp; - } - unset($lines); - }*/ - return $out; } - public function adjustClassAlignTag(&$class, &$align, &$tag, &$out, $params) + public function adjustClassAlignTag(&$class, &$align, &$tag, &$out, $params): void { if (isset($params['class'])) { $class = $params['class']; @@ -396,7 +386,8 @@ trait MiscTrait public function getTabsRoot($data) { $lang = $this->lang; - $tabs = [ + + return [ 'intro' => [ 'title' => $lang['strintroduction'], 'url' => 'intro', @@ -408,8 +399,6 @@ trait MiscTrait 'icon' => 'Servers', ], ]; - - return $tabs; } /** @@ -424,6 +413,7 @@ trait MiscTrait $lang = $this->lang; $hide_users = true; $hide_roles = false; + if ($data) { $hide_users = !$data->isSuperUser(); } @@ -447,7 +437,7 @@ trait MiscTrait ]; if ($data && $data->hasRoles()) { - $tabs = array_merge($tabs, [ + $tabs = \array_merge($tabs, [ 'roles' => [ 'title' => $lang['strroles'], 'url' => 'roles', @@ -458,7 +448,7 @@ trait MiscTrait ], ]); } else { - $tabs = array_merge($tabs, [ + $tabs = \array_merge($tabs, [ 'groups' => [ 'title' => $lang['strgroups'], 'url' => 'groups', @@ -470,7 +460,7 @@ trait MiscTrait ]); } - $tabs = array_merge($tabs, [ + return \array_merge($tabs, [ 'account' => [ 'title' => $lang['straccount'], 'url' => ($data && $data->hasRoles()) ? 'roles' : 'users', @@ -495,8 +485,6 @@ trait MiscTrait 'icon' => 'Export', ], ]); - - return $tabs; } /** @@ -509,8 +497,9 @@ trait MiscTrait public function getTabsDatabase($data) { $lang = $this->lang; - $hide_advanced = ($this->conf['show_advanced'] === false); - $tabs = [ + $hide_advanced = (false === $this->conf['show_advanced']); + + return [ 'schemas' => [ 'title' => $lang['strschemas'], 'url' => 'schemas', @@ -598,14 +587,12 @@ trait MiscTrait 'icon' => 'Export', ], ]; - - return $tabs; } public function getTabsSchema($data) { $lang = $this->lang; - $hide_advanced = ($this->conf['show_advanced'] === false); + $hide_advanced = (false === $this->conf['show_advanced']); $tabs = [ 'tables' => [ 'title' => $lang['strtables'], @@ -714,6 +701,7 @@ trait MiscTrait 'icon' => 'Export', ], ]; + if (!$data->hasFTS()) { unset($tabs['fulltext']); } @@ -724,7 +712,8 @@ trait MiscTrait public function getTabsTable($data) { $lang = $this->lang; - $tabs = [ + + return [ 'columns' => [ 'title' => $lang['strcolumns'], 'url' => 'tblproperties', @@ -823,14 +812,13 @@ trait MiscTrait 'hide' => false, ], ]; - - return $tabs; } public function getTabsView($data) { $lang = $this->lang; - $tabs = [ + + return [ 'columns' => [ 'title' => $lang['strcolumns'], 'url' => 'viewproperties', @@ -886,14 +874,13 @@ trait MiscTrait 'hide' => false, ], ]; - - return $tabs; } public function getTabsMatview($data) { $lang = $this->lang; - $tabs = [ + + return [ 'columns' => [ 'title' => $lang['strcolumns'], 'url' => 'materializedviewproperties', @@ -966,14 +953,13 @@ trait MiscTrait 'hide' => false, ], ]; - - return $tabs; } public function getTabsFunction($data) { $lang = $this->lang; - $tabs = [ + + return [ 'definition' => [ 'title' => $lang['strdefinition'], 'url' => 'functions', @@ -1007,14 +993,13 @@ trait MiscTrait 'icon' => 'Search', ], ]; - - return $tabs; } public function getTabsAggregate($data) { $lang = $this->lang; - $tabs = [ + + return [ 'definition' => [ 'title' => $lang['strdefinition'], 'url' => 'aggregates', @@ -1027,14 +1012,13 @@ trait MiscTrait 'icon' => 'Definition', ], ]; - - return $tabs; } public function getTabsRole($data) { $lang = $this->lang; - $tabs = [ + + return [ 'definition' => [ 'title' => $lang['strdefinition'], 'url' => 'roles', @@ -1046,14 +1030,13 @@ trait MiscTrait 'icon' => 'Definition', ], ]; - - return $tabs; } public function getTabsPopup($data) { $lang = $this->lang; - $tabs = [ + + return [ 'sql' => [ 'title' => $lang['strsql'], 'url' => \SUBFOLDER . '/src/views/sqledit', @@ -1068,8 +1051,6 @@ trait MiscTrait 'icon' => 'Search', ], ]; - - return $tabs; } public function getTabsColumn($data) @@ -1100,9 +1081,11 @@ trait MiscTrait 'icon' => 'Privileges', ], ]; + if (empty($tabs['properties']['urlvars']['table'])) { unset($tabs['properties']['urlvars']['table']); } + if (empty($tabs['privileges']['urlvars']['table'])) { unset($tabs['privileges']['urlvars']['table']); } @@ -1113,7 +1096,8 @@ trait MiscTrait public function getTabsFulltext($data) { $lang = $this->lang; - $tabs = [ + + return [ 'ftsconfigs' => [ 'title' => $lang['strftstabconfigs'], 'url' => 'fulltext', @@ -1142,8 +1126,6 @@ trait MiscTrait 'icon' => 'FtsParser', ], ]; - - return $tabs; } /** @@ -1158,7 +1140,7 @@ trait MiscTrait $data = $this->getDatabaseAccessor(); $lang = $this->lang; - $hide_advanced = ($this->conf['show_advanced'] === false); + $hide_advanced = (false === $this->conf['show_advanced']); $tabs = []; switch ($section) { @@ -1224,10 +1206,11 @@ trait MiscTrait //$data = $this->getDatabaseAccessor(); $tabs = $this->getNavTabs($section); + if (isset($_SESSION['webdbLastTab'][$section], $tabs[$_SESSION['webdbLastTab'][$section]])) { $tab = $tabs[$_SESSION['webdbLastTab'][$section]]; } else { - $tab = reset($tabs); + $tab = \reset($tabs); } // $this->prtrace(['section' => $section, 'tabs' => $tabs, 'tab' => $tab]); diff --git a/src/traits/ServersTrait.php b/src/traits/ServersTrait.php index c206cf01..840804ce 100644 --- a/src/traits/ServersTrait.php +++ b/src/traits/ServersTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -23,12 +26,12 @@ trait ServersTrait */ public function getServers($recordset = false, $group = false) { - $logins = isset($_SESSION['webdbLogin']) && is_array($_SESSION['webdbLogin']) ? $_SESSION['webdbLogin'] : []; + $logins = isset($_SESSION['webdbLogin']) && \is_array($_SESSION['webdbLogin']) ? $_SESSION['webdbLogin'] : []; $srvs = []; - if (($group !== false) && ($group !== 'all')) { + if ((false !== $group) && ('all' !== $group)) { if (isset($this->conf['srv_groups'][$group]['servers'])) { - $group = array_fill_keys(explode(',', preg_replace( + $group = \array_fill_keys(\explode(',', \preg_replace( '/\s/', '', $this->conf['srv_groups'][$group]['servers'] @@ -39,10 +42,11 @@ trait ServersTrait } foreach ($this->conf['servers'] as $idx => $info) { - $server_id = $info['host'].':'.$info['port'].':'.$info['sslmode']; - if ($group === false || isset($group[$idx]) || ($group === 'all')) { - $server_id = $info['host'].':'.$info['port'].':'.$info['sslmode']; - $server_sha = sha1($server_id); + $server_id = $info['host'] . ':' . $info['port'] . ':' . $info['sslmode']; + + if (false === $group || isset($group[$idx]) || ('all' === $group)) { + $server_id = $info['host'] . ':' . $info['port'] . ':' . $info['sslmode']; + $server_sha = \sha1($server_id); if (isset($logins[$server_sha])) { $srvs[$server_sha] = $logins[$server_sha]; @@ -60,6 +64,7 @@ trait ServersTrait 'server' => Decorator::field('sha'), ] ); + if (isset($srvs[$server_sha]['username'])) { $srvs[$server_sha]['icon'] = 'Server'; $srvs[$server_sha]['branch'] = Decorator::url( @@ -77,8 +82,8 @@ trait ServersTrait } } - uasort($srvs, function ($a, $b) { - return strcmp($a['desc'], $b['desc']); + \uasort($srvs, static function ($a, $b) { + return \strcmp($a['desc'], $b['desc']); }); if ($recordset) { @@ -88,81 +93,87 @@ trait ServersTrait return $srvs; } - /* + /** * Output dropdown list to select server and * databases form the popups windows. + * * @param string $the_action an action identifying the purpose of this snipper sql|find|history + * @param mixed $do_print */ public function printConnection($the_action, $do_print = true) { - $connection_html = '<table class="printconnection" style="width: 100%"><tr><td class="popup_select1">'.PHP_EOL; + $connection_html = '<table class="printconnection" style="width: 100%"><tr><td class="popup_select1">' . \PHP_EOL; $conf_servers = $this->getServers(); $server_id = $this->misc->getServerId(); $servers = []; + foreach ($conf_servers as $key => $info) { if (empty($info['username'])) { continue; } $info['selected'] = ''; + if ($this->getRequestParam('server') === $info['id'] || $this->getRequestParam('server') === $key) { $info['selected'] = ' selected="selected" '; } $servers[$key] = $info; } - $connection_html .= '<input type="hidden" readonly="readonly" value="'.$the_action.'" id="the_action">'; + $connection_html .= '<input type="hidden" readonly="readonly" value="' . $the_action . '" id="the_action">'; - if (count($servers) === 1) { - $connection_html .= '<input type="hidden" readonly="readonly" value="'.$server_id.'" name="server">'; + if (1 === \count($servers)) { + $connection_html .= '<input type="hidden" readonly="readonly" value="' . $server_id . '" name="server">'; } else { $connection_html .= '<label>'; $connection_html .= $this->misc->printHelp($this->lang['strserver'], 'pg.server', false); $connection_html .= ': </label>'; - $connection_html .= " <select name=\"server\" id='selectserver' >".PHP_EOL; + $connection_html .= " <select name=\"server\" id='selectserver' >" . \PHP_EOL; + foreach ($servers as $id => $server) { - $connection_html .= '<option value="'.$id.'" '.$server['selected'].'>'; - $connection_html .= htmlspecialchars("{$server['desc']} ({$server['id']})"); - $connection_html .= '</option>'.PHP_EOL; + $connection_html .= '<option value="' . $id . '" ' . $server['selected'] . '>'; + $connection_html .= \htmlspecialchars("{$server['desc']} ({$server['id']})"); + $connection_html .= '</option>' . \PHP_EOL; } - $connection_html .= '</select>'.PHP_EOL; + $connection_html .= '</select>' . \PHP_EOL; } - $connection_html .= '</td><td class="popup_select2" style="text-align: right">'.PHP_EOL; + $connection_html .= '</td><td class="popup_select2" style="text-align: right">' . \PHP_EOL; - if (count($servers) === 1 && + if (1 === \count($servers) && isset($servers[$server_id]['useonlydefaultdb']) && - $servers[$server_id]['useonlydefaultdb'] === true + true === $servers[$server_id]['useonlydefaultdb'] ) { - $connection_html .= '<input type="hidden" name="database" value="'.htmlspecialchars($servers[$server_id]['defaultdb']).'" />'.PHP_EOL; + $connection_html .= '<input type="hidden" name="database" value="' . \htmlspecialchars($servers[$server_id]['defaultdb']) . '" />' . \PHP_EOL; } else { // Get the list of all databases $data = $this->misc->getDatabaseAccessor(); $databases = $data->getDatabases(); - if ($databases->recordCount() > 0) { + + if (0 < $databases->recordCount()) { $connection_html .= '<label>'; $connection_html .= $this->misc->printHelp($this->lang['strdatabase'], 'pg.database', false); - $connection_html .= ": <select id='selectdb' name=\"database\" >".PHP_EOL; + $connection_html .= ": <select id='selectdb' name=\"database\" >" . \PHP_EOL; //if no database was selected, user should select one if (!isset($_REQUEST['database'])) { - $connection_html .= '<option value="">--</option>'.PHP_EOL; + $connection_html .= '<option value="">--</option>' . \PHP_EOL; } while (!$databases->EOF) { $dbname = $databases->fields['datname']; - $dbselected = isset($_REQUEST['database']) && $dbname == $_REQUEST['database'] ? ' selected="selected"' : ''; - $connection_html .= '<option value="'.htmlspecialchars($dbname).'" '.$dbselected.'>'.htmlspecialchars($dbname).'</option>'.PHP_EOL; + $dbselected = isset($_REQUEST['database']) && $dbname === $_REQUEST['database'] ? ' selected="selected"' : ''; + $connection_html .= '<option value="' . \htmlspecialchars($dbname) . '" ' . $dbselected . '>' . \htmlspecialchars($dbname) . '</option>' . \PHP_EOL; $databases->moveNext(); } - $connection_html .= '</select></label>'.PHP_EOL; + $connection_html .= '</select></label>' . \PHP_EOL; } else { $server_info = $this->misc->getServerInfo(); - $connection_html .= '<input type="hidden" name="database" value="'.htmlspecialchars($server_info['defaultdb']).'" />'.PHP_EOL; + $connection_html .= '<input type="hidden" name="database" value="' . \htmlspecialchars($server_info['defaultdb']) . '" />' . \PHP_EOL; } } - $connection_html .= '</td></tr></table>'.PHP_EOL; + $connection_html .= '</td></tr></table>' . \PHP_EOL; if ($do_print) { echo $connection_html; diff --git a/src/traits/ViewsMatViewsPropertiesTrait.php b/src/traits/ViewsMatViewsPropertiesTrait.php index 294578d4..903f3836 100644 --- a/src/traits/ViewsMatViewsPropertiesTrait.php +++ b/src/traits/ViewsMatViewsPropertiesTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -14,7 +17,9 @@ use PHPPgAdmin\Decorators\Decorator; trait ViewsMatViewsPropertiesTrait { public $href = ''; + public $misc; + public $view_name; /** @@ -22,11 +27,11 @@ trait ViewsMatViewsPropertiesTrait * * @param mixed $msg */ - public function doDefault($msg = '') + public function doDefault($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); - $attPre = function (&$rowdata) use ($data) { + $attPre = static function (&$rowdata) use ($data): void { $rowdata->fields['+type'] = $data->formatType($rowdata->fields['type'], $rowdata->fields['atttypmod']); }; @@ -41,14 +46,14 @@ trait ViewsMatViewsPropertiesTrait // Show comment if any if (null !== $vdata->fields['relcomment']) { - echo '<p class="comment">', $this->misc->printVal($vdata->fields['relcomment']), '</p>'.PHP_EOL; + echo '<p class="comment">', $this->misc->printVal($vdata->fields['relcomment']), '</p>' . \PHP_EOL; } $columns = [ 'column' => [ 'title' => $this->lang['strcolumn'], 'field' => Decorator::field('attname'), - 'url' => "colproperties?subject=column&{$this->misc->href}&view=".urlencode($_REQUEST[$this->subject]).'&', + 'url' => "colproperties?subject=column&{$this->misc->href}&view=" . \urlencode($_REQUEST[$this->subject]) . '&', 'vars' => ['column' => 'attname'], ], 'type' => [ @@ -86,7 +91,7 @@ trait ViewsMatViewsPropertiesTrait echo $this->printTable($attrs, $columns, $actions, "{$this->view_name}-{$this->view_name}", $this->lang['strnodata'], $attPre); - echo '<br />'.PHP_EOL; + echo '<br />' . \PHP_EOL; $navlinks = [ 'browse' => [ @@ -108,7 +113,7 @@ trait ViewsMatViewsPropertiesTrait 'select' => [ 'attr' => [ 'href' => [ - 'url' => str_replace('properties', 's', $this->view_name), + 'url' => \str_replace('properties', 's', $this->view_name), 'urlvars' => [ 'action' => 'confselectrows', 'server' => $_REQUEST['server'], @@ -123,7 +128,7 @@ trait ViewsMatViewsPropertiesTrait 'drop' => [ 'attr' => [ 'href' => [ - 'url' => str_replace('properties', 's', $this->view_name), + 'url' => \str_replace('properties', 's', $this->view_name), 'urlvars' => [ 'action' => 'confirm_drop', 'server' => $_REQUEST['server'], @@ -152,7 +157,8 @@ trait ViewsMatViewsPropertiesTrait ], ]; $this->prtrace($this->view_name); - if ($this->view_name === 'materializedviewproperties') { + + if ('materializedviewproperties' === $this->view_name) { $navlinks['refresh'] = [ 'attr' => [ 'href' => [ @@ -170,7 +176,7 @@ trait ViewsMatViewsPropertiesTrait ]; } - $this->printNavLinks($navlinks, "{$this->view_name}-{$this->view_name}", get_defined_vars()); + $this->printNavLinks($navlinks, "{$this->view_name}-{$this->view_name}", \get_defined_vars()); } public function doTree() @@ -221,7 +227,7 @@ trait ViewsMatViewsPropertiesTrait * * @param mixed $msg */ - public function doExport($msg = '') + public function doExport($msg = ''): void { $this->printTrail($this->subject); $this->printTabs($this->subject, 'export'); @@ -250,7 +256,7 @@ trait ViewsMatViewsPropertiesTrait * * @param mixed $msg */ - public function doDefinition($msg = '') + public function doDefinition($msg = ''): void { $data = $this->misc->getDatabaseAccessor(); @@ -261,18 +267,18 @@ trait ViewsMatViewsPropertiesTrait $this->printTabs($this->subject, 'definition'); $this->printMsg($msg); - if ($vdata->recordCount() > 0) { + if (0 < $vdata->recordCount()) { // Show comment if any if (null !== $vdata->fields['relcomment']) { - echo '<p class="comment">', $this->misc->printVal($vdata->fields['relcomment']), '</p>'.PHP_EOL; + echo '<p class="comment">', $this->misc->printVal($vdata->fields['relcomment']), '</p>' . \PHP_EOL; } - echo '<table style="width: 100%">'.PHP_EOL; - echo "<tr><th class=\"data\">{$this->lang['strdefinition']}</th></tr>".PHP_EOL; - echo '<tr><td class="data1">', $this->misc->printVal($vdata->fields['vwdefinition']), '</td></tr>'.PHP_EOL; - echo '</table>'.PHP_EOL; + echo '<table style="width: 100%">' . \PHP_EOL; + echo "<tr><th class=\"data\">{$this->lang['strdefinition']}</th></tr>" . \PHP_EOL; + echo '<tr><td class="data1">', $this->misc->printVal($vdata->fields['vwdefinition']), '</td></tr>' . \PHP_EOL; + echo '</table>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL; + echo "<p>{$this->lang['strnodata']}</p>" . \PHP_EOL; } $this->printNavLinks(['alter' => [ @@ -289,6 +295,6 @@ trait ViewsMatViewsPropertiesTrait ], ], 'content' => $this->lang['stralter'], - ]], "{$this->view_name}-definition", get_defined_vars()); + ]], "{$this->view_name}-definition", \get_defined_vars()); } } diff --git a/src/traits/ViewsMatviewsTrait.php b/src/traits/ViewsMatviewsTrait.php index b404668c..61a11b43 100644 --- a/src/traits/ViewsMatviewsTrait.php +++ b/src/traits/ViewsMatviewsTrait.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Traits; @@ -14,7 +17,9 @@ use PHPPgAdmin\Decorators\Decorator; trait ViewsMatviewsTrait { public $href = ''; + public $misc; + public $view_name; public function doSubTree() @@ -62,12 +67,12 @@ trait ViewsMatviewsTrait $attrs = $data->getTableAttributes($_REQUEST[$this->keystring]); - echo '<form action="'.\SUBFOLDER.'/src/views/'.$this->script.'" method="post" id="selectform">'; - echo PHP_EOL; + echo '<form action="' . \SUBFOLDER . '/src/views/' . $this->script . '" method="post" id="selectform">'; + echo \PHP_EOL; - if ($attrs->recordCount() > 0) { + if (0 < $attrs->recordCount()) { // JavaScript for select all feature - echo '<script type="text/javascript">'.PHP_EOL; + echo '<script type="text/javascript">' . \PHP_EOL; echo "//<![CDATA[\n"; echo " function selectAll() {\n"; echo " for (var i=0; i<document.getElementById('selectform').elements.length; i++) {\n"; @@ -77,10 +82,10 @@ trait ViewsMatviewsTrait echo " }\n"; echo " }\n"; echo " }\n"; - echo '//]]>'.PHP_EOL; - echo '</script>'.PHP_EOL; + echo '//]]>' . \PHP_EOL; + echo '</script>' . \PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; // Output table header echo "<tr><th class=\"data\">{$this->lang['strshow']}</th><th class=\"data\">{$this->lang['strcolumn']}</th>"; @@ -88,6 +93,7 @@ trait ViewsMatviewsTrait echo "<th class=\"data\">{$this->lang['strvalue']}</th></tr>"; $i = 0; + while (!$attrs->EOF) { $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']); // Set up default value if there isn't one already @@ -100,43 +106,44 @@ trait ViewsMatviewsTrait } // Continue drawing row - $id = (0 == ($i % 2) ? '1' : '2'); - echo "<tr class=\"data{$id}\">".PHP_EOL; + $id = (0 === ($i % 2) ? '1' : '2'); + echo "<tr class=\"data{$id}\">" . \PHP_EOL; echo '<td style="white-space:nowrap;">'; - echo '<input type="checkbox" name="show[', htmlspecialchars($attrs->fields['attname']), ']"', + echo '<input type="checkbox" name="show[', \htmlspecialchars($attrs->fields['attname']), ']"', isset($_REQUEST['show'][$attrs->fields['attname']]) ? ' checked="checked"' : '', ' /></td>'; echo '<td style="white-space:nowrap;">', $this->misc->printVal($attrs->fields['attname']), '</td>'; echo '<td style="white-space:nowrap;">', $this->misc->printVal($data->formatType($attrs->fields['type'], $attrs->fields['atttypmod'])), '</td>'; echo '<td style="white-space:nowrap;">'; - echo "<select name=\"ops[{$attrs->fields['attname']}]\">".PHP_EOL; - foreach (array_keys($data->selectOps) as $v) { - echo '<option value="', htmlspecialchars($v), '"', ($_REQUEST['ops'][$attrs->fields['attname']] == $v) ? ' selected="selected"' : '', - '>', htmlspecialchars($v), '</option>'.PHP_EOL; + echo "<select name=\"ops[{$attrs->fields['attname']}]\">" . \PHP_EOL; + + foreach (\array_keys($data->selectOps) as $v) { + echo '<option value="', \htmlspecialchars($v), '"', ($_REQUEST['ops'][$attrs->fields['attname']] === $v) ? ' selected="selected"' : '', + '>', \htmlspecialchars($v), '</option>' . \PHP_EOL; } - echo '</select></td>'.PHP_EOL; + echo '</select></td>' . \PHP_EOL; echo '<td style="white-space:nowrap;">', $data->printField( "values[{$attrs->fields['attname']}]", $_REQUEST['values'][$attrs->fields['attname']], $attrs->fields['type'] ), '</td>'; - echo '</tr>'.PHP_EOL; + echo '</tr>' . \PHP_EOL; ++$i; $attrs->moveNext(); } // Select all checkbox echo "<tr><td colspan=\"5\"><input type=\"checkbox\" id=\"selectall\" name=\"selectall\" accesskey=\"a\" onclick=\"javascript:selectAll()\" /><label for=\"selectall\">{$this->lang['strselectallfields']}</label></td></tr>"; - echo '</table>'.PHP_EOL; + echo '</table>' . \PHP_EOL; } else { - echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL; + echo "<p>{$this->lang['strinvalidparam']}</p>" . \PHP_EOL; } - echo '<p><input type="hidden" name="action" value="selectrows" />'.PHP_EOL; - echo '<input type="hidden" name="view" value="', htmlspecialchars($_REQUEST[$this->keystring]), '" />'.PHP_EOL; - echo '<input type="hidden" name="subject" value="view" />'.PHP_EOL; + echo '<p><input type="hidden" name="action" value="selectrows" />' . \PHP_EOL; + echo '<input type="hidden" name="view" value="', \htmlspecialchars($_REQUEST[$this->keystring]), '" />' . \PHP_EOL; + echo '<input type="hidden" name="subject" value="view" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" name=\"select\" accesskey=\"r\" value=\"{$this->lang['strselect']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" name=\"select\" accesskey=\"r\" value=\"{$this->lang['strselect']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; return; } @@ -148,18 +155,18 @@ trait ViewsMatviewsTrait // Verify that they haven't supplied a value for unary operators foreach ($_POST['ops'] as $k => $v) { - if ('p' == $data->selectOps[$v] && $_POST['values'][$k] != '') { + if ('p' === $data->selectOps[$v] && '' !== $_POST['values'][$k]) { $this->doSelectRows(true, $this->lang['strselectunary']); return; } } - if (0 == sizeof($_POST['show'])) { + if (0 === \count($_POST['show'])) { return $this->doSelectRows(true, $this->lang['strselectneedscol']); } // Generate query SQL - $query = $data->getSelectSQL($_REQUEST[$this->keystring], array_keys($_POST['show']), $_POST['values'], $_POST['ops']); + $query = $data->getSelectSQL($_REQUEST[$this->keystring], \array_keys($_POST['show']), $_POST['values'], $_POST['ops']); $_REQUEST['query'] = $query; $_REQUEST['return'] = 'schema'; @@ -174,82 +181,36 @@ trait ViewsMatviewsTrait /** * Prints the form wizard to create view or materialized view. */ - public function printWizardCreateForm() + public function printWizardCreateForm(): void { $data = $this->misc->getDatabaseAccessor(); $tables = $data->getAllTables(); - echo '<form action="'.\SUBFOLDER."/src/views/{$this->script}\" method=\"post\">".PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<form action="' . \SUBFOLDER . "/src/views/{$this->script}\" method=\"post\">" . \PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data\">{$this->lang['strtables']}</th></tr>"; - echo "<tr>\n<td class=\"data1\">".PHP_EOL; + echo "<tr>\n<td class=\"data1\">" . \PHP_EOL; $arrTables = []; + while (!$tables->EOF) { $arrTmp = []; $arrTmp['schemaname'] = $tables->fields['nspname']; $arrTmp['tablename'] = $tables->fields['relname']; - $schema_and_name = $tables->fields['nspname'].'.'.$tables->fields['relname']; - $arrTables[$schema_and_name] = serialize($arrTmp); + $schema_and_name = $tables->fields['nspname'] . '.' . $tables->fields['relname']; + $arrTables[$schema_and_name] = \serialize($arrTmp); $tables->moveNext(); } echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrTables, 'formTables[]', false, '', true); - echo "</td>\n</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="set_params_create" />'.PHP_EOL; + echo "</td>\n</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="set_params_create" />' . \PHP_EOL; echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strnext']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; - } - - /** - * Appends to selected fields. - * - * @param array $arrTmp The arr temporary - * @param string $selFields The selected fields - * @param array $tmpHsh The temporary hsh - */ - private function _appendToSelFields($arrTmp, &$selFields, &$tmpHsh) - { - $field_arr = [$arrTmp['schemaname'], $arrTmp['tablename'], $arrTmp['fieldname']]; - - $field_element = '"'.implode('"."', $field_arr).'"'; - if (empty($_POST['dblFldMeth'])) { - // no doublon control - $selFields .= $field_element.', '; - } elseif (empty($tmpHsh[$arrTmp['fieldname']])) { - // field does not exist - $selFields .= $field_element.', '; - $tmpHsh[$arrTmp['fieldname']] = 1; - } elseif ('rename' == $_POST['dblFldMeth']) { - // field exist and must be renamed - ++$tmpHsh[$arrTmp['fieldname']]; - $selFields .= $field_element.' AS "'.implode('_', $field_arr).'_'.$tmpHsh[$arrTmp['fieldname']].'", '; - } - // if field already exist, just ignore this one - } - - private function _getArrLinks() - { - $arrLinks = []; - $count = 0; - // If we have links, out put the JOIN ... ON statements - if (is_array($_POST['formLink'])) { - // Filter out invalid/blank entries for our links - - foreach ($_POST['formLink'] as $curLink) { - if (strlen($curLink['leftlink']) && strlen($curLink['rightlink']) && strlen($curLink['operator'])) { - $arrLinks[] = $curLink; - } - } - // We must perform some magic to make sure that we have a valid join order - $count = sizeof($arrLinks); - } - - return [$arrLinks, $count]; + echo "<input type=\"submit\" value=\"{$this->lang['strnext']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } /** @@ -265,10 +226,11 @@ trait ViewsMatviewsTrait // Check that they've given a name and fields they want to select - if (!strlen($_POST['formView'])) { + if (!\mb_strlen($_POST['formView'])) { return $this->doSetParamsCreate($this->lang['strviewneedsname']); } - if (!isset($_POST['formFields']) || !count($_POST['formFields'])) { + + if (!isset($_POST['formFields']) || !\count($_POST['formFields'])) { return $this->doSetParamsCreate($this->lang['strviewneedsfields']); } $selFields = ''; @@ -276,13 +238,13 @@ trait ViewsMatviewsTrait $tmpHsh = []; foreach ($_POST['formFields'] as $curField) { - $arrTmp = unserialize($curField); + $arrTmp = \unserialize($curField); $data->fieldArrayClean($arrTmp); $this->_appendToSelFields($arrTmp, $selFields, $tmpHsh); } - $selFields = substr($selFields, 0, -2); + $selFields = \mb_substr($selFields, 0, -2); unset($arrTmp, $tmpHsh); $linkFields = ''; $arrJoined = []; @@ -296,32 +258,33 @@ trait ViewsMatviewsTrait while ($j < $count) { foreach ($arrLinks as $curLink) { - $arrLeftLink = unserialize($curLink['leftlink']); - $arrRightLink = unserialize($curLink['rightlink']); + $arrLeftLink = \unserialize($curLink['leftlink']); + $arrRightLink = \unserialize($curLink['rightlink']); $data->fieldArrayClean($arrLeftLink); $data->fieldArrayClean($arrRightLink); $tbl1 = "\"{$arrLeftLink['schemaname']}\".\"{$arrLeftLink['tablename']}\""; $tbl2 = "\"{$arrRightLink['schemaname']}\".\"{$arrRightLink['tablename']}\""; - if (!((!in_array($curLink, $arrJoined, true) && in_array($tbl1, $arrUsedTbls, true)) || !count($arrJoined))) { + if (!((!\in_array($curLink, $arrJoined, true) && \in_array($tbl1, $arrUsedTbls, true)) || !\count($arrJoined))) { continue; } // Make sure for multi-column foreign keys that we use a table alias tables joined to more than once // This can (and should be) more optimized for multi-column foreign keys - $adj_tbl2 = in_array($tbl2, $arrUsedTbls, true) ? "${tbl2} AS alias_ppa_".time() : $tbl2; + $adj_tbl2 = \in_array($tbl2, $arrUsedTbls, true) ? "{$tbl2} AS alias_ppa_" . \time() : $tbl2; - $clause1 = "{$curLink['operator']} ${adj_tbl2} ON ({$tbl1}.\"{$arrLeftLink['fieldname']}\" = {$tbl2}.\"{$arrRightLink['fieldname']}\") "; - $clause2 = "${tbl1} {$curLink['operator']} ${adj_tbl2} ON ({$tbl1}.\"{$arrLeftLink['fieldname']}\" = {$tbl2}.\"{$arrRightLink['fieldname']}\") "; + $clause1 = "{$curLink['operator']} {$adj_tbl2} ON ({$tbl1}.\"{$arrLeftLink['fieldname']}\" = {$tbl2}.\"{$arrRightLink['fieldname']}\") "; + $clause2 = "{$tbl1} {$curLink['operator']} {$adj_tbl2} ON ({$tbl1}.\"{$arrLeftLink['fieldname']}\" = {$tbl2}.\"{$arrRightLink['fieldname']}\") "; - $linkFields .= strlen($linkFields) ? $clause1 : $clause2; + $linkFields .= \mb_strlen($linkFields) ? $clause1 : $clause2; $arrJoined[] = $curLink; - if (!in_array($tbl1, $arrUsedTbls, true)) { + + if (!\in_array($tbl1, $arrUsedTbls, true)) { $arrUsedTbls[] = $tbl1; } - if (!in_array($tbl2, $arrUsedTbls, true)) { + if (!\in_array($tbl2, $arrUsedTbls, true)) { $arrUsedTbls[] = $tbl2; } } @@ -330,36 +293,38 @@ trait ViewsMatviewsTrait //if linkFields has no length then either _POST['formLink'] was not set, or there were no join conditions //just select from all seleted tables - a cartesian join do a - if (!strlen($linkFields)) { + if (!\mb_strlen($linkFields)) { foreach ($_POST['formTables'] as $curTable) { - $arrTmp = unserialize($curTable); + $arrTmp = \unserialize($curTable); $data->fieldArrayClean($arrTmp); - $linkFields .= (strlen($linkFields) ? ', ' : ' ')."\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\""; + $linkFields .= (\mb_strlen($linkFields) ? ', ' : ' ') . "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\""; } } $addConditions = ''; - if (is_array($_POST['formCondition'])) { + + if (\is_array($_POST['formCondition'])) { foreach ($_POST['formCondition'] as $curCondition) { - if (strlen($curCondition['field']) && strlen($curCondition['txt'])) { - $arrTmp = unserialize($curCondition['field']); + if (\mb_strlen($curCondition['field']) && \mb_strlen($curCondition['txt'])) { + $arrTmp = \unserialize($curCondition['field']); $data->fieldArrayClean($arrTmp); $condition = " \"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\" {$curCondition['operator']} '{$curCondition['txt']}' "; - $addConditions .= (strlen($addConditions) ? ' AND ' : ' ').$condition; + $addConditions .= (\mb_strlen($addConditions) ? ' AND ' : ' ') . $condition; } } } - $viewQuery = "SELECT ${selFields} FROM ${linkFields} "; + $viewQuery = "SELECT {$selFields} FROM {$linkFields} "; //add where from additional conditions - if (strlen($addConditions)) { - $viewQuery .= ' WHERE '.$addConditions; + if (\mb_strlen($addConditions)) { + $viewQuery .= ' WHERE ' . $addConditions; } try { $status = $data->createView($_POST['formView'], $viewQuery, false, $_POST['formComment'], $is_materialized); - if (0 == $status) { + + if (0 === $status) { $this->misc->setReloadBrowser(true); return $this->doDefault($this->lang['strviewcreated']); @@ -371,15 +336,15 @@ trait ViewsMatviewsTrait } } - public function printParamsCreateForm() + public function printParamsCreateForm(): void { $data = $this->misc->getDatabaseAccessor(); - $tblCount = sizeof($_POST['formTables']); + $tblCount = \count($_POST['formTables']); $arrSelTables = []; //unserialize our schema/table information and store in arrSelTables for ($i = 0; $i < $tblCount; ++$i) { - $arrSelTables[] = unserialize($_POST['formTables'][$i]); + $arrSelTables[] = \unserialize($_POST['formTables'][$i]); } //get linking keys @@ -391,113 +356,166 @@ trait ViewsMatviewsTrait //if we have schemas we need to specify the correct schema for each table we're retrieiving //with getTableAttributes $curSchema = $data->_schema; + for ($i = 0; $i < $tblCount; ++$i) { - if ($arrSelTables[$i]['schemaname'] != $data->_schema) { + if ($arrSelTables[$i]['schemaname'] !== $data->_schema) { $data->setSchema($arrSelTables[$i]['schemaname']); } $attrs = $data->getTableAttributes($arrSelTables[$i]['tablename']); + while (!$attrs->EOF) { - $arrFields["{$arrSelTables[$i]['schemaname']}.{$arrSelTables[$i]['tablename']}.{$attrs->fields['attname']}"] = serialize( + $arrFields["{$arrSelTables[$i]['schemaname']}.{$arrSelTables[$i]['tablename']}.{$attrs->fields['attname']}"] = \serialize( [ 'schemaname' => $arrSelTables[$i]['schemaname'], 'tablename' => $arrSelTables[$i]['tablename'], - 'fieldname' => $attrs->fields['attname'], ] + 'fieldname' => $attrs->fields['attname']] ); $attrs->moveNext(); } $data->setSchema($curSchema); } - asort($arrFields); + \asort($arrFields); - echo '<form action="'.\SUBFOLDER.'/src/views/materializedviews" method="post">'.PHP_EOL; - echo '<table>'.PHP_EOL; + echo '<form action="' . \SUBFOLDER . '/src/views/materializedviews" method="post">' . \PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data\">{$this->lang['strviewname']}</th></tr>"; - echo "<tr>\n<td class=\"data1\">".PHP_EOL; + echo "<tr>\n<td class=\"data1\">" . \PHP_EOL; // View name - echo '<input name="formView" value="'.htmlspecialchars($_REQUEST['formView'])."\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" />".PHP_EOL; - echo "</td>\n</tr>".PHP_EOL; + echo '<input name="formView" value="' . \htmlspecialchars($_REQUEST['formView']) . "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" />" . \PHP_EOL; + echo "</td>\n</tr>" . \PHP_EOL; echo "<tr><th class=\"data\">{$this->lang['strcomment']}</th></tr>"; - echo "<tr>\n<td class=\"data1\">".PHP_EOL; + echo "<tr>\n<td class=\"data1\">" . \PHP_EOL; // View comments - echo '<textarea name="formComment" rows="3" cols="32">'.htmlspecialchars($_REQUEST['formComment']).'</textarea>'.PHP_EOL; - echo "</td>\n</tr>".PHP_EOL; - echo '</table>'.PHP_EOL; + echo '<textarea name="formComment" rows="3" cols="32">' . \htmlspecialchars($_REQUEST['formComment']) . '</textarea>' . \PHP_EOL; + echo "</td>\n</tr>" . \PHP_EOL; + echo '</table>' . \PHP_EOL; // Output selector for fields to be retrieved from view - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data\">{$this->lang['strcolumns']}</th></tr>"; - echo "<tr>\n<td class=\"data1\">".PHP_EOL; + echo "<tr>\n<td class=\"data1\">" . \PHP_EOL; echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, 'formFields[]', false, '', true); echo "</td>\n</tr>"; echo '<tr><td>'; - echo sprintf('<input type="radio" name="dblFldMeth" id="dblFldMeth1" value="rename" /><label for="dblFldMeth1">%s</label><br>', $this->lang['strrenamedupfields']); - echo sprintf('<input type="radio" name="dblFldMeth" id="dblFldMeth2" value="drop" /><label for="dblFldMeth2">%s</label><br>', $this->lang['strdropdupfields']); - echo sprintf('<input type="radio" name="dblFldMeth" id="dblFldMeth3" value="" checked="checked" /><label for="dblFldMeth3">%s</label>', $this->lang['strerrordupfields']); + echo \sprintf('<input type="radio" name="dblFldMeth" id="dblFldMeth1" value="rename" /><label for="dblFldMeth1">%s</label><br>', $this->lang['strrenamedupfields']); + echo \sprintf('<input type="radio" name="dblFldMeth" id="dblFldMeth2" value="drop" /><label for="dblFldMeth2">%s</label><br>', $this->lang['strdropdupfields']); + echo \sprintf('<input type="radio" name="dblFldMeth" id="dblFldMeth3" value="" checked="checked" /><label for="dblFldMeth3">%s</label>', $this->lang['strerrordupfields']); echo '</td></tr></table><br />'; // Output the Linking keys combo boxes - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data\">{$this->lang['strviewlink']}</th></tr>"; $rowClass = 'data1'; $formLink = []; + for ($i = 0; $i < $linkCount; ++$i) { // Initialise variables $this->coalesceArr($formLink[$i], 'operator', 'INNER JOIN'); - echo "<tr>\n<td class=\"{$rowClass}\">".PHP_EOL; + echo "<tr>\n<td class=\"{$rowClass}\">" . \PHP_EOL; if (!$rsLinkKeys->EOF) { - $curLeftLink = htmlspecialchars(serialize(['schemaname' => $rsLinkKeys->fields['p_schema'], 'tablename' => $rsLinkKeys->fields['p_table'], 'fieldname' => $rsLinkKeys->fields['p_field']])); - $curRightLink = htmlspecialchars(serialize(['schemaname' => $rsLinkKeys->fields['f_schema'], 'tablename' => $rsLinkKeys->fields['f_table'], 'fieldname' => $rsLinkKeys->fields['f_field']])); + $curLeftLink = \htmlspecialchars(\serialize(['schemaname' => $rsLinkKeys->fields['p_schema'], 'tablename' => $rsLinkKeys->fields['p_table'], 'fieldname' => $rsLinkKeys->fields['p_field']])); + $curRightLink = \htmlspecialchars(\serialize(['schemaname' => $rsLinkKeys->fields['f_schema'], 'tablename' => $rsLinkKeys->fields['f_table'], 'fieldname' => $rsLinkKeys->fields['f_field']])); $rsLinkKeys->moveNext(); } else { $curLeftLink = ''; $curRightLink = ''; } - echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formLink[${i}][leftlink]", true, $curLeftLink, false); - echo \PHPPgAdmin\XHtml\HTMLController::printCombo($data->joinOps, "formLink[${i}][operator]", true, $formLink[$i]['operator']); - echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formLink[${i}][rightlink]", true, $curRightLink, false); - echo "</td>\n</tr>".PHP_EOL; - $rowClass = 'data1' == $rowClass ? 'data2' : 'data1'; + echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formLink[{$i}][leftlink]", true, $curLeftLink, false); + echo \PHPPgAdmin\XHtml\HTMLController::printCombo($data->joinOps, "formLink[{$i}][operator]", true, $formLink[$i]['operator']); + echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formLink[{$i}][rightlink]", true, $curRightLink, false); + echo "</td>\n</tr>" . \PHP_EOL; + $rowClass = 'data1' === $rowClass ? 'data2' : 'data1'; } - echo "</table>\n<br />".PHP_EOL; + echo "</table>\n<br />" . \PHP_EOL; // Build list of available operators (infix only) $arrOperators = []; + foreach ($data->selectOps as $k => $v) { - if ('i' == $v) { + if ('i' === $v) { $arrOperators[$k] = $k; } } // Output additional conditions, note that this portion of the wizard treats the right hand side as literal values //(not as database objects) so field names will be treated as strings, use the above linking keys section to perform joins - echo '<table>'.PHP_EOL; + echo '<table>' . \PHP_EOL; echo "<tr><th class=\"data\">{$this->lang['strviewconditions']}</th></tr>"; $rowClass = 'data1'; + for ($i = 0; $i < $linkCount; ++$i) { - echo "<tr>\n<td class=\"${rowClass}\">".PHP_EOL; - echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formCondition[${i}][field]"); - echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrOperators, "formCondition[${i}][operator]", false, '', false); - echo "<input type=\"text\" name=\"formCondition[${i}][txt]\" />".PHP_EOL; - echo "</td>\n</tr>".PHP_EOL; - $rowClass = 'data1' == $rowClass ? 'data2' : 'data1'; + echo "<tr>\n<td class=\"{$rowClass}\">" . \PHP_EOL; + echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formCondition[{$i}][field]"); + echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrOperators, "formCondition[{$i}][operator]", false, '', false); + echo "<input type=\"text\" name=\"formCondition[{$i}][txt]\" />" . \PHP_EOL; + echo "</td>\n</tr>" . \PHP_EOL; + $rowClass = 'data1' === $rowClass ? 'data2' : 'data1'; } - echo '</table>'.PHP_EOL; - echo '<p><input type="hidden" name="action" value="save_create_wiz" />'.PHP_EOL; + echo '</table>' . \PHP_EOL; + echo '<p><input type="hidden" name="action" value="save_create_wiz" />' . \PHP_EOL; foreach ($arrSelTables as $curTable) { - echo '<input type="hidden" name="formTables[]" value="'.htmlspecialchars(serialize($curTable)).'" />'.PHP_EOL; + echo '<input type="hidden" name="formTables[]" value="' . \htmlspecialchars(\serialize($curTable)) . '" />' . \PHP_EOL; } echo $this->misc->form; - echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />".PHP_EOL; - echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL; - echo '</form>'.PHP_EOL; + echo "<input type=\"submit\" value=\"{$this->lang['strcreate']}\" />" . \PHP_EOL; + echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>" . \PHP_EOL; + echo '</form>' . \PHP_EOL; } abstract public function doSetParamsCreate($msg = ''); + + /** + * Appends to selected fields. + * + * @param array $arrTmp The arr temporary + * @param string $selFields The selected fields + * @param array $tmpHsh The temporary hsh + */ + private function _appendToSelFields($arrTmp, &$selFields, &$tmpHsh): void + { + $field_arr = [$arrTmp['schemaname'], $arrTmp['tablename'], $arrTmp['fieldname']]; + + $field_element = '"' . \implode('"."', $field_arr) . '"'; + + if (empty($_POST['dblFldMeth'])) { + // no doublon control + $selFields .= $field_element . ', '; + } elseif (empty($tmpHsh[$arrTmp['fieldname']])) { + // field does not exist + $selFields .= $field_element . ', '; + $tmpHsh[$arrTmp['fieldname']] = 1; + } elseif ('rename' === $_POST['dblFldMeth']) { + // field exist and must be renamed + ++$tmpHsh[$arrTmp['fieldname']]; + $selFields .= $field_element . ' AS "' . \implode('_', $field_arr) . '_' . $tmpHsh[$arrTmp['fieldname']] . '", '; + } + // if field already exist, just ignore this one + } + + private function _getArrLinks() + { + $arrLinks = []; + $count = 0; + // If we have links, out put the JOIN ... ON statements + if (\is_array($_POST['formLink'])) { + // Filter out invalid/blank entries for our links + + foreach ($_POST['formLink'] as $curLink) { + if (\mb_strlen($curLink['leftlink']) && \mb_strlen($curLink['rightlink']) && \mb_strlen($curLink['operator'])) { + $arrLinks[] = $curLink; + } + } + // We must perform some magic to make sure that we have a valid join order + $count = \count($arrLinks); + } + + return [$arrLinks, $count]; + } } diff --git a/src/translations/Afrikaans.php b/src/translations/Afrikaans.php index 4f4a8f25..703cf464 100644 --- a/src/translations/Afrikaans.php +++ b/src/translations/Afrikaans.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Afrikaans language. - * - * @package PHPPgAdmin */ class Afrikaans extends English { diff --git a/src/translations/Arabic.php b/src/translations/Arabic.php index feb47502..f2900171 100644 --- a/src/translations/Arabic.php +++ b/src/translations/Arabic.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Arabic language. - * - * @package PHPPgAdmin */ class Arabic extends English { diff --git a/src/translations/Catalan.php b/src/translations/Catalan.php index b65df235..7540fed1 100644 --- a/src/translations/Catalan.php +++ b/src/translations/Catalan.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Catalan language. - * - * @package PHPPgAdmin */ class Catalan extends English { diff --git a/src/translations/ChineseSim.php b/src/translations/ChineseSim.php index c98568db..9b49fe56 100644 --- a/src/translations/ChineseSim.php +++ b/src/translations/ChineseSim.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for ChineseSim language. - * - * @package PHPPgAdmin */ class ChineseSim extends English { diff --git a/src/translations/ChineseTr.php b/src/translations/ChineseTr.php index 158552d3..2694381f 100644 --- a/src/translations/ChineseTr.php +++ b/src/translations/ChineseTr.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for ChineseTr language. - * - * @package PHPPgAdmin */ class ChineseTr extends English { diff --git a/src/translations/ChineseUtf8ZhCn.php b/src/translations/ChineseUtf8ZhCn.php index 22190407..420ac208 100644 --- a/src/translations/ChineseUtf8ZhCn.php +++ b/src/translations/ChineseUtf8ZhCn.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for ChineseUtf8ZhCn language. - * - * @package PHPPgAdmin */ class ChineseUtf8ZhCn extends English { diff --git a/src/translations/ChineseUtf8ZhTw.php b/src/translations/ChineseUtf8ZhTw.php index c5bb3291..5805adf0 100644 --- a/src/translations/ChineseUtf8ZhTw.php +++ b/src/translations/ChineseUtf8ZhTw.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for ChineseUtf8ZhTw language. - * - * @package PHPPgAdmin */ class ChineseUtf8ZhTw extends English { diff --git a/src/translations/Czech.php b/src/translations/Czech.php index 25254785..20d380ab 100644 --- a/src/translations/Czech.php +++ b/src/translations/Czech.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Czech language. - * - * @package PHPPgAdmin */ class Czech extends English { diff --git a/src/translations/Danish.php b/src/translations/Danish.php index dfd7d26b..d0fcb856 100644 --- a/src/translations/Danish.php +++ b/src/translations/Danish.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Danish language. - * - * @package PHPPgAdmin */ class Danish extends English { diff --git a/src/translations/Dutch.php b/src/translations/Dutch.php index de7af4ac..b2282a5c 100644 --- a/src/translations/Dutch.php +++ b/src/translations/Dutch.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Dutch language. - * - * @package PHPPgAdmin */ class Dutch extends English { diff --git a/src/translations/English.php b/src/translations/English.php index a2595c49..3c80278b 100644 --- a/src/translations/English.php +++ b/src/translations/English.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Ukrainian language. - * - * @package PHPPgAdmin */ class English { @@ -880,8 +881,6 @@ class English public function getLang() { - $lang = $this->lang; - - return $lang; + return $this->lang; } } diff --git a/src/translations/French.php b/src/translations/French.php index b0fefded..f5aeaee6 100644 --- a/src/translations/French.php +++ b/src/translations/French.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for French language. - * - * @package PHPPgAdmin */ class French extends English { diff --git a/src/translations/Galician.php b/src/translations/Galician.php index d4e4f601..a0b4b6ad 100644 --- a/src/translations/Galician.php +++ b/src/translations/Galician.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Galician language. - * - * @package PHPPgAdmin */ class Galician extends English { diff --git a/src/translations/German.php b/src/translations/German.php index d7e4eaa0..892a0d6e 100644 --- a/src/translations/German.php +++ b/src/translations/German.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for German language. - * - * @package PHPPgAdmin */ class German extends English { diff --git a/src/translations/Greek.php b/src/translations/Greek.php index b8d32047..dd58c2a3 100644 --- a/src/translations/Greek.php +++ b/src/translations/Greek.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Greek language. - * - * @package PHPPgAdmin */ class Greek extends English { diff --git a/src/translations/Hebrew.php b/src/translations/Hebrew.php index 3b5e6c3e..dedb3d50 100644 --- a/src/translations/Hebrew.php +++ b/src/translations/Hebrew.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Hebrew language. - * - * @package PHPPgAdmin */ class Hebrew extends English { diff --git a/src/translations/Hungarian.php b/src/translations/Hungarian.php index 3787f2ff..3df971aa 100644 --- a/src/translations/Hungarian.php +++ b/src/translations/Hungarian.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Hungarian language. - * - * @package PHPPgAdmin */ class Hungarian extends English { diff --git a/src/translations/Italian.php b/src/translations/Italian.php index 2199365e..024d0683 100644 --- a/src/translations/Italian.php +++ b/src/translations/Italian.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Italian language. - * - * @package PHPPgAdmin */ class Italian extends English { diff --git a/src/translations/Japanese.php b/src/translations/Japanese.php index e74c7321..5c132067 100644 --- a/src/translations/Japanese.php +++ b/src/translations/Japanese.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Japanese language. - * - * @package PHPPgAdmin */ class Japanese extends English { diff --git a/src/translations/Lithuanian.php b/src/translations/Lithuanian.php index 3ac2f5c7..7c3bcaf0 100644 --- a/src/translations/Lithuanian.php +++ b/src/translations/Lithuanian.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Lithuanian language. - * - * @package PHPPgAdmin */ class Lithuanian extends English { diff --git a/src/translations/Mongol.php b/src/translations/Mongol.php index a3ce6c1c..b466b6d0 100644 --- a/src/translations/Mongol.php +++ b/src/translations/Mongol.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Mongol language. - * - * @package PHPPgAdmin */ class Mongol extends English { diff --git a/src/translations/Polish.php b/src/translations/Polish.php index 98270656..9438c82d 100644 --- a/src/translations/Polish.php +++ b/src/translations/Polish.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Polish language. - * - * @package PHPPgAdmin */ class Polish extends English { diff --git a/src/translations/PortugueseBr.php b/src/translations/PortugueseBr.php index 271c3c92..1be9ea7f 100644 --- a/src/translations/PortugueseBr.php +++ b/src/translations/PortugueseBr.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for PortugueseBr language. - * - * @package PHPPgAdmin */ class PortugueseBr extends English { diff --git a/src/translations/PortuguesePt.php b/src/translations/PortuguesePt.php index f5ae4e01..47dff8e6 100644 --- a/src/translations/PortuguesePt.php +++ b/src/translations/PortuguesePt.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for PortuguesePt language. - * - * @package PHPPgAdmin */ class PortuguesePt extends English { diff --git a/src/translations/Romanian.php b/src/translations/Romanian.php index bfe2ade5..ff1ab232 100644 --- a/src/translations/Romanian.php +++ b/src/translations/Romanian.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Romanian language. - * - * @package PHPPgAdmin */ class Romanian extends English { diff --git a/src/translations/Russian.php b/src/translations/Russian.php index 82616515..461c4013 100644 --- a/src/translations/Russian.php +++ b/src/translations/Russian.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Russian language. - * - * @package PHPPgAdmin */ class Russian extends English { diff --git a/src/translations/RussianUtf8.php b/src/translations/RussianUtf8.php index 5322dd9a..820d058d 100644 --- a/src/translations/RussianUtf8.php +++ b/src/translations/RussianUtf8.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for RussianUtf8 language. - * - * @package PHPPgAdmin */ class RussianUtf8 extends English { diff --git a/src/translations/Slovak.php b/src/translations/Slovak.php index 34e857cd..996e9a6e 100644 --- a/src/translations/Slovak.php +++ b/src/translations/Slovak.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Slovak language. - * - * @package PHPPgAdmin */ class Slovak extends English { diff --git a/src/translations/Spanish.php b/src/translations/Spanish.php index 36172f67..6833ed43 100644 --- a/src/translations/Spanish.php +++ b/src/translations/Spanish.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Spanish language. - * - * @package PHPPgAdmin */ class Spanish extends English { diff --git a/src/translations/Swedish.php b/src/translations/Swedish.php index c492ff54..830eb553 100644 --- a/src/translations/Swedish.php +++ b/src/translations/Swedish.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Swedish language. - * - * @package PHPPgAdmin */ class Swedish extends English { diff --git a/src/translations/Turkish.php b/src/translations/Turkish.php index b499472a..064c2223 100644 --- a/src/translations/Turkish.php +++ b/src/translations/Turkish.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Turkish language. - * - * @package PHPPgAdmin */ class Turkish extends English { diff --git a/src/translations/Ukrainian.php b/src/translations/Ukrainian.php index e1e90c59..c7b214b5 100644 --- a/src/translations/Ukrainian.php +++ b/src/translations/Ukrainian.php @@ -1,15 +1,16 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\Translations; /** * Class providing translation for Ukrainian language. - * - * @package PHPPgAdmin */ class Ukrainian extends English { diff --git a/src/xhtml/HTMLController.php b/src/xhtml/HTMLController.php index 010bc34a..ae751e01 100644 --- a/src/xhtml/HTMLController.php +++ b/src/xhtml/HTMLController.php @@ -1,28 +1,70 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; use PHPPgAdmin\Decorators\Decorator; +\defined('BASE_PATH') || \define('BASE_PATH', \dirname(__DIR__, 2)); +\defined('SUBFOLDER') || \define( + 'SUBFOLDER', + \str_replace($_SERVER['DOCUMENT_ROOT'] ?? '', '', BASE_PATH) +); +\defined('DEBUGMODE') || \define('DEBUGMODE', false); + /** * Base HTMLController controller class. */ class HTMLController { use \PHPPgAdmin\Traits\HelperTrait; + /** + * @var string + */ + const BASE_PATH = BASE_PATH; + /** + * @var string + */ + const SUBFOLDER = SUBFOLDER; + /** + * @var string + */ + const DEBUGMODE = DEBUGMODE; + + public $form = ''; + + public $href = ''; + + public $lang = []; + + public $action = ''; + + public $controller_name = 'HTMLController'; - protected $container; - public $form = ''; - public $href = ''; - public $lang = []; - public $action = ''; - public $controller_name = 'HTMLController'; public $controller_title = 'html'; + public $view; + + public $appName; + + public $appVersion; + + public $appLangFiles; + + public $misc; + + public $conf; + + public $appThemes; + + protected $container; + // Constructor public function __construct(\Slim\Container $container, $controller_name = null) { @@ -49,6 +91,89 @@ class HTMLController } /** + * Display a link. + * + * @param array $link An associative array of link parameters to print + * link = array( + * 'attr' => array( // list of A tag attribute + * 'attrname' => attribute value + * ... + * ), + * 'content' => The link text + * 'fields' => (optionnal) the data from which content and attr's values are obtained + * ); + * the special attribute 'href' might be a string or an array. If href is an array it + * will be generated by getActionUrl. See getActionUrl comment for array format. + * @param mixed $do_print + * @param null|mixed $from + */ + public function printLink($link, $do_print = true, $from = null) + { + if (!isset($link['fields'])) { + $link['fields'] = $_REQUEST; + } + $from = $from ? $from : __METHOD__; + $tag = '<a '; + + foreach ($link['attr'] as $attr => $value) { + if ('href' === $attr && \is_array($value)) { + $tag .= 'href="' . \htmlentities($this->getActionUrl($value, $link['fields'], $from)) . '" '; + } else { + $tag .= \htmlentities($attr) . '="' . Decorator::get_sanitized_value($value, $link['fields'], 'html') . '" '; + } + } + $tag .= '>' . Decorator::get_sanitized_value($link['content'], $link['fields'], 'html') . '</a>' . \PHP_EOL; + + if ($do_print) { + echo $tag; + } else { + return $tag; + } + } + + /** + * Prints a combox box. + * + * @param array $arrOptions associative array storing options and values of combo should be Option => Value + * @param string $szName string to specify the name of the form element + * @param bool $bBlankEntry either to insert a blank option at the beggining of the combo + * @param string $szDefault the current selected value + * @param bool $bMultiple enable multible selection + * @param int $iSize combobox size + * + * @return string with the generated HTML select box + * + * @internal param $ (optional) $bBlankEntry bool to specify whether or not we want a blank selection + * @internal param $ (optional) $szDefault string to specify the default VALUE selected + * @internal param $ (optional) $bMultiple bool to specify whether or not we want a multi select combo box + * @internal param $ (optional) $iSize int to specify the size IF a multi select combo + */ + public static function printCombo(&$arrOptions, $szName, $bBlankEntry = true, $szDefault = '', $bMultiple = false, $iSize = 10) + { + $htmlOut = ''; + + if ($bMultiple) { + // If multiple select combo + $htmlOut .= "<select rel=\"printCombo\" name=\"{$szName}\" id=\"{$szName}\" multiple=\"multiple\" size=\"{$iSize}\">" . \PHP_EOL; + } else { + $htmlOut .= "<select rel=\"printCombo\" name=\"{$szName}\" id=\"{$szName}\" class=\"select2\" >" . \PHP_EOL; + } + + if ($bBlankEntry) { + $htmlOut .= '<option value=""></option>' . \PHP_EOL; + } + + foreach ($arrOptions as $curKey => $curVal) { + $curVal = \htmlspecialchars($curVal); + $curKey = \htmlspecialchars($curKey); + $htmlOut .= \sprintf('<option value="%s" %s >%s</option>%s', $curVal, ($curVal === $szDefault) ? 'selected="selected"' : '', $curKey, \PHP_EOL); + } + $htmlOut .= '</select>' . \PHP_EOL; + + return $htmlOut; + } + + /** * Returns URL given an action associative array. * NOTE: this function does not html-escape, only url-escape. * @@ -94,11 +219,13 @@ class HTMLController //$this->prtrace('server', $server, 'database', $database, 'schema', $schema); - if ($server && !isset($urlvars['server']) && 'root' != $subject) { + if ($server && !isset($urlvars['server']) && 'root' !== $subject) { $urlvars['server'] = $server; - if ($database && !isset($urlvars['database']) && 'server' != $subject) { + + if ($database && !isset($urlvars['database']) && 'server' !== $subject) { $urlvars['database'] = $database; - if ($schema && !isset($urlvars['schema']) && 'database' != $subject) { + + if ($schema && !isset($urlvars['schema']) && 'database' !== $subject) { $urlvars['schema'] = $schema; } } @@ -106,9 +233,10 @@ class HTMLController $sep = '?'; - ksort($urlvars); + \ksort($urlvars); + foreach ($urlvars as $var => $varfield) { - $url .= $sep.Decorator::value_url($var, $fields).'='.Decorator::value_url($varfield, $fields); + $url .= $sep . Decorator::value_url($var, $fields) . '=' . Decorator::value_url($varfield, $fields); $sep = '&'; } @@ -116,46 +244,6 @@ class HTMLController } /** - * Display a link. - * - * @param array $link An associative array of link parameters to print - * link = array( - * 'attr' => array( // list of A tag attribute - * 'attrname' => attribute value - * ... - * ), - * 'content' => The link text - * 'fields' => (optionnal) the data from which content and attr's values are obtained - * ); - * the special attribute 'href' might be a string or an array. If href is an array it - * will be generated by getActionUrl. See getActionUrl comment for array format. - * @param mixed $do_print - * @param null|mixed $from - */ - public function printLink($link, $do_print = true, $from = null) - { - if (!isset($link['fields'])) { - $link['fields'] = $_REQUEST; - } - $from = $from ? $from : __METHOD__; - $tag = '<a '; - foreach ($link['attr'] as $attr => $value) { - if ('href' == $attr and is_array($value)) { - $tag .= 'href="'.htmlentities($this->getActionUrl($value, $link['fields'], $from)).'" '; - } else { - $tag .= htmlentities($attr).'="'.Decorator::get_sanitized_value($value, $link['fields'], 'html').'" '; - } - } - $tag .= '>'.Decorator::get_sanitized_value($link['content'], $link['fields'], 'html').'</a>'.PHP_EOL; - - if ($do_print) { - echo $tag; - } else { - return $tag; - } - } - - /** * Display a list of links. * * @param array $links An associative array of links to print. See printLink function for @@ -170,62 +258,23 @@ class HTMLController if (null === $from || false === $from) { $from = __METHOD__; } - $list_html = "<ul class=\"{$class}\">".PHP_EOL; + $list_html = "<ul class=\"{$class}\">" . \PHP_EOL; + foreach ($links as $link) { - if ($from === 'PHPPgAdmin\Controller\BaseController::printNavLinks') { + if ('PHPPgAdmin\Controller\BaseController::printNavLinks' === $from) { //$this->prtrace($link); } $list_html .= "\t<li>"; - $list_html .= str_replace('.php', '', $this->printLink($link, false, $from)); - $list_html .= '</li>'.PHP_EOL; + $list_html .= \str_replace('.php', '', $this->printLink($link, false, $from)); + $list_html .= '</li>' . \PHP_EOL; } - $list_html .= '</ul>'.PHP_EOL; + $list_html .= '</ul>' . \PHP_EOL; + if ($do_print) { echo $list_html; } else { return $list_html; } } - - /** - * Prints a combox box. - * - * @param array $arrOptions associative array storing options and values of combo should be Option => Value - * @param string $szName string to specify the name of the form element - * @param bool $bBlankEntry either to insert a blank option at the beggining of the combo - * @param string $szDefault the current selected value - * @param bool $bMultiple enable multible selection - * @param int $iSize combobox size - * - * @return string with the generated HTML select box - * - * @internal param $ (optional) $bBlankEntry bool to specify whether or not we want a blank selection - * @internal param $ (optional) $szDefault string to specify the default VALUE selected - * @internal param $ (optional) $bMultiple bool to specify whether or not we want a multi select combo box - * @internal param $ (optional) $iSize int to specify the size IF a multi select combo - */ - public static function printCombo(&$arrOptions, $szName, $bBlankEntry = true, $szDefault = '', $bMultiple = false, $iSize = 10) - { - $htmlOut = ''; - if ($bMultiple) { - // If multiple select combo - $htmlOut .= "<select rel=\"printCombo\" name=\"${szName}\" id=\"${szName}\" multiple=\"multiple\" size=\"${iSize}\">".PHP_EOL; - } else { - $htmlOut .= "<select rel=\"printCombo\" name=\"${szName}\" id=\"${szName}\" class=\"select2\" >".PHP_EOL; - } - - if ($bBlankEntry) { - $htmlOut .= '<option value=""></option>'.PHP_EOL; - } - - foreach ($arrOptions as $curKey => $curVal) { - $curVal = htmlspecialchars($curVal); - $curKey = htmlspecialchars($curKey); - $htmlOut .= sprintf('<option value="%s" %s >%s</option>%s', $curVal, ($curVal == $szDefault) ? 'selected="selected"' : '', $curKey, PHP_EOL); - } - $htmlOut .= '</select>'.PHP_EOL; - - return $htmlOut; - } } diff --git a/src/xhtml/HTMLFooterController.php b/src/xhtml/HTMLFooterController.php index a823b310..f1a1dd3f 100644 --- a/src/xhtml/HTMLFooterController.php +++ b/src/xhtml/HTMLFooterController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; @@ -11,9 +14,11 @@ namespace PHPPgAdmin\XHtml; */ class HTMLFooterController extends HTMLController { - public $controller_name = 'HTMLFooterController'; + public $controller_name = 'HTMLFooterController'; + private $_reload_drop_database = false; - private $_no_bottom_link = false; + + private $_no_bottom_link = false; /** * Sets the value of $_reload_drop_database which in turn will trigger a reload in the browser frame. @@ -52,6 +57,7 @@ class HTMLFooterController extends HTMLController public function printFooter($doBody = true, $template = 'footer.twig') { $reload_param = 'none'; + if ($this->misc->getReloadBrowser()) { $reload_param = 'other'; } elseif ($this->_reload_drop_database) { @@ -77,11 +83,11 @@ class HTMLFooterController extends HTMLController * * @param string $object eg. forms[0].username */ - public function setFocus($object) + public function setFocus($object): void { - echo '<script type="text/javascript">'.PHP_EOL; + echo '<script type="text/javascript">' . \PHP_EOL; echo " document.{$object}.focus();\n"; - echo '</script>'.PHP_EOL; + echo '</script>' . \PHP_EOL; } /** @@ -91,13 +97,13 @@ class HTMLFooterController extends HTMLController * @param bool $addServer if true (default) then the server id is * attached to the name */ - public function setWindowName($name, $addServer = true) + public function setWindowName($name, $addServer = true): void { - echo '<script type="text/javascript">'.PHP_EOL; + echo '<script type="text/javascript">' . \PHP_EOL; echo "//<![CDATA[\n"; - echo " window.name = '{$name}", ($addServer ? ':'.htmlspecialchars($this->misc->getServerId()) : ''), "';\n"; - echo '//]]>'.PHP_EOL; - echo '</script>'.PHP_EOL; + echo " window.name = '{$name}", ($addServer ? ':' . \htmlspecialchars($this->misc->getServerId()) : ''), "';\n"; + echo '//]]>' . \PHP_EOL; + echo '</script>' . \PHP_EOL; } /** @@ -127,7 +133,7 @@ class HTMLFooterController extends HTMLController 'env' => $env, ]; - if (count($navlinks) > 0) { + if (0 < \count($navlinks)) { if ($do_print) { $this->printLinksList($navlinks, 'navlink', true, $from); } else { diff --git a/src/xhtml/HTMLHeaderController.php b/src/xhtml/HTMLHeaderController.php index 73cb6d17..7a8d1979 100644 --- a/src/xhtml/HTMLHeaderController.php +++ b/src/xhtml/HTMLHeaderController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; @@ -12,7 +15,8 @@ namespace PHPPgAdmin\XHtml; class HTMLHeaderController extends HTMLController { public $controller_name = 'HTMLHeaderController'; - private $_no_output = false; + + private $_no_output = false; /** * Sets the value of private member variable $_no_output. @@ -41,7 +45,7 @@ class HTMLHeaderController extends HTMLController */ public function printHeader($title = '', $script = null, $do_print = true, $template = 'header.twig') { - if (function_exists('newrelic_disable_autorum')) { + if (\function_exists('newrelic_disable_autorum')) { newrelic_disable_autorum(); } @@ -49,10 +53,10 @@ class HTMLHeaderController extends HTMLController $viewVars = []; - $viewVars['dir'] = (0 != strcasecmp($lang['applangdir'], 'ltr')) ? ' dir="'.htmlspecialchars($lang['applangdir']).'"' : ''; + $viewVars['dir'] = (0 !== \strcasecmp($lang['applangdir'], 'ltr')) ? ' dir="' . \htmlspecialchars($lang['applangdir']) . '"' : ''; $viewVars['headertemplate'] = $template; - $viewVars['title'] = ('' !== $title) ? ' - '.$title : ''; - $viewVars['appName'] = htmlspecialchars($this->appName); + $viewVars['title'] = ('' !== $title) ? ' - ' . $title : ''; + $viewVars['appName'] = \htmlspecialchars($this->appName); $viewVars['script'] = $script; //$this->prtrace($viewVars); @@ -66,7 +70,7 @@ class HTMLHeaderController extends HTMLController }*/ if (!$this->_no_output && $do_print) { - header('Content-Type: text/html; charset=utf-8'); + \header('Content-Type: text/html; charset=utf-8'); echo $header_html; } else { return $header_html; @@ -82,11 +86,11 @@ class HTMLHeaderController extends HTMLController */ public function printBody($doBody = true, $bodyClass = 'detailbody', $onloadInit = false) { - $bodyClass = $this->lang['applangdir'].' '.htmlspecialchars($bodyClass); + $bodyClass = $this->lang['applangdir'] . ' ' . \htmlspecialchars($bodyClass); $onload = ($onloadInit ? 'onload="init();" ' : ''); - $bodyHtml = sprintf('<body data-controller="%s" class="%s" %s >', $this->controller_name, $bodyClass, $onload); - $bodyHtml .= PHP_EOL; + $bodyHtml = \sprintf('<body data-controller="%s" class="%s" %s >', $this->controller_name, $bodyClass, $onload); + $bodyHtml .= \PHP_EOL; if (!$this->_no_output && $doBody) { echo $bodyHtml; @@ -106,7 +110,7 @@ class HTMLHeaderController extends HTMLController { $title_html = '<h2>'; $title_html .= $this->misc->printHelp($title, $help, false); - $title_html .= '</h2>'.PHP_EOL; + $title_html .= '</h2>' . \PHP_EOL; if ($do_print) { echo $title_html; diff --git a/src/xhtml/HTMLNavbarController.php b/src/xhtml/HTMLNavbarController.php index 2e1b79c0..88f5b759 100644 --- a/src/xhtml/HTMLNavbarController.php +++ b/src/xhtml/HTMLNavbarController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; @@ -13,64 +16,6 @@ class HTMLNavbarController extends HTMLController { public $controller_name = 'HTMLNavbarController'; - private function _getCrumbs($trail) - { - $crumbs = []; - foreach ($trail as $crumb_id => $crumb) { - if (isset($crumb['url'])) { - $crumbs[$crumb_id]['url'] = str_replace('&', '&', $crumb['url']); - } - - if (isset($crumb['title'])) { - $crumbs[$crumb_id]['title'] = $crumb['title']; - $crumbs[$crumb_id]['iconalt'] = $crumb['title']; - } else { - $crumbs[$crumb_id]['iconalt'] = 'Database Root'; - } - - if (isset($crumb['icon']) && $icon = $this->misc->icon($crumb['icon'])) { - $crumbs[$crumb_id]['icon'] = $icon; - } - - $crumbs[$crumb_id]['text'] = $crumb['text']; - - if (isset($crumb['help'])) { - $crumbs[$crumb_id]['helpurl'] = str_replace('&', '&', $this->misc->getHelpLink($crumb['help'])); - } - } - - return $crumbs; - } - - /** - * @param mixed $crumbs - */ - private function _getSearchPathsCrumbs($crumbs, array $viewVars) - { - $data = $this->misc->getDatabaseAccessor(); - $lang = $this->lang; - if (isset($crumbs['database'])) { - $search_path_crumbs = []; - $dburl = $crumbs['database']['url']; - $search_paths = $data->getSearchPath(); - foreach ($search_paths as $schema) { - $url = str_replace(['&', 'redirect/database'], ['&', 'redirect/schema'], $dburl.'&schema='.$schema); - $destination = $this->container->utils->getDestinationWithLastTab('database'); - //$this->dump(['url' => $url, 'destination' => $destination]); - $search_path_crumbs[$schema] = [ - 'title' => $lang['strschema'], - 'text' => $schema, - 'icon' => $this->misc->icon('Schema'), - 'iconalt' => $lang['strschema'], - 'url' => $url, - ]; - } - $viewVars['search_paths'] = $search_path_crumbs; - } - - return $viewVars; - } - /** * Display a bread crumb trail. * @@ -84,7 +29,7 @@ class HTMLNavbarController extends HTMLController $trail_html = $this->printTopbar(false, $from); - if (is_string($trail)) { + if (\is_string($trail)) { $subject = $trail; $trail = $this->_getTrail($subject); // Trail hook's place @@ -128,7 +73,7 @@ class HTMLNavbarController extends HTMLController $this->misc = $this->misc; - if (is_string($alltabs)) { + if (\is_string($alltabs)) { $_SESSION['webdbLastTab'][$alltabs] = $activetab; $alltabs = $this->misc->getNavTabs($alltabs); } @@ -138,18 +83,20 @@ class HTMLNavbarController extends HTMLController //Getting only visible tabs $tabs = []; - if (count($alltabs) > 0) { + + if (0 < \count($alltabs)) { foreach ($alltabs as $tab_id => $tab) { if (!isset($tab['hide']) || true !== $tab['hide']) { $tabs[$tab_id] = $tab; - $tabs[$tab_id]['active'] = ($tab_id == $activetab) ? ' active' : ''; - $tabs[$tab_id]['tablink'] = str_replace(['&', '.php'], ['&', ''], htmlentities($this->getActionUrl($tab, $_REQUEST, $from))); + $tabs[$tab_id]['active'] = ($tab_id === $activetab) ? ' active' : ''; + $tabs[$tab_id]['tablink'] = \str_replace(['&', '.php'], ['&', ''], \htmlentities($this->getActionUrl($tab, $_REQUEST, $from))); //$this->prtrace('link for ' . $tab_id, $tabs[$tab_id]['tablink']); if (isset($tab['icon']) && $icon = $this->misc->icon($tab['icon'])) { $tabs[$tab_id]['iconurl'] = $icon; } + if (isset($tab['help'])) { - $tabs[$tab_id]['helpurl'] = str_replace('&', '&', $this->misc->getHelpLink($tab['help'])); + $tabs[$tab_id]['helpurl'] = \str_replace('&', '&', $this->misc->getHelpLink($tab['help'])); } } } @@ -157,8 +104,8 @@ class HTMLNavbarController extends HTMLController //$this->prtrace($tabs); - if (count($tabs) > 0) { - $width = (int) (100 / count($tabs)).'%'; + if (0 < \count($tabs)) { + $width = (int) (100 / \count($tabs)) . '%'; $viewVars = [ 'width' => $width, @@ -176,13 +123,74 @@ class HTMLNavbarController extends HTMLController } } + private function _getCrumbs($trail) + { + $crumbs = []; + + foreach ($trail as $crumb_id => $crumb) { + if (isset($crumb['url'])) { + $crumbs[$crumb_id]['url'] = \str_replace('&', '&', $crumb['url']); + } + + if (isset($crumb['title'])) { + $crumbs[$crumb_id]['title'] = $crumb['title']; + $crumbs[$crumb_id]['iconalt'] = $crumb['title']; + } else { + $crumbs[$crumb_id]['iconalt'] = 'Database Root'; + } + + if (isset($crumb['icon']) && $icon = $this->misc->icon($crumb['icon'])) { + $crumbs[$crumb_id]['icon'] = $icon; + } + + $crumbs[$crumb_id]['text'] = $crumb['text']; + + if (isset($crumb['help'])) { + $crumbs[$crumb_id]['helpurl'] = \str_replace('&', '&', $this->misc->getHelpLink($crumb['help'])); + } + } + + return $crumbs; + } + + /** + * @param mixed $crumbs + */ + private function _getSearchPathsCrumbs($crumbs, array $viewVars) + { + $data = $this->misc->getDatabaseAccessor(); + $lang = $this->lang; + + if (isset($crumbs['database'])) { + $search_path_crumbs = []; + $dburl = $crumbs['database']['url']; + $search_paths = $data->getSearchPath(); + + foreach ($search_paths as $schema) { + $url = \str_replace(['&', 'redirect/database'], ['&', 'redirect/schema'], $dburl . '&schema=' . $schema); + $destination = $this->container->utils->getDestinationWithLastTab('database'); + //$this->dump(['url' => $url, 'destination' => $destination]); + $search_path_crumbs[$schema] = [ + 'title' => $lang['strschema'], + 'text' => $schema, + 'icon' => $this->misc->icon('Schema'), + 'iconalt' => $lang['strschema'], + 'url' => $url, + ]; + } + $viewVars['search_paths'] = $search_path_crumbs; + } + + return $viewVars; + } + /** * [printTopbar description]. * * @param bool $do_print true to print, false to return html * @param null|mixed $from which method is calling this one */ - private function printTopbar($do_print = true, $from = null): ?string + private function printTopbar($do_print = true, $from = null): ? string { $from = $from ? $from : __METHOD__; @@ -196,16 +204,16 @@ class HTMLNavbarController extends HTMLController $server_id = $this->misc->getServerId(); $reqvars = $this->misc->getRequestVars('table'); - $topbar_html = '<div class="topbar" data-controller="'.$this->controller_name.'"><table style="width: 100%"><tr><td>'; + $topbar_html = '<div class="topbar" data-controller="' . $this->controller_name . '"><table style="width: 100%"><tr><td>'; if ($server_info && isset($server_info['platform'], $server_info['username'])) { // top left informations when connected - $topbar_html .= sprintf( + $topbar_html .= \sprintf( $lang['strtopbar'], - '<span class="platform">'.htmlspecialchars($server_info['platform']).'</span>', - '<span class="host">'.htmlspecialchars((empty($server_info['host'])) ? 'localhost' : $server_info['host']).'</span>', - '<span class="port">'.htmlspecialchars($server_info['port']).'</span>', - '<span class="username">'.htmlspecialchars($server_info['username']).'</span>' + '<span class="platform">' . \htmlspecialchars($server_info['platform']) . '</span>', + '<span class="host">' . \htmlspecialchars((empty($server_info['host'])) ? 'localhost' : $server_info['host']) . '</span>', + '<span class="port">' . \htmlspecialchars($server_info['port']) . '</span>', + '<span class="username">' . \htmlspecialchars($server_info['username']) . '</span>' ); $topbar_html .= '</td>'; @@ -216,8 +224,8 @@ class HTMLNavbarController extends HTMLController 'sql' => [ 'attr' => [ 'href' => [ - 'url' => SUBFOLDER.'/src/views/sqledit', - 'urlvars' => array_merge($reqvars, [ + 'url' => SUBFOLDER . '/src/views/sqledit', + 'urlvars' => \array_merge($reqvars, [ 'action' => 'sql', ]), ], @@ -230,8 +238,8 @@ class HTMLNavbarController extends HTMLController 'history' => [ 'attr' => [ 'href' => [ - 'url' => SUBFOLDER.'/src/views/history', - 'urlvars' => array_merge($reqvars, [ + 'url' => SUBFOLDER . '/src/views/history', + 'urlvars' => \array_merge($reqvars, [ 'action' => 'pophistory', ]), ], @@ -243,8 +251,8 @@ class HTMLNavbarController extends HTMLController 'find' => [ 'attr' => [ 'href' => [ - 'url' => SUBFOLDER.'/src/views/sqledit', - 'urlvars' => array_merge($reqvars, [ + 'url' => SUBFOLDER . '/src/views/sqledit', + 'urlvars' => \array_merge($reqvars, [ 'action' => 'find', ]), ], @@ -257,10 +265,10 @@ class HTMLNavbarController extends HTMLController 'logout' => [ 'attr' => [ 'href' => [ - 'url' => SUBFOLDER.'/src/views/servers', + 'url' => SUBFOLDER . '/src/views/servers', 'urlvars' => [ 'action' => 'logout', - 'logoutServer' => sha1("{$server_info['host']}:{$server_info['port']}:{$server_info['sslmode']}"), + 'logoutServer' => \sha1("{$server_info['host']}:{$server_info['port']}:{$server_info['sslmode']}"), ], ], 'id' => 'toplink_logout', @@ -283,7 +291,7 @@ class HTMLNavbarController extends HTMLController $topbar_html .= "<span class=\"appname\">{$appName}</span> <span class=\"version\">{$appVersion}</span>"; } - $topbar_html .= '</tr></table></div>'.PHP_EOL; + $topbar_html .= '</tr></table></div>' . \PHP_EOL; if ($do_print) { echo $topbar_html; @@ -295,9 +303,9 @@ class HTMLNavbarController extends HTMLController private function getHREFSubject(string $subject) { $vars = $this->misc->getSubjectParams($subject); - ksort($vars['params']); + \ksort($vars['params']); - return "{$vars['url']}?".http_build_query($vars['params'], '', '&'); + return "{$vars['url']}?" . \http_build_query($vars['params'], '', '&'); } /** @@ -317,11 +325,11 @@ class HTMLNavbarController extends HTMLController $trail['root'] = [ 'text' => $appName, - 'url' => SUBFOLDER.'/src/views/servers', + 'url' => SUBFOLDER . '/src/views/servers', 'icon' => 'Introduction', ]; - if ('root' == $subject) { + if ('root' === $subject) { return $trail; } @@ -334,7 +342,7 @@ class HTMLNavbarController extends HTMLController 'icon' => 'Server', ]; - if ('server' == $subject) { + if ('server' === $subject) { return $trail; } @@ -355,7 +363,7 @@ class HTMLNavbarController extends HTMLController $trail = $this->_getTrailsFromArray($trail, $database_rolename); - if (in_array($subject, ['database', 'role'], true)) { + if (\in_array($subject, ['database', 'role'], true)) { return $trail; } @@ -369,7 +377,8 @@ class HTMLNavbarController extends HTMLController ]; $trail = $this->_getTrailsFromArray($trail, $schema); - if ('schema' == $subject) { + + if ('schema' === $subject) { return $trail; } @@ -387,7 +396,7 @@ class HTMLNavbarController extends HTMLController 'icon' => 'View', ], 'matview' => [ - 'title' => 'M'.$lang['strview'], + 'title' => 'M' . $lang['strview'], 'subject' => 'matview', 'help' => 'pg.matview', 'icon' => 'MViews', @@ -402,11 +411,11 @@ class HTMLNavbarController extends HTMLController $trail = $this->_getTrailsFromArray($trail, $table_view_matview_fts); - if (in_array($subject, ['table', 'view', 'matview', 'ftscfg'], true)) { + if (\in_array($subject, ['table', 'view', 'matview', 'ftscfg'], true)) { return $trail; } - if (!is_null($subject)) { + if (null !== $subject) { $trail = $this->_getLastTrailPart($subject, $trail); } @@ -445,7 +454,7 @@ class HTMLNavbarController extends HTMLController switch ($subject) { case 'function': $trail[$subject] = [ - 'title' => $lang['str'.$subject], + 'title' => $lang['str' . $subject], 'text' => $_REQUEST[$subject], 'url' => $this->getHREFSubject('function'), 'help' => 'pg.function', @@ -501,9 +510,9 @@ class HTMLNavbarController extends HTMLController break; } $trail[$subject] = [ - 'title' => array_key_exists('str'.$subject, $lang) ? $lang['str'.$subject] : $subject, + 'title' => \array_key_exists('str' . $subject, $lang) ? $lang['str' . $subject] : $subject, 'text' => $_REQUEST[$subject], - 'help' => 'pg.'.$subject, + 'help' => 'pg.' . $subject, 'icon' => $icon, ]; } diff --git a/src/xhtml/HTMLTableController.php b/src/xhtml/HTMLTableController.php index 161c3d54..f422b84a 100644 --- a/src/xhtml/HTMLTableController.php +++ b/src/xhtml/HTMLTableController.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; @@ -13,16 +16,24 @@ use PHPPgAdmin\Decorators\Decorator; */ class HTMLTableController extends HTMLController { - public $controller_name = 'HTMLTableController'; - protected $ma = []; + public $controller_name = 'HTMLTableController'; + + protected $ma = []; + protected $plugin_functions_parameters = []; - protected $has_ma = false; + + protected $has_ma = false; protected $tabledata; + protected $columns; + protected $actions; + protected $place; + protected $nodata; + protected $pre_fn; /** @@ -89,8 +100,8 @@ class HTMLTableController extends HTMLController public function printTable($turn_into_datatable = true, $with_body = true) { - if ($this->tabledata->recordCount() <= 0) { - return "<p>{$this->nodata}</p>".PHP_EOL; + if (0 >= $this->tabledata->recordCount()) { + return "<p>{$this->nodata}</p>" . \PHP_EOL; } $tablehtml = ''; @@ -109,7 +120,7 @@ class HTMLTableController extends HTMLController $tablehtml .= $matop_html; - $tablehtml .= '<table width="auto" class="'.($turn_into_datatable ? 'will_be_datatable ' : ' ').$this->place.'">'.PHP_EOL; + $tablehtml .= '<table width="auto" class="' . ($turn_into_datatable ? 'will_be_datatable ' : ' ') . $this->place . '">' . \PHP_EOL; $tablehtml .= $this->getThead(); @@ -119,7 +130,7 @@ class HTMLTableController extends HTMLController $tablehtml .= $this->getTfooter(); - $tablehtml .= '</table>'.PHP_EOL; + $tablehtml .= '</table>' . \PHP_EOL; // Multi action table footer w/ options & [un]check'em all $tablehtml .= $mabottom_html; @@ -127,69 +138,12 @@ class HTMLTableController extends HTMLController return $tablehtml; } - private function _getMaHtml() - { - $matop_html = ''; - $ma_bottomhtml = ''; - $lang = $this->lang; - - if ($this->has_ma) { - $matop_html .= '<script src="'.SUBFOLDER.'/assets/js/multiactionform.js" type="text/javascript"></script>'.PHP_EOL; - $matop_html .= sprintf('<form id="multi_form" action="%s" method="post" enctype="multipart/form-data">%s', $this->ma['url'], PHP_EOL); - $this->coalesceArr($this->ma, 'vars', []); - - foreach ($this->ma['vars'] as $k => $v) { - $matop_html .= sprintf('<input type="hidden" name="%s" value="%s" />', $k, $v); - } - - // if default is not set or doesn't exist, set it to null - if (!isset($this->ma['default']) || !isset($this->actions[$this->ma['default']])) { - $this->ma['default'] = null; - } - - $ma_bottomhtml .= '<br />'.PHP_EOL; - $ma_bottomhtml .= '<table>'.PHP_EOL; - $ma_bottomhtml .= '<tr>'.PHP_EOL; - $ma_bottomhtml .= "<th class=\"data\" style=\"text-align: left\" colspan=\"3\">{$lang['stractionsonmultiplelines']}</th>".PHP_EOL; - $ma_bottomhtml .= '</tr>'.PHP_EOL; - $ma_bottomhtml .= '<tr class="row1">'.PHP_EOL; - $ma_bottomhtml .= '<td>'; - $ma_bottomhtml .= "<a href=\"#\" onclick=\"javascript:checkAll(true);\">{$lang['strselectall']}</a> / "; - $ma_bottomhtml .= "<a href=\"#\" onclick=\"javascript:checkAll(false);\">{$lang['strunselectall']}</a></td>".PHP_EOL; - $ma_bottomhtml .= '<td> ---> </td>'.PHP_EOL; - $ma_bottomhtml .= '<td>'.PHP_EOL; - $ma_bottomhtml .= "\t<select name=\"action\">".PHP_EOL; - if (null == $this->ma['default']) { - $ma_bottomhtml .= "\t\t<option value=\"\">--</option>".PHP_EOL; - } - - foreach ($this->actions as $k => $a) { - if (isset($a['multiaction'])) { - $selected = $this->ma['default'] == $k ? ' selected="selected" ' : ''; - $ma_bottomhtml .= "\t\t"; - $ma_bottomhtml .= '<option value="'.$a['multiaction'].'" '.$selected.' rel="'.$k.'">'.$a['content'].'</option>'; - $ma_bottomhtml .= PHP_EOL; - } - } - - $ma_bottomhtml .= "\t</select>".PHP_EOL; - $ma_bottomhtml .= "<input type=\"submit\" value=\"{$lang['strexecute']}\" />".PHP_EOL; - $ma_bottomhtml .= $this->getForm(); - $ma_bottomhtml .= '</td>'.PHP_EOL; - $ma_bottomhtml .= '</tr>'.PHP_EOL; - $ma_bottomhtml .= '</table>'.PHP_EOL; - $ma_bottomhtml .= '</form>'; - } - - return [$matop_html, $ma_bottomhtml]; - } - public function getThead() { $columns = $this->columns; $actions = $this->actions; - $thead_html = '<thead><tr>'.PHP_EOL; + $thead_html = '<thead><tr>' . \PHP_EOL; // Display column headings if ($this->has_ma) { @@ -203,29 +157,114 @@ class HTMLTableController extends HTMLController switch ($column_id) { case 'actions': - if (sizeof($actions) > 0) { - $thead_html .= '<th class="data" >'.$column['title'].'</th>'.PHP_EOL; + if (0 < \count($actions)) { + $thead_html .= '<th class="data" >' . $column['title'] . '</th>' . \PHP_EOL; } break; default: - $thead_html .= '<th class="data'.$class.'">'; + $thead_html .= '<th class="data' . $class . '">'; + if (isset($column['help'])) { $thead_html .= $this->misc->printHelp($column['title'], $column['help'], false); } else { $thead_html .= $column['title']; } - $thead_html .= '</th>'.PHP_EOL; + $thead_html .= '</th>' . \PHP_EOL; break; } } - $thead_html .= '</tr></thead>'.PHP_EOL; + $thead_html .= '</tr></thead>' . \PHP_EOL; return $thead_html; } + public function getTfooter() + { + $columns = $this->columns; + $actions = $this->actions; + + $tfoot_html = '<tfoot><tr>' . \PHP_EOL; + + // Display column headings + if ($this->has_ma) { + $tfoot_html .= '<td></td>'; + } + + foreach ($columns as $column_id => $column) { + // Handle cases where no class has been passed + + $class = (isset($column['class']) && '' !== $column['class']) ? $column['class'] : ''; + + if ('actions' !== $column_id || 0 < \count($actions)) { + $tfoot_html .= "<td class=\"data{$class}\"></td>" . \PHP_EOL; + } + } + $tfoot_html .= '</tr></tfoot>' . \PHP_EOL; + + return $tfoot_html; + } + + private function _getMaHtml() + { + $matop_html = ''; + $ma_bottomhtml = ''; + $lang = $this->lang; + + if ($this->has_ma) { + $matop_html .= '<script src="' . SUBFOLDER . '/assets/js/multiactionform.js" type="text/javascript"></script>' . \PHP_EOL; + $matop_html .= \sprintf('<form id="multi_form" action="%s" method="post" enctype="multipart/form-data">%s', $this->ma['url'], \PHP_EOL); + $this->coalesceArr($this->ma, 'vars', []); + + foreach ($this->ma['vars'] as $k => $v) { + $matop_html .= \sprintf('<input type="hidden" name="%s" value="%s" />', $k, $v); + } + + // if default is not set or doesn't exist, set it to null + if (!isset($this->ma['default']) || !isset($this->actions[$this->ma['default']])) { + $this->ma['default'] = null; + } + + $ma_bottomhtml .= '<br />' . \PHP_EOL; + $ma_bottomhtml .= '<table>' . \PHP_EOL; + $ma_bottomhtml .= '<tr>' . \PHP_EOL; + $ma_bottomhtml .= "<th class=\"data\" style=\"text-align: left\" colspan=\"3\">{$lang['stractionsonmultiplelines']}</th>" . \PHP_EOL; + $ma_bottomhtml .= '</tr>' . \PHP_EOL; + $ma_bottomhtml .= '<tr class="row1">' . \PHP_EOL; + $ma_bottomhtml .= '<td>'; + $ma_bottomhtml .= "<a href=\"#\" onclick=\"javascript:checkAll(true);\">{$lang['strselectall']}</a> / "; + $ma_bottomhtml .= "<a href=\"#\" onclick=\"javascript:checkAll(false);\">{$lang['strunselectall']}</a></td>" . \PHP_EOL; + $ma_bottomhtml .= '<td> ---> </td>' . \PHP_EOL; + $ma_bottomhtml .= '<td>' . \PHP_EOL; + $ma_bottomhtml .= "\t<select name=\"action\">" . \PHP_EOL; + + if (null === $this->ma['default']) { + $ma_bottomhtml .= "\t\t<option value=\"\">--</option>" . \PHP_EOL; + } + + foreach ($this->actions as $k => $a) { + if (isset($a['multiaction'])) { + $selected = $this->ma['default'] === $k ? ' selected="selected" ' : ''; + $ma_bottomhtml .= "\t\t"; + $ma_bottomhtml .= '<option value="' . $a['multiaction'] . '" ' . $selected . ' rel="' . $k . '">' . $a['content'] . '</option>'; + $ma_bottomhtml .= \PHP_EOL; + } + } + + $ma_bottomhtml .= "\t</select>" . \PHP_EOL; + $ma_bottomhtml .= "<input type=\"submit\" value=\"{$lang['strexecute']}\" />" . \PHP_EOL; + $ma_bottomhtml .= $this->getForm(); + $ma_bottomhtml .= '</td>' . \PHP_EOL; + $ma_bottomhtml .= '</tr>' . \PHP_EOL; + $ma_bottomhtml .= '</table>' . \PHP_EOL; + $ma_bottomhtml .= '</form>'; + } + + return [$matop_html, $ma_bottomhtml]; + } + private function getTbody() { $columns = $this->columns; @@ -241,7 +280,8 @@ class HTMLTableController extends HTMLController $id = ($i % 2) + 1; unset($alt_actions); - if (!is_null($pre_fn)) { + + if (null !== $pre_fn) { $alt_actions = $pre_fn($tabledata, $actions); } @@ -249,14 +289,16 @@ class HTMLTableController extends HTMLController $alt_actions = &$actions; } - $tbody_html .= sprintf('<tr class="data%s">', $id).PHP_EOL; + $tbody_html .= \sprintf('<tr class="data%s">', $id) . \PHP_EOL; + if ($this->has_ma) { $a = []; + foreach ($this->ma['keycols'] as $k => $v) { $a[$k] = $tabledata->fields[$v]; } //\Kint::dump($a); - $tbody_html .= sprintf('<td><input type="checkbox" name="ma[]" value="%s"/></td>', htmlentities(serialize($a), ENT_COMPAT, 'UTF-8')).PHP_EOL; + $tbody_html .= \sprintf('<td><input type="checkbox" name="ma[]" value="%s"/></td>', \htmlentities(\serialize($a), \ENT_COMPAT, 'UTF-8')) . \PHP_EOL; } foreach ($columns as $column_id => $column) { @@ -269,6 +311,7 @@ class HTMLTableController extends HTMLController switch ($column_id) { case 'actions': $tbody_html .= "<td class=\"opbutton{$id} {$class}\">"; + foreach ($alt_actions as $action) { if (isset($action['disable']) && true === $action['disable']) { continue; @@ -276,38 +319,40 @@ class HTMLTableController extends HTMLController $action['fields'] = $tabledata->fields; $tbody_html .= $this->printLink($action, false, __METHOD__); } - $tbody_html .= '</td>'.PHP_EOL; + $tbody_html .= '</td>' . \PHP_EOL; break; case 'comment': $tbody_html .= "<td class='comment_cell'>"; - $tbody_html .= htmlentities(Decorator::get_sanitized_value($column['field'], $tabledata->fields)); + $tbody_html .= \htmlentities(Decorator::get_sanitized_value($column['field'], $tabledata->fields)); $tbody_html .= '</td>'; break; default: - $tbody_html .= '<td class="'.$class.'">'; + $tbody_html .= '<td class="' . $class . '">'; $val = Decorator::get_sanitized_value($column['field'], $tabledata->fields); - if (!is_null($val)) { + + if (null !== $val) { if (isset($column['url'])) { $tbody_html .= "<a href=\"{$column['url']}"; $tbody_html .= $this->printUrlVars($column['vars'], $tabledata->fields, false); $tbody_html .= '">'; } - $type = isset($column['type']) ? $column['type'] : null; - $params = isset($column['params']) ? $column['params'] : []; + $type = $column['type'] ?? null; + $params = $column['params'] ?? []; $tbody_html .= $this->misc->printVal($val, $type, $params); + if (isset($column['url'])) { $tbody_html .= '</a>'; } } - $tbody_html .= '</td>'.PHP_EOL; + $tbody_html .= '</td>' . \PHP_EOL; break; } } - $tbody_html .= '</tr>'.PHP_EOL; + $tbody_html .= '</tr>' . \PHP_EOL; $tabledata->moveNext(); ++$i; @@ -318,32 +363,6 @@ class HTMLTableController extends HTMLController return $tbody_html; } - public function getTfooter() - { - $columns = $this->columns; - $actions = $this->actions; - - $tfoot_html = '<tfoot><tr>'.PHP_EOL; - - // Display column headings - if ($this->has_ma) { - $tfoot_html .= '<td></td>'; - } - - foreach ($columns as $column_id => $column) { - // Handle cases where no class has been passed - - $class = (isset($column['class']) && '' !== $column['class']) ? $column['class'] : ''; - - if ($column_id !== 'actions' || sizeof($actions) > 0) { - $tfoot_html .= "<td class=\"data{$class}\"></td>".PHP_EOL; - } - } - $tfoot_html .= '</tr></tfoot>'.PHP_EOL; - - return $tfoot_html; - } - private function getForm() { if (!$this->form) { @@ -356,9 +375,11 @@ class HTMLTableController extends HTMLController private function printUrlVars(&$vars, &$fields, bool $do_print = true) { $url_vars_html = ''; + foreach ($vars as $var => $varfield) { - $url_vars_html .= "{$var}=".urlencode($fields[$varfield]).'&'; + $url_vars_html .= "{$var}=" . \urlencode($fields[$varfield]) . '&'; } + if ($do_print) { echo $url_vars_html; } else { diff --git a/src/xhtml/XHtmlButton.php b/src/xhtml/XHtmlButton.php index 61b30cfa..2e258021 100644 --- a/src/xhtml/XHtmlButton.php +++ b/src/xhtml/XHtmlButton.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; diff --git a/src/xhtml/XHtmlElement.php b/src/xhtml/XHtmlElement.php index 74e5e287..4350d24b 100644 --- a/src/xhtml/XHtmlElement.php +++ b/src/xhtml/XHtmlElement.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC8 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; @@ -15,7 +18,9 @@ namespace PHPPgAdmin\XHtml; class XHtmlElement extends XHtmlSimpleElement { public $_text; + public $_htmlcode = ''; + public $_siblings = []; public function __construct($text = null) @@ -27,25 +32,25 @@ class XHtmlElement extends XHtmlSimpleElement } } - /* - * Adds an xhtml child to element + /** + * Adds an xhtml child to element. * - * @param XHtmlElement $object The element to become a child of element + * @param XHtmlElement $object The element to become a child of element */ - public function add(&XHtmlOption $object) + public function add(XHtmlOption &$object): void { - array_push($this->_siblings, $object); + \array_push($this->_siblings, $object); } - /* - * The CDATA section of Element + /** + * The CDATA section of Element. * - * @param string $text Text content of the element + * @param string $text Text content of the element */ - public function set_text($text) + public function set_text($text): void { if ($text) { - $this->_text = htmlspecialchars($text); + $this->_text = \htmlspecialchars($text); } } @@ -57,9 +62,10 @@ class XHtmlElement extends XHtmlSimpleElement public function _html() { $this->_htmlcode = "<{$this->_element}"; + foreach ($this->_attributes as $attribute => $value) { if (!empty($value)) { - $this->_htmlcode .= sprintf(' %s="%s" ', $attribute, $value); + $this->_htmlcode .= \sprintf(' %s="%s" ', $attribute, $value); } } $this->_htmlcode .= '>'; @@ -85,6 +91,6 @@ class XHtmlElement extends XHtmlSimpleElement public function has_siblings() { - return 0 != count($this->_siblings); + return 0 !== \count($this->_siblings); } } diff --git a/src/xhtml/XHtmlOption.php b/src/xhtml/XHtmlOption.php index 2a563ba9..29116ee5 100644 --- a/src/xhtml/XHtmlOption.php +++ b/src/xhtml/XHtmlOption.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; diff --git a/src/xhtml/XHtmlSelect.php b/src/xhtml/XHtmlSelect.php index c87d058c..844c07b4 100644 --- a/src/xhtml/XHtmlSelect.php +++ b/src/xhtml/XHtmlSelect.php @@ -1,7 +1,10 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; @@ -18,6 +21,7 @@ class XHtmlSelect extends XHtmlElement parent::__construct(); $this->set_attribute('name', $name); + if ($multiple) { $this->set_attribute('multiple', 'multiple'); } @@ -27,11 +31,11 @@ class XHtmlSelect extends XHtmlElement } } - public function set_data(&$data, $delim = ',') + public function set_data(&$data, $delim = ','): void { - switch (gettype($data)) { + switch (\gettype($data)) { case 'string': - $this->_data = explode($delim, $data); + $this->_data = \explode($delim, $data); break; case 'array': diff --git a/src/xhtml/XHtmlSimpleElement.php b/src/xhtml/XHtmlSimpleElement.php index b5a10805..01ea5003 100644 --- a/src/xhtml/XHtmlSimpleElement.php +++ b/src/xhtml/XHtmlSimpleElement.php @@ -1,27 +1,53 @@ <?php +// declare(strict_types=1); + /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace PHPPgAdmin\XHtml; +\defined('BASE_PATH') || \define('BASE_PATH', \dirname(__DIR__, 2)); +\defined('SUBFOLDER') || \define( + 'SUBFOLDER', + \str_replace($_SERVER['DOCUMENT_ROOT'] ?? '', '', BASE_PATH) +); +\defined('DEBUGMODE') || \define('DEBUGMODE', false); + /** * XHtmlSimpleElement. * * Used to generate Xhtml-Code for simple xhtml elements * (i.e. elements, that can't contain child elements) * + * * @author Felix Meinhold */ class XHtmlSimpleElement { + use \PHPPgAdmin\Traits\HelperTrait; + /** + * @var string + */ + const BASE_PATH = BASE_PATH; + /** + * @var string + */ + const SUBFOLDER = SUBFOLDER; + /** + * @var string + */ + const DEBUGMODE = DEBUGMODE; + public $_element; + public $_siblings = []; + public $_htmlcode; - public $_attributes = []; - use \PHPPgAdmin\Traits\HelperTrait; + public $_attributes = []; /** * Constructor. @@ -34,22 +60,22 @@ class XHtmlSimpleElement $this->_element = $this->is_element(); } - public function set_style(string $style) + public function set_style(string $style): void { $this->set_attribute('style', $style); } - public function set_class($class) + public function set_class($class): void { $this->set_attribute('class', $class); } public function is_element() { - $lower_classname = strtolower(get_class($this)); - $is_element_string = str_replace('phppgadmin\xhtml\xhtml', '', $lower_classname); + $lower_classname = \mb_strtolower(\get_class($this)); + + return \str_replace('phppgadmin\xhtml\xhtml', '', $lower_classname); //$this->prtrace('is_element_string', $is_element_string, 'lower_classname', $lower_classname, '__CLASS__'); - return $is_element_string; } /** @@ -58,9 +84,10 @@ class XHtmlSimpleElement public function _html() { $this->_htmlcode = '<'; + foreach ($this->_attributes as $attribute => $value) { if (!empty($value)) { - $this->_htmlcode .= sprintf(' %s="%s" ', $attribute, $value); + $this->_htmlcode .= \sprintf(' %s="%s" ', $attribute, $value); } } $this->_htmlcode .= '/>'; @@ -79,12 +106,12 @@ class XHtmlSimpleElement /** * Echoes xhtml. */ - public function show() + public function show(): void { echo $this->fetch(); } - public function set_attribute(string $attr, string $value) + public function set_attribute(string $attr, string $value): void { $this->_attributes[$attr] = $value; } diff --git a/tests/_support/AcceptanceTester.php b/tests/_support/AcceptanceTester.php index 355ea599..23b7c964 100644 --- a/tests/_support/AcceptanceTester.php +++ b/tests/_support/AcceptanceTester.php @@ -1,7 +1,8 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ class AcceptanceTester extends \Codeception\Actor diff --git a/tests/_support/FunctionalTester.php b/tests/_support/FunctionalTester.php index 7c712c7b..b2679c07 100644 --- a/tests/_support/FunctionalTester.php +++ b/tests/_support/FunctionalTester.php @@ -1,7 +1,8 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ class FunctionalTester extends \Codeception\Actor diff --git a/tests/_support/Helper/Acceptance.php b/tests/_support/Helper/Acceptance.php index ec3dee7d..d3cdc24c 100644 --- a/tests/_support/Helper/Acceptance.php +++ b/tests/_support/Helper/Acceptance.php @@ -1,7 +1,8 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace Helper; diff --git a/tests/_support/Helper/Functional.php b/tests/_support/Helper/Functional.php index 6e60102e..cef29ef4 100644 --- a/tests/_support/Helper/Functional.php +++ b/tests/_support/Helper/Functional.php @@ -1,7 +1,8 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace Helper; diff --git a/tests/_support/Helper/Unit.php b/tests/_support/Helper/Unit.php index 84c82e5b..a72c96d7 100644 --- a/tests/_support/Helper/Unit.php +++ b/tests/_support/Helper/Unit.php @@ -1,19 +1,40 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace Helper; +use PHPPgAdmin\ContainerUtils; + +defined('BASE_PATH') || define('BASE_PATH', dirname(dirname(dirname(__DIR__)))); +defined('SUBFOLDER') || define( + 'SUBFOLDER', + str_replace($_SERVER['DOCUMENT_ROOT'] ?? '', '', BASE_PATH) +); +defined('DEBUGMODE') || define('DEBUGMODE', false); +if (!is_readable(BASE_PATH . '/src/lib.inc.php')) { + die('lib.inc.php is not readable'); +} +defined('IN_TEST') || define('IN_TEST', true); // here you can define custom actions // all public methods declared in helper class will be available in $I class Unit extends \Codeception\Module { - const DIRNAME = __DIR__; - - private static $container; + /** @var string */ + const BASE_PATH = BASE_PATH; + /** @var string */ + const SUBFOLDER = SUBFOLDER; + /** @var string */ + const DEBUGMODE = DEBUGMODE; + /** + * @var \PHPPgAdmin + */ + private static $_container; + private static $_conf; public static function getDir() { @@ -22,13 +43,17 @@ class Unit extends \Codeception\Module public static function getContainer() { - if (!static::$container) { - require_once self::DIRNAME.'/../../../src/lib.inc.php'; - self::$container = $container; + + //$conf = self::getConf(); + if (!static::$_container) { + require_once BASE_PATH . '/src/lib.inc.php'; + self::$_container = ContainerUtils::getContainerInstance(); } - \Codeception\Util\Debug::debug('BASE_PATH is '.\BASE_PATH); + //dump(PHP_SAPI); + + //\Codeception\Util\Debug::debug('BASE_PATH is ' . \BASE_PATH); - return self::$container; + return self::$_container; } } diff --git a/tests/_support/UnitTester.php b/tests/_support/UnitTester.php index 218e677a..d4400c06 100644 --- a/tests/_support/UnitTester.php +++ b/tests/_support/UnitTester.php @@ -1,7 +1,8 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ class UnitTester extends \Codeception\Actor diff --git a/tests/_support/_generated/UnitTesterActions.php b/tests/_support/_generated/UnitTesterActions.php index ee1f441d..557327ac 100644 --- a/tests/_support/_generated/UnitTesterActions.php +++ b/tests/_support/_generated/UnitTesterActions.php @@ -1,7 +1,8 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ namespace _generated; diff --git a/tests/unit/ContainerTest.php b/tests/unit/ContainerTest.php index 7553c7a1..12241e1d 100644 --- a/tests/unit/ContainerTest.php +++ b/tests/unit/ContainerTest.php @@ -1,7 +1,9 @@ + <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ class ContainerTest extends \Codeception\Test\Unit @@ -15,9 +17,11 @@ class ContainerTest extends \Codeception\Test\Unit protected function _before() { $Helper = $this->getModule('\Helper\Unit'); - $this->container = $Helper->getContainer(); + $this->container = $Helper::getContainer(); + //dump($this->container->environment->all()); + //\Codeception\Util\Debug::debug($container); + $this->container->misc->setNoDBConnection(true); - //\Codeception\Util\Debug::debug('BASE_PATH is ' . \BASE_PATH); } protected function _after() diff --git a/tests/unit/TablesAndViewsTest.php b/tests/unit/TablesAndViewsTest.php new file mode 100644 index 00000000..9cc504d6 --- /dev/null +++ b/tests/unit/TablesAndViewsTest.php @@ -0,0 +1,76 @@ +<?php + +/** + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * + */ + +class TablesAndViewsTest extends \Codeception\Test\Unit +{ + /** + * @var \UnitTester + */ + protected $tester; + protected $_container; + + protected function _before() + { + $Helper = $this->getModule('\Helper\Unit'); + $this->container = $Helper::getContainer(); + + $this->container->get('misc')->setNoDBConnection(true); + //\Codeception\Util\Debug::debug('BASE_PATH is ' . \BASE_PATH); + } + + protected function _after() + { + } + + public function testMaterializedviewpropertiesView() + { + $_container = $this->container; + require BASE_PATH . '/tests/views/materializedviewproperties.php'; + $controller = materializedviewpropertiesFactory($_container); + $this->assertSame($controller->controller_name, 'MaterializedviewpropertiesController', 'controller name should be MaterializedviewpropertiesController'); + } + + public function testMaterializedviewsView() + { + $_container = $this->container; + require BASE_PATH . '/tests/views/materializedviews.php'; + $controller = materializedviewsFactory($_container); + $this->assertSame($controller->controller_name, 'MaterializedviewsController', 'controller name should be MaterializedviewsController'); + } + + public function testTablesView() + { + $_container = $this->container; + require BASE_PATH . '/tests/views/tables.php'; + $controller = tablesFactory($_container); + $this->assertSame($controller->controller_name, 'TablesController', 'controller name should be TablesController'); + } + + public function testTblpropertiesView() + { + $_container = $this->container; + require BASE_PATH . '/tests/views/tblproperties.php'; + $controller = tblpropertiesFactory($_container); + $this->assertSame($controller->controller_name, 'TblpropertiesController', 'controller name should be TblpropertiesController'); + } + + public function testViewpropertiesView() + { + $_container = $this->container; + require BASE_PATH . '/tests/views/viewproperties.php'; + $controller = viewpropertiesFactory($_container); + $this->assertSame($controller->controller_name, 'ViewpropertiesController', 'controller name should be ViewpropertiesController'); + } + + public function testViewsView() + { + $_container = $this->container; + require BASE_PATH . '/tests/views/views.php'; + $controller = viewsFactory($_container); + $this->assertSame($controller->controller_name, 'ViewsController', 'controller name should be ViewsController'); + } +} diff --git a/tests/unit/ViewTest.php b/tests/unit/ViewTest.php index 5aa145c3..651237a9 100644 --- a/tests/unit/ViewTest.php +++ b/tests/unit/ViewTest.php @@ -1,7 +1,8 @@ <?php /** - * PHPPgAdmin v6.0.0-RC9 + * PHPPgAdmin vv6.0.0-RC8-16-g13de173f + * */ class ViewTest extends \Codeception\Test\Unit @@ -10,13 +11,14 @@ class ViewTest extends \Codeception\Test\Unit * @var \UnitTester */ protected $tester; - protected $container; + protected $_container; protected function _before() { $Helper = $this->getModule('\Helper\Unit'); - $this->container = $Helper->getContainer(); - $this->container->misc->setNoDBConnection(true); + $this->container = $Helper::getContainer(); + + $this->container->get('misc')->setNoDBConnection(true); //\Codeception\Util\Debug::debug('BASE_PATH is ' . \BASE_PATH); } @@ -28,309 +30,305 @@ class ViewTest extends \Codeception\Test\Unit public function testAcinsertView() { - $container = $this->container; - require BASE_PATH.'/tests/views/acinsert.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/acinsert.php'; + $controller = acinsertFactory($_container); $this->assertSame($controller->controller_name, 'AcinsertController', 'controller name should be AcinsertController'); } public function testAggregatesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/aggregates.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/aggregates.php'; + $controller = aggregatesFactory($_container); $this->assertSame($controller->controller_name, 'AggregatesController', 'controller name should be AggregatesController'); } public function testAlldbView() { - $container = $this->container; - require BASE_PATH.'/tests/views/alldb.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/alldb.php'; + $controller = alldbFactory($_container); $this->assertSame($controller->controller_name, 'AlldbController', 'controller name should be AlldbController'); } public function testBrowserView() { - $container = $this->container; - require BASE_PATH.'/tests/views/browser.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/browser.php'; + $controller = browserFactory($_container); $this->assertSame($controller->controller_name, 'BrowserController', 'controller name should be BrowserController'); } public function testCastsView() { - $container = $this->container; - require BASE_PATH.'/tests/views/casts.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/casts.php'; + $controller = castsFactory($_container); $this->assertSame($controller->controller_name, 'CastsController', 'controller name should be CastsController'); } public function testColpropertiesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/colproperties.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/colproperties.php'; + $controller = colpropertiesFactory($_container); $this->assertSame($controller->controller_name, 'ColpropertiesController', 'controller name should be ColpropertiesController'); } public function testConstraintsView() { - $container = $this->container; - require BASE_PATH.'/tests/views/constraints.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/constraints.php'; + $controller = constraintsFactory($_container); $this->assertSame($controller->controller_name, 'ConstraintsController', 'controller name should be ConstraintsController'); } public function testConversionsView() { - $container = $this->container; - require BASE_PATH.'/tests/views/conversions.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/conversions.php'; + $controller = conversionsFactory($_container); $this->assertSame($controller->controller_name, 'ConversionsController', 'controller name should be ConversionsController'); } public function testDatabaseView() { - $container = $this->container; - require BASE_PATH.'/tests/views/database.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/database.php'; + $controller = databaseFactory($_container); $this->assertSame($controller->controller_name, 'DatabaseController', 'controller name should be DatabaseController'); } public function testDataexportView() { - $container = $this->container; - require BASE_PATH.'/tests/views/dataexport.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/dataexport.php'; + $controller = dataexportFactory($_container); $this->assertSame($controller->controller_name, 'DataexportController', 'controller name should be DataexportController'); } public function testDataimportView() { - $container = $this->container; - require BASE_PATH.'/tests/views/dataimport.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/dataimport.php'; + $controller = dataimportFactory($_container); $this->assertSame($controller->controller_name, 'DataimportController', 'controller name should be DataimportController'); } public function testDbexportView() { - $container = $this->container; - require BASE_PATH.'/tests/views/dbexport.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/dbexport.php'; + $controller = dbexportFactory($_container); $this->assertSame($controller->controller_name, 'DbexportController', 'controller name should be DbexportController'); } public function testDisplayView() { - $container = $this->container; - require BASE_PATH.'/tests/views/display.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/display.php'; + $controller = displayFactory($_container); $this->assertSame($controller->controller_name, 'DisplayController', 'controller name should be DisplayController'); } public function testDomainsView() { - $container = $this->container; - require BASE_PATH.'/tests/views/domains.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/domains.php'; + $controller = domainsFactory($_container); $this->assertSame($controller->controller_name, 'DomainsController', 'controller name should be DomainsController'); } public function testFulltextView() { - $container = $this->container; - require BASE_PATH.'/tests/views/fulltext.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/fulltext.php'; + $controller = fulltextFactory($_container); $this->assertSame($controller->controller_name, 'FulltextController', 'controller name should be FulltextController'); } public function testFunctionsView() { - $container = $this->container; - require BASE_PATH.'/tests/views/functions.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/functions.php'; + $controller = functionsFactory($_container); $this->assertSame($controller->controller_name, 'FunctionsController', 'controller name should be FunctionsController'); } public function testGroupsView() { - $container = $this->container; - require BASE_PATH.'/tests/views/groups.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/groups.php'; + $controller = groupsFactory($_container); $this->assertSame($controller->controller_name, 'GroupsController', 'controller name should be GroupsController'); } public function testHelpView() { - $container = $this->container; - require BASE_PATH.'/tests/views/help.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/help.php'; + $controller = helpFactory($_container); $this->assertSame($controller->controller_name, 'HelpController', 'controller name should be HelpController'); } public function testHistoryView() { - $container = $this->container; - require BASE_PATH.'/tests/views/history.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/history.php'; + $controller = historyFactory($_container); $this->assertSame($controller->controller_name, 'HistoryController', 'controller name should be HistoryController'); } public function testIndexesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/indexes.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/indexes.php'; + $controller = indexesFactory($_container); $this->assertSame($controller->controller_name, 'IndexesController', 'controller name should be IndexesController'); } public function testInfoView() { - $container = $this->container; - require BASE_PATH.'/tests/views/info.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/info.php'; + $controller = infoFactory($_container); $this->assertSame($controller->controller_name, 'InfoController', 'controller name should be InfoController'); } public function testIntroView() { - $container = $this->container; - require BASE_PATH.'/tests/views/intro.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/intro.php'; + $controller = introFactory($_container); $this->assertSame($controller->controller_name, 'IntroController', 'controller name should be IntroController'); } public function testLanguagesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/languages.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/languages.php'; + $controller = languagesFactory($_container); $this->assertSame($controller->controller_name, 'LanguagesController', 'controller name should be LanguagesController'); } public function testLoginView() { - $container = $this->container; - require BASE_PATH.'/tests/views/login.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/login.php'; + $controller = loginFactory($_container); $this->assertSame($controller->controller_name, 'LoginController', 'controller name should be LoginController'); } - public function testMaterializedviewpropertiesView() - { - $container = $this->container; - require BASE_PATH.'/tests/views/materializedviewproperties.php'; - $this->assertSame($controller->controller_name, 'MaterializedviewpropertiesController', 'controller name should be MaterializedviewpropertiesController'); - } - - public function testMaterializedviewsView() - { - $container = $this->container; - require BASE_PATH.'/tests/views/materializedviews.php'; - $this->assertSame($controller->controller_name, 'MaterializedviewsController', 'controller name should be MaterializedviewsController'); - } - public function testOpclassesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/opclasses.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/opclasses.php'; + $controller = opclassesFactory($_container); $this->assertSame($controller->controller_name, 'OpclassesController', 'controller name should be OpclassesController'); } public function testOperatorsView() { - $container = $this->container; - require BASE_PATH.'/tests/views/operators.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/operators.php'; + $controller = operatorsFactory($_container); $this->assertSame($controller->controller_name, 'OperatorsController', 'controller name should be OperatorsController'); } public function testPrivilegesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/privileges.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/privileges.php'; + $controller = privilegesFactory($_container); $this->assertSame($controller->controller_name, 'PrivilegesController', 'controller name should be PrivilegesController'); } public function testRolesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/roles.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/roles.php'; + $controller = rolesFactory($_container); $this->assertSame($controller->controller_name, 'RolesController', 'controller name should be RolesController'); } public function testRulesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/rules.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/rules.php'; + $controller = rulesFactory($_container); $this->assertSame($controller->controller_name, 'RulesController', 'controller name should be RulesController'); } public function testSchemasView() { - $container = $this->container; - require BASE_PATH.'/tests/views/schemas.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/schemas.php'; + $controller = schemasFactory($_container); $this->assertSame($controller->controller_name, 'SchemasController', 'controller name should be SchemasController'); } public function testSequencesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/sequences.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/sequences.php'; + $controller = sequencesFactory($_container); $this->assertSame($controller->controller_name, 'SequencesController', 'controller name should be SequencesController'); } public function testServersView() { - $container = $this->container; - require BASE_PATH.'/tests/views/servers.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/servers.php'; + $controller = serversFactory($_container); $this->assertSame($controller->controller_name, 'ServersController', 'controller name should be ServersController'); } public function testSqleditView() { - $container = $this->container; - require BASE_PATH.'/tests/views/sqledit.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/sqledit.php'; + $controller = sqleditFactory($_container); $this->assertSame($controller->controller_name, 'SqleditController', 'controller name should be SqleditController'); } public function testSqlView() { - $container = $this->container; - require BASE_PATH.'/tests/views/sql.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/sql.php'; + $controller = sqlFactory($_container); $this->assertSame($controller->controller_name, 'SqlController', 'controller name should be SqlController'); } public function testTablespacesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/tablespaces.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/tablespaces.php'; + $controller = tablespacesFactory($_container); $this->assertSame($controller->controller_name, 'TablespacesController', 'controller name should be TablespacesController'); } - public function testTablesView() - { - $container = $this->container; - require BASE_PATH.'/tests/views/tables.php'; - $this->assertSame($controller->controller_name, 'TablesController', 'controller name should be TablesController'); - } - - public function testTblpropertiesView() - { - $container = $this->container; - require BASE_PATH.'/tests/views/tblproperties.php'; - $this->assertSame($controller->controller_name, 'TblpropertiesController', 'controller name should be TblpropertiesController'); - } - public function testTriggersView() { - $container = $this->container; - require BASE_PATH.'/tests/views/triggers.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/triggers.php'; + $controller = triggersFactory($_container); $this->assertSame($controller->controller_name, 'TriggersController', 'controller name should be TriggersController'); } public function testTypesView() { - $container = $this->container; - require BASE_PATH.'/tests/views/types.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/types.php'; + $controller = typesFactory($_container); $this->assertSame($controller->controller_name, 'TypesController', 'controller name should be TypesController'); } public function testUsersView() { - $container = $this->container; - require BASE_PATH.'/tests/views/users.php'; + $_container = $this->container; + require BASE_PATH . '/tests/views/users.php'; + $controller = usersFactory($_container); $this->assertSame($controller->controller_name, 'UsersController', 'controller name should be UsersController'); } - - public function testViewpropertiesView() - { - $container = $this->container; - require BASE_PATH.'/tests/views/viewproperties.php'; - $this->assertSame($controller->controller_name, 'ViewpropertiesController', 'controller name should be ViewpropertiesController'); - } - - public function testViewsView() - { - $container = $this->container; - require BASE_PATH.'/tests/views/views.php'; - $this->assertSame($controller->controller_name, 'ViewsController', 'controller name should be ViewsController'); - } } diff --git a/tests/views/acinsert.php b/tests/views/acinsert.php index a5e4a014..83e09272 100644 --- a/tests/views/acinsert.php +++ b/tests/views/acinsert.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function acinsertFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\AcinsertController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/aggregates.php b/tests/views/aggregates.php index eea98714..dfa65d0e 100644 --- a/tests/views/aggregates.php +++ b/tests/views/aggregates.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function aggregatesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\AggregatesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/alldb.php b/tests/views/alldb.php index e4096824..cc4686df 100644 --- a/tests/views/alldb.php +++ b/tests/views/alldb.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function alldbFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\AlldbController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/browser.php b/tests/views/browser.php index 33b128f0..da5defef 100644 --- a/tests/views/browser.php +++ b/tests/views/browser.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function browserFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\BrowserController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/casts.php b/tests/views/casts.php index 37868863..17c5df90 100644 --- a/tests/views/casts.php +++ b/tests/views/casts.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function castsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\CastsController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/colproperties.php b/tests/views/colproperties.php index ee7345e0..200dc961 100644 --- a/tests/views/colproperties.php +++ b/tests/views/colproperties.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function colpropertiesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\ColpropertiesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/constraints.php b/tests/views/constraints.php index 7abf15b2..068d9666 100644 --- a/tests/views/constraints.php +++ b/tests/views/constraints.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function constraintsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\ConstraintsController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/conversions.php b/tests/views/conversions.php index 52deec74..4b00d415 100644 --- a/tests/views/conversions.php +++ b/tests/views/conversions.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function conversionsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\ConversionsController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/database.php b/tests/views/database.php index 09b15f66..d6cc21c4 100644 --- a/tests/views/database.php +++ b/tests/views/database.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function databaseFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\DatabaseController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/dataexport.php b/tests/views/dataexport.php index 320ac062..ad554515 100644 --- a/tests/views/dataexport.php +++ b/tests/views/dataexport.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function dataexportFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\DataexportController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/dataimport.php b/tests/views/dataimport.php index 87fb2428..c255f18b 100644 --- a/tests/views/dataimport.php +++ b/tests/views/dataimport.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function dataimportFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\DataimportController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/dbexport.php b/tests/views/dbexport.php index 57483a18..f681e780 100644 --- a/tests/views/dbexport.php +++ b/tests/views/dbexport.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function dbexportFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\DbexportController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/display.php b/tests/views/display.php index 3db8c274..7051e7fd 100644 --- a/tests/views/display.php +++ b/tests/views/display.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function displayFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\DisplayController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/domains.php b/tests/views/domains.php index d60991c1..d56571c0 100644 --- a/tests/views/domains.php +++ b/tests/views/domains.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function domainsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\DomainsController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/fulltext.php b/tests/views/fulltext.php index f99bdbb2..21811bb7 100644 --- a/tests/views/fulltext.php +++ b/tests/views/fulltext.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function fulltextFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\FulltextController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/functions.php b/tests/views/functions.php index 6247a8cc..3cb82b3f 100644 --- a/tests/views/functions.php +++ b/tests/views/functions.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function functionsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\FunctionsController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/groups.php b/tests/views/groups.php index de94990f..d799af75 100644 --- a/tests/views/groups.php +++ b/tests/views/groups.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function groupsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\GroupsController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/help.php b/tests/views/help.php index f690063e..acc1e598 100644 --- a/tests/views/help.php +++ b/tests/views/help.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function helpFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\HelpController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/history.php b/tests/views/history.php index a678d0ce..89a6f4a9 100644 --- a/tests/views/history.php +++ b/tests/views/history.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function historyFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\HistoryController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/indexes.php b/tests/views/indexes.php index 53620e08..0f2ea4d5 100644 --- a/tests/views/indexes.php +++ b/tests/views/indexes.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function indexesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\IndexesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/info.php b/tests/views/info.php index c000a771..ed34a81f 100644 --- a/tests/views/info.php +++ b/tests/views/info.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function infoFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\InfoController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/intro.php b/tests/views/intro.php index 4f8f6b86..415c50c5 100644 --- a/tests/views/intro.php +++ b/tests/views/intro.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function introFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\IntroController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/languages.php b/tests/views/languages.php index 46e02fd4..fd99b635 100644 --- a/tests/views/languages.php +++ b/tests/views/languages.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function languagesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\LanguagesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/login.php b/tests/views/login.php index def89502..5e757462 100644 --- a/tests/views/login.php +++ b/tests/views/login.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function loginFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\LoginController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/materializedviewproperties.php b/tests/views/materializedviewproperties.php index e7bc6940..768213c0 100644 --- a/tests/views/materializedviewproperties.php +++ b/tests/views/materializedviewproperties.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function materializedviewpropertiesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\MaterializedviewpropertiesController($c if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/materializedviews.php b/tests/views/materializedviews.php index c15353a1..bc6c52b4 100644 --- a/tests/views/materializedviews.php +++ b/tests/views/materializedviews.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function materializedviewsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\MaterializedviewsController($container) if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/opclasses.php b/tests/views/opclasses.php index 353622f9..a1b16d35 100644 --- a/tests/views/opclasses.php +++ b/tests/views/opclasses.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function opclassesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\OpclassesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/operators.php b/tests/views/operators.php index 4f7ff984..d7094a75 100644 --- a/tests/views/operators.php +++ b/tests/views/operators.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function operatorsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\OperatorsController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/privileges.php b/tests/views/privileges.php index f9096ee5..baf19a0d 100644 --- a/tests/views/privileges.php +++ b/tests/views/privileges.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function privilegesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\PrivilegesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/roles.php b/tests/views/roles.php index b8b73057..783cbb48 100644 --- a/tests/views/roles.php +++ b/tests/views/roles.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function rolesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\RolesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/rules.php b/tests/views/rules.php index 29f3119f..24ae2abe 100644 --- a/tests/views/rules.php +++ b/tests/views/rules.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function rulesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\RulesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/schemas.php b/tests/views/schemas.php index 8cd3f457..989ee33d 100644 --- a/tests/views/schemas.php +++ b/tests/views/schemas.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function schemasFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\SchemasController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/sequences.php b/tests/views/sequences.php index 79cf2890..a210bae9 100644 --- a/tests/views/sequences.php +++ b/tests/views/sequences.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function sequencesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\SequencesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/servers.php b/tests/views/servers.php index f3fa88ac..7cb8649b 100644 --- a/tests/views/servers.php +++ b/tests/views/servers.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function serversFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\ServersController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/sql.php b/tests/views/sql.php index 00ca2b22..bf5d68b1 100644 --- a/tests/views/sql.php +++ b/tests/views/sql.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function sqlFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\SqlController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/sqledit.php b/tests/views/sqledit.php index 5b75a56c..e90f28ea 100644 --- a/tests/views/sqledit.php +++ b/tests/views/sqledit.php @@ -6,7 +6,7 @@ // Include application functions //require_once '../../src/lib.inc.php'; -$do_render = false; +function sqleditFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\SqleditController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/tables.php b/tests/views/tables.php index 96f31e11..c90ba944 100644 --- a/tests/views/tables.php +++ b/tests/views/tables.php @@ -4,7 +4,7 @@ * PHPPgAdmin v6.0.0-RC9 */ -$do_render = false; +function tablesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -13,3 +13,4 @@ $controller = new \PHPPgAdmin\Controller\TablesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/tablespaces.php b/tests/views/tablespaces.php index 68289217..40f63594 100644 --- a/tests/views/tablespaces.php +++ b/tests/views/tablespaces.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function tablespacesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\TablespacesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/tblproperties.php b/tests/views/tblproperties.php index f9a0b0f8..96acb499 100644 --- a/tests/views/tblproperties.php +++ b/tests/views/tblproperties.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function tblpropertiesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\TblpropertiesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/triggers.php b/tests/views/triggers.php index a482604f..cc6e7682 100644 --- a/tests/views/triggers.php +++ b/tests/views/triggers.php @@ -6,7 +6,7 @@ // Include application functions -$do_render = false; +function triggersFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -15,3 +15,4 @@ $controller = new \PHPPgAdmin\Controller\TriggersController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/types.php b/tests/views/types.php index ad998b86..975cd36d 100644 --- a/tests/views/types.php +++ b/tests/views/types.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function typesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\TypesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/users.php b/tests/views/users.php index 8bfda679..a71aeb0d 100644 --- a/tests/views/users.php +++ b/tests/views/users.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function usersFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\UsersController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/viewproperties.php b/tests/views/viewproperties.php index 55dfd197..8914b7ff 100644 --- a/tests/views/viewproperties.php +++ b/tests/views/viewproperties.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function viewpropertiesFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\ViewpropertiesController($container); if ($do_render) { $controller->render(); } +return $controller; } diff --git a/tests/views/views.php b/tests/views/views.php index 6501fca8..3f4bd439 100644 --- a/tests/views/views.php +++ b/tests/views/views.php @@ -5,7 +5,7 @@ */ // Include application functions -$do_render = false; +function viewsFactory($container) { $do_render = false ; if (!defined('BASE_PATH')) { require_once '../../src/lib.inc.php'; $do_render = true; @@ -14,3 +14,4 @@ $controller = new \PHPPgAdmin\Controller\ViewsController($container); if ($do_render) { $controller->render(); } +return $controller; } |