Compare commits

...

31 Commits

Author SHA1 Message Date
Clemens Schwaighofer
6001934d9c Some minor fixes in Progress, FileUploader for phpstan level 9 2021-11-02 14:42:20 +09:00
Clemens Schwaighofer
f622d59ed9 Revert backend string|null to string only 2021-11-02 10:17:20 +09:00
Clemens Schwaighofer
6147d28b37 some backend admin class var declarations fixes 2021-11-02 10:14:55 +09:00
Clemens Schwaighofer
f9072f64f1 Ignore defined + empty check php stan errors 2021-11-02 10:06:30 +09:00
Clemens Schwaighofer
0f38cb4f89 Stub tests for Check::File 2021-11-02 09:33:04 +09:00
Clemens Schwaighofer
08bbc913a9 Updates for phpstan 1.0 level 8, fix spaces in config.master.php, add phpunit tets for math, email; update email class with more check methods 2021-11-02 09:16:23 +09:00
Clemens Schwaighofer
4c859ada01 Add phpunit tests folder, fix in Math method floorp when precision was larger then number length 2021-10-29 11:12:23 +09:00
Clemens Schwaighofer
58e61b8902 autoloader test info update 2021-10-28 10:39:08 +09:00
Clemens Schwaighofer
edfbe476c4 Composer.json add lib/ folder, fix Smart extended class
Smarty extended class is now included in checks and is fixed.

Add the lib/ folder to the composer.json autoloader block so we can use
the composer autoloader and not the one from CoreLibs

Added an autoloader load test backend file
2021-10-28 10:11:56 +09:00
Clemens Schwaighofer
0907325a38 Delete pChart class from standard libs 2021-10-28 10:09:54 +09:00
Clemens Schwaighofer
60b6fae33a Composer php unit install and composer.json update 2021-10-27 17:56:46 +09:00
Clemens Schwaighofer
0b7dba5e2f PHPstan composer autoloader boostrap 2021-10-27 17:46:29 +09:00
Clemens Schwaighofer
c1212d8116 Add basic Test run class 2021-10-27 13:25:59 +09:00
Clemens Schwaighofer
5230cbf5d3 Update DB IO classes with better RETURNING data handle
Dropped old insert_id and insert_id_ext and only kepy insert_id_arr.
Added insert_id_pk_name to get the inserted pk name.
Insert RETURNING also works on non set pk name with RETURNING set

Moved the get insert (RETURNING) into method so it can be called from
both dbExec and dbExecute flow.

Error code 31 is only thrown if no returning is set and insert flow
cannot find a primary key for this table

Update all old insert_id calls from other classes
2021-10-27 12:18:28 +09:00
Clemens Schwaighofer
a6b42f243f Update CoreLibs with phpstan level 8, add qqFileUploader implementation base, add base Test class for testing 2021-10-26 16:35:26 +09:00
Clemens Schwaighofer
736f822363 PHPstan check for level 5
Fix various issues for phpstan level 5

Start initial settings for level 6 (needs type declarations for all
vars)
2021-10-22 11:14:00 +09:00
Clemens Schwaighofer
ffd1a86dcc Force DB IO db_port to INT because it must be INT 2021-10-11 11:16:23 +09:00
Clemens Schwaighofer
b3d783bf63 Add .env reading flow in config.php
Will check if there is a read_env_file.php and then run it to load .env
file in /configs folder

This file can hold secrets that are not to be checked into git

Updated edit.js file to be eslint compatible
2021-10-11 09:40:01 +09:00
Clemens Schwaighofer
e0cc766cc7 Fix Flash constant calls 2021-08-30 11:28:06 +09:00
Clemens Schwaighofer
f151509bfe Update CoreLibs with remove of flash folder and add data folder 2021-08-30 11:25:19 +09:00
Clemens Schwaighofer
e252a76c4c Fix for test datetime, indet on test db, remove debug in test lang 2021-08-13 18:11:37 +09:00
Clemens Schwaighofer
7005e07f4c Composer core updates, Fix for Form/Generate 2021-08-12 16:49:36 +09:00
Clemens Schwaighofer
a86ae3efc3 DB IO updates for settings return, Smarty Extended update
Update core template main body with better position for overlib init,
pagename div id add, remove px from any size call (width)

DB IO adds return for config settings, fix db async check to always
return boolean only, add had error variable return method

Some minor fixes in Smarty Extended for some legacy admin page variables
needed.

Update Error reporting to be self containing with defines
2021-07-26 16:09:51 +09:00
Clemens Schwaighofer
8577345799 class check email fix getEmailRegexCheck
This should only return the part email checks from position 1 to n, but
it returned all of them. Fixed with slice call
2021-07-20 06:18:14 +09:00
Clemens Schwaighofer
4779e4ccbe Bug fixes for PSR-12 update 2021-07-14 16:36:13 +09:00
Clemens Schwaighofer
c1240c0614 config master & other warning ignore 2021-07-14 14:11:36 +09:00
Clemens Schwaighofer
6722468bdb Update from PSR-2 to PSR-12
- Tabs are indent
- Warning at 120, Error at 240 char length
2021-07-14 10:02:27 +09:00
Clemens Schwaighofer
11daac6d23 Debug tests update, IO class fixes, support class fixes
Added more tests to debug, form, system class tests

IO: max calls check return variable name was wrong
Logging: changed from preg to str replace for HTMLPRE tag clean up
Debug: empty string debug, returns filled string with dummy text if
string is empty()
System: return base name as is array

Updated Array IO check for loading control array not only from file, but
from direct variable if set or from an array filled with control array
2021-07-12 06:25:10 +09:00
Clemens Schwaighofer
678aa7460e CoreLibs Array keyword remove and switch over to [] 2021-06-30 15:07:22 +09:00
Clemens Schwaighofer
76e0c0ac06 Update and add class test pages, minor updates for CoreLibs
Some code clean up in smarty class (check if $cms object is actually
set)
Logger/Support Debug clean up for some minor logic with debug prefixes
DB IO update debug prefix for log line so we can have a HTML formatted
prefix for echo output
2021-06-28 18:07:40 +09:00
Clemens Schwaighofer
3512fa73ee Remove all execute flaggs from javascript files 2021-06-28 09:48:14 +09:00
1513 changed files with 142487 additions and 16772 deletions

View File

@@ -1,7 +1,5 @@
<?php
use Phan\Config;
/**
* This configuration will be read and overlaid on top of the
* default configuration. Command line arguments will be applied
@@ -24,6 +22,9 @@ use Phan\Config;
* of the phan executable or a path passed in via the CLI
* '-d' flag.
*/
use Phan\Config;
return [
// If true, missing properties will be created when
// they are first seen. If false, we'll report an
@@ -69,14 +70,14 @@ return [
// Thus, both first-party and third-party code being used by
// your application should be included in this list.
'directory_list' => [
// Change this to include the folders you wish to analyze
// (and the folders of their dependencies)
'www',
// To speed up analysis, we recommend going back later and
// limiting this to only the vendor/ subdirectories your
// project depends on.
// `phan --init` will generate a list of folders for you
//'www/vendor',
// Change this to include the folders you wish to analyze
// (and the folders of their dependencies)
'www',
// To speed up analysis, we recommend going back later and
// limiting this to only the vendor/ subdirectories your
// project depends on.
// `phan --init` will generate a list of folders for you
//'www/vendor',
],
@@ -84,9 +85,7 @@ return [
// to parse, but not analyze
"exclude_analysis_directory_list" => [
'www/vendor',
// 'www/lib/FileUpload',
'www/lib/pChart',
'www/lib/pChart2.1.4',
'www/tests',
'www/lib/Smarty',
'www/lib/smarty-3.1.30',
'www/templates_c',

3
4dev/checking/phan.sh Normal file
View File

@@ -0,0 +1,3 @@
base="/storage/var/www/html/developers/clemens/core_data/php_libraries/trunk/";
# must be run in ${base}www/
phan --progress-bar -C --analyze-twice

3
4dev/checking/phpstan.sh Normal file
View File

@@ -0,0 +1,3 @@
base="/storage/var/www/html/developers/clemens/core_data/php_libraries/trunk/";
# must be run in ${base}www/
phpstan

4
4dev/checking/phpunit.sh Executable file
View File

@@ -0,0 +1,4 @@
base="/storage/var/www/html/developers/clemens/core_data/php_libraries/trunk/";
# -c phpunit.xml
# --testdox
${base}www/vendor/bin/phpunit -c ${base}phpunit.xml ${base}4dev/tests/

View File

@@ -1,21 +1,27 @@
Install composer:
curl -sS https://getcomposer.org/installer | /usr/local/php-7.3-httpd-2.4/bin/php
# old
curl -sS https://getcomposer.org/installer | /usr/local/php-8.0-httpd-2.4/bin/php
# new (4 steps) https://getcomposer.org/download/
/usr/local/php-8.0-httpd-2.4/bin/php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
/usr/local/php-8.0-httpd-2.4/bin/php -r "if (hash_file('sha384', 'composer-setup.php') === '906a84df04cea2aa72f40b5f787e49f22d4c2f19492ac310e8cba5b96ac8b64115ac402c8cd292b8a03482574915d1a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
/usr/local/php-8.0-httpd-2.4/bin/php composer-setup.php
/usr/local/php-8.0-httpd-2.4/bin/php -r "unlink('composer-setup.php');
Update composer phar file
/usr/local/php-7.3-httpd-2.4/bin/php composer.phar selfupdate
/usr/local/php-8.0-httpd-2.4/bin/php composer.phar selfupdate
Install something:
/usr/local/php-7.3-httpd-2.4/bin/php composer.phar require something/something
/usr/local/php-8.0-httpd-2.4/bin/php composer.phar require something/something
Update all installed:
/usr/local/php-7.3-httpd-2.4/bin/php composer.phar update
/usr/local/php-8.0-httpd-2.4/bin/php composer.phar update
Or update only one package:
/usr/local/php-7.3-httpd-2.4/bin/php composer.phar something/something
/usr/local/php-8.0-httpd-2.4/bin/php composer.phar something/something
Install AWS SDK:
/usr/local/php-7.3-httpd-2.4/bin/php -d memory_limit=-1 composer.phar require aws/aws-sdk-php
/usr/local/php-8.0-httpd-2.4/bin/php -d memory_limit=-1 composer.phar require aws/aws-sdk-php
Install zipStream:
/usr/local/php-7.3-httpd-2.4/bin/php composer.phar require maennchen/zipstream-php
/usr/local/php-8.0-httpd-2.4/bin/php composer.phar require maennchen/zipstream-php

View File

@@ -147,4 +147,4 @@ BEGIN
RETURN NULL;
END
$$
LANGUAGE 'plpgsql'
LANGUAGE 'plpgsql';

View File

@@ -27,3 +27,9 @@ msgstr "Month"
msgid "INPUT TEST"
msgstr "OUTPUT TEST EN"
msgid "I should be translated"
msgstr "I should be translated: I WAS TRANSLATED"
msgid "Are we translated?"
msgstr "Are we translated? Yes, we are!"

View File

@@ -10,6 +10,9 @@ TARGET_HOST_WEB="<user>@<host>";
TMP_DIR=$LOCAL_BASE_DIR"/4dev/tmp/";
tmpf_web=$TMP_DIR"sync.exclude.tmp";
# if vendor be sure group folder is +x
chmod -R ug+rX ${LOCAL_DIR}/vender/
# for web (ika)
rm -f $tmpf_web;
echo ".*.swp" >> $tmpf_web;
@@ -35,20 +38,19 @@ cat $tmpf_web;
echo "($1) Syncing from $LOCAL_DIR/* to $TARGET_HOST_WEB:$REMOTE_WEB";
echo "You hav 5 seconds to abort (<ctrl> + c)";
#c=0;until [ $c -eq 10 ];do echo -n "#"; sleep 1; c=`expr $c + 1`;done;
for ((i=5;i>=1;i--));
do
echo -n $i" ";
sleep 1;
echo -n $i" ";
sleep 1;
done;
if [ "$1" = "live" ];
then
# ika sync
rsync -Plzvrupt --stats --include ".htaccess" --exclude-from=$tmpf_web --delete -e ssh $LOCAL_DIR/* $TARGET_HOST_WEB:$REMOTE_WEB
# live sync
rsync -Plzvrupt --stats --include ".htaccess" --exclude-from=$tmpf_web --delete -e ssh $LOCAL_DIR/* $TARGET_HOST_WEB:$REMOTE_WEB
else
# ika sync
rsync -n -Plzvrupt --stats --include ".htaccess" --exclude-from=$tmpf_web --delete -e ssh $LOCAL_DIR/* $TARGET_HOST_WEB:$REMOTE_WEB
# test sync
rsync -n -Plzvrupt --stats --include ".htaccess" --exclude-from=$tmpf_web --delete -e ssh $LOCAL_DIR/* $TARGET_HOST_WEB:$REMOTE_WEB
fi;
# END

View File

@@ -0,0 +1,373 @@
<?php
declare(strict_types=1);
namespace tests;
use PHPUnit\Framework\TestCase;
/**
* Undocumented class
* @testdox CoreLibs\Check\Email method tests
*/
final class CoreLibsCheckEmailTest extends TestCase
{
/**
* Array position to regex
*
* @return array<mixed>
*/
public function emailRegexProvider(): array
{
return [
'get email regex invalid -1, will be 0' => [
-1,
"^[A-Za-z0-9!#$%&'*+\-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+\-\/=?^_`{|}~\.]{0,63}@"
. "[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*\.([a-zA-Z]{2,}){1}$"
],
'get email regex invalid 10, will be 0' => [
10,
"^[A-Za-z0-9!#$%&'*+\-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+\-\/=?^_`{|}~\.]{0,63}@"
. "[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*\.([a-zA-Z]{2,}){1}$"
],
'get email regex valid 1, will be 1' => [
1,
"@(.*)@(.*)"
]
];
}
/**
* Test regex level return
*
* @dataProvider emailRegexProvider
* @testdox Email::getEmailRegex $input will be $expected [$_dataName]
*
* @param int $input
* @param string $expected
* @return void
*/
public function testGetEmailRegexReturn(int $input, string $expected): void
{
$this->assertEquals(
$expected,
\CoreLibs\Check\Email::getEmailRegex($input)
);
}
/**
* provides data for emailCheckProvider and emailCheckFullProvider
*
* @return array
*/
public function emailCheckList(): array
{
return [
'valid email' => ['test@test.com', true, []],
'invalid empty email' => ['', false, [0, 2, 3, 4, 5]],
'invalid email' => ['-@-', false, [0, 3, 4, 5]],
'invalid email leading dot' => ['.test@test.com', false, [0, 2]],
'invalid email invalid domain' => ['test@t_est.com', false, [0, 3, 4]],
'invalid email double @' => ['test@@test.com', false, [0, 1]],
'invalid email double dot' => ['test@test..com', false, [0, 3, 6]],
'invalid email end with dot' => ['test@test.', false, [0, 3, 5, 7]],
'invalid email bad top level' => ['test@test.j', false, [0, 3, 5]],
'invalid email double @ and double dot' => ['test@@test..com', false, [0, 1, 3, 6]],
];
}
/**
* Valids or not valid email address
*
* @return array
*/
public function emailCheckProvider(): array
{
$list = [];
foreach ($this->emailCheckList() as $key => $data) {
$list[$key] = [$data[0], $data[1]];
}
return $list;
}
/**
* Undocumented function
*
* @dataProvider emailCheckProvider
* @testdox Email::checkEmail $input will be $expected [$_dataName]
*
* @return void
*/
public function testCheckEmail(string $input, bool $expected): void
{
$this->assertEquals(
$expected,
\CoreLibs\Check\Email::checkEmail($input)
);
}
/**
* this is like emailCheckProvider but it has the full detail errors
* All errors should be tetsed in testGetEmailRegexErrorMessage
*
* @return array
*/
public function emailCheckFullProvider(): array
{
$list = [];
foreach ($this->emailCheckList() as $key => $data) {
$list[$key] = [$data[0], $data[2]];
}
return $list;
}
/**
* Undocumented function
*
* @dataProvider emailCheckFullProvider
* @testdox Email::checkEmailFull $input will be $expected [$_dataName]
*
* @param string $input
* @param array $expected
* @return void
*/
public function testCheckEmailFull(string $input, array $expected): void
{
$this->assertEqualsCanonicalizing(
$expected,
\CoreLibs\Check\Email::checkEmailFull($input, true)
);
}
/**
* error data returned for each error position
*
* @return array
*/
public function emailRegexErrorProvider(): array
{
return [
'error 0 will return general' => [
0,
[
'error' => 0,
'message' => 'Invalid email address',
'regex' => "^[A-Za-z0-9!#$%&'*+\-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+\-\/=?^_`{|}~\.]{0,63}@"
. "[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*\.([a-zA-Z]{2,}){1}$"
]
],
'error 1 will return double @ error' => [
1,
[
'error' => 1,
'message' => 'Double @ mark in email address',
'regex' => "@(.*)@(.*)"
]
],
'error 2 will be invalid before @' => [
2,
[
'error' => 2,
'message' => 'Invalid email part before @ sign',
'regex' => "^[A-Za-z0-9!#$%&'*+\-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+\-\/=?^_`{|}~\.]{0,63}@"
]
],
'error 3 will be invalid domain and top level' => [
3,
[
'error' => 3,
'message' => 'Invalid domain part after @ sign',
'regex' => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.([a-zA-Z]{2,}){1}$"
]
],
'error 4 will be invalid domain' => [
4,
[
'error' => 4,
'message' => 'Invalid domain name part',
'regex' => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\."
]
],
'error 5 will be invalid domain top level only' => [
5,
[
'error' => 5,
'message' => 'Wrong domain top level part',
'regex' => "\.([a-zA-Z]{2,6}){1}$"
]
],
'error 6 will be domain double dot' => [
6,
[
'error' => 6,
'message' => 'Double consecutive dots in domain name (..)',
'regex' => "@(.*)\.{2,}"
]
],
'error 7 will domain ends with dot' => [
7,
[
'error' => 7,
'message' => 'Domain ends with a dot or is missing top level part',
'regex' => "@.*\.$"
]
]
];
}
/**
* Undocumented function
*
* @dataProvider emailRegexErrorProvider
* @testdox Email::getEmailRegexErrorMessage $input will be $expected [$_dataName]
*
* @param integer $input
* @param array $expected
* @return void
*/
public function testGetEmailRegexErrorMessage(int $input, array $expected): void
{
$this->assertEqualsCanonicalizing(
$expected,
\CoreLibs\Check\Email::getEmailRegexErrorMessage($input)
);
}
/**
* This holds all email type checks normal and short
*
* @return array
*/
public function emailTypeProvider(): array
{
return [
['test@test.com', 'pc_html', 'pc'],
['test@docomo.ne.jp', 'keitai_docomo', 'docomo'],
['test@softbank.ne.jp', 'keitai_softbank', 'softbank'],
['test@i.softbank.ne.jp', 'smartphone_softbank_iphone', 'iphone'],
// TODO: add more test emails here
];
}
/**
* Returns only normal email type checks
*
* @return array<mixed>
*/
public function emailTypeProviderLong(): array
{
$list = [];
foreach ($this->emailTypeProvider() as $set) {
$list['email ' . $set[0] . ' is valid and matches normal ' . $set[1]] = [$set[0], $set[1]];
}
$list['email is empty and not valid normal'] = ['', 'invalid'];
return $list;
}
/**
* only short email type list
*
* @return array<mixed>
*/
public function emailTypeProviderShort(): array
{
$list = [];
foreach ($this->emailTypeProvider() as $set) {
$list['email ' . $set[0] . ' is valid and matches short ' . $set[2]] = [$set[0], $set[2]];
}
$list['email is empty and not valid short'] = ['', 'invalid'];
return $list;
}
/**
* Undocumented function
*
* @dataProvider emailTypeProviderLong
* @testdox Email::getEmailType $input will be normal $expected [$_dataName]
*
* @param string $input
* @param string $expected
* @return void
*/
public function testGetEmailTypeNormal(string $input, string $expected)
{
$this->assertEquals(
$expected,
\CoreLibs\Check\Email::getEmailType($input, false)
);
}
/**
* Undocumented function
*
* @dataProvider emailTypeProviderShort
* @testdox Email::getEmailType $input will be short $expected [$_dataName]
*
* @param string $input
* @param string $expected
* @return void
*/
public function testGetEmailTypeShort(string $input, string $expected)
{
$this->assertEquals(
$expected,
\CoreLibs\Check\Email::getEmailType($input, true)
);
}
/**
* Undocumented function
*
* @return array
*/
public function emailProviderTypeLongToShort(): array
{
$mobile_email_type_short = [
'keitai_docomo' => 'docomo',
'keitai_kddi_ezweb' => 'kddi',
'keitai_kddi' => 'kddi',
'keitai_kddi_tu-ka' => 'kddi',
'keitai_kddi_sky' => 'kddi',
'keitai_softbank' => 'softbank',
'smartphone_softbank_iphone' => 'iphone',
'keitai_softbank_disney' => 'softbank',
'keitai_softbank_vodafone' => 'softbank',
'keitai_softbank_j-phone' => 'softbank',
'keitai_willcom' => 'willcom',
'keitai_willcom_pdx' => 'willcom',
'keitai_willcom_bandai' => 'willcom',
'keitai_willcom_pipopa' => 'willcom',
'keitai_willcom_ymobile' => 'willcom',
'keitai_willcom_emnet' => 'willcom',
'pc_html' => 'pc',
];
$list = [];
// use the static one
foreach ($mobile_email_type_short as $long => $short) {
$list[$long . ' matches to ' . $short] = [$long, $short];
}
// add invalid check
$list['Not found will be bool false'] = ['invalid', false];
return $list;
}
/**
* Undocumented function
*
* @dataProvider emailProviderTypeLongToShort
* @testdox Email::getShortEmailType $input will be $expected [$_dataName]
*
* @param string $input
* @param string|bool $expected
* @return void
*/
public function testGetShortEmailType(string $input, $expected)
{
$this->assertEquals(
$expected,
\CoreLibs\Check\Email::getShortEmailType($input)
);
}
}
// __END__

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace tests;
use PHPUnit\Framework\TestCase;
/**
* Undocumented class
* @testdox CoreLibs\Check\File method tests
*/
final class CoreLibsCheckFileTest extends TestCase
{
/** @var array<mixed> */
private $files = [];
protected function setUp(): void
{
// write a dummy files for testing
}
protected function tearDown(): void
{
// unlink files
}
/**
* main file list + data provider
*
* @return array
*/
public function filesList(): array
{
return [
['filename.txt', 'txt', 5]
];
}
public function filesExtensionProvider(): array
{
$list = [];
foreach ($this->filesList as $row) {
$list[$row[0] . ' must be extension ' . $row[1]] = [$row[0], $row[1]];
}
return $list;
}
/**
* Undocumented function
*
* @#dataProvider filesExtensionProvider
* @#testdox File::getFilenameEnding Input $input must be $expected
* //string $input, string $expected
*
* @param string $input
* @param string $expected
* @return void
*/
public function testGetFilenameEnding(): void
{
// getFilenameEnding
/* $this->assertEquals(
$expected,
\CoreLibs\Check\File::getFilenameEnding($input)
); */
$this->assertTrue(true, 'This should already work.');
$this->markTestIncomplete(
'testGetFilenameEnding has not been implemented yet.'
);
}
/**
* Undocumented function
* // string $input, string $expected
*
* @return void
*/
public function testGetLinesFromFile(): void
{
// getLinesFromFile
$this->assertTrue(true, 'This should already work.');
$this->markTestIncomplete(
'testGetLinesFromFile has not been implemented yet.'
);
}
}
// __END__

View File

@@ -0,0 +1,134 @@
<?php
declare(strict_types=1);
namespace tests;
use PHPUnit\Framework\TestCase;
/**
* Undocumented class
* @testdox CoreLibs\Convert\Math method tests
*/
final class CoreLibsConvertMathTest extends TestCase
{
/**
* Undocumented function
*
* @return array<mixed>
*/
public function fceilProvider(): array
{
return [
'5.5 must be 6' => [5.5, 6],
'5.1234567890 with 5 must be 6' => [5.1234567890, 6],
'6 must be 6' => [6, 6]
];
}
/**
* Undocumented function
*
* @dataProvider fceilProvider
* @testdox Math::fceil: Input $input must be $expected
*
* @param float $input
* @param int $expected
* @return void
*/
public function testMathFceilValue(float $input, int $expected): void
{
$this->assertEquals(
$expected,
\CoreLibs\Convert\Math::fceil($input)
);
}
/**
* Undocumented function
*
* @return array<mixed>
*/
public function floorProvider(): array
{
return [
'5123456 with -3 must be 5123000' => [5123456, -3, 5123000],
'5123456 with -10 must be 5000000' => [5123456, -10, 5000000]
];
}
/**
* Undocumented function
*
* @dataProvider floorProvider
* @testdox Math::floor: Input $input with cutoff $cutoff must be $expected
*
* @param int $input
* @param int $cutoff
* @param int $expected
* @return void
*/
public function testMathFloorValue(int $input, int $cutoff, int $expected): void
{
$this->assertEquals(
$expected,
\CoreLibs\Convert\Math::floorp($input, $cutoff)
);
}
/**
* Undocumented function
*
* @return array<mixed>
*/
public function initNumericProvider(): array
{
return [
'5 must be 5' => [5, 5, 'int'],
'5.123 must be 5.123' => [5.123, 5.123, 'float'],
"'5' must be 5" => ['5', 5, 'string'],
"'5.123' must be 5.123" => ['5.123', 5.123, 'string'],
];
}
/**
* Undocumented function
*
* @dataProvider initNumericProvider
* @testdox Math::initNumeric: Input $info $input must match $expected [$_dataName]
*
* @param int|float|string $input
* @param float $expected
* @param string $info
* @return void
*/
public function testMathInitNumericValue($input, float $expected, string $info): void
{
$this->assertEquals(
$expected,
\CoreLibs\Convert\Math::initNumeric($input)
);
}
/**
* A testWith sample
*
* @testdox Math::initNumeric: alternate tests $input => $expected ($info) [$_dataName]
* @testWith [123.123, 123.123, "float"]
* ["123.123", 123.123, "string"]
*
* @param int|float|string $input
* @param float $expected
* @param string $info
* @return void
*/
public function testMathInitNumericValueAlt($input, float $expected, string $info): void
{
$this->assertEquals(
$expected,
\CoreLibs\Convert\Math::initNumeric($input)
);
}
}
// __END__

View File

@@ -1,5 +1,13 @@
# PHP Core Library
## Code Standard
* 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
@@ -25,3 +33,13 @@ last tested PHP 5.6 and PHP 7.0
### namespace
The new namespace branch. This is the development area for the master branch
## Static checks
With phpstan
`phpstan`
With phan
`phan --progress-bar -C --analyze-twice`
pslam is setup but not configured

View File

@@ -1,6 +1,12 @@
<?php
<?php // phpcs:ignore PSR1.Files.SideEffects
// Boostrap file for PHPstand
// sets the _SERVER['HTTP_HOST'] var so we can have DB detection
$_SERVER['HTTP_HOST'] = 'soba.tokyo.tequila.jp';
// so www/includes/edit_base.php works
require_once('www/lib/Smarty/SmartyBC.class.php');
// for whatever reason it does not load that from the confing.master.php
// for includes/admin_header.php
define('BASE_NAME', '');
// __END__

View File

@@ -2,37 +2,34 @@
parameters:
tmpDir: /tmp/phpstan-corelibs
level: 1
level: 8 # max is now 9
paths:
- %currentWorkingDirectory%/www
bootstrapFiles:
- %currentWorkingDirectory%/phpstan-bootstrap.php
# - %currentWorkingDirectory%/www/lib/autoloader.php
- %currentWorkingDirectory%/www/vendor/autoload.php
scanDirectories:
- www/lib/Smarty
scanFiles:
- www/configs/config.php
- www/configs/config.master.php
- www/lib/autoloader.php
# if composer.json autoloader defined, this is not needed
# - www/lib/autoloader.php
- www/vendor/autoload.php
- www/lib/Smarty/Autoloader.php
- www/lib/CoreLibs/Template/SmartyExtend.php
excludes_analyse:
# no check admin
- www/admin/qq_file_upload_front.php
- www/admin/qq_file_upload_ajax.php
excludePaths:
# do not check old qq file uploader tests
- www/admin/qq_file_upload_*.php
# ignore all test files
- www/admin/class_test*php
- www/admin/error_test.php
# admin synlink files
- www/admin/edit_access.php
- www/admin/edit_groups.php
- www/admin/edit_languages.php
- www/admin/edit_menu_group.php
- www/admin/edit_order.php
- www/admin/edit_pages.php
- www/admin/edit_schemes.php
- www/admin/edit_users.php
- www/admin/edit_visible_group.php
- www/admin/edit_*.php
# ignore admin header stuff
- www/includes/admin_header.php # ignore the admin include stuff
# - www/includes/admin_header.php # ignore the admin include stuff
- www/includes/admin_footer.php # ignore the admin include stuff
# deprecated files
- www/includes/admin_set_paths.php # ignore the admin include stuff
- www/includes/admin_smarty.php # ignore the admin include stuff
# folders with data no check needed
@@ -41,16 +38,18 @@ parameters:
- www/log
- www/media
- www/tmp
- www/lib/pChart
- www/lib/pChart2.1.4
- www/lib/Smarty
- www/lib/smarty-3.1.30
# external libs are not checked
- www/lib/Smarty/
- www/lib/smarty-*/
# ignore composer
- www/vendor
# ignore the smartyextend
- www/lib/CoreLibs/Template/SmartyExtend.php
# ignore errores with
# ignoreErrors:
ignoreErrors:
# this is ignored for now
# - '#Expression in empty\(\) is always falsy.#'
# -
# message: '#Reflection error: [a-zA-Z0-9\\_]+ not found.#'
# path: www/includes/edit_base.php
#- 'error regex'
#-
# message: 'error regex'

6
phpunit.xml Normal file
View File

@@ -0,0 +1,6 @@
<phpunit
cacheResultFile="/tmp/phpunit-corelibs.result.cache"
colors="true"
verbose="true"
>
</phpunit>

View File

@@ -0,0 +1,54 @@
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true;
$PRINT_ALL = true;
$DB_DEBUG = true;
if ($DEBUG_ALL) {
error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
}
ob_start();
// basic class test file
define('USE_DATABASE', true);
// sample config
require 'config.php';
// override ECHO ALL FALSE
$ECHO_ALL = true;
// set session name
if (!defined('SET_SESSION_NAME')) {
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
}
// define log file id
$LOG_FILE_ID = 'classTest-admin';
ob_end_flush();
$basic = new CoreLibs\Basic();
$backend = new CoreLibs\Admin\Backend(DB_CONFIG);
print "<html><head><title>TEST CLASS: ADMIN BACKEND</title><head>";
print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
// set acl, from eg login acl
print "SETACL[]: " . $backend->setACL([]) . "<br>";
print "ADBEDITLOG: " . $backend->adbEditLog('CLASSTEST-ADMIN', 'Some info stirng') . "<br>";
print "ADBTOPMENU(0): " . \CoreLibs\Debug\Support::printAr($backend->adbTopMenu()) . "<br>";
print "ADBMSG: " . $backend->adbMsg('info', 'Message: %1$d', [1]) . "<br>";
print "Messaes: " . \CoreLibs\Debug\Support::printAr($this->messages) . "<br>";
print "ADBPRINTDATETIME:<br>" . $backend->adbPrintDateTime(2021, 6, 21, 6, 38, '_test') . "<br>";
// error message
print $basic->log->printErrorMsg();
print "</body></html>";
// __END__

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -30,7 +33,7 @@ use CoreLibs\Combined\ArrayHandler;
use CoreLibs\Debug\Support as DgS;
$basic = new CoreLibs\Basic();
// $_array= new CoreLibs\Combined\ArrayHandler();
// $_array = new CoreLibs\Combined\ArrayHandler();
// $array_class = 'CoreLibs\Combination\ArrayHandler';
print "<html><head><title>TEST CLASS: ARRAY HANDLER</title><head>";
@@ -53,15 +56,19 @@ $test_array = [
],
];
echo "SOURCE ARRAY: ".DgS::printAr($test_array)."<br>";
echo "SOURCE ARRAY: " . DgS::printAr($test_array) . "<br>";
// frist return
echo "ARRAYSEARCHRECURSIVE(email, [array], type): ".DgS::printAr(ArrayHandler::arraySearchRecursive('email', $test_array, 'type'))."<br>";
echo "ARRAYSEARCHRECURSIVE(email, [array]['input'], type): ".DgS::printAr(ArrayHandler::arraySearchRecursive('email', $test_array['input'], 'type'))."<br>";
echo "ARRAYSEARCHRECURSIVE(email, [array], type): "
. DgS::printAr(ArrayHandler::arraySearchRecursive('email', $test_array, 'type')) . "<br>";
echo "ARRAYSEARCHRECURSIVE(email, [array]['input'], type): "
. DgS::printAr(ArrayHandler::arraySearchRecursive('email', $test_array['input'], 'type')) . "<br>";
// all return
echo "ARRAYSEARCHRECURSIVEALL(email, [array], type): ".Dgs::printAr((array)ArrayHandler::arraySearchRecursiveAll('email', $test_array, 'type'))."<br>";
echo "ARRAYSEARCHRECURSIVEALL(email, [array], type): "
. Dgs::printAr((array)ArrayHandler::arraySearchRecursiveAll('email', $test_array, 'type')) . "<br>";
// simple search
echo "ARRAYSEARCHSIMPLE([array], type, email): ".(string)ArrayHandler::arraySearchSimple($test_array, 'type', 'email')."<br>";
echo "ARRAYSEARCHSIMPLE([array], type, email): "
. (string)ArrayHandler::arraySearchSimple($test_array, 'type', 'email') . "<br>";
$array_1 = [
'foo' => 'bar'
@@ -75,7 +82,7 @@ $array_3 = [
]
];
// recusrice merge
print "ARRAYMERGERECURSIVE: ".DgS::printAr(ArrayHandler::arrayMergeRecursive($array_1, $array_2, $array_3))."<br>";
print "ARRAYMERGERECURSIVE: " . DgS::printAr(ArrayHandler::arrayMergeRecursive($array_1, $array_2, $array_3)) . "<br>";
// array difference
$array_left = [
'same' => 'data',
@@ -85,18 +92,109 @@ $array_right = [
'same' => 'data',
'right' => 'has R'
];
print "ARRAYDIFF: ".DgS::printAr(ArrayHandler::arrayDiff($array_left, $array_right))."<br>";
print "ARRAYDIFF: " . DgS::printAr(ArrayHandler::arrayDiff($array_left, $array_right)) . "<br>";
// in array check
print "INARRAYANY([1,3], [array]): ".DgS::printAr(ArrayHandler::inArrayAny([1, 3], $array_2))."<br>";
print "INARRAYANY([1,3], [array]): " . DgS::printAr(ArrayHandler::inArrayAny([1, 3], $array_2)) . "<br>";
// flatten array
print "FLATTENARRAY: ".DgS::printAr(ArrayHandler::flattenArray($test_array))."<br>";
print "FLATTENARRAYKEY: ".DgS::printAr(ArrayHandler::flattenArrayKey($test_array))."<br>";
print "FLATTENARRAY: " . DgS::printAr(ArrayHandler::flattenArray($test_array)) . "<br>";
print "FLATTENARRAYKEY: " . DgS::printAr(ArrayHandler::flattenArrayKey($test_array)) . "<br>";
// flatten for key set
print "ARRAYFLATFORKEY: ".DgS::printAr(ArrayHandler::arrayFlatForKey($test_array, 'type'))."<br>";
print "ARRAYFLATFORKEY: " . DgS::printAr(ArrayHandler::arrayFlatForKey($test_array, 'type')) . "<br>";
// DEPRECATED
// print "ARRAYMERGERECURSIVE: ".DgS::printAr($basic->arrayMergeRecursive($array_1, $array_2, $array_3))."<br>";
/**
* attach key/value to an array so it becomes nested
*
* @param string $pre Attach to new (empty for new root node)
* @param string $cur New node
* @param array $node Previous created array
* @return array Updated array
*/
function rec(string $pre, string $cur, array $node = [])
{
if (!is_array($node)) {
$node = [];
}
print "<div style='color: green;'>#### PRE: " . $pre . ", CUR: " . $cur . ", N-c: "
. count($node) . " [" . join('|', array_keys($node)) . "]</div>";
if (!$pre) {
print "** <span style='color: red;'>NEW</span><br>";
$node[$cur] = [];
} else {
if (array_key_exists($pre, $node)) {
print "+ <span style='color: orange;'>KEY FOUND:</span> " . $pre . ", add: " . $cur . "<br>";
$node[$pre][$cur] = [];
} else {
print "- NOT FOUND: loop<br>";
foreach ($node as $_pre => $_cur) {
print "> TRY: " . $_pre . " => " . count($_cur) . " [" . join('|', array_keys($_cur)) . "]<br>";
if (count($_cur) > 0) {
$node[$_pre] = rec($pre, $cur, $_cur);
}
}
}
}
return $node;
}
/**
* flatten array down to own level
*
* @param array $array
* @param array $return
* @return array
*/
function flattenArrayKey(array $array, array $return = [])
{
foreach ($array as $key => $sub) {
$return[] = $key;
if (count($sub) > 0) {
$return = flattenArrayKey($sub, $return);
}
}
return $return;
}
// $test = [
// 'A' => [
// 'B' => [],
// 'C' => [
// 'D' => [],
// 'E' => [
// 'F' => []
// ]
// ]
// ],
// '1' => [],
// '2' => [],
// '3' => [
// 'G' => []
// ]
// ];
// build a tested array for flatten
$test = [];
// core
$test = rec('', 'A', $test);
$test = rec('', '1', $test);
$test = rec('', '2', $test);
$test = rec('', '3', $test);
$test = rec('3', 'G', $test);
$test = rec('A', 'B', $test);
$test = rec('A', 'C', $test);
$test = rec('C', 'D', $test);
$test = rec('C', 'E', $test);
$test = rec('E', 'F', $test);
// new
$test = rec('C', 'U', $test);
$test = rec('F', 'U', $test);
$test = rec('', 'Al', $test);
$test = rec('B', 'B1', $test);
print "ORIGINAL: " . \CoreLibs\Debug\Support::printAr($test) . "<br>";
print "FLATTEN: " . \CoreLibs\Debug\Support::printAr(flattenArrayKey($test)) . "<br>";
// error message
print $basic->log->printErrorMsg();

View File

@@ -0,0 +1,45 @@
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true;
$PRINT_ALL = true;
$DB_DEBUG = true;
if ($DEBUG_ALL) {
error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
}
ob_start();
// basic class test file
define('USE_DATABASE', false);
// sample config
require 'config.php';
// set session name
if (!defined('SET_SESSION_NAME')) {
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
}
// define log file id
$LOG_FILE_ID = 'classTest-autoloader';
ob_end_flush();
# Test if composer autoloader works here
use CoreLibs\Convert\Byte;
print "<html><head><title>TEST CLASS: AUTOLOADER</title><head>";
print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
$bytes = 10242424;
$_bytes = Byte::humanReadableByteFormat($bytes);
print "BYTES: " . $_bytes . "<br>";
print "</body></html>";
// __END__

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -39,8 +42,8 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$byte = 254779258;
$string = '242.98 MB';
// static
print "S::BYTE TO: $byte: ".$byte_class::humanReadableByteFormat($byte)."<br>";
print "S::BYTE FROM: $string: ".$byte_class::stringByteFormat($string)."<br>";
print "S::BYTE TO: $byte: " . $byte_class::humanReadableByteFormat($byte) . "<br>";
print "S::BYTE FROM: $string: " . $byte_class::stringByteFormat($string) . "<br>";
// *** BYTES TEST ***
$bytes = array(
@@ -59,9 +62,9 @@ foreach ($bytes as $byte) {
print '<div style="display: flex; border-bottom: 1px dashed gray;">';
//
print '<div style="width: 35%; text-align: right; padding-right: 2px;">';
print "(".number_format($byte)."/".$byte.") bytes :";
print "(" . number_format($byte) . "/" . $byte . ") bytes :";
$_bytes = Byte::humanReadableByteFormat($byte);
print '</div><div style="width: 10%;">'.$_bytes;
print '</div><div style="width: 10%;">' . $_bytes;
print '</div><div style="width: 10%;">';
print Byte::stringByteFormat($_bytes);
print "</div>";
@@ -73,7 +76,7 @@ foreach ($bytes as $byte) {
print '<div style="width: 35%; text-align: right; padding-right: 2px;">';
print "bytes [si]:";
$_bytes = Byte::humanReadableByteFormat($byte, Byte::BYTE_FORMAT_SI);
print '</div><div style="width: 10%;">'.$_bytes;
print '</div><div style="width: 10%;">' . $_bytes;
print '</div><div style="width: 10%;">';
print Byte::stringByteFormat($_bytes);
print "</div>";

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -39,22 +42,26 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
// define a list of from to color sets for conversion test
// A(out of bounds)
print "C::S/COLOR invalid rgb->hex (gray 125): -1, -1, -1: ".CoreLibs\Convert\Colors::rgb2hex(-1, -1, -1)."<br>";
print "\$C::S/COLOR invalid rgb->hex (gary 125): -1, -1, -1: ".$color_class::rgb2hex(-1, -1, -1)."<br>";
print "C::S/COLOR invalid rgb->hex (gray 125): -1, -1, -1: " . CoreLibs\Convert\Colors::rgb2hex(-1, -1, -1) . "<br>";
print "\$C::S/COLOR invalid rgb->hex (gary 125): -1, -1, -1: " . $color_class::rgb2hex(-1, -1, -1) . "<br>";
// B(valid)
$rgb = [10, 20, 30];
$hex = '#0a141e';
$hsb = [210, 67, 12];
$hsl = [210, 50, 7.8];
print "S::COLOR rgb->hex: $rgb[0], $rgb[1], $rgb[2]: ".Colors::rgb2hex($rgb[0], $rgb[1], $rgb[2])."<br>";
print "S::COLOR hex->rgb: $hex: ".DgS::printAr(Colors::hex2rgb($hex))."<br>";
print "C::S/COLOR rgb->hext: $hex: ".DgS::printAr(CoreLibs\Convert\Colors::hex2rgb($hex))."<br>";
print "S::COLOR rgb->hex: $rgb[0], $rgb[1], $rgb[2]: " . Colors::rgb2hex($rgb[0], $rgb[1], $rgb[2]) . "<br>";
print "S::COLOR hex->rgb: $hex: " . DgS::printAr(Colors::hex2rgb($hex)) . "<br>";
print "C::S/COLOR rgb->hext: $hex: " . DgS::printAr(CoreLibs\Convert\Colors::hex2rgb($hex)) . "<br>";
// C(to hsb/hsl)
print "S::COLOR rgb->hsb: $rgb[0], $rgb[1], $rgb[2]: ".DgS::printAr(Colors::rgb2hsb($rgb[0], $rgb[1], $rgb[2]))."<br>";
print "S::COLOR rgb->hsl: $rgb[0], $rgb[1], $rgb[2]: ".DgS::printAr(Colors::rgb2hsl($rgb[0], $rgb[1], $rgb[2]))."<br>";
print "S::COLOR rgb->hsb: $rgb[0], $rgb[1], $rgb[2]: "
. DgS::printAr(Colors::rgb2hsb($rgb[0], $rgb[1], $rgb[2])) . "<br>";
print "S::COLOR rgb->hsl: $rgb[0], $rgb[1], $rgb[2]: "
. DgS::printAr(Colors::rgb2hsl($rgb[0], $rgb[1], $rgb[2])) . "<br>";
// D(from hsb/hsl) Note that param 2 + 3 is always 0-100 divided
print "S::COLOR hsb->rgb: $hsb[0], $hsb[1], $hsb[2]: ".DgS::printAr(Colors::hsb2rgb($hsb[0], $hsb[1], $hsb[2]))."<br>";
print "S::COLOR hsl->rgb: $hsl[0], $hsl[1], $hsl[2]: ".DgS::printAr(Colors::hsl2rgb($hsl[0], $hsl[1], $hsl[2]))."<br>";
print "S::COLOR hsb->rgb: $hsb[0], $hsb[1], $hsb[2]: "
. DgS::printAr(Colors::hsb2rgb($hsb[0], $hsb[1], $hsb[2])) . "<br>";
print "S::COLOR hsl->rgb: $hsl[0], $hsl[1], $hsl[2]: "
. DgS::printAr(Colors::hsl2rgb($hsl[0], $hsl[1], $hsl[2])) . "<br>";
// TODO: run compare check input must match output

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -30,7 +33,7 @@ use CoreLibs\Combined\DateTime;
use CoreLibs\Debug\Support as DgS;
$basic = new CoreLibs\Basic();
$datetime_class = 'CoreLibs\Combination\DateTime';
$datetime_class = 'CoreLibs\Combined\DateTime';
print "<html><head><title>TEST CLASS: DATE/TIME</title><head>";
print "<body>";
@@ -39,47 +42,47 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
// class
$timestamp = 1622788315.123456;
// static
print "S::DATESTRINGFORMAT(sm:0): $timestamp: ".$datetime_class::dateStringFormat($timestamp)."<br>";
print "S::DATESTRINGFORMAT(sm:0): $timestamp: " . $datetime_class::dateStringFormat($timestamp) . "<br>";
// time string thest
$timestamp = 5887998.33445;
$time_string = DateTime::timeStringFormat($timestamp);
print "PLANE TIME STRING: ".$timestamp."<br>";
print "TIME STRING TEST: ".$time_string."<br>";
print "REVERSE TIME STRING: ".DateTime::stringToTime($time_string)."<br>";
print "PLANE TIME STRING: " . $timestamp . "<br>";
print "TIME STRING TEST: " . $time_string . "<br>";
print "REVERSE TIME STRING: " . DateTime::stringToTime($time_string) . "<br>";
if (round($timestamp, 4) == DateTime::stringToTime($time_string)) {
print "REVERSE TIME STRING MATCH<br>";
} else {
print "REVERSE TRIME STRING DO NOT MATCH<br>";
}
print "ZERO TIME STRING: ".DateTime::timeStringFormat(0, true)."<br>";
print "ZERO TIME STRING: ".DateTime::timeStringFormat(0.0, true)."<br>";
print "ZERO TIME STRING: ".DateTime::timeStringFormat(1.005, true)."<br>";
print "ZERO TIME STRING: " . DateTime::timeStringFormat(0, true) . "<br>";
print "ZERO TIME STRING: " . DateTime::timeStringFormat(0.0, true) . "<br>";
print "ZERO TIME STRING: " . DateTime::timeStringFormat(1.005, true) . "<br>";
$timestamps = [
1622788315.123456,
-1622788315.456789
];
foreach ($timestamps as $timestamp) {
print "DATESTRINGFORMAT(sm:0): $timestamp: ".DateTime::dateStringFormat($timestamp)."<br>";
print "DATESTRINGFORMAT(sm:1): $timestamp: ".DateTime::dateStringFormat($timestamp, true)."<br>";
print "DATESTRINGFORMAT(sm:0): $timestamp: " . DateTime::dateStringFormat($timestamp) . "<br>";
print "DATESTRINGFORMAT(sm:1): $timestamp: " . DateTime::dateStringFormat($timestamp, true) . "<br>";
}
$intervals = [
788315.123456,
-123.456
];
foreach ($intervals as $interval) {
print "TIMESTRINGFORMAT(sm:0): $interval: ".DateTime::timeStringFormat($interval, false)."<br>";
print "TIMESTRINGFORMAT(sm:0): $interval: " . DateTime::timeStringFormat($interval, false) . "<br>";
$reverse_interval = DateTime::timeStringFormat($interval);
print "TIMESTRINGFORMAT(sm:1): $interval: ".$reverse_interval."<br>";
print "STRINGTOTIME: $reverse_interval: ".DateTime::stringToTime($reverse_interval)."<br>";
print "TIMESTRINGFORMAT(sm:1): $interval: " . $reverse_interval . "<br>";
print "STRINGTOTIME: $reverse_interval: " . DateTime::stringToTime($reverse_interval) . "<br>";
}
$check_dates = [
'2021-05-01',
'2021-05-40'
];
foreach ($check_dates as $check_date) {
print "CHECKDATE: $check_date: ".(string)DateTime::checkDate($check_date)."<br>";
print "CHECKDATE: $check_date: " . (string)DateTime::checkDate($check_date) . "<br>";
}
$check_datetimes = [
'2021-05-01',
@@ -89,7 +92,7 @@ $check_datetimes = [
'2021-05-01 25:13:14',
];
foreach ($check_datetimes as $check_datetime) {
print "CHECKDATETIME: $check_datetime: ".(string)DateTime::checkDateTime($check_datetime)."<br>";
print "CHECKDATETIME: $check_datetime: " . (string)DateTime::checkDateTime($check_datetime) . "<br>";
}
$compare_dates = [
[ '2021-05-01', '2021-05-02', ],
@@ -99,7 +102,8 @@ $compare_dates = [
];
// compareDate
foreach ($compare_dates as $compare_date) {
print "COMPAREDATE: $compare_date[0] = $compare_date[1]: ".(string)DateTime::compareDate($compare_date[0], $compare_date[1])."<br>";
print "COMPAREDATE: $compare_date[0] = $compare_date[1]: "
. (string)DateTime::compareDate($compare_date[0], $compare_date[1]) . "<br>";
}
$compare_datetimes = [
[ '2021-05-01', '2021-05-02', ],
@@ -110,7 +114,8 @@ $compare_datetimes = [
[ '2021-05-01 10:00:00', '2021-05-01 10:00:00', ],
];
foreach ($compare_datetimes as $compare_datetime) {
print "COMPAREDATE: $compare_datetime[0] = $compare_datetime[1]: ".(string)DateTime::compareDateTime($compare_datetime[0], $compare_datetime[1])."<br>";
print "COMPAREDATE: $compare_datetime[0] = $compare_datetime[1]: "
. (string)DateTime::compareDateTime($compare_datetime[0], $compare_datetime[1]) . "<br>";
}
$compare_dates = [
[ '2021-05-01', '2021-05-10', ],
@@ -119,8 +124,10 @@ $compare_dates = [
[ '2021-05-02', '2021-05-02', ],
];
foreach ($compare_dates as $compare_date) {
print "CALCDAYSINTERVAL: $compare_date[0] = $compare_date[1]: ".DgS::printAr(DateTime::calcDaysInterval($compare_date[0], $compare_date[1]))."<br>";
print "CALCDAYSINTERVAL(named): $compare_date[0] = $compare_date[1]: ".DgS::printAr(DateTime::calcDaysInterval($compare_date[0], $compare_date[1], true))."<br>";
print "CALCDAYSINTERVAL: $compare_date[0] = $compare_date[1]: "
. DgS::printAr(DateTime::calcDaysInterval($compare_date[0], $compare_date[1])) . "<br>";
print "CALCDAYSINTERVAL(named): $compare_date[0] = $compare_date[1]: "
. DgS::printAr(DateTime::calcDaysInterval($compare_date[0], $compare_date[1], true)) . "<br>";
}
// DEPRECATED
@@ -135,11 +142,14 @@ print "CHECKDATE: $check_date: ".(string)$basic->checkDate($check_date)."<br>";
$check_datetime = '2021-05-01 12:13:14';
print "CHECKDATETIME: $check_datetime: ".(string)$basic->checkDateTime($check_datetime)."<br>";
$compare_date = ['2021-05-01', '2021-05-02'];
print "COMPAREDATE: $compare_date[0] = $compare_date[1]: ".(string)$basic->compareDate($compare_date[0], $compare_date[1])."<br>";
print "COMPAREDATE: $compare_date[0] = $compare_date[1]: "
. (string)$basic->compareDate($compare_date[0], $compare_date[1])."<br>";
$compare_datetime = ['2021-05-01 10:00:00', '2021-05-01 11:00:00'];
print "COMPAREDATE: $compare_datetime[0] = $compare_datetime[1]: ".(string)$basic->compareDateTime($compare_datetime[0], $compare_datetime[1])."<br>";
print "COMPAREDATE: $compare_datetime[0] = $compare_datetime[1]: "
. (string)$basic->compareDateTime($compare_datetime[0], $compare_datetime[1])."<br>";
$compare_date = ['2021-05-01', '2021-05-10'];
print "CALCDAYSINTERVAL(named): $compare_date[0] = $compare_date[1]: ".DgS::printAr($basic->calcDaysInterval($compare_date[0], $compare_date[1], true))."<br>"; */
print "CALCDAYSINTERVAL(named): $compare_date[0] = $compare_date[1]: "
. DgS::printAr($basic->calcDaysInterval($compare_date[0], $compare_date[1], true))."<br>"; */
// error message
print $basic->log->printErrorMsg();

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true;
$PRINT_ALL = true;
@@ -18,6 +21,8 @@ ob_start();
define('USE_DATABASE', true);
// sample config
require 'config.php';
// override ECHO ALL FALSE
$ECHO_ALL = true;
// set session name
if (!defined('SET_SESSION_NAME')) {
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
@@ -28,114 +33,220 @@ ob_end_flush();
use CoreLibs\Debug\Support as DgS;
$basic = new CoreLibs\Admin\Backend(DB_CONFIG);
$db = $basic = new CoreLibs\Admin\Backend(DB_CONFIG);
// NEXT STEP
// $basic = new CoreLibs\Basic();
// change __construct
// add object $logger
// add $this->log = $logger;
// $db = new CoreLibs\DB\IO(DB_CONFIG, $basic->log);
print "<html><head><title>TEST CLASS: DB</title><head>";
print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
print "DBINFO: ".$basic->dbInfo()."<br>";
echo "DB_CONFIG_SET constant: <pre>".print_r(DB_CONFIG, true)."</pre><br>";
print "DBINFO: " . $db->dbInfo() . "<br>";
echo "DB_CONFIG_SET constant: <pre>" . print_r(DB_CONFIG, true) . "</pre><br>";
// DB client encoding
print "DB Client encoding: ".$basic->dbGetEncoding()."<br>";
print "DB Client encoding: " . $db->dbGetEncoding() . "<br>";
while ($res = $basic->dbReturn("SELECT * FROM max_test", 0, true)) {
print "TIME: ".$res['time']."<br>";
while (is_array($res = $db->dbReturn("SELECT * FROM max_test", 0, true))) {
print "TIME: " . $res['time'] . "<br>";
}
print "CACHED DATA: <pre>".print_r($basic->cursor_ext, true)."</pre><br>";
while ($res = $basic->dbReturn("SELECT * FROM max_test")) {
print "[CACHED] TIME: ".$res['time']."<br>";
print "CACHED DATA: <pre>" . print_r($db->cursor_ext, true) . "</pre><br>";
while (is_array($res = $db->dbReturn("SELECT * FROM max_test"))) {
print "[CACHED] TIME: " . $res['time'] . "<br>";
}
// alternate check for valid data
// while (($res = $db->dbReturn("SELECT * FROM max_test")) !== false) {
// print "[CACHED] TIME: " . $res['time'] . "<br>";
// }
print "<pre>";
$status = $basic->dbExec("INSERT INTO foo (test) VALUES ('FOO TEST ".time()."') RETURNING test");
// truncate test_foo table before testing
print "<b>TRUNCATE test_foo</b><br>";
$query = "TRUNCATE test_foo";
$db->dbExec($query);
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");
print "DIRECT INSERT STATUS: $status | "
."PRIMARY KEY: ".$basic->dbGetInsertPK()." | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | "
."RETURNING ARRAY: ".print_r($basic->dbGetReturningArray(), true)."<br>";
. "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>";
// should throw deprecated error
// $basic->getReturningExt();
print "DIRECT INSERT PREVIOUS INSERTED: ".print_r($basic->dbReturnRow("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->dbGetInsertPK()), true)."<br>";
$basic->dbPrepare("ins_foo", "INSERT INTO foo (test) VALUES ($1)");
$status = $basic->dbExecute("ins_foo", array('BAR TEST '.time()));
print "PREPARE INSERT STATUS: $status | "
."PRIMARY KEY: ".$basic->dbGetInsertPK()." | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | "
."RETURNING RETURN: ".print_r($basic->dbGetReturningArray(), true)."<br>";
// $db->getReturningExt();
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>";
print "PREPARE INSERT PREVIOUS INSERTED: ".print_r($basic->dbReturnRow("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->dbGetInsertPK()), true)."<br>";
// PREPARED INSERT
$db->dbPrepare("ins_test_foo", "INSERT INTO test_foo (test) VALUES ($1) RETURNING test");
$status = $db->dbExecute("ins_test_foo", array('BAR TEST ' . time()));
print "PREPARE INSERT[ins_test_foo] STATUS: $status | "
. "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING RETURN: " . print_r($db->dbGetReturningArray(), true) . "<br>";
print "PREPARE INSERT PREVIOUS INSERTED: "
. print_r($db->dbReturnRow("SELECT test_foo_id, test FROM test_foo "
. "WHERE test_foo_id = " . $db->dbGetInsertPK()), true) . "<br>";
// returning test with multiple entries
// $status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id");
$status = $basic->dbExec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id, test");
print "DIRECT MULTIPLE INSERT STATUS: $status | "
."PRIMARY KEYS: ".print_r($basic->dbGetInsertPK(), true)." | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | "
."RETURNING ARRAY: ".print_r($basic->dbGetReturningArray(), true)."<br>";
// $status = $db->db_exec(
// "INSERT INTO test_foo (test) VALUES "
// . "('BAR 1 " . time() . "'), "
// . "('BAR 2 " . time() . "'), "
// . "('BAR 3 " . time() . "') "
// . "RETURNING test_foo_id"
// );
$status = $db->dbExec(
"INSERT INTO test_foo (test) VALUES "
. "('BAR 1 " . time() . "'), "
. "('BAR 2 " . time() . "'), "
. "('BAR 3 " . time() . "') "
. "RETURNING test_foo_id, test"
);
print "DIRECT MULTIPLE INSERT WITH RETURN STATUS: $status | "
. "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 = $basic->dbExec("INSERT INTO foo (test) VALUES ('FOO; TEST ".time()."');");
print "DIRECT INSERT STATUS: $status | "
."PRIMARY KEY: ".$basic->dbGetInsertPK()." | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | "
."RETURNING ARRAY: ".print_r($basic->dbGetReturningArray(), true)."<br>";
$status = $db->dbExec("INSERT INTO test_foo (test) VALUES ('FOO; TEST " . time() . "');");
print "DIRECT INSERT NO RETURN STATUS: $status | "
. "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
$last_insert_pk = $db->dbGetInsertPK();
// is_array read test
$q = "SELECT test_foo_id, test FROM test_foo WHERE test_foo_id = " . $last_insert_pk;
if (is_array($s_res = $db->dbReturnRow($q)) && !empty($s_res['test'])) {
print "WE HAVE DATA FOR: " . $last_insert_pk . " WITH: " . $s_res['test'] . "<br>";
}
// UPDATE WITH RETURNING
$status = $basic->dbExec("UPDATE foo SET test = 'SOMETHING DIFFERENT' WHERE foo_id = 3688452 RETURNING test");
print "UPDATE STATUS: $status | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | "
."RETURNING ARRAY: ".print_r($basic->dbGetReturningArray(), true)."<br>";
$status = $db->dbExec("UPDATE test_foo SET test = 'SOMETHING DIFFERENT' "
. "WHERE test_foo_id = " . $last_insert_pk . " RETURNING test");
print "UPDATE WITH PK " . $last_insert_pk . " RETURN STATUS: $status | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
// INSERT WITH NO RETURNING
$status = $db->dbExec("INSERT INTO test_foobar (type, integer) VALUES ('WITH DATA', 123)");
print "INSERT WITH NO PRIMARY KEY NO RETURNING STATUS: $status | "
. "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
$status = $db->dbExec("INSERT INTO test_foobar (type, integer) VALUES ('WITH DATA', 123) RETURNING type, integer");
print "INSERT WITH NO PRIMARY KEY WITH RETURNING STATUS: $status | "
. "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
. "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
. "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
print "</pre>";
// REEAD PREPARE
if ($basic->dbPrepare('sel_foo', "SELECT foo_id, test, some_bool, string_a, number_a, number_a_numeric, some_time FROM foo ORDER BY foo_id DESC LIMIT 5") === false) {
print "Error in sel_foo prepare<br>";
// READ PREPARE
if (
$db->dbPrepare(
'sel_test_foo',
"SELECT test_foo_id, test, some_bool, string_a, number_a, number_a_numeric, some_time "
. "FROM test_foo ORDER BY test_foo_id DESC LIMIT 5"
) === false
) {
print "Error in sel_test_foo prepare<br>";
} else {
$max_rows = 6;
// do not run this in dbFetchArray directly as
// dbFetchArray(dbExecute(...))
// this will end in an endless loop
$cursor = $basic->dbExecute('sel_foo', []);
$cursor = $db->dbExecute('sel_test_foo', []);
$i = 1;
while (($res = $basic->dbFetchArray($cursor, true)) !== false) {
print "DB PREP EXEC FETCH ARR: ".$i.": <pre>".print_r($res, true)."</pre><br>";
$i ++;
while (($res = $db->dbFetchArray($cursor, true)) !== false) {
print "DB PREP EXEC FETCH ARR: " . $i . ": <pre>" . print_r($res, true) . "</pre><br>";
$i++;
}
}
# db write class test
$table = 'foo';
print "TABLE META DATA: ".DgS::printAr($basic->dbShowTableMetaData($table))."<br>";
$table = 'test_foo';
print "TABLE META DATA: " . DgS::printAr($db->dbShowTableMetaData($table)) . "<br>";
// insert first, then use primary key to update
$primary_key = ''; # unset
$db_write_table = array('test', 'string_a', 'number_a', 'some_bool');
// $db_write_table = array('test');
$object_fields_not_touch = array();
$object_fields_not_update = array();
$data = array('test' => 'BOOL TEST SOMETHING '.time(), 'string_a' => 'SOME TEXT', 'number_a' => 5);
$primary_key = $basic->dbWriteDataExt($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data);
print "Wrote to DB tabel $table and got primary key $primary_key<br>";
$data = array('test' => 'BOOL TEST ON '.time(), 'string_a' => '', 'number_a' => 0, 'some_bool' => 1);
$primary_key = $basic->dbWriteDataExt($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data);
print "Wrote to DB tabel $table and got primary key $primary_key<br>";
$data = array('test' => 'BOOL TEST OFF '.time(), 'string_a' => null, 'number_a' => null, 'some_bool' => 0);
$primary_key = $basic->dbWriteDataExt($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data);
print "Wrote to DB tabel $table and got primary key $primary_key<br>";
$data = array('test' => 'BOOL TEST UNSET '.time());
$primary_key = $basic->dbWriteDataExt($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data);
print "Wrote to DB tabel $table and got primary key $primary_key<br>";
$db_write_table = ['test', 'string_a', 'number_a', 'some_bool'];
$object_fields_not_touch = [];
$object_fields_not_update = [];
$data = [
'test' => 'dbWriteDataExt: BOOL TEST SOMETHING ' . time(), 'string_a' => 'SOME TEXT', 'number_a' => 5
];
$primary_key = $db->dbWriteDataExt(
$db_write_table,
$primary_key,
$table,
$object_fields_not_touch,
$object_fields_not_update,
$data
);
print "Wrote to DB tabel $table with data " . print_r($data, true) . " and got primary key $primary_key<br>";
$data = [
'test' => 'dbWriteDataExt: BOOL TEST ON ' . time(), 'string_a' => '', 'number_a' => 0, 'some_bool' => 1
];
$primary_key = $db->dbWriteDataExt(
$db_write_table,
$primary_key,
$table,
$object_fields_not_touch,
$object_fields_not_update,
$data
);
print "Wrote to DB tabel $table with data " . print_r($data, true) . " and got primary key $primary_key<br>";
$data = [
'test' => 'dbWriteDataExt: BOOL TEST OFF ' . time(), 'string_a' => null, 'number_a' => null, 'some_bool' => 0
];
$primary_key = $db->dbWriteDataExt(
$db_write_table,
$primary_key,
$table,
$object_fields_not_touch,
$object_fields_not_update,
$data
);
print "Wrote to DB tabel $table with data " . print_r($data, true) . " and got primary key $primary_key<br>";
$data = [
'test' => 'dbWriteDataExt: BOOL TEST UNSET ' . time()
];
$primary_key = $db->dbWriteDataExt(
$db_write_table,
$primary_key,
$table,
$object_fields_not_touch,
$object_fields_not_update,
$data
);
print "Wrote to DB tabel $table with data " . print_r($data, true) . " and got primary key $primary_key<br>";
// return Array Test
$query = "SELECT type, sdate, integer FROM foobar";
$data = $basic->dbReturnArray($query, true);
print "Full foobar list: <br><pre>".print_r($data, true)."</pre><br>";
$data = $db->dbReturnArray($query, true);
print "Full foobar list: <br><pre>" . print_r($data, true) . "</pre><br>";
# async test queries
/* $basic->dbExecAsync("SELECT test FROM foo, (SELECT pg_sleep(10)) as sub WHERE foo_id IN (27, 50, 67, 44, 10)");
/*
$db->dbExecAsync("SELECT test FROM test_foo, (SELECT pg_sleep(10)) as sub WHERE test_foo_id IN (27, 50, 67, 44, 10)");
echo "WAITING FOR ASYNC: ";
$chars = array('|', '/', '-', '\\');
while (($ret = $basic->dbCheckAsync()) === true)
while (($ret = $db->dbCheckAsync()) === true)
{
if ((list($_, $char) = each($chars)) === FALSE)
{
@@ -146,60 +257,71 @@ while (($ret = $basic->dbCheckAsync()) === true)
sleep(1);
flush();
}
print "<br>END STATUS: ".$ret."<br>";
// while ($res = $basic->dbFetchArray($ret))
while ($res = $basic->dbFetchArray())
print "<br>END STATUS: " . $ret . "<br>";
// while ($res = $db->dbFetchArray($ret))
while ($res = $db->dbFetchArray())
{
echo "RES: ".$res['test']."<br>";
echo "RES: " . $res['test'] . "<br>";
}
# test async insert
$basic->dbExecAsync("INSERT INTO foo (Test) VALUES ('ASYNC TEST ".time()."')");
$db->dbExecAsync("INSERT INTO test_foo (Test) VALUES ('ASYNC TEST " . time() . "')");
echo "WAITING FOR ASYNC INSERT: ";
while (($ret = $basic->dbCheckAsync()) === true)
while (($ret = $db->dbCheckAsync()) === true)
{
print ".";
print " . ";
sleep(1);
flush();
}
print "<br>END STATUS: ".$ret." | PK: ".$basic->insert_id."<br>";
print "ASYNC PREVIOUS INSERTED: ".print_r($basic->dbReturnRow("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), true)."<br>"; */
print "<br>END STATUS: " . $ret . " | PK: " . $db->insert_id . "<br>";
print "ASYNC PREVIOUS INSERTED: "
. print_r(
$db->dbReturnRow("SELECT test_foo_id, test FROM test_foo WHERE test_foo_id = "
. $db->insert_id),
true
) . "<br>";
*/
$to_db_version = '9.1.9';
print "VERSION DB: ".$basic->dbVersion()."<br>";
print "DB Version smaller $to_db_version: ".$basic->dbCompareVersion('<'.$to_db_version)."<br>";
print "DB Version smaller than $to_db_version: ".$basic->dbCompareVersion('<='.$to_db_version)."<br>";
print "DB Version equal $to_db_version: ".$basic->dbCompareVersion('='.$to_db_version)."<br>";
print "DB Version bigger than $to_db_version: ".$basic->dbCompareVersion('>='.$to_db_version)."<br>";
print "DB Version bigger $to_db_version: ".$basic->dbCompareVersion('>'.$to_db_version)."<br>";
print "VERSION DB: " . $db->dbVersion() . "<br>";
print "DB Version smaller $to_db_version: " . $db->dbCompareVersion('<' . $to_db_version) . "<br>";
print "DB Version smaller than $to_db_version: " . $db->dbCompareVersion('<=' . $to_db_version) . "<br>";
print "DB Version equal $to_db_version: " . $db->dbCompareVersion('=' . $to_db_version) . "<br>";
print "DB Version bigger than $to_db_version: " . $db->dbCompareVersion('>=' . $to_db_version) . "<br>";
print "DB Version bigger $to_db_version: " . $db->dbCompareVersion('>' . $to_db_version) . "<br>";
/* $q = "SELECT FOO FRO BAR";
// $q = "Select * from foo";
$foo = $basic->dbExecAsync($q);
print "[ERR] Query: ".$q."<br>";
print "[ERR] RESOURCE: $foo<br>";
while (($ret = $basic->dbCheckAsync()) === true)
/*
$q = "Select * from test_foo";
$test_foo = $db->dbExecAsync($q);
print "[ERR] Query: " . $q . "<br>";
print "[ERR] RESOURCE: $test_foo<br>";
while (($ret = $db->dbCheckAsync()) === true)
{
print "[ERR]: $ret<br>";
sleep(5);
} */
}
*/
// search path check
$q = "SHOW search_path";
$cursor = $basic->dbExec($q);
$data = $basic->dbFetchArray($cursor)['search_path'];
print "RETURN DATA FOR search_path: ".$data."<br>";
// print "RETURN DATA FOR search_path: ".DgS::printAr($data)."<br>";
$cursor = $db->dbExec($q);
$data = $db->dbFetchArray($cursor)['search_path'];
print "RETURN DATA FOR search_path: " . $data . "<br>";
// print "RETURN DATA FOR search_path: " . DgS::printAr($data) . "<br>";
// insert something into test.schema_test and see if we get the PK back
$status = $basic->dbExec("INSERT INTO test.schema_test (contents, id) VALUES ('TIME: ".time()."', ".rand(1, 10).")");
print "OTHER SCHEMA INSERT STATUS: ".$status." | PK NAME: ".$basic->pk_name.", PRIMARY KEY: ".$basic->insert_id."<br>";
$status = $db->dbExec(
"INSERT INTO test.schema_test (contents, id) VALUES "
. "('TIME: " . time() . "', " . rand(1, 10) . ")"
);
print "OTHER SCHEMA INSERT STATUS: "
. $status . " | PK NAME: " . $db->dbGetInsertPKName() . ", PRIMARY KEY: " . $db->dbGetInsertPK() . "<br>";
print "<b>NULL TEST DB READ</b><br>";
$q = "SELECT uid, null_varchar, null_int FROM test_null_data WHERE uid = 'A'";
$res = $basic->dbReturnRow($q);
$res = $db->dbReturnRow($q);
var_dump($res);
print "RES: ".DgS::printAr($res)."<br>";
print "ISSET: ".isset($res['null_varchar'])."<br>";
print "EMPTY: ".empty($res['null_varchar'])."<br>";
print "RES: " . DgS::printAr($res) . "<br>";
print "ISSET: " . isset($res['null_varchar']) . "<br>";
print "EMPTY: " . empty($res['null_varchar']) . "<br>";
// error message
print $basic->log->printErrorMsg();

View File

@@ -1,9 +1,11 @@
<?php // phpcs:ignore warning
declare(strict_types=1);
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
// all the settings are overruled by config
$DEBUG_ALL_OVERRIDE = true; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true;
@@ -48,16 +50,19 @@ function test()
return DebugSupport::getCallerMethod(1);
}
print "S::GETCALLERMETHOD: ".DebugSupport::getCallerMethod(0)."<br>";
print "S::GETCALLERMETHOD: ".test()."<br>";
print "S::PRINTAR: ".DebugSupport::printAr(['Foo', 'Bar'])."<br>";
print "V-S::PRINTAR: ".$debug_support_class::printAr(['Foo', 'Bar'])."<br>";
print "S::GETCALLERMETHOD: " . DebugSupport::getCallerMethod(0) . "<br>";
print "S::GETCALLERMETHOD: " . test() . "<br>";
print "S::PRINTAR: " . DebugSupport::printAr(['Foo', 'Bar']) . "<br>";
print "V-S::PRINTAR: " . $debug_support_class::printAr(['Foo', 'Bar']) . "<br>";
print "S::DEBUSTRING(s): " . DebugSupport::debugString('SET') . "<br>";
print "S::DEBUSTRING(''): " . DebugSupport::debugString('') . "<br>";
print "S::DEBUSTRING(,s): " . DebugSupport::debugString(null, '{-}') . "<br>";
// debug
print "C->DEBUG: ".$debug->debug('CLASS-TEST-DEBUG', 'Class Test Debug')."<br>";
print "C->DEBUG(html): ".$debug->debug('CLASS-TEST-DEBUG', 'HTML TAG<br><b>BOLD</b>')."<br>";
print "C->DEBUG(html,strip): ".$debug->debug('CLASS-TEST-DEBUG', 'HTML TAG<br><b>BOLD</b>', true)."<br>";
print "C->PRINTERRORMSG: <br>".$debug->printErrorMsg()."<br>";
print "C->DEBUG: " . $debug->debug('CLASS-TEST-DEBUG', 'Class Test Debug') . "<br>";
print "C->DEBUG(html): " . $debug->debug('CLASS-TEST-DEBUG', 'HTML TAG<br><b>BOLD</b>') . "<br>";
print "C->DEBUG(html,strip): " . $debug->debug('CLASS-TEST-DEBUG', 'HTML TAG<br><b>BOLD</b>', true) . "<br>";
print "C->PRINTERRORMSG: <br>" . $debug->printErrorMsg() . "<br>";
echo "<b>CLASS DEBUG CALL</b><br>";
// @codingStandardsIgnoreLine
@@ -70,8 +75,8 @@ class TestL
}
public function test(string $ts = null)
{
print "* GETCALLERCLASS(INSIDE CLASS): ".\CoreLibs\Debug\Support::getCallerClass()."<br>";
$this->log->debug('TESTL', 'Logging in class testL'.($ts !== null ? ': '.$ts : ''));
print "* GETCALLERCLASS(INSIDE CLASS): " . \CoreLibs\Debug\Support::getCallerClass() . "<br>";
$this->log->debug('TESTL', 'Logging in class testL' . ($ts !== null ? ': ' . $ts : ''));
$this->log->debug('TESTL', 'Some other message');
return true;
}
@@ -86,22 +91,23 @@ class TestR extends TestL
}
public function subTest()
{
print "** GETCALLERCLASS(INSIDE EXTND CLASS): ".\CoreLibs\Debug\Support::getCallerClass()."<br>";
print "** GETCALLERCLASS(INSIDE EXTND CLASS): " . \CoreLibs\Debug\Support::getCallerClass() . "<br>";
$this->log->debug('TESTR', 'Logging in class testR (extends testL)');
$this->test('TESTR INSIDE');
$this->log->debug('TESTR', 'Array: '.$this->log->prAr(['a', 'b']).', Other: '.$this->log->prAr(['a', 'b']));
$this->log->debug('TESTR', 'Array: '
. $this->log->prAr(['a', 'b']) . ', Other: ' . $this->log->prAr(['a', 'b']));
return true;
}
}
$tl = new TestL();
print "CLASS: LOG ECHO: ".(string)$tl->log->getLogLevelAll('echo')."<br>";
print "CLASS: DEBUG: ".$tl->test()."<br>";
print "CLASS: PRINTERRORMSG: <br>".$tl->log->printErrorMsg()."<br>";
print "CLASS: LOG ECHO: " . (string)$tl->log->getLogLevelAll('echo') . "<br>";
print "CLASS: DEBUG: " . $tl->test() . "<br>";
print "CLASS: PRINTERRORMSG: <br>" . $tl->log->printErrorMsg() . "<br>";
$tr = new TestR();
print "CLASS: LOG ECHO: ".(string)$tr->log->getLogLevelAll('echo')."<br>";
print "CLASS EXTEND: DEBUG/tl: ".$tr->test('TESTR OUTSIDE')."<br>";
print "CLASS EXTEND: DEBUG/tr: ".$tr->subTest()."<br>";
print "CLASS EXTEND: PRINTERRORMSG: <br>".$tr->log->printErrorMsg()."<br>";
print "CLASS: LOG ECHO: " . (string)$tr->log->getLogLevelAll('echo') . "<br>";
print "CLASS EXTEND: DEBUG/tl: " . $tr->test('TESTR OUTSIDE') . "<br>";
print "CLASS EXTEND: DEBUG/tr: " . $tr->subTest() . "<br>";
print "CLASS EXTEND: PRINTERRORMSG: <br>" . $tr->log->printErrorMsg() . "<br>";
// test attaching a logger from outside
// @codingStandardsIgnoreLine
@@ -119,19 +125,39 @@ class AttachOutside
}
}
$ao = new AttachOutside($basic->log);
print "AO-CLASS: DEBUG: ".$ao->test()."<br>";
print "AO-CLASS: DEBUG: " . $ao->test() . "<br>";
print "GETCALLERCLASS(NON CLASS): ".\CoreLibs\Debug\Support::getCallerClass()."<br>";
// @codingStandardsIgnoreLine
class AttachFull
{
public $main;
public function __construct(object $class)
{
$this->main = $class;
}
public function test()
{
// should trigger deprecated
return $this->main->rgb2hex(2, 3, 4);
}
}
$af = new AttachFull($basic);
// should trigger deprecated
print "DEPREACTEDTEST: " . $af->test() . "<br>";
print "GETCALLERCLASS(NON CLASS): " . \CoreLibs\Debug\Support::getCallerClass() . "<br>";
// fdebug
print "S::FSETFILENAME: ".FileWriter::fsetFilename('class_test_debug_file.log')."<br>";
print "S::FDEBUG: ".FileWriter::fdebug('CLASS TEST DEBUG FILE: '.date('Y-m-d H:i:s'))."<br>";
print "S::FSETFILENAME: " . FileWriter::fsetFilename('class_test_debug_file.log') . "<br>";
print "S::FDEBUG: " . FileWriter::fdebug('CLASS TEST DEBUG FILE: ' . date('Y-m-d H:i:s')) . "<br>";
// error message
// future DEPRECATED
// $basic->debug('BASIC CLASS', 'Debug test');
$basic->log->debug('BASIC CLASS', 'Debug test');
print "BASIC PRINTERRORMSG:<br>".$basic->log->printErrorMsg();
print "BASIC PRINTERRORMSG:<br>" . $basic->log->printErrorMsg();
print "</body></html>";

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -36,19 +39,37 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
// regex get
print "S::GETEMAILREGEX(0): ".Email::getEmailRegex(0)."<br>";
print "S::GETEMAILREGEX(2): ".Email::getEmailRegex(2)."<br>";
print "S::GETEMAILREGEX(7): ".Email::getEmailRegex(7)."<br>";
print "S::GETEMAILREGEX(8 invalid): ".Email::getEmailRegex(8)."<br>";
print "S::GETEMAILREGEXCHECK: ".DgS::printAr(Email::getEmailRegexCheck())."<br>";
print "S::GETEMAILREGEX(0): " . Email::getEmailRegex(0) . "<br>";
print "S::GETEMAILREGEX(2): " . Email::getEmailRegex(2) . "<br>";
print "S::GETEMAILREGEX(7): " . Email::getEmailRegex(7) . "<br>";
print "S::GETEMAILREGEX(8 invalid): " . Email::getEmailRegex(8) . "<br>";
print "S::GETEMAILREGEXCHECK: " . DgS::printAr(Email::getEmailRegexCheck()) . "<br>";
print "S::GETEMAILREGEXERRORMESSAGE " . Dgs::printAr(Email::getEmailRegexErrorMessage(1)) . "<br>";
$email = [
'foo@bar.org',
'foo@i.softbank.ne.jp'
];
foreach ($email as $s_email) {
print "S::EMAIL: $s_email: ".Email::getEmailType($s_email)."<br>";
print "S::EMAIL SHORT: $s_email: ".Email::getEmailType($s_email, true)."<br>";
print "S::EMAIL: $s_email: " . Email::getEmailType($s_email) . "<br>";
print "S::EMAIL SHORT: $s_email: " . Email::getEmailType($s_email, true) . "<br>";
}
$email = [
'test@test.com',
'',
'-@-',
'.test@test.com',
'test@t_est.com',
'test@@test.com',
'test@test..com',
'test@@test..com',
'test@test.',
'test@test.j',
];
foreach ($email as $s_email) {
print "S::CHECKEMAIL: " . $s_email . ": " . (Email::checkEmail($s_email) ? 'Yes' : 'No') . "<br>";
print "S::CHECKEMAILFULL: " . $s_email . ": " . Dgs::printAr(Email::checkEmailFull($s_email)) . "<br>";
print "S::CHECKEMAILFULL(true): " . $s_email . ": " . Dgs::printAr(Email::checkEmailFull($s_email, true)) . "<br>";
}
// DEPRECATED
/* foreach ($email as $s_email) {

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -46,7 +49,7 @@ $mime_encodes = [
['日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい', 'ISO-2022-JP-MS'],
];
foreach ($mime_encodes as $mime_encode) {
print "__MBMIMEENCODE: $mime_encode[0]: ".Encoding::__mbMimeEncode($mime_encode[0], $mime_encode[1])."<br>";
print "__MBMIMEENCODE: $mime_encode[0]: " . Encoding::__mbMimeEncode($mime_encode[0], $mime_encode[1]) . "<br>";
}
$enc_strings = [
@@ -59,26 +62,29 @@ $enc_strings = [
$_encoding->setErrorChar('∴');
foreach ($enc_strings as $_string) {
$string = $_encoding->checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS');
print "ENC CHECK: $_string: ".($string === false ? '-OK-' : $string)."<br>";
print "CONV ENCODING: $_string: ".$_encoding->convertEncoding($_string, 'ISO-2022-JP')."<br>";
print "CONV ENCODING (s): $_string: ".$_encoding->convertEncoding($_string, 'ISO-2022-JP', 'UTF-8')."<br>";
print "CONV ENCODING (s,a-false): $_string: ".$_encoding->convertEncoding($_string, 'ISO-2022-JP', 'UTF-8', false)."<br>";
print "ENC CHECK: $_string: " . ($string === false ? '-OK-' : $string) . "<br>";
print "CONV ENCODING: $_string: " . $_encoding->convertEncoding($_string, 'ISO-2022-JP') . "<br>";
print "CONV ENCODING (s): $_string: " . $_encoding->convertEncoding($_string, 'ISO-2022-JP', 'UTF-8') . "<br>";
print "CONV ENCODING (s,a-false): $_string: "
. $_encoding->convertEncoding($_string, 'ISO-2022-JP', 'UTF-8', false) . "<br>";
}
print "ERROR CHAR: ".$_encoding->getErrorChar()."<br>";
print "ERROR CHAR: " . $_encoding->getErrorChar() . "<br>";
// static
$encoding_class::setErrorChar('∴');
foreach ($enc_strings as $_string) {
$string = $encoding_class::checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS');
print "S::ENC CHECK: $_string: ".($string === false ? '-OK-' : $string)."<br>";
print "S::CONV ENCODING: $_string: ".$encoding_class::convertEncoding($_string, 'ISO-2022-JP')."<br>";
print "S::CONV ENCODING (s): $_string: ".$encoding_class::convertEncoding($_string, 'ISO-2022-JP', 'UTF-8')."<br>";
print "S::CONV ENCODING (s,a-false): $_string: ".$encoding_class::convertEncoding($_string, 'ISO-2022-JP', 'UTF-8', false)."<br>";
print "S::ENC CHECK: $_string: " . ($string === false ? '-OK-' : $string) . "<br>";
print "S::CONV ENCODING: $_string: " . $encoding_class::convertEncoding($_string, 'ISO-2022-JP') . "<br>";
print "S::CONV ENCODING (s): $_string: "
. $encoding_class::convertEncoding($_string, 'ISO-2022-JP', 'UTF-8') . "<br>";
print "S::CONV ENCODING (s,a-false): $_string: "
. $encoding_class::convertEncoding($_string, 'ISO-2022-JP', 'UTF-8', false) . "<br>";
}
print "S::ERROR CHAR: ".$encoding_class::getErrorChar()."<br>";
print "S::ERROR CHAR: " . $encoding_class::getErrorChar() . "<br>";
// static use
$_string = $enc_strings[1];
$string = Encoding::checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS');
print "S::ENC CHECK: $_string: ".($string === false ? '-OK-' : $string)."<br>";
print "S::ENC CHECK: $_string: " . ($string === false ? '-OK-' : $string) . "<br>";
// DEPRECATED
/* $string = $basic->checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS');

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -35,9 +38,9 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
$file = '/some/path/to/some/file.txt';
print "GETFILENAMEENDING: $file: ".File::getFilenameEnding($file)."<br>";
$file = getcwd().DIRECTORY_SEPARATOR.'class_test.file.php';
print "GETLINESFROMFILE: $file: ".File::getLinesFromFile($file)."<br>";
print "GETFILENAMEENDING: $file: " . File::getFilenameEnding($file) . "<br>";
$file = getcwd() . DIRECTORY_SEPARATOR . 'class_test.file.php';
print "GETLINESFROMFILE: $file: " . File::getLinesFromFile($file) . "<br>";
// error message
print $basic->log->printErrorMsg();

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -39,15 +42,15 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$to_crc = 'Some text block';
// static
print "S::__CRC32B: $to_crc: ".$hash_class::__crc32b($to_crc)."<br>";
print "S::__SHA1SHORT(off): $to_crc: ".$hash_class::__sha1short($to_crc)."<br>";
print "S::__SHA1SHORT(on): $to_crc: ".$hash_class::__sha1short($to_crc, true)."<br>";
print "S::__hash(d): $to_crc: ".$hash_class::__hash($to_crc)."<br>";
print "S::__CRC32B: $to_crc: " . $hash_class::__crc32b($to_crc) . "<br>";
print "S::__SHA1SHORT(off): $to_crc: " . $hash_class::__sha1short($to_crc) . "<br>";
print "S::__SHA1SHORT(on): $to_crc: " . $hash_class::__sha1short($to_crc, true) . "<br>";
print "S::__hash(d): $to_crc: " . $hash_class::__hash($to_crc) . "<br>";
foreach (['adler32', 'fnv132', 'fnv1a32', 'joaat'] as $__hash_c) {
print "S::__hash($__hash_c): $to_crc: ".$hash_class::__hash($to_crc, $__hash_c)."<br>";
print "S::__hash($__hash_c): $to_crc: " . $hash_class::__hash($to_crc, $__hash_c) . "<br>";
}
// static use
print "U-S::__CRC32B: $to_crc: ".Hash::__crc32b($to_crc)."<br>";
print "U-S::__CRC32B: $to_crc: " . Hash::__crc32b($to_crc) . "<br>";
// DEPRECATED
/* print "D/__CRC32B: $to_crc: ".$basic->__crc32b($to_crc)."<br>";

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -42,21 +45,23 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
$string = "Something < = > Other <br> Next line";
print "HTMLENT: ".Html::htmlent($string).": ".$_html->htmlent($string)."<br>";
print "REMOVELB: ".Html::htmlent($string).": ".$_html->removeLB($string)."<br>";
print "HTMLENT: " . Html::htmlent($string) . ": " . $_html->htmlent($string) . "<br>";
print "REMOVELB: " . Html::htmlent($string) . ": " . $_html->removeLB($string) . "<br>";
$date_str = [2021, 5, 1, 11, 10];
print "PRINTDATETIME: ".$_elements->printDateTime($date_str[0], $date_str[1], $date_str[2], $date_str[3], $date_str[4])."<br>";
print "PRINTDATETIME: "
. $_elements->printDateTime($date_str[0], $date_str[1], $date_str[2], $date_str[3], $date_str[4]) . "<br>";
// STATIC
$string = "Something < = > Other <br> Next line";
print "S::HTMLENT: ".Html::htmlent($string).": ".$html_class::htmlent($string)."<br>";
print "S::REMOVELB: ".Html::htmlent($string).": ".$html_class::removeLB($string)."<br>";
print "S::HTMLENT: " . Html::htmlent($string) . ": " . $html_class::htmlent($string) . "<br>";
print "S::REMOVELB: " . Html::htmlent($string) . ": " . $html_class::removeLB($string) . "<br>";
$date_str = [2021, 5, 1, 11, 10];
print "S::PRINTDATETIME: ".$elements_class::printDateTime($date_str[0], $date_str[1], $date_str[2], $date_str[3], $date_str[4])."<br>";
print "S::PRINTDATETIME: "
. $elements_class::printDateTime($date_str[0], $date_str[1], $date_str[2], $date_str[3], $date_str[4]) . "<br>";
// STATIC use
echo "U-S::HTML ENT INT: ".Html::htmlent(5)."<br>";
echo "U-S::HTML ENT STRING: ".Html::htmlent('5<<>')."<br>";
echo "U-S::HTML ENT NULL: ".Html::htmlent(null)."<br>";
echo "U-S::HTML ENT INT: " . Html::htmlent(5) . "<br>";
echo "U-S::HTML ENT STRING: " . Html::htmlent('5<<>') . "<br>";
echo "U-S::HTML ENT NULL: " . Html::htmlent(null) . "<br>";
// check convert
$checked_list = [
@@ -66,8 +71,8 @@ $checked_list = [
['foo', ['bar']],
];
foreach ($checked_list as $check) {
print "CHECKED(0): $check[0]: ".Html::checked($check[1], $check[0])."<br>";
print "CHECKED(1): $check[0]: ".Html::checked($check[1], $check[0], 1)."<br>";
print "CHECKED(0): $check[0]: " . Html::checked($check[1], $check[0]) . "<br>";
print "CHECKED(1): $check[0]: " . Html::checked($check[1], $check[0], 1) . "<br>";
}
// magic link creation test
@@ -80,7 +85,7 @@ $magic_links = [
'http://www.somelink.com/?with=1234 <br>Some Title',
];
foreach ($magic_links as $magic_link) {
print "MAGICLINK: ".Html::htmlent($magic_link).": ".Html::htmlent(Elements::magicLinks($magic_link))."<br>";
print "MAGICLINK: " . Html::htmlent($magic_link) . ": " . Html::htmlent(Elements::magicLinks($magic_link)) . "<br>";
}
// DEPREACTED
@@ -88,11 +93,20 @@ foreach ($magic_links as $magic_link) {
print "D/HTMLENT: $string: ".$basic->htmlent($string)."<br>";
print "D/REMOVELB: $string: ".$basic->removeLB($string)."<br>";
$date_str = [2021, 5, 1, 11, 10];
print "D/PRINTDATETIME: ".$basic->printDateTime($date_str[0], $date_str[1], $date_str[2], $date_str[3], $date_str[4])."<br>";
print "D/PRINTDATETIME: "
. $basic->printDateTime($date_str[0], $date_str[1], $date_str[2], $date_str[3], $date_str[4])."<br>";
$magic_link = 'http://www.somelink.com/?with=1234|Some Title|';
print "D/MAGICLINK: ".Html::htmlent($basic->magicLinks($magic_link))."<Br>";
*/
$text = 'I am some text
with some
line breaks
in there. Theis
is sucky';
print "LB remove: " . \CoreLibs\Convert\Html::removeLB($text) . "<br>";
print "LB remove: " . \CoreLibs\Convert\Html::removeLB($text, '##BR##') . "<br>";
// error message
print $basic->log->printErrorMsg();

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -42,17 +45,21 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$thumb_width = 250;
$thumb_height = 300;
// class
$image = BASE.LAYOUT.CONTENT_PATH.IMAGES.'no_picture_square.jpg';
$image = BASE . LAYOUT . CONTENT_PATH . IMAGES . 'no_picture_square.jpg';
// rotate image first
$_image->correctImageOrientation($image);
// thumbnail tests
echo "<div>CLASS->CREATETHUMBNAILSIMPLE: ".basename($image).": WIDTH: $thumb_width<br><img src=".$_image->createThumbnailSimple($image, $thumb_width)."></div>";
echo "<div>CLASS->CREATETHUMBNAILSIMPLE: "
. basename($image) . ": WIDTH: $thumb_width<br><img src="
. $_image->createThumbnailSimple($image, $thumb_width) . "></div>";
// static
$image = BASE.LAYOUT.CONTENT_PATH.IMAGES.'no_picture.jpg';
$image = BASE . LAYOUT . CONTENT_PATH . IMAGES . 'no_picture.jpg';
// rotate image first
$image_class::correctImageOrientation($image);
// thumbnail tests
echo "<div>S::CREATETHUMBNAILSIMPLE: ".basename($image).": WIDTH: $thumb_width<br><img src=".$image_class::createThumbnailSimple($image, $thumb_width)."></div>";
echo "<div>S::CREATETHUMBNAILSIMPLE: "
. basename($image) . ": WIDTH: $thumb_width<br><img src="
. $image_class::createThumbnailSimple($image, $thumb_width) . "></div>";
echo "U-STATIC VARIOUS:<br>";
// image thumbnail
@@ -76,17 +83,22 @@ $images = array(
// return mime type ala mimetype
$finfo = new finfo(FILEINFO_MIME_TYPE);
foreach ($images as $image) {
$image = BASE.LAYOUT.CONTENT_PATH.IMAGES.$image;
$image = BASE . LAYOUT . CONTENT_PATH . IMAGES . $image;
list ($height, $width, $img_type) = getimagesize($image);
echo "<div><b>IMAGE INFO</b>: ".$height."x".$width.", TYPE: ".$img_type." [".$finfo->file($image)."]</div>";
echo "<div><b>IMAGE INFO</b>: " . $height . "x" . $width . ", TYPE: "
. $img_type . " [" . $finfo->file($image) . "]</div>";
// rotate image first
Image::correctImageOrientation($image);
// thumbnail tests
echo "<div>".basename($image).": WIDTH: $thumb_width<br><img src=".Image::createThumbnailSimple($image, $thumb_width)."></div>";
echo "<div>".basename($image).": HEIGHT: $thumb_height<br><img src=".Image::createThumbnailSimple($image, 0, $thumb_height)."></div>";
echo "<div>".basename($image).": WIDTH/HEIGHT: $thumb_width x $thumb_height<br><img src=".Image::createThumbnailSimple($image, $thumb_width, $thumb_height)."></div>";
echo "<div>" . basename($image) . ": WIDTH: $thumb_width<br><img src="
. Image::createThumbnailSimple($image, $thumb_width) . "></div>";
echo "<div>" . basename($image) . ": HEIGHT: $thumb_height<br><img src="
. Image::createThumbnailSimple($image, 0, $thumb_height) . "></div>";
echo "<div>" . basename($image) . ": WIDTH/HEIGHT: $thumb_width x $thumb_height<br><img src="
. Image::createThumbnailSimple($image, $thumb_width, $thumb_height) . "></div>";
// test with dummy
echo "<div>".basename($image).": WIDTH/HEIGHT: $thumb_width x $thumb_height (+DUMMY)<br><img src=".Image::createThumbnailSimple($image, $thumb_width, $thumb_height, null, true, false)."></div>";
echo "<div>" . basename($image) . ": WIDTH/HEIGHT: $thumb_width x $thumb_height (+DUMMY)<br><img src="
. Image::createThumbnailSimple($image, $thumb_width, $thumb_height, null, true, false) . "></div>";
echo "<hr>";
}
@@ -96,7 +108,8 @@ foreach ($images as $image) {
// rotate image first
$basic->correctImageOrientation($image);
// thumbnail tests
echo "<div>S::CREATETHUMBNAILSIMPLE: ".basename($image).": WIDTH: $thumb_width<br><img src=".$basic->createThumbnailSimple($image, $thumb_width)."></div>"; */
echo "<div>S::CREATETHUMBNAILSIMPLE: ".basename($image).": WIDTH: $thumb_width<br><img src="
. $basic->createThumbnailSimple($image, $thumb_width)."></div>"; */
// error message
print $basic->log->printErrorMsg();

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -40,24 +43,24 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$json = '{"foo": "bar"}';
$output = Jason::jsonConvertToArray($json);
print "S::JSON: $json: ".DgS::printAr($output)."<br>";
print "S::JSON ERROR: ".Jason::jsonGetLastError().": ".Jason::jsonGetLastError(true)."<br>";
print "S::JSON: $json: " . DgS::printAr($output) . "<br>";
print "S::JSON ERROR: " . Jason::jsonGetLastError() . ": " . Jason::jsonGetLastError(true) . "<br>";
$json = '["f: {b"""ar}]';
$output = Jason::jsonConvertToArray($json);
print "S::E-JSON: $json: ".DgS::printAr($output)."<br>";
print "S::E-JSON ERROR: ".Jason::jsonGetLastError().": ".Jason::jsonGetLastError(true)."<br>";
print "S::E-JSON: $json: " . DgS::printAr($output) . "<br>";
print "S::E-JSON ERROR: " . Jason::jsonGetLastError() . ": " . Jason::jsonGetLastError(true) . "<br>";
// direct
$json = '{"direct": "static function call"}';
$output = $json_class::jsonConvertToArray($json);
print "J/S::JSON: $json: ".DgS::printAr($output)."<br>";
print "J/S::JSON ERROR: ".$json_class::jsonGetLastError().": ".$json_class::jsonGetLastError(true)."<br>";
print "J/S::JSON: $json: " . DgS::printAr($output) . "<br>";
print "J/S::JSON ERROR: " . $json_class::jsonGetLastError() . ": " . $json_class::jsonGetLastError(true) . "<br>";
$json = '["f: {b"""ar}]';
$output = $json_class::jsonConvertToArray($json);
print "J/S::E-JSON: $json: ".DgS::printAr($output)."<br>";
print "J/S::E-JSON ERROR: ".$json_class::jsonGetLastError().": ".$json_class::jsonGetLastError(true)."<br>";
print "J/S::E-JSON: $json: " . DgS::printAr($output) . "<br>";
print "J/S::E-JSON ERROR: " . $json_class::jsonGetLastError() . ": " . $json_class::jsonGetLastError(true) . "<br>";
// DEPRECATE TEST
/* $json = '["f: {b"""ar}]';

View File

@@ -0,0 +1,57 @@
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
$DB_DEBUG = 1;
if ($DEBUG_ALL) {
error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
}
ob_start();
// basic class test file
define('USE_DATABASE', false);
// init language
$lang = 'en_utf8';
// sample config
require 'config.php';
// set session name
if (!defined('SET_SESSION_NAME')) {
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
}
// define log file id
$LOG_FILE_ID = 'classTest-lang';
$l = new CoreLibs\Language\L10n($lang);
ob_end_flush();
print "<html><head><title>TEST CLASS: LANG</title><head>";
print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
$string = 'INPUT TEST';
echo "LANGUAGE SET: " . $l->__getLang() . "<br>";
echo "LANGUAGE FILE: " . $l->__getMoFile() . "<br>";
echo "INPUT TEST: " . $string . " => " . $l->__($string) . "<br>";
// switch to other language
$lang = 'ja_utf8';
$l->l10nReloadMOfile($lang);
echo "LANGUAGE SET: " . $l->__getLang() . "<br>";
echo "LANGUAGE FILE: " . $l->__getMoFile() . "<br>";
echo "INPUT TEST: " . $string . " => " . $l->__($string) . "<br>";
// TODO: run compare check input must match output
print "</body></html>";
// __END__

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -36,13 +39,17 @@ print "<html><head><title>TEST CLASS: MATH</title><head>";
print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
print "FCEIL: ".$_math->fceil(5.1234567890, 5)."<br>";
print "FLOORP: ".$_math->floorp(5123456, -3)."<br>";
print "INITNUMERIC: ".$_math->initNumeric('123')."<br>";
print "FCEIL: " . $_math->fceil(5.1234567890, 5) . "<br>";
print "FLOORP: " . $_math->floorp(5123456, -3) . "<br>";
print "FLOORP: " . $_math->floorp(5123456, -10) . "<br>";
print "INITNUMERIC: " . $_math->initNumeric('123') . "<br>";
print "S-FCEIL: ".$math_class::fceil(5.1234567890, 5)."<br>";
print "S-FLOORP: ".$math_class::floorp(5123456, -3)."<br>";
print "S-INITNUMERIC: ".$math_class::initNumeric('123')."<br>";
print "S-FCEIL: " . $math_class::fceil(5.1234567890, 5) . "<br>";
print "S-FLOORP: " . $math_class::floorp(5123456, -3) . "<br>";
print "S-INITNUMERIC: " . $math_class::initNumeric(123) . "<br>";
print "S-INITNUMERIC: " . $math_class::initNumeric(123.456) . "<br>";
print "S-INITNUMERIC: " . $math_class::initNumeric('123') . "<br>";
print "S-INITNUMERIC: " . $math_class::initNumeric('123.456') . "<br>";
// DEPRECATED
/* print "FCEIL: ".$basic->fceil(5.1234567890, 5)."<br>";

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -34,22 +37,22 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
$mime = 'application/illustrator';
print "MIME $mime: ".$_mime->mimeGetAppName($mime)."<br>";
print "MIME $mime: " . $_mime->mimeGetAppName($mime) . "<br>";
$mime = 'fake/mime';
$_mime->mimeSetAppName($mime, 'This is a fake mime');
print "MIME $mime: ".$_mime->mimeGetAppName($mime)."<br>";
print "MIME $mime: " . $_mime->mimeGetAppName($mime) . "<br>";
// mime test
$mime = 'application/vnd.ms-excel';
print "App for mime $mime: ".$_mime->mimeGetAppName($mime)."<br>";
print "App for mime $mime: " . $_mime->mimeGetAppName($mime) . "<br>";
$_mime->mimeSetAppName($mime, 'Microsoft (better) Excel');
print "App for mime changed $mime: ".$_mime->mimeGetAppName($mime)."<br>";
print "App for mime changed $mime: " . $_mime->mimeGetAppName($mime) . "<br>";
// static call test
$mime = 'application/x-indesign';
print "S::App for mime $mime: ".\CoreLibs\Convert\MimeAppName::mimeGetAppName($mime)."<br>";
print "S::App for mime $mime: " . \CoreLibs\Convert\MimeAppName::mimeGetAppName($mime) . "<br>";
$mime = 'application/vnd.ms-excel';
print "S::App for mime $mime: ".\CoreLibs\Convert\MimeAppName::mimeGetAppName($mime)."<br>";
print "S::App for mime $mime: " . \CoreLibs\Convert\MimeAppName::mimeGetAppName($mime) . "<br>";
// DEPRECATED
/* $mime = 'application/illustrator';

View File

@@ -0,0 +1,77 @@
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true;
$PRINT_ALL = true;
$DB_DEBUG = true;
if ($DEBUG_ALL) {
error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
}
ob_start();
// basic class test file
define('USE_DATABASE', true);
// sample config
require 'config.php';
// override ECHO ALL FALSE
$ECHO_ALL = true;
// set session name
if (!defined('SET_SESSION_NAME')) {
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
}
// define log file id
$LOG_FILE_ID = 'classTest-form';
ob_end_flush();
// define an array for page use
$table_arrays = [];
$table_arrays[\CoreLibs\Get\System::getPageName(1)] = [
// form fields mtaching up with db fields
'table_array' => [
],
// laod query
'load_query' => '',
// database table to load from
'table_name' => '',
// for load dro pdown, format output
'show_fields' => [
[
'name' => 'name'
],
[
'name' => 'enabled',
'binary' => ['Yes', 'No'],
'before_value' => 'Enabled: '
],
],
// a multi reference entry
'element_list' => [
]
];
$basic = new CoreLibs\Basic();
$form = new CoreLibs\Output\Form\Generate(DB_CONFIG);
// $db = new CoreLibs\DB\IO(DB_CONFIG, $basic->log);
print "<html><head><title>TEST CLASS: FORM GENERATE</title><head>";
print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
print "MOBILE PHONE: " . $form->mobile_phone . "<br>";
// sets table array to include
print "MY PAGE NAME: " . $form->my_page_name . "<br>";
// error message
print $basic->log->printErrorMsg();
print "</body></html>";
// __END__

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -40,17 +43,17 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$password = 'something1234';
$enc_password = $_password->passwordSet($password);
print "PASSWORD: $password: ".$enc_password."<br>";
print "PASSWORD VERIFY: ".(string)$_password->passwordVerify($password, $enc_password)."<br>";
print "PASSWORD REHASH: ".(string)$_password->passwordRehashCheck($enc_password)."<br>";
print "PASSWORD: $password: " . $enc_password . "<br>";
print "PASSWORD VERIFY: " . (string)$_password->passwordVerify($password, $enc_password) . "<br>";
print "PASSWORD REHASH: " . (string)$_password->passwordRehashCheck($enc_password) . "<br>";
// static verify
$password = 'othername7890';
$enc_password = $password_class::passwordSet($password);
print "PASSWORD: $password: ".$enc_password."<br>";
print "S-PASSWORD VERIFY: ".(string)$password_class::passwordVerify($password, $enc_password)."<br>";
print "PASSWORD REHASH: ".(string)$password_class::passwordRehashCheck($enc_password)."<br>";
print "PASSWORD: $password: " . $enc_password . "<br>";
print "S-PASSWORD VERIFY: " . (string)$password_class::passwordVerify($password, $enc_password) . "<br>";
print "PASSWORD REHASH: " . (string)$password_class::passwordRehashCheck($enc_password) . "<br>";
// direct static
print "S::PASSWORD VERFIY: ".(string)PwdChk::passwordVerify($password, $enc_password)."<br>";
print "S::PASSWORD VERFIY: " . (string)PwdChk::passwordVerify($password, $enc_password) . "<br>";
// DEPRECATED
/* $password = 'deprecated4567';

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true;
$PRINT_ALL = true;
@@ -56,12 +59,21 @@ print '<div><a href="class_test.randomkey.php">Class Test: RANDOM KEY</a></div>'
print '<div><a href="class_test.system.php">Class Test: SYSTEM</a></div>';
print '<div><a href="class_test.runningtime.php">Class Test: RUNNING TIME</a></div>';
print '<div><a href="class_test.debug.php">Class Test: DEBUG</a></div>';
print '<div><a href="class_test.form.php">Class Test: FORM</a></div>';
print '<div><a href="class_test.backend.php">Class Test: BACKEND ADMIN CLASS</a></div>';
print '<div><a href="class_test.lang.php">Class Test: LANG/L10n</a></div>';
print '<div><a href="class_test.smarty.php">Class Test: SMARTY</a></div>';
print '<div><a href="class_test.autoloader.php">Class Test: AUTOLOADER</a></div>';
print "<hr>";
// print all _ENV vars set
print "<div>READ _ENV ARRAY:</div>";
print "<pre>" . print_r(array_map('htmlentities', $_ENV), true) . "</pre>";
// set + check edit access id
$edit_access_id = 3;
if (is_object($login) && isset($login->acl['unit'])) {
print "ACL UNIT: ".print_r(array_keys($login->acl['unit']), true)."<br>";
print "ACCESS CHECK: ".(string)$login->loginCheckEditAccess($edit_access_id)."<br>";
print "ACL UNIT: " . print_r(array_keys($login->acl['unit']), true) . "<br>";
print "ACCESS CHECK: " . (string)$login->loginCheckEditAccess($edit_access_id) . "<br>";
if ($login->loginCheckEditAccess($edit_access_id)) {
$basic->edit_access_id = $edit_access_id;
} else {
@@ -74,7 +86,8 @@ if (is_object($login) && isset($login->acl['unit'])) {
// $basic->log->debug('SESSION', \CoreLibs\Debug\Support::printAr($_SESSION));
print '<form method="post" name="loginlogout">';
print '<a href="javascript:document.loginlogout.login_logout.value=\'Logou\';document.loginlogout.submit();">Logout</a>';
print '<a href="javascript:document.loginlogout.login_logout.value=\'Logou\';'
. 'document.loginlogout.submit();">Logout</a>';
print '<input type="hidden" name="login_logout" value="">';
print '</form>';
@@ -82,28 +95,49 @@ print '</form>';
foreach (['on', 'off'] as $flag) {
foreach (['debug', 'echo', 'print'] as $type) {
$prefix = $flag == 'off' ? 'NOT ' : '';
print $prefix.strtoupper($type).' OUT: '.\CoreLibs\Debug\Support::printAr($basic->log->getLogLevel($type, $flag)).'<br>';
print $prefix . strtoupper($type) . ' OUT: '
. \CoreLibs\Debug\Support::printAr($basic->log->getLogLevel($type, $flag)) . '<br>';
}
}
foreach (['debug', 'echo', 'print'] as $type) {
print strtoupper($type).' OUT ALL: '.$basic->log->getLogLevelAll($type).'<br>';
print strtoupper($type) . ' OUT ALL: ' . $basic->log->getLogLevelAll($type) . '<br>';
}
$basic->log->debug('SOME MARK', 'Some error output');
// INTERNAL SET
print "EDIT ACCESS ID: ".$basic->edit_access_id."<br>";
print "EDIT ACCESS ID: " . $basic->edit_access_id . "<br>";
if (is_object($login)) {
// print "ACL: <br>".$basic->print_ar($login->acl)."<br>";
$basic->log->debug('ACL', "ACL: ".\CoreLibs\Debug\Support::printAr($login->acl));
$basic->log->debug('ACL', "ACL: " . \CoreLibs\Debug\Support::printAr($login->acl));
// print "DEFAULT ACL: <br>".$basic->print_ar($login->default_acl_list)."<br>";
// print "DEFAULT ACL: <br>".$basic->print_ar($login->default_acl_list)."<br>";
// $result = array_flip(array_filter(array_flip($login->default_acl_list), function ($key) { if (is_numeric($key)) return $key; }));
// $result = array_flip(
// array_filter(
// array_flip($login->default_acl_list),
// function ($key) {
// if (is_numeric($key)) {
// return $key;
// }
// }
// )
// );
// print "DEFAULT ACL: <br>".$basic->print_ar($result)."<br>";
// DEPRICATED CALL
// $basic->adbSetACL($login->acl);
}
print "THIS HOST: " . HOST_NAME . ", with PROTOCOL: " . HOST_PROTOCOL . " is running SSL: " . HOST_SSL . "<br>";
print "DIR: " . DIR . "<br>";
print "BASE: " . BASE . "<br>";
print "ROOT: " . ROOT . "<br>";
print "HOST: " . HOST_NAME . " => DB HOST: " . DB_CONFIG_NAME . " => " . print_r(DB_CONFIG, true) . "<br>";
$ds = defined('DS') ? DS : DIRECTORY_SEPARATOR;
$du = DS ?? DIRECTORY_SEPARATOR;
print "DS is: " . $ds . "<br>";
print "SERVER HOST: " . $_SERVER['HTTP_HOST'] . "<br>";
// print error messages
// print $login->log->printErrorMsg();
print $basic->log->printErrorMsg();

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -43,17 +46,18 @@ $min_version_ss = '7.1';
$min_version = '7.1.0';
$max_version = '7.3.1';
// class
print "MIN: $min_version: ".(string)$_phpv->checkPHPVersion($min_version)."<br>";
print "MIN/MAX: $min_version/$max_version: ".(string)$_phpv->checkPHPVersion($min_version, $max_version)."<br>";
print "MIN/S: $min_version_s: ".(string)$_phpv->checkPHPVersion($min_version_s)."<br>";
print "MIN/SS: $min_version_ss: ".(string)$_phpv->checkPHPVersion($min_version_ss)."<br>";
print "MIN: $min_version: " . (string)$_phpv->checkPHPVersion($min_version) . "<br>";
print "MIN/MAX: $min_version/$max_version: " . (string)$_phpv->checkPHPVersion($min_version, $max_version) . "<br>";
print "MIN/S: $min_version_s: " . (string)$_phpv->checkPHPVersion($min_version_s) . "<br>";
print "MIN/SS: $min_version_ss: " . (string)$_phpv->checkPHPVersion($min_version_ss) . "<br>";
// static
print "S::MIN: $min_version: ".(string)$phpv_class::checkPHPVersion($min_version)."<br>";
print "S::MIN/MAX: $min_version/$max_version: ".(string)$phpv_class::checkPHPVersion($min_version, $max_version)."<br>";
print "S::MIN/S: $min_version_s: ".(string)$phpv_class::checkPHPVersion($min_version_s)."<br>";
print "S::MIN/SS: $min_version_ss: ".(string)$phpv_class::checkPHPVersion($min_version_ss)."<br>";
print "S::MIN: $min_version: " . (string)$phpv_class::checkPHPVersion($min_version) . "<br>";
print "S::MIN/MAX: $min_version/$max_version: "
. (string)$phpv_class::checkPHPVersion($min_version, $max_version) . "<br>";
print "S::MIN/S: $min_version_s: " . (string)$phpv_class::checkPHPVersion($min_version_s) . "<br>";
print "S::MIN/SS: $min_version_ss: " . (string)$phpv_class::checkPHPVersion($min_version_ss) . "<br>";
// use stats
print "U-S::MIN: $min_version: ".(string)PhpVersion::checkPHPVersion($min_version)."<br>";
print "U-S::MIN: $min_version: " . (string)PhpVersion::checkPHPVersion($min_version) . "<br>";
// DEPRECATED
// print "MIN: $min_version: ".(string)$basic->checkPHPVersion($min_version)."<br>";

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -37,13 +40,13 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$key_length = 10;
$key_length_b = 5;
print "S::RANDOMKEYGEN(auto): ".RandomKey::randomKeyGen()."<br>";
print "S::SETRANDOMKEYLENGTH($key_length): ".RandomKey::setRandomKeyLength($key_length)."<br>";
print "S::RANDOMKEYGEN($key_length): ".RandomKey::randomKeyGen()."<br>";
print "S::RANDOMKEYGEN($key_length_b): ".RandomKey::randomKeyGen($key_length_b)."<br>";
print "S::RANDOMKEYGEN($key_length): ".RandomKey::randomKeyGen()."<br>";
$_array= new CoreLibs\Create\RandomKey();
print "C->RANDOMKEYGEN(auto): ".$_array->randomKeyGen()."<br>";
print "S::RANDOMKEYGEN(auto): " . RandomKey::randomKeyGen() . "<br>";
print "S::SETRANDOMKEYLENGTH($key_length): " . RandomKey::setRandomKeyLength($key_length) . "<br>";
print "S::RANDOMKEYGEN($key_length): " . RandomKey::randomKeyGen() . "<br>";
print "S::RANDOMKEYGEN($key_length_b): " . RandomKey::randomKeyGen($key_length_b) . "<br>";
print "S::RANDOMKEYGEN($key_length): " . RandomKey::randomKeyGen() . "<br>";
$_array = new CoreLibs\Create\RandomKey();
print "C->RANDOMKEYGEN(auto): " . $_array->randomKeyGen() . "<br>";
// DEPRECATED
// print "D\RANDOMKEYGEN(auto): ".$basic->randomKeyGen()."<br>";

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -36,13 +39,13 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
RunningTime::hrRunningTime();
RunningTime::runningTime();
echo "RANDOM KEY [50]: ".\CoreLibs\Create\RandomKey::randomKeyGen(50)."<br>";
echo "TIMED [hr]: ".RunningTime::hrRunningTime()."<br>";
echo "TIMED [def]: ".RunningTime::runningTime()."<br>";
echo "TIMED [string]: ".RunningTime::runningTimeString()."<br>";
echo "RANDOM KEY [50]: " . \CoreLibs\Create\RandomKey::randomKeyGen(50) . "<br>";
echo "TIMED [hr]: " . RunningTime::hrRunningTime() . "<br>";
echo "TIMED [def]: " . RunningTime::runningTime() . "<br>";
echo "TIMED [string]: " . RunningTime::runningTimeString() . "<br>";
RunningTime::hrRunningTime();
echo "RANDOM KEY [default]: ".\CoreLibs\Create\RandomKey::randomKeyGen()."<br>";
echo "TIMED [hr]: ".RunningTime::hrRunningTime()."<br>";
echo "RANDOM KEY [default]: " . \CoreLibs\Create\RandomKey::randomKeyGen() . "<br>";
echo "TIMED [hr]: " . RunningTime::hrRunningTime() . "<br>";
// DEPRECATED
/* $basic->hrRunningTime();

View File

@@ -0,0 +1,97 @@
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true;
$PRINT_ALL = true;
$DB_DEBUG = true;
if ($DEBUG_ALL) {
error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
}
ob_start();
// basic class test file
define('USE_DATABASE', true);
// set language
$lang = 'en_utf8';
// sample config
require 'config.php';
// override ECHO ALL FALSE
$ECHO_ALL = true;
// set session name
if (!defined('SET_SESSION_NAME')) {
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
}
// define log file id
$LOG_FILE_ID = 'classTest-smarty';
ob_end_flush();
$basic = new CoreLibs\Basic();
$smarty = new CoreLibs\Template\SmartyExtend();
// for testing with or without CMS
// $cms = new CoreLibs\Admin\Backend(DB_CONFIG);
$l = new CoreLibs\Language\L10n($lang);
print "<html><head><title>TEST CLASS: SMARTY</title><head>";
print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
$smarty->DATA['JS_DEBUG'] = DEBUG;
$smarty->MASTER_TEMPLATE_NAME = 'main_body.tpl';
$smarty->TEMPLATE_NAME = 'smarty_test.tpl';
$smarty->CSS_SPECIAL_TEMPLATE_NAME = 'smart_test.css';
$smarty->USE_PROTOTYPE = false;
$smarty->USE_JQUERY = true;
$smarty->JS_DATEPICKR = false;
if ($smarty->USE_PROTOTYPE) {
$smarty->ADMIN_JAVASCRIPT = 'edit.pt.js';
$smarty->JS_SPECIAL_TEMPLATE_NAME = 'prototype.test.js';
} elseif ($smarty->USE_JQUERY) {
$smarty->ADMIN_JAVASCRIPT = 'edit.jq.js';
$smarty->JS_SPECIAL_TEMPLATE_NAME = 'jquery.test.js';
}
$smarty->PAGE_WIDTH = '100%';
// require BASE.INCLUDES.'admin_set_paths.php';
$smarty->setSmartyPaths();
// smarty test
$smarty->DATA['SMARTY_TEST'] = 'Test Data';
$smarty->DATA['TRANSLATE_TEST'] = $l->__('Are we translated?');
$smarty->DATA['TRANSLATE_TEST_SMARTY'] = $smarty->l10n->__('Are we translated?');
// drop down test with optgroups
$options = [
'' => '選択してください',
'4/25(木)' => [
'4/25(木) 11:00-11:50' => '4/25(木) 11:00-11:50',
'4/25(木) 12:20-13:00' => '4/25(木) 12:20-13:00'
],
'4/26(金)' => [
'4/26(金) 11:00-11:50' => '4/26(金) 11:00-11:50',
'4/26(金) 12:20-13:00' => '4/26(金) 12:20-13:00'
],
'4/27(土)' => [
'4/27(土) 11:00-11:50' => '4/27(土) 11:00-11:50',
'4/27(土) 12:20-13:00' => '4/27(土) 12:20-13:00'
],
];
$smarty->DATA['drop_down_test'] = $options;
$smarty->DATA['drop_down_test_selected'] = '';
$smarty->DATA['loop_start'] = 2;
// require BASE.INCLUDES.'admin_smarty.php';
$smarty->setSmartyVarsAdmin();
// error message
print $basic->log->printErrorMsg();
print "</body></html>";
// __END__

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -35,13 +38,15 @@ print "<html><head><title>TEST CLASS: SYSTEM</title><head>";
print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
print "GETHOSTNAME: ".DgS::printAr(System::getHostName())."<br>";
print "GETPAGENAME(0): ".System::getPageName()."<br>";
print "GETPAGENAME(1): ".System::getPageName(1)."<br>";
print "GETPAGENAME(2): ".System::getPageName(2)."<br>";
print "GETHOSTNAME: " . DgS::printAr(System::getHostName()) . "<br>";
print "GETPAGENAME(0): " . System::getPageName() . "<br>";
print "GETPAGENAME(1): " . System::getPageName(1) . "<br>";
print "GETPAGENAME(2): " . System::getPageName(2) . "<br>";
print "GETPAGENAMEARRAY: " . \CoreLibs\Debug\Support::printAr(System::getPageNameArray()) . "<br>";
// seting errro codes file upload
print "FILEUPLOADERRORMESSAGE(): ".System::fileUploadErrorMessage(-1)."<br>";
print "FILEUPLOADERRORMESSAGE(UPLOAD_ERR_CANT_WRITE): ".System::fileUploadErrorMessage(UPLOAD_ERR_CANT_WRITE)."<br>";
print "FILEUPLOADERRORMESSAGE(): " . System::fileUploadErrorMessage(-1) . "<br>";
print "FILEUPLOADERRORMESSAGE(UPLOAD_ERR_CANT_WRITE): "
. System::fileUploadErrorMessage(UPLOAD_ERR_CANT_WRITE) . "<br>";
// error message
print $basic->log->printErrorMsg();

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -36,13 +39,13 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$token = 'test_form_token';
$token_id = $_token->setFormToken($token);
print "TOKEN: $token: (ID) ".$token_id." => (S) ".$_SESSION[$token]."<br>";
print "VALIDATE: $token: ".(string)$_token->validateFormToken($token_id, $token)."<br>";
print "TOKEN: $token: (ID) " . $token_id . " => (S) " . $_SESSION[$token] . "<br>";
print "VALIDATE: $token: " . (string)$_token->validateFormToken($token_id, $token) . "<br>";
$token = 'test_form_token_static';
$token_id = $token_class::setFormToken($token);
print "S-TOKEN: $token: (ID) ".$token_id." => (S) ".$_SESSION[$token]."<br>";
print "S-VALIDATE: $token: ".(string)$token_class::validateFormToken($token_id, $token)."<br>";
print "S-TOKEN: $token: (ID) " . $token_id . " => (S) " . $_SESSION[$token] . "<br>";
print "S-VALIDATE: $token: " . (string)$token_class::validateFormToken($token_id, $token) . "<br>";
// DEPRECATED
/* $token = 'test_form_token_deprecated';

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
@@ -35,15 +38,15 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>';
// class
print "UUIDV4: ".$_uids->uuidv4()."<br>";
print "UNIQID (d): ".$_uids->uniqId()."<br>";
print "UNIQID (md5): ".$_uids->uniqId('md5')."<br>";
print "UNIQID (sha256): ".$_uids->uniqId('sha256')."<br>";
print "UUIDV4: " . $_uids->uuidv4() . "<br>";
print "UNIQID (d): " . $_uids->uniqId() . "<br>";
print "UNIQID (md5): " . $_uids->uniqId('md5') . "<br>";
print "UNIQID (sha256): " . $_uids->uniqId('sha256') . "<br>";
// statc
print "S::UUIDV4: ".$uids_class::uuidv4()."<br>";
print "S::UNIQID (d): ".$uids_class::uniqId()."<br>";
print "S::UNIQID (md5): ".$uids_class::uniqId('md5')."<br>";
print "S::UNIQID (sha256): ".$uids_class::uniqId('sha256')."<br>";
print "S::UUIDV4: " . $uids_class::uuidv4() . "<br>";
print "S::UNIQID (d): " . $uids_class::uniqId() . "<br>";
print "S::UNIQID (md5): " . $uids_class::uniqId('md5') . "<br>";
print "S::UNIQID (sha256): " . $uids_class::uniqId('sha256') . "<br>";
// DEPRECATED
/* print "D/UUIDV4: ".$basic->uuidv4()."<br>";
print "/DUNIQID (d): ".$basic->uniqId()."<br>"; */

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
@@ -11,8 +13,8 @@ if ($DEBUG_ALL) {
// sample config
require 'config.php';
echo "FILE: ".BASE.LIB."Error.Handling.php<br>";
require(BASE.LIB."Error.Handling.php");
echo "FILE: " . BASE . LIB . "Error.Handling.php<br>";
require(BASE . LIB . "Error.Handling.php");
if ($var) {
echo "OUT<br>";

View File

@@ -1,29 +0,0 @@
<?php declare(strict_types=1);
// debug for L10n issues in php 7.3
// namespace test
ob_start();
// init language
$lang = 'en_utf8';
// admin class tests
require 'config.php';
$l = new CoreLibs\Language\L10n($lang);
ob_end_flush();
$string = 'INPUT TEST';
echo "LANGUAGE SET: ".$l->__getLang()."<br>";
echo "LANGUAGE FILE: ".$l->__getMoFile()."<br>";
echo "INPUT TEST: ".$string." => ".$l->__($string)."<br>";
// switch to other language
$lang = 'ja_utf8';
$l->l10nReloadMOfile($lang);
echo "LANGUAGE SET: ".$l->__getLang()."<br>";
echo "LANGUAGE FILE: ".$l->__getMoFile()."<br>";
echo "INPUT TEST: ".$string." => ".$l->__($string)."<br>";
// __END__

View File

@@ -1,41 +0,0 @@
<?php declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
$DB_DEBUG = 1;
// namespace test
ob_start();
// admin class tests
require 'config.php';
$SET_SESSION_NAME = EDIT_SESSION_NAME;
echo "DIR: ".DIR."<br>ROOT: ".ROOT."<br>BASE: ".BASE."<br>";
$base = new CoreLibs\Admin\Backend(DB_CONFIG);
ob_end_flush();
if ($base->getConnectionStatus()) {
die("Cannot connect to database");
}
print "Start time: ".\CoreLibs\Debug\RunningTime::runningTime()."<br>";
print "HumanReadableByteFormat: ".\CoreLibs\Convert\Byte::HumanReadableByteFormat(1234567.12)."<br>";
print "humanReadableByteFormat: ".\CoreLibs\Convert\Byte::humanReadableByteFormat(1234567.12)."<br>";
print "getPageName: ". \CoreLibs\Get\System::getPageName()."<br>";
print "DB Info: ".$base->dbInfo(true)."<br>";
print "End Time: ".\CoreLibs\Debug\RunningTime::runningTime()."<br>";
print "Start Time: ".\CoreLibs\Debug\RunningTime::runningTime()."<br>";
print "Lang: ".$base->l->__getLang().", MO File: ".$base->l->__getMoFile()."<br>";
print "Translate test: Year -> ".$base->l->__('Year')."<br>";
print "End Time: ".\CoreLibs\Debug\RunningTime::runningTime()."<br>";
// end error print
print $base->log->printErrorMsg();
# __END__

View File

@@ -1,34 +0,0 @@
<?php declare(strict_types=1);
namespace Foo;
class FooBar
{
public $foo = '';
public function __construct()
{
$this->foo = 'BAR';
}
public function otherBarBar($wrong)
{
echo "B: $wrong<br>";
}
public function barBar($wrong)
{
echo "B: $wrong<br>";
}
}
$foo = $bar ?? 'EMPTY';
echo "BAR: ".$foo."<br>";
// define('DS', DIRECTORY_SEPARATOR);
$ds = defined('DS') ? DS : DIRECTORY_SEPARATOR;
$du = DS ?? DIRECTORY_SEPARATOR;
echo "DS is: ".$ds."<br>";
echo "SERVER HOST: ".$_SERVER['HTTP_HOST']."<br>";
// __END__

View File

@@ -1,7 +1,9 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
require 'config.php';
require BASE.INCLUDES.'admin_header.php';
require BASE . INCLUDES . 'admin_header.php';
// $DATA['foo'] = 'bar';
// $messages['foo'] = 'bar';

View File

@@ -15,17 +15,19 @@ $MAX_UPLOAD_SIZE = $base->StringByteFormat(ini_get('upload_max_filesize'));
// test for qqFileUploader (AJAX side)
$allowedExtensions = array ('csv', 'zip', 'jpg', 'pdf', 'bz2');
$sizeLimit = $MAX_UPLOAD_SIZE; // as set in php ini
$base->debug('AJAX UPLOAD', 'Size: '.$sizeLimit.', Memory Limit: '.ini_get('memory_limit'));
$base->debug('AJAX UPLOAD', 'Size: ' . $sizeLimit . ', Memory Limit: ' . ini_get('memory_limit'));
$uploader = new FileUpload\qqFileUploader($allowedExtensions, $sizeLimit);
// either in post or get
$_action= $_POST['action'] ? $_POST['action'] : $_GET['action'];
$_action = $_POST['action'] ? $_POST['action'] : $_GET['action'];
$_task_uid = $_POST['task_uid'] ? $_POST['task_uid'] : $_GET['task_uid'];
$get_post['start'] = microtime(true);
$base->debug('AJAX UPLOAD', 'Action: '.$_action.', Task UID: '.$_task_uid.' => '.$base->dateStringFormat($get_post['start']));
$base->debug('AJAX UPLOAD', 'Action: ' . $_action . ', Task UID: '
. $_task_uid . ' => ' . $base->dateStringFormat($get_post['start']));
$upload_path = ROOT.MEDIA.UPLOADS;
$upload_path = ROOT . MEDIA . UPLOADS;
$get_post['result'] = $uploader->handleUpload($upload_path, false);
$base->debug('AJAX UPLOAD', 'Memory peak: '.$base->ByteStringFormat(memory_get_usage()).' | '.$base->ByteStringFormat(memory_get_peak_usage()));
$base->debug('AJAX UPLOAD', 'Memory peak: ' . $base->ByteStringFormat(memory_get_usage())
. ' | ' . $base->ByteStringFormat(memory_get_peak_usage()));
// set file name
$get_post['filename'] = $uploader->uploadFileName;

View File

@@ -10,7 +10,7 @@ require 'config.php';
$base = new CoreLibs\Basic();
// set max upload size
$MAX_UPLOAD_SIZE = $base->StringByteFormat(ini_get('upload_max_filesize'));
$base->debug('UPLOADED FRONT', 'With max size: '.$MAX_UPLOAD_SIZE);
$base->debug('UPLOADED FRONT', 'With max size: ' . $MAX_UPLOAD_SIZE);
// very basic template output with super basic div for two file upload
?>

View File

@@ -1,59 +0,0 @@
<?php declare(strict_types=1);
$ENABLE_ERROR_HANDLING = 0;
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
$DB_DEBUG = 1;
$LOG_PER_RUN = 1;
define('USE_DATABASE', true);
define('USE_HEADER', true);
require 'config.php';
require BASE.INCLUDES.'admin_header.php';
if (is_object($smarty)) {
$smarty->MASTER_TEMPLATE_NAME = 'main_body.tpl';
$smarty->TEMPLATE_NAME = 'smarty_test.tpl';
$smarty->CSS_SPECIAL_TEMPLATE_NAME = 'smart_test.css';
$smarty->USE_PROTOTYPE = false;
$smarty->USE_JQUERY = true;
$smarty->JS_DATEPICKR = false;
if ($smarty->USE_PROTOTYPE) {
$smarty->ADMIN_JAVASCRIPT = 'edit.pt.js';
$smarty->JS_SPECIAL_TEMPLATE_NAME = 'prototype.test.js';
} elseif ($smarty->USE_JQUERY) {
$smarty->ADMIN_JAVASCRIPT = 'edit.jq.js';
$smarty->JS_SPECIAL_TEMPLATE_NAME = 'jquery.test.js';
}
$smarty->PAGE_WIDTH = '100%';
// require BASE.INCLUDES.'admin_set_paths.php';
$smarty->setSmartyPaths();
// smarty test
$smarty->DATA['SMARTY_TEST'] = 'Test Data';
$smarty->DATA['TRANSLATE_TEST'] = $cms->l->__('Are we translated?');
}
// drop down test with optgroups
$options = array (
'' => '選択してください',
'4/25(木)' => array (
'4/25(木) 11:00-11:50' => '4/25(木) 11:00-11:50',
'4/25(木) 12:20-13:00' => '4/25(木) 12:20-13:00'
),
'4/26(金)' => array (
'4/26(金) 11:00-11:50' => '4/26(金) 11:00-11:50',
'4/26(金) 12:20-13:00' => '4/26(金) 12:20-13:00'
),
'4/27(土)' => array (
'4/27(土) 11:00-11:50' => '4/27(土) 11:00-11:50',
'4/27(土) 12:20-13:00' => '4/27(土) 12:20-13:00'
)
);
if (is_object($smarty)) {
$smarty->DATA['drop_down_test'] = $options;
$smarty->DATA['loop_start'] = 2;
// require BASE.INCLUDES.'admin_smarty.php';
$smarty->setSmartyVarsAdmin();
}
require BASE.INCLUDES.'admin_footer.php';

View File

@@ -1,111 +0,0 @@
<?php
/**
* @phan-file-suppress PhanTypeSuspiciousStringExpression
*/
namespace CoreLibs;
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
$DB_DEBUG = 1;
// admin class tests
require 'config.php';
$SET_SESSION_NAME = EDIT_SESSION_NAME;
$base = new Basic();
print "THIS HOST: ".HOST_NAME.", with PROTOCOL: ".HOST_PROTOCOL." is running SSL: ".HOST_SSL."<br>";
print "DIR: ".DIR."<br>";
print "BASE: ".BASE."<br>";
print "ROOT: ".ROOT."<br>";
print "HOST: ".HOST_NAME." => DB HOST: ".DB_CONFIG_NAME." => ".print_r(DB_CONFIG, true)."<br>";
$text = 'I am some text
with some
line breaks
in there. Theis
is sucky';
print "LB remove: ".\CoreLibs\Convert\Html::removeLB($text)."<br>";
print "LB remove: ".\CoreLibs\Convert\Html::removeLB($text, '##BR##')."<br>";
// $test = array (
// 'A' => array (
// 'B' => array (),
// 'C' => array (
// 'D' => array (),
// 'E' => array (
// 'F' => array ()
// )
// )
// ),
// '1' => array (),
// '2' => array (),
// '3' => array (
// 'G' => array ()
// )
// );
// $base->log->debug('ARRAY', \CoreLibs\Debug\Support::printAr($test));
function rec($pre, $cur, $node = array ())
{
if (!is_array($node)) {
$node = array ();
}
print "<div style='color: green;'>#### PRE: ".$pre.", CUR: ".$cur.", N-c: ".count($node)." [".join('|', array_keys($node))."]</div>";
if (!$pre) {
print "** <span style='color: red;'>NEW</span><br>";
$node[$cur] = array ();
} else {
if (array_key_exists($pre, $node)) {
print "+ <span style='color: orange;'>KEY FOUND:</span> ".$pre.", add: ".$cur."<br>";
$node[$pre][$cur] = array ();
} else {
print "- NOT FOUND: loop<br>";
foreach ($node as $_pre => $_cur) {
print "> TRY: ".$_pre." => ".count($_cur)." [".join('|', array_keys($_cur))."]<br>";
if (count($_cur) > 0) {
$node[$_pre] = rec($pre, $cur, $_cur);
}
}
}
}
return $node;
}
function flattenArrayKey(array $array, array $return = array ())
{
foreach ($array as $key => $sub) {
$return[] = $key;
if (count($sub) > 0) {
$return = flattenArrayKey($sub, $return);
}
}
return $return;
}
$test = array ();
// core
$test = rec('', 'A', $test);
$test = rec('', '1', $test);
$test = rec('', '2', $test);
$test = rec('', '3', $test);
$test = rec('3', 'G', $test);
$test = rec('A', 'B', $test);
$test = rec('A', 'C', $test);
$test = rec('C', 'D', $test);
$test = rec('C', 'E', $test);
$test = rec('E', 'F', $test);
// new
$test = rec('C', 'U', $test);
$test = rec('F', 'U', $test);
$test = rec('', 'Al', $test);
$test = rec('B', 'B1', $test);
$base->log->debug('REC', \CoreLibs\Debug\Support::printAr($test));
print "FLATTEN: ".\CoreLibs\Debug\Support::printAr(flattenArrayKey($test))."<br>";
print $base->log->printErrorMsg();
// __END__

View File

@@ -1,5 +1,5 @@
{
"name": "gullevek/www",
"name": "gullevek/corelibs",
"description": "CoreLibs",
"type": "library",
"authors": [
@@ -8,5 +8,12 @@
"email": "clemens.schwaighofer@egplusww.com"
}
],
"require": {}
"autoload": {
"classmap": [
"lib/"
]
},
"require-dev": {
"phpunit/phpunit": "^9"
}
}

2112
www/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

8
www/configs/.env.example Normal file
View File

@@ -0,0 +1,8 @@
# Master configs
BASE_NAME=
G_TITLE=
# DB configs
DB_NAME_TEST=
DB_USER_TEST=
DB_PASS_TEST=
DB_HOST_TEST=

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2018/10/11
@@ -7,19 +8,21 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
// please be VERY carefull only to change the right side
$DB_CONFIG = [
'test' => [
'db_name' => 'gullevek',
'db_user' => 'gullevek',
'db_pass' => 'gullevek',
'db_host' => 'db.tokyo.tequila.jp',
'db_name' => $_ENV['DB_NAME_TEST'] ?? '',
'db_user' => $_ENV['DB_USER_TEST'] ?? '',
'db_pass' => $_ENV['DB_PASS_TEST'] ?? '',
'db_host' => $_ENV['DB_HOST_TEST'] ?? '',
'db_port' => 5432,
'db_schema' => 'public',
'db_type' => 'pgsql',
'db_encoding' => '',
'db_ssl' => 'disable' // allow, disable, require, prefer
]
'db_ssl' => 'allow' // allow, disable, require, prefer
],
];
// __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2018/10/11
@@ -11,6 +12,8 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
// other master config to attach
// $__LOCAL_CONFIG = [
// 'db_host' => '',

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore PSR1.Files.SideEffects
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2003/06/10
@@ -7,75 +8,75 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
/************* PATHS *********************/
// directory seperator
define('DS', DIRECTORY_SEPARATOR);
// ** NEW/BETTER DIR DECLARATIONS **
// path to original file (if symlink)
define('DIR', __DIR__.DS);
define('DIR', __DIR__ . DS);
// base dir root folder level
define('BASE', str_replace('/configs', '', __DIR__).DS);
define('BASE', str_replace('/configs', '', __DIR__) . DS);
// ** OLD DIR DECLARATIONS **
// path to document root of file called
define('ROOT', getcwd().DS);
define('ROOT', getcwd() . DS);
// libs path
define('LIB', 'lib'.DS);
define('LIBS', 'lib'.DS);
define('LIB', 'lib' . DS);
define('LIBS', 'lib' . DS);
// configs folder
define('CONFIGS', 'configs'.DS);
define('CONFIGS', 'configs' . DS);
// includes (strings, arrays for static, etc)
define('INCLUDES', 'includes'.DS);
define('INCLUDES', 'includes' . DS);
// data folder (mostly in includes, or root for internal data)
define('DATA', 'data'.DS);
define('DATA', 'data' . DS);
// layout base path
define('LAYOUT', 'layout'.DS);
define('LAYOUT', 'layout' . DS);
// pic-root (compatible to CMS)
define('PICTURES', 'images'.DS);
define('PICTURES', 'images' . DS);
// images
define('IMAGES', 'images'.DS);
define('IMAGES', 'images' . DS);
// icons (below the images/ folder)
define('ICONS', 'icons'.DS);
define('ICONS', 'icons' . DS);
// media (accessable from outside)
define('MEDIA', 'media'.DS);
// flash-root (below media or data)
define('FLASH', 'flash'.DS);
define('MEDIA', 'media' . DS);
// uploads (anything to keep or data)
define('UPLOADS', 'uploads'.DS);
define('UPLOADS', 'uploads' . DS);
// files (binaries) (below media or data)
define('BINARIES', 'binaries'.DS);
define('BINARIES', 'binaries' . DS);
// files (videos) (below media or data)
define('VIDEOS', 'videos'.DS);
define('VIDEOS', 'videos' . DS);
// files (documents) (below media or data)
define('DOCUMENTS', 'documents'.DS);
define('DOCUMENTS', 'documents' . DS);
// files (pdfs) (below media or data)
define('PDFS', 'documents'.DS);
define('PDFS', 'documents' . DS);
// files (general) (below media or data)
define('FILES', 'files'.DS);
define('FILES', 'files' . DS);
// CSV
define('CSV', 'csv'.DS);
define('CSV', 'csv' . DS);
// css
define('CSS', 'css'.DS);
define('CSS', 'css' . DS);
// font (web)
define('FONT', 'font'.DS);
define('FONT', 'font' . DS);
// js
define('JS', 'javascript'.DS);
define('JS', 'javascript' . DS);
// table arrays
define('TABLE_ARRAYS', 'table_arrays'.DS);
define('TABLE_ARRAYS', 'table_arrays' . DS);
// smarty libs path
define('SMARTY', 'Smarty'.DS);
define('SMARTY', 'Smarty' . DS);
// po langs
define('LANG', 'lang'.DS);
define('LANG', 'lang' . DS);
// cache path
define('CACHE', 'cache'.DS);
define('CACHE', 'cache' . DS);
// temp path
define('TMP', 'tmp'.DS);
define('TMP', 'tmp' . DS);
// log files
define('LOG', 'log'.DS);
define('LOG', 'log' . DS);
// compiled template folder
define('TEMPLATES_C', 'templates_c'.DS);
define('TEMPLATES_C', 'templates_c' . DS);
// template base
define('TEMPLATES', 'templates'.DS);
define('TEMPLATES', 'templates' . DS);
/************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/
// default hash type
@@ -83,7 +84,7 @@ define('DEFAULT_HASH', 'sha256');
// default acl level
define('DEFAULT_ACL_LEVEL', 80);
// SSL host name
// define('SSL_HOST', 'ssl.host.name');
// define('SSL_HOST', $_ENV['SSL_HOST'] ?? '');
// error page strictness, Default is 3
// 1: only show error page as the last mesure if really no mid & aid can be loaded and found at all
// 2: if template not found, do not search, show error template
@@ -112,14 +113,14 @@ define('PASSWORD_SPECIAL_RANGE', '@$!%*?&');
define('PASSWORD_LOWER', '(?=.*[a-z])');
define('PASSWORD_UPPER', '(?=.*[A-Z])');
define('PASSWORD_NUMBER', '(?=.*\d)');
define('PASSWORD_SPECIAL', "(?=.*[".PASSWORD_SPECIAL_RANGE."])");
define('PASSWORD_SPECIAL', "(?=.*[" . PASSWORD_SPECIAL_RANGE . "])");
// 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."}$/");
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 . "}$/");
/************* AJAX / ACCESS *************/
// ajax request type
@@ -130,30 +131,31 @@ define('USE_SCRIPTACULOUS', false);
define('USE_JQUERY', true);
/************* LAYOUT WIDTHS *************/
define('PAGE_WIDTH', 800);
define('CONTENT_WIDTH', 800);
define('PAGE_WIDTH', '100%');
define('CONTENT_WIDTH', '100%');
// the default template name
define('MASTER_TEMPLATE_NAME', 'main_body.tpl');
/************* OVERALL CONTROL NAMES *************/
// BELOW has HAS to be changed
// base name for all session and log names
define('BASE_NAME', 'CoreLibs');
// only alphanumeric characters, strip all others
define('BASE_NAME', preg_replace('/[^A-Za-z0-9]/', '', $_ENV['BASE_NAME'] ?? ''));
/************* SESSION NAMES *************/
// server name HASH
define('SERVER_NAME_HASH', hash('crc32b', $_SERVER['HTTP_HOST']));
define('SERVER_PATH_HASH', hash('crc32b', BASE));
// backend
define('EDIT_SESSION_NAME', BASE_NAME.'Admin'.SERVER_NAME_HASH.SERVER_PATH_HASH);
define('EDIT_SESSION_NAME', BASE_NAME . 'Admin' . SERVER_NAME_HASH . SERVER_PATH_HASH);
// frontend
define('SESSION_NAME', BASE_NAME.SERVER_NAME_HASH.SERVER_PATH_HASH);
define('SESSION_NAME', BASE_NAME . SERVER_NAME_HASH . SERVER_PATH_HASH);
// SET_SESSION_NAME should be set in the header if a special session name is needed
define('SET_SESSION_NAME', SESSION_NAME);
/************* CACHE/COMPILE IDS *************/
define('CACHE_ID', 'CACHE_'.BASE_NAME.'_'.SERVER_NAME_HASH);
define('COMPILE_ID', 'COMPILE_'.BASE_NAME.'_'.SERVER_NAME_HASH);
define('CACHE_ID', 'CACHE_' . BASE_NAME . '_' . SERVER_NAME_HASH);
define('COMPILE_ID', 'COMPILE_' . BASE_NAME . '_' . SERVER_NAME_HASH);
/************* LANGUAGE / ENCODING *******/
define('DEFAULT_LANG', 'en_utf8');
@@ -183,22 +185,22 @@ define('GLOBAL_DB_SCHEMA', '');
define('LOGIN_DB_SCHEMA', '');
/************* CORE HOST SETTINGS *****************/
if (file_exists(BASE.CONFIGS.'config.host.php')) {
require BASE.CONFIGS.'config.host.php';
if (file_exists(BASE . CONFIGS . 'config.host.php')) {
require BASE . CONFIGS . 'config.host.php';
}
if (!isset($SITE_CONFIG)) {
$SITE_CONFIG = [];
}
/************* DB ACCESS *****************/
if (file_exists(BASE.CONFIGS.'config.db.php')) {
require BASE.CONFIGS.'config.db.php';
if (file_exists(BASE . CONFIGS . 'config.db.php')) {
require BASE . CONFIGS . 'config.db.php';
}
if (!isset($DB_CONFIG)) {
$DB_CONFIG = [];
}
/************* OTHER PATHS *****************/
if (file_exists(BASE.CONFIGS.'config.path.php')) {
require BASE.CONFIGS.'config.path.php';
if (file_exists(BASE . CONFIGS . 'config.path.php')) {
require BASE . CONFIGS . 'config.path.php';
}
/************* MASTER INIT *****************/
@@ -210,14 +212,15 @@ list($HOST_NAME) = array_pad(explode(':', $_SERVER['HTTP_HOST'], 2), 2, null);
define('HOST_NAME', $HOST_NAME);
// BAIL ON MISSING MASTER SITE CONFIG
if (!isset($SITE_CONFIG[HOST_NAME]['location'])) {
echo 'Missing SITE_CONFIG entry for: "'.HOST_NAME.'". Contact Administrator';
echo 'Missing SITE_CONFIG entry for: "' . HOST_NAME . '" . Contact Administrator';
exit;
}
// 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)) ||
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)) ||
@@ -226,12 +229,14 @@ if ((!isset($SITE_CONFIG[HOST_NAME]['db_host']) && count($DB_CONFIG)) ||
(is_array($DB_CONFIG) && count($DB_CONFIG) && !isset($DB_CONFIG[$SITE_CONFIG[HOST_NAME]['db_host']])))
)
) {
echo 'No matching DB config found for: "'.HOST_NAME.'". Contact Administrator';
echo 'No matching DB config found for: "' . HOST_NAME . '" . Contact Administrator';
exit;
}
// set SSL on
if ((array_key_exists('HTTPS', $_SERVER) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
$_SERVER['SERVER_PORT'] == 443) {
if (
(array_key_exists('HTTPS', $_SERVER) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
$_SERVER['SERVER_PORT'] == 443
) {
define('HOST_SSL', true);
define('HOST_PROTOCOL', 'https://');
} else {
@@ -244,8 +249,10 @@ define('DB_CONFIG', isset($DB_CONFIG[DB_CONFIG_NAME]) ? $DB_CONFIG[DB_CONFIG_NAM
// define('DB_CONFIG_TARGET', SITE_CONFIG[$HOST_NAME]['db_host_target']);
// define('DB_CONFIG_OTHER', SITE_CONFIG[$HOST_NAME]['db_host_other']);
// override for login and global schemas
// define('LOGIN_DB_SCHEMA', PUBLIC_SCHEMA); // where the edit* tables are
// define('GLOBAL_DB_SCHEMA', PUBLIC_SCHEMA); // where global tables are that are used by all schemas (eg queue tables for online, etc)
// where the edit* tables are
// define('LOGIN_DB_SCHEMA', PUBLIC_SCHEMA);
// where global tables are that are used by all schemas (eg queue tables for online, etc)
// define('GLOBAL_DB_SCHEMA', PUBLIC_SCHEMA);
// debug settings, site lang, etc
define('TARGET', $SITE_CONFIG[HOST_NAME]['location']);
define('DEBUG', $SITE_CONFIG[HOST_NAME]['debug_flag']);
@@ -260,7 +267,7 @@ define('LOGIN_ENABLED', $SITE_CONFIG[HOST_NAME]['login_enabled']);
define('SHOW_ALL_ERRORS', true);
/************* GENERAL PAGE TITLE ********/
define('G_TITLE', '<OVERALL FALLBACK PAGE TITLE>');
define('G_TITLE', $_ENV['G_TITLE'] ?? '');
/************ STYLE SHEETS / JS **********/
define('ADMIN_STYLESHEET', 'edit.css');
@@ -271,8 +278,8 @@ define('JAVASCRIPT', 'frontend.js');
// anything optional
/************* INTERNAL ******************/
// any other global definitons in the config.other.php
if (file_exists(BASE.CONFIGS.'config.other.php')) {
require BASE.CONFIGS.'config.other.php';
if (file_exists(BASE . CONFIGS . 'config.other.php')) {
require BASE . CONFIGS . 'config.other.php';
}
/************* DEBUG *******************/
@@ -294,7 +301,15 @@ if (defined('DEBUG') && DEBUG == false) {
}
/************* AUTO LOADER *******************/
// read auto loader
require BASE.LIB.'autoloader.php';
// read auto loader for lib only
// require BASE . LIB . 'autoloader.php';
// composer auto loader, IF composer.json file includes classmap for lib/:
// "autoload": {
// "classmap": [
// "lib/"
// ]
// },
// NOTE BASE: __DIR__ . DIRECTORY_SEPARATOR . '..' DIRECTORY_SEPARATOR;
require BASE . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
// __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore PSR1.Files.SideEffects
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2019/10/28
@@ -7,20 +8,22 @@
* HISTORY:
*********************************************************************/
// DEFINE('SOME_ID', <SOME VALUE>);
declare(strict_types=1);
// define('SOME_ID', <SOME VALUE>);
/************* CONVERT *******************/
// this only needed if the external thumbnail create is used
$paths = [
'/bin',
'/usr/bin',
'/usr/local/bin'
'/usr/local/bin',
];
// find convert
foreach ($paths as $path) {
if (file_exists($path.DS.'convert') && is_file($path.DS.'convert')) {
if (file_exists($path . DS . 'convert') && is_file($path . DS . 'convert')) {
// image magick convert location
define('CONVERT', $path.DS.'convert');
define('CONVERT', $path . DS . 'convert');
}
}
unset($paths);

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2018/10/11
@@ -8,6 +9,8 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
// File and Folder paths
// ID is TARGET (first array element)
/*$PATHS = [
@@ -15,7 +18,7 @@
'csv_path' => '',
'perl_bin' => '',
'other_url' => '',
]
],
];*/
// __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php // phpcs:ignore warning
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2018/10/11
@@ -7,13 +8,22 @@
* HISTORY:
*********************************************************************/
define('CONFIG_PATH', 'configs'.DIRECTORY_SEPARATOR);
declare(strict_types=1);
define('CONFIG_PATH', 'configs' . DIRECTORY_SEPARATOR);
// config path prefix search, start with 0, got down each level __DIR__ has, if nothing found -> bail
$CONFIG_PATH_PREFIX = '';
for ($dir_pos = 0, $dir_max = count(explode(DIRECTORY_SEPARATOR, __DIR__)); $dir_pos <= $dir_max; $dir_pos ++) {
$CONFIG_PATH_PREFIX .= '..'.DIRECTORY_SEPARATOR;
if (file_exists($CONFIG_PATH_PREFIX.CONFIG_PATH.'config.master.php')) {
require $CONFIG_PATH_PREFIX.CONFIG_PATH.'config.master.php';
for ($dir_pos = 0, $dir_max = count(explode(DIRECTORY_SEPARATOR, __DIR__)); $dir_pos <= $dir_max; $dir_pos++) {
$CONFIG_PATH_PREFIX .= '..' . DIRECTORY_SEPARATOR;
if (file_exists($CONFIG_PATH_PREFIX . CONFIG_PATH . 'config.master.php')) {
// check if there is an read env file, load it
if (file_exists($CONFIG_PATH_PREFIX . CONFIG_PATH . 'read_env_file.php')) {
require $CONFIG_PATH_PREFIX . CONFIG_PATH . 'read_env_file.php';
// load env variables first
readEnvFile($CONFIG_PATH_PREFIX . CONFIG_PATH);
}
// then load master config file that loads all other config files
require $CONFIG_PATH_PREFIX . CONFIG_PATH . 'config.master.php';
break;
}
}
@@ -23,8 +33,8 @@ if (!defined('DS')) {
}
// find trigger name "admin/" or "frontend/" in the getcwd() folder
foreach (['admin', 'frontend'] as $folder) {
if (strstr(getcwd(), DS.$folder)) {
define('CONTENT_PATH', $folder.DS);
if (strstr(getcwd() ?: '', DS . $folder)) {
define('CONTENT_PATH', $folder . DS);
break;
}
}

View File

@@ -0,0 +1,84 @@
<?php
/**
* parses .env file
*
* Rules for .env file
* variable is any alphanumeric string followed by = on the same line
* content starts with the first non space part
* strings can be contained in "
* strings MUST be contained in " if they are multiline
* if string starts with " it will match until another " is found
* anything AFTER " is ignored
* if there are two variables with the same name only the first is used
* variables are case sensitive
*
* @param string $path Folder to file, default is __DIR__
* @param string $env_file What file to load, default is .env
* @return int -1 other error
* 0 for success full load
* 1 for file loadable, but no data inside
* 2 for file not readable
* 3 for file not found
*/
function readEnvFile(string $path = __DIR__, string $env_file = '.env'): int
{
// default -1;
$status = -1;
$env_file_target = $path . DIRECTORY_SEPARATOR . $env_file;
// this is not a file -> abort
if (!is_file($env_file_target)) {
$status = 3;
return $status;
}
// cannot open file -> abort
if (($fp = fopen($env_file_target, 'r')) === false) {
$status = 2;
return $status;
}
// set to readable but not yet any data loaded
$status = 1;
$block = false;
$var = '';
while ($line = fgets($fp)) {
// main match for variable = value part
if (preg_match("/^\s*([\w_.]+)\s*=\s*((\"?).*)/", $line, $matches)) {
$var = $matches[1];
$value = $matches[2];
$quotes = $matches[3];
// wirte only if env is not set yet, and write only the first time
if (empty($_ENV[$var])) {
if (!empty($quotes)) {
// match greedy for first to last so we move any " if there are
if (preg_match('/^"(.*[^\\\])"/U', $value, $matches)) {
$value = $matches[1];
} else {
// this is a multi line
$block = true;
// first " in string remove
// add removed new line back because this is a multi line
$value = ltrim($value, '"') . PHP_EOL;
}
}
// if block is set, we strip line of slashes
$_ENV[$var] = $block === true ? stripslashes($value) : $value;
// set successful load
$status = 0;
}
} elseif ($block === true) {
// read line until there is a unescaped "
// this also strips everything after the last "
if (preg_match("/(.*[^\\\])\"/", $line, $matches)) {
$block = false;
// strip ending " and EVERYTHING that follows after that
$line = $matches[1];
}
// strip line of slashes
$_ENV[$var] .= stripslashes($line);
}
}
fclose($fp);
return $status;
}
// __END__

View File

@@ -1,3 +1,7 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
require 'config.php';
// __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2005/07/19
@@ -7,6 +8,8 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
$day_short = [
1 => 'Mon',
2 => 'Tue',

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2008/08/14
@@ -7,8 +8,11 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
// print debug messages
echo $login->log->printErrorMsg();
echo $cms->log->printErrorMsg();
$cms->log->debug('DEBUGEND', '==================================== [END]');
// __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2008/08/01
@@ -7,13 +8,13 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
//------------------------------ variable init start
// for dev test we set full error reporting; writes everything, except E_ERROR into logs/php_error-<day>.log
if ($DEBUG_ALL && $ENABLE_ERROR_HANDLING) {
include BASE.LIBS."Error.Handling.php";
if (!empty($DEBUG_ALL) && !empty($ENABLE_ERROR_HANDLING)) {
include BASE . LIBS . "Error.Handling.php";
}
// predefine vars
$messages = array();
//------------------------------ variable init end
//------------------------------ library include start
@@ -21,7 +22,7 @@ $messages = array();
ob_start();
// set the session name
$SET_SESSION_NAME = EDIT_SESSION_NAME;
$LOG_FILE_ID = BASE_NAME.'Admin';
$LOG_FILE_ID = BASE_NAME . 'Admin';
//------------------------------ library include end
//------------------------------ basic variable settings start
@@ -37,7 +38,7 @@ if (!isset($ENCODING) || !$ENCODING) {
}
// end the stop of the output flow, but only if we didn't request a csv file download
if (isset($_POST['action']) && $_POST['action'] != 'download_csv' && !$AJAX_PAGE) {
header("Content-type: text/html; charset=".$ENCODING);
header("Content-type: text/html; charset=" . $ENCODING);
}
if ($AJAX_PAGE && !$ZIP_STREAM) {
header("Content-Type: application/json; charset=UTF-8");
@@ -79,10 +80,10 @@ if (!$login->login) {
// automatic hide for DEBUG messages on live server
// can be overridden when setting DEBUG_ALL_OVERRIDE on top of the script (for emergency debugging of one page only)
if ((TARGET == 'live' || TARGET == 'remote') && !$DEBUG_ALL_OVERRIDE) {
if ((TARGET == 'live' || TARGET == 'remote') && !empty($DEBUG_ALL_OVERRIDE)) {
foreach (['debug', 'echo', 'print'] as $target) {
$login->log->setLogLevelAll($type, false);
$cms->log->setLogLevelAll($type, false);
$login->log->setLogLevelAll($target, false);
$cms->log->setLogLevelAll($target, false);
}
}
$smarty->DATA['JS_DEBUG'] = DEBUG;

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2007/09/03
@@ -7,6 +8,8 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
/******
NOTE THAT THIS INCLUDE IS OBSOLETE
USE THE BELOW FUNCTION CALL IN THE SCRIPT ITSELF

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2005/07/12
@@ -7,11 +8,16 @@
* HISTORY:
*********************************************************************/
declare(strict_types=1);
/******
NOTE THAT THIS INCLUDE IS OBSOLETE
USE THE BELOW FUNCTION CALL IN THE SCRIPT ITSELF
*******/
trigger_error('admin_smarty.php is deprecated. Use SmartyExtended->setSmartyVarsAdmin(); or setSmartyVarsFrontend();', E_USER_DEPRECATED);
trigger_error(
'admin_smarty.php is deprecated. Use SmartyExtended->setSmartyVarsAdmin(); or setSmartyVarsFrontend();',
E_USER_DEPRECATED
);
$smarty->setSmartyVarsAdmin();
// __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2003/06/10
@@ -12,14 +13,19 @@
* - edit_visible_group.php
* HISTORY:
* 2005/06/30 (cs) remove color settings, they are in CSS File now
* 2005/06/22 (cs) moved load of config array into form class, set lang and lang is must set var for form class; removed the page name setting, moved it into the form class, remove all HTML from main page
* 2005/06/22 (cs) moved load of config array into form class, set lang
* and lang is must set var for form class; removed the
* page name setting, moved it into the form class,
* emove all HTML from main page
* 2004/09/30 (cs) changed layout to fit default layout & changed LIBS, etc
* 2003-06-10: creation of this page
*********************************************************************/
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
$DB_DEBUG = 1;
declare(strict_types=1);
$DEBUG_ALL = true;
$PRINT_ALL = true;
$DB_DEBUG = true;
// TODO: only extract _POST data that is needed
extract($_POST, EXTR_SKIP);
@@ -30,14 +36,14 @@ require 'config.php';
$SET_SESSION_NAME = EDIT_SESSION_NAME;
// overrride debug flags
if (!DEBUG) {
$DEBUG_ALL = 0;
$PRINT_ALL = 0;
$DB_DEBUG = 0;
$ECHO_ALL = 0;
$DEBUG_ALL = false;
$PRINT_ALL = false;
$DB_DEBUG = false;
$ECHO_ALL = false;
}
// should be utf8
header("Content-type: text/html; charset=".DEFAULT_ENCODING);
header("Content-type: text/html; charset=" . DEFAULT_ENCODING);
ob_end_flush();
$login = new CoreLibs\ACL\Login(DB_CONFIG);
@@ -71,9 +77,9 @@ $DEBUG_DATA = [];
// set the template dir
// WARNING: this has a special check for the mailing tool layout (old layout)
if (defined('LAYOUT')) {
$smarty->setTemplateDir(BASE.INCLUDES.TEMPLATES.CONTENT_PATH);
$DATA['css'] = LAYOUT.CSS;
$DATA['js'] = LAYOUT.JS;
$smarty->setTemplateDir(BASE . INCLUDES . TEMPLATES . CONTENT_PATH);
$DATA['css'] = LAYOUT . CSS;
$DATA['js'] = LAYOUT . JS;
} else {
$smarty->setTemplateDir(TEMPLATES);
$DATA['css'] = CSS;
@@ -115,17 +121,22 @@ if ($form->my_page_name == 'edit_order') {
// this gets temp, id before that, gets actual (moves one "down")
// this gets the old before (moves one "up")
// is done for every element in row
// echo "A: ".$row_data_id[$position[$i]]." (".$row_data_order[$position[$i]].") -- ".$row_data_id[$position[$i]-1]." (".$row_data_order[$position[$i]-1].")<br>";
// echo "A: ".$row_data_id[$position[$i]]
// ." (".$row_data_order[$position[$i]].") -- ".$row_data_id[$position[$i]-1]
// ." (".$row_data_order[$position[$i]-1].")<br>";
$temp_id = $row_data_id[$position[$i]] ?? null;
$row_data_id[$position[$i]] = $row_data_id[$position[$i] - 1] ?? null;
$row_data_id[$position[$i] - 1] = $temp_id;
// echo "A: ".$row_data_id[$position[$i]]." (".$row_data_order[$position[$i]].") -- ".$row_data_id[$position[$i]-1]." (".$row_data_order[$position[$i]-1].")<br>";
// echo "A: ".$row_data_id[$position[$i]]
// ." (".$row_data_order[$position[$i]].") -- "
// .$row_data_id[$position[$i]-1]." (".$row_data_order[$position[$i]-1].")<br>";
} // for
} // if up
// the last position id from position array is not to be the count-1 of row_data_id array, or it is the last element
// the last position id from position array is not to be the count - 1 of
// row_data_id array, or it is the last element
if (isset($down) && ($position[count($position) - 1] != (count($row_data_id) - 1))) {
for ($i = count($position) - 1; $i >= 0; $i --) {
for ($i = count($position) - 1; $i >= 0; $i--) {
// same as up, just up in other way, starts from bottom (last element) and moves "up"
// element before actuel gets temp, this element, becomes element after this,
// element after this, gets this
@@ -136,12 +147,15 @@ if ($form->my_page_name == 'edit_order') {
} // if down
// write data ... (which has to be abstrackt ...)
if ((isset($up) && $position[0] > 0) ||
if (
(isset($up) && $position[0] > 0) ||
(isset($down) && ($position[count($position) - 1] != (count($row_data_id) - 1)))
) {
for ($i = 0; $i < count($row_data_id); $i ++) {
for ($i = 0; $i < count($row_data_id); $i++) {
if (isset($row_data_order[$i]) && isset($row_data_id[$i])) {
$q = "UPDATE ".$table_name." SET order_number = ".$row_data_order[$i]." WHERE ".$table_name."_id = ".$row_data_id[$i];
$q = "UPDATE " . $table_name
. " SET order_number = " . $row_data_order[$i]
. " WHERE " . $table_name . "_id = " . $row_data_id[$i];
$q = $form->dbExec($q);
}
} // for all article ids ...
@@ -149,7 +163,7 @@ if ($form->my_page_name == 'edit_order') {
} // if there is something to move
// get ...
$q = "SELECT ".$table_name."_id, name, order_number FROM ".$table_name." ";
$q = "SELECT " . $table_name . "_id, name, order_number FROM " . $table_name . " ";
if (!empty($where_string)) {
$q .= "WHERE $where_string ";
}
@@ -161,9 +175,9 @@ if ($form->my_page_name == 'edit_order') {
$options_name = [];
$options_selected = [];
// DB read data for menu
while ($res = $form->dbReturn($q)) {
while (is_array($res = $form->dbReturn($q))) {
$row_data[] = [
"id" => $res[$table_name."_id"],
"id" => $res[$table_name . "_id"],
"name" => $res["name"],
"order" => $res["order_number"]
];
@@ -187,13 +201,14 @@ if ($form->my_page_name == 'edit_order') {
$DATA['form_error_msg'] = $messages;
// all the row data
for ($i = 0; $i < count($row_data); $i ++) {
for ($i = 0; $i < count($row_data); $i++) {
$options_id[] = $i;
$options_name[] = $row_data[$i]['name'];
// list of points to order
for ($j = 0; $j < count($position); $j++) {
// if matches, put into select array
if (isset($original_id[$position[$j]]) && isset($row_data[$i]['id']) &&
if (
isset($original_id[$position[$j]]) && isset($row_data[$i]['id']) &&
$original_id[$position[$j]] == $row_data[$i]['id']
) {
$options_selected[] = $i;
@@ -288,11 +303,11 @@ if ($form->my_page_name == 'edit_order') {
(isset($data['hostname']) && $data['hostname'] ?
$data['hostname'] :
''
).
)
// filename
($data['filename'] ?? '').
. ($data['filename'] ?? '')
// query string
(isset($data['query_string']) && $data['query_string'] ?
. (isset($data['query_string']) && $data['query_string'] ?
$data['query_string'] :
''
);
@@ -302,7 +317,8 @@ if ($form->my_page_name == 'edit_order') {
$menu_data[$i]['splitfactor_in'] = 0;
}
// on matching, we also need to check if we are in the same folder
if (isset($data['filename']) &&
if (
isset($data['filename']) &&
$data['filename'] == \CoreLibs\Get\System::getPageName() &&
(!isset($data['hostname']) || (
isset($data['hostname']) &&
@@ -334,7 +350,7 @@ if ($form->my_page_name == 'edit_order') {
} // for
// $form->log->debug('MENU ARRAY', $form->log->prAr($menu_data));
$DATA['menu_data'] = $menu_data;
$DATA['page_name'] = $menuarray[$position]['page_name'] ?? '-Undefined ['.$position.'] -';
$DATA['page_name'] = $menuarray[$position]['page_name'] ?? '-Undefined [' . $position . '] -';
$L_TITLE = $DATA['page_name'];
// html title
$HEADER['HTML_TITLE'] = $form->l->__($L_TITLE);
@@ -391,13 +407,13 @@ if ($form->my_page_name == 'edit_order') {
$search_glob = [];
foreach ($folders as $folder) {
// make sure this folder actually exists
if (is_dir(ROOT.$folder)) {
if (is_dir(ROOT . $folder)) {
foreach ($files as $file) {
$search_glob[] = $folder.$file;
$search_glob[] = $folder . $file;
}
}
}
$crap = exec('ls '.join(' ', $search_glob), $output, $status);
$crap = exec('ls ' . join(' ', $search_glob), $output, $status);
// now get all that are NOT in de DB
$q = "INSERT INTO temp_files (folder, filename) VALUES ";
$t_q = '';
@@ -410,10 +426,11 @@ if ($form->my_page_name == 'edit_order') {
if ($t_q) {
$t_q .= ', ';
}
$t_q .= "('".$form->dbEscapeString($matches[1])."', '".$form->dbEscapeString($matches[2])."')";
$t_q .= "('" . $form->dbEscapeString($matches[1]) . "', '"
. $form->dbEscapeString($matches[2]) . "')";
}
}
$form->dbExec($q.$t_q, 'NULL');
$form->dbExec($q . $t_q, 'NULL');
$elements[] = $form->formCreateElement('filename');
} else {
// show file menu
@@ -493,13 +510,13 @@ $CONTENT_DATA = array_merge($HEADER, $DATA, $DEBUG_DATA);
foreach ($CONTENT_DATA as $key => $value) {
$smarty->assign($key, $value);
}
if (is_dir(BASE.TEMPLATES_C)) {
$smarty->setCompileDir(BASE.TEMPLATES_C);
if (is_dir(BASE . TEMPLATES_C)) {
$smarty->setCompileDir(BASE . TEMPLATES_C);
}
if (is_dir(BASE.CACHE)) {
$smarty->setCacheDir(BASE.CACHE);
if (is_dir(BASE . CACHE)) {
$smarty->setCacheDir(BASE . CACHE);
}
$smarty->display($EDIT_TEMPLATE, 'editAdmin_'.$smarty->lang, 'editAdmin_'.$smarty->lang);
$smarty->display($EDIT_TEMPLATE, 'editAdmin_' . $smarty->lang, 'editAdmin_' . $smarty->lang);
// debug output
echo $login->log->printErrorMsg();

Binary file not shown.

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$edit_access = [
'table_array' => [

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$edit_groups = [
'table_array' => [

View File

@@ -1,6 +1,8 @@
<?php declare(strict_types=1);
<?php
$edit_languages=[
declare(strict_types=1);
$edit_languages = [
'table_array' => [
'edit_language_id' => [
'value' => $GLOBALS['edit_language_id'] ?? '',

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$edit_menu_group = [
'table_array' => [

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$edit_pages = [
'table_array' => [
@@ -13,9 +15,9 @@ $edit_pages = [
'mandatory' => 1,
'type' => 'drop_down_db',
'query' => "SELECT DISTINCT temp_files.filename AS id, temp_files.folder || temp_files.filename AS name "
."FROM temp_files "
."LEFT JOIN edit_page ep ON temp_files.filename = ep.filename "
."WHERE ep.filename IS NULL"
. "FROM temp_files "
. "LEFT JOIN edit_page ep ON temp_files.filename = ep.filename "
. "WHERE ep.filename IS NULL"
],
'hostname' => [
'value' => $GLOBALS['hostname'] ?? '',
@@ -112,7 +114,11 @@ $edit_pages = [
// "ORDER BY order_number"
],
],
'load_query' => "SELECT edit_page_id, CASE WHEN hostname IS NOT NULL THEN hostname ELSE ''::VARCHAR END || filename AS filename, name, online, menu, popup FROM edit_page ORDER BY order_number",
'load_query' => "SELECT edit_page_id, "
. "CASE WHEN hostname IS NOT NULL THEN hostname ELSE ''::VARCHAR END || filename AS filename, "
. "name, online, menu, popup "
. "FROM edit_page "
. "ORDER BY order_number",
'table_name' => 'edit_page',
'show_fields' => [
[
@@ -124,17 +130,17 @@ $edit_pages = [
],
[
'name' => 'online',
'binary' => ['Yes','No'],
'binary' => ['Yes', 'No'],
'before_value' => 'Online: '
],
[
'name' => 'menu',
'binary' => ['Yes','No'],
'binary' => ['Yes', 'No'],
'before_value' => 'Menu: '
],
[
'name' => 'popup',
'binary' => ['Yes','No'],
'binary' => ['Yes', 'No'],
'before_value' => 'Popup: '
],
],
@@ -146,7 +152,8 @@ $edit_pages = [
'mandatory' => 1,
'select_size' => 10,
'selected' => $GLOBALS['edit_visible_group_id'] ?? '',
'query' => "SELECT edit_visible_group_id, 'Name: ' || name || ', ' || 'Flag: ' || flag FROM edit_visible_group ORDER BY name"
'query' => "SELECT edit_visible_group_id, 'Name: ' || name || ', ' || 'Flag: ' || flag "
. "FROM edit_visible_group ORDER BY name"
],
'edit_menu_group' => [
'table_name' => 'edit_page_menu_group',
@@ -155,7 +162,8 @@ $edit_pages = [
'mandatory' => 1,
'select_size' => 10,
'selected' => $GLOBALS['edit_menu_group_id'] ?? '',
'query' => "SELECT edit_menu_group_id, 'Name: ' || name || ', ' || 'Flag: ' || flag FROM edit_menu_group ORDER BY order_number"
'query' => "SELECT edit_menu_group_id, 'Name: ' || name || ', ' || 'Flag: ' || flag "
. "FROM edit_menu_group ORDER BY order_number"
],
],

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$edit_schemes = [
'table_array' => [

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$edit_users = [
'table_array' => [
@@ -34,7 +36,8 @@ $edit_users = [
'password_change_interval' => [
'value' => $GLOBALS['password_change_interval'] ?? '',
'output_name' => 'Password change interval',
'error_check' => 'intervalshort', // can be any date length format. n Y/M/D [not H/M/S], only one set, no combination
// can be any date length format. n Y/M/D [not H/M/S], only one set, no combination
'error_check' => 'intervalshort',
'type' => 'text',
'interval' => 1, // interval needs NULL write for empty
'size' => 5, // make it 5 chars long
@@ -184,7 +187,8 @@ $edit_users = [
'cols' => 60
],
],
'load_query' => "SELECT edit_user_id, username, enabled, debug, db_debug, strict, locked, login_error_count FROM edit_user ORDER BY username",
'load_query' => "SELECT edit_user_id, username, enabled, debug, db_debug, strict, locked, login_error_count "
. "FROM edit_user ORDER BY username",
'table_name' => 'edit_user',
'show_fields' => [
[

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$edit_visible_group = [
'table_array' => [

View File

@@ -100,10 +100,10 @@
</script>
<!-- /TinyMCE -->
{/if}
{popup_init src="`$js`/overlib/overlib.js"}
</head>
<body>
<div style="margin: 2px; width: {$table_width}px; margin-bottom: 10px;">
{popup_init src="`$js`/overlib/overlib.js"}
<div style="margin: 2px; width: {$table_width}; margin-bottom: 10px;">
<div style="position: relative; height: 20px;" class="menu">
<div style="position: absolute; width: 200px;">{t 1=$USER_NAME|upper}Hello %1{/t}</div>
<div style="position: absolute; text-align: right; right: 0px; width: 120px;">
@@ -127,13 +127,13 @@
{/if}
{/foreach}
</div>
<div class="pagename">
<div id="pagename" class="pagename">
{$page_name}
</div>
</div>
{* error/warning *}
{if $messages}
<div style="margin: 2px; width: {$table_width}px;">
<div style="margin: 2px; width: {$table_width};">
{foreach from=$messages item=item key=key}
<div class="{$item.class}">{$item.msg}</div>
{/foreach}
@@ -143,7 +143,7 @@
{* debug info *}
{if $DEBUG}
<div style="width:{$table_width}px;" class="debug_message">
<div style="width:{$table_width};" class="debug_message">
{$Id}<br>
<b>{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}</b><br>
{$debug_error_msg}

View File

@@ -2,7 +2,10 @@
{$SMARTY_TEST}
</div>
<div>
TRANSLATION CLASS: {$TRANSLATE_TEST}
TRANSLATION CLASS (OUT): {$TRANSLATE_TEST}
</div>
<div>
TRANSLATION CLASS (SMARTY): {$TRANSLATE_TEST_SMARTY}
</div>
<div>
<select id="drop_down_test" name="drop_down_test">

View File

View File

@@ -3,6 +3,8 @@
/* jshint esversion: 6 */
/* global i18n */
// debug set
/*var FRONTEND_DEBUG = false;
var DEBUG = true;
@@ -22,7 +24,8 @@ var GL_OB_BASE = 30;
* @param {String} winName window name
* @param {Object} features popup features
*/
function pop(theURL, winName, features) {
function pop(theURL, winName, features) // eslint-disable-line no-unused-vars
{
winName = window.open(theURL, winName, features);
winName.focus();
}
@@ -31,7 +34,8 @@ function pop(theURL, winName, features) {
* automatically resize a text area based on the amount of lines in it
* @param {[string} ta_id element id
*/
function expandTA(ta_id) {
function expandTA(ta_id) // eslint-disable-line no-unused-vars
{
var ta;
// if a string comes, its a get by id, else use it as an element pass on
if (!ta_id.length) {
@@ -40,7 +44,7 @@ function expandTA(ta_id) {
ta = document.getElementById(ta_id);
}
var maxChars = ta.cols;
var theRows = ta.value.split("\n");
var theRows = ta.value.split('\n');
var numNewRows = 0;
for ( var i = 0; i < theRows.length; i++ ) {
@@ -124,7 +128,7 @@ function setCenter(id, left, top)
* @param {Number} [duration=500] animation time, default 500ms
* @param {String} [base='body,html'] base element for offset scroll
*/
function goToPos(element, offset = 0, duration = 500, base = 'body,html')
function goToPos(element, offset = 0, duration = 500, base = 'body,html') // eslint-disable-line no-unused-vars
{
try {
if ($('#' + element).length) {
@@ -190,7 +194,7 @@ if (Number.prototype.round) {
* @param {Number} x number to be formated
* @return {String} formatted with , in thousands
*/
function numberWithCommas(x)
function numberWithCommas(x) // eslint-disable-line no-unused-vars
{
var parts = x.toString().split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
@@ -202,7 +206,7 @@ function numberWithCommas(x)
* @param {String} string any string
* @return {String} string with <br>
*/
function convertLBtoBR(string)
function convertLBtoBR(string) // eslint-disable-line no-unused-vars
{
return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
}
@@ -214,14 +218,14 @@ function convertLBtoBR(string)
*/
if (!String.prototype.escapeHTML) {
String.prototype.escapeHTML = function() {
return this.replace(/[&<>"'\/]/g, function (s) {
return this.replace(/[&<>"'/]/g, function (s) {
var entityMap = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
"/": '&#x2F;'
'\'': '&#39;',
'/': '&#x2F;'
};
return entityMap[s];
@@ -238,12 +242,12 @@ if (!String.prototype.unescapeHTML) {
String.prototype.unescapeHTML = function() {
return this.replace(/&[#\w]+;/g, function (s) {
var entityMap = {
"&amp;": "&",
"&lt;": "<",
"&gt;": ">",
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
'&#x2F;': "/"
'&#39;': '\'',
'&#x2F;': '/'
};
return entityMap[s];
@@ -255,7 +259,7 @@ if (!String.prototype.unescapeHTML) {
* returns current timestamp (unix timestamp)
* @return {Number} timestamp (in milliseconds)
*/
function getTimestamp()
function getTimestamp() // eslint-disable-line no-unused-vars
{
var date = new Date();
return date.getTime();
@@ -278,7 +282,7 @@ function dec2hex(dec)
* @param {Number} len length of unique id string
* @return {String} random string in length of len
*/
function generateId(len)
function generateId(len) // eslint-disable-line no-unused-vars
{
var arr = new Uint8Array((len || 40) / 2);
(window.crypto || window.msCrypto).getRandomValues(arr);
@@ -291,7 +295,7 @@ function generateId(len)
* after many runs it will create duplicates
* @return {String} not true random string
*/
function randomIdF()
function randomIdF() // eslint-disable-line no-unused-vars
{
return Math.random().toString(36).substring(2);
}
@@ -301,7 +305,7 @@ function randomIdF()
* @param {string} name Name of function to check if exists
* @return {Boolean} true/false
*/
function isFunction(name)
function isFunction(name) // eslint-disable-line no-unused-vars
{
if (typeof window[name] !== 'undefined' &&
typeof window[name] === 'function') {
@@ -320,7 +324,7 @@ function isFunction(name)
* hidden next are all the arguments
* @return {mixed} Return values from functon
*/
function executeFunctionByName(functionName, context /*, args */)
function executeFunctionByName(functionName, context /*, args */) // eslint-disable-line no-unused-vars
{
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split('.');
@@ -362,7 +366,7 @@ function getObjectCount(object)
*/
function keyInObject(key, object)
{
return (Object.prototype.hasOwnProperty.call(object, key)) ? true : false;
return Object.prototype.hasOwnProperty.call(object, key) ? true : false;
}
/**
@@ -371,7 +375,7 @@ function keyInObject(key, object)
* @param {Mixed} value any value (String, Number, etc)
* @return {String} the key found for the first matching value
*/
function getKeyByValue(object, value)
function getKeyByValue(object, value) // eslint-disable-line no-unused-vars
{
return Object.keys(object).find(key => object[key] === value);
// return Object.keys(object).find(function (key) {
@@ -385,9 +389,9 @@ function getKeyByValue(object, value)
* @param {Mixed} value any value (String, Number, etc)
* @return {Boolean} true on value found, false on not found
*/
function valueInObject(object, value)
function valueInObject(object, value) // eslint-disable-line no-unused-vars
{
return (Object.keys(object).find(key => object[key] === value)) ? true : false;
return Object.keys(object).find(key => object[key] === value) ? true : false;
// return Object.keys(object).find(function (key) {
// return object[key] === value;
// }) ? true : false;
@@ -403,7 +407,7 @@ function valueInObject(object, value)
function deepCopyFunction(inObject)
{
var outObject, value, key;
if (typeof inObject !== "object" || inObject === null) {
if (typeof inObject !== 'object' || inObject === null) {
return inObject; // Return the value if inObject is not an object
}
// Create an array or object to hold the values
@@ -434,14 +438,15 @@ function exists(id)
* @param {Number} bytes bytes in int
* @return {String} string in GB/MB/KB
*/
function formatBytes(bytes)
function formatBytes(bytes) // eslint-disable-line no-unused-vars
{
var i = -1;
do {
bytes = bytes / 1024;
i++;
} while (bytes > 99);
return parseFloat(Math.round(bytes * Math.pow(10, 2)) / Math.pow(10, 2)) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
return parseFloat(Math.round(bytes * Math.pow(10, 2)) / Math.pow(10, 2)) +
['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
}
/**
@@ -449,7 +454,7 @@ function formatBytes(bytes)
* @param {Number} bytes bytes in int
* @return {String} string in GB/MB/KB
*/
function formatBytesLong(bytes)
function formatBytesLong(bytes) // eslint-disable-line no-unused-vars
{
var i = Math.floor(Math.log(bytes) / Math.log(1024));
var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
@@ -461,7 +466,7 @@ function formatBytesLong(bytes)
* @param {String|Number} bytes Any string with B/K/M/etc
* @return {String|Number} A byte number, or original string as is
*/
function stringByteFormat(bytes)
function stringByteFormat(bytes) // eslint-disable-line no-unused-vars
{
// if anything not string return
if (!(typeof bytes === 'string' || bytes instanceof String)) {
@@ -536,7 +541,7 @@ function errorCatch(err)
* default empty. for console.log
* @param {Boolean} [overlay=true] override the auto hide/show over the overlay div block
*/
function actionIndicator(loc, overlay = true)
function actionIndicator(loc, overlay = true) // eslint-disable-line no-unused-vars
{
if ($('#indicator').is(':visible')) {
actionIndicatorHide(loc, overlay);
@@ -613,7 +618,7 @@ function overlayBoxHide()
/**
* position the overlay block box and shows it
*/
function setOverlayBox()
function setOverlayBox() // eslint-disable-line no-unused-vars
{
if (!$('#overlayBox').is(':visible')) {
$('#overlayBox').show();
@@ -623,7 +628,7 @@ function setOverlayBox()
/**
* opposite of set, always hides overlay box
*/
function hideOverlayBox()
function hideOverlayBox() // eslint-disable-line no-unused-vars
{
if ($('#overlayBox').is(':visible')) {
$('#overlayBox').hide();
@@ -633,7 +638,7 @@ function hideOverlayBox()
/**
* the abort call, clears the action box and hides it and the overlay box
*/
function ClearCall()
function ClearCall() // eslint-disable-line no-unused-vars
{
$('#actionBox').html('');
$('#actionBox').hide();
@@ -654,7 +659,7 @@ function ClearCall()
* - indicator is page centered
* @param {String} loc ID string, only used for console log
*/
function showActionIndicator(loc)
function showActionIndicator(loc) // eslint-disable-line no-unused-vars
{
// console.log('Indicator: SHOW [%s]', loc);
// check if indicator element exists
@@ -692,7 +697,7 @@ function showActionIndicator(loc)
* is set to this value
* @param {String} loc ID string, only used for console log
*/
function hideActionIndicator(loc)
function hideActionIndicator(loc) // eslint-disable-line no-unused-vars
{
// console.log('Indicator: HIDE [%s]', loc);
// check if indicator is visible
@@ -732,7 +737,7 @@ function checkOverlayExists()
* if visible, add +1 to the GL_OB_S variable and
* up zIndex by this value
*/
function showOverlayBoxLayers(el_id)
function showOverlayBoxLayers(el_id) // eslint-disable-line no-unused-vars
{
// console.log('SHOW overlaybox: %s', GL_OB_S);
// if overlay box is not visible show and set zIndex to 0
@@ -789,7 +794,7 @@ function hideOverlayBoxLayers(el_id)
/**
* only for single action box
*/
function clearCallActionBox()
function clearCallActionBox() // eslint-disable-line no-unused-vars
{
$('#actionBox').html('');
$('#actionBox').hide();
@@ -872,7 +877,7 @@ function aelx(base, ...attach)
* @param {Array} attach array of objects to attach
* @return {Object} "none", technically there is no return needed, global attach
*/
function aelxar(base, attach)
function aelxar(base, attach) // eslint-disable-line no-unused-vars
{
for (var i = 0; i < attach.length; i ++) {
// base.sub.push(Object.assign({}, attach[i]));
@@ -886,7 +891,7 @@ function aelxar(base, attach)
* @param {Object} base cel created element
* @return {Object} returns reset base element
*/
function rel(base)
function rel(base) // eslint-disable-line no-unused-vars
{
base.sub = [];
return base;
@@ -930,7 +935,7 @@ function acssel(_element, css)
* @param {String} acss style to add (name)
* @return {Object} returns full element
*/
function scssel(_element, rcss, acss)
function scssel(_element, rcss, acss) // eslint-disable-line no-unused-vars
{
rcssel(_element, rcss);
acssel(_element, acss);
@@ -1008,7 +1013,7 @@ function phfo(tree)
* @param {Array} list Array of cel created objects
* @return {String} HTML String
*/
function phfa(list)
function phfa(list) // eslint-disable-line no-unused-vars
{
var content = [];
for (var i = 0; i < list.length; i ++) {
@@ -1034,7 +1039,7 @@ function phfa(list)
* 'values' all others are ignored
* @return {String} html with build options block
*/
function html_options(name, data, selected = '', options_only = false, return_string = false, sort = '')
function html_options(name, data, selected = '', options_only = false, return_string = false, sort = '') // eslint-disable-line no-unused-vars
{
// wrapper to new call
return html_options_block(name, data, selected, false, options_only, return_string, sort);
@@ -1067,6 +1072,7 @@ function html_options_block(name, data, selected = '', multiple = 0, options_onl
var element_option;
var data_list = []; // for sorted output
var value;
var options = {};
// var option;
if (multiple > 0) {
select_options.multiple = '';
@@ -1139,7 +1145,7 @@ function html_options_block(name, data, selected = '', multiple = 0, options_onl
* @param {String} [sort=''] if empty as is, else allowed 'keys', 'values'
* all others are ignored
*/
function html_options_refill(name, data, sort = '')
function html_options_refill(name, data, sort = '') // eslint-disable-line no-unused-vars
{
var element_option;
var option_selected;
@@ -1186,21 +1192,26 @@ function html_options_refill(name, data, sort = '')
* or empty for none
* @return {Object|String} parameter entry list
*/
function parseQueryString(query = '', return_key = '') {
function parseQueryString(query = '', return_key = '') // eslint-disable-line no-unused-vars
{
if (!query) {
query = window.location.search.substring(1);
}
var vars = query.split("&");
var vars = query.split('&');
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var pair = vars[i].split('=');
var key = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
// skip over run if there is nothing
if (!key || value === 'undefined') {
continue;
}
// If first entry with this name
if (typeof query_string[key] === "undefined") {
if (typeof query_string[key] === 'undefined') {
query_string[key] = decodeURIComponent(value);
// If second entry with this name
} else if (typeof query_string[key] === "string") {
} else if (typeof query_string[key] === 'string') {
var arr = [query_string[key], decodeURIComponent(value)];
query_string[key] = arr;
// If third or later entry with this name
@@ -1220,26 +1231,59 @@ function parseQueryString(query = '', return_key = '') {
}
/**
* searchs the current url for a parameter
* @param {String} key uid key to get data for
* @return {String} value for the key or '' for not found
* searches query parameters for entry and returns data either as string or array
* if no search is given the whole parameters are returned as an object
* if a parameter is set several times it will be returned as an array
* if search parameter set and nothing found and empty string is returned
* if no parametes exist and no serach is set and empty object is returned
* @param {String} [search=''] if set searches for this entry, if empty
* all parameters are returned
* @param {String} [query=''] different query string to parse, if not
* set (default) the current window href is used
* @param {Bool} [single=false] if set to true then only the first found
* will be returned
* @return {Object|Array|String} if search is empty, object, if search is set
* and only one entry, then string, else array
* unless single is true
*/
function getQueryStringParam(key)
function getQueryStringParam(search = '', query = '', single = false) // eslint-disable-line no-unused-vars
{
var url = new URL(window.location.href);
var param = url.searchParams.get(key);
if (param) {
return param;
} else {
return '';
if (!query) {
query = window.location.href;
}
const url = new URL(query);
let param = '';
if (search) {
let _params = url.searchParams.getAll(search);
if (_params.length == 1 || single === true) {
param = _params[0];
} else if (_params.length > 1) {
param = _params;
}
} else {
// will be object, so declare it one
param = {};
// loop over paramenters
for (const [key] of url.searchParams.entries()) {
// check if not yet set
if (typeof param[key] === 'undefined') {
// get the parameters multiple
let _params = url.searchParams.getAll(key);
// if 1 set as string, else attach array as is
param[key] = _params.length < 2 || single === true ?
_params[0] :
_params;
}
}
}
return param;
}
// *** MASTER logout call
/**
* submits basic data for form logout
*/
function loginLogout()
function loginLogout() // eslint-disable-line no-unused-vars
{
const form = document.createElement('form');
form.method = 'post';
@@ -1259,7 +1303,7 @@ function loginLogout()
* if not set mainHeader is assumed
* this is the target div for the "loginRow"
*/
function createLoginRow(login_string, header_id = 'mainHeader')
function createLoginRow(login_string, header_id = 'mainHeader') // eslint-disable-line no-unused-vars
{
// if header does not exist, we do nothing
if (exists(header_id)) {
@@ -1293,7 +1337,8 @@ function createLoginRow(login_string, header_id = 'mainHeader')
* if not set mainHeader is assumed
* this is the target div for the "menuRow"
*/
function createNavMenu(nav_menu, header_id = 'mainHeader') {
function createNavMenu(nav_menu, header_id = 'mainHeader') // eslint-disable-line no-unused-vars
{
// must be an object
if (isObject(nav_menu) && getObjectCount(nav_menu) > 1) {
// do we have more than one entry, if not, do not show (single page)

View File

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

View File

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

View File

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

View File

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

0
www/layout/admin/javascript/jquery.test.js Executable file → Normal file
View File

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/*********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2000/06/01
@@ -32,16 +33,22 @@
*
* HISTORY:
* 2010/12/21 (cs) merge back password change interface
* 2010/12/17 (cs) change that password can be blowfish encrypted, auto detects if other encryption is used (md5, std des) and tries to use them
* 2010/12/17 (cs) change that password can be blowfish encrypted,
* auto detects if other encryption is used (md5, std des)
* and tries to use them
* 2007/05/29 (cs) BUG with assign query and visible sub arrays to pages
* 2005/09/21 (cs) if error -> unset the session vars
* 2005/07/04 (cs) add a function to write into the edit log file
* 2005/07/01 (cs) start adepting login class to new edit interface layout
* 2005/03/31 (cs) fixed the class call with all debug vars
* 2004/11/17 (cs) unused var cleanup
* 2004/11/16 (cs) rewrite login so it uses a template and not just plain html. prepare it, so it will be able to use external stuff later (some interface has to be designed for that
* 2004/11/16 (cs) removed the mobile html part from login * 2004/09/30 (cs) layout fix
* 2003-11-11: if user has debug 1 unset memlimit, because there can be serious problems with the query logging
* 2004/11/16 (cs) rewrite login so it uses a template and not just plain html.
* prepare it, so it will be able to use external stuff later
* (some interface has to be designed for that
* 2004/11/16 (cs) removed the mobile html part from login
* 2004/09/30 (cs) layout fix
* 2003-11-11: if user has debug 1 unset memlimit, because there can be serious
* problems with the query logging
* 2003-06-12: added flag to PAGES array
* changed the get vars from GLOBALS to _POST
* changed the session registration. no more GLOBAL vars are registered
@@ -57,47 +64,78 @@
* 2000-06-01: created basic idea and functions
*********************************************************************/
declare(strict_types=1);
namespace CoreLibs\ACL;
use CoreLibs\Check\Password;
class Login extends \CoreLibs\DB\IO
{
/** @var string */
private $euid; // the user id var
private $permission_okay = false; // is set to one if login okay, or EUID is set and user is okay to access this page
// is set to one if login okay, or EUID is set and user is okay to access this page
/** @var bool */
private $permission_okay = false;
/** @var string */
public $login; // pressed login
/** @var string */
private $action; // master action command
/** @var string */
private $username; // login name
/** @var string */
private $password; // login password
/** @var string */
private $logout; // logout button
private $login_error = 0; // login error code, can be matched to the array login_error_msg, which holds the string
// login error code, can be matched to the array login_error_msg, which holds the string
/** @var int */
private $login_error = 0;
/** @var bool */
private $password_change = false; // if this is set to true, the user can change passwords
/** @var bool */
private $password_change_ok = false; // password change was successful
private $password_forgot = false; // can we reset password and mail to user with new password set screen
private $password_forgot_ok = false; // password forgot mail send ok
// can we reset password and mail to user with new password set screen
/** @var bool */
private $password_forgot = false;
/** @var bool */
// private $password_forgot_ok = false; // password forgot mail send ok
/** @var string */
private $change_password;
/** @var string */
private $pw_username;
/** @var string */
private $pw_old_password;
/** @var string */
private $pw_new_password;
/** @var string */
private $pw_new_password_confirm;
/** @var array<string> */
private $pw_change_deny_users = []; // array of users for which the password change is forbidden
/** @var string */
private $logout_target;
/** @var int */
private $max_login_error_count = -1;
/** @var array<string> */
private $lock_deny_users = [];
// if we have password change we need to define some rules
/** @var int */
private $password_min_length = PASSWORD_MIN_LENGTH;
// max length is fixed as 255 (for input type max), if set highter, it will be set back to 255
/** @var int */
private $password_max_length = PASSWORD_MAX_LENGTH;
// can have several regexes, if nothing set, all is ok
/** @var array<string> */
private $password_valid_chars = [
// '^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,}$',
// '^(?.*(\pL)u)(?=.*(\pN)u)(?=.*([^\pL\pN])u).{8,}',
];
// all possible login error conditions
/** @var array<mixed> */
private $login_error_msg = [];
// this is an array holding all strings & templates passed from the outside (translation)
/** @var array<mixed> */
private $login_template = [
'strings' => [],
'password_change' => '',
@@ -105,18 +143,23 @@ class Login extends \CoreLibs\DB\IO
];
// acl vars
/** @var array<mixed> */
public $acl = [];
/** @var array<mixed> */
public $default_acl_list = [];
// login html, if we are on an ajax page
/** @var string|null */
private $login_html = '';
/** @var bool */
private $login_is_ajax_page = false;
// language
/** @var \CoreLibs\Language\L10n */
public $l;
/**
* constructor, does ALL, opens db, works through connection checks, closes itself
* @param array $db_config db config array
* @param array<mixed> $db_config db config array
*/
public function __construct(array $db_config)
{
@@ -148,12 +191,13 @@ class Login extends \CoreLibs\DB\IO
exit;
}
// set global is ajax page for if we show the data directly, or need to pass it back
// set global is ajax page for if we show the data directly,
// or need to pass it back
// to the continue AJAX class for output back to the user
$this->login_is_ajax_page = isset($GLOBALS['AJAX_PAGE']) && $GLOBALS['AJAX_PAGE'] ? true : false;
// set the default lang
$lang = 'en_utf8';
if (session_id() && isset($_SESSION['DEFAULT_LANG']) && $_SESSION['DEFAULT_LANG']) {
if (session_id() !== false && !empty($_SESSION['DEFAULT_LANG'])) {
$lang = $_SESSION['DEFAULT_LANG'];
} else {
$lang = defined('SITE_LANG') ? SITE_LANG : DEFAULT_LANG;
@@ -161,8 +205,11 @@ class Login extends \CoreLibs\DB\IO
$this->l = new \CoreLibs\Language\L10n($lang);
// if we have a search path we need to set it, to use the correct DB to login
// check what schema to use. if there is a login schema use this, else check if there is a schema set in the config, or fall back to DB_SCHEMA if this exists, if this also does not exists use public schema
if (defined('LOGIN_DB_SCHEMA') && LOGIN_DB_SCHEMA) {
// check what schema to use. if there is a login schema use this, else check
// if there is a schema set in the config, or fall back to DB_SCHEMA
// if this exists, if this also does not exists use public schema
/** @phpstan-ignore-next-line */
if (defined('LOGIN_DB_SCHEMA') && !empty(LOGIN_DB_SCHEMA)) {
$SCHEMA = LOGIN_DB_SCHEMA;
} elseif (isset($db_config['db_schema']) && $db_config['db_schema']) {
$SCHEMA = $db_config['db_schema'];
@@ -171,11 +218,13 @@ class Login extends \CoreLibs\DB\IO
} else {
$SCHEMA = 'public';
}
// echo "<h1>*****SCHEMA******</h1>: $SCHEMA<br>";
// set schema if schema differs to schema set in db conneciton
if ($this->dbGetSchema() && $this->dbGetSchema() != $SCHEMA) {
$this->dbExec("SET search_path TO ".$SCHEMA);
$this->dbExec("SET search_path TO " . $SCHEMA);
}
$this->euid = array_key_exists('EUID', $_SESSION) ? $_SESSION['EUID'] : 0; // if there is none, there is none, saves me POST/GET check
// if there is none, there is none, saves me POST/GET check
$this->euid = array_key_exists('EUID', $_SESSION) ? $_SESSION['EUID'] : 0;
// get login vars, are so, can't be changed
// prepare
// pass on vars to Object vars
@@ -210,7 +259,7 @@ class Login extends \CoreLibs\DB\IO
$_SESSION['DEFAULT_ACL_LIST'] = [];
// read the current edit_access_right list into an array
$q = "SELECT level, type, name FROM edit_access_right WHERE level >= 0 ORDER BY level";
while ($res = $this->dbReturn($q)) {
while (is_array($res = $this->dbReturn($q))) {
// level to description format (numeric)
$this->default_acl_list[$res['level']] = [
'type' => $res['type'],
@@ -303,21 +352,24 @@ class Login extends \CoreLibs\DB\IO
$password = $this->password;
}
// first, errors on missing encryption
if ((preg_match("/^\\$2(a|y)\\$/", $hash) && CRYPT_BLOWFISH != 1) ||
if (
(preg_match("/^\\$2(a|y)\\$/", $hash) && CRYPT_BLOWFISH != 1) ||
(preg_match("/^\\$1\\$/", $hash) && CRYPT_MD5 != 1) ||
(preg_match("/^\\$[0-9A-Za-z.]{12}$/", $hash) && CRYPT_STD_DES != 1)
) {
// this means password cannot be decrypted because of missing crypt methods
$this->login_error = 9999;
$password_ok = false;
} elseif (preg_match("/^\\$2y\\$/", $hash) &&
} elseif (
preg_match("/^\\$2y\\$/", $hash) &&
!Password::passwordVerify($password, $hash)
) {
// this is the new password hash methid, is only $2y$
// all others are not valid anymore
$this->login_error = 1013;
$password_ok = false;
} elseif (!preg_match("/^\\$2(a|y)\\$/", $hash) &&
} elseif (
!preg_match("/^\\$2(a|y)\\$/", $hash) &&
!preg_match("/^\\$1\\$/", $hash) &&
!preg_match("/^\\$[0-9A-Za-z.]{12}$/", $hash) &&
$hash != $password
@@ -344,30 +396,40 @@ class Login extends \CoreLibs\DB\IO
$this->login_error = 102;
} else {
// we have to get the themes in here too
$q = "SELECT eu.edit_user_id, username, password, eu.edit_group_id, eg.name AS edit_group_name, admin, ";
$q .= "eu.login_error_count, eu.login_error_date_last, eu.login_error_date_first, eu.strict, eu.locked, ";
$q .= "debug, db_debug, ";
$q .= "eareu.level AS user_level, eareu.type AS user_type, ";
$q .= "eareg.level AS group_level, eareg.type AS group_type, ";
$q .= "eu.enabled, el.short_name AS lang_short, el.iso_name AS lang_iso, first.header_color AS first_header_color, ";
$q .= "second.header_color AS second_header_color, second.template ";
$q .= "FROM edit_user eu ";
$q .= "LEFT JOIN edit_scheme second ON (second.edit_scheme_id = eu.edit_scheme_id AND second.enabled = 1), ";
$q .= "edit_language el, edit_group eg, ";
$q .= "edit_access_right eareu, ";
$q .= "edit_access_right eareg, ";
$q .= "edit_scheme first ";
$q .= "WHERE first.edit_scheme_id = eg.edit_scheme_id AND eu.edit_group_id = eg.edit_group_id AND eu.edit_language_id = el.edit_language_id AND ";
$q .= "eu.edit_access_right_id = eareu.edit_access_right_id AND ";
$q .= "eg.edit_access_right_id = eareg.edit_access_right_id AND ";
// password match is done in script, against old plain or new blowfish encypted
$q .= "(LOWER(username) = '".$this->dbEscapeString(strtolower($this->username))."') ";
$q = "SELECT eu.edit_user_id, username, password, eu.edit_group_id, "
. "eg.name AS edit_group_name, admin, "
. "eu.login_error_count, eu.login_error_date_last, "
. "eu.login_error_date_first, eu.strict, eu.locked, "
. "debug, db_debug, "
. "eareu.level AS user_level, eareu.type AS user_type, "
. "eareg.level AS group_level, eareg.type AS group_type, "
. "eu.enabled, el.short_name AS lang_short, el.iso_name AS lang_iso, "
. "first.header_color AS first_header_color, "
. "second.header_color AS second_header_color, second.template "
. "FROM edit_user eu "
. "LEFT JOIN edit_scheme second ON "
. "(second.edit_scheme_id = eu.edit_scheme_id AND second.enabled = 1), "
. "edit_language el, edit_group eg, "
. "edit_access_right eareu, "
. "edit_access_right eareg, "
. "edit_scheme first "
. "WHERE first.edit_scheme_id = eg.edit_scheme_id "
. "AND eu.edit_group_id = eg.edit_group_id "
. "AND eu.edit_language_id = el.edit_language_id AND "
. "eu.edit_access_right_id = eareu.edit_access_right_id AND "
. "eg.edit_access_right_id = eareg.edit_access_right_id AND "
// password match is done in script, against old plain or new blowfish encypted
. "(LOWER(username) = '" . $this->dbEscapeString(strtolower($this->username)) . "') ";
$res = $this->dbReturn($q);
// username is wrong, but we throw for wrong username and wrong password the same error
if (!$this->cursor_ext[md5($q)]['num_rows']) {
if (!is_array($res)) {
$this->login_error = 1009;
$this->permission_okay = false;
} elseif (!$this->cursor_ext[md5($q)]['num_rows']) {
// username is wrong, but we throw for wrong username and wrong password the same error
$this->login_error = 1010;
} else {
// if login errors is half of max errors and the last login error was less than 10s ago, forbid any new login try
// if login errors is half of max errors and the last login error
// was less than 10s ago, forbid any new login try
// check flow
// - user is enabled
@@ -386,10 +448,14 @@ class Login extends \CoreLibs\DB\IO
// none to be set, set in login password check
} else {
// check if the current password is an invalid hash and do a rehash and set password
// $this->debug('LOGIN', 'Hash: '.$res['password'].' -> VERIFY: '.($Password::passwordVerify($this->password, $res['password']) ? 'OK' : 'FAIL').' => HASH: '.(Password::passwordRehashCheck($res['password']) ? 'NEW NEEDED' : 'OK'));
// $this->debug('LOGIN', 'Hash: '.$res['password'].' -> VERIFY: '
// .($Password::passwordVerify($this->password, $res['password']) ? 'OK' : 'FAIL')
// .' => HASH: '.(Password::passwordRehashCheck($res['password']) ? 'NEW NEEDED' : 'OK'));
if (Password::passwordRehashCheck($res['password'])) {
// update password hash to new one now
$q = "UPDATE edit_user SET password = '".$this->dbEscapeString(Password::passwordSet($this->password))."' WHERE edit_user_id = ".$res['edit_user_id'];
$q = "UPDATE edit_user "
. "SET password = '" . $this->dbEscapeString(Password::passwordSet($this->password))
. "' WHERE edit_user_id = " . $res['edit_user_id'];
$this->dbExec($q);
}
// normal user processing
@@ -397,7 +463,7 @@ class Login extends \CoreLibs\DB\IO
$_SESSION['EUID'] = $this->euid = $res['edit_user_id'];
// check if user is okay
$this->loginCheckPermissions();
if (!$this->login_error) {
if ($this->login_error == 0) {
// now set all session vars and read page permissions
$GLOBALS['DEBUG_ALL'] = $_SESSION['DEBUG_ALL'] = $res['debug'];
$GLOBALS['DB_DEBUG'] = $_SESSION['DB_DEBUG'] = $res['db_debug'];
@@ -410,39 +476,48 @@ class Login extends \CoreLibs\DB\IO
$_SESSION['GROUP_ACL_TYPE'] = $res['group_type'];
// deprecated TEMPLATE setting
$_SESSION['TEMPLATE'] = $res['template'] ? $res['template'] : '';
$_SESSION['HEADER_COLOR'] = $res['second_header_color'] ? $res['second_header_color'] : $res['first_header_color'];
$_SESSION['HEADER_COLOR'] = $res['second_header_color'] ?
$res['second_header_color'] :
$res['first_header_color'];
$_SESSION['LANG'] = $res['lang_short'];
$_SESSION['DEFAULT_CHARSET'] = $res['lang_iso'];
$_SESSION['DEFAULT_LANG'] = $res['lang_short'].'_'.strtolower(str_replace('-', '', $res['lang_iso']));
$_SESSION['DEFAULT_LANG'] = $res['lang_short'] . '_'
. strtolower(str_replace('-', '', $res['lang_iso']));
// reset any login error count for this user
if ($res['login_error_count'] > 0) {
$q = "UPDATE edit_user ";
$q .= "SET login_error_count = 0, login_error_date_last = NULL, login_error_date_first = NULL ";
$q .= "WHERE edit_user_id = ".$res['edit_user_id'];
$q = "UPDATE edit_user "
. "SET login_error_count = 0, login_error_date_last = NULL, "
. "login_error_date_first = NULL "
. "WHERE edit_user_id = " . $res['edit_user_id'];
$this->dbExec($q);
}
$edit_page_ids = [];
$pages = [];
$pages_acl = [];
// set pages access
$q = "SELECT ep.edit_page_id, ep.cuid, epca.cuid AS content_alias_uid, ";
$q .= "ep.hostname, ep.filename, ep.name AS edit_page_name, ";
$q .= "ep.order_number AS edit_page_order, ep.menu, ";
$q .= "ep.popup, ep.popup_x, ep.popup_y, ep.online, ear.level, ear.type ";
$q .= "FROM edit_page ep ";
$q .= "LEFT JOIN edit_page epca ON (epca.edit_page_id = ep.content_alias_edit_page_id)";
$q .= ", edit_page_access epa, edit_access_right ear ";
$q .= "WHERE ep.edit_page_id = epa.edit_page_id AND ear.edit_access_right_id = epa.edit_access_right_id ";
$q .= "AND epa.enabled = 1 AND epa.edit_group_id = ".$res["edit_group_id"]." ";
$q .= "ORDER BY ep.order_number";
$q = "SELECT ep.edit_page_id, ep.cuid, epca.cuid AS content_alias_uid, "
. "ep.hostname, ep.filename, ep.name AS edit_page_name, "
. "ep.order_number AS edit_page_order, ep.menu, "
. "ep.popup, ep.popup_x, ep.popup_y, ep.online, ear.level, ear.type "
. "FROM edit_page ep "
. "LEFT JOIN edit_page epca ON (epca.edit_page_id = ep.content_alias_edit_page_id)"
. ", edit_page_access epa, edit_access_right ear "
. "WHERE ep.edit_page_id = epa.edit_page_id "
. "AND ear.edit_access_right_id = epa.edit_access_right_id "
. "AND epa.enabled = 1 AND epa.edit_group_id = " . $res["edit_group_id"] . " "
. "ORDER BY ep.order_number";
while ($res = $this->dbReturn($q)) {
if (!is_array($res)) {
break;
}
// page id array for sub data readout
$edit_page_ids[$res['edit_page_id']] = $res['cuid'];
// create the array for pages
$pages[$res['cuid']] = [
'edit_page_id' => $res['edit_page_id'],
'cuid' => $res['cuid'],
'content_alias_uid' => $res['content_alias_uid'], // for reference of content data on a differen page
// for reference of content data on a differen page
'content_alias_uid' => $res['content_alias_uid'],
'hostname' => $res['hostname'],
'filename' => $res['filename'],
'page_name' => $res['edit_page_name'],
@@ -461,20 +536,20 @@ class Login extends \CoreLibs\DB\IO
$pages_acl[$res['filename']] = $res['level'];
} // for each page
// get the visible groups for all pages and write them to the pages
$_edit_page_id = 0;
$q = "SELECT epvg.edit_page_id, name, flag ";
$q .= "FROM edit_visible_group evp, edit_page_visible_group epvg ";
$q .= "WHERE evp.edit_visible_group_id = epvg.edit_visible_group_id AND epvg.edit_page_id IN (".join(', ', array_keys($edit_page_ids)).") ";
$q .= "ORDER BY epvg.edit_page_id";
while ($res = $this->dbReturn($q)) {
$q = "SELECT epvg.edit_page_id, name, flag "
. "FROM edit_visible_group evp, edit_page_visible_group epvg "
. "WHERE evp.edit_visible_group_id = epvg.edit_visible_group_id "
. "AND epvg.edit_page_id IN (" . join(', ', array_keys($edit_page_ids)) . ") "
. "ORDER BY epvg.edit_page_id";
while (is_array($res = $this->dbReturn($q))) {
$pages[$edit_page_ids[$res['edit_page_id']]]['visible'][$res['name']] = $res['flag'];
}
// get the same for the query strings
$_edit_page_id = 0;
$q = "SELECT eqs.edit_page_id, name, value, dynamic FROM edit_query_string eqs ";
$q .= "WHERE enabled = 1 AND edit_page_id IN (".join(', ', array_keys($edit_page_ids)).") ";
$q .= "ORDER BY eqs.edit_page_id";
while ($res = $this->dbReturn($q)) {
$q = "SELECT eqs.edit_page_id, name, value, dynamic FROM edit_query_string eqs "
. "WHERE enabled = 1 AND edit_page_id "
. "IN (" . join(', ', array_keys($edit_page_ids)) . ") "
. "ORDER BY eqs.edit_page_id";
while (is_array($res = $this->dbReturn($q))) {
$pages[$edit_page_ids[$res['edit_page_id']]]['query'][] = [
'name' => $res['name'],
'value' => $res['value'],
@@ -482,13 +557,13 @@ class Login extends \CoreLibs\DB\IO
];
}
// get the page content and add them to the page
$_edit_page_id = 0;
$q = "SELECT epc.edit_page_id, epc.name, epc.uid, epc.order_number, epc.online, ear.level, ear.type ";
$q .= "FROM edit_page_content epc, edit_access_right ear ";
$q .= "WHERE epc.edit_access_right_id = ear.edit_access_right_id AND ";
$q .= "epc.edit_page_id IN (".join(', ', array_keys($edit_page_ids)).") ";
$q .= "ORDER BY epc.order_number";
while ($res = $this->dbReturn($q)) {
$q = "SELECT epc.edit_page_id, epc.name, epc.uid, epc.order_number, "
. "epc.online, ear.level, ear.type "
. "FROM edit_page_content epc, edit_access_right ear "
. "WHERE epc.edit_access_right_id = ear.edit_access_right_id AND "
. "epc.edit_page_id IN (" . join(', ', array_keys($edit_page_ids)) . ") "
. "ORDER BY epc.order_number";
while (is_array($res = $this->dbReturn($q))) {
$pages[$edit_page_ids[$res['edit_page_id']]]['content'][$res['uid']] = [
'name' => $res['name'],
'uid' => $res['uid'],
@@ -503,19 +578,22 @@ class Login extends \CoreLibs\DB\IO
$_SESSION['PAGES'] = $pages;
$_SESSION['PAGES_ACL_LEVEL'] = $pages_acl;
// load the edit_access user rights
$q = "SELECT ea.edit_access_id, level, type, ea.name, ea.color, ea.uid, edit_default ";
$q .= "FROM edit_access_user eau, edit_access_right ear, edit_access ea ";
$q .= "WHERE eau.edit_access_id = ea.edit_access_id AND eau.edit_access_right_id = ear.edit_access_right_id ";
$q .= "AND eau.enabled = 1 AND edit_user_id = ".$this->euid." ";
$q .= "ORDER BY ea.name";
$q = "SELECT ea.edit_access_id, level, type, ea.name, ea.color, ea.uid, edit_default "
. "FROM edit_access_user eau, edit_access_right ear, edit_access ea "
. "WHERE eau.edit_access_id = ea.edit_access_id "
. "AND eau.edit_access_right_id = ear.edit_access_right_id "
. "AND eau.enabled = 1 AND edit_user_id = " . $this->euid . " "
. "ORDER BY ea.name";
$unit_access = [];
$eauid = [];
$unit_acl = [];
while ($res = $this->dbReturn($q)) {
while (is_array($res = $this->dbReturn($q))) {
// read edit access data fields and drop them into the unit access array
$q_sub ="SELECT name, value FROM edit_access_data WHERE enabled = 1 AND edit_access_id = ".$res['edit_access_id'];
$q_sub = "SELECT name, value "
. "FROM edit_access_data "
. "WHERE enabled = 1 AND edit_access_id = " . $res['edit_access_id'];
$ea_data = [];
while ($res_sub = $this->dbReturn($q_sub)) {
while (is_array($res_sub = $this->dbReturn($q_sub))) {
$ea_data[$res_sub['name']] = $res_sub['value'];
}
// build master unit array
@@ -542,25 +620,27 @@ class Login extends \CoreLibs\DB\IO
$_SESSION['EAID'] = $eauid;
} // user has permission to THIS page
} // user was not enabled or other login error
if ($this->login_error) {
if ($this->login_error && is_array($res)) {
$login_error_date_first = '';
if ($res['login_error_count'] == 0) {
$login_error_date_first = ", login_error_date_first = NOW()";
}
// update login error count for this user
$q = "UPDATE edit_user ";
$q .= "SET login_error_count = login_error_count + 1, login_error_date_last = NOW() ".$login_error_date_first." ";
$q .= "WHERE edit_user_id = ".$res['edit_user_id'];
$q = "UPDATE edit_user "
. "SET login_error_count = login_error_count + 1, "
. "login_error_date_last = NOW() " . $login_error_date_first . " "
. "WHERE edit_user_id = " . $res['edit_user_id'];
$this->dbExec($q);
// totally lock the user if error max is reached
if ($this->max_login_error_count != -1 &&
if (
$this->max_login_error_count != -1 &&
$res['login_error_count'] + 1 > $this->max_login_error_count
) {
// do some alert reporting in case this error is too big
// if strict is set, lock this user
// this needs manual unlocking by an admin user
if ($res['strict'] && !in_array($this->username, $this->lock_deny_users)) {
$q = "UPDATE edit_user SET locked = 1 WHERE edit_user_id = ".$res['edit_user_id'];
$q = "UPDATE edit_user SET locked = 1 WHERE edit_user_id = " . $res['edit_user_id'];
}
}
}
@@ -581,14 +661,28 @@ class Login extends \CoreLibs\DB\IO
public function loginCheckPermissions(): bool
{
if ($this->euid && $this->login_error != 103) {
$q = "SELECT filename ";
$q .= "FROM edit_page ep, edit_page_access epa, edit_group eg, edit_user eu ";
$q .= "WHERE ep.edit_page_id = epa.edit_page_id AND eg.edit_group_id = epa.edit_group_id AND eg.edit_group_id = eu.edit_group_id ";
$q .= "AND eu.edit_user_id = ".$this->euid." AND filename = '".$this->page_name."' AND eg.enabled = 1 AND epa.enabled = 1";
$q = "SELECT filename "
. "FROM edit_page ep, edit_page_access epa, edit_group eg, edit_user eu "
. "WHERE ep.edit_page_id = epa.edit_page_id "
. "AND eg.edit_group_id = epa.edit_group_id "
. "AND eg.edit_group_id = eu.edit_group_id "
. "AND eu.edit_user_id = " . $this->euid . " "
. "AND filename = '" . $this->page_name . "' "
. "AND eg.enabled = 1 AND epa.enabled = 1";
$res = $this->dbReturnRow($q);
if (!is_array($res)) {
$this->login_error = 109;
$this->permission_okay = false;
return $this->permission_okay;
}
// unset mem limit if debug is set to 1
// if (($GLOBALS["DEBUG_ALL"] || $GLOBALS["DB_DEBUG"] || $_SESSION["DEBUG_ALL"] || $_SESSION["DB_DEBUG"]) && ini_get('memory_limit') != -1)
// ini_set('memory_limit', -1);
// if (
// ($GLOBALS["DEBUG_ALL"] || $GLOBALS["DB_DEBUG"] ||
// $_SESSION["DEBUG_ALL"] || $_SESSION["DB_DEBUG"]) &&
// ini_get('memory_limit') != -1
// ) {
// ini_set('memory_limit', '-1');
// }
if (isset($res['filename']) && $res['filename'] == $this->page_name) {
$this->permission_okay = true;
} else {
@@ -687,7 +781,10 @@ class Login extends \CoreLibs\DB\IO
if ($_SESSION['GROUP_ACL_LEVEL'] != -1) {
$this->acl['page'] = $_SESSION['GROUP_ACL_LEVEL'];
}
if (isset($_SESSION['PAGES_ACL_LEVEL'][$this->page_name]) && $_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) {
if (
isset($_SESSION['PAGES_ACL_LEVEL'][$this->page_name]) &&
$_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1
) {
$this->acl['page'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name];
}
@@ -740,10 +837,14 @@ class Login extends \CoreLibs\DB\IO
/**
* checks if this edit access id is valid
* @param int|null $edit_access_id access id pk to check
* @return bool true/false: if the edit access is not in the valid list: false
* @return bool true/false: if the edit access is not
* in the valid list: false
*/
public function loginCheckEditAccess($edit_access_id): bool
{
if ($edit_access_id === null) {
return false;
}
if (array_key_exists($edit_access_id, $this->acl['unit'])) {
return true;
} else {
@@ -820,9 +921,15 @@ class Login extends \CoreLibs\DB\IO
}
// check user exist, if not -> error
if (!$this->login_error) {
$q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->dbEscapeString($this->pw_username)."'";
list ($edit_user_id) = $this->dbReturnRow($q);
if (!$edit_user_id) {
$q = "SELECT edit_user_id "
. "FROM edit_user "
. "WHERE enabled = 1 "
. "AND username = '" . $this->dbEscapeString($this->pw_username) . "'";
$res = $this->dbReturnRow($q);
if (
!is_array($res) ||
(is_array($res) && empty($res['edit_user_id']))
) {
// username wrong
$this->login_error = 201;
$data = 'User could not be found';
@@ -830,9 +937,21 @@ class Login extends \CoreLibs\DB\IO
}
// check old passwords match -> error
if (!$this->login_error) {
$q = "SELECT edit_user_id, password FROM edit_user WHERE enabled = 1 AND username = '".$this->dbEscapeString($this->pw_username)."'";
list ($edit_user_id, $old_password_hash) = $this->dbReturnRow($q);
if (!$edit_user_id || !$this->loginPasswordCheck($old_password_hash, $this->pw_old_password)) {
$q = "SELECT edit_user_id, password "
. "FROM edit_user "
. "WHERE enabled = 1 "
. "AND username = '" . $this->dbEscapeString($this->pw_username) . "'";
$edit_user_id = '';
$res = $this->dbReturnRow($q);
if (is_array($res)) {
$edit_user_id = $res['edit_user_id'];
}
if (
!is_array($res) ||
(is_array($res) &&
(empty($res['edit_user_id']) ||
!$this->loginPasswordCheck($res['old_password_hash'], $this->pw_old_password)))
) {
// old password wrong
$this->login_error = 202;
$data = 'The old password does not match';
@@ -862,15 +981,18 @@ class Login extends \CoreLibs\DB\IO
// no error change this users password
if (!$this->login_error && $edit_user_id) {
// update the user (edit_user_id) with the new password
$q = "UPDATE edit_user SET password = '".$this->dbEscapeString(Password::passwordSet($this->pw_new_password))."' WHERE edit_user_id = ".$edit_user_id;
$q = "UPDATE edit_user "
. "SET password = "
. "'" . $this->dbEscapeString(Password::passwordSet($this->pw_new_password)) . "' "
. "WHERE edit_user_id = " . $edit_user_id;
$this->dbExec($q);
$data = 'Password change for user "'.$this->pw_username.'"';
$data = 'Password change for user "' . $this->pw_username . '"';
$this->password_change_ok = true;
}
} else {
// illegal user error
$this->login_error = 220;
$data = 'Illegal user for password change: '.$this->pw_username;
$data = 'Illegal user for password change: ' . $this->pw_username;
}
// log this password change attempt
$this->writeLog($event, $data, $this->login_error, $this->pw_username);
@@ -879,7 +1001,7 @@ class Login extends \CoreLibs\DB\IO
/**
* prints out login html part if no permission (error) is set
* @return ?string html data for login page, or null for nothing
* @return string|null html data for login page, or null for nothing
*/
private function loginPrintLogin()
{
@@ -894,7 +1016,7 @@ class Login extends \CoreLibs\DB\IO
$LOGOUT_TARGET = "";
}
$html_string = $this->login_template['template'];
$html_string = (string)$this->login_template['template'];
// if password change is okay
if ($this->password_change) {
@@ -903,43 +1025,76 @@ class Login extends \CoreLibs\DB\IO
// pre change the data in the PASSWORD_CHANGE_DIV first
foreach ($this->login_template['strings'] as $string => $data) {
if ($data) {
$html_string_password_change = str_replace('{'.$string.'}', $data, $html_string_password_change);
$html_string_password_change = str_replace(
'{' . $string . '}',
$data,
$html_string_password_change
);
}
}
// print error messagae
if ($this->login_error) {
$html_string_password_change = str_replace('{ERROR_MSG}', $this->login_error_msg[$this->login_error].'<br>', $html_string_password_change);
$html_string_password_change = str_replace(
'{ERROR_MSG}',
$this->login_error_msg[$this->login_error] . '<br>',
$html_string_password_change
);
} else {
$html_string_password_change = str_replace('{ERROR_MSG}', '<br>', $html_string_password_change);
$html_string_password_change = str_replace(
'{ERROR_MSG}',
'<br>',
$html_string_password_change
);
}
// if pw change action, show the float again
if ($this->change_password && !$this->password_change_ok) {
$html_string_password_change = str_replace('{PASSWORD_CHANGE_SHOW}', '<script language="JavaScript">ShowHideDiv(\'pw_change_div\');</script>', $html_string_password_change);
$html_string_password_change = str_replace(
'{PASSWORD_CHANGE_SHOW}',
'<script language="JavaScript">'
. 'ShowHideDiv(\'pw_change_div\');</script>',
$html_string_password_change
);
} else {
$html_string_password_change = str_replace('{PASSWORD_CHANGE_SHOW}', '', $html_string_password_change);
$html_string_password_change = str_replace(
'{PASSWORD_CHANGE_SHOW}',
'',
$html_string_password_change
);
}
$this->login_template['strings']['PASSWORD_CHANGE_DIV'] = $html_string_password_change;
}
// put in the logout redirect string
if ($this->logout && $LOGOUT_TARGET) {
$html_string = str_replace('{LOGOUT_TARGET}', '<meta http-equiv="refresh" content="0; URL='.$LOGOUT_TARGET.'">', $html_string);
$html_string = str_replace(
'{LOGOUT_TARGET}',
'<meta http-equiv="refresh" content="0; URL=' . $LOGOUT_TARGET . '">',
$html_string
);
} else {
$html_string = str_replace('{LOGOUT_TARGET}', '', $html_string);
}
// print error messagae
if ($this->login_error) {
$html_string = str_replace('{ERROR_MSG}', $this->login_error_msg[$this->login_error].'<br>', $html_string);
$html_string = str_replace(
'{ERROR_MSG}',
$this->login_error_msg[$this->login_error] . '<br>',
$html_string
);
} elseif ($this->password_change_ok && $this->password_change) {
$html_string = str_replace('{ERROR_MSG}', $this->login_error_msg[300].'<br>', $html_string);
$html_string = str_replace(
'{ERROR_MSG}',
$this->login_error_msg[300] . '<br>',
$html_string
);
} else {
$html_string = str_replace('{ERROR_MSG}', '<br>', $html_string);
}
// create the replace array context
foreach ($this->login_template['strings'] as $string => $data) {
$html_string = str_replace('{'.$string.'}', $data, $html_string);
$html_string = str_replace('{' . $string . '}', $data, $html_string);
}
} // if permission is 0 then print out login
// return the created HTML here or null for nothing
@@ -956,7 +1111,7 @@ class Login extends \CoreLibs\DB\IO
// write to LOG table ...
if ($this->login_error || $this->login || $this->logout) {
$username = '';
$password = '';
// $password = '';
// set event
if ($this->login) {
$event = 'Login';
@@ -968,8 +1123,11 @@ class Login extends \CoreLibs\DB\IO
// prepare for log
if ($this->euid) {
// get user from user table
$q = "SELECT username FROM edit_user WHERE edit_user_id = ".$this->euid;
list($username) = $this->dbReturnRow($q);
$q = "SELECT username FROM edit_user WHERE edit_user_id = " . $this->euid;
$username = '';
if (is_array($res = $this->dbReturnRow($q))) {
$username = $res['username'];
}
} // if euid is set, get username (or try)
$this->writeLog($event, '', $this->login_error, $username);
} // write log under certain settings
@@ -1000,24 +1158,37 @@ class Login extends \CoreLibs\DB\IO
];
$error_msgs = [
'100' => $this->l->__('Fatal Error: <b>[EUID] came in as GET/POST!</b>'), // actually obsolete
'1010' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'), // user not found
'1011' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'), // blowfish password wrong
'1012' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'), // fallback md5 password wrong
'1013' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'), // new password_hash wrong
// actually obsolete
'100' => $this->l->__('Fatal Error: <b>[EUID] came in as GET/POST!</b>'),
// query errors
'1009' => $this->l->__('Fatal Error: <b>Login query reading failed<b>'),
// user not found
'1010' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'),
// blowfish password wrong
'1011' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'),
// fallback md5 password wrong
'1012' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'),
// new password_hash wrong
'1013' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'),
'102' => $this->l->__('Fatal Error: <b>Login Failed - Please enter username and password</b>'),
'103' => $this->l->__('Fatal Error: <b>You do not have the rights to access this Page</b>'),
'104' => $this->l->__('Fatal Error: <b>Login Failed - User not enabled</b>'),
'105' => $this->l->__('Fatal Error: <b>Login Failed - User is locked</b>'),
'220' => $this->l->__('Fatal Error: <b>Password change - The user could not be found</b>'), // actually this is an illegal user, but I mask it
'109' => $this->l->__('Fatal Error: <b>Check permission query reading failed</b>'),
// actually this is an illegal user, but I mask it
'220' => $this->l->__('Fatal Error: <b>Password change - The user could not be found</b>'),
'200' => $this->l->__('Fatal Error: <b>Password change - Please enter username and old password</b>'),
'201' => $this->l->__('Fatal Error: <b>Password change - The user could not be found</b>'),
'202' => $this->l->__('Fatal Error: <b>Password change - The old password is not correct</b>'),
'203' => $this->l->__('Fatal Error: <b>Password change - Please fill out both new password fields</b>'),
'204' => $this->l->__('Fatal Error: <b>Password change - The new passwords do not match</b>'),
'205' => $this->l->__('Fatal Error: <b>Password change - The new password is not in a valid format</b>'), // we should also not here WHAT is valid
'300' => $this->l->__('Success: <b>Password change successful</b>'), // for OK password change
'9999' => $this->l->__('Fatal Error: <b>necessary crypt engine could not be found</b>. Login is impossible') // this is bad bad error
// we should also not here WHAT is valid
'205' => $this->l->__('Fatal Error: <b>Password change - The new password is not in a valid format</b>'),
// for OK password change
'300' => $this->l->__('Success: <b>Password change successful</b>'),
// this is bad bad error
'9999' => $this->l->__('Fatal Error: <b>necessary crypt engine could not be found</b>. '
. 'Login is impossible'),
];
// if password change is okay
@@ -1028,23 +1199,36 @@ class Login extends \CoreLibs\DB\IO
'NEW_PASSWORD' => $this->l->__('New Password'),
'NEW_PASSWORD_CONFIRM' => $this->l->__('New Password confirm'),
'CLOSE' => $this->l->__('Close'),
'JS_SHOW_HIDE' => "function ShowHideDiv(id) { element = document.getElementById(id); if (element.className == 'visible' || !element.className) element.className = 'hidden'; else element.className = 'visible'; }",
'PASSWORD_CHANGE_BUTTON' => '<input type="button" name="pw_change" value="'.$strings['PASSWORD_CHANGE_BUTTON_VALUE'].'" OnClick="ShowHideDiv(\'pw_change_div\');">'
'JS_SHOW_HIDE' => "function ShowHideDiv(id) { "
. "element = document.getElementById(id); "
. "if (element.className == 'visible' || !element.className) element.className = 'hidden'; "
. "else element.className = 'visible'; }",
'PASSWORD_CHANGE_BUTTON' => '<input type="button" name="pw_change" value="'
. $strings['PASSWORD_CHANGE_BUTTON_VALUE']
. '" OnClick="ShowHideDiv(\'pw_change_div\');">'
]);
// NOTE: for the HTML block I ignore line lengths
// phpcs:disable
$this->login_template['password_change'] = <<<EOM
<div id="pw_change_div" class="hidden" style="position: absolute; top: 30px; left: 50px; width: 400px; height: 220px; background-color: white; border: 1px solid black; padding: 25px;">
<table>
<tr><td class="norm" align="center" colspan="2"><h3>{TITLE_PASSWORD_CHANGE}</h3></td></tr>
<tr><td class="norm" colspan="2">{ERROR_MSG}</td></tr>
<tr><td class="norm" align="right">{USERNAME}</td><td><input type="text" name="pw_username" value=""></td></tr>
<tr><td class="norm" align="right">{OLD_PASSWORD}</td><td><input type="password" name="pw_old_password" value=""></td></tr>
<tr><td class="norm" align="right">{NEW_PASSWORD}</td><td><input type="password" name="pw_new_password" value=""></td></tr>
<tr><td class="norm" align="right">{NEW_PASSWORD_CONFIRM}</td><td><input type="password" name="pw_new_password_confirm" value=""></td></tr>
<tr><td></td><td><input type="submit" name="change_password" value="{PASSWORD_CHANGE_BUTTON_VALUE}"><input type="button" name="pw_change" value="{CLOSE}" OnClick="ShowHideDiv('pw_change_div');"></td></tr>
<tr><td class="norm" align="right">{OLD_PASSWORD}</td>
<td><input type="password" name="pw_old_password" value=""></td></tr>
<tr><td class="norm" align="right">{NEW_PASSWORD}</td>
<td><input type="password" name="pw_new_password" value=""></td></tr>
<tr><td class="norm" align="right">{NEW_PASSWORD_CONFIRM}</td>
<td><input type="password" name="pw_new_password_confirm" value=""></td></tr>
<tr><td></td>
<td><input type="submit" name="change_password" value="{PASSWORD_CHANGE_BUTTON_VALUE}">
<input type="button" name="pw_change" value="{CLOSE}" OnClick="ShowHideDiv('pw_change_div');"></td></tr>
</table>
</div>
{PASSWORD_CHANGE_SHOW}
EOM;
// phpcs:enable
}
if ($this->password_forgot) {
}
@@ -1161,30 +1345,40 @@ EOM;
'_FILES' => $_FILES,
'error' => $this->login_error
];
$data_binary = $this->dbEscapeBytea(bzcompress(serialize($_data_binary)));
$data_binary = $this->dbEscapeBytea((string)bzcompress(serialize($_data_binary)));
// SQL querie for log entry
$q = "INSERT INTO edit_log ";
$q .= "(username, password, euid, event_date, event, error, data, data_binary, page, ";
$q .= "ip, user_agent, referer, script_name, query_string, server_name, http_host, http_accept, http_accept_charset, http_accept_encoding, session_id, ";
$q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) ";
$q .= "VALUES ('".$this->dbEscapeString($username)."', 'PASSWORD', ".($this->euid ? $this->euid : 'NULL').", ";
$q .= "NOW(), '".$this->dbEscapeString($event)."', '".$this->dbEscapeString((string)$error)."', '".$this->dbEscapeString($data)."', '".$data_binary."', '".$this->page_name."', ";
foreach ([
'REMOTE_ADDR', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'SCRIPT_FILENAME', 'QUERY_STRING', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_ACCEPT', 'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING'
] as $server_code) {
$q = "INSERT INTO edit_log "
. "(username, password, euid, event_date, event, error, data, data_binary, page, "
. "ip, user_agent, referer, script_name, query_string, server_name, http_host, "
. "http_accept, http_accept_charset, http_accept_encoding, session_id, "
. "action, action_id, action_yes, action_flag, action_menu, action_loaded, "
. "action_value, action_error) "
. "VALUES ('" . $this->dbEscapeString($username) . "', 'PASSWORD', "
. ($this->euid ? $this->euid : 'NULL') . ", "
. "NOW(), '" . $this->dbEscapeString($event) . "', "
. "'" . $this->dbEscapeString((string)$error) . "', "
. "'" . $this->dbEscapeString($data) . "', '" . $data_binary . "', "
. "'" . $this->page_name . "', ";
foreach (
[
'REMOTE_ADDR', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'SCRIPT_FILENAME',
'QUERY_STRING', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_ACCEPT',
'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING'
] as $server_code
) {
if (array_key_exists($server_code, $_SERVER)) {
$q .= "'".$this->dbEscapeString($_SERVER[$server_code])."', ";
$q .= "'" . $this->dbEscapeString($_SERVER[$server_code]) . "', ";
} else {
$q .= "NULL, ";
}
}
$q .= "'".session_id()."', ";
$q .= "'".$this->dbEscapeString($this->action)."', ";
$q .= "'".$this->dbEscapeString($this->username)."', ";
$q .= "'" . session_id() . "', ";
$q .= "'" . $this->dbEscapeString($this->action) . "', ";
$q .= "'" . $this->dbEscapeString($this->username) . "', ";
$q .= "NULL, ";
$q .= "'".$this->dbEscapeString((string)$this->login_error)."', ";
$q .= "'" . $this->dbEscapeString((string)$this->login_error) . "', ";
$q .= "NULL, NULL, ";
$q .= "'".$this->dbEscapeString((string)$this->permission_okay)."', ";
$q .= "'" . $this->dbEscapeString((string)$this->permission_okay) . "', ";
$q .= "NULL)";
$this->dbExec($q, 'NULL');
}
@@ -1197,7 +1391,9 @@ EOM;
*/
public function loginCheckEditAccessId(?int $edit_access_id): ?int
{
if (isset($_SESSION['UNIT']) &&
if (
$edit_access_id !== null &&
isset($_SESSION['UNIT']) &&
is_array($_SESSION['UNIT']) &&
!array_key_exists($edit_access_id, $_SESSION['UNIT'])
) {
@@ -1222,6 +1418,7 @@ EOM;
return $_SESSION['UNIT'][$edit_access_id]['data'][$data_key];
}
}
} // close class
// close class
}
// __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1);
<?php
/*********************************************************************
* AUTHOR: Clemens Schwaighofer
* CREATED: 2006/08/15
@@ -10,6 +11,10 @@
* - menu creation
* - array vars for smarty
*
* CHANGE PLAN:
* loads DB\IO + Logger and returns one group object
* also checks all missing CONFIG vars from Basic class
*
* PUBLIC VARIABLES
*
* PRIVATE VARIABLES
@@ -22,53 +27,87 @@
*
*********************************************************************/
declare(strict_types=1);
namespace CoreLibs\Admin;
class Backend extends \CoreLibs\DB\IO
{
// page name
/** @var array<mixed> */
public $menu = [];
/** @var int|string */
public $menu_show_flag = 0; // top menu flag (mostly string)
// action ids
public $action_list = ['action', 'action_id', 'action_sub_id', 'action_yes', 'action_flag', 'action_menu', 'action_value', 'action_error', 'action_loaded'];
/** @var array<string> */
public $action_list = [
'action', 'action_id', 'action_sub_id', 'action_yes', 'action_flag',
'action_menu', 'action_value', 'action_error', 'action_loaded'
];
/** @var string */
public $action;
/** @var string|int */
public $action_id;
/** @var string|int */
public $action_sub_id;
/** @var string|int|bool */
public $action_yes;
/** @var string */
public $action_flag;
/** @var string */
public $action_menu;
/** @var string */
public $action_loaded;
/** @var string */
public $action_value;
/** @var string */
public $action_error;
// ACL array variable if we want to set acl data from outisde
/** @var array<mixed> */
public $acl = [];
/** @var int */
public $default_acl;
// queue key
/** @var string */
public $queue_key;
// the current active edit access id
/** @var int */
public $edit_access_id;
// error/warning/info messages
/** @var array<mixed> */
public $messages = [];
public $error = 0;
public $warning = 0;
public $info = 0;
/** @var bool */
public $error = false;
/** @var bool */
public $warning = false;
/** @var bool */
public $info = false;
// internal lang & encoding vars
/** @var string */
public $lang_dir = '';
/** @var string */
public $lang;
/** @var string */
public $lang_short;
/** @var string */
public $encoding;
// language
/** @var \CoreLibs\Language\L10n */
public $l;
// smarty publics [end processing in smarty class]
/** @var array<mixed> */
public $DATA;
/** @var array<mixed> */
public $HEADER;
/** @var array<mixed> */
public $DEBUG_DATA;
/** @var array<mixed> */
public $CONTENT_DATA;
// CONSTRUCTOR / DECONSTRUCTOR |====================================>
/**
* main class constructor
* @param array $db_config db config array
* @param array<mixed> $db_config db config array
*/
public function __construct(array $db_config)
{
@@ -134,14 +173,14 @@ class Backend extends \CoreLibs\DB\IO
// create the char lang encoding
$this->lang_short = substr($this->lang, 0, 2);
// set the language folder
$this->lang_dir = BASE.INCLUDES.LANG.CONTENT_PATH;
$this->lang_dir = BASE . INCLUDES . LANG . CONTENT_PATH;
}
// PUBLIC METHODS |=================================================>
/**
* set internal ACL from login ACL
* @param array $acl login acl array
* @param array<mixed> $acl login acl array
*/
public function setACL(array $acl): void
{
@@ -150,16 +189,16 @@ class Backend extends \CoreLibs\DB\IO
/**
* writes all action vars plus other info into edit_log tabl
* @param string $event any kind of event description,
* @param string|array $data any kind of data related to that event
* @param string $write_type write type can bei STRING or BINARY
* @return void has no return
* @param string $event any kind of event description,
* @param string|array<mixed> $data any kind of data related to that event
* @param string $write_type write type can bei STRING or BINARY
* @return void
*/
public function adbEditLog(string $event = '', $data = '', string $write_type = 'STRING'): void
{
$data_binary = '';
if ($write_type == 'BINARY') {
$data_binary = $this->dbEscapeBytea(bzcompress(serialize($data)));
$data_binary = $this->dbEscapeBytea((string)bzcompress(serialize($data)));
$data = 'see bzip compressed data_binary field';
}
if ($write_type == 'STRING') {
@@ -168,49 +207,55 @@ class Backend extends \CoreLibs\DB\IO
}
// check schema
if (defined('LOGIN_DB_SCHEMA') && LOGIN_DB_SCHEMA) {
$SCHEMA = 'public';
/** @phpstan-ignore-next-line */
if (defined('LOGIN_DB_SCHEMA') && !empty(LOGIN_DB_SCHEMA)) {
$SCHEMA = LOGIN_DB_SCHEMA;
} elseif ($this->dbGetSchema()) {
$SCHEMA = $this->dbGetSchema();
} elseif (defined('PUBLIC_SCHEMA')) {
$SCHEMA = PUBLIC_SCHEMA;
} else {
$SCHEMA = 'public';
}
$q = "INSERT INTO ".$SCHEMA.".edit_log ";
$q .= "(euid, event_date, event, data, data_binary, page, ";
$q .= "ip, user_agent, referer, script_name, query_string, server_name, http_host, http_accept, http_accept_charset, http_accept_encoding, session_id, ";
$q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) ";
$q .= "VALUES ";
$q .= "(".$this->dbEscapeString(isset($_SESSION['EUID']) && is_numeric($_SESSION['EUID']) ? $_SESSION['EUID'] : 'NULL').", ";
$q .= "NOW(), ";
$q .= "'".$this->dbEscapeString((string)$event)."', '".$data."', '".$data_binary."', '".$this->dbEscapeString((string)$this->page_name)."', ";
$q .= "'".@$_SERVER["REMOTE_ADDR"]."', '".$this->dbEscapeString(@$_SERVER['HTTP_USER_AGENT'])."', ";
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_REFERER'] ?? '')."', ";
$q .= "'".$this->dbEscapeString($_SERVER['SCRIPT_FILENAME'] ?? '')."', ";
$q .= "'".$this->dbEscapeString($_SERVER['QUERY_STRING'] ?? '')."', ";
$q .= "'".$this->dbEscapeString($_SERVER['SERVER_NAME'] ?? '')."', ";
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_HOST'] ?? '')."', ";
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_ACCEPT'] ?? '')."', ";
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_ACCEPT_CHARSET'] ?? '')."', ";
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '')."', ";
$q .= "'".session_id()."', ";
$q .= "'".$this->dbEscapeString($this->action)."', ";
$q .= "'".$this->dbEscapeString($this->action_id)."', ";
$q .= "'".$this->dbEscapeString($this->action_yes)."', ";
$q .= "'".$this->dbEscapeString($this->action_flag)."', ";
$q .= "'".$this->dbEscapeString($this->action_menu)."', ";
$q .= "'".$this->dbEscapeString($this->action_loaded)."', ";
$q .= "'".$this->dbEscapeString($this->action_value)."', ";
$q .= "'".$this->dbEscapeString($this->action_error)."')";
/** @phpstan-ignore-next-line for whatever reason $SCHEMA is seen as possible array */
$q = "INSERT INTO " . $SCHEMA . ".edit_log "
. "(euid, event_date, event, data, data_binary, page, "
. "ip, user_agent, referer, script_name, query_string, server_name, http_host, "
. "http_accept, http_accept_charset, http_accept_encoding, session_id, "
. "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "
. "VALUES "
. "(" . $this->dbEscapeString(isset($_SESSION['EUID']) && is_numeric($_SESSION['EUID']) ?
$_SESSION['EUID'] :
'NULL')
. ", "
. "NOW(), "
. "'" . $this->dbEscapeString((string)$event) . "', '" . $data . "', "
. "'" . $data_binary . "', '" . $this->dbEscapeString((string)$this->page_name) . "', "
. "'" . @$_SERVER["REMOTE_ADDR"] . "', "
. "'" . $this->dbEscapeString(@$_SERVER['HTTP_USER_AGENT']) . "', "
. "'" . $this->dbEscapeString($_SERVER['HTTP_REFERER'] ?? '') . "', "
. "'" . $this->dbEscapeString($_SERVER['SCRIPT_FILENAME'] ?? '') . "', "
. "'" . $this->dbEscapeString($_SERVER['QUERY_STRING'] ?? '') . "', "
. "'" . $this->dbEscapeString($_SERVER['SERVER_NAME'] ?? '') . "', "
. "'" . $this->dbEscapeString($_SERVER['HTTP_HOST'] ?? '') . "', "
. "'" . $this->dbEscapeString($_SERVER['HTTP_ACCEPT'] ?? '') . "', "
. "'" . $this->dbEscapeString($_SERVER['HTTP_ACCEPT_CHARSET'] ?? '') . "', "
. "'" . $this->dbEscapeString($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '') . "', "
. "'" . session_id() . "', "
. "'" . $this->dbEscapeString($this->action) . "', "
. "'" . $this->dbEscapeString($this->action_id) . "', "
. "'" . $this->dbEscapeString($this->action_yes) . "', "
. "'" . $this->dbEscapeString($this->action_flag) . "', "
. "'" . $this->dbEscapeString($this->action_menu) . "', "
. "'" . $this->dbEscapeString($this->action_loaded) . "', "
. "'" . $this->dbEscapeString($this->action_value) . "', "
. "'" . $this->dbEscapeString($this->action_error) . "')";
$this->dbExec($q, 'NULL');
}
/**
* menu creater (from login menu session pages)
* @param int $flag visible flag trigger
* @return array menu array for output on page (smarty)
* @param int $flag visible flag trigger
* @return array<mixed> menu array for output on page (smarty)
*/
public function adbTopMenu(int $flag = 0): array
{
@@ -224,14 +269,14 @@ class Backend extends \CoreLibs\DB\IO
$PAGES = [];
}
$pages = [];
foreach ($PAGES as $PAGE_CUID => $PAGE_DATA) {
foreach ($PAGES as $PAGE_DATA) {
$pages[] = $PAGE_DATA;
}
// $this->debug('pages', $this->print_ar($pages));
// if flag is 0, then we show all, else, we show only the matching flagges array points
// array is already sorted after correct order
reset($pages);
foreach ($pages as $i => $data) {
foreach ($pages as $data) {
// for ($i = 0, $iMax = count($pages); $i < $iMax; $i ++) {
$show = 0;
// is it visible in the menu & is it online
@@ -258,20 +303,23 @@ class Backend extends \CoreLibs\DB\IO
}
$query_string = '';
if (isset($data['query']) &&
if (
isset($data['query']) &&
is_array($data['query']) &&
count($data['query'])
) {
// for ($j = 0, $jMax = count($pages[$i]['query']); $j < $jMax; $j ++) {
foreach ($data['query'] as $j => $query) {
if (!empty($query['name']) &&
if (
!empty($query['name']) &&
!empty($query['value'])
) {
if (strlen($query_string)) {
$query_string .= '&';
}
$query_string .= $query['name'].'=';
if (isset($query['dynamic']) &&
$query_string .= $query['name'] . '=';
if (
isset($query['dynamic']) &&
$query['dynamic']
) {
if (isset($_GET[$query['value']])) {
@@ -291,12 +339,13 @@ class Backend extends \CoreLibs\DB\IO
}
$url .= $data['filename'] ?? '';
if (strlen($query_string)) {
$url .= '?'.$query_string;
$url .= '?' . $query_string;
}
$name = $data['page_name'] ?? '';
// if page name matchs -> set selected flag
$selected = 0;
if (isset($data['filename']) &&
if (
isset($data['filename']) &&
\CoreLibs\Get\System::getPageName() == $data['filename'] &&
(!isset($data['hostname']) || (
isset($data['hostname']) &&
@@ -308,7 +357,8 @@ class Backend extends \CoreLibs\DB\IO
}
// last check, is this menu point okay to show
$enabled = 0;
if (isset($data['filename']) &&
if (
isset($data['filename']) &&
$this->adbShowMenuPoint($data['filename'])
) {
$enabled = 1;
@@ -329,11 +379,12 @@ class Backend extends \CoreLibs\DB\IO
}
/**
* ONLY USED IN adbTopMenu
* checks if this filename is in the current situation (user id, etc) available
* @param string|null $filename filename
* @return bool true for visible/accessable menu point, false for not
*/
public function adbShowMenuPoint(?string $filename): bool
private function adbShowMenuPoint(?string $filename): bool
{
$enabled = false;
if ($filename === null) {
@@ -351,15 +402,18 @@ class Backend extends \CoreLibs\DB\IO
/**
* @deprecated
* creates out of a normal db_return array an assoc array
* @param array $db_array input array
* @param array<mixed> $db_array input array
* @param string|int|bool $key key
* @param string|int|bool $value value
* @return array associative array
* @return array<mixed> associative array
* @deprecated \CoreLibs\Combined\ArrayHandler::genAssocArray()
*/
public function adbAssocArray(array $db_array, $key, $value): array
{
trigger_error('Method '.__METHOD__.' is deprecated: \CoreLibs\Combined\ArrayHandler::genAssocArray', E_USER_DEPRECATED);
trigger_error(
'Method ' . __METHOD__ . ' is deprecated: \CoreLibs\Combined\ArrayHandler::genAssocArray',
E_USER_DEPRECATED
);
return \CoreLibs\Combined\ArrayHandler::genAssocArray($db_array, $key, $value);
}
@@ -372,33 +426,47 @@ class Backend extends \CoreLibs\DB\IO
*/
public function adbByteStringFormat($number): string
{
trigger_error('Method '.__METHOD__.' is deprecated: \CoreLibs\Convert\Byte::humanReadableByteFormat()', E_USER_DEPRECATED);
trigger_error(
'Method ' . __METHOD__ . ' is deprecated: \CoreLibs\Convert\Byte::humanReadableByteFormat()',
E_USER_DEPRECATED
);
return \CoreLibs\Convert\Byte::humanReadableByteFormat($number);
}
/**
* @deprecated
* converts picture to a thumbnail with max x and max y size
* @param string $pic source image file with or without path
* @param int $size_x maximum size width
* @param int $size_y maximum size height
* @param string $dummy empty, or file_type to show an icon instead of nothing if file is not found
* @param string $path if source start is not ROOT path, if empty ROOT is choosen
* @return string|bool thumbnail name, or false for error
* @param string $pic source image file with or without path
* @param int $size_x maximum size width
* @param int $size_y maximum size height
* @param string $dummy empty, or file_type to show an icon
* instead of nothing if file is not found
* @param string $path if source start is not ROOT path
* if empty ROOT is choosen
* @return string|bool thumbnail name, or false for error
* @deprecated \CoreLibs\Output\Image::createThumbnail()
*/
public function adbCreateThumbnail($pic, $size_x, $size_y, $dummy = '', $path = "", $cache = "")
{
trigger_error('Method '.__METHOD__.' is deprecated: \CoreLibs\Output\Image::createThumbnail()', E_USER_DEPRECATED);
public function adbCreateThumbnail(
string $pic,
int $size_x,
int $size_y,
string $dummy = '',
string $path = '',
string $cache = ''
) {
trigger_error(
'Method ' . __METHOD__ . ' is deprecated: \CoreLibs\Output\Image::createThumbnail()',
E_USER_DEPRECATED
);
return \CoreLibs\Output\Image::createThumbnail($pic, $size_x, $size_y, $dummy, $path, $cache);
}
/**
* wrapper function to fill up the mssages array
* @param string $level info/warning/error
* @param string $msg string, can be printf formated
* @param array $vars optional data for a possible printf formated msg
* @return void has no return
* @param string $level info/warning/error
* @param string $msg string, can be printf formated
* @param array<mixed> $vars optional data for a possible printf formated msg
* @return void has no return
*/
public function adbMsg(string $level, string $msg, array $vars = []): void
{
@@ -411,13 +479,13 @@ class Backend extends \CoreLibs\DB\IO
];
switch ($level) {
case 'info':
$this->info = 1;
$this->info = true;
break;
case 'warning':
$this->warning = 1;
$this->warning = true;
break;
case 'error':
$this->error = 1;
$this->error = true;
break;
}
}
@@ -444,7 +512,8 @@ class Backend extends \CoreLibs\DB\IO
string $associate = null,
string $file = null
): void {
if (defined('GLOBAL_DB_SCHEMA') && GLOBAL_DB_SCHEMA) {
/** @phpstan-ignore-next-line */
if (defined('GLOBAL_DB_SCHEMA') && !empty(GLOBAL_DB_SCHEMA)) {
$SCHEMA = GLOBAL_DB_SCHEMA;
} elseif ($this->dbGetSchema()) {
$SCHEMA = $this->dbGetSchema();
@@ -453,14 +522,15 @@ class Backend extends \CoreLibs\DB\IO
} else {
$SCHEMA = 'public';
}
$q = "INSERT INTO ".$SCHEMA.".live_queue (";
$q .= "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file";
$q .= ") VALUES (";
$q .= "'".$this->dbEscapeString($queue_key)."', '".$this->dbEscapeString($key_value)."', ";
$q .= "'".$this->dbEscapeString($key_name)."', '".$this->dbEscapeString($type)."', ";
$q .= "'".$this->dbEscapeString($target)."', '".$this->dbEscapeString($data)."', ";
$q .= "'".$this->queue_key."', '".$this->action."', '".$this->dbEscapeString((string)$associate)."', ";
$q .= "'".$this->dbEscapeString((string)$file)."')";
$q = "INSERT INTO " . $SCHEMA . ".live_queue ("
. "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file"
. ") VALUES ("
. "'" . $this->dbEscapeString($queue_key) . "', '" . $this->dbEscapeString($key_value) . "', "
. "'" . $this->dbEscapeString($key_name) . "', '" . $this->dbEscapeString($type) . "', "
. "'" . $this->dbEscapeString($target) . "', '" . $this->dbEscapeString($data) . "', "
. "'" . $this->queue_key . "', '" . $this->action . "', "
. "'" . $this->dbEscapeString((string)$associate) . "', "
. "'" . $this->dbEscapeString((string)$file) . "')";
$this->dbExec($q);
}
@@ -490,14 +560,23 @@ class Backend extends \CoreLibs\DB\IO
bool $name_pos_back = false
) {
// get the build layout
$html_time = \CoreLibs\Output\Form\Elements::printDateTime($year, $month, $day, $hour, $min, $suffix, $min_steps, $name_pos_back);
$html_time = \CoreLibs\Output\Form\Elements::printDateTime(
$year,
$month,
$day,
$hour,
$min,
$suffix,
$min_steps,
$name_pos_back
);
// translate the strings inside
foreach (['Year ', 'Month ', 'Day ', 'Hour ', 'Minute '] as $_time) {
$html_time = str_replace($_time, $this->l->__(str_replace(' ', '', $_time)).' ', $html_time);
$html_time = str_replace($_time, $this->l->__(str_replace(' ', '', $_time)) . ' ', $html_time);
}
// replace week days in short
foreach (['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as $_date) {
$html_time = str_replace('('.$_date.')', '('.$this->l->__($_date).')', $html_time);
$html_time = str_replace('(' . $_date . ')', '(' . $this->l->__($_date) . ')', $html_time);
}
// return the datetime select string with strings translated
return $html_time;

File diff suppressed because it is too large Load Diff

View File

@@ -1,48 +1,77 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace CoreLibs\Check;
class Email
{
// this is for error check parts in where the email regex failed
/** @var array<int,string> */
private static $email_regex_check = [
0 => "^[A-Za-z0-9!#$%&'*+\-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+\-\/=?^_`{|}~\.]{0,63}@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*\.([a-zA-Z]{2,}){1}$", // MASTER
0 => "^[A-Za-z0-9!#$%&'*+\-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+\-\/=?^_`{|}~\.]{0,63}@"
. "[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*\.([a-zA-Z]{2,}){1}$", // MASTER
1 => "@(.*)@(.*)", // double @
2 => "^[A-Za-z0-9!#$%&'*+-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+-\/=?^_`{|}~\.]{0,63}@", // wrong part before @
2 => "^[A-Za-z0-9!#$%&'*+\-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+\-\/=?^_`{|}~\.]{0,63}@", // wrong part before @
3 => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.([a-zA-Z]{2,}){1}$", // wrong part after @
4 => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.", // wrong domain name part
5 => "\.([a-zA-Z]{2,6}){1}$", // wrong top level part
6 => "@(.*)\.{2,}", // double .. in domain name part
7 => "@.*\.$" // ends with a dot, top level, domain missing
];
// for above position, description string below
/** @var array<int,string> */
private static $email_regex_check_message = [
0 => 'Invalid email address',
1 => 'Double @ mark in email address',
2 => 'Invalid email part before @ sign',
3 => 'Invalid domain part after @ sign',
4 => 'Invalid domain name part',
5 => 'Wrong domain top level part',
6 => 'Double consecutive dots in domain name (..)',
7 => 'Domain ends with a dot or is missing top level part'
];
// the array with the mobile types that are valid
/** @var array<string,string> */
private static $mobile_email_type = [
'.*@docomo\.ne\.jp$' => 'keitai_docomo',
'.*@([a-z0-9]{2}\.)?ezweb\.ne\.jp$' => 'keitai_kddi_ezweb', # correct are a[2-4], b2, c[1-9], e[2-9], h[2-4], t[1-9]
'.*@(ez[a-j]{1}\.)?ido\.ne\.jp$' => 'keitai_kddi_ido', # ez[a-j] or nothing
'.*@([a-z]{2}\.)?sky\.tu-ka\.ne\.jp$' => 'keitai_kddi_tu-ka', # (sky group)
'.*@([a-z]{2}\.)?sky\.tk[kc]{1}\.ne\.jp$' => 'keitai_kddi_sky', # (sky group) [tkk,tkc only]
'.*@([a-z]{2}\.)?sky\.dtg\.ne\.jp$' => 'keitai_kddi_dtg', # dtg (sky group)
'.*@[tkdhcrnsq]{1}\.vodafone\.ne\.jp$' => 'keitai_softbank_vodafone', # old vodafone [t,k,d,h,c,r,n,s,q]
'.*@jp-[dhtkrsnqc]{1}\.ne\.jp$' => 'keitai_softbank_j-phone', # very old j-phone (pre vodafone) [d,h,t,k,r,s,n,q,c]
'.*@([dhtcrknsq]{1}\.)?softbank\.ne\.jp$' => 'keitai_softbank', # add i for iphone also as keitai, others similar to the vodafone group
'.*@i{1}\.softbank(\.ne)?\.jp$' => 'smartphone_softbank_iphone', # add iPhone also as keitai and not as pc
'.*@disney\.ne\.jp$' => 'keitai_softbank_disney', # (kids)
// correct are a[2-4], b2, c[1-9], e[2-9], h[2-4], t[1-9]
'.*@([a-z0-9]{2}\.)?ezweb\.ne\.jp$' => 'keitai_kddi_ezweb',
// ez[a-j] or nothing
'.*@(ez[a-j]{1}\.)?ido\.ne\.jp$' => 'keitai_kddi_ido',
// (sky group)
'.*@([a-z]{2}\.)?sky\.tu-ka\.ne\.jp$' => 'keitai_kddi_tu-ka',
// (sky group) [tkk,tkc only]
'.*@([a-z]{2}\.)?sky\.tk[kc]{1}\.ne\.jp$' => 'keitai_kddi_sky',
// dtg (sky group)
'.*@([a-z]{2}\.)?sky\.dtg\.ne\.jp$' => 'keitai_kddi_dtg',
// old vodafone [t,k,d,h,c,r,n,s,q]
'.*@[tkdhcrnsq]{1}\.vodafone\.ne\.jp$' => 'keitai_softbank_vodafone',
// very old j-phone (pre vodafone) [d,h,t,k,r,s,n,q,c]
'.*@jp-[dhtkrsnqc]{1}\.ne\.jp$' => 'keitai_softbank_j-phone',
// add i for iphone also as keitai, others similar to the vodafone group
'.*@([dhtcrknsq]{1}\.)?softbank\.ne\.jp$' => 'keitai_softbank',
// add iPhone also as keitai and not as pc
'.*@i{1}\.softbank(\.ne)?\.jp$' => 'smartphone_softbank_iphone',
'.*@disney\.ne\.jp$' => 'keitai_softbank_disney', // (kids)
'.*@willcom\.ne\.jp$' => 'keitai_willcom',
'.*@willcom\.com$' => 'keitai_willcom', # new for pdx.ne.jp address
'.*@willcom\.com$' => 'keitai_willcom', # new for pdx.ne.jp address
'.*@wcm\.ne\.jp$' => 'keitai_willcom', # old willcom wcm.ne.jp
'.*@pdx\.ne\.jp$' => 'keitai_willcom_pdx', # old pdx address for willcom
'.*@bandai\.jp$' => 'keitai_willcom_bandai', # willcom paipo! (kids)
'.*@pipopa\.ne\.jp$' => 'keitai_willcom_pipopa', # willcom paipo! (kids)
'.*@([a-z0-9]{2,4}\.)?pdx\.ne\.jp$' => 'keitai_willcom_pdx', # actually only di,dj,dk,wm -> all others are "wrong", but none also allowed?
'.*@ymobile([1]{1})?\.ne\.jp$' => 'keitai_willcom_ymobile', # ymobile, ymobile1 techincally not willcom, but I group them there (softbank sub)
'.*@y-mobile\.ne\.jp$' => 'keitai_willcom_ymobile', # y-mobile techincally not willcom, but I group them there (softbank sub)
'.*@emnet\.ne\.jp$' => 'keitai_willcom_emnet', # e-mobile, group will willcom
'.*@emobile\.ne\.jp$' => 'keitai_willcom_emnet', # e-mobile, group will willcom
'.*@willcom\.com$' => 'keitai_willcom', // new for pdx.ne.jp address
'.*@wcm\.ne\.jp$' => 'keitai_willcom', // old willcom wcm.ne.jp
'.*@pdx\.ne\.jp$' => 'keitai_willcom_pdx', // old pdx address for willcom
'.*@bandai\.jp$' => 'keitai_willcom_bandai', // willcom paipo! (kids)
'.*@pipopa\.ne\.jp$' => 'keitai_willcom_pipopa', // willcom paipo! (kids)
// actually only di,dj,dk,wm -> all others are "wrong", but none also allowed?
'.*@([a-z0-9]{2,4}\.)?pdx\.ne\.jp$' => 'keitai_willcom_pdx',
// ymobile, ymobile1 techincally not willcom, but I group them there (softbank sub)
'.*@ymobile([1]{1})?\.ne\.jp$' => 'keitai_willcom_ymobile',
// y-mobile techincally not willcom, but I group them there (softbank sub)
'.*@y-mobile\.ne\.jp$' => 'keitai_willcom_ymobile',
'.*@emnet\.ne\.jp$' => 'keitai_willcom_emnet', // e-mobile, group will willcom
'.*@emobile\.ne\.jp$' => 'keitai_willcom_emnet', // e-mobile, group will willcom
'.*@emobile-s\.ne\.jp$' => 'keitai_willcom_emnet' # e-mobile, group will willcom
];
// short list for mobile email types
/** @var array<string,string> */
private static $mobile_email_type_short = [
'keitai_docomo' => 'docomo',
'keitai_kddi_ezweb' => 'kddi',
@@ -83,7 +112,7 @@ class Email
];
/**
* Undocumented function
* get one position from the regex check list
*
* @param int $type Which position in the regex list to get
* if not set or not valid get default pos 0
@@ -99,22 +128,48 @@ class Email
}
/**
* get the full check array
* this will be deprected at some point
* get the full check array, except position 0, but preserve keys
* Currently used to add per error level type from
* getEmailRegex to error reporting
* Might be deprecated at some point
*
* @return array
* @return array<mixed>
*/
public static function getEmailRegexCheck(): array
{
return self::$email_regex_check;
// return all but the first
return array_slice(
self::$email_regex_check,
1,
count(self::$email_regex_check) - 1,
true
);
}
/**
* Returns error message for email ergex error, or empty string if not set
*
* @param int $error
* @return array<string,string|int> Error message and regex
*/
public static function getEmailRegexErrorMessage(int $error): array
{
// return error message and regex
return [
'error' => $error,
'message' => self::$email_regex_check_message[$error] ?? '',
'regex' => self::$email_regex_check[$error] ?? '',
];
}
/**
* guesses the email type (mostly for mobile) from the domain
* if second is set to true, it will return short naming scheme (only provider)
* @param string $email email string
* @param bool $short default false, if true, returns only short type (pc instead of pc_html)
* @return string|bool email type, eg "pc", "docomo", etc, false for invalid short type
* @param string $email email string
* @param bool $short default false, if true,
* returns only short type (pc instead of pc_html)
* @return string|bool email type, eg "pc", "docomo", etc,
* false for invalid short type
*/
public static function getEmailType(string $email, bool $short = false)
{
@@ -155,6 +210,54 @@ class Email
return false;
}
}
/**
* simple email check with the basic email eregex
*
* @param string $email Email address, will be checkd as lower
* @return bool True if email is ok, or false if regex failed
*/
public static function checkEmail(string $email): bool
{
$email_regex = self::getEmailRegex();
if (!preg_match("/$email_regex/", strtolower($email))) {
return false;
}
return true;
}
/**
* Undocumented function
*
* @param string $email Email address, will be checkd as lower
* @param bool $error_code_only If this is set to true it will only return
* the error pos, instead of detailed array
* @return array<mixed> Errors as array with message and regex
*/
public static function checkEmailFull(string $email, bool $error_code_only = false): array
{
$errors = [];
foreach (self::$email_regex_check as $pos => $email_regex) {
$match = preg_match("/$email_regex/", strtolower($email));
// if the first does not fail, quit as ok
if ($pos == 0 && $match) {
break;
}
// else do error storage
// not that for 1, 6, 7 the regex is matching
if (
(!$match && in_array($pos, [0, 2, 3, 4, 5])) ||
($match && in_array($pos, [1, 6, 7]))
) {
if ($error_code_only === true) {
$errors[] = $pos;
} else {
$errors[] = self::getEmailRegexErrorMessage($pos);
}
}
}
return $errors;
}
}
// __END__

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1);
<?php
/*
* various file/file name functions
*/
declare(strict_types=1);
namespace CoreLibs\Check;
class File
@@ -26,14 +28,18 @@ class File
*/
public static function getLinesFromFile(string $file): int
{
if (is_file($file) &&
if (
is_file($file) &&
file_exists($file) &&
is_readable($file)
) {
$f = fopen($file, 'rb');
if (!is_resource($f)) {
return 0;
}
$lines = 0;
while (!feof($f)) {
$lines += substr_count(fread($f, 8192), "\n");
$lines += substr_count(fread($f, 8192) ?: '', "\n");
}
fclose($f);
} else {

View File

@@ -1,4 +1,4 @@
<?php declare(strict_types=1);
<?php
/*
* Converts a json string to array and stores error for later checking
@@ -6,10 +6,13 @@
* and self set json as is on error as array
*/
declare(strict_types=1);
namespace CoreLibs\Check;
class Jason
{
/** @var int */
private static $json_last_error;
/**
@@ -21,7 +24,7 @@ class Jason
* @param string|null $json a json string, or null data
* @param bool $override if set to true, then on json error
* set original value as array
* @return array returns an array from the json values
* @return array<mixed> returns an array from the json values
*/
public static function jsonConvertToArray(?string $json, bool $override = false): array
{

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1);
<?php
/*
* core password set, check and rehash check wrapper functions
*/
declare(strict_types=1);
namespace CoreLibs\Check;
class Password
@@ -33,8 +35,6 @@ class Password
} else {
return false;
}
// in case something strange, return false on default
return false;
}
/**
@@ -49,8 +49,6 @@ class Password
} else {
return false;
}
// in case of strange, force re-hash
return true;
}
}

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace CoreLibs\Check;
@@ -33,19 +35,15 @@ class PhpVersion
}
// set the php version id
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', phpversion());
$version = explode('.', phpversion() ?: '');
// creates something like 50107
define('PHP_VERSION_ID', (int)$version[0] * 10000 + (int)$version[1] * 100 + (int)$version[2]);
}
// check if matching for version
if ($min_version && !$max_version) {
if (PHP_VERSION_ID >= $min_version) {
return true;
}
} elseif ($min_version && $max_version) {
if (PHP_VERSION_ID >= $min_version && PHP_VERSION_ID <= $max_version) {
return true;
}
if (!$max_version && PHP_VERSION_ID >= $min_version) {
return true;
} elseif (PHP_VERSION_ID >= $min_version && PHP_VERSION_ID <= $max_version) {
return true;
}
// if no previous return, fail
return false;

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1);
<?php
/*
* html convert functions
*/
declare(strict_types=1);
namespace CoreLibs\Combined;
class ArrayHandler
@@ -11,11 +13,11 @@ class ArrayHandler
/**
* searches key = value in an array / array
* only returns the first one found
* @param string|int $needle needle (search for)
* @param array $haystack haystack (search in)
* @param string|null $key_lookin the key to look out for, default empty
* @return array array with the elements where the needle can be
* found in the haystack array
* @param string|int $needle needle (search for)
* @param array<mixed> $haystack haystack (search in)
* @param string|null $key_lookin the key to look out for, default empty
* @return array<mixed> array with the elements where the needle can be
* found in the haystack array
*/
public static function arraySearchRecursive($needle, array $haystack, ?string $key_lookin = null): array
{
@@ -23,28 +25,31 @@ class ArrayHandler
if (!is_array($haystack)) {
$haystack = [];
}
if ($key_lookin != null &&
!empty($key_lookin) &&
if (
$key_lookin != null &&
array_key_exists($key_lookin, $haystack) &&
$needle === $haystack[$key_lookin]
) {
$path[] = $key_lookin;
} else {
foreach ($haystack as $key => $val) {
if (is_scalar($val) &&
if (
is_scalar($val) &&
$val === $needle &&
empty($key_lookin)
) {
$path[] = $key;
break;
} elseif (is_scalar($val) &&
} elseif (
is_scalar($val) &&
!empty($key_lookin) &&
$key === $key_lookin &&
$val == $needle
) {
$path[] = $key;
break;
} elseif (is_array($val) &&
} elseif (
is_array($val) &&
$path = self::arraySearchRecursive(
$needle,
(array)$val,
@@ -62,11 +67,11 @@ class ArrayHandler
/**
* recursive array search function, which returns all found not only the first one
* @param string|int $needle needle (search for)
* @param array $haystack haystack (search in)
* @param string|int $key the key to look for in
* @param array|null $path recursive call for previous path
* @return ?array all array elements paths where the element was found
* @param string|int $needle needle (search for)
* @param array<mixed> $haystack haystack (search in)
* @param string|int $key the key to look for in
* @param array<mixed>|null $path recursive call for previous path
* @return array<mixed>|null all array elements paths where the element was found
*/
public static function arraySearchRecursiveAll($needle, array $haystack, $key, ?array $path = null): ?array
{
@@ -76,41 +81,40 @@ class ArrayHandler
'level' => 0,
'work' => []
];
}
// init sub sets if not set
if (!isset($path['level'])) {
$path['level'] = 0;
}
if (!isset($path['work'])) {
$path['work'] = [];
} else {
// init sub sets if not set
if (!isset($path['level'])) {
$path['level'] = 0;
}
if (!isset($path['work'])) {
$path['work'] = [];
}
}
// should not be needed because it would trigger a php mehtod error
if (!is_array($haystack)) {
$haystack = [];
}
// @phan HACK
$path['level'] = $path['level'] ?? 0;
// go through the array,
foreach ($haystack as $_key => $_value) {
if (is_scalar($_value) && $_value == $needle && !$key) {
// only value matches
$path['work'][$path['level']] = $_key;
$path['work'][$path['level'] ?? 0] = $_key;
$path['found'][] = $path['work'];
} elseif (is_scalar($_value) && $_value == $needle && $_key == $key) {
// key and value matches
$path['work'][$path['level']] = $_key;
$path['work'][$path['level'] ?? 0] = $_key;
$path['found'][] = $path['work'];
} elseif (is_array($_value)) {
// add position to working
$path['work'][$path['level']] = $_key;
$path['work'][$path['level'] ?? 0] = $_key;
// we will up a level
$path['level'] += 1;
// call recursive
$path = self::arraySearchRecursiveAll($needle, $_value, $key, $path);
}
}
// @phan HACK
// be 100% sure the array elements are set
$path['level'] = $path['level'] ?? 0;
$path['work'] = $path['work'] ?? [];
// cut all that is >= level
@@ -122,10 +126,10 @@ class ArrayHandler
/**
* array search simple. looks for key, value combination, if found, returns true
* @param array $array array(search in)
* @param string|int $key key (key to search in)
* @param string|int $value value (what to find)
* @return bool true on found, false on not found
* @param array<mixed> $array search in as array
* @param string|int $key key (key to search in)
* @param string|int $value value (what to find)
* @return bool true on found, false on not found
*/
public static function arraySearchSimple(array $array, $key, $value): bool
{
@@ -154,13 +158,13 @@ class ArrayHandler
* ... etc
* bool key flag: true: handle keys as string or int
* default false: all keys are string
* @return array|bool merged array
* @return array<mixed>|bool merged array
*/
public static function arrayMergeRecursive()
{
// croak on not enough arguemnts (we need at least two)
if (func_num_args() < 2) {
trigger_error(__FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
trigger_error(__FUNCTION__ . ' needs two or more array arguments', E_USER_WARNING);
return false;
}
// default key is not string
@@ -174,14 +178,14 @@ class ArrayHandler
}
// check that arrays count is at least two, else we don't have enough to do anything
if (count($arrays) < 2) {
trigger_error(__FUNCTION__.' needs two or more array arguments', E_USER_WARNING);
trigger_error(__FUNCTION__ . ' needs two or more array arguments', E_USER_WARNING);
return false;
}
$merged = [];
while ($arrays) {
$array = array_shift($arrays);
if (!is_array($array)) {
trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
trigger_error(__FUNCTION__ . ' encountered a non array argument', E_USER_WARNING);
return false;
}
if (!$array) {
@@ -209,9 +213,9 @@ class ArrayHandler
* array_diff only checks elements from A that are not in B, but not the
* other way around.
* Note that like array_diff this only checks first level values not keys
* @param array $a array to compare a
* @param array $b array to compare b
* @return array array with missing elements from a & b
* @param array<mixed> $a array to compare a
* @param array<mixed> $b array to compare b
* @return array<mixed> array with missing elements from a & b
*/
public static function arrayDiff(array $a, array $b): array
{
@@ -222,9 +226,9 @@ class ArrayHandler
/**
* search for the needle array elements in haystack and return the ones found as an array,
* is there nothing found, it returns FALSE (boolean)
* @param array $needle elements to search for
* @param array $haystack array where the $needle elements should be searched int
* @return array|bool either the found elements or false for nothing found or error
* @param array<mixed> $needle elements to search for
* @param array<mixed> $haystack array where the $needle elements should be searched int
* @return array<mixed>|bool either the found elements or false for nothing found or error
*/
public static function inArrayAny(array $needle, array $haystack)
{
@@ -249,19 +253,20 @@ class ArrayHandler
/**
* creates out of a normal db_return array an assoc array
* @param array $db_array return array from the database
* @param array<mixed> $db_array return array from the database
* @param string|int|bool $key key set, false for not set
* @param string|int|bool $value value set, false for not set
* @param bool $set_only flag to return all (default), or set only
* @return array associative array
* @return array<mixed> associative array
*/
public static function genAssocArray(array $db_array, $key, $value, bool $set_only = false): array
{
$ret_array = [];
// do this to only run count once
for ($i = 0, $iMax = count($db_array); $i < $iMax; $i ++) {
for ($i = 0, $iMax = count($db_array); $i < $iMax; $i++) {
// if no key then we make an order reference
if ($key !== false &&
if (
$key !== false &&
$value !== false &&
(($set_only && $db_array[$i][$value]) || (!$set_only))
) {
@@ -278,8 +283,8 @@ class ArrayHandler
/**
* converts multi dimensional array to a flat array
* does NOT preserve keys
* @param array $array ulti dimensionial array
* @return array flattened array
* @param array<mixed> $array ulti dimensionial array
* @return array<mixed> flattened array
*/
public static function flattenArray(array $array): array
{
@@ -295,8 +300,8 @@ class ArrayHandler
/**
* will loop through an array recursivly and write the array keys back
* @param array $array multidemnsional array to flatten
* @return array flattened keys array
* @param array<mixed> $array multidemnsional array to flatten
* @return array<mixed> flattened keys array
*/
public static function flattenArrayKey(array $array): array
{
@@ -313,9 +318,9 @@ class ArrayHandler
/**
* searches for key -> value in an array tree and writes the value one level up
* this will remove this leaf will all other values
* @param array $array array(nested)
* @param string|int $search key to find that has no sub leaf and will be pushed up
* @return array modified, flattened array
* @param array<mixed> $array nested array
* @param string|int $search key to find that has no sub leaf and will be pushed up
* @return array<mixed> modified, flattened array
*/
public static function arrayFlatForKey(array $array, $search): array
{

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1);
<?php
/*
* image thumbnail, rotate, etc
*/
declare(strict_types=1);
namespace CoreLibs\Combined;
class DateTime
@@ -21,7 +23,7 @@ class DateTime
list ($timestamp, $ms) = array_pad(explode('.', (string)round($timestamp, 4)), 2, null);
$string = date("Y-m-d H:i:s", (int)$timestamp);
if ($show_micro && $ms) {
$string .= ' '.$ms.'ms';
$string .= ' ' . $ms . 'ms';
}
return $string;
}
@@ -36,7 +38,7 @@ class DateTime
{
// check if the timestamp has any h/m/s/ms inside, if yes skip
if (!preg_match("/(h|m|s|ms)/", (string)$timestamp)) {
list($timestamp, $ms) = array_pad(explode('.', (string)round($timestamp, 4)), 2, null);
list($timestamp, $ms) = array_pad(explode('.', (string)round((float)$timestamp, 4)), 2, null);
// if negative remember
$negative = false;
if ((int)$timestamp < 0) {
@@ -50,12 +52,12 @@ class DateTime
if ($timestamp == 0) {
$time_string = '0s';
} else {
for ($i = 0, $iMax = count($timegroups); $i < $iMax; $i ++) {
for ($i = 0, $iMax = count($timegroups); $i < $iMax; $i++) {
$output = floor((float)$timestamp / $timegroups[$i]);
$timestamp = (float)$timestamp % $timegroups[$i];
// output has days|hours|min|sec
if ($output || $time_string) {
$time_string .= $output.$labels[$i].(($i + 1) != count($timegroups) ? ' ' : '');
$time_string .= $output . $labels[$i] . (($i + 1) != count($timegroups) ? ' ' : '');
}
}
}
@@ -63,20 +65,23 @@ class DateTime
if ($ms !== null) {
// if we have ms and it has leading zeros, remove them, but only if it is nut just 0
$ms = preg_replace("/^0+(\d+)$/", '${1}', $ms);
if (!is_string($ms) || empty($ms)) {
$ms = '0';
}
// add ms if there
if ($show_micro) {
$time_string .= ' '.(!$ms ? 0 : $ms).'ms';
$time_string .= ' ' . $ms . 'ms';
} elseif (!$time_string) {
$time_string .= (!$ms ? 0 : $ms).'ms';
$time_string .= $ms . 'ms';
}
}
if ($negative) {
$time_string = '-'.$time_string;
$time_string = '-' . $time_string;
}
} else {
$time_string = $timestamp;
}
return $time_string;
return (string)$time_string;
}
/**
@@ -88,7 +93,8 @@ class DateTime
public static function stringToTime($timestring)
{
$timestamp = 0;
if (preg_match("/(d|h|m|s|ms)/", $timestring)) {
if (preg_match("/(d|h|m|s|ms)/", (string)$timestring)) {
$timestring = (string)$timestring;
// pos for preg match read + multiply factor
$timegroups = [2 => 86400, 4 => 3600, 6 => 60, 8 => 1];
$matches = [];
@@ -108,7 +114,7 @@ class DateTime
}
}
if (isset($matches[10]) && is_numeric($matches[10])) {
$timestamp .= '.'.$matches[10];
$timestamp .= '.' . $matches[10];
}
if ($negative) {
$timestamp *= -1;
@@ -129,7 +135,11 @@ class DateTime
if (!$date) {
return false;
}
list ($year, $month, $day) = array_pad(preg_split("/[\/-]/", $date), 3, null);
list ($year, $month, $day) = array_pad(
preg_split("/[\/-]/", $date) ?: [],
3,
null
);
if (!$year || !$month || !$day) {
return false;
}
@@ -144,12 +154,16 @@ class DateTime
* @param string $datetime date (YYYY-MM-DD) + time (HH:MM:SS), SS can be dropped
* @return bool true if valid date, false if date not valid
*/
public static function checkDateTime($datetime): bool
public static function checkDateTime(string $datetime): bool
{
if (!$datetime) {
return false;
}
list ($year, $month, $day, $hour, $min, $sec) = array_pad(preg_split("/[\/\- :]/", $datetime), 6, null);
list ($year, $month, $day, $hour, $min, $sec) = array_pad(
preg_split("/[\/\- :]/", $datetime) ?: [],
6,
null
);
if (!$year || !$month || !$day) {
return false;
}
@@ -159,7 +173,8 @@ class DateTime
if (!is_numeric($hour) || !is_numeric($min)) {
return false;
}
if (($hour < 0 || $hour > 24) ||
if (
($hour < 0 || $hour > 24) ||
($min < 0 || $min > 60) ||
(is_numeric($sec) && ($sec < 0 || $sec > 60))
) {
@@ -187,20 +202,28 @@ class DateTime
}
// splits the data up with / or -
list ($start_year, $start_month, $start_day) = array_pad(preg_split('/[\/-]/', $start_date), 3, null);
list ($end_year, $end_month, $end_day) = array_pad(preg_split('/[\/-]/', $end_date), 3, null);
list ($start_year, $start_month, $start_day) = array_pad(
preg_split('/[\/-]/', $start_date) ?: [],
3,
null
);
list ($end_year, $end_month, $end_day) = array_pad(
preg_split('/[\/-]/', $end_date) ?: [],
3,
null
);
// check that month & day are two digits and then combine
foreach (array('start', 'end') as $prefix) {
foreach (array('month', 'day') as $date_part) {
$_date = $prefix.'_'.$date_part;
foreach (['start', 'end'] as $prefix) {
foreach (['month', 'day'] as $date_part) {
$_date = $prefix . '_' . $date_part;
if (isset($$_date) && $$_date < 10 && !preg_match("/^0/", $$_date)) {
$$_date = '0'.$$_date;
$$_date = '0' . $$_date;
}
}
$_date = $prefix.'_date';
$_date = $prefix . '_date';
$$_date = '';
foreach (array('year', 'month', 'day') as $date_part) {
$_sub_date = $prefix.'_'.$date_part;
foreach (['year', 'month', 'day'] as $date_part) {
$_sub_date = $prefix . '_' . $date_part;
$$_date .= $$_sub_date;
}
}
@@ -211,6 +234,8 @@ class DateTime
return 0;
} elseif ($start_date > $end_date) {
return 1;
} else {
return false;
}
}
@@ -239,6 +264,8 @@ class DateTime
return 0;
} elseif ($start_timestamp > $end_timestamp) {
return 1;
} else {
return false;
}
}
@@ -249,12 +276,12 @@ class DateTime
* @param string $start_date valid start date (y/m/d)
* @param string $end_date valid end date (y/m/d)
* @param bool $return_named return array type, false (default), true for named
* @return array 0/overall, 1/weekday, 2/weekend
* @return array<mixed> 0/overall, 1/weekday, 2/weekend
*/
public static function calcDaysInterval($start_date, $end_date, bool $return_named = false): array
{
// pos 0 all, pos 1 weekday, pos 2 weekend
$days = array();
$days = [];
$start = new \DateTime($start_date);
$end = new \DateTime($end_date);
// so we include the last day too, we need to add +1 second in the time
@@ -275,11 +302,11 @@ class DateTime
}
}
if ($return_named === true) {
return array(
return [
'overall' => $days[0],
'weekday' => $days[1],
'weekend' => $days[2]
);
];
} else {
return $days;
}

View File

@@ -1,17 +1,19 @@
<?php declare(strict_types=1);
<?php
/*
* image thumbnail, rotate, etc
*/
declare(strict_types=1);
namespace CoreLibs\Convert;
class Byte
{
// define byteFormat
const BYTE_FORMAT_NOSPACE = 1;
const BYTE_FORMAT_ADJUST = 2;
const BYTE_FORMAT_SI = 4;
public const BYTE_FORMAT_NOSPACE = 1;
public const BYTE_FORMAT_ADJUST = 2;
public const BYTE_FORMAT_SI = 4;
/**
* This function replaces the old byteStringFormat
@@ -62,10 +64,10 @@ class Byte
$abs_bytes = $bytes == PHP_INT_MIN ? PHP_INT_MAX : abs($bytes);
// smaller than unit is always B
if ($abs_bytes < $unit) {
return $bytes.'B';
return $bytes . 'B';
}
// labels in order of size [Y, Z]
$labels = array('', 'K', 'M', 'G', 'T', 'P', 'E');
$labels = ['', 'K', 'M', 'G', 'T', 'P', 'E'];
// exp position calculation
$exp = floor(log($abs_bytes, $unit));
// avoid printing out anything larger than max labels
@@ -75,13 +77,14 @@ class Byte
// deviation calculation
$dev = pow($unit, $exp) * ($unit - 0.05);
// shift the exp +1 for on the border units
if ($exp < 6 &&
if (
$exp < 6 &&
$abs_bytes > ($dev - (((int)$dev & 0xfff) == 0xd00 ? 52 : 0))
) {
$exp ++;
$exp++;
}
// label name, including leading space if flagged
$pre = ($space ? ' ' : '').($labels[$exp] ?? '>E').($si ? 'i' : '').'B';
$pre = ($space ? ' ' : '') . ($labels[$exp] ?? '>E') . ($si ? 'i' : '') . 'B';
$bytes_calc = $abs_bytes / pow($unit, $exp);
// if original is negative, reverse
if ($bytes < 0) {
@@ -90,7 +93,7 @@ class Byte
if ($adjust) {
return sprintf("%.2f%s", $bytes_calc, $pre);
} else {
return round($bytes_calc, 2).$pre;
return round($bytes_calc, 2) . $pre;
}
} else {
// if anything other return as string
@@ -120,7 +123,11 @@ class Byte
// all valid units
$valid_units_ = 'bkmgtpezy';
// detects up to exo bytes
preg_match("/([\d.,]*)\s?(eib|pib|tib|gib|mib|kib|eb|pb|tb|gb|mb|kb|e|p|t|g|m|k|b)$/i", strtolower($number), $matches);
preg_match(
"/([\d.,]*)\s?(eib|pib|tib|gib|mib|kib|eb|pb|tb|gb|mb|kb|e|p|t|g|m|k|b)$/i",
strtolower((string)$number),
$matches
);
if (isset($matches[1]) && isset($matches[2])) {
// remove all non valid characters from the number
$number = preg_replace('/[^0-9\.]/', '', $matches[1]);
@@ -129,7 +136,7 @@ class Byte
// convert any mb/gb/etc to single m/b
$unit = preg_replace('/[^bkmgtpezy]/i', '', $matches[2]);
if ($unit) {
$number = $number * pow($si ? 1000 : 1024, stripos($valid_units_, $unit[0]));
$number = $number * pow($si ? 1000 : 1024, stripos($valid_units_, $unit[0]) ?: 0);
}
// convert to INT to avoid +E output
$number = (int)round($number);

View File

@@ -1,4 +1,4 @@
<?php declare(strict_types=1);
<?php
/*
* Convert color spaces
@@ -10,21 +10,27 @@
* hsl to rgb
*/
declare(strict_types=1);
namespace CoreLibs\Convert;
class Colors
{
/**
* converts a hex RGB color to the int numbers
* @param string $hexStr RGB hexstring
* @param bool $returnAsString flag to return as string
* @param string $seperator string seperator: default: ","
* @return string|array|bool false on error or array with RGB or a string with the seperator
* @param string $hexStr RGB hexstring
* @param bool $returnAsString flag to return as string
* @param string $seperator string seperator: default: ","
* @return string|array<string,float|int>|bool false on error or array with RGB
* or a string with the seperator
*/
public static function hex2rgb(string $hexStr, bool $returnAsString = false, string $seperator = ',')
{
$hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
$rgbArray = array();
if (!is_string($hexStr)) {
return false;
}
$rgbArray = [];
if (strlen($hexStr) == 6) {
// If a proper hex code, convert using bitwise operation. No overhead... faster
$colorVal = hexdec($hexStr);
@@ -59,7 +65,7 @@ class Colors
if ($hex_prefix === true) {
$hex_color = '#';
}
foreach (array('red', 'green', 'blue') as $color) {
foreach (['red', 'green', 'blue'] as $color) {
// if not valid, set to gray
if ($$color < 0 || $$color > 255) {
$$color = 125;
@@ -74,15 +80,15 @@ class Colors
* converts RGB to HSB/V values
* returns:
* array with hue (0-360), sat (0-100%), brightness/value (0-100%)
* @param int $red red 0-255
* @param int $green green 0-255
* @param int $blue blue 0-255
* @return array Hue, Sat, Brightness/Value
* @param int $red red 0-255
* @param int $green green 0-255
* @param int $blue blue 0-255
* @return array<int|float> Hue, Sat, Brightness/Value
*/
public static function rgb2hsb(int $red, int $green, int $blue): array
{
// check that rgb is from 0 to 255
foreach (array('red', 'green', 'blue') as $c) {
foreach (['red', 'green', 'blue'] as $c) {
if ($$c < 0 || $$c > 255) {
$$c = 0;
}
@@ -94,7 +100,7 @@ class Colors
$HUE = 0;
if ($MAX == $MIN) {
return array(0, 0, round($MAX * 100));
return [0, 0, round($MAX * 100)];
}
if ($red == $MAX) {
$HUE = ($green - $blue) / ($MAX - $MIN);
@@ -108,19 +114,19 @@ class Colors
$HUE += 360;
}
return array(
return [
(int)round($HUE),
(int)round((($MAX - $MIN) / $MAX) * 100),
(int)round($MAX * 100)
);
];
}
/**
* converts HSB/V to RGB values RGB is full INT
* @param int $H hue 0-360
* @param int $S saturation 0-100 (int)
* @param int $V brightness/value 0-100 (int)
* @return array 0 red/1 green/2 blue array as 0-255
* @param int $H hue 0-360
* @param int $S saturation 0-100 (int)
* @param int $V brightness/value 0-100 (int)
* @return array<int> 0 red/1 green/2 blue array as 0-255
*/
public static function hsb2rgb(int $H, int $S, int $V): array
{
@@ -140,7 +146,7 @@ class Colors
$V /= 100;
if ($S == 0) {
return array($V * 255, $V * 255, $V * 255);
return [$V * 255, $V * 255, $V * 255];
}
$Hi = floor($H / 60);
@@ -186,26 +192,26 @@ class Colors
$blue = 0;
}
return array(
return [
(int)round($red * 255),
(int)round($green * 255),
(int)round($blue * 255)
);
];
}
/**
* converts a RGB (0-255) to HSL
* return:
* array with hue (0-360), saturation (0-100%) and luminance (0-100%)
* @param int $red red 0-255
* @param int $green green 0-255
* @param int $blue blue 0-255
* @return array hue/sat/luminance
* @param int $red red 0-255
* @param int $green green 0-255
* @param int $blue blue 0-255
* @return array<float> hue/sat/luminance
*/
public static function rgb2hsl(int $red, int $green, int $blue): array
{
// check that rgb is from 0 to 255
foreach (array('red', 'green', 'blue') as $c) {
foreach (['red', 'green', 'blue'] as $c) {
if ($$c < 0 || $$c > 255) {
$$c = 0;
}
@@ -251,7 +257,7 @@ class Colors
* @param int $hue hue: 0-360 (degrees)
* @param float $sat saturation: 0-100
* @param float $lum luminance: 0-100
* @return array red/blue/green 0-255 each
* @return array<int,float|int> red/blue/green 0-255 each
*/
public static function hsl2rgb(int $hue, float $sat, float $lum): array
{
@@ -270,7 +276,7 @@ class Colors
$lum /= 100;
// if saturation is 0
if ($sat == 0) {
return array($lum * 255, $lum * 255, $lum * 255);
return [$lum * 255, $lum * 255, $lum * 255];
} else {
$m2 = $lum < 0.5 ? $lum * ($sat + 1) : ($lum + $sat) - ($lum * $sat);
$m1 = $lum * 2 - $m2;
@@ -292,11 +298,11 @@ class Colors
return $m1;
};
return array(
return [
(int)round(255 * $hueue($hue + (1 / 3))),
(int)round(255 * $hueue($hue)),
(int)round(255 * $hueue($hue - (1 / 3)))
);
];
}
}
}

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1);
<?php
/*
* html convert functions
*/
declare(strict_types=1);
namespace CoreLibs\Convert;
class Html
@@ -16,7 +18,7 @@ class Html
public static function htmlent($string)
{
if (is_string($string)) {
return htmlentities($string, ENT_COMPAT|ENT_HTML401, 'UTF-8', false);
return htmlentities($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
} else {
return $string;
}
@@ -30,17 +32,17 @@ class Html
*/
public static function removeLB(string $string, string $replace = ' '): string
{
return str_replace(array("\r", "\n"), $replace, $string);
return str_replace(["\r", "\n"], $replace, $string);
}
/**
* returns 'checked' or 'selected' if okay
* $needle is a var, $haystack an array or a string
* **** THE RETURN: VALUE WILL CHANGE TO A DEFAULT NULL IF NOT FOUND ****
* @param array|string $haystack (search in) haystack can be an array or a string
* @param string $needle needle (search for)
* @param int $type type: 0: returns selected, 1, returns checked
* @return ?string returns checked or selected, else returns null
* @param array<mixed>|string $haystack (search in) haystack can be an array or a string
* @param string $needle needle (search for)
* @param int $type type: 0: returns selected, 1, returns checked
* @return ?string returns checked or selected, else returns null
*/
public static function checked($haystack, $needle, int $type = 0): ?string
{

Some files were not shown because too many files have changed in this diff Show More