Compare commits

...

10 Commits

Author SHA1 Message Date
Clemens Schwaighofer
53eef03387 Fixes in DB\IO query detection regex
- start with allow whitespace in front
- returning allows more white space types between keyword and parameter list
2023-02-02 10:27:07 +09:00
Clemens Schwaighofer
5a81445a28 DB\IO table match regex fix
UPDATE with SET can have spaces with variable length before
2023-01-27 11:31:26 +09:00
Clemens Schwaighofer
4bbbd653cd DB\IO fix for regex query detection
Fix for basic query detection:
Simeple starts with
SELECT/WITH/SHOW
INSERT INTO/UPDATE/DELETE FROM
UPDATE

Above does no complex query detection, just if the string starts with this

Fix form table detection for primary key auto set trial.
2023-01-27 11:12:46 +09:00
Clemens Schwaighofer
4c28e6d0ec Change DB\IO Returning check regex
Better regex to only get last returning in query, with proper parameter
check
2023-01-26 16:37:22 +09:00
Clemens Schwaighofer
66b7e81463 Bug fix in DB\IO for EOM string build queries with returning
on EOM string build queries it was not checked that RETURNING could have
no space in front.

Fixed and updated test calls
2023-01-25 16:47:31 +09:00
Clemens Schwaighofer
cf58f86802 Remove not needed ?? '' in ACL\Login 2023-01-16 14:29:25 +09:00
Clemens Schwaighofer
ff644310cd Readme file update 2023-01-11 09:22:18 +09:00
Clemens Schwaighofer
58988b9c0f Rename edit schemes pages to schemas 2023-01-11 09:12:56 +09:00
Clemens Schwaighofer
fe75f1d724 Add missing table arrays and name fix schim
missed two table arrays as class EditVisibleGroup and EditAccess

also fix wrong name for EditSchemas (wrong: EditSchemes) with a shim
lookup.

edit_schemes.php file will stay the same for now.
2023-01-11 07:06:28 +09:00
Clemens Schwaighofer
0607cdc3be Add logger $log public entry in Form class
We need that for sub calls to debugger from TableArray loads
2023-01-10 18:19:20 +09:00
13 changed files with 596 additions and 123 deletions

View File

@@ -155,37 +155,57 @@ final class CoreLibsDBIOTest extends TestCase
$db->dbExec("DROP TABLE table_without_primary_key");
$db->dbExec("DROP TABLE test_meta");
}
$base_table = "uid VARCHAR, " // uid is for internal reference tests
. "row_int INT, "
. "row_numeric NUMERIC, "
. "row_varchar VARCHAR, "
. "row_varchar_literal VARCHAR, "
. "row_json JSON, "
. "row_jsonb JSONB, "
. "row_bytea BYTEA, "
. "row_timestamp TIMESTAMP WITHOUT TIME ZONE, "
. "row_date DATE, "
. "row_interval INTERVAL, "
. "row_array_int INT ARRAY, "
. "row_array_varchar VARCHAR ARRAY"
. ") WITHOUT OIDS";
// uid is for internal reference tests
$base_table = <<<EOM
uid VARCHAR,
row_int INT,
row_numeric NUMERIC,
row_varchar VARCHAR,
row_varchar_literal VARCHAR,
row_json JSON,
row_jsonb JSONB,
row_bytea BYTEA,
row_timestamp TIMESTAMP WITHOUT TIME ZONE,
row_date DATE,
row_interval INTERVAL,
row_array_int INT ARRAY,
row_array_varchar VARCHAR ARRAY
)
WITHOUT OIDS
EOM;
// create the tables
$db->dbExec(
"CREATE TABLE table_with_primary_key ("
// primary key name is table + '_id'
<<<EOM
CREATE TABLE table_with_primary_key (
table_with_primary_key_id SERIAL PRIMARY KEY,
$base_table
EOM
/* "CREATE TABLE table_with_primary_key ("
// primary key name is table + '_id'
. "table_with_primary_key_id SERIAL PRIMARY KEY, "
. $base_table
. $base_table */
);
$db->dbExec(
"CREATE TABLE table_without_primary_key ("
. $base_table
<<<EOM
CREATE TABLE table_without_primary_key (
$base_table
EOM
/* "CREATE TABLE table_without_primary_key ("
. $base_table */
);
// create simple table for meta test
$db->dbExec(
"CREATE TABLE test_meta ("
<<<EOM
CREATE TABLE test_meta (
row_1 VARCHAR,
row_2 INT
) WITHOUT OIDS
EOM
/* "CREATE TABLE test_meta ("
. "row_1 VARCHAR, "
. "row_2 INT"
. ") WITHOUT OIDS"
. ") WITHOUT OIDS" */
);
// set some test schema
$db->dbExec("CREATE SCHEMA IF NOT EXISTS testschema");
@@ -3893,6 +3913,38 @@ final class CoreLibsDBIOTest extends TestCase
]
]
],
// same but as EOM
'single insert (PK), EOM string' => [
<<<EOM
INSERT INTO table_with_primary_key (
row_varchar, row_varchar_literal, row_int, row_date
) VALUES (
'Text', 'Other', 123, '2022-03-01'
)
RETURNING row_varchar, row_varchar_literal, row_int, row_date
EOM,
null,
null,
null,
[
'row_varchar' => 'Text',
'row_varchar_literal' => 'Other',
'row_int' => 123,
'row_date' => '2022-03-01',
// 'table_with_primary_key_id' => "/^\d+$/",
'table_with_primary_key_id' => $table_with_primary_key_id + 2,
],
[
0 => [
'row_varchar' => 'Text',
'row_varchar_literal' => 'Other',
'row_int' => 123,
'row_date' => '2022-03-01',
// 'table_with_primary_key_id' => "/^\d+$/",
'table_with_primary_key_id' => $table_with_primary_key_id + 2,
]
]
],
// double insert (PK)
'dobule insert (PK)' => [
"INSERT INTO table_with_primary_key "
@@ -3910,14 +3962,14 @@ final class CoreLibsDBIOTest extends TestCase
'row_varchar_literal' => 'Other',
'row_int' => 123,
'row_date' => '2022-03-01',
'table_with_primary_key_id' => $table_with_primary_key_id + 2,
'table_with_primary_key_id' => $table_with_primary_key_id + 3,
],
1 => [
'row_varchar' => 'Foxtrott',
'row_varchar_literal' => 'Tango',
'row_int' => 789,
'row_date' => '1982-10-15',
'table_with_primary_key_id' => $table_with_primary_key_id + 3,
'table_with_primary_key_id' => $table_with_primary_key_id + 4,
],
],
[
@@ -3926,14 +3978,14 @@ final class CoreLibsDBIOTest extends TestCase
'row_varchar_literal' => 'Other',
'row_int' => 123,
'row_date' => '2022-03-01',
'table_with_primary_key_id' => $table_with_primary_key_id + 2,
'table_with_primary_key_id' => $table_with_primary_key_id + 3,
],
1 => [
'row_varchar' => 'Foxtrott',
'row_varchar_literal' => 'Tango',
'row_int' => 789,
'row_date' => '1982-10-15',
'table_with_primary_key_id' => $table_with_primary_key_id + 3,
'table_with_primary_key_id' => $table_with_primary_key_id + 4,
],
]
],
@@ -3961,7 +4013,35 @@ final class CoreLibsDBIOTest extends TestCase
'row_date' => '2022-03-01',
]
]
]
],
// same as above but as EOM string
'single insert (No PK), EOM string' => [
<<<EOM
INSERT INTO table_without_primary_key (
row_varchar, row_varchar_literal, row_int, row_date
) VALUES (
'Text', 'Other', 123, '2022-03-01'
)
RETURNING row_varchar, row_varchar_literal, row_int, row_date
EOM,
null,
null,
null,
[
'row_varchar' => 'Text',
'row_varchar_literal' => 'Other',
'row_int' => 123,
'row_date' => '2022-03-01',
],
[
0 => [
'row_varchar' => 'Text',
'row_varchar_literal' => 'Other',
'row_int' => 123,
'row_date' => '2022-03-01',
]
]
],
];
}
@@ -4008,11 +4088,13 @@ final class CoreLibsDBIOTest extends TestCase
$this->assertEquals(
$expected_ret_ext,
$returning_ext
$returning_ext,
'Returning extended failed'
);
$this->assertEquals(
$expected_ret_arr,
$returning_arr
$returning_arr,
'Returning Array failed'
);
// print "EXT: " . print_r($returning_ext, true) . "\n";

View File

@@ -0,0 +1,7 @@
-- Fix for edit_schemes.php DB settings
-- will not change file name only visual name
UPDATE edit_page SET name = 'Edit Schemas' WHERE filename = 'edit_schemes.php';
-- will change BOTH, must have file name renamed too
UPDATE edit_page SET name = 'Edit Schemas', filename = 'edit_schemas.php' WHERE filename = 'edit_schemes.php';

View File

@@ -1,103 +1,128 @@
# Upgrade to Version 6
* remove old `lib/CoreLibs` and copy the new over
* copy `config/config.php`
* install composer if not installed `composer init` and `composer install`
* update composer.json
```json
* remove old `lib/CoreLibs` and copy the new over
* copy `config/config.php`
* install composer if not installed `composer init` and `composer install`
* update composer.json
```json
"autoload": {
"classmap": [
"lib/"
]
},
```
Run to update autoloader list
```sh
composer dump-autoload
```
* copy `includes/edit_base.inc`
* add session start in the top header block where the `header()` calls are
* copy `includes/edit_base.inc`
* add session start in the top header block where the `header()` calls are
```php
// start session
CoreLibs\Create\Session::startSession();
```
* update all header calls if needed to add new log type call
```php
* update all header calls if needed to add new log type call
```php
// create logger
$log = new CoreLibs\Debug\Logging([
'log_folder' => BASE . LOG,
'file_id' => LOG_FILE_ID,
'print_file_date' => true,
'debug_all' => $DEBUG_ALL ?? false,
'echo_all' => $ECHO_ALL ?? false,
'print_all' => $PRINT_ALL ?? false,
'log_folder' => BASE . LOG,
'file_id' => LOG_FILE_ID,
'print_file_date' => true,
'debug_all' => $DEBUG_ALL ?? false,
'echo_all' => $ECHO_ALL ?? false,
'print_all' => $PRINT_ALL ?? false,
]);
```
* add a db class
* add a db class
```php
// db config with logger
$db = new CoreLibs\DB\IO(DB_CONFIG, $log);
```
* login class needs to have db and logger added
* login class needs to have db and logger added
```php
// login & page access check
$login = new CoreLibs\ACL\Login($db, $log);
```
* update language class
```php
// pre auto detect language after login
$locale = \CoreLibs\Language\GetLocale::setLocale();
// set lang and pass to smarty/backend
$l10n = new \CoreLibs\Language\L10n(
$locale['locale'],
$locale['domain'],
$locale['path'],
$locale['locale'],
$locale['domain'],
$locale['path'],
);
```
* smarty needs language
```php
$smarty = new CoreLibs\Template\SmartyExtend($l10n, $locale);
```
* admin backend also needs logger
```php
$cms = new CoreLibs\Admin\Backend($db, $log, $l10n, $locale);
```
* update and `$cms` or similar calls so db is in `$cms->db->...` and log are in `$cms->log->...`
* update all `config.*.php` files where needed
* check config.master.php for `BASE_NAME` and `G_TITLE` and set them in the `.env` file so the `config.master.php` can be copied as os
* If not doable, see changed below in `config.master.php` must remove old auto loder and `FLASH` constant at least
**REMOVE:**
```php
/************* AUTO LOADER *******************/
// read auto loader
require BASE . LIB . 'autoloader.php';
```
**UPDATE:**
```php
// po langs [DEPRECAED: use LOCALE]
define('LANG', 'lang' . DIRECTORY_SEPARATOR);
// po locale file
define('LOCALE', 'locale' . DIRECTORY_SEPARATOR);
```
```php
// SSL host name
// define('SSL_HOST', $_ENV['SSL_HOST'] ?? '');
```
```php
// define full regex
define('PASSWORD_REGEX', "/^"
. (defined('PASSWORD_LOWER') ? PASSWORD_LOWER : '')
. (defined('PASSWORD_UPPER') ? PASSWORD_UPPER : '')
. (defined('PASSWORD_NUMBER') ? PASSWORD_NUMBER : '')
. (defined('PASSWORD_SPECIAL') ? PASSWORD_SPECIAL : '')
. "[A-Za-z\d" . PASSWORD_SPECIAL_RANGE . "]{" . PASSWORD_MIN_LENGTH . "," . PASSWORD_MAX_LENGTH . "}$/");
. (defined('PASSWORD_LOWER') ? PASSWORD_LOWER : '')
. (defined('PASSWORD_UPPER') ? PASSWORD_UPPER : '')
. (defined('PASSWORD_NUMBER') ? PASSWORD_NUMBER : '')
. (defined('PASSWORD_SPECIAL') ? PASSWORD_SPECIAL : '')
. "[A-Za-z\d" . PASSWORD_SPECIAL_RANGE . "]{" . PASSWORD_MIN_LENGTH . "," . PASSWORD_MAX_LENGTH . "}$/");
```
```php
/************* LAYOUT WIDTHS *************/
define('PAGE_WIDTH', '100%');
define('CONTENT_WIDTH', '100%');
```
```php
/************* OVERALL CONTROL NAMES *************/
// BELOW has HAS to be changed
@@ -105,6 +130,7 @@ define('CONTENT_WIDTH', '100%');
// only alphanumeric characters, strip all others
define('BASE_NAME', preg_replace('/[^A-Za-z0-9]/', '', $_ENV['BASE_NAME'] ?? ''));
```
```php
/************* LANGUAGE / ENCODING *******/
// default lang + encoding
@@ -112,53 +138,63 @@ define('DEFAULT_LOCALE', 'en_US.UTF-8');
// default web page encoding setting
define('DEFAULT_ENCODING', 'UTF-8');
```
```php
// BAIL ON MISSING DB CONFIG:
// we have either no db selction for this host but have db config entries
// or we have a db selection but no db config as array or empty
// or we have a selection but no matching db config entry
if (
(!isset($SITE_CONFIG[HOST_NAME]['db_host']) && count($DB_CONFIG)) ||
(isset($SITE_CONFIG[HOST_NAME]['db_host']) &&
// missing DB CONFIG
((is_array($DB_CONFIG) && !count($DB_CONFIG)) ||
!is_array($DB_CONFIG) ||
// has DB CONFIG but no match
empty($DB_CONFIG[$SITE_CONFIG[HOST_NAME]['db_host']]))
)
(!isset($SITE_CONFIG[HOST_NAME]['db_host']) && count($DB_CONFIG)) ||
(isset($SITE_CONFIG[HOST_NAME]['db_host']) &&
// missing DB CONFIG
((is_array($DB_CONFIG) && !count($DB_CONFIG)) ||
!is_array($DB_CONFIG) ||
// has DB CONFIG but no match
empty($DB_CONFIG[$SITE_CONFIG[HOST_NAME]['db_host']]))
)
) {
echo 'No matching DB config found for: "' . HOST_NAME . '". Contact Administrator';
exit;
echo 'No matching DB config found for: "' . HOST_NAME . '". Contact Administrator';
exit;
}
```
```php
// remove SITE_LANG
define('SITE_LOCALE', $SITE_CONFIG[HOST_NAME]['site_locale'] ?? DEFAULT_LOCALE);
define('SITE_ENCODING', $SITE_CONFIG[HOST_NAME]['site_encoding'] ?? DEFAULT_ENCODING);
```
```php
/************* GENERAL PAGE TITLE ********/
define('G_TITLE', $_ENV['G_TITLE'] ?? '');
```
* move all login passweords into the `.env` file in the `configs/` folder
in the `.env` file
```
```sql
DB_NAME.TEST=some_database
...
```
In the config then
```php
'db_name' => $_ENV['DB_NAME.TEST'] ?? '',
```
* config.host.php update
must add site_locale (site_lang + site_encoding)
remove site_lang
```php
// lang + encoding
'site_locale' => 'en_US.UTF-8',
// site language
'site_encoding' => 'UTF-8',
// lang + encoding
'site_locale' => 'en_US.UTF-8',
// site language
'site_encoding' => 'UTF-8',
```
* copy `layout/admin/javascript/edit.jq.js`
* check other javacsript files if needed (`edit.jq.js`)

View File

@@ -2,19 +2,20 @@
## Code Standard
* Uses PSR-12
* tab indent instead of 4 spaces indent
* Warning at 120 character length, error at 240 character length
* Uses PSR-12
* tab indent instead of 4 spaces indent
* Warning at 120 character length, error at 240 character length
## General information
Base PHP class files to setup any project
* login
* database wrapper
* basic helper class for debugging and other features
* admin/frontend split
* domain controlled database/settings split
* dynamic layout groups
* login
* database wrapper
* basic helper class for debugging and other features
* admin/frontend split
* domain controlled database/settings split
* dynamic layout groups
## NOTE
@@ -50,7 +51,6 @@ pslam is setup but not configured
With phpunit (`4dev/checking/phpunit.sh`)
`phpunit -c $phpunit.xml 4dev/tests/`
## Other Notes
### Session used
@@ -58,29 +58,38 @@ With phpunit (`4dev/checking/phpunit.sh`)
The following classes use _SESSION
The main one is ACL\Login, this class will fail without a session started
* \CoreLibs\ACL\Login
* \CoreLibs\Admin\Backend
* \CoreLibs\Output\Form\Generate
* \CoreLibs\Output\Form\Token
* \CoreLibs\Template\SmartyExtend
* \CoreLibs\ACL\Login
* \CoreLibs\Admin\Backend
* \CoreLibs\Output\Form\Generate
* \CoreLibs\Output\Form\Token
* \CoreLibs\Template\SmartyExtend
### Class extends
The following classes extend these classes
* \CoreLibs\ACL\Login extends \CoreLibs\DB\IO
* \CoreLibs\Admin\Backend extends \CoreLibs\DB\IO
* \CoreLibs\DB\Extended\ArrayIO extends \CoreLibs\DB\IO
* \CoreLibs\Output\Form\Generate extends \CoreLibs\DB\Extended\ArrayIO
* \CoreLibs\Template\SmartyExtend extends SmartyBC
* \CoreLibs\ACL\Login extends \CoreLibs\DB\IO
* \CoreLibs\Admin\Backend extends \CoreLibs\DB\IO
* \CoreLibs\DB\Extended\ArrayIO extends \CoreLibs\DB\IO
* \CoreLibs\Output\Form\Generate extends \CoreLibs\DB\Extended\ArrayIO
* \CoreLibs\Template\SmartyExtend extends SmartyBC
### Class used
The following classes use the following classes
* \CoreLibs\ACL\Login uses \CoreLibs\Debug\Logger, \CoreLibs\Language\L10n
* \CoreLibs\DB\IO uses \CoreLibs\Debug\Logger, \CoreLibs\DB\SQL\PgSQL
* \CoreLibs\Admin\Backend uses \CoreLibs\Debug\Logger, \CoreLibs\Language\L10n
* \CoreLibs\Output\Form\Generate uses \CoreLibs\Debug\Logger, \CoreLibs\Language\L10n
* \CoreLibs\ACL\Login uses \CoreLibs\Debug\Logging, \CoreLibs\Language\L10n
* \CoreLibs\DB\IO uses \CoreLibs\Debug\Logging, \CoreLibs\DB\SQL\PgSQL
* \CoreLibs\Admin\Backend uses \CoreLibs\Debug\Logging, \CoreLibs\Language\L10n
* \CoreLibs\Output\Form\Generate uses \CoreLibs\Debug\Logging, \CoreLibs\Language\L10n
* \CoreLibs\Template\SmartyExtend uses \CoreLibs\Language\L10n
* \CoreLibs\Language\L10n uses FileReader, GetTextReader
* \CoreLibs\Admin\EditBase uses \CoreLibs\Debug\Logging, \CoreLibs\Language\L10n
### Class internal load
Loads classes internal (not passed in, not extend)
* \CoreLibs\Admin\EditBase loads \CoreLibs\Template\SmartyExtend, \CoreLibs\Output\Form\Generate
* \CoreLibs\Output\From\Generate loads \CoreLibs\Debug\Logging, \CoreLibs\Language\L10n if not passed on
* \CoreLibs\Output\From\Generate loads \CoreLibs\Output\From\TableArrays

View File

@@ -118,7 +118,8 @@ print "<b>TRUNCATE test_foobar</b><br>";
$query = "TRUNCATE test_foobar";
$db->dbExec($query);
$status = $db->dbExec("INSERT INTO test_foo (test) VALUES ('FOO TEST " . time() . "') RETURNING test");
$status = $db->dbExec("INSERT INTO test_foo (test, number_a) VALUES "
. "('FOO TEST " . time() . "', 1) RETURNING test, number_a");
print "DIRECT INSERT STATUS: " . Support::printToString($status) . " |<br>"
. "QUERY: " . $db->dbGetQuery() . " |<br>"
. "DB OBJECT: <pre>" . print_r($status, true) . "</pre>| "
@@ -127,17 +128,50 @@ print "DIRECT INSERT STATUS: " . Support::printToString($status) . " |<br>"
. "RETURNING EXT[test]: " . print_r($db->dbGetReturningExt('test'), true) . " | "
. "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
var_dump($db->dbGetReturningExt());
// same as above but use an EOM string
$some_time = time();
$query = <<<EOM
INSERT INTO test_foo (
test, number_a
) VALUES (
'EOM FOO TEST $some_time', 1
)
RETURNING test, number_a
EOM;
$status = $db->dbExec($query);
print "EOM STRING DIRECT INSERT STATUS: " . Support::printToString($status) . " |<br>"
. "QUERY: " . $db->dbGetQuery() . " |<br>"
. "DB OBJECT: <pre>" . print_r($status, true) . "</pre>| "
. "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING EXT[test]: " . print_r($db->dbGetReturningExt('test'), true) . " | "
. "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
var_dump($db->dbGetReturningExt());
// should throw deprecated error
// $db->getReturningExt();
$last_insert_pk = $db->dbGetInsertPK();
print "DIRECT INSERT PREVIOUS INSERTED: "
. print_r($db->dbReturnRow("SELECT test_foo_id, test FROM test_foo "
. "WHERE test_foo_id = " . $db->dbGetInsertPK()), true) . "<br>";
. "WHERE test_foo_id = " . $last_insert_pk), true) . "<br>";
$q = <<<EOM
SELECT
test_foo_id, test
FROM test_foo
WHERE test_foo_id = $last_insert_pk;
EOM;
print "EOM READ OF PREVIOUS INSERTED: " . print_r($db->dbReturnRow($q), true) . "<br>";
print "LAST ERROR: " . $db->dbGetLastError() . "<br>";
print "<br>";
// PREPARED INSERT
$db->dbPrepare("ins_test_foo", "INSERT INTO test_foo (test) VALUES ($1) RETURNING test");
$status = $db->dbExecute("ins_test_foo", ['BAR TEST ' . time()]);
print "PREPARE INSERT[ins_test_foo] STATUS: " . Support::printToString($status) . " |<br>"
. "QUERY: " . $db->dbGetQuery() . " |<br>"
. "QUERY: " . $db->dbGetPrepareCursorValue('ins_test_foo', 'query') . " |<br>"
. "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING RETURN: " . print_r($db->dbGetReturningArray(), true) . "<br>";
@@ -150,6 +184,23 @@ print "PREPARE CURSOR RETURN:<br>";
foreach (['pk_name', 'count', 'query', 'returning_id'] as $key) {
print "KEY: " . $key . ': ' . $db->dbGetPrepareCursorValue('ins_test_foo', $key) . "<br>";
}
$query = <<<EOM
INSERT INTO test_foo (
test
) VALUES (
$1
)
RETURNING test
EOM;
$db->dbPrepare("ins_test_foo_eom", $query);
$status = $db->dbExecute("ins_test_foo_eom", ['EOM BAR TEST ' . time()]);
print "EOM STRING PREPARE INSERT[ins_test_foo_eom] STATUS: " . Support::printToString($status) . " |<br>"
. "QUERY: " . $db->dbGetPrepareCursorValue('ins_test_foo_eom', 'query') . " |<br>"
. "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING RETURN: " . print_r($db->dbGetReturningArray(), true) . "<br>";
// returning test with multiple entries
// $status = $db->db_exec(
// "INSERT INTO test_foo (test) VALUES "
@@ -172,6 +223,26 @@ print "DIRECT MULTIPLE INSERT WITH RETURN STATUS: " . Support::printToString($st
. "RETURNING EXT[test]: " . print_r($db->dbGetReturningExt('test'), true) . " | "
. "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
$t_1 = time();
$t_2 = time();
$t_3 = time();
$query = <<<EOM
INSERT INTO test_foo (
test
) VALUES
('EOM BAR 1 $t_1'),
('EOM BAR 2 $t_2'),
('EOM BAR 3 $t_3')
RETURNING test_foo_id, test
EOM;
$status = $db->dbExec($query);
print "EOM STRING DIRECT MULTIPLE INSERT WITH RETURN STATUS: " . Support::printToString($status) . " |<br>"
. "QUERY: " . $db->dbGetQuery() . " |<br>"
. "PRIMARY KEYS: " . print_r($db->dbGetInsertPK(), true) . " | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING EXT[test]: " . print_r($db->dbGetReturningExt('test'), true) . " | "
. "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
// no returning, but not needed ;
$status = $db->dbExec("INSERT INTO test_foo (test) VALUES ('FOO; TEST " . time() . "')");
print "DIRECT INSERT NO RETURN STATUS: " . Support::printToString($status) . " |<br>"
@@ -240,6 +311,24 @@ if ($db->dbPrepare('sel_test_foo', $q_prep) === false) {
. $db->dbGetLastError() . "/" . $db->dbGetLastWarning() . "/"
. "<pre>" . print_r($db->dbGetCombinedErrorHistory(), true) . "</pre><br>";
}
echo "<hr>";
print "EOM STYLE STRINGS<br>";
$test_bar = $db->dbEscapeLiteral('SOMETHING DIFFERENT');
// Test EOM block
$q = <<<EOM
SELECT test_foo_id, test, some_bool, string_a, number_a,
-- comment
number_a_numeric, some_time
FROM test_foo
WHERE test = $test_bar
ORDER BY test_foo_id DESC LIMIT 5
EOM;
while (is_array($res = $db->dbReturn($q))) {
print "ROW: <pre>" . print_r($res, true) . "</pre><br>";
}
echo "<hr>";
// NOTE: try to replacate connection still exists if script is run a second time
// open pg bouncer connection
$db_pgb = new CoreLibs\DB\IO($DB_CONFIG['test_pgbouncer'], $log);

View File

@@ -1633,7 +1633,7 @@ EOM;
$this->session->checkActiveSession() === true &&
!empty($_SESSION['DEFAULT_LOCALE'])
) {
$locale = $_SESSION['DEFAULT_LOCALE'] ?? '';
$locale = $_SESSION['DEFAULT_LOCALE'];
} else {
$locale = (defined('SITE_LOCALE') && !empty(SITE_LOCALE)) ?
SITE_LOCALE :

View File

@@ -266,16 +266,18 @@ class IO
// 1: read new, keep at end, clean before new run
// 2: read new, clean at the end (temporary cache)
// 3: never cache
/** @var int */
/** @var int use cache (default) in dbReturn */
public const USE_CACHE = 0;
/** @var int */
/** @var int reset cache and read new in dbReturn */
public const READ_NEW = 1;
/** @var int */
/** @var int clear cache after read in dbeEturn */
public const CLEAR_CACHE = 2;
/** @var int */
/** @var int do not use any cache in dbReturn */
public const NO_CACHE = 3;
/** @var string */
/** @var string default hash type */
public const ERROR_HASH_TYPE = 'adler32';
/** @var string regex to get returning with matches at position 1 */
public const REGEX_RETURNING = '/\s+returning\s+(.+?);?$/i';
// recommend to set private/protected and only allow setting via method
// can bet set from outside
@@ -573,14 +575,14 @@ class IO
/**
* checks if query is a SELECT, SHOW or WITH, if not error, 0 return
* NOTE:
* Query needs to start with SELECT, SHOW or WITH. if starts with "with" it is ignored
* Query needs to start with SELECT, SHOW or WITH
* @param string $query query to check
* @return bool true if matching, false if not
*/
private function __checkQueryForSelect(string $query): bool
{
// perhaps allow spaces before select ?!?
if (preg_match("/^(select|show|with) /i", $query)) {
// change to string starts with?
if (preg_match("/^\s*(?:SELECT|SHOW|WITH)\s/i", $query)) {
return true;
}
return false;
@@ -597,10 +599,10 @@ class IO
*/
private function __checkQueryForInsert(string $query, bool $pure = false): bool
{
if ($pure && preg_match("/^insert /i", $query)) {
if ($pure && preg_match("/^\s*INSERT\s+?INTO\s/i", $query)) {
return true;
}
if (!$pure && preg_match("/^(insert|update|delete) /i", $query)) {
if (!$pure && preg_match("/^\s*(?:INSERT\s+?INTO|DELETE\s+?FROM|UPDATE)\s/i", $query)) {
return true;
}
return false;
@@ -614,7 +616,7 @@ class IO
*/
private function __checkQueryForUpdate(string $query): bool
{
if (preg_match("/^update /i", $query)) {
if (preg_match("/^\s*UPDATE\s?(.+)/i", $query)) {
return true;
}
return false;
@@ -879,12 +881,33 @@ class IO
private function __dbReturnTable(string $query): array
{
$matches = [];
if (preg_match("/^SELECT /i", $query)) {
preg_match("/ (FROM) \"?(([\w_]+)\.)?([\w_]+)\"? /i", $query, $matches);
$schema_table = [];
if ($this->__checkQueryForSelect($query)) {
// only selects the first one, this is more a fallback
// MATCHES 1 (call), 3 (schema), 4 (table)
preg_match("/\s+?(FROM)\s+?([\"'])?(?:([\w_]+)\.)?([\w_]+)(?:\2)?\s?/i", $query, $matches);
$schema_table = [
$matches[3] ?? '',
$matches[4] ?? '',
];
} else {
preg_match("/(INSERT INTO|DELETE FROM|UPDATE) \"?(([\w_]+)\.)?([\w_]+)\"? /i", $query, $matches);
preg_match(
// must start with
// INSERT INTO (table)
// DELETE FROM (table)
// UPDATE (table) SET
// MATCHES 1 (call), 4 (schema), 5 (table)
"/^\s*(INSERT\s+?INTO|DELETE\s+?FROM|(UPDATE))\s+?"
. "([\"'])?(?:([\w_]+)\.)?([\w_]+)(?:\3)?\s?(?(2)\s+?SET|)/i",
$query,
$matches
);
$schema_table = [
$matches[4] ?? '',
$matches[5] ?? ''
];
}
return [$matches[3] ?? '', $matches[4] ?? ''];
return $schema_table;
}
/**
@@ -1007,7 +1030,7 @@ class IO
$this->pk_name_table[$table] : 'NULL';
}
if (
!preg_match("/ returning /i", $this->query) &&
!preg_match(self::REGEX_RETURNING, $this->query) &&
$this->pk_name && $this->pk_name != 'NULL'
) {
// check if this query has a ; at the end and remove it
@@ -1016,7 +1039,9 @@ class IO
$this->query = !is_string($__query) ? $this->query : $__query;
$this->query .= " RETURNING " . $this->pk_name;
$this->returning_id = true;
} elseif (preg_match("/ returning (.*)/i", $this->query, $matches)) {
} elseif (
preg_match(self::REGEX_RETURNING, $this->query, $matches)
) {
if ($this->pk_name && $this->pk_name != 'NULL') {
// add the primary key if it is not in the returning set
if (!preg_match("/$this->pk_name/", $matches[1])) {
@@ -1030,7 +1055,7 @@ class IO
// if we have an UPDATE and RETURNING, flag for true, but do not add anything
if (
$this->__checkQueryForUpdate($this->query) &&
preg_match("/ returning (.*)/i", $this->query, $matches)
preg_match(self::REGEX_RETURNING, $this->query, $matches)
) {
$this->returning_id = true;
}
@@ -2288,11 +2313,14 @@ class IO
$this->prepare_cursor[$stm_name]['pk_name'] = $pk_name;
}
// if no returning, then add it
if (!preg_match("/ returning /i", $query) && $this->prepare_cursor[$stm_name]['pk_name']) {
if (
!preg_match(self::REGEX_RETURNING, $query) &&
$this->prepare_cursor[$stm_name]['pk_name']
) {
$query .= " RETURNING " . $this->prepare_cursor[$stm_name]['pk_name'];
$this->prepare_cursor[$stm_name]['returning_id'] = true;
} elseif (
preg_match("/ returning (.*)/i", $query, $matches) &&
preg_match(self::REGEX_RETURNING, $query, $matches) &&
$this->prepare_cursor[$stm_name]['pk_name']
) {
// if returning exists but not pk_name, add it

View File

@@ -294,6 +294,9 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
// language
/** @var \CoreLibs\Language\L10n */
public $l;
// log
/** @var \CoreLibs\Debug\Logging */
public $log;
// now some default error msgs (english)
/** @var array<mixed> */
@@ -319,13 +322,10 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
?array $locale = null,
?array $table_arrays = null,
) {
// init logger if not set
$this->log = $log ?? new \CoreLibs\Debug\Logging();
// don't log per class
if ($log !== null) {
$log->setLogPer('class', false);
}
// replace any non valid variable names
// TODO extract only alphanumeric and _ after . to _ replacement
$this->my_page_name = str_replace(['.'], '_', System::getPageName(System::NO_EXTENSION));
$this->log->setLogPer('class', false);
// if pass on locale is null
if ($locale === null) {
$locale = \CoreLibs\Language\GetLocale::setLocale();
@@ -350,6 +350,13 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
$this->base_acl_level = (int)$_SESSION['BASE_ACL_LEVEL'];
$this->acl_admin = (int)$_SESSION['ADMIN'];
// replace any non valid variable names and set my page name
$this->my_page_name = str_replace(
['.'],
'_',
System::getPageName(System::NO_EXTENSION)
);
// first check if we have a in page override as $table_arrays[page name]
if (
isset($table_arrays[System::getPageName(System::NO_EXTENSION)]) &&
@@ -374,7 +381,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
$db_config,
$config_array['table_array'],
$config_array['table_name'],
$log ?? new \CoreLibs\Debug\Logging(),
$this->log,
// set the ACL
$this->base_acl_level,
$this->acl_admin
@@ -465,12 +472,22 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
*/
private function loadTableArray()
{
// note: it schould be Schemas but an original type made it to this
// this file is kept for the old usage, new one should be EditSchemas
$table_array_shim = [
'EditSchemes' => 'EditSchemas'
];
// camel case $this->my_page_name from foo_bar_note to FooBarNote
$page_name_camel_case = '';
foreach (explode('_', $this->my_page_name) as $part) {
$page_name_camel_case .= ucfirst($part);
}
$class_string = __NAMESPACE__ . "\\TableArrays\\" . $page_name_camel_case;
$class_string = __NAMESPACE__ . "\\TableArrays\\"
. (
// shim lookup
$table_array_shim[$page_name_camel_case] ??
$page_name_camel_case
);
try {
/** @var \CoreLibs\Output\Form\TableArraysInterface|false $class */
$class = new $class_string($this);

View File

@@ -0,0 +1,140 @@
<?php
declare(strict_types=1);
namespace CoreLibs\Output\Form\TableArrays;
class EditAccess implements \CoreLibs\Output\Form\TableArraysInterface
{
/** @var \CoreLibs\Output\Form\Generate */
private $form;
/**
* constructor
* @param \CoreLibs\Output\Form\Generate $form base form class
*/
public function __construct(\CoreLibs\Output\Form\Generate $form)
{
$this->form = $form;
$this->form->log->debug('CLASS LOAD', __NAMESPACE__ . __CLASS__);
}
/**
* return the table array
*
* @return array<mixed>
*/
public function setTableArray(): array
{
return [
'table_array' => [
'edit_access_id' => [
'value' => $_POST['edit_access_id'] ?? '',
'type' => 'hidden',
'pk' => 1
],
'name' => [
'value' => $_POST['name'] ?? '',
'output_name' => 'Access Group Name',
'mandatory' => 1,
'type' => 'text',
'error_check' => 'alphanumericspace|unique'
],
'description' => [
'value' => $_POST['description'] ?? '',
'output_name' => 'Description',
'type' => 'textarea'
],
'color' => [
'value' => $_POST['color'] ?? '',
'output_name' => 'Color',
'mandatory' => 0,
'type' => 'text',
'size' => 10,
'length' => 9,
'error_check' => 'custom',
// FIXME: update regex check for hex/rgb/hsl with color check class
'error_regex' => '/^#([\dA-Fa-f]{6}|[\dA-Fa-f]{8})$/',
'error_example' => '#F6A544'
],
'enabled' => [
'value' => $_POST['enabled'] ?? 0,
'output_name' => 'Enabled',
'type' => 'binary',
'int' => 1, // OR 'bool' => 1
'element_list' => [
'1' => 'Yes',
'0' => 'No'
],
],
'protected' => [
'value' => $_POST['protected'] ?? 0,
'output_name' => 'Protected',
'type' => 'binary',
'int' => 1,
'element_list' => [
'1' => 'Yes',
'0' => 'No'
],
],
'additional_acl' => [
'value' => $_POST['additional_acl'] ?? '',
'output_name' => 'Additional ACL (as JSON)',
'type' => 'textarea',
'error_check' => 'json',
'rows' => 10,
'cols' => 60
],
],
'table_name' => 'edit_access',
"load_query" => "SELECT edit_access_id, name FROM edit_access ORDER BY name",
'show_fields' => [
[
'name' => 'name'
],
],
'element_list' => [
'edit_access_data' => [
'output_name' => 'Edit Access Data',
'delete_name' => 'remove_edit_access_data',
// is not a sub table read and connect, but only a sub table with data
// 'type' => 'reference_data',
// maxium visible if no data is set, if filled add this number to visible
'max_empty' => 5,
'prefix' => 'ead',
'elements' => [
'name' => [
'type' => 'text',
'error_check' => 'alphanumeric|unique',
'output_name' => 'Name',
'mandatory' => 1
],
'value' => [
'type' => 'text',
'output_name' => 'Value'
],
'enabled' => [
'type' => 'checkbox',
'output_name' => 'Activate',
'int' => 1,
'element_list' => [1]
],
/*'edit_access_id' => [
'int' => 1,
'type' => 'hidden',
// reference main key from master table above
'fk_id' => 1
],*/
'edit_access_data_id' => [
'type' => 'hidden',
'int' => 1,
'pk_id' => 1
],
],
],
],
];
}
}
// __END__

View File

@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace CoreLibs\Output\Form\TableArrays;
class EditVisibleGroup implements \CoreLibs\Output\Form\TableArraysInterface
{
/** @var \CoreLibs\Output\Form\Generate */
private $form;
/**
* constructor
* @param \CoreLibs\Output\Form\Generate $form base form class
*/
public function __construct(\CoreLibs\Output\Form\Generate $form)
{
$this->form = $form;
$this->form->log->debug('CLASS LOAD', __NAMESPACE__ . __CLASS__);
}
/**
* return the table array
*
* @return array<mixed>
*/
public function setTableArray(): array
{
return [
'table_array' => [
'edit_visible_group_id' => [
'value' => $_POST['edit_visible_group_id'] ?? '',
'type' => 'hidden',
'pk' => 1
],
'name' => [
'value' => $_POST['name'] ?? '',
'output_name' => 'Group name',
'mandatory' => 1,
'type' => 'text'
],
'flag' => [
'value' => $_POST['flag'] ?? '',
'output_name' => 'Flag',
'mandatory' => 1,
'type' => 'text',
'error_check' => 'alphanumeric|unique'
],
],
'table_name' => 'edit_visible_group',
'load_query' => "SELECT edit_visible_group_id, name FROM edit_visible_group ORDER BY name",
'show_fields' => [
[
'name' => 'name'
],
],
];
}
}
// __END__

View File

@@ -58,12 +58,14 @@ return array(
'CoreLibs\\Output\\Form\\Elements' => $baseDir . '/lib/CoreLibs/Output/Form/Elements.php',
'CoreLibs\\Output\\Form\\Generate' => $baseDir . '/lib/CoreLibs/Output/Form/Generate.php',
'CoreLibs\\Output\\Form\\TableArraysInterface' => $baseDir . '/lib/CoreLibs/Output/TableArraysInterface.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditAccess' => $baseDir . '/lib/CoreLibs/Output/Form/TableArrays/EditAccess.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditGroups' => $baseDir . '/lib/CoreLibs/Output/Form/TableArrays/EditGroups.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditLanguages' => $baseDir . '/lib/CoreLibs/Output/Form/TableArrays/EditLanguages.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditMenuGroup' => $baseDir . '/lib/CoreLibs/Output/Form/TableArrays/EditMenuGroup.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditPages' => $baseDir . '/lib/CoreLibs/Output/Form/TableArrays/EditPages.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditSchemas' => $baseDir . '/lib/CoreLibs/Output/Form/TableArrays/EditSchemas.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditUsers' => $baseDir . '/lib/CoreLibs/Output/Form/TableArrays/EditUsers.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditVisibleGroup' => $baseDir . '/lib/CoreLibs/Output/Form/TableArrays/EditVisibleGroup.php',
'CoreLibs\\Output\\Form\\Token' => $baseDir . '/lib/CoreLibs/Output/Form/Token.php',
'CoreLibs\\Output\\Image' => $baseDir . '/lib/CoreLibs/Output/Image.php',
'CoreLibs\\Output\\ProgressBar' => $baseDir . '/lib/CoreLibs/Output/ProgressBar.php',

View File

@@ -91,12 +91,14 @@ class ComposerStaticInit10fe8fe2ec4017b8644d2b64bcf398b9
'CoreLibs\\Output\\Form\\Elements' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/Elements.php',
'CoreLibs\\Output\\Form\\Generate' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/Generate.php',
'CoreLibs\\Output\\Form\\TableArraysInterface' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/TableArraysInterface.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditAccess' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/TableArrays/EditAccess.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditGroups' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/TableArrays/EditGroups.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditLanguages' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/TableArrays/EditLanguages.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditMenuGroup' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/TableArrays/EditMenuGroup.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditPages' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/TableArrays/EditPages.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditSchemas' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/TableArrays/EditSchemas.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditUsers' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/TableArrays/EditUsers.php',
'CoreLibs\\Output\\Form\\TableArrays\\EditVisibleGroup' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/TableArrays/EditVisibleGroup.php',
'CoreLibs\\Output\\Form\\Token' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Form/Token.php',
'CoreLibs\\Output\\Image' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/Image.php',
'CoreLibs\\Output\\ProgressBar' => __DIR__ . '/../..' . '/lib/CoreLibs/Output/ProgressBar.php',