From e80915cd5c44961e4ca9865ec38c9d5ce3a2c024 Mon Sep 17 00:00:00 2001 From: Clemens Schwaighofer Date: Tue, 8 Jun 2021 18:08:42 +0900 Subject: [PATCH] Further split out Class.Basic - Email/File/Hash class update - add random key, running time - get system calls - Debug classes for logging, running time, etc --- www/admin/class_test.array.php | 8 +- www/admin/class_test.byte.php | 5 - www/admin/class_test.colors.php | 21 +- www/admin/class_test.datetime.php | 4 - www/admin/class_test.db.php | 2 - www/admin/class_test.debug.php | 87 +++++ www/admin/class_test.email.php | 21 +- www/admin/class_test.encoding.php | 2 - www/admin/class_test.file.php | 4 - www/admin/class_test.hash.php | 9 - www/admin/class_test.json.php | 23 +- www/admin/class_test.mime.php | 1 - www/admin/class_test.php | 15 +- www/admin/class_test.randomkey.php | 55 ++++ www/admin/class_test.runningtime.php | 63 ++++ www/admin/class_test.system.php | 48 +++ www/admin/class_test.token.php | 2 - www/admin/class_test.uids.php | 2 - www/lib/CoreLibs/Basic.php | 437 ++++++------------------- www/lib/CoreLibs/Check/Email.php | 169 ++++++---- www/lib/CoreLibs/Check/File.php | 2 +- www/lib/CoreLibs/Create/Hash.php | 10 + www/lib/CoreLibs/Create/RandomKey.php | 106 ++++++ www/lib/CoreLibs/Debug/FileWriter.php | 61 ++++ www/lib/CoreLibs/Debug/Logging.php | 420 ++++++++++++++++++++++++ www/lib/CoreLibs/Debug/RunningTime.php | 119 +++++++ www/lib/CoreLibs/Debug/Support.php | 60 ++++ www/lib/CoreLibs/Get/System.php | 85 +++++ 28 files changed, 1358 insertions(+), 483 deletions(-) create mode 100644 www/admin/class_test.debug.php create mode 100644 www/admin/class_test.randomkey.php create mode 100644 www/admin/class_test.runningtime.php create mode 100644 www/admin/class_test.system.php create mode 100644 www/lib/CoreLibs/Create/RandomKey.php create mode 100644 www/lib/CoreLibs/Debug/FileWriter.php create mode 100644 www/lib/CoreLibs/Debug/Logging.php create mode 100644 www/lib/CoreLibs/Debug/RunningTime.php create mode 100644 www/lib/CoreLibs/Debug/Support.php create mode 100644 www/lib/CoreLibs/Get/System.php diff --git a/www/admin/class_test.array.php b/www/admin/class_test.array.php index 57ae270c..0f9f7d8c 100644 --- a/www/admin/class_test.array.php +++ b/www/admin/class_test.array.php @@ -23,16 +23,14 @@ if (!defined('SET_SESSION_NAME')) { define('SET_SESSION_NAME', EDIT_SESSION_NAME); } // define log file id -$LOG_FILE_ID = 'classTest-datetime'; +$LOG_FILE_ID = 'classTest-array'; ob_end_flush(); use CoreLibs\Combined\ArrayHandler; $basic = new CoreLibs\Basic(); -$_array= new CoreLibs\Combined\ArrayHandler(); -$array_class = 'CoreLibs\Combination\ArrayHandler'; - -// define a list of from to color sets for conversion test +// $_array= new CoreLibs\Combined\ArrayHandler(); +// $array_class = 'CoreLibs\Combination\ArrayHandler'; print "TEST CLASS: ARRAY HANDLER"; print ""; diff --git a/www/admin/class_test.byte.php b/www/admin/class_test.byte.php index cecb7c92..b36e5005 100644 --- a/www/admin/class_test.byte.php +++ b/www/admin/class_test.byte.php @@ -29,11 +29,8 @@ ob_end_flush(); use CoreLibs\Convert\Byte; $basic = new CoreLibs\Basic(); -$_byte = new CoreLibs\Convert\Byte(); $byte_class = 'CoreLibs\Convert\Byte'; -// define a list of from to color sets for conversion test - print "TEST CLASS: BYTE CONVERT"; print ""; print '
Class Test Master
'; @@ -41,8 +38,6 @@ print '
Class Test Master
'; // class $byte = 254779258; $string = '242.98 MB'; -print "BYTE TO: $byte: ".$_byte->humanReadableByteFormat($byte)."
"; -print "BYTE FROM: $string: ".$_byte->stringByteFormat($string)."
"; // static print "S::BYTE TO: $byte: ".$byte_class::humanReadableByteFormat($byte)."
"; print "S::BYTE FROM: $string: ".$byte_class::stringByteFormat($string)."
"; diff --git a/www/admin/class_test.colors.php b/www/admin/class_test.colors.php index 73dc31ee..8d99995e 100644 --- a/www/admin/class_test.colors.php +++ b/www/admin/class_test.colors.php @@ -26,16 +26,17 @@ if (!defined('SET_SESSION_NAME')) { $LOG_FILE_ID = 'classTest-colors'; ob_end_flush(); -$basic = new CoreLibs\Basic(); -$color = new CoreLibs\Convert\Colors(); -$color_class = 'CoreLibs\Convert\Colors'; +use CoreLibs\Convert\Colors; -// define a list of from to color sets for conversion test +$basic = new CoreLibs\Basic(); +$color_class = 'CoreLibs\Convert\Colors'; print "TEST CLASS: COLORS"; print ""; print '
Class Test Master
'; +// 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)."
"; print "\$C::S/COLOR invalid rgb->hex (gary 125): -1, -1, -1: ".$color_class::rgb2hex(-1, -1, -1)."
"; @@ -44,15 +45,15 @@ $rgb = [10, 20, 30]; $hex = '#0a141e'; $hsb = [210, 67, 12]; $hsl = [210, 50, 7.8]; -print "C/COLOR rgb->hex: $rgb[0], $rgb[1], $rgb[2]: ".$color->rgb2hex($rgb[0], $rgb[1], $rgb[2])."
"; -print "C/COLOR hex->rgb: $hex: ".$basic->printAr($color->hex2rgb($hex))."
"; +print "S::COLOR rgb->hex: $rgb[0], $rgb[1], $rgb[2]: ".Colors::rgb2hex($rgb[0], $rgb[1], $rgb[2])."
"; +print "S::COLOR hex->rgb: $hex: ".$basic->printAr(Colors::hex2rgb($hex))."
"; print "C::S/COLOR rgb->hext: $hex: ".$basic->printAr(CoreLibs\Convert\Colors::hex2rgb($hex))."
"; // C(to hsb/hsl) -print "C/COLOR rgb->hsb: $rgb[0], $rgb[1], $rgb[2]: ".$basic->printAr($color->rgb2hsb($rgb[0], $rgb[1], $rgb[2]))."
"; -print "C/COLOR rgb->hsl: $rgb[0], $rgb[1], $rgb[2]: ".$basic->printAr($color->rgb2hsl($rgb[0], $rgb[1], $rgb[2]))."
"; +print "S::COLOR rgb->hsb: $rgb[0], $rgb[1], $rgb[2]: ".$basic->printAr(Colors::rgb2hsb($rgb[0], $rgb[1], $rgb[2]))."
"; +print "S::COLOR rgb->hsl: $rgb[0], $rgb[1], $rgb[2]: ".$basic->printAr(Colors::rgb2hsl($rgb[0], $rgb[1], $rgb[2]))."
"; // D(from hsb/hsl) Note that param 2 + 3 is always 0-100 divided -print "C/COLOR hsb->rgb: $hsb[0], $hsb[1], $hsb[2]: ".$basic->printAr($color->hsb2rgb($hsb[0], $hsb[1], $hsb[2]))."
"; -print "C/COLOR hsl->rgb: $hsl[0], $hsl[1], $hsl[2]: ".$basic->printAr($color->hsl2rgb($hsl[0], $hsl[1], $hsl[2]))."
"; +print "S::COLOR hsb->rgb: $hsb[0], $hsb[1], $hsb[2]: ".$basic->printAr(Colors::hsb2rgb($hsb[0], $hsb[1], $hsb[2]))."
"; +print "S::COLOR hsl->rgb: $hsl[0], $hsl[1], $hsl[2]: ".$basic->printAr(Colors::hsl2rgb($hsl[0], $hsl[1], $hsl[2]))."
"; // TODO: run compare check input must match output diff --git a/www/admin/class_test.datetime.php b/www/admin/class_test.datetime.php index 363d1bfd..f88481aa 100644 --- a/www/admin/class_test.datetime.php +++ b/www/admin/class_test.datetime.php @@ -29,18 +29,14 @@ ob_end_flush(); use CoreLibs\Combined\DateTime; $basic = new CoreLibs\Basic(); -$_datetime = new CoreLibs\Combined\DateTime(); $datetime_class = 'CoreLibs\Combination\DateTime'; -// define a list of from to color sets for conversion test - print "TEST CLASS: DATE/TIME"; print ""; print '
Class Test Master
'; // class $timestamp = 1622788315.123456; -print "C->DATESTRINGFORMAT(sm:0): $timestamp: ".$_datetime->dateStringFormat($timestamp)."
"; // static print "S::DATESTRINGFORMAT(sm:0): $timestamp: ".$datetime_class::dateStringFormat($timestamp)."
"; diff --git a/www/admin/class_test.db.php b/www/admin/class_test.db.php index 4e0175d9..5d0cc4d1 100644 --- a/www/admin/class_test.db.php +++ b/www/admin/class_test.db.php @@ -28,8 +28,6 @@ ob_end_flush(); $basic = new CoreLibs\Admin\Backend(DB_CONFIG); -// define a list of from to color sets for conversion test - print "TEST CLASS: DB"; print ""; print '
Class Test Master
'; diff --git a/www/admin/class_test.debug.php b/www/admin/class_test.debug.php new file mode 100644 index 00000000..7b04787d --- /dev/null +++ b/www/admin/class_test.debug.php @@ -0,0 +1,87 @@ +TEST CLASS: DEBUG"; +print ""; +print '
Class Test Master
'; + +function test() +{ + return DebugSupport::getCallerMethod(1); +} + +print "S::GETCALLERMETHOD: ".DebugSupport::getCallerMethod(0)."
"; +print "S::GETCALLERMETHOD: ".test()."
"; +print "S::PRINTAR: ".DebugSupport::printAr(['Foo', 'Bar'])."
"; +print "V-S::PRINTAR: ".$debug_support_class::printAr(['Foo', 'Bar'])."
"; + +// debug +print "C->DEBUG: ".$debug->debug('CLASS-TEST-DEBUG', 'Class Test Debug')."
"; +print "C->PRINTERRORMSG:
".$debug->printErrorMsg()."
"; + +class TestL +{ + public $log; + public function __construct() + { + $this->log = new CoreLibs\Debug\Logging(); + } + public function test() + { + $this->log->debug('TESTL', 'Logging in class testL'); + print "IN TestL->test:
".$this->log->printErrorMsg()."
"; + return true; + } +} +$tl = new TestL(); +print "CLASS SUB: DEBUG: ".$tl->test()."
"; + +// fdebug +print "S::FSETFILENAME: ".FileWriter::fsetFilename('class_test_debug_file.log')."
"; +print "S::FDEBUG: ".FileWriter::fdebug('CLASS TEST DEBUG FILE: '.date('Y-m-d H:i:s'))."
"; + +// error message +// future DEPRECATED +$basic->debug('BASIC CLASS', 'Debug test'); +print "BASIC:
".$basic->printErrorMsg(); + +print ""; + +// __END__ diff --git a/www/admin/class_test.email.php b/www/admin/class_test.email.php index ffe06c68..d0f54c97 100644 --- a/www/admin/class_test.email.php +++ b/www/admin/class_test.email.php @@ -26,27 +26,28 @@ if (!defined('SET_SESSION_NAME')) { $LOG_FILE_ID = 'classTest-email'; ob_end_flush(); -$basic = new CoreLibs\Basic(); -$_email = new CoreLibs\Check\Email(); -$email_class = 'CoreLibs\Check\Email'; +use CoreLibs\Check\Email; -// define a list of from to color sets for conversion test +$basic = new CoreLibs\Basic(); print "TEST CLASS: HTML/ELEMENTS"; print ""; print '
Class Test Master
'; +// regex get +print "S::GETEMAILREGEX(0): ".Email::getEmailRegex(0)."
"; +print "S::GETEMAILREGEX(2): ".Email::getEmailRegex(2)."
"; +print "S::GETEMAILREGEX(7): ".Email::getEmailRegex(7)."
"; +print "S::GETEMAILREGEX(8 invalid): ".Email::getEmailRegex(8)."
"; +print "S::GETEMAILREGEXCHECK: ".$basic->printAr(Email::getEmailRegexCheck())."
"; + $email = [ 'foo@bar.org', 'foo@i.softbank.ne.jp' ]; foreach ($email as $s_email) { - print "EMAIL: $s_email: ".$_email->getEmailType($s_email)."
"; - print "EMAIL SHORT: $s_email: ".$_email->getEmailType($s_email, true)."
"; -} -foreach ($email as $s_email) { - print "S-EMAIL: $s_email: ".$email_class::getEmailType($s_email)."
"; - print "S-EMAIL SHORT: $s_email: ".$email_class::getEmailType($s_email, true)."
"; + print "S::EMAIL: $s_email: ".Email::getEmailType($s_email)."
"; + print "S::EMAIL SHORT: $s_email: ".Email::getEmailType($s_email, true)."
"; } // DEPRECATED /* foreach ($email as $s_email) { diff --git a/www/admin/class_test.encoding.php b/www/admin/class_test.encoding.php index b0119f73..cbcbf160 100644 --- a/www/admin/class_test.encoding.php +++ b/www/admin/class_test.encoding.php @@ -32,8 +32,6 @@ $basic = new CoreLibs\Basic(); $_encoding = new CoreLibs\Language\Encoding(); $encoding_class = 'CoreLibs\Language\Encoding'; -// define a list of from to color sets for conversion test - print "TEST CLASS: ENCODING"; print ""; print '
Class Test Master
'; diff --git a/www/admin/class_test.file.php b/www/admin/class_test.file.php index 7a2702e1..b643597e 100644 --- a/www/admin/class_test.file.php +++ b/www/admin/class_test.file.php @@ -29,10 +29,6 @@ ob_end_flush(); use CoreLibs\Check\File; $basic = new CoreLibs\Basic(); -$_array= new CoreLibs\Check\File(); -$array_class = 'CoreLibs\Check\File'; - -// define a list of from to color sets for conversion test print "TEST CLASS: FILE"; print ""; diff --git a/www/admin/class_test.hash.php b/www/admin/class_test.hash.php index 865ae1c6..420bc056 100644 --- a/www/admin/class_test.hash.php +++ b/www/admin/class_test.hash.php @@ -29,7 +29,6 @@ ob_end_flush(); use CoreLibs\Create\Hash; $basic = new CoreLibs\Basic(); -$_hash = new CoreLibs\Create\Hash(); $hash_class = 'CoreLibs\Create\Hash'; // define a list of from to color sets for conversion test @@ -39,14 +38,6 @@ print ""; print '
Class Test Master
'; $to_crc = 'Some text block'; -// class -print "__CRC32B: $to_crc: ".$_hash->__crc32b($to_crc)."
"; -print "__SHA1SHORT(off): $to_crc: ".$_hash->__sha1short($to_crc)."
"; -print "__SHA1SHORT(on): $to_crc: ".$_hash->__sha1short($to_crc, true)."
"; -print "__hash(d): $to_crc: ".$_hash->__hash($to_crc)."
"; -foreach (['adler32', 'fnv132', 'fnv1a32', 'joaat'] as $__hash_c) { - print "__hash($__hash_c): $to_crc: ".$_hash->__hash($to_crc, $__hash_c)."
"; -} // static print "S::__CRC32B: $to_crc: ".$hash_class::__crc32b($to_crc)."
"; print "S::__SHA1SHORT(off): $to_crc: ".$hash_class::__sha1short($to_crc)."
"; diff --git a/www/admin/class_test.json.php b/www/admin/class_test.json.php index 56fa784e..1510bcd3 100644 --- a/www/admin/class_test.json.php +++ b/www/admin/class_test.json.php @@ -26,8 +26,9 @@ if (!defined('SET_SESSION_NAME')) { $LOG_FILE_ID = 'classTest-json'; ob_end_flush(); +use CoreLibs\Check\Jason; + $basic = new CoreLibs\Basic(); -$_json = new CoreLibs\Check\Jason(); $json_class = 'CoreLibs\Check\Jason'; // define a list of from to color sets for conversion test @@ -37,25 +38,25 @@ print ""; print '
Class Test Master
'; $json = '{"foo": "bar"}'; -$output = $_json->jsonConvertToArray($json); -print "JSON: $json: ".$basic->printAr($output)."
"; -print "JSON ERROR: ".$_json->jsonGetLastError().": ".$_json->jsonGetLastError(true)."
"; +$output = Jason::jsonConvertToArray($json); +print "S::JSON: $json: ".$basic->printAr($output)."
"; +print "S::JSON ERROR: ".Jason::jsonGetLastError().": ".Jason::jsonGetLastError(true)."
"; $json = '["f: {b"""ar}]'; -$output = $_json->jsonConvertToArray($json); -print "E-JSON: $json: ".$basic->printAr($output)."
"; -print "E-JSON ERROR: ".$_json->jsonGetLastError().": ".$_json->jsonGetLastError(true)."
"; +$output = Jason::jsonConvertToArray($json); +print "S::E-JSON: $json: ".$basic->printAr($output)."
"; +print "S::E-JSON ERROR: ".Jason::jsonGetLastError().": ".Jason::jsonGetLastError(true)."
"; // direct $json = '{"direct": "static function call"}'; $output = $json_class::jsonConvertToArray($json); -print "S::JSON: $json: ".$basic->printAr($output)."
"; -print "S::JSON ERROR: ".$json_class::jsonGetLastError().": ".$json_class::jsonGetLastError(true)."
"; +print "J/S::JSON: $json: ".$basic->printAr($output)."
"; +print "J/S::JSON ERROR: ".$json_class::jsonGetLastError().": ".$json_class::jsonGetLastError(true)."
"; $json = '["f: {b"""ar}]'; $output = $json_class::jsonConvertToArray($json); -print "S::E-JSON: $json: ".$basic->printAr($output)."
"; -print "S::E-JSON ERROR: ".$json_class::jsonGetLastError().": ".$json_class::jsonGetLastError(true)."
"; +print "J/S::E-JSON: $json: ".$basic->printAr($output)."
"; +print "J/S::E-JSON ERROR: ".$json_class::jsonGetLastError().": ".$json_class::jsonGetLastError(true)."
"; // DEPRECATE TEST /* $json = '["f: {b"""ar}]'; diff --git a/www/admin/class_test.mime.php b/www/admin/class_test.mime.php index e136d2a4..ef432395 100644 --- a/www/admin/class_test.mime.php +++ b/www/admin/class_test.mime.php @@ -29,7 +29,6 @@ ob_end_flush(); $basic = new CoreLibs\Basic(); $_mime = new CoreLibs\Convert\MimeAppName(); - print "TEST CLASS: MIME"; print ""; print '
Class Test Master
'; diff --git a/www/admin/class_test.php b/www/admin/class_test.php index 40ce39e3..69b41e25 100644 --- a/www/admin/class_test.php +++ b/www/admin/class_test.php @@ -52,16 +52,10 @@ print '
Class Test: BYTE CONVERT
'; print '
Class Test: DATE/TIME
'; print '
Class Test: ARRAY HANDLER
'; print '
Class Test: FILE
'; - -$basic->hrRunningTime(); -$basic->runningTime(); -echo "RANDOM KEY [50]: ".$basic->randomKeyGen(50)."
"; -echo "TIMED [hr]: ".$basic->hrRunningTime()."
"; -echo "TIMED [def]: ".$basic->runningTime()."
"; -echo "TIMED [string]: ".$basic->runningtime_string."
"; -$basic->hrRunningTime(); -echo "RANDOM KEY [default]: ".$basic->randomKeyGen()."
"; -echo "TIMED [hr]: ".$basic->hrRunningTime()."
"; +print '
Class Test: RANDOM KEY
'; +print '
Class Test: SYSTEM
'; +print '
Class Test: RUNNING TIME
'; +print '
Class Test: DEBUG
'; // set + check edit access id $edit_access_id = 3; @@ -95,7 +89,6 @@ print "DEBUG OUT ALL: ".$basic->debug_output_all."
"; print "ECHO OUT ALL: ".$basic->echo_output_all."
"; print "PRINT OUT ALL: ".$basic->print_output_all."
"; -print "CALLER BACKTRACE: ".$basic->getCallerMethod()."
"; $basic->debug('SOME MARK', 'Some error output'); print "EDIT ACCESS ID: ".$basic->edit_access_id."
"; diff --git a/www/admin/class_test.randomkey.php b/www/admin/class_test.randomkey.php new file mode 100644 index 00000000..332167ca --- /dev/null +++ b/www/admin/class_test.randomkey.php @@ -0,0 +1,55 @@ +TEST CLASS: RANDOM KEY"; +print ""; +print '
Class Test Master
'; + +$key_length = 10; +$key_length_b = 5; +print "S::RANDOMKEYGEN(auto): ".RandomKey::randomKeyGen()."
"; +print "S::SETRANDOMKEYLENGTH($key_length): ".RandomKey::setRandomKeyLength($key_length)."
"; +print "S::RANDOMKEYGEN($key_length): ".RandomKey::randomKeyGen()."
"; +print "S::RANDOMKEYGEN($key_length_b): ".RandomKey::randomKeyGen($key_length_b)."
"; +print "S::RANDOMKEYGEN($key_length): ".RandomKey::randomKeyGen()."
"; +$_array= new CoreLibs\Create\RandomKey(); +print "C->RANDOMKEYGEN(auto): ".$_array->randomKeyGen()."
"; +// DEPRECATED +// print "D\RANDOMKEYGEN(auto): ".$basic->randomKeyGen()."
"; + +// error message +print $basic->printErrorMsg(); + +print ""; + +// __END__ diff --git a/www/admin/class_test.runningtime.php b/www/admin/class_test.runningtime.php new file mode 100644 index 00000000..d17bec7b --- /dev/null +++ b/www/admin/class_test.runningtime.php @@ -0,0 +1,63 @@ +TEST CLASS: RUNNING IMTE"; +print ""; +print '
Class Test Master
'; + +RunningTime::hrRunningTime(); +RunningTime::runningTime(); +echo "RANDOM KEY [50]: ".\CoreLibs\Create\RandomKey::randomKeyGen(50)."
"; +echo "TIMED [hr]: ".RunningTime::hrRunningTime()."
"; +echo "TIMED [def]: ".RunningTime::runningTime()."
"; +echo "TIMED [string]: ".RunningTime::runningTimeString()."
"; +RunningTime::hrRunningTime(); +echo "RANDOM KEY [default]: ".\CoreLibs\Create\RandomKey::randomKeyGen()."
"; +echo "TIMED [hr]: ".RunningTime::hrRunningTime()."
"; + +// DEPRECATED +/* $basic->hrRunningTime(); +$basic->runningTime(); +echo "RANDOM KEY [50]: ".$basic->randomKeyGen(50)."
"; +echo "TIMED [hr]: ".$basic->hrRunningTime()."
"; +echo "TIMED [def]: ".$basic->runningTime()."
"; +echo "TIMED [string]: ".$basic->runningtime_string."
"; +$basic->hrRunningTime(); +echo "RANDOM KEY [default]: ".$basic->randomKeyGen()."
"; +echo "TIMED [hr]: ".$basic->hrRunningTime()."
"; */ + +// error message +print $basic->printErrorMsg(); + +print ""; + +// __END__ diff --git a/www/admin/class_test.system.php b/www/admin/class_test.system.php new file mode 100644 index 00000000..113ea626 --- /dev/null +++ b/www/admin/class_test.system.php @@ -0,0 +1,48 @@ +TEST CLASS: SYSTEM"; +print ""; +print '
Class Test Master
'; + +print "GETHOSTNAME: ".$basic->printAr(System::getHostName())."
"; +print "GETPAGENAME(0): ".System::getPageName()."
"; +print "GETPAGENAME(1): ".System::getPageName(1)."
"; +print "GETPAGENAME(2): ".System::getPageName(2)."
"; +// seting errro codes file upload +print "FILEUPLOADERRORMESSAGE(): ".System::fileUploadErrorMessage(-1)."
"; +print "FILEUPLOADERRORMESSAGE(UPLOAD_ERR_CANT_WRITE): ".System::fileUploadErrorMessage(UPLOAD_ERR_CANT_WRITE)."
"; + +// error message +print $basic->printErrorMsg(); + +print ""; diff --git a/www/admin/class_test.token.php b/www/admin/class_test.token.php index ca7a8a3a..a240a9f4 100644 --- a/www/admin/class_test.token.php +++ b/www/admin/class_test.token.php @@ -30,8 +30,6 @@ $basic = new CoreLibs\Basic(); $_token = new CoreLibs\Output\Form\Token(); $token_class = 'CoreLibs\Output\Form\Token'; -// define a list of from to color sets for conversion test - print "TEST CLASS: FORM TOKEN"; print ""; print '
Class Test Master
'; diff --git a/www/admin/class_test.uids.php b/www/admin/class_test.uids.php index a35f57ee..86af392f 100644 --- a/www/admin/class_test.uids.php +++ b/www/admin/class_test.uids.php @@ -30,8 +30,6 @@ $basic = new CoreLibs\Basic(); $_uids = new CoreLibs\Create\Uids(); $uids_class = 'CoreLibs\Create\Uids'; -// define a list of from to color sets for conversion test - print "TEST CLASS: UIDS"; print ""; print '
Class Test Master
'; diff --git a/www/lib/CoreLibs/Basic.php b/www/lib/CoreLibs/Basic.php index 4d78ed45..2b986589 100644 --- a/www/lib/CoreLibs/Basic.php +++ b/www/lib/CoreLibs/Basic.php @@ -2,66 +2,16 @@ /********************************************************************* * AUTHOR: Clemens Schwaighofer * CREATED: 2003/03/24 -* VERSION: 2.0.0 +* VERSION: 5.0.0 * RELEASED LICENSE: GNU GPL 3 * SHORT DESCRIPTION: +* 2021/6/7, transfer all methods in this class to their own classes +* so we can use them independent without always using the full class * 2018/3/23, the whole class system is transformed to namespaces * also all internal class calls are converted to camel case * * basic class start class for ALL clases, holds basic vars, infos, methods, etc * -* PUBLIC VARIABLES -* -* These are if there is any debug to print out at all at the end -* debug_output_all - general yes no -* It's recommended to use the method "debug_for" to turn on of the array vars -* debug_output - turn on for one level (Array) -* debug_output_not - turn off for one level (array) -* -* Print out the debug at thend of the html -* echo_output_all -* echo_output -* echo_output_not -* -* Write debug to file -* print_output_all -* print_output -* print_output_not -* -* PRIVATE VARIABLES -* error_msg -> array that holds all the error messages, should not be written from outside, use debug method -* error_id -* error_string -* -* PUBLIC METHODS -* debug -> calls with "level", "string" and flag to turn off (0) the newline at the end -* debugFor -> sets debug on/off for a type (error, echo, print) for a certain level -* printErrorMsg -> prints out the error message, optional parameter is a header prefix -* fdebug -> prints line directly to debug_file.log in tmp -* -* printTime -> prints time + microtime, optional flag to turn off (0) microtime printout -* info -> info about that class -* runningTime -> prints out the time of start/end (automatically called on created and error printout -* checked -> returnes checked or selected for var & array -* magicLinks -> parses text and makes out of links -* getPageName -> get the filename of the current page -* arraySearchRecursive -> search for a value/key Combined in an array of arrays -* byteStringFormat -> format bytes into KB, MB, GB, ... -* timeStringFormat -> format a timestamp (seconds) into days, months, ... also with ms -* stringToTime -> reverste a TimeStringFormat to a timestamp -* genAssocArray -> generactes a new associativ array from an existing array -* checkDate -> checks if a date is valid -* compareDate -> compares two dates. -1 if the first is smaller, 0 if they are equal, 1 if the first is bigger -* compareDateTime -> compares two dates with time. -1 if the first is smaller, 0 if they are equal, 1 if the first is bigger -* __crc32b -> behaves like the hash("crc32b") in php < 5.2.8. this function will flip the hash like it was (wrong) -* before if a new php version is found -* crypt* -> encrypt and decrypt login string data, used by Login class -* setFormToken/validateFormToken -> form protection with token -* -* PRIVATE METHODS -* fdebug_fp -> opens and closes file, called from fdebug method -* write_error_msg -> writes error msg to file if requested -* * HISTORY: * 2010/12/24 (cs) add crypt classes with auto detect what crypt we can use, add php version check class * 2008/08/07 (cs) fixed strange DEBUG_ALL on off behavour. data was written even thought DBEUG_ALL was off. now no debug logging is done at all if DEBUG_ALL is off @@ -132,50 +82,25 @@ class Basic public $log_per_class = false; // set, will split log per class public $log_per_page = false; // set, will split log per called file public $log_per_run = false; // create a new log file per run (time stamp + unique ID) - // run time messurements - private $starttime; // start time if time debug is used - private $endtime; // end time if time debug is used - public $runningtime_string; // the running time as a string with info text - private $hr_starttime; // start time - private $hr_endtime; // end time - private $hr_runtime = 0; // run time // script running time private $script_starttime; // email valid checks - public $email_regex_check = array(); + public $email_regex_check = []; public $email_regex; // regex var for email check - public $keitai_email_regex; // regex var for email check // data path for files - public $data_path = array(); - - // error char for the char conver - // DEPRECATED - /** @internal */ - /** @deprecated */ - private $mbErrorChar; + public $data_path = []; // session name private $session_name = ''; private $session_id = ''; - // key generation - private $key_range = array(); - private $one_key_length; - private $key_length; - private $max_key_length = 256; // max allowed length // form token (used for form validation) // private $form_token = ''; // ajax flag protected $ajax_page_flag = false; - // [DEPRECATED] holds mime class, will be removed - protected $mime; - - // last json error - private $json_last_error; - /** * main Basic constructor to init and check base settings */ @@ -210,8 +135,9 @@ class Basic $this->ajax_page_flag = isset($GLOBALS['AJAX_PAGE']) && $GLOBALS['AJAX_PAGE'] ? true : false; // set the page name - $this->page_name = $this->getPageName(); - $this->host_name = $this->getHostName(); + $this->page_name = \CoreLibs\Get\System::getPageName(); + // set host name + list($this->host_name , $this->host_port) = \CoreLibs\Get\System::getHostName(); // init the log file id // * GLOBALS // * CONSTANT @@ -223,14 +149,14 @@ class Basic } // set the paths matching to the valid file types - $this->data_path = array( + $this->data_path = [ 'P' => PICTURES, 'F' => FLASH, 'V' => VIDEOS, 'D' => DOCUMENTS, 'A' => PDFS, 'B' => BINARIES - ); + ]; // if given via parameters, only for all $this->debug_output_all = false; @@ -287,17 +213,11 @@ class Basic } // set the regex for checking emails - $this->email_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}$"; + /** @deprecated */ + $this->email_regex = \CoreLibs\Check\Email::getEmailRegex(); // this is for error check parts in where the email regex failed - $this->email_regex_check = array( - 1 => "@(.*)@(.*)", // double @ - 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 - ); + /** @deprecated */ + $this->email_regex_check = \CoreLibs\Check\Email::getEmailRegexCheck(); // initial the session if there is no session running already if (!session_id()) { @@ -319,15 +239,6 @@ class Basic // set internal session id, we can use that later for protection check $this->session_id = session_id(); } - - // new better password init - // $this->passwordInit(); - - // key generation init - $this->initRandomKeyData(); - - // [DEPRECATED] init mime apps - $this->mime = new \CoreLibs\Convert\MimeAppName(); } // METHOD: __destruct @@ -364,6 +275,9 @@ class Basic // ****** DEBUG/ERROR FUNCTIONS ****** + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Debug\RunningTime + /** * for messure run time between two calls for this method * uses the hrtime() for running time @@ -374,47 +288,12 @@ class Basic * default is milliseconds * @param string $out_time set return time adjustment calculation * @return float running time without out_time suffix + * @deprecated Use \CoreLibs\Debug\RunningTime::hrRunningTime() instead */ public function hrRunningTime(string $out_time = 'ms'): float { - // if start time not set, set start time - if (!$this->hr_starttime) { - $this->hr_starttime = hrtime(true); - $this->hr_runtime = 0; - } else { - $this->hr_endtime = hrtime(true); - $this->hr_runtime = $this->hr_endtime - $this->hr_starttime; - // reset start and end time past run - $this->hr_starttime = 0; - $this->hr_endtime = 0; - } - // init divisor, just in case - $divisor = 1; - // check through valid out time, if nothing matches default to ms - switch ($out_time) { - case 'n': - case 'ns': - $divisor = 1; - break; - case 'y': - case 'ys': - $divisor = 1000; - break; - case 'm': - case 'ms': - $divisor = 1000000; - break; - case 's': - $divisor = 1000000000; - break; - // default is ms - default: - $divisor = 1000000; - break; - } - // return the run time in converted format - $this->hr_runtime /= $divisor; - return $this->hr_runtime; + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\RunningTime::hrRunningTime()', E_USER_DEPRECATED); + return \CoreLibs\Debug\RunningTime::hrRunningTime($out_time); } /** @@ -424,90 +303,53 @@ class Basic * NOTE: for pure running time check it is recommended to use hrRunningTime method * @param bool|boolean $simple if true prints HTML strings, default text only * @return float running time as float number + * @deprecated Use \CoreLibs\Debug\RunningTime::runningTime() instead */ public function runningTime(bool $simple = false): float { - list($micro, $timestamp) = explode(' ', microtime()); - $running_time = 0; - // set start & end time - if (!$this->starttime) { - // always reset running time string on first call - $this->runningtime_string = ''; - $this->starttime = ((float)$micro + (float)$timestamp); - $this->runningtime_string .= $simple ? 'Start: ' : "Started at: "; - } else { - $this->endtime = ((float)$micro + (float)$timestamp); - $this->runningtime_string .= $simple ? 'End: ' : "Stopped at: "; - } - $this->runningtime_string .= date('Y-m-d H:i:s', (int)$timestamp); - $this->runningtime_string .= ' '.$micro.($simple ? ', ' : '
'); - // if both are set - if ($this->starttime && $this->endtime) { - $running_time = $this->endtime - $this->starttime; - $this->runningtime_string .= ($simple ? 'Run: ' : "Script running time: ").$running_time." s"; - // reset start & end time after run - $this->starttime = 0; - $this->endtime = 0; - } - return $running_time; + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\RunningTime::runningTime()', E_USER_DEPRECATED); + return \CoreLibs\Debug\RunningTime::runningTime($simple); } + // ****** DEBUG SUPPORT FUNCTIONS ****** + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Debug\Support + /** * wrapper around microtime function to print out y-m-d h:i:s.ms * @param int $set_microtime -1 to set micro time, 0 for none, positive for rounding * @return string formated datetime string with microtime + * @deprecated Use \CoreLibs\Debug\Support::printTime() instead */ public static function printTime(int $set_microtime = -1): string { - list($microtime, $timestamp) = explode(' ', microtime()); - $string = date("Y-m-d H:i:s", (int)$timestamp); - // if microtime flag is -1 no round, if 0, no microtime, if >= 1, round that size - if ($set_microtime == -1) { - $string .= substr($microtime, 1); - } elseif ($set_microtime >= 1) { - // in round case we run this through number format to always get the same amount of digits - $string .= substr(number_format(round((float)$microtime, $set_microtime), $set_microtime), 1); - } - return $string; + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\Support::printTime()', E_USER_DEPRECATED); + return \CoreLibs\Debug\Support::printTime($set_microtime); } + // ****** DEBUG SUPPORT FUNCTIONS ****** + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Debug\FileWriter + /** * writes a string to a file immediatly, for fast debug output * @param string $string string to write to the file * @param boolean $enter default true, if set adds a linebreak \n at the end * @return void has no return + * @deprecated Use \CoreLibs\Debug\FileWriter::fdebug() instead */ - public function fdebug(string $string, bool $enter = true): void + public function fdebug(string $string, bool $enter = true): bool { - if ($this->debug_filename) { - $this->fdebugFP(); - if ($enter === true) { - $string .= "\n"; - } - $string = "[".$this->printTime()."] [".$this->getPageName(2)."] - ".$string; - fwrite($this->debug_fp, $string); - $this->fdebugFP(); - } + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\FileWriter::fdebug()', E_USER_DEPRECATED); + return \CoreLibs\Debug\FileWriter::fdebug($string, $enter); } - /** - * if no debug_fp found, opens a new one; if fp exists close it - * @param string $flag default '', 'o' -> open, 'c' -> close - * @return void has no return - */ - private function fdebugFP(string $flag = ''): void - { - if (!$this->debug_fp || $flag == 'o') { - $fn = BASE.LOG.$this->debug_filename; - $this->debug_fp = @fopen($fn, 'a'); - } elseif ($this->debug_fp || $flag == 'c') { - fclose($this->debug_fp); - } - } + // ****** DEBUG LOGGING FUNCTIONS ****** + // Moved to \CoreLibs\Debug\Logging /** * passes list of level names, to turn on debug - * eg $foo->debugFor('print', 'on', array('LOG', 'DEBUG', 'INFO')); + * eg $foo->debugFor('print', 'on', ['LOG', 'DEBUG', 'INFO']); * @param string $type error, echo, print * @param string $flag on/off * array $array of levels to turn on/off debug @@ -602,7 +444,7 @@ class Basic $this->error_msg[$level] = ''; } $error_string = '
'; - $error_string .= '['.$this->printTime().'] '; + $error_string .= '['.\CoreLibs\Debug\Support::printTime().'] '; $error_string .= '['.$level.'] '; $error_string .= '['.$this->host_name.'] '; $error_string .= '['.$this->page_name.'] '; @@ -616,7 +458,7 @@ class Basic $string = preg_replace("/(<\/?)(\w+)([^>]*>)/", '', $string); } // same string put for print (no html crap inside) - $error_string_print = '['.$this->printTime().'] ['.$this->host_name.'] ['.$this->getPageName(2).'] ['.$this->running_uid.'] {'.get_class($this).'} <'.$level.'> - '.$string; + $error_string_print = '['.\CoreLibs\Debug\Support::printTime().'] ['.$this->host_name.'] ['.\CoreLibs\Get\System::getPageName(2).'] ['.$this->running_uid.'] {'.get_class($this).'} <'.$level.'> - '.$string; $error_string_print .= "\n"; // write to file if set $this->writeErrorMsg($level, $error_string_print); @@ -627,41 +469,16 @@ class Basic } } - /** - * if there is a need to find out which parent method called a child method, - * eg for debugging, this function does this - * call this method in the child method and you get the parent function that called - * @param int $level debug level, default 2 - * @return ?string null or the function that called the function where this method is called - */ - public function getCallerMethod(int $level = 2): ?string - { - $traces = debug_backtrace(); - // extended info (later) - /*$file = $trace[$level]['file']; - $line = $trace[$level]['line']; - $object = $trace[$level]['object']; - if (is_object($object)) { - $object = get_class($object); - } - return "Where called: line $line of $object \n(in $file)";*/ - // sets the start point here, and in level two (the sub call) we find this - if (isset($traces[$level])) { - return $traces[$level]['function']; - } - return null; - } - /** * merges the given error array with the one from this class * only merges visible ones * @param array $error_msg error array * @return void has no return */ - public function mergeErrors(array $error_msg = array()): void + public function mergeErrors(array $error_msg = []): void { if (!is_array($error_msg)) { - $error_msg = array(); + $error_msg = []; } foreach ($error_msg as $level => $msg) { $this->error_msg[$level] .= $msg; @@ -750,7 +567,7 @@ class Basic $rpl_string = !$this->log_per_class ? '' : '_'.str_replace('\\', '-', get_class($this)); // set sub class settings $fn = str_replace('##CLASS##', $rpl_string, $fn); // create output filename - $rpl_string = !$this->log_per_page ? '' : '_'.$this->getPageName(1); // if request to write to one file + $rpl_string = !$this->log_per_page ? '' : '_'.\CoreLibs\Get\System::getPageName(1); // if request to write to one file $fn = str_replace('##PAGENAME##', $rpl_string, $fn); // create output filename // write to file @@ -789,102 +606,61 @@ class Basic * prints a html formatted (pre) array * @param array $array any array * @return string formatted array for output with
 tag added
+	 * DEPRCATE LATER
+	 * @_deprecated Use \CoreLibs\Debug\Support::printAr() instead
 	 */
 	public static function printAr(array $array): string
 	{
-		return "
".print_r($array, true)."
"; + return \CoreLibs\Debug\Support::printAr($array); } + /** + * if there is a need to find out which parent method called a child method, + * eg for debugging, this function does this + * call this method in the child method and you get the parent function that called + * @param int $level debug level, default 2 + * @return ?string null or the function that called the function where this method is called + * @deprecated Use \CoreLibs\Debug\Support::getCallerMethod() instead + */ + public static function getCallerMethod(int $level = 2): ?string + { + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\Support::getCallerMethod()', E_USER_DEPRECATED); + return \CoreLibs\Debug\Support::getCallerMethod($level); + } + + // *** SYSTEM HANDLING + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Get\System + /** * helper function for PHP file upload error messgaes to messge string * @param int $error_code integer _FILE upload error code * @return string message string, translated + * @deprecated Use \CoreLibs\Get\System::fileUploadErrorMessage() instead */ public function fileUploadErrorMessage(int $error_code): string { - switch ($error_code) { - case UPLOAD_ERR_INI_SIZE: - $message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini'; - break; - case UPLOAD_ERR_FORM_SIZE: - $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; - break; - case UPLOAD_ERR_PARTIAL: - $message = 'The uploaded file was only partially uploaded'; - break; - case UPLOAD_ERR_NO_FILE: - $message = 'No file was uploaded'; - break; - case UPLOAD_ERR_NO_TMP_DIR: - $message = 'Missing a temporary folder'; - break; - case UPLOAD_ERR_CANT_WRITE: - $message = 'Failed to write file to disk'; - break; - case UPLOAD_ERR_EXTENSION: - $message = 'File upload stopped by extension'; - break; - default: - $message = 'Unknown upload error'; - break; - } - return $message; + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Get\System::fileUploadErrorMessage()', E_USER_DEPRECATED); + return \CoreLibs\Get\System::fileUploadErrorMessage($error_code); } // ****** DEBUG/ERROR FUNCTIONS ****** // ****** RANDOM KEY GEN ****** - - // METHOD: initRandomKeyData - // PARAMS: none - // RETURN: none - // DESC : sets the random key range with the default values - /** - * sets the random key range with the default values - * @return void has no return - */ - private function initRandomKeyData() - { - // random key generation - $this->key_range = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9')); - $this->one_key_length = count($this->key_range); - // pow($this->one_key_length, 4); - // default set to 4, should be more than enought (62*62*62*62) - $this->key_length = 4; - } - - /** - * validates they key length for random string generation - * @param int $key_length key length - * @return bool true for valid, false for invalid length - */ - private function validateRandomKeyLenght(int $key_length): bool - { - if (is_numeric($key_length) && - $key_length > 0 && - $key_length <= $this->max_key_length - ) { - return true; - } else { - return false; - } - } + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Create\RandomKey /** * sets the key length and checks that they key given is valid * if failed it will not change the default key length and return false * @param int $key_length key length * @return bool true/false for set status + * @deprecated Use \CoreLibs\Create\RandomKey::setRandomKeyLength() instead */ public function initRandomKeyLength(int $key_length): bool { - // only if valid int key with valid length - if ($this->validateRandomKeyLenght($key_length) === true) { - $this->key_length = $key_length; - return true; - } else { - return false; - } + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\RandomKey::setRandomKeyLength()', E_USER_DEPRECATED); + return \CoreLibs\Create\RandomKey::setRandomKeyLength($key_length); } /** @@ -893,25 +669,17 @@ class Basic * this will not set the class key length variable * @param int $key_length key length override, -1 for use default * @return string random key + * @deprecated Use \CoreLibs\Create\RandomKey::randomKeyGen() instead */ public function randomKeyGen(int $key_length = -1): string { - $use_key_length = 0; - // only if valid int key with valid length - if ($this->validateRandomKeyLenght($key_length) === true) { - $use_key_length = $key_length; - } else { - $use_key_length = $this->key_length; - } - - $pieces = []; - for ($i = 1; $i <= $use_key_length; $i ++) { - $pieces[] = $this->key_range[random_int(0, $this->one_key_length - 1)]; - } - return join('', $pieces); + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\RandomKey::randomKeyGen()', E_USER_DEPRECATED); + return \CoreLibs\Create\RandomKey::randomKeyGen($key_length); } - // ****** RANDOM KEY GEN ****** + // ****** MAGIC LINK/CHECKED/SELECTED ****** + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Output\Form\Elements /** * returns 'checked' or 'selected' if okay @@ -944,24 +712,19 @@ class Basic return \CoreLibs\Output\Form\Elements::magicLinks($string, $target); } + // *** SYSTEM HANDLING + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Get\System + /** * get the host name without the port as given by the SELF var - * @return string host name + * @return array host name/port name + * @deprecated Use \CoreLibs\Get\System::getHostName() instead */ - public function getHostName(): string + public function getHostName(): array { - $port = ''; - if ($_SERVER['HTTP_HOST'] && preg_match("/:/", $_SERVER['HTTP_HOST'])) { - list($host_name, $port) = explode(":", $_SERVER['HTTP_HOST']); - } elseif ($_SERVER['HTTP_HOST']) { - $host_name = $_SERVER['HTTP_HOST']; - } else { - $host_name = 'NA'; - } - $this->host_port = $port ? $port : 80; - $this->host_name = $host_name; - // also return for old type call - return $host_name; + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Get\System::getHostName()', E_USER_DEPRECATED); + return \CoreLibs\Get\System::getHostName(); } /** @@ -970,20 +733,18 @@ class Basic * 0: keep filename as is * 2: keep filename as is, but add dirname too * @return string filename + * @deprecated Use \CoreLibs\Get\System::getPageName() instead */ public static function getPageName(int $strip_ext = 0): string { - // get the file info - $page_temp = pathinfo($_SERVER['PHP_SELF']); - if ($strip_ext == 1) { - return $page_temp['filename']; - } elseif ($strip_ext == 2) { - return $_SERVER['PHP_SELF']; - } else { - return $page_temp['basename']; - } + trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Get\System::getPageName()', E_USER_DEPRECATED); + return \CoreLibs\Get\System::getPageName($strip_ext); } + // *** FILE HANDLING + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Check\File + /** * quick return the extension of the given file name * @param string $filename file name @@ -1009,6 +770,8 @@ class Basic } // *** ARRAY HANDLING + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Combined\ArrayHandler /** * searches key = value in an array / array @@ -1174,6 +937,8 @@ class Basic } // *** ARRAY HANDLING END + // [!!! DEPRECATED !!!] + // Moved to \CoreLibs\Language\Encoding /** * wrapper function for mb mime convert, for correct conversion with long strings diff --git a/www/lib/CoreLibs/Check/Email.php b/www/lib/CoreLibs/Check/Email.php index 02c0013d..263b31a7 100644 --- a/www/lib/CoreLibs/Check/Email.php +++ b/www/lib/CoreLibs/Check/Email.php @@ -4,76 +4,109 @@ namespace CoreLibs\Check; class Email { - private static $mobile_email_type = []; - private static $mobile_email_type_short = []; + // this is for error check parts in where the email regex failed + 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 + 1 => "@(.*)@(.*)", // double @ + 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 + ]; + // the array with the mobile types that are valid + 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) + '.*@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 + '.*@emobile-s\.ne\.jp$' => 'keitai_willcom_emnet' # e-mobile, group will willcom + ]; + // short list for mobile email types + private static $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', + // old sets -> to be removed later + 'docomo' => 'docomo', + 'kddi_ezweb' => 'kddi', + 'kddi' => 'kddi', + 'kddi_tu-ka' => 'kddi', + 'kddi_sky' => 'kddi', + 'softbank' => 'softbank', + 'keitai_softbank_iphone' => 'iphone', + 'softbank_iphone' => 'iphone', + 'softbank_disney' => 'softbank', + 'softbank_vodafone' => 'softbank', + 'softbank_j-phone' => 'softbank', + 'willcom' => 'willcom', + 'willcom_pdx' => 'willcom', + 'willcom_bandai' => 'willcom', + 'willcom_pipopa' => 'willcom', + 'willcom_ymobile' => 'willcom', + 'willcom_emnet' => 'willcom', + 'pc' => 'pc' + ]; - public function __construct() + /** + * Undocumented function + * + * @param int $type Which position in the regex list to get + * if not set or not valid get default pos 0 + * @return string + */ + public static function getEmailRegex(int $type = 0): string { - // the array with the mobile types that are valid - self::$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) - '.*@willcom\.ne\.jp$' => 'keitai_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) - '.*@([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 - '.*@emobile-s\.ne\.jp$' => 'keitai_willcom_emnet' # e-mobile, group will willcom - ]; - // short list for mobile email types - self::$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', - // old sets -> to be removed later - 'docomo' => 'docomo', - 'kddi_ezweb' => 'kddi', - 'kddi' => 'kddi', - 'kddi_tu-ka' => 'kddi', - 'kddi_sky' => 'kddi', - 'softbank' => 'softbank', - 'keitai_softbank_iphone' => 'iphone', - 'softbank_iphone' => 'iphone', - 'softbank_disney' => 'softbank', - 'softbank_vodafone' => 'softbank', - 'softbank_j-phone' => 'softbank', - 'willcom' => 'willcom', - 'willcom_pdx' => 'willcom', - 'willcom_bandai' => 'willcom', - 'willcom_pipopa' => 'willcom', - 'willcom_ymobile' => 'willcom', - 'willcom_emnet' => 'willcom', - 'pc' => 'pc' - ]; + // make sure type is in valid range + if ($type < 0 || $type >= count(self::$email_regex_check)) { + $type = 0; + } + return self::$email_regex_check[$type]; + } + + /** + * get the full check array + * this will be deprected at some point + * + * @return array + */ + public static function getEmailRegexCheck(): array + { + return self::$email_regex_check; } /** diff --git a/www/lib/CoreLibs/Check/File.php b/www/lib/CoreLibs/Check/File.php index 30061388..0f06fa62 100644 --- a/www/lib/CoreLibs/Check/File.php +++ b/www/lib/CoreLibs/Check/File.php @@ -1,7 +1,7 @@ initRandomKeyData(); + } + /** + * sets the random key range with the default values + * @return void has no return + */ + private static function initRandomKeyData() + { + // random key generation + self::$key_range = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9')); + self::$one_key_length = count(self::$key_range); + } + + /** + * validates they key length for random string generation + * @param int $key_length key length + * @return bool true for valid, false for invalid length + */ + private static function validateRandomKeyLenght(int $key_length): bool + { + if (is_numeric($key_length) && + $key_length > 0 && + $key_length <= self::$max_key_length + ) { + return true; + } else { + return false; + } + } + + /** + * sets the key length and checks that they key given is valid + * if failed it will not change the default key length and return false + * @param int $key_length key length + * @return bool true/false for set status + */ + public static function setRandomKeyLength(int $key_length): bool + { + // only if valid int key with valid length + if (self::validateRandomKeyLenght($key_length) === true) { + self::$key_length = $key_length; + return true; + } else { + return false; + } + } + + /** + * get the current set random key length + * + * @return int Current set key length + */ + public static function getRandomKeyLength(): int + { + return self::$key_length; + } + + /** + * creates a random key based on the key_range with key_length + * if override key length is set, it will check on valid key and use this + * this will not set the class key length variable + * @param int $key_length key length override, -1 for use default + * @return string random key + */ + public static function randomKeyGen(int $key_length = -1): string + { + // init random key strings if not set + if (!is_numeric(self::$one_key_length)) { + self::initRandomKeyData(); + } + $use_key_length = 0; + // only if valid int key with valid length + if (self::validateRandomKeyLenght($key_length) === true) { + $use_key_length = $key_length; + } else { + $use_key_length = self::$key_length; + } + + $pieces = []; + for ($i = 1; $i <= $use_key_length; $i ++) { + $pieces[] = self::$key_range[random_int(0, self::$one_key_length - 1)]; + } + return join('', $pieces); + } +} diff --git a/www/lib/CoreLibs/Debug/FileWriter.php b/www/lib/CoreLibs/Debug/FileWriter.php new file mode 100644 index 00000000..f2f98303 --- /dev/null +++ b/www/lib/CoreLibs/Debug/FileWriter.php @@ -0,0 +1,61 @@ +script_starttime = microtime(true); + // set per run UID for logging + $this->running_uid = \CoreLibs\Create\Hash::__uniqId(); + // set the page name + $this->page_name = \CoreLibs\Get\System::getPageName(); + // set host name + list($this->host_name , $this->host_port) = \CoreLibs\Get\System::getHostName(); + // add port to host name if not port 80 + if ($this->host_port != 80) { + $this->host_name .= ':'.$this->host_port; + } + // can be overridden with basicSetLogFileId + if (isset($GLOBALS['LOG_FILE_ID'])) { + $this->basicSetLogId($GLOBALS['LOG_FILE_ID']); + } elseif (defined('LOG_FILE_ID')) { + $this->basicSetLogId(LOG_FILE_ID); + } + + // init the log levels + $this->setLogLevels(); + } + + /** + * sets the internal log file prefix id + * string must be a alphanumeric string + * if non valid string is given it returns the previous set one only + * @param string $string log file id string value + * @return string returns the set log file id string + */ + public function basicSetLogId(string $string): string + { + if (preg_match("/^\w+$/", $string)) { + $this->log_file_id = $string; + } + return $this->log_file_id; + } + + /** + * init the basic log levels based on global set variables + * + * @return void + */ + private function setLogLevels(): void + { + // if given via parameters, only for all + // globals overrule given settings, for one (array), eg $ECHO['db'] = 1; + if (isset($GLOBALS['DEBUG']) && is_array($GLOBALS['DEBUG'])) { + $this->debug_output = $GLOBALS['DEBUG']; + } + if (isset($GLOBALS['ECHO']) && is_array($GLOBALS['ECHO'])) { + $this->echo_output = $GLOBALS['ECHO']; + } + if (isset($GLOBALS['PRINT']) && is_array($GLOBALS['PRINT'])) { + $this->print_output = $GLOBALS['PRINT']; + } + + // exclude these ones from output + if (isset($GLOBALS['DEBUG_NOT']) && is_array($GLOBALS['DEBUG_NOT'])) { + $this->debug_output_not = $GLOBALS['DEBUG_NOT']; + } + if (isset($GLOBALS['ECHO_NOT']) && is_array($GLOBALS['ECHO_NOT'])) { + $this->echo_output_not = $GLOBALS['ECHO_NOT']; + } + if (isset($GLOBALS['PRINT_NOT']) && is_array($GLOBALS['PRINT_NOT'])) { + $this->print_output_not = $GLOBALS['PRINT_NOT']; + } + + // all overrule + $this->debug_output_all = $GLOBALS['DEBUG_ALL'] ?? false; + $this->echo_output_all = $GLOBALS['ECHO_ALL'] ?? false; + $this->print_output_all = $GLOBALS['PRINT_ALL'] ?? false; + + // GLOBAL rules for log writing + $this->log_print_file_date = $GLOBALS['LOG_PRINT_FILE_DATE'] ?? true; + $this->log_per_level = $GLOBALS['LOG_PER_LEVEL'] ?? false; + $this->log_per_class = $GLOBALS['LOG_PER_CLASS'] ?? false; + $this->log_per_page = $GLOBALS['LOG_PER_PAGE'] ?? false; + $this->log_per_run = $GLOBALS['LOG_PER_RUN'] ?? false; + } + + /** + * passes list of level names, to turn on debug + * eg $foo->debugFor('print', 'on', ['LOG', 'DEBUG', 'INFO']); + * @param string $type error, echo, print + * @param string $flag on/off + * array $array of levels to turn on/off debug + * @return void has no return + */ + public function debugFor(string $type, string $flag): void + { + $debug_on = func_get_args(); + array_shift($debug_on); // kick out type + array_shift($debug_on); // kick out flag (on/off) + if (count($debug_on) >= 1) { + foreach ($debug_on as $level) { + $switch = $type.'_output'; + if ($flag == 'off') { + $switch .= '_not'; + } + $this->{$switch}[$level] = true; + } + } + } + + /** + * checks if we have a need to work on certain debug output + * Needs debug/echo/print ad target for which of the debug flag groups we check + * also needs level string to check in the per level output flag check. + * In case we have invalid target it will return false + * @param string $target target group to check debug/echo/print + * @param string $level level to check in detailed level flag + * @return bool true on access allowed or false on no access + */ + private function doDebugTrigger(string $target, string $level): bool + { + $access = false; + // check if we do debug, echo or print + switch ($target) { + case 'debug': + if (( + (isset($this->debug_output[$level]) && $this->debug_output[$level]) || + $this->debug_output_all + ) && + (!isset($this->debug_output_not[$level]) || + (isset($this->debug_output_not[$level]) && !$this->debug_output_not[$level]) + ) + ) { + $access = true; + } + break; + case 'echo': + if (( + (isset($this->echo_output[$level]) && $this->echo_output[$level]) || + $this->echo_output_all + ) && + (!isset($this->echo_output_not[$level]) || + (isset($this->echo_output_not[$level]) && !$this->echo_output_not[$level]) + ) + ) { + $access = true; + } + break; + case 'print': + if (( + (isset($this->print_output[$level]) && $this->print_output[$level]) || + $this->print_output_all + ) && + (!isset($this->print_output_not[$level]) || + (isset($this->print_output_not[$level]) && !$this->print_output_not[$level]) + ) + ) { + $access = true; + } + break; + } + return $access; + } + + /** + * write debug data to error_msg array + * @param string $level id for error message, groups messages together + * @param string $string the actual error message + * @param bool $strip default on false, if set to true, + * all html tags will be stripped and
changed to \n + * this is only used for debug output + * @return bool True if logged, false if not logged + */ + public function debug(string $level, string $string, bool $strip = false): bool + { + if (!$this->doDebugTrigger('debug', $level)) { + return false; + } + if (!isset($this->error_msg[$level])) { + $this->error_msg[$level] = ''; + } + // get the last class entry and wrie that + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) ?? [['class' => get_class($this)]]; + $class = end($backtrace)['class']; + // get timestamp + $timestamp = \CoreLibs\Debug\Support::printTime(); + // HTML string, create only if we have echo + if ($this->doDebugTrigger('echo', $level)) { + $error_string = '
' + .'['.$timestamp.'] ' + .'['.$level.'] ' + .'['.$this->host_name.'] ' + .'['.$this->page_name.'] ' + .'['.$this->running_uid.'] ' + .'{'.$class.'} - '.\CoreLibs\Convert\Html::htmlent($string) + ."
"; + } + // if stripping all html, etc is requested + if ($strip) { + // find any
and replace them with \n + $string = str_replace('
', "\n", $string); + // strip rest of html elements + $string = preg_replace("/(<\/?)(\w+)([^>]*>)/", '', $string); + } + // same string put for print (no html data inside) + $error_string_print = + '['.$timestamp.'] ' + .'['.$this->host_name.'] ' + .'['.\CoreLibs\Get\System::getPageName(2).'] ' + .'['.$this->running_uid.'] ' + .'{'.$class.'} ' + .'<'.$level.'> - ' + .$string; + $error_string_print .= "\n"; + // write to file if set + $this->writeErrorMsg($level, $error_string_print); + // write to error level + if ($this->doDebugTrigger('echo', $level)) { + $this->error_msg[$level] .= $error_string; + } + return true; + } + + /** + * merges the given error array with the one from this class + * only merges visible ones + * @param array $error_msg error array + * @return void has no return + */ + public function mergeErrors(array $error_msg = []): void + { + if (!is_array($error_msg)) { + $error_msg = []; + } + foreach ($error_msg as $level => $msg) { + $this->error_msg[$level] .= $msg; + } + } + + /** + * prints out the error string + * @param string $string prefix string for header + * @return string error msg for all levels + */ + public function printErrorMsg(string $string = ''): string + { + $string_output = ''; + if ($this->debug_output_all) { + if ($this->error_msg_prefix) { + $string = $this->error_msg_prefix; + } + $script_end = microtime(true) - $this->script_starttime; + foreach ($this->error_msg as $level => $temp_debug_output) { + if ($this->doDebugTrigger('debug', $level)) { + if ($this->doDebugTrigger('echo', $level)) { + $string_output = '
' + .'['.$level.'] ' + .($string ? "**** ".\CoreLibs\Convert\Html::htmlent($string)." ****\n" : "") + .'
' + .$temp_debug_output; + } // echo it out + } // do printout + } // for each level + // create the output wrapper around, so we have a nice formated output per class + if ($string_output) { + $string_prefix = '
' + .'
{'.get_class($this).'}
'; + $string_output = $string_prefix.$string_output + .'
Script Run Time: '.$script_end.'
' + .'
'; + } + } + return $string_output; + } + + /** + * writes error msg data to file for current level + * @param string $level the level to write + * @param string $error_string error string to write + * @return bool True if message written, FAlse if not + */ + private function writeErrorMsg(string $level, string $error_string): bool + { + // only write if write is requested + if (!($this->doDebugTrigger('debug', $level) && + $this->doDebugTrigger('print', $level)) + ) { + return false; + } + // replace all html tags + // $error_string = preg_replace("/(<\/?)(\w+)([^>]*>)/", "##\\2##", $error_string); + // $error_string = preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $error_string); + // replace special line break tag + // $error_string = str_replace('', "\n", $error_string); + + // init output variable + $output = $error_string; // output formated error string to output file + // init base file path + $fn = BASE.LOG.$this->log_print_file.'.'.$this->log_file_name_ext; + // log ID prefix settings, if not valid, replace with empty + if (preg_match("/^[A-Za-z0-9]+$/", $this->log_file_id)) { + $rpl_string = '_'.$this->log_file_id; + } else { + $rpl_string = ''; + } + $fn = str_replace('##LOGID##', $rpl_string, $fn); // log id (like a log file prefix) + + if ($this->log_per_run) { + if (isset($GLOBALS['LOG_FILE_UNIQUE_ID'])) { + $this->log_file_unique_id = $GLOBALS['LOG_FILE_UNIQUE_ID']; + } + if (!$this->log_file_unique_id) { + $GLOBALS['LOG_FILE_UNIQUE_ID'] = $this->log_file_unique_id = date('Y-m-d_His').'_U_'.substr(hash('sha1', uniqid((string)mt_rand(), true)), 0, 8); + } + $rpl_string = '_'.$this->log_file_unique_id; // add 8 char unique string + } else { + $rpl_string = !$this->log_print_file_date ? '' : '_'.date('Y-m-d'); // add date to file + } + $fn = str_replace('##DATE##', $rpl_string, $fn); // create output filename + + $rpl_string = !$this->log_per_level ? '' : '_'.$level; // if request to write to one file + $fn = str_replace('##LEVEL##', $rpl_string, $fn); // create output filename + + $rpl_string = !$this->log_per_class ? '' : '_'.str_replace('\\', '-', get_class($this)); // set sub class settings + $fn = str_replace('##CLASS##', $rpl_string, $fn); // create output filename + + $rpl_string = !$this->log_per_page ? '' : '_'.\CoreLibs\Get\System::getPageName(1); // if request to write to one file + $fn = str_replace('##PAGENAME##', $rpl_string, $fn); // create output filename + + // write to file + // first check if max file size is is set and file is bigger + if ($this->log_max_filesize > 0 && ((filesize($fn) / 1024) > $this->log_max_filesize)) { + // for easy purpose, rename file only to attach timestamp, nur sequence numbering + rename($fn, $fn.'.'.date("YmdHis")); + } + $fp = fopen($fn, 'a'); + if ($fp !== false) { + fwrite($fp, $output); + fclose($fp); + } else { + echo ""; + } + return true; + } + + /** + * unsests the error message array + * can be used if writing is primary to file + * if no level given resets all + * @param string $level optional level + * @return void has no return + */ + public function resetErrorMsg(string $level = ''): void + { + if (!$level) { + $this->error_msg = []; + } elseif (isset($this->error_msg[$level])) { + unset($this->error_msg[$level]); + } + } +} + +// __END__ diff --git a/www/lib/CoreLibs/Debug/RunningTime.php b/www/lib/CoreLibs/Debug/RunningTime.php new file mode 100644 index 00000000..0c4b1136 --- /dev/null +++ b/www/lib/CoreLibs/Debug/RunningTime.php @@ -0,0 +1,119 @@ +Started at: "; + } else { + self::$endtime = ((float)$micro + (float)$timestamp); + self::$runningtime_string .= $simple ? 'End: ' : "Stopped at: "; + } + self::$runningtime_string .= date('Y-m-d H:i:s', (int)$timestamp); + self::$runningtime_string .= ' '.$micro.($simple ? ', ' : '
'); + // if both are set + if (self::$starttime && self::$endtime) { + $running_time = self::$endtime - self::$starttime; + self::$runningtime_string .= ($simple ? 'Run: ' : "Script running time: ").$running_time." s"; + // reset start & end time after run + self::$starttime = 0; + self::$endtime = 0; + } + return $running_time; + } + + /** + * get the runningTime string (for debug visual) + * + * @return string + */ + public static function runningTimeString(): string + { + return self::$runningtime_string; + } +} + +// __END__ diff --git a/www/lib/CoreLibs/Debug/Support.php b/www/lib/CoreLibs/Debug/Support.php new file mode 100644 index 00000000..445e3a40 --- /dev/null +++ b/www/lib/CoreLibs/Debug/Support.php @@ -0,0 +1,60 @@ += 1, round that size + if ($set_microtime == -1) { + $string .= substr($microtime, 1); + } elseif ($set_microtime >= 1) { + // in round case we run this through number format to always get the same amount of digits + $string .= substr(number_format(round((float)$microtime, $set_microtime), $set_microtime), 1); + } + return $string; + } + + /** + * prints a html formatted (pre) array + * @param array $array any array + * @return string formatted array for output with
 tag added
+	 */
+	public static function printAr(array $array): string
+	{
+		return "
".print_r($array, true)."
"; + } + + /** + * if there is a need to find out which parent method called a child method, + * eg for debugging, this function does this + * call this method in the child method and you get the parent function that called + * @param int $level debug level, default 2 + * @return ?string null or the function that called the function where this method is called + */ + public static function getCallerMethod(int $level = 1): ?string + { + $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + // print \CoreLibs\Debug\Support::printAr($traces); + // We should check from top down if unset? + // sets the start point here, and in level two (the sub call) we find this + if (isset($traces[$level])) { + return $traces[$level]['function']; + } + return null; + } +} + +// __END__ diff --git a/www/lib/CoreLibs/Get/System.php b/www/lib/CoreLibs/Get/System.php new file mode 100644 index 00000000..a7450afa --- /dev/null +++ b/www/lib/CoreLibs/Get/System.php @@ -0,0 +1,85 @@ +