Compare commits

...

15 Commits

Author SHA1 Message Date
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
121 changed files with 3780 additions and 2148 deletions

View File

@@ -1,7 +1,5 @@
<?php <?php
use Phan\Config;
/** /**
* This configuration will be read and overlaid on top of the * This configuration will be read and overlaid on top of the
* default configuration. Command line arguments will be applied * 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 * of the phan executable or a path passed in via the CLI
* '-d' flag. * '-d' flag.
*/ */
use Phan\Config;
return [ return [
// If true, missing properties will be created when // If true, missing properties will be created when
// they are first seen. If false, we'll report an // they are first seen. If false, we'll report an

View File

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

View File

@@ -27,3 +27,9 @@ msgstr "Month"
msgid "INPUT TEST" msgid "INPUT TEST"
msgstr "OUTPUT TEST EN" 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

@@ -1,5 +1,13 @@
# PHP Core Library # 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 Base PHP class files to setup any project
* login * login
* database wrapper * database wrapper

View File

@@ -1,4 +1,5 @@
<?php <?php
// Boostrap file for PHPstand // Boostrap file for PHPstand
// sets the _SERVER['HTTP_HOST'] var so we can have DB detection // sets the _SERVER['HTTP_HOST'] var so we can have DB detection
$_SERVER['HTTP_HOST'] = 'soba.tokyo.tequila.jp'; $_SERVER['HTTP_HOST'] = 'soba.tokyo.tequila.jp';

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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -53,15 +56,19 @@ $test_array = [
], ],
]; ];
echo "SOURCE ARRAY: ".DgS::printAr($test_array)."<br>"; echo "SOURCE ARRAY: " . DgS::printAr($test_array) . "<br>";
// frist return // frist return
echo "ARRAYSEARCHRECURSIVE(email, [array], type): ".DgS::printAr(ArrayHandler::arraySearchRecursive('email', $test_array, 'type'))."<br>"; echo "ARRAYSEARCHRECURSIVE(email, [array], type): "
echo "ARRAYSEARCHRECURSIVE(email, [array]['input'], type): ".DgS::printAr(ArrayHandler::arraySearchRecursive('email', $test_array['input'], 'type'))."<br>"; . 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 // 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 // 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 = [ $array_1 = [
'foo' => 'bar' 'foo' => 'bar'
@@ -75,7 +82,7 @@ $array_3 = [
] ]
]; ];
// recusrice merge // 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 difference
$array_left = [ $array_left = [
'same' => 'data', 'same' => 'data',
@@ -85,18 +92,109 @@ $array_right = [
'same' => 'data', 'same' => 'data',
'right' => 'has R' '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 // 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 // flatten array
print "FLATTENARRAY: ".DgS::printAr(ArrayHandler::flattenArray($test_array))."<br>"; print "FLATTENARRAY: " . DgS::printAr(ArrayHandler::flattenArray($test_array)) . "<br>";
print "FLATTENARRAYKEY: ".DgS::printAr(ArrayHandler::flattenArrayKey($test_array))."<br>"; print "FLATTENARRAYKEY: " . DgS::printAr(ArrayHandler::flattenArrayKey($test_array)) . "<br>";
// flatten for key set // 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 // DEPRECATED
// print "ARRAYMERGERECURSIVE: ".DgS::printAr($basic->arrayMergeRecursive($array_1, $array_2, $array_3))."<br>"; // 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 // error message
print $basic->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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -39,8 +42,8 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$byte = 254779258; $byte = 254779258;
$string = '242.98 MB'; $string = '242.98 MB';
// static // static
print "S::BYTE TO: $byte: ".$byte_class::humanReadableByteFormat($byte)."<br>"; print "S::BYTE TO: $byte: " . $byte_class::humanReadableByteFormat($byte) . "<br>";
print "S::BYTE FROM: $string: ".$byte_class::stringByteFormat($string)."<br>"; print "S::BYTE FROM: $string: " . $byte_class::stringByteFormat($string) . "<br>";
// *** BYTES TEST *** // *** BYTES TEST ***
$bytes = array( $bytes = array(
@@ -59,9 +62,9 @@ foreach ($bytes as $byte) {
print '<div style="display: flex; border-bottom: 1px dashed gray;">'; print '<div style="display: flex; border-bottom: 1px dashed gray;">';
// //
print '<div style="width: 35%; text-align: right; padding-right: 2px;">'; 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); $_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 '</div><div style="width: 10%;">';
print Byte::stringByteFormat($_bytes); print Byte::stringByteFormat($_bytes);
print "</div>"; print "</div>";
@@ -73,7 +76,7 @@ foreach ($bytes as $byte) {
print '<div style="width: 35%; text-align: right; padding-right: 2px;">'; print '<div style="width: 35%; text-align: right; padding-right: 2px;">';
print "bytes [si]:"; print "bytes [si]:";
$_bytes = Byte::humanReadableByteFormat($byte, Byte::BYTE_FORMAT_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 '</div><div style="width: 10%;">';
print Byte::stringByteFormat($_bytes); print Byte::stringByteFormat($_bytes);
print "</div>"; print "</div>";

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1); <?php // phpcs:ignore warning
/** /**
* @phan-file-suppress PhanTypeSuspiciousStringExpression * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_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 // define a list of from to color sets for conversion test
// A(out of bounds) // 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 (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 (gary 125): -1, -1, -1: " . $color_class::rgb2hex(-1, -1, -1) . "<br>";
// B(valid) // B(valid)
$rgb = [10, 20, 30]; $rgb = [10, 20, 30];
$hex = '#0a141e'; $hex = '#0a141e';
$hsb = [210, 67, 12]; $hsb = [210, 67, 12];
$hsl = [210, 50, 7.8]; $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 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 "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 "C::S/COLOR rgb->hext: $hex: " . DgS::printAr(CoreLibs\Convert\Colors::hex2rgb($hex)) . "<br>";
// C(to hsb/hsl) // 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->hsb: $rgb[0], $rgb[1], $rgb[2]: "
print "S::COLOR rgb->hsl: $rgb[0], $rgb[1], $rgb[2]: ".DgS::printAr(Colors::rgb2hsl($rgb[0], $rgb[1], $rgb[2]))."<br>"; . 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 // 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 hsb->rgb: $hsb[0], $hsb[1], $hsb[2]: "
print "S::COLOR hsl->rgb: $hsl[0], $hsl[1], $hsl[2]: ".DgS::printAr(Colors::hsl2rgb($hsl[0], $hsl[1], $hsl[2]))."<br>"; . 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 // 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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -30,7 +33,7 @@ use CoreLibs\Combined\DateTime;
use CoreLibs\Debug\Support as DgS; use CoreLibs\Debug\Support as DgS;
$basic = new CoreLibs\Basic(); $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 "<html><head><title>TEST CLASS: DATE/TIME</title><head>";
print "<body>"; print "<body>";
@@ -39,47 +42,47 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
// class // class
$timestamp = 1622788315.123456; $timestamp = 1622788315.123456;
// static // 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 // time string thest
$timestamp = 5887998.33445; $timestamp = 5887998.33445;
$time_string = DateTime::timeStringFormat($timestamp); $time_string = DateTime::timeStringFormat($timestamp);
print "PLANE TIME STRING: ".$timestamp."<br>"; print "PLANE TIME STRING: " . $timestamp . "<br>";
print "TIME STRING TEST: ".$time_string."<br>"; print "TIME STRING TEST: " . $time_string . "<br>";
print "REVERSE TIME STRING: ".DateTime::stringToTime($time_string)."<br>"; print "REVERSE TIME STRING: " . DateTime::stringToTime($time_string) . "<br>";
if (round($timestamp, 4) == DateTime::stringToTime($time_string)) { if (round($timestamp, 4) == DateTime::stringToTime($time_string)) {
print "REVERSE TIME STRING MATCH<br>"; print "REVERSE TIME STRING MATCH<br>";
} else { } else {
print "REVERSE TRIME STRING DO NOT MATCH<br>"; print "REVERSE TRIME STRING DO NOT MATCH<br>";
} }
print "ZERO TIME STRING: ".DateTime::timeStringFormat(0, 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(0.0, true) . "<br>";
print "ZERO TIME STRING: ".DateTime::timeStringFormat(1.005, true)."<br>"; print "ZERO TIME STRING: " . DateTime::timeStringFormat(1.005, true) . "<br>";
$timestamps = [ $timestamps = [
1622788315.123456, 1622788315.123456,
-1622788315.456789 -1622788315.456789
]; ];
foreach ($timestamps as $timestamp) { foreach ($timestamps as $timestamp) {
print "DATESTRINGFORMAT(sm:0): $timestamp: ".DateTime::dateStringFormat($timestamp)."<br>"; print "DATESTRINGFORMAT(sm:0): $timestamp: " . DateTime::dateStringFormat($timestamp) . "<br>";
print "DATESTRINGFORMAT(sm:1): $timestamp: ".DateTime::dateStringFormat($timestamp, true)."<br>"; print "DATESTRINGFORMAT(sm:1): $timestamp: " . DateTime::dateStringFormat($timestamp, true) . "<br>";
} }
$intervals = [ $intervals = [
788315.123456, 788315.123456,
-123.456 -123.456
]; ];
foreach ($intervals as $interval) { 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); $reverse_interval = DateTime::timeStringFormat($interval);
print "TIMESTRINGFORMAT(sm:1): $interval: ".$reverse_interval."<br>"; print "TIMESTRINGFORMAT(sm:1): $interval: " . $reverse_interval . "<br>";
print "STRINGTOTIME: $reverse_interval: ".DateTime::stringToTime($reverse_interval)."<br>"; print "STRINGTOTIME: $reverse_interval: " . DateTime::stringToTime($reverse_interval) . "<br>";
} }
$check_dates = [ $check_dates = [
'2021-05-01', '2021-05-01',
'2021-05-40' '2021-05-40'
]; ];
foreach ($check_dates as $check_date) { 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 = [ $check_datetimes = [
'2021-05-01', '2021-05-01',
@@ -89,7 +92,7 @@ $check_datetimes = [
'2021-05-01 25:13:14', '2021-05-01 25:13:14',
]; ];
foreach ($check_datetimes as $check_datetime) { 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 = [ $compare_dates = [
[ '2021-05-01', '2021-05-02', ], [ '2021-05-01', '2021-05-02', ],
@@ -99,7 +102,8 @@ $compare_dates = [
]; ];
// compareDate // compareDate
foreach ($compare_dates as $compare_date) { 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 = [ $compare_datetimes = [
[ '2021-05-01', '2021-05-02', ], [ '2021-05-01', '2021-05-02', ],
@@ -110,7 +114,8 @@ $compare_datetimes = [
[ '2021-05-01 10:00:00', '2021-05-01 10:00:00', ], [ '2021-05-01 10:00:00', '2021-05-01 10:00:00', ],
]; ];
foreach ($compare_datetimes as $compare_datetime) { 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 = [ $compare_dates = [
[ '2021-05-01', '2021-05-10', ], [ '2021-05-01', '2021-05-10', ],
@@ -119,8 +124,10 @@ $compare_dates = [
[ '2021-05-02', '2021-05-02', ], [ '2021-05-02', '2021-05-02', ],
]; ];
foreach ($compare_dates as $compare_date) { 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: $compare_date[0] = $compare_date[1]: "
print "CALCDAYSINTERVAL(named): $compare_date[0] = $compare_date[1]: ".DgS::printAr(DateTime::calcDaysInterval($compare_date[0], $compare_date[1], true))."<br>"; . 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 // DEPRECATED
@@ -135,11 +142,14 @@ print "CHECKDATE: $check_date: ".(string)$basic->checkDate($check_date)."<br>";
$check_datetime = '2021-05-01 12:13:14'; $check_datetime = '2021-05-01 12:13:14';
print "CHECKDATETIME: $check_datetime: ".(string)$basic->checkDateTime($check_datetime)."<br>"; print "CHECKDATETIME: $check_datetime: ".(string)$basic->checkDateTime($check_datetime)."<br>";
$compare_date = ['2021-05-01', '2021-05-02']; $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']; $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']; $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 // error message
print $basic->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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true; $DEBUG_ALL = true;
$PRINT_ALL = true; $PRINT_ALL = true;
@@ -18,6 +21,8 @@ ob_start();
define('USE_DATABASE', true); define('USE_DATABASE', true);
// sample config // sample config
require 'config.php'; require 'config.php';
// override ECHO ALL FALSE
$ECHO_ALL = true;
// set session name // set session name
if (!defined('SET_SESSION_NAME')) { if (!defined('SET_SESSION_NAME')) {
define('SET_SESSION_NAME', EDIT_SESSION_NAME); define('SET_SESSION_NAME', EDIT_SESSION_NAME);
@@ -28,114 +33,169 @@ ob_end_flush();
use CoreLibs\Debug\Support as DgS; 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 "<html><head><title>TEST CLASS: DB</title><head>";
print "<body>"; print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>'; print '<div><a href="class_test.php">Class Test Master</a></div>';
print "DBINFO: ".$basic->dbInfo()."<br>"; print "DBINFO: " . $db->dbInfo() . "<br>";
echo "DB_CONFIG_SET constant: <pre>".print_r(DB_CONFIG, true)."</pre><br>"; echo "DB_CONFIG_SET constant: <pre>" . print_r(DB_CONFIG, true) . "</pre><br>";
// DB client encoding // 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)) { while ($res = $db->dbReturn("SELECT * FROM max_test", 0, true)) {
print "TIME: ".$res['time']."<br>"; print "TIME: " . $res['time'] . "<br>";
} }
print "CACHED DATA: <pre>".print_r($basic->cursor_ext, true)."</pre><br>"; print "CACHED DATA: <pre>" . print_r($db->cursor_ext, true) . "</pre><br>";
while ($res = $basic->dbReturn("SELECT * FROM max_test")) { while ($res = $db->dbReturn("SELECT * FROM max_test")) {
print "[CACHED] TIME: ".$res['time']."<br>"; print "[CACHED] TIME: " . $res['time'] . "<br>";
} }
print "<pre>"; print "<pre>";
$status = $basic->dbExec("INSERT INTO foo (test) VALUES ('FOO TEST ".time()."') RETURNING test"); $status = $db->dbExec("INSERT INTO foo (test) VALUES ('FOO TEST " . time() . "') RETURNING test");
print "DIRECT INSERT STATUS: $status | " print "DIRECT INSERT STATUS: $status | "
."PRIMARY KEY: ".$basic->dbGetInsertPK()." | " . "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | " . "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
."RETURNING ARRAY: ".print_r($basic->dbGetReturningArray(), true)."<br>"; . "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
// should throw deprecated error // should throw deprecated error
// $basic->getReturningExt(); // $db->getReturningExt();
print "DIRECT INSERT PREVIOUS INSERTED: ".print_r($basic->dbReturnRow("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->dbGetInsertPK()), true)."<br>"; print "DIRECT INSERT PREVIOUS INSERTED: "
$basic->dbPrepare("ins_foo", "INSERT INTO foo (test) VALUES ($1)"); . print_r($db->dbReturnRow("SELECT foo_id, test FROM foo WHERE foo_id = " . $db->dbGetInsertPK()), true) . "<br>";
$status = $basic->dbExecute("ins_foo", array('BAR TEST '.time())); $db->dbPrepare("ins_foo", "INSERT INTO foo (test) VALUES ($1)");
$status = $db->dbExecute("ins_foo", array('BAR TEST ' . time()));
print "PREPARE INSERT STATUS: $status | " print "PREPARE INSERT STATUS: $status | "
."PRIMARY KEY: ".$basic->dbGetInsertPK()." | " . "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | " . "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
."RETURNING RETURN: ".print_r($basic->dbGetReturningArray(), true)."<br>"; . "RETURNING RETURN: " . print_r($db->dbGetReturningArray(), true) . "<br>";
print "PREPARE INSERT PREVIOUS INSERTED: ".print_r($basic->dbReturnRow("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->dbGetInsertPK()), true)."<br>"; print "PREPARE INSERT PREVIOUS INSERTED: "
. print_r($db->dbReturnRow("SELECT foo_id, test FROM foo WHERE foo_id = " . $db->dbGetInsertPK()), true) . "<br>";
// returning test with multiple entries // 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 = $db->db_exec(
$status = $basic->dbExec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id, test"); // "INSERT INTO foo (test) VALUES "
// . "('BAR 1 " . time() . "'), "
// . "('BAR 2 " . time() . "'), "
// . "('BAR 3 " . time() . "') "
// . "RETURNING foo_id"
// );
$status = $db->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 | " print "DIRECT MULTIPLE INSERT STATUS: $status | "
."PRIMARY KEYS: ".print_r($basic->dbGetInsertPK(), true)." | " . "PRIMARY KEYS: " . print_r($db->dbGetInsertPK(), true) . " | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | " . "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
."RETURNING ARRAY: ".print_r($basic->dbGetReturningArray(), true)."<br>"; . "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
// no returning, but not needed ; // no returning, but not needed ;
$status = $basic->dbExec("INSERT INTO foo (test) VALUES ('FOO; TEST ".time()."');"); $status = $db->dbExec("INSERT INTO foo (test) VALUES ('FOO; TEST " . time() . "');");
print "DIRECT INSERT STATUS: $status | " print "DIRECT INSERT STATUS: $status | "
."PRIMARY KEY: ".$basic->dbGetInsertPK()." | " . "PRIMARY KEY: " . $db->dbGetInsertPK() . " | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | " . "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
."RETURNING ARRAY: ".print_r($basic->dbGetReturningArray(), true)."<br>"; . "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
// UPDATE WITH RETURNING // UPDATE WITH RETURNING
$status = $basic->dbExec("UPDATE foo SET test = 'SOMETHING DIFFERENT' WHERE foo_id = 3688452 RETURNING test"); $status = $db->dbExec("UPDATE foo SET test = 'SOMETHING DIFFERENT' WHERE foo_id = 3688452 RETURNING test");
print "UPDATE STATUS: $status | " print "UPDATE STATUS: $status | "
."RETURNING EXT: ".print_r($basic->dbGetReturningExt(), true)." | " . "RETURNING EXT: " . print_r($db->dbGetReturningExt(), true) . " | "
."RETURNING ARRAY: ".print_r($basic->dbGetReturningArray(), true)."<br>"; . "RETURNING ARRAY: " . print_r($db->dbGetReturningArray(), true) . "<br>";
print "</pre>"; print "</pre>";
// REEAD PREPARE // 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) { if (
$db->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>"; print "Error in sel_foo prepare<br>";
} else { } else {
$max_rows = 6; $max_rows = 6;
// do not run this in dbFetchArray directly as // do not run this in dbFetchArray directly as
// dbFetchArray(dbExecute(...)) // dbFetchArray(dbExecute(...))
// this will end in an endless loop // this will end in an endless loop
$cursor = $basic->dbExecute('sel_foo', []); $cursor = $db->dbExecute('sel_foo', []);
$i = 1; $i = 1;
while (($res = $basic->dbFetchArray($cursor, true)) !== false) { while (($res = $db->dbFetchArray($cursor, true)) !== false) {
print "DB PREP EXEC FETCH ARR: ".$i.": <pre>".print_r($res, true)."</pre><br>"; print "DB PREP EXEC FETCH ARR: " . $i . ": <pre>" . print_r($res, true) . "</pre><br>";
$i ++; $i++;
} }
} }
# db write class test # db write class test
$table = 'foo'; $table = 'foo';
print "TABLE META DATA: ".DgS::printAr($basic->dbShowTableMetaData($table))."<br>"; print "TABLE META DATA: " . DgS::printAr($db->dbShowTableMetaData($table)) . "<br>";
$primary_key = ''; # unset $primary_key = ''; # unset
$db_write_table = array('test', 'string_a', 'number_a', 'some_bool'); $db_write_table = array('test', 'string_a', 'number_a', 'some_bool');
// $db_write_table = array('test'); // $db_write_table = array('test');
$object_fields_not_touch = array(); $object_fields_not_touch = array();
$object_fields_not_update = array(); $object_fields_not_update = array();
$data = array('test' => 'BOOL TEST SOMETHING '.time(), 'string_a' => 'SOME TEXT', 'number_a' => 5); $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); $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 and got primary key $primary_key<br>"; 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); $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); $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 and got primary key $primary_key<br>"; 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); $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); $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 and got primary key $primary_key<br>"; print "Wrote to DB tabel $table and got primary key $primary_key<br>";
$data = array('test' => 'BOOL TEST UNSET '.time()); $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); $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 and got primary key $primary_key<br>"; print "Wrote to DB tabel $table and got primary key $primary_key<br>";
// return Array Test // return Array Test
$query = "SELECT type, sdate, integer FROM foobar"; $query = "SELECT type, sdate, integer FROM foobar";
$data = $basic->dbReturnArray($query, true); $data = $db->dbReturnArray($query, true);
print "Full foobar list: <br><pre>".print_r($data, true)."</pre><br>"; print "Full foobar list: <br><pre>" . print_r($data, true) . "</pre><br>";
# async test queries # 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 foo, (SELECT pg_sleep(10)) as sub WHERE foo_id IN (27, 50, 67, 44, 10)");
echo "WAITING FOR ASYNC: "; echo "WAITING FOR ASYNC: ";
$chars = array('|', '/', '-', '\\'); $chars = array('|', '/', '-', '\\');
while (($ret = $basic->dbCheckAsync()) === true) while (($ret = $db->dbCheckAsync()) === true)
{ {
if ((list($_, $char) = each($chars)) === FALSE) if ((list($_, $char) = each($chars)) === FALSE)
{ {
@@ -146,38 +206,39 @@ while (($ret = $basic->dbCheckAsync()) === true)
sleep(1); sleep(1);
flush(); flush();
} }
print "<br>END STATUS: ".$ret."<br>"; print "<br>END STATUS: " . $ret . "<br>";
// while ($res = $basic->dbFetchArray($ret)) // while ($res = $db->dbFetchArray($ret))
while ($res = $basic->dbFetchArray()) while ($res = $db->dbFetchArray())
{ {
echo "RES: ".$res['test']."<br>"; echo "RES: " . $res['test'] . "<br>";
} }
# test async insert # test async insert
$basic->dbExecAsync("INSERT INTO foo (Test) VALUES ('ASYNC TEST ".time()."')"); $db->dbExecAsync("INSERT INTO foo (Test) VALUES ('ASYNC TEST " . time() . "')");
echo "WAITING FOR ASYNC INSERT: "; echo "WAITING FOR ASYNC INSERT: ";
while (($ret = $basic->dbCheckAsync()) === true) while (($ret = $db->dbCheckAsync()) === true)
{ {
print "."; print " . ";
sleep(1); sleep(1);
flush(); flush();
} }
print "<br>END STATUS: ".$ret." | PK: ".$basic->insert_id."<br>"; print "<br>END STATUS: " . $ret . " | PK: " . $db->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 "ASYNC PREVIOUS INSERTED: "
. print_r($db->dbReturnRow("SELECT foo_id, test FROM foo WHERE foo_id = " . $db->insert_id), true) . "<br>"; */
$to_db_version = '9.1.9'; $to_db_version = '9.1.9';
print "VERSION DB: ".$basic->dbVersion()."<br>"; print "VERSION DB: " . $db->dbVersion() . "<br>";
print "DB Version smaller $to_db_version: ".$basic->dbCompareVersion('<'.$to_db_version)."<br>"; print "DB Version smaller $to_db_version: " . $db->dbCompareVersion('<' . $to_db_version) . "<br>";
print "DB Version smaller than $to_db_version: ".$basic->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: ".$basic->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: ".$basic->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: ".$basic->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 FOO FRO BAR";
// $q = "Select * from foo"; // $q = "Select * from foo";
$foo = $basic->dbExecAsync($q); $foo = $db->dbExecAsync($q);
print "[ERR] Query: ".$q."<br>"; print "[ERR] Query: " . $q . "<br>";
print "[ERR] RESOURCE: $foo<br>"; print "[ERR] RESOURCE: $foo<br>";
while (($ret = $basic->dbCheckAsync()) === true) while (($ret = $db->dbCheckAsync()) === true)
{ {
print "[ERR]: $ret<br>"; print "[ERR]: $ret<br>";
sleep(5); sleep(5);
@@ -185,21 +246,25 @@ while (($ret = $basic->dbCheckAsync()) === true)
// search path check // search path check
$q = "SHOW search_path"; $q = "SHOW search_path";
$cursor = $basic->dbExec($q); $cursor = $db->dbExec($q);
$data = $basic->dbFetchArray($cursor)['search_path']; $data = $db->dbFetchArray($cursor)['search_path'];
print "RETURN DATA FOR search_path: ".$data."<br>"; print "RETURN DATA FOR search_path: " . $data . "<br>";
// print "RETURN DATA FOR search_path: ".DgS::printAr($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 // 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).")"); $status = $db->dbExec(
print "OTHER SCHEMA INSERT STATUS: ".$status." | PK NAME: ".$basic->pk_name.", PRIMARY KEY: ".$basic->insert_id."<br>"; "INSERT INTO test.schema_test (contents, id) VALUES "
. "('TIME: " . time() . "', " . rand(1, 10) . ")"
);
print "OTHER SCHEMA INSERT STATUS: "
. $status . " | PK NAME: " . $db->pk_name . ", PRIMARY KEY: " . $db->insert_id . "<br>";
print "<b>NULL TEST DB READ</b><br>"; print "<b>NULL TEST DB READ</b><br>";
$q = "SELECT uid, null_varchar, null_int FROM test_null_data WHERE uid = 'A'"; $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); var_dump($res);
print "RES: ".DgS::printAr($res)."<br>"; print "RES: " . DgS::printAr($res) . "<br>";
print "ISSET: ".isset($res['null_varchar'])."<br>"; print "ISSET: " . isset($res['null_varchar']) . "<br>";
print "EMPTY: ".empty($res['null_varchar'])."<br>"; print "EMPTY: " . empty($res['null_varchar']) . "<br>";
// error message // error message
print $basic->log->printErrorMsg(); print $basic->log->printErrorMsg();

View File

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

View File

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

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1); <?php // phpcs:ignore warning
/** /**
* @phan-file-suppress PhanTypeSuspiciousStringExpression * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -46,7 +49,7 @@ $mime_encodes = [
['日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい', 'ISO-2022-JP-MS'], ['日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい日本語ながい', 'ISO-2022-JP-MS'],
]; ];
foreach ($mime_encodes as $mime_encode) { 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 = [ $enc_strings = [
@@ -59,26 +62,29 @@ $enc_strings = [
$_encoding->setErrorChar('∴'); $_encoding->setErrorChar('∴');
foreach ($enc_strings as $_string) { foreach ($enc_strings as $_string) {
$string = $_encoding->checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS'); $string = $_encoding->checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS');
print "ENC CHECK: $_string: ".($string === false ? '-OK-' : $string)."<br>"; print "ENC CHECK: $_string: " . ($string === false ? '-OK-' : $string) . "<br>";
print "CONV ENCODING: $_string: ".$_encoding->convertEncoding($_string, 'ISO-2022-JP')."<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): $_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 "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 // static
$encoding_class::setErrorChar('∴'); $encoding_class::setErrorChar('∴');
foreach ($enc_strings as $_string) { foreach ($enc_strings as $_string) {
$string = $encoding_class::checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS'); $string = $encoding_class::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>";
print "S::CONV ENCODING: $_string: ".$encoding_class::convertEncoding($_string, 'ISO-2022-JP')."<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): $_string: "
print "S::CONV ENCODING (s,a-false): $_string: ".$encoding_class::convertEncoding($_string, 'ISO-2022-JP', 'UTF-8', false)."<br>"; . $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 // static use
$_string = $enc_strings[1]; $_string = $enc_strings[1];
$string = Encoding::checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS'); $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 // DEPRECATED
/* $string = $basic->checkConvertEncoding($_string, 'UTF-8', 'ISO-2022-JP-MS'); /* $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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -35,9 +38,9 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>'; print '<div><a href="class_test.php">Class Test Master</a></div>';
$file = '/some/path/to/some/file.txt'; $file = '/some/path/to/some/file.txt';
print "GETFILENAMEENDING: $file: ".File::getFilenameEnding($file)."<br>"; print "GETFILENAMEENDING: $file: " . File::getFilenameEnding($file) . "<br>";
$file = getcwd().DIRECTORY_SEPARATOR.'class_test.file.php'; $file = getcwd() . DIRECTORY_SEPARATOR . 'class_test.file.php';
print "GETLINESFROMFILE: $file: ".File::getLinesFromFile($file)."<br>"; print "GETLINESFROMFILE: $file: " . File::getLinesFromFile($file) . "<br>";
// error message // error message
print $basic->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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_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'; $to_crc = 'Some text block';
// static // static
print "S::__CRC32B: $to_crc: ".$hash_class::__crc32b($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(off): $to_crc: " . $hash_class::__sha1short($to_crc) . "<br>";
print "S::__SHA1SHORT(on): $to_crc: ".$hash_class::__sha1short($to_crc, true)."<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::__hash(d): $to_crc: " . $hash_class::__hash($to_crc) . "<br>";
foreach (['adler32', 'fnv132', 'fnv1a32', 'joaat'] as $__hash_c) { 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 // 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 // DEPRECATED
/* print "D/__CRC32B: $to_crc: ".$basic->__crc32b($to_crc)."<br>"; /* 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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -42,21 +45,23 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>'; print '<div><a href="class_test.php">Class Test Master</a></div>';
$string = "Something < = > Other <br> Next line"; $string = "Something < = > Other <br> Next line";
print "HTMLENT: ".Html::htmlent($string).": ".$_html->htmlent($string)."<br>"; print "HTMLENT: " . Html::htmlent($string) . ": " . $_html->htmlent($string) . "<br>";
print "REMOVELB: ".Html::htmlent($string).": ".$_html->removeLB($string)."<br>"; print "REMOVELB: " . Html::htmlent($string) . ": " . $_html->removeLB($string) . "<br>";
$date_str = [2021, 5, 1, 11, 10]; $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 // STATIC
$string = "Something < = > Other <br> Next line"; $string = "Something < = > Other <br> Next line";
print "S::HTMLENT: ".Html::htmlent($string).": ".$html_class::htmlent($string)."<br>"; print "S::HTMLENT: " . Html::htmlent($string) . ": " . $html_class::htmlent($string) . "<br>";
print "S::REMOVELB: ".Html::htmlent($string).": ".$html_class::removeLB($string)."<br>"; print "S::REMOVELB: " . Html::htmlent($string) . ": " . $html_class::removeLB($string) . "<br>";
$date_str = [2021, 5, 1, 11, 10]; $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 // STATIC use
echo "U-S::HTML ENT INT: ".Html::htmlent(5)."<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 STRING: " . Html::htmlent('5<<>') . "<br>";
echo "U-S::HTML ENT NULL: ".Html::htmlent(null)."<br>"; echo "U-S::HTML ENT NULL: " . Html::htmlent(null) . "<br>";
// check convert // check convert
$checked_list = [ $checked_list = [
@@ -66,8 +71,8 @@ $checked_list = [
['foo', ['bar']], ['foo', ['bar']],
]; ];
foreach ($checked_list as $check) { foreach ($checked_list as $check) {
print "CHECKED(0): $check[0]: ".Html::checked($check[1], $check[0])."<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>"; print "CHECKED(1): $check[0]: " . Html::checked($check[1], $check[0], 1) . "<br>";
} }
// magic link creation test // magic link creation test
@@ -80,7 +85,7 @@ $magic_links = [
'http://www.somelink.com/?with=1234 <br>Some Title', 'http://www.somelink.com/?with=1234 <br>Some Title',
]; ];
foreach ($magic_links as $magic_link) { 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 // DEPREACTED
@@ -88,11 +93,20 @@ foreach ($magic_links as $magic_link) {
print "D/HTMLENT: $string: ".$basic->htmlent($string)."<br>"; print "D/HTMLENT: $string: ".$basic->htmlent($string)."<br>";
print "D/REMOVELB: $string: ".$basic->removeLB($string)."<br>"; print "D/REMOVELB: $string: ".$basic->removeLB($string)."<br>";
$date_str = [2021, 5, 1, 11, 10]; $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|'; $magic_link = 'http://www.somelink.com/?with=1234|Some Title|';
print "D/MAGICLINK: ".Html::htmlent($basic->magicLinks($magic_link))."<Br>"; 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 // error message
print $basic->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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_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_width = 250;
$thumb_height = 300; $thumb_height = 300;
// class // class
$image = BASE.LAYOUT.CONTENT_PATH.IMAGES.'no_picture_square.jpg'; $image = BASE . LAYOUT . CONTENT_PATH . IMAGES . 'no_picture_square.jpg';
// rotate image first // rotate image first
$_image->correctImageOrientation($image); $_image->correctImageOrientation($image);
// thumbnail tests // 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 // static
$image = BASE.LAYOUT.CONTENT_PATH.IMAGES.'no_picture.jpg'; $image = BASE . LAYOUT . CONTENT_PATH . IMAGES . 'no_picture.jpg';
// rotate image first // rotate image first
$image_class::correctImageOrientation($image); $image_class::correctImageOrientation($image);
// thumbnail tests // 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>"; echo "U-STATIC VARIOUS:<br>";
// image thumbnail // image thumbnail
@@ -76,17 +83,22 @@ $images = array(
// return mime type ala mimetype // return mime type ala mimetype
$finfo = new finfo(FILEINFO_MIME_TYPE); $finfo = new finfo(FILEINFO_MIME_TYPE);
foreach ($images as $image) { 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); 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 // rotate image first
Image::correctImageOrientation($image); Image::correctImageOrientation($image);
// thumbnail tests // thumbnail tests
echo "<div>".basename($image).": WIDTH: $thumb_width<br><img src=".Image::createThumbnailSimple($image, $thumb_width)."></div>"; echo "<div>" . basename($image) . ": WIDTH: $thumb_width<br><img src="
echo "<div>".basename($image).": HEIGHT: $thumb_height<br><img src=".Image::createThumbnailSimple($image, 0, $thumb_height)."></div>"; . Image::createThumbnailSimple($image, $thumb_width) . "></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) . ": 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 // 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>"; echo "<hr>";
} }
@@ -96,7 +108,8 @@ foreach ($images as $image) {
// rotate image first // rotate image first
$basic->correctImageOrientation($image); $basic->correctImageOrientation($image);
// thumbnail tests // 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 // error message
print $basic->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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -40,24 +43,24 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$json = '{"foo": "bar"}'; $json = '{"foo": "bar"}';
$output = Jason::jsonConvertToArray($json); $output = Jason::jsonConvertToArray($json);
print "S::JSON: $json: ".DgS::printAr($output)."<br>"; print "S::JSON: $json: " . DgS::printAr($output) . "<br>";
print "S::JSON ERROR: ".Jason::jsonGetLastError().": ".Jason::jsonGetLastError(true)."<br>"; print "S::JSON ERROR: " . Jason::jsonGetLastError() . ": " . Jason::jsonGetLastError(true) . "<br>";
$json = '["f: {b"""ar}]'; $json = '["f: {b"""ar}]';
$output = Jason::jsonConvertToArray($json); $output = Jason::jsonConvertToArray($json);
print "S::E-JSON: $json: ".DgS::printAr($output)."<br>"; print "S::E-JSON: $json: " . DgS::printAr($output) . "<br>";
print "S::E-JSON ERROR: ".Jason::jsonGetLastError().": ".Jason::jsonGetLastError(true)."<br>"; print "S::E-JSON ERROR: " . Jason::jsonGetLastError() . ": " . Jason::jsonGetLastError(true) . "<br>";
// direct // direct
$json = '{"direct": "static function call"}'; $json = '{"direct": "static function call"}';
$output = $json_class::jsonConvertToArray($json); $output = $json_class::jsonConvertToArray($json);
print "J/S::JSON: $json: ".DgS::printAr($output)."<br>"; 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 ERROR: " . $json_class::jsonGetLastError() . ": " . $json_class::jsonGetLastError(true) . "<br>";
$json = '["f: {b"""ar}]'; $json = '["f: {b"""ar}]';
$output = $json_class::jsonConvertToArray($json); $output = $json_class::jsonConvertToArray($json);
print "J/S::E-JSON: $json: ".DgS::printAr($output)."<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>"; print "J/S::E-JSON ERROR: " . $json_class::jsonGetLastError() . ": " . $json_class::jsonGetLastError(true) . "<br>";
// DEPRECATE TEST // DEPRECATE TEST
/* $json = '["f: {b"""ar}]'; /* $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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -36,13 +39,13 @@ print "<html><head><title>TEST CLASS: MATH</title><head>";
print "<body>"; print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>'; print '<div><a href="class_test.php">Class Test Master</a></div>';
print "FCEIL: ".$_math->fceil(5.1234567890, 5)."<br>"; print "FCEIL: " . $_math->fceil(5.1234567890, 5) . "<br>";
print "FLOORP: ".$_math->floorp(5123456, -3)."<br>"; print "FLOORP: " . $_math->floorp(5123456, -3) . "<br>";
print "INITNUMERIC: ".$_math->initNumeric('123')."<br>"; print "INITNUMERIC: " . $_math->initNumeric('123') . "<br>";
print "S-FCEIL: ".$math_class::fceil(5.1234567890, 5)."<br>"; print "S-FCEIL: " . $math_class::fceil(5.1234567890, 5) . "<br>";
print "S-FLOORP: ".$math_class::floorp(5123456, -3)."<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') . "<br>";
// DEPRECATED // DEPRECATED
/* print "FCEIL: ".$basic->fceil(5.1234567890, 5)."<br>"; /* 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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -34,22 +37,22 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>'; print '<div><a href="class_test.php">Class Test Master</a></div>';
$mime = 'application/illustrator'; $mime = 'application/illustrator';
print "MIME $mime: ".$_mime->mimeGetAppName($mime)."<br>"; print "MIME $mime: " . $_mime->mimeGetAppName($mime) . "<br>";
$mime = 'fake/mime'; $mime = 'fake/mime';
$_mime->mimeSetAppName($mime, 'This is a 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 test
$mime = 'application/vnd.ms-excel'; $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'); $_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 // static call test
$mime = 'application/x-indesign'; $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'; $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 // DEPRECATED
/* $mime = 'application/illustrator'; /* $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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -40,17 +43,17 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
$password = 'something1234'; $password = 'something1234';
$enc_password = $_password->passwordSet($password); $enc_password = $_password->passwordSet($password);
print "PASSWORD: $password: ".$enc_password."<br>"; print "PASSWORD: $password: " . $enc_password . "<br>";
print "PASSWORD VERIFY: ".(string)$_password->passwordVerify($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 REHASH: " . (string)$_password->passwordRehashCheck($enc_password) . "<br>";
// static verify // static verify
$password = 'othername7890'; $password = 'othername7890';
$enc_password = $password_class::passwordSet($password); $enc_password = $password_class::passwordSet($password);
print "PASSWORD: $password: ".$enc_password."<br>"; print "PASSWORD: $password: " . $enc_password . "<br>";
print "S-PASSWORD VERIFY: ".(string)$password_class::passwordVerify($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 REHASH: " . (string)$password_class::passwordRehashCheck($enc_password) . "<br>";
// direct static // 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 // DEPRECATED
/* $password = 'deprecated4567'; /* $password = 'deprecated4567';

View File

@@ -1,8 +1,11 @@
<?php declare(strict_types=1); <?php // phpcs:ignore warning
/** /**
* @phan-file-suppress PhanTypeSuspiciousStringExpression * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = false; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = true; $DEBUG_ALL = true;
$PRINT_ALL = true; $PRINT_ALL = true;
@@ -56,12 +59,20 @@ 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.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.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.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 "<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 // set + check edit access id
$edit_access_id = 3; $edit_access_id = 3;
if (is_object($login) && isset($login->acl['unit'])) { if (is_object($login) && isset($login->acl['unit'])) {
print "ACL UNIT: ".print_r(array_keys($login->acl['unit']), true)."<br>"; print "ACL UNIT: " . print_r(array_keys($login->acl['unit']), true) . "<br>";
print "ACCESS CHECK: ".(string)$login->loginCheckEditAccess($edit_access_id)."<br>"; print "ACCESS CHECK: " . (string)$login->loginCheckEditAccess($edit_access_id) . "<br>";
if ($login->loginCheckEditAccess($edit_access_id)) { if ($login->loginCheckEditAccess($edit_access_id)) {
$basic->edit_access_id = $edit_access_id; $basic->edit_access_id = $edit_access_id;
} else { } else {
@@ -74,7 +85,8 @@ if (is_object($login) && isset($login->acl['unit'])) {
// $basic->log->debug('SESSION', \CoreLibs\Debug\Support::printAr($_SESSION)); // $basic->log->debug('SESSION', \CoreLibs\Debug\Support::printAr($_SESSION));
print '<form method="post" name="loginlogout">'; 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 '<input type="hidden" name="login_logout" value="">';
print '</form>'; print '</form>';
@@ -82,28 +94,49 @@ print '</form>';
foreach (['on', 'off'] as $flag) { foreach (['on', 'off'] as $flag) {
foreach (['debug', 'echo', 'print'] as $type) { foreach (['debug', 'echo', 'print'] as $type) {
$prefix = $flag == 'off' ? 'NOT ' : ''; $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) { 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'); $basic->log->debug('SOME MARK', 'Some error output');
// INTERNAL SET // INTERNAL SET
print "EDIT ACCESS ID: ".$basic->edit_access_id."<br>"; print "EDIT ACCESS ID: " . $basic->edit_access_id . "<br>";
if (is_object($login)) { if (is_object($login)) {
// print "ACL: <br>".$basic->print_ar($login->acl)."<br>"; // 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>";
// 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>"; // print "DEFAULT ACL: <br>".$basic->print_ar($result)."<br>";
// DEPRICATED CALL // DEPRICATED CALL
// $basic->adbSetACL($login->acl); // $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 error messages
// print $login->log->printErrorMsg(); // print $login->log->printErrorMsg();
print $basic->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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -43,17 +46,18 @@ $min_version_ss = '7.1';
$min_version = '7.1.0'; $min_version = '7.1.0';
$max_version = '7.3.1'; $max_version = '7.3.1';
// class // class
print "MIN: $min_version: ".(string)$_phpv->checkPHPVersion($min_version)."<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/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/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/SS: $min_version_ss: " . (string)$_phpv->checkPHPVersion($min_version_ss) . "<br>";
// static // static
print "S::MIN: $min_version: ".(string)$phpv_class::checkPHPVersion($min_version)."<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/MAX: $min_version/$max_version: "
print "S::MIN/S: $min_version_s: ".(string)$phpv_class::checkPHPVersion($min_version_s)."<br>"; . (string)$phpv_class::checkPHPVersion($min_version, $max_version) . "<br>";
print "S::MIN/SS: $min_version_ss: ".(string)$phpv_class::checkPHPVersion($min_version_ss)."<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 // 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 // DEPRECATED
// print "MIN: $min_version: ".(string)$basic->checkPHPVersion($min_version)."<br>"; // 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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_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 = 10;
$key_length_b = 5; $key_length_b = 5;
print "S::RANDOMKEYGEN(auto): ".RandomKey::randomKeyGen()."<br>"; print "S::RANDOMKEYGEN(auto): " . RandomKey::randomKeyGen() . "<br>";
print "S::SETRANDOMKEYLENGTH($key_length): ".RandomKey::setRandomKeyLength($key_length)."<br>"; print "S::SETRANDOMKEYLENGTH($key_length): " . RandomKey::setRandomKeyLength($key_length) . "<br>";
print "S::RANDOMKEYGEN($key_length): ".RandomKey::randomKeyGen()."<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_b): " . RandomKey::randomKeyGen($key_length_b) . "<br>";
print "S::RANDOMKEYGEN($key_length): ".RandomKey::randomKeyGen()."<br>"; print "S::RANDOMKEYGEN($key_length): " . RandomKey::randomKeyGen() . "<br>";
$_array= new CoreLibs\Create\RandomKey(); $_array = new CoreLibs\Create\RandomKey();
print "C->RANDOMKEYGEN(auto): ".$_array->randomKeyGen()."<br>"; print "C->RANDOMKEYGEN(auto): " . $_array->randomKeyGen() . "<br>";
// DEPRECATED // DEPRECATED
// print "D\RANDOMKEYGEN(auto): ".$basic->randomKeyGen()."<br>"; // 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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -36,13 +39,13 @@ print '<div><a href="class_test.php">Class Test Master</a></div>';
RunningTime::hrRunningTime(); RunningTime::hrRunningTime();
RunningTime::runningTime(); RunningTime::runningTime();
echo "RANDOM KEY [50]: ".\CoreLibs\Create\RandomKey::randomKeyGen(50)."<br>"; echo "RANDOM KEY [50]: " . \CoreLibs\Create\RandomKey::randomKeyGen(50) . "<br>";
echo "TIMED [hr]: ".RunningTime::hrRunningTime()."<br>"; echo "TIMED [hr]: " . RunningTime::hrRunningTime() . "<br>";
echo "TIMED [def]: ".RunningTime::runningTime()."<br>"; echo "TIMED [def]: " . RunningTime::runningTime() . "<br>";
echo "TIMED [string]: ".RunningTime::runningTimeString()."<br>"; echo "TIMED [string]: " . RunningTime::runningTimeString() . "<br>";
RunningTime::hrRunningTime(); RunningTime::hrRunningTime();
echo "RANDOM KEY [default]: ".\CoreLibs\Create\RandomKey::randomKeyGen()."<br>"; echo "RANDOM KEY [default]: " . \CoreLibs\Create\RandomKey::randomKeyGen() . "<br>";
echo "TIMED [hr]: ".RunningTime::hrRunningTime()."<br>"; echo "TIMED [hr]: " . RunningTime::hrRunningTime() . "<br>";
// DEPRECATED // DEPRECATED
/* $basic->hrRunningTime(); /* $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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -35,13 +38,15 @@ print "<html><head><title>TEST CLASS: SYSTEM</title><head>";
print "<body>"; print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>'; print '<div><a href="class_test.php">Class Test Master</a></div>';
print "GETHOSTNAME: ".DgS::printAr(System::getHostName())."<br>"; print "GETHOSTNAME: " . DgS::printAr(System::getHostName()) . "<br>";
print "GETPAGENAME(0): ".System::getPageName()."<br>"; print "GETPAGENAME(0): " . System::getPageName() . "<br>";
print "GETPAGENAME(1): ".System::getPageName(1)."<br>"; print "GETPAGENAME(1): " . System::getPageName(1) . "<br>";
print "GETPAGENAME(2): ".System::getPageName(2)."<br>"; print "GETPAGENAME(2): " . System::getPageName(2) . "<br>";
print "GETPAGENAMEARRAY: " . \CoreLibs\Debug\Support::printAr(System::getPageNameArray()) . "<br>";
// seting errro codes file upload // seting errro codes file upload
print "FILEUPLOADERRORMESSAGE(): ".System::fileUploadErrorMessage(-1)."<br>"; print "FILEUPLOADERRORMESSAGE(): " . System::fileUploadErrorMessage(-1) . "<br>";
print "FILEUPLOADERRORMESSAGE(UPLOAD_ERR_CANT_WRITE): ".System::fileUploadErrorMessage(UPLOAD_ERR_CANT_WRITE)."<br>"; print "FILEUPLOADERRORMESSAGE(UPLOAD_ERR_CANT_WRITE): "
. System::fileUploadErrorMessage(UPLOAD_ERR_CANT_WRITE) . "<br>";
// error message // error message
print $basic->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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_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 = 'test_form_token';
$token_id = $_token->setFormToken($token); $token_id = $_token->setFormToken($token);
print "TOKEN: $token: (ID) ".$token_id." => (S) ".$_SESSION[$token]."<br>"; print "TOKEN: $token: (ID) " . $token_id . " => (S) " . $_SESSION[$token] . "<br>";
print "VALIDATE: $token: ".(string)$_token->validateFormToken($token_id, $token)."<br>"; print "VALIDATE: $token: " . (string)$_token->validateFormToken($token_id, $token) . "<br>";
$token = 'test_form_token_static'; $token = 'test_form_token_static';
$token_id = $token_class::setFormToken($token); $token_id = $token_class::setFormToken($token);
print "S-TOKEN: $token: (ID) ".$token_id." => (S) ".$_SESSION[$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>"; print "S-VALIDATE: $token: " . (string)$token_class::validateFormToken($token_id, $token) . "<br>";
// DEPRECATED // DEPRECATED
/* $token = 'test_form_token_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 * @phan-file-suppress PhanTypeSuspiciousStringExpression
*/ */
declare(strict_types=1);
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
@@ -35,15 +38,15 @@ print "<body>";
print '<div><a href="class_test.php">Class Test Master</a></div>'; print '<div><a href="class_test.php">Class Test Master</a></div>';
// class // class
print "UUIDV4: ".$_uids->uuidv4()."<br>"; print "UUIDV4: " . $_uids->uuidv4() . "<br>";
print "UNIQID (d): ".$_uids->uniqId()."<br>"; print "UNIQID (d): " . $_uids->uniqId() . "<br>";
print "UNIQID (md5): ".$_uids->uniqId('md5')."<br>"; print "UNIQID (md5): " . $_uids->uniqId('md5') . "<br>";
print "UNIQID (sha256): ".$_uids->uniqId('sha256')."<br>"; print "UNIQID (sha256): " . $_uids->uniqId('sha256') . "<br>";
// statc // statc
print "S::UUIDV4: ".$uids_class::uuidv4()."<br>"; print "S::UUIDV4: " . $uids_class::uuidv4() . "<br>";
print "S::UNIQID (d): ".$uids_class::uniqId()."<br>"; print "S::UNIQID (d): " . $uids_class::uniqId() . "<br>";
print "S::UNIQID (md5): ".$uids_class::uniqId('md5')."<br>"; print "S::UNIQID (md5): " . $uids_class::uniqId('md5') . "<br>";
print "S::UNIQID (sha256): ".$uids_class::uniqId('sha256')."<br>"; print "S::UNIQID (sha256): " . $uids_class::uniqId('sha256') . "<br>";
// DEPRECATED // DEPRECATED
/* print "D/UUIDV4: ".$basic->uuidv4()."<br>"; /* print "D/UUIDV4: ".$basic->uuidv4()."<br>";
print "/DUNIQID (d): ".$basic->uniqId()."<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_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
@@ -11,8 +13,8 @@ if ($DEBUG_ALL) {
// sample config // sample config
require 'config.php'; require 'config.php';
echo "FILE: ".BASE.LIB."Error.Handling.php<br>"; echo "FILE: " . BASE . LIB . "Error.Handling.php<br>";
require(BASE.LIB."Error.Handling.php"); require(BASE . LIB . "Error.Handling.php");
if ($var) { if ($var) {
echo "OUT<br>"; 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 'config.php';
require BASE.INCLUDES.'admin_header.php'; require BASE . INCLUDES . 'admin_header.php';
// $DATA['foo'] = 'bar'; // $DATA['foo'] = 'bar';
// $messages['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) // test for qqFileUploader (AJAX side)
$allowedExtensions = array ('csv', 'zip', 'jpg', 'pdf', 'bz2'); $allowedExtensions = array ('csv', 'zip', 'jpg', 'pdf', 'bz2');
$sizeLimit = $MAX_UPLOAD_SIZE; // as set in php ini $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); $uploader = new FileUpload\qqFileUploader($allowedExtensions, $sizeLimit);
// either in post or get // 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']; $_task_uid = $_POST['task_uid'] ? $_POST['task_uid'] : $_GET['task_uid'];
$get_post['start'] = microtime(true); $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); $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 // set file name
$get_post['filename'] = $uploader->uploadFileName; $get_post['filename'] = $uploader->uploadFileName;

View File

@@ -10,7 +10,7 @@ require 'config.php';
$base = new CoreLibs\Basic(); $base = new CoreLibs\Basic();
// set max upload size // set max upload size
$MAX_UPLOAD_SIZE = $base->StringByteFormat(ini_get('upload_max_filesize')); $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 // 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__

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1); <?php // phpcs:ignore warning
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2018/10/11 * CREATED: 2018/10/11
@@ -7,13 +8,22 @@
* HISTORY: * 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 search, start with 0, got down each level __DIR__ has, if nothing found -> bail
$CONFIG_PATH_PREFIX = ''; $CONFIG_PATH_PREFIX = '';
for ($dir_pos = 0, $dir_max = count(explode(DIRECTORY_SEPARATOR, __DIR__)); $dir_pos <= $dir_max; $dir_pos ++) { for ($dir_pos = 0, $dir_max = count(explode(DIRECTORY_SEPARATOR, __DIR__)); $dir_pos <= $dir_max; $dir_pos++) {
$CONFIG_PATH_PREFIX .= '..'.DIRECTORY_SEPARATOR; $CONFIG_PATH_PREFIX .= '..' . DIRECTORY_SEPARATOR;
if (file_exists($CONFIG_PATH_PREFIX.CONFIG_PATH.'config.master.php')) { if (file_exists($CONFIG_PATH_PREFIX . CONFIG_PATH . 'config.master.php')) {
require $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; break;
} }
} }
@@ -23,8 +33,8 @@ if (!defined('DS')) {
} }
// find trigger name "admin/" or "frontend/" in the getcwd() folder // find trigger name "admin/" or "frontend/" in the getcwd() folder
foreach (['admin', 'frontend'] as $folder) { foreach (['admin', 'frontend'] as $folder) {
if (strstr(getcwd(), DS.$folder)) { if (strstr(getcwd(), DS . $folder)) {
define('CONTENT_PATH', $folder.DS); define('CONTENT_PATH', $folder . DS);
break; 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,5 @@
<?php declare(strict_types=1); <?php
declare(strict_types=1);
require 'config.php'; require 'config.php';

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1); <?php
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2005/07/12 * CREATED: 2005/07/12
@@ -7,11 +8,16 @@
* HISTORY: * HISTORY:
*********************************************************************/ *********************************************************************/
declare(strict_types=1);
/****** /******
NOTE THAT THIS INCLUDE IS OBSOLETE NOTE THAT THIS INCLUDE IS OBSOLETE
USE THE BELOW FUNCTION CALL IN THE SCRIPT ITSELF 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(); $smarty->setSmartyVarsAdmin();
// __END__ // __END__

View File

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

View File

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

View File

@@ -1,6 +1,8 @@
<?php declare(strict_types=1); <?php
$edit_languages=[ declare(strict_types=1);
$edit_languages = [
'table_array' => [ 'table_array' => [
'edit_language_id' => [ 'edit_language_id' => [
'value' => $GLOBALS['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 = [ $edit_menu_group = [
'table_array' => [ 'table_array' => [

View File

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

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1); <?php
declare(strict_types=1);
$edit_users = [ $edit_users = [
'table_array' => [ 'table_array' => [
@@ -34,7 +36,8 @@ $edit_users = [
'password_change_interval' => [ 'password_change_interval' => [
'value' => $GLOBALS['password_change_interval'] ?? '', 'value' => $GLOBALS['password_change_interval'] ?? '',
'output_name' => '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', 'type' => 'text',
'interval' => 1, // interval needs NULL write for empty 'interval' => 1, // interval needs NULL write for empty
'size' => 5, // make it 5 chars long 'size' => 5, // make it 5 chars long
@@ -184,7 +187,8 @@ $edit_users = [
'cols' => 60 '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', 'table_name' => 'edit_user',
'show_fields' => [ 'show_fields' => [
[ [

View File

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

View File

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

View File

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

View File

View File

@@ -3,6 +3,8 @@
/* jshint esversion: 6 */ /* jshint esversion: 6 */
/* global i18n */
// debug set // debug set
/*var FRONTEND_DEBUG = false; /*var FRONTEND_DEBUG = false;
var DEBUG = true; var DEBUG = true;
@@ -22,7 +24,8 @@ var GL_OB_BASE = 30;
* @param {String} winName window name * @param {String} winName window name
* @param {Object} features popup features * @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 = window.open(theURL, winName, features);
winName.focus(); winName.focus();
} }
@@ -31,7 +34,8 @@ function pop(theURL, winName, features) {
* automatically resize a text area based on the amount of lines in it * automatically resize a text area based on the amount of lines in it
* @param {[string} ta_id element id * @param {[string} ta_id element id
*/ */
function expandTA(ta_id) { function expandTA(ta_id) // eslint-disable-line no-unused-vars
{
var ta; var ta;
// if a string comes, its a get by id, else use it as an element pass on // if a string comes, its a get by id, else use it as an element pass on
if (!ta_id.length) { if (!ta_id.length) {
@@ -40,7 +44,7 @@ function expandTA(ta_id) {
ta = document.getElementById(ta_id); ta = document.getElementById(ta_id);
} }
var maxChars = ta.cols; var maxChars = ta.cols;
var theRows = ta.value.split("\n"); var theRows = ta.value.split('\n');
var numNewRows = 0; var numNewRows = 0;
for ( var i = 0; i < theRows.length; i++ ) { 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 {Number} [duration=500] animation time, default 500ms
* @param {String} [base='body,html'] base element for offset scroll * @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 { try {
if ($('#' + element).length) { if ($('#' + element).length) {
@@ -190,7 +194,7 @@ if (Number.prototype.round) {
* @param {Number} x number to be formated * @param {Number} x number to be formated
* @return {String} formatted with , in thousands * @return {String} formatted with , in thousands
*/ */
function numberWithCommas(x) function numberWithCommas(x) // eslint-disable-line no-unused-vars
{ {
var parts = x.toString().split('.'); var parts = x.toString().split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
@@ -202,7 +206,7 @@ function numberWithCommas(x)
* @param {String} string any string * @param {String} string any string
* @return {String} string with <br> * @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>'); return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
} }
@@ -214,14 +218,14 @@ function convertLBtoBR(string)
*/ */
if (!String.prototype.escapeHTML) { if (!String.prototype.escapeHTML) {
String.prototype.escapeHTML = function() { String.prototype.escapeHTML = function() {
return this.replace(/[&<>"'\/]/g, function (s) { return this.replace(/[&<>"'/]/g, function (s) {
var entityMap = { var entityMap = {
"&": "&amp;", '&': '&amp;',
"<": "&lt;", '<': '&lt;',
">": "&gt;", '>': '&gt;',
'"': '&quot;', '"': '&quot;',
"'": '&#39;', '\'': '&#39;',
"/": '&#x2F;' '/': '&#x2F;'
}; };
return entityMap[s]; return entityMap[s];
@@ -238,12 +242,12 @@ if (!String.prototype.unescapeHTML) {
String.prototype.unescapeHTML = function() { String.prototype.unescapeHTML = function() {
return this.replace(/&[#\w]+;/g, function (s) { return this.replace(/&[#\w]+;/g, function (s) {
var entityMap = { var entityMap = {
"&amp;": "&", '&amp;': '&',
"&lt;": "<", '&lt;': '<',
"&gt;": ">", '&gt;': '>',
'&quot;': '"', '&quot;': '"',
'&#39;': "'", '&#39;': '\'',
'&#x2F;': "/" '&#x2F;': '/'
}; };
return entityMap[s]; return entityMap[s];
@@ -255,7 +259,7 @@ if (!String.prototype.unescapeHTML) {
* returns current timestamp (unix timestamp) * returns current timestamp (unix timestamp)
* @return {Number} timestamp (in milliseconds) * @return {Number} timestamp (in milliseconds)
*/ */
function getTimestamp() function getTimestamp() // eslint-disable-line no-unused-vars
{ {
var date = new Date(); var date = new Date();
return date.getTime(); return date.getTime();
@@ -278,7 +282,7 @@ function dec2hex(dec)
* @param {Number} len length of unique id string * @param {Number} len length of unique id string
* @return {String} random string in length of len * @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); var arr = new Uint8Array((len || 40) / 2);
(window.crypto || window.msCrypto).getRandomValues(arr); (window.crypto || window.msCrypto).getRandomValues(arr);
@@ -291,7 +295,7 @@ function generateId(len)
* after many runs it will create duplicates * after many runs it will create duplicates
* @return {String} not true random string * @return {String} not true random string
*/ */
function randomIdF() function randomIdF() // eslint-disable-line no-unused-vars
{ {
return Math.random().toString(36).substring(2); return Math.random().toString(36).substring(2);
} }
@@ -301,7 +305,7 @@ function randomIdF()
* @param {string} name Name of function to check if exists * @param {string} name Name of function to check if exists
* @return {Boolean} true/false * @return {Boolean} true/false
*/ */
function isFunction(name) function isFunction(name) // eslint-disable-line no-unused-vars
{ {
if (typeof window[name] !== 'undefined' && if (typeof window[name] !== 'undefined' &&
typeof window[name] === 'function') { typeof window[name] === 'function') {
@@ -320,7 +324,7 @@ function isFunction(name)
* hidden next are all the arguments * hidden next are all the arguments
* @return {mixed} Return values from functon * @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 args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split('.'); var namespaces = functionName.split('.');
@@ -362,7 +366,7 @@ function getObjectCount(object)
*/ */
function keyInObject(key, 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) * @param {Mixed} value any value (String, Number, etc)
* @return {String} the key found for the first matching value * @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(key => object[key] === value);
// return Object.keys(object).find(function (key) { // return Object.keys(object).find(function (key) {
@@ -385,9 +389,9 @@ function getKeyByValue(object, value)
* @param {Mixed} value any value (String, Number, etc) * @param {Mixed} value any value (String, Number, etc)
* @return {Boolean} true on value found, false on not found * @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.keys(object).find(function (key) {
// return object[key] === value; // return object[key] === value;
// }) ? true : false; // }) ? true : false;
@@ -403,7 +407,7 @@ function valueInObject(object, value)
function deepCopyFunction(inObject) function deepCopyFunction(inObject)
{ {
var outObject, value, key; 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 return inObject; // Return the value if inObject is not an object
} }
// Create an array or object to hold the values // Create an array or object to hold the values
@@ -434,14 +438,15 @@ function exists(id)
* @param {Number} bytes bytes in int * @param {Number} bytes bytes in int
* @return {String} string in GB/MB/KB * @return {String} string in GB/MB/KB
*/ */
function formatBytes(bytes) function formatBytes(bytes) // eslint-disable-line no-unused-vars
{ {
var i = -1; var i = -1;
do { do {
bytes = bytes / 1024; bytes = bytes / 1024;
i++; i++;
} while (bytes > 99); } 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 * @param {Number} bytes bytes in int
* @return {String} string in GB/MB/KB * @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 i = Math.floor(Math.log(bytes) / Math.log(1024));
var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; 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 * @param {String|Number} bytes Any string with B/K/M/etc
* @return {String|Number} A byte number, or original string as is * @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 anything not string return
if (!(typeof bytes === 'string' || bytes instanceof String)) { if (!(typeof bytes === 'string' || bytes instanceof String)) {
@@ -536,7 +541,7 @@ function errorCatch(err)
* default empty. for console.log * default empty. for console.log
* @param {Boolean} [overlay=true] override the auto hide/show over the overlay div block * @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')) { if ($('#indicator').is(':visible')) {
actionIndicatorHide(loc, overlay); actionIndicatorHide(loc, overlay);
@@ -613,7 +618,7 @@ function overlayBoxHide()
/** /**
* position the overlay block box and shows it * position the overlay block box and shows it
*/ */
function setOverlayBox() function setOverlayBox() // eslint-disable-line no-unused-vars
{ {
if (!$('#overlayBox').is(':visible')) { if (!$('#overlayBox').is(':visible')) {
$('#overlayBox').show(); $('#overlayBox').show();
@@ -623,7 +628,7 @@ function setOverlayBox()
/** /**
* opposite of set, always hides overlay box * opposite of set, always hides overlay box
*/ */
function hideOverlayBox() function hideOverlayBox() // eslint-disable-line no-unused-vars
{ {
if ($('#overlayBox').is(':visible')) { if ($('#overlayBox').is(':visible')) {
$('#overlayBox').hide(); $('#overlayBox').hide();
@@ -633,7 +638,7 @@ function hideOverlayBox()
/** /**
* the abort call, clears the action box and hides it and the overlay box * 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').html('');
$('#actionBox').hide(); $('#actionBox').hide();
@@ -654,7 +659,7 @@ function ClearCall()
* - indicator is page centered * - indicator is page centered
* @param {String} loc ID string, only used for console log * @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); // console.log('Indicator: SHOW [%s]', loc);
// check if indicator element exists // check if indicator element exists
@@ -692,7 +697,7 @@ function showActionIndicator(loc)
* is set to this value * is set to this value
* @param {String} loc ID string, only used for console log * @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); // console.log('Indicator: HIDE [%s]', loc);
// check if indicator is visible // check if indicator is visible
@@ -732,7 +737,7 @@ function checkOverlayExists()
* if visible, add +1 to the GL_OB_S variable and * if visible, add +1 to the GL_OB_S variable and
* up zIndex by this value * 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); // console.log('SHOW overlaybox: %s', GL_OB_S);
// if overlay box is not visible show and set zIndex to 0 // 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 * only for single action box
*/ */
function clearCallActionBox() function clearCallActionBox() // eslint-disable-line no-unused-vars
{ {
$('#actionBox').html(''); $('#actionBox').html('');
$('#actionBox').hide(); $('#actionBox').hide();
@@ -872,7 +877,7 @@ function aelx(base, ...attach)
* @param {Array} attach array of objects to attach * @param {Array} attach array of objects to attach
* @return {Object} "none", technically there is no return needed, global 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 ++) { for (var i = 0; i < attach.length; i ++) {
// base.sub.push(Object.assign({}, attach[i])); // base.sub.push(Object.assign({}, attach[i]));
@@ -886,7 +891,7 @@ function aelxar(base, attach)
* @param {Object} base cel created element * @param {Object} base cel created element
* @return {Object} returns reset base element * @return {Object} returns reset base element
*/ */
function rel(base) function rel(base) // eslint-disable-line no-unused-vars
{ {
base.sub = []; base.sub = [];
return base; return base;
@@ -930,7 +935,7 @@ function acssel(_element, css)
* @param {String} acss style to add (name) * @param {String} acss style to add (name)
* @return {Object} returns full element * @return {Object} returns full element
*/ */
function scssel(_element, rcss, acss) function scssel(_element, rcss, acss) // eslint-disable-line no-unused-vars
{ {
rcssel(_element, rcss); rcssel(_element, rcss);
acssel(_element, acss); acssel(_element, acss);
@@ -1008,7 +1013,7 @@ function phfo(tree)
* @param {Array} list Array of cel created objects * @param {Array} list Array of cel created objects
* @return {String} HTML String * @return {String} HTML String
*/ */
function phfa(list) function phfa(list) // eslint-disable-line no-unused-vars
{ {
var content = []; var content = [];
for (var i = 0; i < list.length; i ++) { for (var i = 0; i < list.length; i ++) {
@@ -1034,7 +1039,7 @@ function phfa(list)
* 'values' all others are ignored * 'values' all others are ignored
* @return {String} html with build options block * @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 // wrapper to new call
return html_options_block(name, data, selected, false, options_only, return_string, sort); 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 element_option;
var data_list = []; // for sorted output var data_list = []; // for sorted output
var value; var value;
var options = {};
// var option; // var option;
if (multiple > 0) { if (multiple > 0) {
select_options.multiple = ''; 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' * @param {String} [sort=''] if empty as is, else allowed 'keys', 'values'
* all others are ignored * 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 element_option;
var option_selected; var option_selected;
@@ -1186,21 +1192,26 @@ function html_options_refill(name, data, sort = '')
* or empty for none * or empty for none
* @return {Object|String} parameter entry list * @return {Object|String} parameter entry list
*/ */
function parseQueryString(query = '', return_key = '') { function parseQueryString(query = '', return_key = '') // eslint-disable-line no-unused-vars
{
if (!query) { if (!query) {
query = window.location.search.substring(1); query = window.location.search.substring(1);
} }
var vars = query.split("&"); var vars = query.split('&');
var query_string = {}; var query_string = {};
for (var i = 0; i < vars.length; i++) { for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("="); var pair = vars[i].split('=');
var key = decodeURIComponent(pair[0]); var key = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]); var value = decodeURIComponent(pair[1]);
// skip over run if there is nothing
if (!key || value === 'undefined') {
continue;
}
// If first entry with this name // If first entry with this name
if (typeof query_string[key] === "undefined") { if (typeof query_string[key] === 'undefined') {
query_string[key] = decodeURIComponent(value); query_string[key] = decodeURIComponent(value);
// If second entry with this name // 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)]; var arr = [query_string[key], decodeURIComponent(value)];
query_string[key] = arr; query_string[key] = arr;
// If third or later entry with this name // If third or later entry with this name
@@ -1220,26 +1231,59 @@ function parseQueryString(query = '', return_key = '') {
} }
/** /**
* searchs the current url for a parameter * searches query parameters for entry and returns data either as string or array
* @param {String} key uid key to get data for * if no search is given the whole parameters are returned as an object
* @return {String} value for the key or '' for not found * 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); if (!query) {
var param = url.searchParams.get(key); query = window.location.href;
if (param) {
return param;
} else {
return '';
} }
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 // *** MASTER logout call
/** /**
* submits basic data for form logout * submits basic data for form logout
*/ */
function loginLogout() function loginLogout() // eslint-disable-line no-unused-vars
{ {
const form = document.createElement('form'); const form = document.createElement('form');
form.method = 'post'; form.method = 'post';
@@ -1259,7 +1303,7 @@ function loginLogout()
* if not set mainHeader is assumed * if not set mainHeader is assumed
* this is the target div for the "loginRow" * 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 header does not exist, we do nothing
if (exists(header_id)) { if (exists(header_id)) {
@@ -1293,7 +1337,8 @@ function createLoginRow(login_string, header_id = 'mainHeader')
* if not set mainHeader is assumed * if not set mainHeader is assumed
* this is the target div for the "menuRow" * 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 // must be an object
if (isObject(nav_menu) && getObjectCount(nav_menu) > 1) { if (isObject(nav_menu) && getObjectCount(nav_menu) > 1) {
// do we have more than one entry, if not, do not show (single page) // 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 * AUTHOR: Clemens Schwaighofer
* CREATED: 2000/06/01 * CREATED: 2000/06/01
@@ -32,16 +33,22 @@
* *
* HISTORY: * HISTORY:
* 2010/12/21 (cs) merge back password change interface * 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 * 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/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/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/07/01 (cs) start adepting login class to new edit interface layout
* 2005/03/31 (cs) fixed the class call with all debug vars * 2005/03/31 (cs) fixed the class call with all debug vars
* 2004/11/17 (cs) unused var cleanup * 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) rewrite login so it uses a template and not just plain html.
* 2004/11/16 (cs) removed the mobile html part from login * 2004/09/30 (cs) layout fix * prepare it, so it will be able to use external stuff later
* 2003-11-11: if user has debug 1 unset memlimit, because there can be serious problems with the query logging * (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 * 2003-06-12: added flag to PAGES array
* changed the get vars from GLOBALS to _POST * changed the get vars from GLOBALS to _POST
* changed the session registration. no more GLOBAL vars are registered * changed the session registration. no more GLOBAL vars are registered
@@ -57,6 +64,8 @@
* 2000-06-01: created basic idea and functions * 2000-06-01: created basic idea and functions
*********************************************************************/ *********************************************************************/
declare(strict_types=1);
namespace CoreLibs\ACL; namespace CoreLibs\ACL;
use CoreLibs\Check\Password; use CoreLibs\Check\Password;
@@ -64,16 +73,19 @@ use CoreLibs\Check\Password;
class Login extends \CoreLibs\DB\IO class Login extends \CoreLibs\DB\IO
{ {
private $euid; // the user id var 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
private $permission_okay = false;
public $login; // pressed login public $login; // pressed login
private $action; // master action command private $action; // master action command
private $username; // login name private $username; // login name
private $password; // login password private $password; // login password
private $logout; // logout button 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
private $login_error = 0;
private $password_change = false; // if this is set to true, the user can change passwords private $password_change = false; // if this is set to true, the user can change passwords
private $password_change_ok = false; // password change was successful 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 // can we reset password and mail to user with new password set screen
private $password_forgot = false;
private $password_forgot_ok = false; // password forgot mail send ok private $password_forgot_ok = false; // password forgot mail send ok
private $change_password; private $change_password;
private $pw_username; private $pw_username;
@@ -161,7 +173,9 @@ class Login extends \CoreLibs\DB\IO
$this->l = new \CoreLibs\Language\L10n($lang); $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 // 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 // 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) { if (defined('LOGIN_DB_SCHEMA') && LOGIN_DB_SCHEMA) {
$SCHEMA = LOGIN_DB_SCHEMA; $SCHEMA = LOGIN_DB_SCHEMA;
} elseif (isset($db_config['db_schema']) && $db_config['db_schema']) { } elseif (isset($db_config['db_schema']) && $db_config['db_schema']) {
@@ -173,9 +187,10 @@ class Login extends \CoreLibs\DB\IO
} }
// set schema if schema differs to schema set in db conneciton // set schema if schema differs to schema set in db conneciton
if ($this->dbGetSchema() && $this->dbGetSchema() != $SCHEMA) { 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 // get login vars, are so, can't be changed
// prepare // prepare
// pass on vars to Object vars // pass on vars to Object vars
@@ -303,21 +318,24 @@ class Login extends \CoreLibs\DB\IO
$password = $this->password; $password = $this->password;
} }
// first, errors on missing encryption // 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("/^\\$1\\$/", $hash) && CRYPT_MD5 != 1) ||
(preg_match("/^\\$[0-9A-Za-z.]{12}$/", $hash) && CRYPT_STD_DES != 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 means password cannot be decrypted because of missing crypt methods
$this->login_error = 9999; $this->login_error = 9999;
$password_ok = false; $password_ok = false;
} elseif (preg_match("/^\\$2y\\$/", $hash) && } elseif (
preg_match("/^\\$2y\\$/", $hash) &&
!Password::passwordVerify($password, $hash) !Password::passwordVerify($password, $hash)
) { ) {
// this is the new password hash methid, is only $2y$ // this is the new password hash methid, is only $2y$
// all others are not valid anymore // all others are not valid anymore
$this->login_error = 1013; $this->login_error = 1013;
$password_ok = false; $password_ok = false;
} elseif (!preg_match("/^\\$2(a|y)\\$/", $hash) && } elseif (
!preg_match("/^\\$2(a|y)\\$/", $hash) &&
!preg_match("/^\\$1\\$/", $hash) && !preg_match("/^\\$1\\$/", $hash) &&
!preg_match("/^\\$[0-9A-Za-z.]{12}$/", $hash) && !preg_match("/^\\$[0-9A-Za-z.]{12}$/", $hash) &&
$hash != $password $hash != $password
@@ -344,30 +362,37 @@ class Login extends \CoreLibs\DB\IO
$this->login_error = 102; $this->login_error = 102;
} else { } else {
// we have to get the themes in here too // 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 = "SELECT eu.edit_user_id, username, password, eu.edit_group_id, "
$q .= "eu.login_error_count, eu.login_error_date_last, eu.login_error_date_first, eu.strict, eu.locked, "; . "eg.name AS edit_group_name, admin, "
$q .= "debug, db_debug, "; . "eu.login_error_count, eu.login_error_date_last, "
$q .= "eareu.level AS user_level, eareu.type AS user_type, "; . "eu.login_error_date_first, eu.strict, eu.locked, "
$q .= "eareg.level AS group_level, eareg.type AS group_type, "; . "debug, db_debug, "
$q .= "eu.enabled, el.short_name AS lang_short, el.iso_name AS lang_iso, first.header_color AS first_header_color, "; . "eareu.level AS user_level, eareu.type AS user_type, "
$q .= "second.header_color AS second_header_color, second.template "; . "eareg.level AS group_level, eareg.type AS group_type, "
$q .= "FROM edit_user eu "; . "eu.enabled, el.short_name AS lang_short, el.iso_name AS lang_iso, "
$q .= "LEFT JOIN edit_scheme second ON (second.edit_scheme_id = eu.edit_scheme_id AND second.enabled = 1), "; . "first.header_color AS first_header_color, "
$q .= "edit_language el, edit_group eg, "; . "second.header_color AS second_header_color, second.template "
$q .= "edit_access_right eareu, "; . "FROM edit_user eu "
$q .= "edit_access_right eareg, "; . "LEFT JOIN edit_scheme second ON "
$q .= "edit_scheme first "; . "(second.edit_scheme_id = eu.edit_scheme_id AND second.enabled = 1), "
$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 "; . "edit_language el, edit_group eg, "
$q .= "eu.edit_access_right_id = eareu.edit_access_right_id AND "; . "edit_access_right eareu, "
$q .= "eg.edit_access_right_id = eareg.edit_access_right_id AND "; . "edit_access_right eareg, "
// password match is done in script, against old plain or new blowfish encypted . "edit_scheme first "
$q .= "(LOWER(username) = '".$this->dbEscapeString(strtolower($this->username))."') "; . "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); $res = $this->dbReturn($q);
// username is wrong, but we throw for wrong username and wrong password the same error // username is wrong, but we throw for wrong username and wrong password the same error
if (!$this->cursor_ext[md5($q)]['num_rows']) { if (!$this->cursor_ext[md5($q)]['num_rows']) {
$this->login_error = 1010; $this->login_error = 1010;
} else { } 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 // check flow
// - user is enabled // - user is enabled
@@ -386,10 +411,14 @@ class Login extends \CoreLibs\DB\IO
// none to be set, set in login password check // none to be set, set in login password check
} else { } else {
// check if the current password is an invalid hash and do a rehash and set password // 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'])) { if (Password::passwordRehashCheck($res['password'])) {
// update password hash to new one now // 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); $this->dbExec($q);
} }
// normal user processing // normal user processing
@@ -410,31 +439,36 @@ class Login extends \CoreLibs\DB\IO
$_SESSION['GROUP_ACL_TYPE'] = $res['group_type']; $_SESSION['GROUP_ACL_TYPE'] = $res['group_type'];
// deprecated TEMPLATE setting // deprecated TEMPLATE setting
$_SESSION['TEMPLATE'] = $res['template'] ? $res['template'] : ''; $_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['LANG'] = $res['lang_short'];
$_SESSION['DEFAULT_CHARSET'] = $res['lang_iso']; $_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 // reset any login error count for this user
if ($res['login_error_count'] > 0) { if ($res['login_error_count'] > 0) {
$q = "UPDATE edit_user "; $q = "UPDATE edit_user "
$q .= "SET login_error_count = 0, login_error_date_last = NULL, login_error_date_first = NULL "; . "SET login_error_count = 0, login_error_date_last = NULL, "
$q .= "WHERE edit_user_id = ".$res['edit_user_id']; . "login_error_date_first = NULL "
. "WHERE edit_user_id = " . $res['edit_user_id'];
$this->dbExec($q); $this->dbExec($q);
} }
$edit_page_ids = []; $edit_page_ids = [];
$pages = []; $pages = [];
$pages_acl = []; $pages_acl = [];
// set pages access // set pages access
$q = "SELECT ep.edit_page_id, ep.cuid, epca.cuid AS content_alias_uid, "; $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, "; . "ep.hostname, ep.filename, ep.name AS edit_page_name, "
$q .= "ep.order_number AS edit_page_order, ep.menu, "; . "ep.order_number AS edit_page_order, ep.menu, "
$q .= "ep.popup, ep.popup_x, ep.popup_y, ep.online, ear.level, ear.type "; . "ep.popup, ep.popup_x, ep.popup_y, ep.online, ear.level, ear.type "
$q .= "FROM edit_page ep "; . "FROM edit_page ep "
$q .= "LEFT JOIN edit_page epca ON (epca.edit_page_id = ep.content_alias_edit_page_id)"; . "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 "; . ", 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 "; . "WHERE ep.edit_page_id = epa.edit_page_id "
$q .= "AND epa.enabled = 1 AND epa.edit_group_id = ".$res["edit_group_id"]." "; . "AND ear.edit_access_right_id = epa.edit_access_right_id "
$q .= "ORDER BY ep.order_number"; . "AND epa.enabled = 1 AND epa.edit_group_id = " . $res["edit_group_id"] . " "
. "ORDER BY ep.order_number";
while ($res = $this->dbReturn($q)) { while ($res = $this->dbReturn($q)) {
// page id array for sub data readout // page id array for sub data readout
$edit_page_ids[$res['edit_page_id']] = $res['cuid']; $edit_page_ids[$res['edit_page_id']] = $res['cuid'];
@@ -442,7 +476,8 @@ class Login extends \CoreLibs\DB\IO
$pages[$res['cuid']] = [ $pages[$res['cuid']] = [
'edit_page_id' => $res['edit_page_id'], 'edit_page_id' => $res['edit_page_id'],
'cuid' => $res['cuid'], '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'], 'hostname' => $res['hostname'],
'filename' => $res['filename'], 'filename' => $res['filename'],
'page_name' => $res['edit_page_name'], 'page_name' => $res['edit_page_name'],
@@ -462,18 +497,20 @@ class Login extends \CoreLibs\DB\IO
} // for each page } // for each page
// get the visible groups for all pages and write them to the pages // get the visible groups for all pages and write them to the pages
$_edit_page_id = 0; $_edit_page_id = 0;
$q = "SELECT epvg.edit_page_id, name, flag "; $q = "SELECT epvg.edit_page_id, name, flag "
$q .= "FROM edit_visible_group evp, edit_page_visible_group epvg "; . "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)).") "; . "WHERE evp.edit_visible_group_id = epvg.edit_visible_group_id "
$q .= "ORDER BY epvg.edit_page_id"; . "AND epvg.edit_page_id IN (" . join(', ', array_keys($edit_page_ids)) . ") "
. "ORDER BY epvg.edit_page_id";
while ($res = $this->dbReturn($q)) { while ($res = $this->dbReturn($q)) {
$pages[$edit_page_ids[$res['edit_page_id']]]['visible'][$res['name']] = $res['flag']; $pages[$edit_page_ids[$res['edit_page_id']]]['visible'][$res['name']] = $res['flag'];
} }
// get the same for the query strings // get the same for the query strings
$_edit_page_id = 0; $_edit_page_id = 0;
$q = "SELECT eqs.edit_page_id, name, value, dynamic FROM edit_query_string eqs "; $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)).") "; . "WHERE enabled = 1 AND edit_page_id "
$q .= "ORDER BY eqs.edit_page_id"; . "IN (" . join(', ', array_keys($edit_page_ids)) . ") "
. "ORDER BY eqs.edit_page_id";
while ($res = $this->dbReturn($q)) { while ($res = $this->dbReturn($q)) {
$pages[$edit_page_ids[$res['edit_page_id']]]['query'][] = [ $pages[$edit_page_ids[$res['edit_page_id']]]['query'][] = [
'name' => $res['name'], 'name' => $res['name'],
@@ -483,11 +520,12 @@ class Login extends \CoreLibs\DB\IO
} }
// get the page content and add them to the page // get the page content and add them to the page
$_edit_page_id = 0; $_edit_page_id = 0;
$q = "SELECT epc.edit_page_id, epc.name, epc.uid, epc.order_number, epc.online, ear.level, ear.type "; $q = "SELECT epc.edit_page_id, epc.name, epc.uid, epc.order_number, "
$q .= "FROM edit_page_content epc, edit_access_right ear "; . "epc.online, ear.level, ear.type "
$q .= "WHERE epc.edit_access_right_id = ear.edit_access_right_id AND "; . "FROM edit_page_content epc, edit_access_right ear "
$q .= "epc.edit_page_id IN (".join(', ', array_keys($edit_page_ids)).") "; . "WHERE epc.edit_access_right_id = ear.edit_access_right_id AND "
$q .= "ORDER BY epc.order_number"; . "epc.edit_page_id IN (" . join(', ', array_keys($edit_page_ids)) . ") "
. "ORDER BY epc.order_number";
while ($res = $this->dbReturn($q)) { while ($res = $this->dbReturn($q)) {
$pages[$edit_page_ids[$res['edit_page_id']]]['content'][$res['uid']] = [ $pages[$edit_page_ids[$res['edit_page_id']]]['content'][$res['uid']] = [
'name' => $res['name'], 'name' => $res['name'],
@@ -503,17 +541,20 @@ class Login extends \CoreLibs\DB\IO
$_SESSION['PAGES'] = $pages; $_SESSION['PAGES'] = $pages;
$_SESSION['PAGES_ACL_LEVEL'] = $pages_acl; $_SESSION['PAGES_ACL_LEVEL'] = $pages_acl;
// load the edit_access user rights // load the edit_access user rights
$q = "SELECT ea.edit_access_id, level, type, ea.name, ea.color, ea.uid, edit_default "; $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 "; . "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 "; . "WHERE eau.edit_access_id = ea.edit_access_id "
$q .= "AND eau.enabled = 1 AND edit_user_id = ".$this->euid." "; . "AND eau.edit_access_right_id = ear.edit_access_right_id "
$q .= "ORDER BY ea.name"; . "AND eau.enabled = 1 AND edit_user_id = " . $this->euid . " "
. "ORDER BY ea.name";
$unit_access = []; $unit_access = [];
$eauid = []; $eauid = [];
$unit_acl = []; $unit_acl = [];
while ($res = $this->dbReturn($q)) { while ($res = $this->dbReturn($q)) {
// read edit access data fields and drop them into the unit access array // 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 = []; $ea_data = [];
while ($res_sub = $this->dbReturn($q_sub)) { while ($res_sub = $this->dbReturn($q_sub)) {
$ea_data[$res_sub['name']] = $res_sub['value']; $ea_data[$res_sub['name']] = $res_sub['value'];
@@ -548,19 +589,21 @@ class Login extends \CoreLibs\DB\IO
$login_error_date_first = ", login_error_date_first = NOW()"; $login_error_date_first = ", login_error_date_first = NOW()";
} }
// update login error count for this user // update login error count for this user
$q = "UPDATE edit_user "; $q = "UPDATE edit_user "
$q .= "SET login_error_count = login_error_count + 1, login_error_date_last = NOW() ".$login_error_date_first." "; . "SET login_error_count = login_error_count + 1, "
$q .= "WHERE edit_user_id = ".$res['edit_user_id']; . "login_error_date_last = NOW() " . $login_error_date_first . " "
. "WHERE edit_user_id = " . $res['edit_user_id'];
$this->dbExec($q); $this->dbExec($q);
// totally lock the user if error max is reached // 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 $res['login_error_count'] + 1 > $this->max_login_error_count
) { ) {
// do some alert reporting in case this error is too big // do some alert reporting in case this error is too big
// if strict is set, lock this user // if strict is set, lock this user
// this needs manual unlocking by an admin user // this needs manual unlocking by an admin user
if ($res['strict'] && !in_array($this->username, $this->lock_deny_users)) { 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 +624,23 @@ class Login extends \CoreLibs\DB\IO
public function loginCheckPermissions(): bool public function loginCheckPermissions(): bool
{ {
if ($this->euid && $this->login_error != 103) { if ($this->euid && $this->login_error != 103) {
$q = "SELECT filename "; $q = "SELECT filename "
$q .= "FROM edit_page ep, edit_page_access epa, edit_group eg, edit_user eu "; . "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 "; . "WHERE ep.edit_page_id = epa.edit_page_id "
$q .= "AND eu.edit_user_id = ".$this->euid." AND filename = '".$this->page_name."' AND eg.enabled = 1 AND epa.enabled = 1"; . "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); $res = $this->dbReturnRow($q);
// unset mem limit if debug is set to 1 // 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) // if (
// ini_set('memory_limit', -1); // ($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) { if (isset($res['filename']) && $res['filename'] == $this->page_name) {
$this->permission_okay = true; $this->permission_okay = true;
} else { } else {
@@ -687,7 +739,10 @@ class Login extends \CoreLibs\DB\IO
if ($_SESSION['GROUP_ACL_LEVEL'] != -1) { if ($_SESSION['GROUP_ACL_LEVEL'] != -1) {
$this->acl['page'] = $_SESSION['GROUP_ACL_LEVEL']; $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]; $this->acl['page'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name];
} }
@@ -820,7 +875,10 @@ class Login extends \CoreLibs\DB\IO
} }
// check user exist, if not -> error // check user exist, if not -> error
if (!$this->login_error) { if (!$this->login_error) {
$q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->dbEscapeString($this->pw_username)."'"; $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); list ($edit_user_id) = $this->dbReturnRow($q);
if (!$edit_user_id) { if (!$edit_user_id) {
// username wrong // username wrong
@@ -830,7 +888,10 @@ class Login extends \CoreLibs\DB\IO
} }
// check old passwords match -> error // check old passwords match -> error
if (!$this->login_error) { if (!$this->login_error) {
$q = "SELECT edit_user_id, password FROM edit_user WHERE enabled = 1 AND username = '".$this->dbEscapeString($this->pw_username)."'"; $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); list ($edit_user_id, $old_password_hash) = $this->dbReturnRow($q);
if (!$edit_user_id || !$this->loginPasswordCheck($old_password_hash, $this->pw_old_password)) { if (!$edit_user_id || !$this->loginPasswordCheck($old_password_hash, $this->pw_old_password)) {
// old password wrong // old password wrong
@@ -862,15 +923,18 @@ class Login extends \CoreLibs\DB\IO
// no error change this users password // no error change this users password
if (!$this->login_error && $edit_user_id) { if (!$this->login_error && $edit_user_id) {
// update the user (edit_user_id) with the new password // 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); $this->dbExec($q);
$data = 'Password change for user "'.$this->pw_username.'"'; $data = 'Password change for user "' . $this->pw_username . '"';
$this->password_change_ok = true; $this->password_change_ok = true;
} }
} else { } else {
// illegal user error // illegal user error
$this->login_error = 220; $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 // log this password change attempt
$this->writeLog($event, $data, $this->login_error, $this->pw_username); $this->writeLog($event, $data, $this->login_error, $this->pw_username);
@@ -903,43 +967,76 @@ class Login extends \CoreLibs\DB\IO
// pre change the data in the PASSWORD_CHANGE_DIV first // pre change the data in the PASSWORD_CHANGE_DIV first
foreach ($this->login_template['strings'] as $string => $data) { foreach ($this->login_template['strings'] as $string => $data) {
if ($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 // print error messagae
if ($this->login_error) { 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 { } 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 pw change action, show the float again
if ($this->change_password && !$this->password_change_ok) { 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 { } 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; $this->login_template['strings']['PASSWORD_CHANGE_DIV'] = $html_string_password_change;
} }
// put in the logout redirect string // put in the logout redirect string
if ($this->logout && $LOGOUT_TARGET) { 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 { } else {
$html_string = str_replace('{LOGOUT_TARGET}', '', $html_string); $html_string = str_replace('{LOGOUT_TARGET}', '', $html_string);
} }
// print error messagae // print error messagae
if ($this->login_error) { 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) { } 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 { } else {
$html_string = str_replace('{ERROR_MSG}', '<br>', $html_string); $html_string = str_replace('{ERROR_MSG}', '<br>', $html_string);
} }
// create the replace array context // create the replace array context
foreach ($this->login_template['strings'] as $string => $data) { 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 } // if permission is 0 then print out login
// return the created HTML here or null for nothing // return the created HTML here or null for nothing
@@ -968,7 +1065,7 @@ class Login extends \CoreLibs\DB\IO
// prepare for log // prepare for log
if ($this->euid) { if ($this->euid) {
// get user from user table // get user from user table
$q = "SELECT username FROM edit_user WHERE edit_user_id = ".$this->euid; $q = "SELECT username FROM edit_user WHERE edit_user_id = " . $this->euid;
list($username) = $this->dbReturnRow($q); list($username) = $this->dbReturnRow($q);
} // if euid is set, get username (or try) } // if euid is set, get username (or try)
$this->writeLog($event, '', $this->login_error, $username); $this->writeLog($event, '', $this->login_error, $username);
@@ -1000,24 +1097,33 @@ class Login extends \CoreLibs\DB\IO
]; ];
$error_msgs = [ $error_msgs = [
'100' => $this->l->__('Fatal Error: <b>[EUID] came in as GET/POST!</b>'), // actually obsolete // actually obsolete
'1010' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'), // user not found '100' => $this->l->__('Fatal Error: <b>[EUID] came in as GET/POST!</b>'),
'1011' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'), // blowfish password wrong // user not found
'1012' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'), // fallback md5 password wrong '1010' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'),
'1013' => $this->l->__('Fatal Error: <b>Login Failed - Wrong Username or Password</b>'), // new password_hash wrong // 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>'), '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>'), '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>'), '104' => $this->l->__('Fatal Error: <b>Login Failed - User not enabled</b>'),
'105' => $this->l->__('Fatal Error: <b>Login Failed - User is locked</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 // 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>'), '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>'), '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>'), '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>'), '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>'), '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 // we should also not here WHAT is valid
'300' => $this->l->__('Success: <b>Password change successful</b>'), // for OK password change '205' => $this->l->__('Fatal Error: <b>Password change - The new password is not in a valid format</b>'),
'9999' => $this->l->__('Fatal Error: <b>necessary crypt engine could not be found</b>. Login is impossible') // this is bad bad error // 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 // if password change is okay
@@ -1028,23 +1134,36 @@ class Login extends \CoreLibs\DB\IO
'NEW_PASSWORD' => $this->l->__('New Password'), 'NEW_PASSWORD' => $this->l->__('New Password'),
'NEW_PASSWORD_CONFIRM' => $this->l->__('New Password confirm'), 'NEW_PASSWORD_CONFIRM' => $this->l->__('New Password confirm'),
'CLOSE' => $this->l->__('Close'), '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'; }", 'JS_SHOW_HIDE' => "function ShowHideDiv(id) { "
'PASSWORD_CHANGE_BUTTON' => '<input type="button" name="pw_change" value="'.$strings['PASSWORD_CHANGE_BUTTON_VALUE'].'" OnClick="ShowHideDiv(\'pw_change_div\');">' . "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 $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;"> <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> <table>
<tr><td class="norm" align="center" colspan="2"><h3>{TITLE_PASSWORD_CHANGE}</h3></td></tr> <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" 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">{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">{OLD_PASSWORD}</td>
<tr><td class="norm" align="right">{NEW_PASSWORD}</td><td><input type="password" name="pw_new_password" value=""></td></tr> <td><input type="password" name="pw_old_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 class="norm" align="right">{NEW_PASSWORD}</td>
<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> <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> </table>
</div> </div>
{PASSWORD_CHANGE_SHOW} {PASSWORD_CHANGE_SHOW}
EOM; EOM;
// phpcs:enable
} }
if ($this->password_forgot) { if ($this->password_forgot) {
} }
@@ -1163,28 +1282,38 @@ EOM;
]; ];
$data_binary = $this->dbEscapeBytea(bzcompress(serialize($_data_binary))); $data_binary = $this->dbEscapeBytea(bzcompress(serialize($_data_binary)));
// SQL querie for log entry // SQL querie for log entry
$q = "INSERT INTO edit_log "; $q = "INSERT INTO edit_log "
$q .= "(username, password, euid, event_date, event, error, data, data_binary, page, "; . "(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, "; . "ip, user_agent, referer, script_name, query_string, server_name, http_host, "
$q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "; . "http_accept, http_accept_charset, http_accept_encoding, session_id, "
$q .= "VALUES ('".$this->dbEscapeString($username)."', 'PASSWORD', ".($this->euid ? $this->euid : 'NULL').", "; . "action, action_id, action_yes, action_flag, action_menu, action_loaded, "
$q .= "NOW(), '".$this->dbEscapeString($event)."', '".$this->dbEscapeString((string)$error)."', '".$this->dbEscapeString($data)."', '".$data_binary."', '".$this->page_name."', "; . "action_value, action_error) "
foreach ([ . "VALUES ('" . $this->dbEscapeString($username) . "', 'PASSWORD', "
'REMOTE_ADDR', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'SCRIPT_FILENAME', 'QUERY_STRING', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_ACCEPT', 'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING' . ($this->euid ? $this->euid : 'NULL') . ", "
] as $server_code) { . "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)) { if (array_key_exists($server_code, $_SERVER)) {
$q .= "'".$this->dbEscapeString($_SERVER[$server_code])."', "; $q .= "'" . $this->dbEscapeString($_SERVER[$server_code]) . "', ";
} else { } else {
$q .= "NULL, "; $q .= "NULL, ";
} }
} }
$q .= "'".session_id()."', "; $q .= "'" . session_id() . "', ";
$q .= "'".$this->dbEscapeString($this->action)."', "; $q .= "'" . $this->dbEscapeString($this->action) . "', ";
$q .= "'".$this->dbEscapeString($this->username)."', "; $q .= "'" . $this->dbEscapeString($this->username) . "', ";
$q .= "NULL, "; $q .= "NULL, ";
$q .= "'".$this->dbEscapeString((string)$this->login_error)."', "; $q .= "'" . $this->dbEscapeString((string)$this->login_error) . "', ";
$q .= "NULL, NULL, "; $q .= "NULL, NULL, ";
$q .= "'".$this->dbEscapeString((string)$this->permission_okay)."', "; $q .= "'" . $this->dbEscapeString((string)$this->permission_okay) . "', ";
$q .= "NULL)"; $q .= "NULL)";
$this->dbExec($q, 'NULL'); $this->dbExec($q, 'NULL');
} }
@@ -1197,7 +1326,8 @@ EOM;
*/ */
public function loginCheckEditAccessId(?int $edit_access_id): ?int public function loginCheckEditAccessId(?int $edit_access_id): ?int
{ {
if (isset($_SESSION['UNIT']) && if (
isset($_SESSION['UNIT']) &&
is_array($_SESSION['UNIT']) && is_array($_SESSION['UNIT']) &&
!array_key_exists($edit_access_id, $_SESSION['UNIT']) !array_key_exists($edit_access_id, $_SESSION['UNIT'])
) { ) {
@@ -1222,6 +1352,7 @@ EOM;
return $_SESSION['UNIT'][$edit_access_id]['data'][$data_key]; return $_SESSION['UNIT'][$edit_access_id]['data'][$data_key];
} }
} }
} // close class // close class
}
// __END__ // __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1); <?php
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2006/08/15 * CREATED: 2006/08/15
@@ -10,6 +11,10 @@
* - menu creation * - menu creation
* - array vars for smarty * - 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 * PUBLIC VARIABLES
* *
* PRIVATE VARIABLES * PRIVATE VARIABLES
@@ -22,6 +27,8 @@
* *
*********************************************************************/ *********************************************************************/
declare(strict_types=1);
namespace CoreLibs\Admin; namespace CoreLibs\Admin;
class Backend extends \CoreLibs\DB\IO class Backend extends \CoreLibs\DB\IO
@@ -30,7 +37,10 @@ class Backend extends \CoreLibs\DB\IO
public $menu = []; public $menu = [];
public $menu_show_flag = 0; // top menu flag (mostly string) public $menu_show_flag = 0; // top menu flag (mostly string)
// action ids // action ids
public $action_list = ['action', 'action_id', 'action_sub_id', 'action_yes', 'action_flag', 'action_menu', 'action_value', 'action_error', 'action_loaded']; public $action_list = [
'action', 'action_id', 'action_sub_id', 'action_yes', 'action_flag',
'action_menu', 'action_value', 'action_error', 'action_loaded'
];
public $action; public $action;
public $action_id; public $action_id;
public $action_sub_id; public $action_sub_id;
@@ -134,7 +144,7 @@ class Backend extends \CoreLibs\DB\IO
// create the char lang encoding // create the char lang encoding
$this->lang_short = substr($this->lang, 0, 2); $this->lang_short = substr($this->lang, 0, 2);
// set the language folder // set the language folder
$this->lang_dir = BASE.INCLUDES.LANG.CONTENT_PATH; $this->lang_dir = BASE . INCLUDES . LANG . CONTENT_PATH;
} }
// PUBLIC METHODS |=================================================> // PUBLIC METHODS |=================================================>
@@ -178,32 +188,38 @@ class Backend extends \CoreLibs\DB\IO
$SCHEMA = 'public'; $SCHEMA = 'public';
} }
$q = "INSERT INTO ".$SCHEMA.".edit_log "; $q = "INSERT INTO " . $SCHEMA . ".edit_log "
$q .= "(euid, event_date, event, data, data_binary, page, "; . "(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, "; . "ip, user_agent, referer, script_name, query_string, server_name, http_host, "
$q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "; . "http_accept, http_accept_charset, http_accept_encoding, session_id, "
$q .= "VALUES "; . "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "
$q .= "(".$this->dbEscapeString(isset($_SESSION['EUID']) && is_numeric($_SESSION['EUID']) ? $_SESSION['EUID'] : 'NULL').", "; . "VALUES "
$q .= "NOW(), "; . "(" . $this->dbEscapeString(isset($_SESSION['EUID']) && is_numeric($_SESSION['EUID']) ?
$q .= "'".$this->dbEscapeString((string)$event)."', '".$data."', '".$data_binary."', '".$this->dbEscapeString((string)$this->page_name)."', "; $_SESSION['EUID'] :
$q .= "'".@$_SERVER["REMOTE_ADDR"]."', '".$this->dbEscapeString(@$_SERVER['HTTP_USER_AGENT'])."', "; 'NULL')
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_REFERER'] ?? '')."', "; . ", "
$q .= "'".$this->dbEscapeString($_SERVER['SCRIPT_FILENAME'] ?? '')."', "; . "NOW(), "
$q .= "'".$this->dbEscapeString($_SERVER['QUERY_STRING'] ?? '')."', "; . "'" . $this->dbEscapeString((string)$event) . "', '" . $data . "', "
$q .= "'".$this->dbEscapeString($_SERVER['SERVER_NAME'] ?? '')."', "; . "'" . $data_binary . "', '" . $this->dbEscapeString((string)$this->page_name) . "', "
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_HOST'] ?? '')."', "; . "'" . @$_SERVER["REMOTE_ADDR"] . "', "
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_ACCEPT'] ?? '')."', "; . "'" . $this->dbEscapeString(@$_SERVER['HTTP_USER_AGENT']) . "', "
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_ACCEPT_CHARSET'] ?? '')."', "; . "'" . $this->dbEscapeString($_SERVER['HTTP_REFERER'] ?? '') . "', "
$q .= "'".$this->dbEscapeString($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '')."', "; . "'" . $this->dbEscapeString($_SERVER['SCRIPT_FILENAME'] ?? '') . "', "
$q .= "'".session_id()."', "; . "'" . $this->dbEscapeString($_SERVER['QUERY_STRING'] ?? '') . "', "
$q .= "'".$this->dbEscapeString($this->action)."', "; . "'" . $this->dbEscapeString($_SERVER['SERVER_NAME'] ?? '') . "', "
$q .= "'".$this->dbEscapeString($this->action_id)."', "; . "'" . $this->dbEscapeString($_SERVER['HTTP_HOST'] ?? '') . "', "
$q .= "'".$this->dbEscapeString($this->action_yes)."', "; . "'" . $this->dbEscapeString($_SERVER['HTTP_ACCEPT'] ?? '') . "', "
$q .= "'".$this->dbEscapeString($this->action_flag)."', "; . "'" . $this->dbEscapeString($_SERVER['HTTP_ACCEPT_CHARSET'] ?? '') . "', "
$q .= "'".$this->dbEscapeString($this->action_menu)."', "; . "'" . $this->dbEscapeString($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '') . "', "
$q .= "'".$this->dbEscapeString($this->action_loaded)."', "; . "'" . session_id() . "', "
$q .= "'".$this->dbEscapeString($this->action_value)."', "; . "'" . $this->dbEscapeString($this->action) . "', "
$q .= "'".$this->dbEscapeString($this->action_error)."')"; . "'" . $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'); $this->dbExec($q, 'NULL');
} }
@@ -224,14 +240,14 @@ class Backend extends \CoreLibs\DB\IO
$PAGES = []; $PAGES = [];
} }
$pages = []; $pages = [];
foreach ($PAGES as $PAGE_CUID => $PAGE_DATA) { foreach ($PAGES as $PAGE_DATA) {
$pages[] = $PAGE_DATA; $pages[] = $PAGE_DATA;
} }
// $this->debug('pages', $this->print_ar($pages)); // $this->debug('pages', $this->print_ar($pages));
// if flag is 0, then we show all, else, we show only the matching flagges array points // if flag is 0, then we show all, else, we show only the matching flagges array points
// array is already sorted after correct order // array is already sorted after correct order
reset($pages); reset($pages);
foreach ($pages as $i => $data) { foreach ($pages as $data) {
// for ($i = 0, $iMax = count($pages); $i < $iMax; $i ++) { // for ($i = 0, $iMax = count($pages); $i < $iMax; $i ++) {
$show = 0; $show = 0;
// is it visible in the menu & is it online // is it visible in the menu & is it online
@@ -258,20 +274,23 @@ class Backend extends \CoreLibs\DB\IO
} }
$query_string = ''; $query_string = '';
if (isset($data['query']) && if (
isset($data['query']) &&
is_array($data['query']) && is_array($data['query']) &&
count($data['query']) count($data['query'])
) { ) {
// for ($j = 0, $jMax = count($pages[$i]['query']); $j < $jMax; $j ++) { // for ($j = 0, $jMax = count($pages[$i]['query']); $j < $jMax; $j ++) {
foreach ($data['query'] as $j => $query) { foreach ($data['query'] as $j => $query) {
if (!empty($query['name']) && if (
!empty($query['name']) &&
!empty($query['value']) !empty($query['value'])
) { ) {
if (strlen($query_string)) { if (strlen($query_string)) {
$query_string .= '&'; $query_string .= '&';
} }
$query_string .= $query['name'].'='; $query_string .= $query['name'] . '=';
if (isset($query['dynamic']) && if (
isset($query['dynamic']) &&
$query['dynamic'] $query['dynamic']
) { ) {
if (isset($_GET[$query['value']])) { if (isset($_GET[$query['value']])) {
@@ -291,12 +310,13 @@ class Backend extends \CoreLibs\DB\IO
} }
$url .= $data['filename'] ?? ''; $url .= $data['filename'] ?? '';
if (strlen($query_string)) { if (strlen($query_string)) {
$url .= '?'.$query_string; $url .= '?' . $query_string;
} }
$name = $data['page_name'] ?? ''; $name = $data['page_name'] ?? '';
// if page name matchs -> set selected flag // if page name matchs -> set selected flag
$selected = 0; $selected = 0;
if (isset($data['filename']) && if (
isset($data['filename']) &&
\CoreLibs\Get\System::getPageName() == $data['filename'] && \CoreLibs\Get\System::getPageName() == $data['filename'] &&
(!isset($data['hostname']) || ( (!isset($data['hostname']) || (
isset($data['hostname']) && isset($data['hostname']) &&
@@ -308,7 +328,8 @@ class Backend extends \CoreLibs\DB\IO
} }
// last check, is this menu point okay to show // last check, is this menu point okay to show
$enabled = 0; $enabled = 0;
if (isset($data['filename']) && if (
isset($data['filename']) &&
$this->adbShowMenuPoint($data['filename']) $this->adbShowMenuPoint($data['filename'])
) { ) {
$enabled = 1; $enabled = 1;
@@ -329,11 +350,12 @@ class Backend extends \CoreLibs\DB\IO
} }
/** /**
* ONLY USED IN adbTopMenu
* checks if this filename is in the current situation (user id, etc) available * checks if this filename is in the current situation (user id, etc) available
* @param string|null $filename filename * @param string|null $filename filename
* @return bool true for visible/accessable menu point, false for not * @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; $enabled = false;
if ($filename === null) { if ($filename === null) {
@@ -359,7 +381,10 @@ class Backend extends \CoreLibs\DB\IO
*/ */
public function adbAssocArray(array $db_array, $key, $value): array 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); return \CoreLibs\Combined\ArrayHandler::genAssocArray($db_array, $key, $value);
} }
@@ -372,7 +397,10 @@ class Backend extends \CoreLibs\DB\IO
*/ */
public function adbByteStringFormat($number): string 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); return \CoreLibs\Convert\Byte::humanReadableByteFormat($number);
} }
@@ -389,7 +417,10 @@ class Backend extends \CoreLibs\DB\IO
*/ */
public function adbCreateThumbnail($pic, $size_x, $size_y, $dummy = '', $path = "", $cache = "") public function adbCreateThumbnail($pic, $size_x, $size_y, $dummy = '', $path = "", $cache = "")
{ {
trigger_error('Method '.__METHOD__.' is deprecated: \CoreLibs\Output\Image::createThumbnail()', E_USER_DEPRECATED); 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); return \CoreLibs\Output\Image::createThumbnail($pic, $size_x, $size_y, $dummy, $path, $cache);
} }
@@ -453,14 +484,15 @@ class Backend extends \CoreLibs\DB\IO
} else { } else {
$SCHEMA = 'public'; $SCHEMA = 'public';
} }
$q = "INSERT INTO ".$SCHEMA.".live_queue ("; $q = "INSERT INTO " . $SCHEMA . ".live_queue ("
$q .= "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file"; . "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file"
$q .= ") VALUES ("; . ") VALUES ("
$q .= "'".$this->dbEscapeString($queue_key)."', '".$this->dbEscapeString($key_value)."', "; . "'" . $this->dbEscapeString($queue_key) . "', '" . $this->dbEscapeString($key_value) . "', "
$q .= "'".$this->dbEscapeString($key_name)."', '".$this->dbEscapeString($type)."', "; . "'" . $this->dbEscapeString($key_name) . "', '" . $this->dbEscapeString($type) . "', "
$q .= "'".$this->dbEscapeString($target)."', '".$this->dbEscapeString($data)."', "; . "'" . $this->dbEscapeString($target) . "', '" . $this->dbEscapeString($data) . "', "
$q .= "'".$this->queue_key."', '".$this->action."', '".$this->dbEscapeString((string)$associate)."', "; . "'" . $this->queue_key . "', '" . $this->action . "', "
$q .= "'".$this->dbEscapeString((string)$file)."')"; . "'" . $this->dbEscapeString((string)$associate) . "', "
. "'" . $this->dbEscapeString((string)$file) . "')";
$this->dbExec($q); $this->dbExec($q);
} }
@@ -490,14 +522,23 @@ class Backend extends \CoreLibs\DB\IO
bool $name_pos_back = false bool $name_pos_back = false
) { ) {
// get the build layout // 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 // translate the strings inside
foreach (['Year ', 'Month ', 'Day ', 'Hour ', 'Minute '] as $_time) { 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 // replace week days in short
foreach (['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as $_date) { 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 the datetime select string with strings translated
return $html_time; return $html_time;

View File

@@ -1,4 +1,7 @@
<?php declare(strict_types=1); <?php
// phpcs:disable Generic.Files.LineLength
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2003/03/24 * CREATED: 2003/03/24
@@ -15,12 +18,15 @@
* HISTORY: * HISTORY:
* 2021/06/16 (cs) CLASS MOSTLY DEPRECATED: moved all methids in their own classes * 2021/06/16 (cs) CLASS MOSTLY DEPRECATED: moved all methids in their own classes
* 2010/12/24 (cs) add crypt classes with auto detect what crypt we can use, add php version check class * 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 * 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
* 2007/11/13 (cs) add Comparedate function * 2007/11/13 (cs) add Comparedate function
* 2007/11/05 (cs) added GenAssocArray and CheckDate functions * 2007/11/05 (cs) added GenAssocArray and CheckDate functions
* 2007/10/10 (cs) magic links function can use http:///path as a local prefix. blank target is removed & http:// also * 2007/10/10 (cs) magic links function can use http:///path as a local prefix.
* blank target is removed & http:// also
* 2006/03/09 (cs) added Byte/TimeStringFormat functions * 2006/03/09 (cs) added Byte/TimeStringFormat functions
* 2006/02/21 (cs) fix various problems with the mime magic function: || not always working, fix prefix replacement, etc * 2006/02/21 (cs) fix various problems with the mime magic function: || not always working,
* fix prefix replacement, etc
* 2006/02/09 (cs) added _mb_mime_encode function, replacement for php internal one * 2006/02/09 (cs) added _mb_mime_encode function, replacement for php internal one
* 2005/07/12 (cs) added some small stylesheet defs to debug output * 2005/07/12 (cs) added some small stylesheet defs to debug output
* 2005/06/24 (cs) made the check selected/checked function way easier * 2005/06/24 (cs) made the check selected/checked function way easier
@@ -43,6 +49,8 @@
* 2003-03-24: start of stub/basic class * 2003-03-24: start of stub/basic class
*********************************************************************/ *********************************************************************/
declare(strict_types=1);
namespace CoreLibs; namespace CoreLibs;
/** Basic core class declaration */ /** Basic core class declaration */
@@ -77,13 +85,19 @@ class Basic
// TODO make check dynamic for entries we MUST have depending on load type // TODO make check dynamic for entries we MUST have depending on load type
// before we start any work, we should check that all MUST constants are defined // before we start any work, we should check that all MUST constants are defined
$abort = false; $abort = false;
foreach ([ foreach (
'DS', 'DIR', 'BASE', 'ROOT', 'LIB', 'INCLUDES', 'LAYOUT', 'PICTURES', 'FLASH', 'VIDEOS', 'DOCUMENTS', 'PDFS', 'BINARIES', 'ICONS', [
'UPLOADS', 'CSV', 'JS', 'CSS', 'TABLE_ARRAYS', 'SMARTY', 'LANG', 'CACHE', 'TMP', 'LOG', 'TEMPLATES', 'TEMPLATES_C', 'DS', 'DIR', 'BASE', 'ROOT', 'LIB', 'INCLUDES', 'LAYOUT', 'PICTURES', 'DATA',
'DEFAULT_LANG', 'DEFAULT_ENCODING', 'DEFAULT_HASH', 'VIDEOS', 'DOCUMENTS', 'PDFS', 'BINARIES', 'ICONS', 'UPLOADS', 'CSV', 'JS',
'DEFAULT_ACL_LEVEL', 'LOGOUT_TARGET', 'PASSWORD_CHANGE', 'AJAX_REQUEST_TYPE', 'USE_PROTOTYPE', 'USE_SCRIPTACULOUS', 'USE_JQUERY', 'CSS', 'TABLE_ARRAYS', 'SMARTY', 'LANG', 'CACHE', 'TMP', 'LOG', 'TEMPLATES',
'PAGE_WIDTH', 'MASTER_TEMPLATE_NAME', 'PUBLIC_SCHEMA', 'TEST_SCHEMA', 'DEV_SCHEMA', 'LIVE_SCHEMA', 'DB_CONFIG_NAME', 'DB_CONFIG', 'TARGET', 'DEBUG', 'SHOW_ALL_ERRORS' 'TEMPLATES_C', 'DEFAULT_LANG', 'DEFAULT_ENCODING', 'DEFAULT_HASH',
] as $constant) { 'DEFAULT_ACL_LEVEL', 'LOGOUT_TARGET', 'PASSWORD_CHANGE', 'AJAX_REQUEST_TYPE',
'USE_PROTOTYPE', 'USE_SCRIPTACULOUS', 'USE_JQUERY', 'PAGE_WIDTH',
'MASTER_TEMPLATE_NAME', 'PUBLIC_SCHEMA', 'TEST_SCHEMA', 'DEV_SCHEMA',
'LIVE_SCHEMA', 'DB_CONFIG_NAME', 'DB_CONFIG', 'TARGET', 'DEBUG',
'SHOW_ALL_ERRORS'
] as $constant
) {
if (!defined($constant)) { if (!defined($constant)) {
echo "Constant $constant misssing<br>"; echo "Constant $constant misssing<br>";
$abort = true; $abort = true;
@@ -101,7 +115,7 @@ class Basic
// set the paths matching to the valid file types // set the paths matching to the valid file types
$this->data_path = [ $this->data_path = [
'P' => PICTURES, 'P' => PICTURES,
'F' => FLASH, 'F' => DATA,
'V' => VIDEOS, 'V' => VIDEOS,
'D' => DOCUMENTS, 'D' => DOCUMENTS,
'A' => PDFS, 'A' => PDFS,
@@ -167,7 +181,7 @@ class Basic
*/ */
public function basicSetLogId(string $string): string public function basicSetLogId(string $string): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use $basic->log->basicSetLogId() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use $basic->log->basicSetLogId() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED);
return $this->log->basicSetLogId($string); return $this->log->basicSetLogId($string);
} }
@@ -190,7 +204,7 @@ class Basic
*/ */
public function hrRunningTime(string $out_time = 'ms'): float public function hrRunningTime(string $out_time = 'ms'): float
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\RunningTime::hrRunningTime()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Debug\RunningTime::hrRunningTime()', E_USER_DEPRECATED);
return \CoreLibs\Debug\RunningTime::hrRunningTime($out_time); return \CoreLibs\Debug\RunningTime::hrRunningTime($out_time);
} }
@@ -205,7 +219,7 @@ class Basic
*/ */
public function runningTime(bool $simple = false): float public function runningTime(bool $simple = false): float
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\RunningTime::runningTime()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Debug\RunningTime::runningTime()', E_USER_DEPRECATED);
return \CoreLibs\Debug\RunningTime::runningTime($simple); return \CoreLibs\Debug\RunningTime::runningTime($simple);
} }
@@ -221,7 +235,7 @@ class Basic
*/ */
public static function printTime(int $set_microtime = -1): string public static function printTime(int $set_microtime = -1): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\Support::printTime()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Debug\Support::printTime()', E_USER_DEPRECATED);
return \CoreLibs\Debug\Support::printTime($set_microtime); return \CoreLibs\Debug\Support::printTime($set_microtime);
} }
@@ -238,7 +252,7 @@ class Basic
*/ */
public function fdebug(string $string, bool $enter = true): bool public function fdebug(string $string, bool $enter = true): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\FileWriter::fdebug()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Debug\FileWriter::fdebug()', E_USER_DEPRECATED);
return \CoreLibs\Debug\FileWriter::fdebug($string, $enter); return \CoreLibs\Debug\FileWriter::fdebug($string, $enter);
} }
@@ -256,7 +270,7 @@ class Basic
*/ */
public function debugFor(string $type, string $flag): void public function debugFor(string $type, string $flag): void
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use $basic->log->debugFor() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use $basic->log->debugFor() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED);
/** @phan-suppress-next-line PhanTypeMismatchArgumentReal */ /** @phan-suppress-next-line PhanTypeMismatchArgumentReal */
$this->log->debugFor(...[func_get_args()]); $this->log->debugFor(...[func_get_args()]);
} }
@@ -342,7 +356,7 @@ class Basic
*/ */
public function mergeErrors(array $error_msg = []): void public function mergeErrors(array $error_msg = []): void
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use $basic->log->mergeErrors() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use $basic->log->mergeErrors() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED);
$this->log->mergeErrors($error_msg); $this->log->mergeErrors($error_msg);
} }
@@ -357,74 +371,6 @@ class Basic
return $this->log->printErrorMsg($string); return $this->log->printErrorMsg($string);
} }
/**
* 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 void has no return
*/
/* private function writeErrorMsg(string $level, string $error_string): void
{
// only write if write is requested
if ($this->doDebugTrigger('debug', $level) &&
$this->doDebugTrigger('print', $level)
) {
// 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('<!--#BR#-->', "\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 "<!-- could not open file: $fn //-->";
}
} // do write to file
} */
/** /**
* unsests the error message array * unsests the error message array
* can be used if writing is primary to file * can be used if writing is primary to file
@@ -435,7 +381,7 @@ class Basic
*/ */
public function resetErrorMsg(string $level = ''): void public function resetErrorMsg(string $level = ''): void
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use $basic->log->resetErrorMsg() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use $basic->log->resetErrorMsg() or use \CoreLibs\Debug\Logging() class', E_USER_DEPRECATED);
$this->log->resetErrorMsg($level); $this->log->resetErrorMsg($level);
} }
@@ -464,7 +410,7 @@ class Basic
*/ */
public static function getCallerMethod(int $level = 2): ?string public static function getCallerMethod(int $level = 2): ?string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Debug\Support::getCallerMethod()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Debug\Support::getCallerMethod()', E_USER_DEPRECATED);
return \CoreLibs\Debug\Support::getCallerMethod($level); return \CoreLibs\Debug\Support::getCallerMethod($level);
} }
@@ -480,7 +426,7 @@ class Basic
*/ */
public function fileUploadErrorMessage(int $error_code): string public function fileUploadErrorMessage(int $error_code): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Get\System::fileUploadErrorMessage()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Get\System::fileUploadErrorMessage()', E_USER_DEPRECATED);
return \CoreLibs\Get\System::fileUploadErrorMessage($error_code); return \CoreLibs\Get\System::fileUploadErrorMessage($error_code);
} }
@@ -499,7 +445,7 @@ class Basic
*/ */
public function initRandomKeyLength(int $key_length): bool public function initRandomKeyLength(int $key_length): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\RandomKey::setRandomKeyLength()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Create\RandomKey::setRandomKeyLength()', E_USER_DEPRECATED);
return \CoreLibs\Create\RandomKey::setRandomKeyLength($key_length); return \CoreLibs\Create\RandomKey::setRandomKeyLength($key_length);
} }
@@ -513,7 +459,7 @@ class Basic
*/ */
public function randomKeyGen(int $key_length = -1): string public function randomKeyGen(int $key_length = -1): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\RandomKey::randomKeyGen()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Create\RandomKey::randomKeyGen()', E_USER_DEPRECATED);
return \CoreLibs\Create\RandomKey::randomKeyGen($key_length); return \CoreLibs\Create\RandomKey::randomKeyGen($key_length);
} }
@@ -533,7 +479,7 @@ class Basic
*/ */
public static function checked($haystack, $needle, int $type = 0): ?string public static function checked($haystack, $needle, int $type = 0): ?string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Html::checked()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Html::checked()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Html::checked($haystack, $needle, $type); return \CoreLibs\Convert\Html::checked($haystack, $needle, $type);
} }
@@ -548,7 +494,7 @@ class Basic
*/ */
public function magicLinks(string $string, string $target = "_blank"): string public function magicLinks(string $string, string $target = "_blank"): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Output\Form\Elements::magicLinks()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Output\Form\Elements::magicLinks()', E_USER_DEPRECATED);
return \CoreLibs\Output\Form\Elements::magicLinks($string, $target); return \CoreLibs\Output\Form\Elements::magicLinks($string, $target);
} }
@@ -563,7 +509,7 @@ class Basic
*/ */
public function getHostName(): array public function getHostName(): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Get\System::getHostName()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Get\System::getHostName()', E_USER_DEPRECATED);
return \CoreLibs\Get\System::getHostName(); return \CoreLibs\Get\System::getHostName();
} }
@@ -577,7 +523,7 @@ class Basic
*/ */
public static function getPageName(int $strip_ext = 0): string public static function getPageName(int $strip_ext = 0): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Get\System::getPageName()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Get\System::getPageName()', E_USER_DEPRECATED);
return \CoreLibs\Get\System::getPageName($strip_ext); return \CoreLibs\Get\System::getPageName($strip_ext);
} }
@@ -593,7 +539,7 @@ class Basic
*/ */
public static function getFilenameEnding(string $filename): string public static function getFilenameEnding(string $filename): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\File::getFilenameEnding()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\File::getFilenameEnding()', E_USER_DEPRECATED);
return \CoreLibs\Check\File::getFilenameEnding($filename); return \CoreLibs\Check\File::getFilenameEnding($filename);
} }
@@ -605,7 +551,7 @@ class Basic
*/ */
public static function getLinesFromFile(string $file): int public static function getLinesFromFile(string $file): int
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\File::getLinesFromFile()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\File::getLinesFromFile()', E_USER_DEPRECATED);
return \CoreLibs\Check\File::getLinesFromFile($file); return \CoreLibs\Check\File::getLinesFromFile($file);
} }
@@ -625,7 +571,7 @@ class Basic
*/ */
public static function arraySearchRecursive($needle, array $haystack, ?string $key_lookin = null): array public static function arraySearchRecursive($needle, array $haystack, ?string $key_lookin = null): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::arraySearchRecursive()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::arraySearchRecursive()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::arraySearchRecursive($needle, $haystack, $key_lookin); return \CoreLibs\Combined\ArrayHandler::arraySearchRecursive($needle, $haystack, $key_lookin);
} }
@@ -640,13 +586,13 @@ class Basic
*/ */
public static function arraySearchRecursiveAll($needle, array $haystack, $key, ?array $path = null): ?array public static function arraySearchRecursiveAll($needle, array $haystack, $key, ?array $path = null): ?array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::arraySearchRecursiveAll()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::arraySearchRecursiveAll()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::arraySearchRecursiveAll($needle, $haystack, $key, $path); return \CoreLibs\Combined\ArrayHandler::arraySearchRecursiveAll($needle, $haystack, $key, $path);
} }
/** /**
* array search simple. looks for key, value Combined, if found, returns true * array search simple. looks for key, value Combined, if found, returns true
* @param array $array array(search in) * @param array $array array (search in)
* @param string|int $key key (key to search in) * @param string|int $key key (key to search in)
* @param string|int $value value (what to find) * @param string|int $value value (what to find)
* @return bool true on found, false on not found * @return bool true on found, false on not found
@@ -654,7 +600,7 @@ class Basic
*/ */
public static function arraySearchSimple(array $array, $key, $value): bool public static function arraySearchSimple(array $array, $key, $value): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::arraySearchSimple()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::arraySearchSimple()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::arraySearchSimple($array, $key, $value); return \CoreLibs\Combined\ArrayHandler::arraySearchSimple($array, $key, $value);
} }
@@ -670,7 +616,7 @@ class Basic
*/ */
public static function arrayMergeRecursive() public static function arrayMergeRecursive()
{ {
trigger_error('MUST CHANGE: Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::arrayMergeRecursive()', E_USER_DEPRECATED); trigger_error('MUST CHANGE: Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::arrayMergeRecursive()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::arrayMergeRecursive(...func_get_args()); return \CoreLibs\Combined\ArrayHandler::arrayMergeRecursive(...func_get_args());
} }
@@ -686,7 +632,7 @@ class Basic
*/ */
public static function arrayDiff(array $a, array $b): array public static function arrayDiff(array $a, array $b): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::arrayDiff()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::arrayDiff()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::arrayDiff($a, $b); return \CoreLibs\Combined\ArrayHandler::arrayDiff($a, $b);
} }
@@ -700,7 +646,7 @@ class Basic
*/ */
public static function inArrayAny(array $needle, array $haystack) public static function inArrayAny(array $needle, array $haystack)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::inArrayAny()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::inArrayAny()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::inArrayAny($needle, $haystack); return \CoreLibs\Combined\ArrayHandler::inArrayAny($needle, $haystack);
} }
@@ -715,7 +661,7 @@ class Basic
*/ */
public static function genAssocArray(array $db_array, $key, $value, bool $set_only = false): array public static function genAssocArray(array $db_array, $key, $value, bool $set_only = false): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::flattenArray()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::flattenArray()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::genAssocArray($db_array, $key, $value, $set_only); return \CoreLibs\Combined\ArrayHandler::genAssocArray($db_array, $key, $value, $set_only);
} }
@@ -729,9 +675,9 @@ class Basic
*/ */
public static function arrayToString(array $array, string $connect_char): string public static function arrayToString(array $array, string $connect_char): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use join()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use join()', E_USER_DEPRECATED);
if (!is_array($array)) { if (!is_array($array)) {
$array = array(); $array = [];
} }
return join($connect_char, $array); return join($connect_char, $array);
} }
@@ -745,7 +691,7 @@ class Basic
*/ */
public static function flattenArray(array $array): array public static function flattenArray(array $array): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::flattenArray()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::flattenArray()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::flattenArray($array); return \CoreLibs\Combined\ArrayHandler::flattenArray($array);
} }
@@ -755,23 +701,23 @@ class Basic
* @return array flattened keys array * @return array flattened keys array
* @deprecated Use \CoreLibs\Combined\ArrayHandler::flattenArrayKey() instead * @deprecated Use \CoreLibs\Combined\ArrayHandler::flattenArrayKey() instead
*/ */
public static function flattenArrayKey(array $array/*, array $return = array()*/): array public static function flattenArrayKey(array $array/*, array $return = []*/): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::flattenArrayKey()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::flattenArrayKey()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::flattenArrayKey($array); return \CoreLibs\Combined\ArrayHandler::flattenArrayKey($array);
} }
/** /**
* searches for key -> value in an array tree and writes the value one level up * searches for key -> value in an array tree and writes the value one level up
* this will remove this leaf will all other values * this will remove this leaf will all other values
* @param array $array array(nested) * @param array $array array (nested)
* @param string|int $search key to find that has no sub leaf and will be pushed up * @param string|int $search key to find that has no sub leaf and will be pushed up
* @return array modified, flattened array * @return array modified, flattened array
* @deprecated Use \CoreLibs\Combined\ArrayHandler::arrayFlatForKey() instead * @deprecated Use \CoreLibs\Combined\ArrayHandler::arrayFlatForKey() instead
*/ */
public static function arrayFlatForKey(array $array, $search): array public static function arrayFlatForKey(array $array, $search): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\ArrayHandler::arrayFlatForKey()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\ArrayHandler::arrayFlatForKey()', E_USER_DEPRECATED);
return \CoreLibs\Combined\ArrayHandler::arrayFlatForKey($array, $search); return \CoreLibs\Combined\ArrayHandler::arrayFlatForKey($array, $search);
} }
@@ -789,7 +735,7 @@ class Basic
public static function __mbMimeEncode(string $string, string $encoding): string public static function __mbMimeEncode(string $string, string $encoding): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Language\Encoding::__mbMimeEncode()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Language\Encoding::__mbMimeEncode()', E_USER_DEPRECATED);
return \CoreLibs\Language\Encoding::__mbMimeEncode($string, $encoding); return \CoreLibs\Language\Encoding::__mbMimeEncode($string, $encoding);
} }
@@ -809,7 +755,7 @@ class Basic
*/ */
public static function byteStringFormat($bytes, bool $space = true, bool $adjust = false, bool $si = false): string public static function byteStringFormat($bytes, bool $space = true, bool $adjust = false, bool $si = false): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Byte::humanReadableByteFormat()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Byte::humanReadableByteFormat()', E_USER_DEPRECATED);
$flags = 0; $flags = 0;
// match over the true/false flags to the new int style flag // match over the true/false flags to the new int style flag
// if space need to set 1 // if space need to set 1
@@ -851,7 +797,7 @@ class Basic
*/ */
public static function humanReadableByteFormat($bytes, int $flags = 0): string public static function humanReadableByteFormat($bytes, int $flags = 0): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Byte::humanReadableByteFormat()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Byte::humanReadableByteFormat()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Byte::humanReadableByteFormat($bytes, $flags); return \CoreLibs\Convert\Byte::humanReadableByteFormat($bytes, $flags);
} }
@@ -863,7 +809,7 @@ class Basic
*/ */
public static function stringByteFormat($number) public static function stringByteFormat($number)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Byte::stringByteFormat()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Byte::stringByteFormat()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Byte::stringByteFormat($number); return \CoreLibs\Convert\Byte::stringByteFormat($number);
} }
@@ -880,7 +826,7 @@ class Basic
*/ */
public static function dateStringFormat($timestamp, bool $show_micro = false): string public static function dateStringFormat($timestamp, bool $show_micro = false): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\DateTime::dateStringFormat()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\DateTime::dateStringFormat()', E_USER_DEPRECATED);
return \CoreLibs\Combined\DateTime::dateStringFormat($timestamp, $show_micro); return \CoreLibs\Combined\DateTime::dateStringFormat($timestamp, $show_micro);
} }
@@ -893,7 +839,7 @@ class Basic
*/ */
public static function timeStringFormat($timestamp, bool $show_micro = true): string public static function timeStringFormat($timestamp, bool $show_micro = true): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\DateTime::timeStringFormat()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\DateTime::timeStringFormat()', E_USER_DEPRECATED);
return \CoreLibs\Combined\DateTime::timeStringFormat($timestamp, $show_micro); return \CoreLibs\Combined\DateTime::timeStringFormat($timestamp, $show_micro);
} }
@@ -906,7 +852,7 @@ class Basic
*/ */
public static function stringToTime($timestring) public static function stringToTime($timestring)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\DateTime::stringToTime()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\DateTime::stringToTime()', E_USER_DEPRECATED);
return \CoreLibs\Combined\DateTime::stringToTime($timestring); return \CoreLibs\Combined\DateTime::stringToTime($timestring);
} }
@@ -918,7 +864,7 @@ class Basic
*/ */
public static function checkDate($date): bool public static function checkDate($date): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\DateTime::checkDate()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\DateTime::checkDate()', E_USER_DEPRECATED);
return \CoreLibs\Combined\DateTime::checkDate($date); return \CoreLibs\Combined\DateTime::checkDate($date);
} }
@@ -930,7 +876,7 @@ class Basic
*/ */
public static function checkDateTime($datetime): bool public static function checkDateTime($datetime): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\DateTime::checkDateTime()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\DateTime::checkDateTime()', E_USER_DEPRECATED);
return \CoreLibs\Combined\DateTime::checkDateTime($datetime); return \CoreLibs\Combined\DateTime::checkDateTime($datetime);
} }
@@ -948,7 +894,7 @@ class Basic
*/ */
public static function compareDate($start_date, $end_date) public static function compareDate($start_date, $end_date)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\DateTime::compareDate()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\DateTime::compareDate()', E_USER_DEPRECATED);
return \CoreLibs\Combined\DateTime::compareDate($start_date, $end_date); return \CoreLibs\Combined\DateTime::compareDate($start_date, $end_date);
} }
@@ -966,7 +912,7 @@ class Basic
*/ */
public static function compareDateTime($start_datetime, $end_datetime) public static function compareDateTime($start_datetime, $end_datetime)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\DateTime::compareDateTime()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\DateTime::compareDateTime()', E_USER_DEPRECATED);
return \CoreLibs\Combined\DateTime::compareDateTime($start_datetime, $end_datetime); return \CoreLibs\Combined\DateTime::compareDateTime($start_datetime, $end_datetime);
} }
@@ -982,7 +928,7 @@ class Basic
*/ */
public static function calcDaysInterval($start_date, $end_date, bool $return_named = false): array public static function calcDaysInterval($start_date, $end_date, bool $return_named = false): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Combined\DateTime::calcDaysInterval()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Combined\DateTime::calcDaysInterval()', E_USER_DEPRECATED);
return \CoreLibs\Combined\DateTime::calcDaysInterval($start_date, $end_date, $return_named); return \CoreLibs\Combined\DateTime::calcDaysInterval($start_date, $end_date, $return_named);
} }
@@ -1013,7 +959,7 @@ class Basic
string $cache_source = '', string $cache_source = '',
bool $clear_cache = false bool $clear_cache = false
) { ) {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Output\Image::createThumbnail()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Output\Image::createThumbnail()', E_USER_DEPRECATED);
return \CoreLibs\Output\Image::createThumbnail($pic, $size_x, $size_y, $dummy, $path, $cache_source, $clear_cache); return \CoreLibs\Output\Image::createThumbnail($pic, $size_x, $size_y, $dummy, $path, $cache_source, $clear_cache);
} }
@@ -1049,7 +995,7 @@ class Basic
bool $high_quality = true, bool $high_quality = true,
int $jpeg_quality = 80 int $jpeg_quality = 80
) { ) {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Output\Image::createThumbnailSimple()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Output\Image::createThumbnailSimple()', E_USER_DEPRECATED);
return \CoreLibs\Output\Image::createThumbnailSimple($filename, $thumb_width, $thumb_height, $thumbnail_path, $create_dummy, $use_cache, $high_quality, $jpeg_quality); return \CoreLibs\Output\Image::createThumbnailSimple($filename, $thumb_width, $thumb_height, $thumbnail_path, $create_dummy, $use_cache, $high_quality, $jpeg_quality);
} }
@@ -1063,7 +1009,7 @@ class Basic
*/ */
public function correctImageOrientation($filename): void public function correctImageOrientation($filename): void
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Output\Image::correctImageOrientation()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Output\Image::correctImageOrientation()', E_USER_DEPRECATED);
\CoreLibs\Output\Image::correctImageOrientation($filename); \CoreLibs\Output\Image::correctImageOrientation($filename);
} }
@@ -1092,7 +1038,7 @@ class Basic
*/ */
public function checkConvertEncoding(string $string, string $from_encoding, string $to_encoding) public function checkConvertEncoding(string $string, string $from_encoding, string $to_encoding)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Language\Encoding::checkConvertEncoding()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Language\Encoding::checkConvertEncoding()', E_USER_DEPRECATED);
return \CoreLibs\Language\Encoding::checkConvertEncoding($string, $from_encoding, $to_encoding); return \CoreLibs\Language\Encoding::checkConvertEncoding($string, $from_encoding, $to_encoding);
} }
@@ -1113,7 +1059,7 @@ class Basic
*/ */
public static function convertEncoding(string $string, string $to_encoding, string $source_encoding = '', bool $auto_check = true): string public static function convertEncoding(string $string, string $to_encoding, string $source_encoding = '', bool $auto_check = true): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Language\Encoding::convertEncoding()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Language\Encoding::convertEncoding()', E_USER_DEPRECATED);
return \CoreLibs\Language\Encoding::convertEncoding($string, $to_encoding, $source_encoding, $auto_check); return \CoreLibs\Language\Encoding::convertEncoding($string, $to_encoding, $source_encoding, $auto_check);
} }
@@ -1131,7 +1077,7 @@ class Basic
*/ */
public function __crc32b(string $string): string public function __crc32b(string $string): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\Hash::__crc32b()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Create\Hash::__crc32b()', E_USER_DEPRECATED);
return \CoreLibs\Create\Hash::__crc32b($string); return \CoreLibs\Create\Hash::__crc32b($string);
} }
@@ -1144,7 +1090,7 @@ class Basic
*/ */
public function __sha1Short(string $string, bool $use_sha = false): string public function __sha1Short(string $string, bool $use_sha = false): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\Hash::__sha1Short()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Create\Hash::__sha1Short()', E_USER_DEPRECATED);
return \CoreLibs\Create\Hash::__sha1Short($string, $use_sha); return \CoreLibs\Create\Hash::__sha1Short($string, $use_sha);
} }
@@ -1160,7 +1106,7 @@ class Basic
*/ */
public function __hash(string $string, string $hash_type = 'adler32'): string public function __hash(string $string, string $hash_type = 'adler32'): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\Hash::__hash()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Create\Hash::__hash()', E_USER_DEPRECATED);
return \CoreLibs\Create\Hash::__hash($string, $hash_type); return \CoreLibs\Create\Hash::__hash($string, $hash_type);
} }
@@ -1178,7 +1124,7 @@ class Basic
*/ */
public static function checkPHPVersion(string $min_version, string $max_version = ''): bool public static function checkPHPVersion(string $min_version, string $max_version = ''): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\PhpVersion::checkPHPVersion()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\PhpVersion::checkPHPVersion()', E_USER_DEPRECATED);
return \CoreLibs\Check\PhpVersion::checkPHPVersion($min_version, $max_version); return \CoreLibs\Check\PhpVersion::checkPHPVersion($min_version, $max_version);
} }
@@ -1195,7 +1141,7 @@ class Basic
*/ */
public static function uuidv4(): string public static function uuidv4(): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\Uids::uuidv4()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Create\Uids::uuidv4()', E_USER_DEPRECATED);
return \CoreLibs\Create\Uids::uuidv4(); return \CoreLibs\Create\Uids::uuidv4();
} }
@@ -1210,7 +1156,7 @@ class Basic
*/ */
public function uniqId(string $type = ''): string public function uniqId(string $type = ''): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Create\Uids::uniqId()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Create\Uids::uniqId()', E_USER_DEPRECATED);
return \CoreLibs\Create\Uids::uniqId($type); return \CoreLibs\Create\Uids::uniqId($type);
} }
@@ -1227,11 +1173,11 @@ class Basic
*/ */
private function passwordInit(): void private function passwordInit(): void
{ {
trigger_error('Method '.__METHOD__.' has been removed', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' has been removed', E_USER_DEPRECATED);
/* // set default password cost: use default set automatically /* // set default password cost: use default set automatically
$this->password_options = array( $this->password_options = [
// 'cost' => PASSWORD_BCRYPT_DEFAULT_COST // 'cost' => PASSWORD_BCRYPT_DEFAULT_COST
); */ ]; */
} }
/** /**
@@ -1242,7 +1188,7 @@ class Basic
*/ */
public function passwordSet(string $password): string public function passwordSet(string $password): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\Password::passwordSet()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\Password::passwordSet()', E_USER_DEPRECATED);
return \CoreLibs\Check\Password::passwordSet($password); return \CoreLibs\Check\Password::passwordSet($password);
} }
@@ -1255,7 +1201,7 @@ class Basic
*/ */
public function passwordVerify(string $password, string $hash): bool public function passwordVerify(string $password, string $hash): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\Password::passwordVerify()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\Password::passwordVerify()', E_USER_DEPRECATED);
return \CoreLibs\Check\Password::passwordVerify($password, $hash); return \CoreLibs\Check\Password::passwordVerify($password, $hash);
} }
@@ -1267,7 +1213,7 @@ class Basic
*/ */
public function passwordRehashCheck(string $hash): bool public function passwordRehashCheck(string $hash): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\Password::passwordRehashCheck()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\Password::passwordRehashCheck()', E_USER_DEPRECATED);
return \CoreLibs\Check\Password::passwordRehashCheck($hash); return \CoreLibs\Check\Password::passwordRehashCheck($hash);
} }
@@ -1287,7 +1233,7 @@ class Basic
*/ */
public static function hex2rgb(string $hexStr, bool $returnAsString = false, string $seperator = ',') public static function hex2rgb(string $hexStr, bool $returnAsString = false, string $seperator = ',')
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Colors::hex2rgb()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Colors::hex2rgb()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Colors::hex2rgb($hexStr, $returnAsString, $seperator); return \CoreLibs\Convert\Colors::hex2rgb($hexStr, $returnAsString, $seperator);
} }
@@ -1303,7 +1249,7 @@ class Basic
*/ */
public static function rgb2hex(int $red, int $green, int $blue, bool $hex_prefix = true): string public static function rgb2hex(int $red, int $green, int $blue, bool $hex_prefix = true): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Colors::rgb2hex()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Colors::rgb2hex()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Colors::rgb2hex($red, $green, $blue, $hex_prefix); return \CoreLibs\Convert\Colors::rgb2hex($red, $green, $blue, $hex_prefix);
} }
@@ -1317,7 +1263,7 @@ class Basic
*/ */
public static function rgb2html(int $red, int $green, int $blue): string public static function rgb2html(int $red, int $green, int $blue): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Colors::rgb2hex()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Colors::rgb2hex()', E_USER_DEPRECATED);
// check that each color is between 0 and 255 // check that each color is between 0 and 255
return \CoreLibs\Convert\Colors::rgb2hex($red, $green, $blue, true); return \CoreLibs\Convert\Colors::rgb2hex($red, $green, $blue, true);
} }
@@ -1334,7 +1280,7 @@ class Basic
*/ */
public static function rgb2hsb(int $red, int $green, int $blue): array public static function rgb2hsb(int $red, int $green, int $blue): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Colors::rgb2hsb()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Colors::rgb2hsb()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Colors::rgb2hsb($red, $green, $blue); return \CoreLibs\Convert\Colors::rgb2hsb($red, $green, $blue);
} }
@@ -1348,7 +1294,7 @@ class Basic
*/ */
public static function hsb2rgb(int $H, float $S, float $V): array public static function hsb2rgb(int $H, float $S, float $V): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Colors::hsb2rgb()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Colors::hsb2rgb()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Colors::hsb2rgb($H, (int)round($S * 100), (int)round($V * 100)); return \CoreLibs\Convert\Colors::hsb2rgb($H, (int)round($S * 100), (int)round($V * 100));
} }
@@ -1364,7 +1310,7 @@ class Basic
*/ */
public static function rgb2hsl(int $r, int $g, int $b): array public static function rgb2hsl(int $r, int $g, int $b): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Colors::rgb2hsl()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Colors::rgb2hsl()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Colors::rgb2hsb($r, $g, $b); return \CoreLibs\Convert\Colors::rgb2hsb($r, $g, $b);
} }
@@ -1378,7 +1324,7 @@ class Basic
*/ */
public static function hsl2rgb(int $h, float $s, float $l): array public static function hsl2rgb(int $h, float $s, float $l): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Colors::hsl2rgb()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Colors::hsl2rgb()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Colors::hsl2rgb($h, $s * 100, $l * 100); return \CoreLibs\Convert\Colors::hsl2rgb($h, $s * 100, $l * 100);
} }
@@ -1398,7 +1344,7 @@ class Basic
*/ */
public function getEmailType(string $email, bool $short = false) public function getEmailType(string $email, bool $short = false)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\Email::getEmailType()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\Email::getEmailType()', E_USER_DEPRECATED);
return \CoreLibs\Check\Email::getEmailType($email, $short); return \CoreLibs\Check\Email::getEmailType($email, $short);
} }
@@ -1410,7 +1356,7 @@ class Basic
*/ */
public function getShortEmailType(string $email_type) public function getShortEmailType(string $email_type)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\Email::getShortEmailType()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\Email::getShortEmailType()', E_USER_DEPRECATED);
return \CoreLibs\Check\Email::getShortEmailType($email_type); return \CoreLibs\Check\Email::getShortEmailType($email_type);
} }
@@ -1437,7 +1383,7 @@ class Basic
*/ */
public static function printDateTime($year, $month, $day, $hour, $min, string $suffix = '', int $min_steps = 1, bool $name_pos_back = false) public static function printDateTime($year, $month, $day, $hour, $min, string $suffix = '', int $min_steps = 1, bool $name_pos_back = false)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Output\Form\Elements::printDateTime()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Output\Form\Elements::printDateTime()', E_USER_DEPRECATED);
return \CoreLibs\Output\Form\Elements::printDateTime($year, $month, $day, $hour, $min, $suffix, $min_steps, $name_pos_back); return \CoreLibs\Output\Form\Elements::printDateTime($year, $month, $day, $hour, $min, $suffix, $min_steps, $name_pos_back);
} }
@@ -1451,7 +1397,7 @@ class Basic
*/ */
public static function htmlent($string) public static function htmlent($string)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Html::htmlent()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Html::htmlent()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Html::htmlent($string); return \CoreLibs\Convert\Html::htmlent($string);
} }
@@ -1464,7 +1410,7 @@ class Basic
*/ */
public static function removeLB(string $string, string $replace = ' '): string public static function removeLB(string $string, string $replace = ' '): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Html::removeLB()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Html::removeLB()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Html::removeLB($string, $replace); return \CoreLibs\Convert\Html::removeLB($string, $replace);
} }
@@ -1484,7 +1430,7 @@ class Basic
*/ */
public static function fceil(float $number, int $precision = 10): float public static function fceil(float $number, int $precision = 10): float
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Math::fceil()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Math::fceil()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Math::fceil($number, $precision); return \CoreLibs\Convert\Math::fceil($number, $precision);
} }
@@ -1498,7 +1444,7 @@ class Basic
*/ */
public static function floorp(float $number, int $precision = -2): float public static function floorp(float $number, int $precision = -2): float
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Math::floorp()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Math::floorp()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Math::floorp($number, $precision); return \CoreLibs\Convert\Math::floorp($number, $precision);
} }
@@ -1510,7 +1456,7 @@ class Basic
*/ */
public static function initNumeric($number): float public static function initNumeric($number): float
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\Math::initNumeric()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\Math::initNumeric()', E_USER_DEPRECATED);
return \CoreLibs\Convert\Math::initNumeric($number); return \CoreLibs\Convert\Math::initNumeric($number);
} }
@@ -1528,7 +1474,7 @@ class Basic
*/ */
public static function setFormToken(string $name = 'form_token'): string public static function setFormToken(string $name = 'form_token'): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Output\Form\Token::setFormToken()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Output\Form\Token::setFormToken()', E_USER_DEPRECATED);
return \CoreLibs\Output\Form\Token::setFormToken($name); return \CoreLibs\Output\Form\Token::setFormToken($name);
} }
@@ -1541,7 +1487,7 @@ class Basic
*/ */
public static function validateFormToken(string $token, string $name = 'form_token'): bool public static function validateFormToken(string $token, string $name = 'form_token'): bool
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Output\Form\Token::validateFormToken()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Output\Form\Token::validateFormToken()', E_USER_DEPRECATED);
return \CoreLibs\Output\Form\Token::validateFormToken($token, $name); return \CoreLibs\Output\Form\Token::validateFormToken($token, $name);
} }
@@ -1560,7 +1506,7 @@ class Basic
*/ */
public function mimeSetAppName(string $mime, string $app): void public function mimeSetAppName(string $mime, string $app): void
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\MimeAppName()->mimeSetAppName()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\MimeAppName()->mimeSetAppName()', E_USER_DEPRECATED);
\CoreLibs\Convert\MimeAppName::mimeSetAppName($mime, $app); \CoreLibs\Convert\MimeAppName::mimeSetAppName($mime, $app);
} }
@@ -1573,7 +1519,7 @@ class Basic
*/ */
public function mimeGetAppName(string $mime): string public function mimeGetAppName(string $mime): string
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Convert\MimeAppName()->mimeGetAppName()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Convert\MimeAppName()->mimeGetAppName()', E_USER_DEPRECATED);
return \CoreLibs\Convert\MimeAppName::mimeGetAppName($mime); return \CoreLibs\Convert\MimeAppName::mimeGetAppName($mime);
} }
@@ -1597,7 +1543,7 @@ class Basic
*/ */
public function jsonConvertToArray(?string $json, bool $override = false): array public function jsonConvertToArray(?string $json, bool $override = false): array
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\Jason::jsonConvertToArray()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\Jason::jsonConvertToArray()', E_USER_DEPRECATED);
return \CoreLibs\Check\Jason::jsonConvertToArray($json, $override); return \CoreLibs\Check\Jason::jsonConvertToArray($json, $override);
} }
@@ -1612,11 +1558,13 @@ class Basic
*/ */
public function jsonGetLastError(bool $return_string = false) public function jsonGetLastError(bool $return_string = false)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use \CoreLibs\Check\Jason::jsonGetLastError()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use \CoreLibs\Check\Jason::jsonGetLastError()', E_USER_DEPRECATED);
return \CoreLibs\Check\Jason::jsonGetLastError($return_string); return \CoreLibs\Check\Jason::jsonGetLastError($return_string);
} }
// *** JSON END *** // *** JSON END ***
} }
// phpcs:enable
// __END__ // __END__

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1); <?php
declare(strict_types=1);
namespace CoreLibs\Check; namespace CoreLibs\Check;
@@ -6,7 +8,8 @@ class Email
{ {
// this is for error check parts in where the email regex failed // this is for error check parts in where the email regex failed
private static $email_regex_check = [ 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 @ 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 @ 3 => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.([a-zA-Z]{2,}){1}$", // wrong part after @
@@ -18,28 +21,39 @@ class Email
// the array with the mobile types that are valid // the array with the mobile types that are valid
private static $mobile_email_type = [ private static $mobile_email_type = [
'.*@docomo\.ne\.jp$' => 'keitai_docomo', '.*@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] // 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-z0-9]{2}\.)?ezweb\.ne\.jp$' => 'keitai_kddi_ezweb',
'.*@([a-z]{2}\.)?sky\.tu-ka\.ne\.jp$' => 'keitai_kddi_tu-ka', # (sky group) // ez[a-j] or nothing
'.*@([a-z]{2}\.)?sky\.tk[kc]{1}\.ne\.jp$' => 'keitai_kddi_sky', # (sky group) [tkk,tkc only] '.*@(ez[a-j]{1}\.)?ido\.ne\.jp$' => 'keitai_kddi_ido',
'.*@([a-z]{2}\.)?sky\.dtg\.ne\.jp$' => 'keitai_kddi_dtg', # dtg (sky group) // (sky group)
'.*@[tkdhcrnsq]{1}\.vodafone\.ne\.jp$' => 'keitai_softbank_vodafone', # old vodafone [t,k,d,h,c,r,n,s,q] '.*@([a-z]{2}\.)?sky\.tu-ka\.ne\.jp$' => 'keitai_kddi_tu-ka',
'.*@jp-[dhtkrsnqc]{1}\.ne\.jp$' => 'keitai_softbank_j-phone', # very old j-phone (pre vodafone) [d,h,t,k,r,s,n,q,c] // (sky group) [tkk,tkc only]
'.*@([dhtcrknsq]{1}\.)?softbank\.ne\.jp$' => 'keitai_softbank', # add i for iphone also as keitai, others similar to the vodafone group '.*@([a-z]{2}\.)?sky\.tk[kc]{1}\.ne\.jp$' => 'keitai_kddi_sky',
'.*@i{1}\.softbank(\.ne)?\.jp$' => 'smartphone_softbank_iphone', # add iPhone also as keitai and not as pc // dtg (sky group)
'.*@disney\.ne\.jp$' => 'keitai_softbank_disney', # (kids) '.*@([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\.ne\.jp$' => 'keitai_willcom',
'.*@willcom\.com$' => 'keitai_willcom', # new for pdx.ne.jp address '.*@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
'.*@wcm\.ne\.jp$' => 'keitai_willcom', # old willcom wcm.ne.jp '.*@pdx\.ne\.jp$' => 'keitai_willcom_pdx', // old pdx address for willcom
'.*@pdx\.ne\.jp$' => 'keitai_willcom_pdx', # old pdx address for willcom '.*@bandai\.jp$' => 'keitai_willcom_bandai', // willcom paipo! (kids)
'.*@bandai\.jp$' => 'keitai_willcom_bandai', # willcom paipo! (kids) '.*@pipopa\.ne\.jp$' => 'keitai_willcom_pipopa', // 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', # 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([1]{1})?\.ne\.jp$' => 'keitai_willcom_ymobile', # ymobile, ymobile1 techincally not willcom, but I group them there (softbank sub) // 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) '.*@ymobile([1]{1})?\.ne\.jp$' => 'keitai_willcom_ymobile',
'.*@emnet\.ne\.jp$' => 'keitai_willcom_emnet', # e-mobile, group will willcom // y-mobile techincally not willcom, but I group them there (softbank sub)
'.*@emobile\.ne\.jp$' => 'keitai_willcom_emnet', # e-mobile, group will willcom '.*@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 '.*@emobile-s\.ne\.jp$' => 'keitai_willcom_emnet' # e-mobile, group will willcom
]; ];
// short list for mobile email types // short list for mobile email types
@@ -106,7 +120,13 @@ class Email
*/ */
public static function getEmailRegexCheck(): array 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
);
} }
/** /**

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* various file/file name functions * various file/file name functions
*/ */
declare(strict_types=1);
namespace CoreLibs\Check; namespace CoreLibs\Check;
class File class File
@@ -26,7 +28,8 @@ class File
*/ */
public static function getLinesFromFile(string $file): int public static function getLinesFromFile(string $file): int
{ {
if (is_file($file) && if (
is_file($file) &&
file_exists($file) && file_exists($file) &&
is_readable($file) is_readable($file)
) { ) {

View File

@@ -1,4 +1,4 @@
<?php declare(strict_types=1); <?php
/* /*
* Converts a json string to array and stores error for later checking * Converts a json string to array and stores error for later checking
@@ -6,6 +6,8 @@
* and self set json as is on error as array * and self set json as is on error as array
*/ */
declare(strict_types=1);
namespace CoreLibs\Check; namespace CoreLibs\Check;
class Jason class Jason

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* core password set, check and rehash check wrapper functions * core password set, check and rehash check wrapper functions
*/ */
declare(strict_types=1);
namespace CoreLibs\Check; namespace CoreLibs\Check;
class Password class Password

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1); <?php
declare(strict_types=1);
namespace CoreLibs\Check; namespace CoreLibs\Check;

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* html convert functions * html convert functions
*/ */
declare(strict_types=1);
namespace CoreLibs\Combined; namespace CoreLibs\Combined;
class ArrayHandler class ArrayHandler
@@ -23,7 +25,8 @@ class ArrayHandler
if (!is_array($haystack)) { if (!is_array($haystack)) {
$haystack = []; $haystack = [];
} }
if ($key_lookin != null && if (
$key_lookin != null &&
!empty($key_lookin) && !empty($key_lookin) &&
array_key_exists($key_lookin, $haystack) && array_key_exists($key_lookin, $haystack) &&
$needle === $haystack[$key_lookin] $needle === $haystack[$key_lookin]
@@ -31,20 +34,23 @@ class ArrayHandler
$path[] = $key_lookin; $path[] = $key_lookin;
} else { } else {
foreach ($haystack as $key => $val) { foreach ($haystack as $key => $val) {
if (is_scalar($val) && if (
is_scalar($val) &&
$val === $needle && $val === $needle &&
empty($key_lookin) empty($key_lookin)
) { ) {
$path[] = $key; $path[] = $key;
break; break;
} elseif (is_scalar($val) && } elseif (
is_scalar($val) &&
!empty($key_lookin) && !empty($key_lookin) &&
$key === $key_lookin && $key === $key_lookin &&
$val == $needle $val == $needle
) { ) {
$path[] = $key; $path[] = $key;
break; break;
} elseif (is_array($val) && } elseif (
is_array($val) &&
$path = self::arraySearchRecursive( $path = self::arraySearchRecursive(
$needle, $needle,
(array)$val, (array)$val,
@@ -122,7 +128,7 @@ class ArrayHandler
/** /**
* array search simple. looks for key, value combination, if found, returns true * array search simple. looks for key, value combination, if found, returns true
* @param array $array array(search in) * @param array $array search in as array
* @param string|int $key key (key to search in) * @param string|int $key key (key to search in)
* @param string|int $value value (what to find) * @param string|int $value value (what to find)
* @return bool true on found, false on not found * @return bool true on found, false on not found
@@ -160,7 +166,7 @@ class ArrayHandler
{ {
// croak on not enough arguemnts (we need at least two) // croak on not enough arguemnts (we need at least two)
if (func_num_args() < 2) { 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; return false;
} }
// default key is not string // default key is not string
@@ -174,14 +180,14 @@ class ArrayHandler
} }
// check that arrays count is at least two, else we don't have enough to do anything // check that arrays count is at least two, else we don't have enough to do anything
if (count($arrays) < 2) { 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; return false;
} }
$merged = []; $merged = [];
while ($arrays) { while ($arrays) {
$array = array_shift($arrays); $array = array_shift($arrays);
if (!is_array($array)) { 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; return false;
} }
if (!$array) { if (!$array) {
@@ -259,9 +265,10 @@ class ArrayHandler
{ {
$ret_array = []; $ret_array = [];
// do this to only run count once // 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 no key then we make an order reference
if ($key !== false && if (
$key !== false &&
$value !== false && $value !== false &&
(($set_only && $db_array[$i][$value]) || (!$set_only)) (($set_only && $db_array[$i][$value]) || (!$set_only))
) { ) {
@@ -313,7 +320,7 @@ class ArrayHandler
/** /**
* searches for key -> value in an array tree and writes the value one level up * searches for key -> value in an array tree and writes the value one level up
* this will remove this leaf will all other values * this will remove this leaf will all other values
* @param array $array array(nested) * @param array $array nested array
* @param string|int $search key to find that has no sub leaf and will be pushed up * @param string|int $search key to find that has no sub leaf and will be pushed up
* @return array modified, flattened array * @return array modified, flattened array
*/ */

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* image thumbnail, rotate, etc * image thumbnail, rotate, etc
*/ */
declare(strict_types=1);
namespace CoreLibs\Combined; namespace CoreLibs\Combined;
class DateTime class DateTime
@@ -21,7 +23,7 @@ class DateTime
list ($timestamp, $ms) = array_pad(explode('.', (string)round($timestamp, 4)), 2, null); list ($timestamp, $ms) = array_pad(explode('.', (string)round($timestamp, 4)), 2, null);
$string = date("Y-m-d H:i:s", (int)$timestamp); $string = date("Y-m-d H:i:s", (int)$timestamp);
if ($show_micro && $ms) { if ($show_micro && $ms) {
$string .= ' '.$ms.'ms'; $string .= ' ' . $ms . 'ms';
} }
return $string; return $string;
} }
@@ -50,12 +52,12 @@ class DateTime
if ($timestamp == 0) { if ($timestamp == 0) {
$time_string = '0s'; $time_string = '0s';
} else { } 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]); $output = floor((float)$timestamp / $timegroups[$i]);
$timestamp = (float)$timestamp % $timegroups[$i]; $timestamp = (float)$timestamp % $timegroups[$i];
// output has days|hours|min|sec // output has days|hours|min|sec
if ($output || $time_string) { if ($output || $time_string) {
$time_string .= $output.$labels[$i].(($i + 1) != count($timegroups) ? ' ' : ''); $time_string .= $output . $labels[$i] . (($i + 1) != count($timegroups) ? ' ' : '');
} }
} }
} }
@@ -65,13 +67,13 @@ class DateTime
$ms = preg_replace("/^0+(\d+)$/", '${1}', $ms); $ms = preg_replace("/^0+(\d+)$/", '${1}', $ms);
// add ms if there // add ms if there
if ($show_micro) { if ($show_micro) {
$time_string .= ' '.(!$ms ? 0 : $ms).'ms'; $time_string .= ' ' . (!$ms ? 0 : $ms) . 'ms';
} elseif (!$time_string) { } elseif (!$time_string) {
$time_string .= (!$ms ? 0 : $ms).'ms'; $time_string .= (!$ms ? 0 : $ms) . 'ms';
} }
} }
if ($negative) { if ($negative) {
$time_string = '-'.$time_string; $time_string = '-' . $time_string;
} }
} else { } else {
$time_string = $timestamp; $time_string = $timestamp;
@@ -108,7 +110,7 @@ class DateTime
} }
} }
if (isset($matches[10]) && is_numeric($matches[10])) { if (isset($matches[10]) && is_numeric($matches[10])) {
$timestamp .= '.'.$matches[10]; $timestamp .= '.' . $matches[10];
} }
if ($negative) { if ($negative) {
$timestamp *= -1; $timestamp *= -1;
@@ -159,7 +161,8 @@ class DateTime
if (!is_numeric($hour) || !is_numeric($min)) { if (!is_numeric($hour) || !is_numeric($min)) {
return false; return false;
} }
if (($hour < 0 || $hour > 24) || if (
($hour < 0 || $hour > 24) ||
($min < 0 || $min > 60) || ($min < 0 || $min > 60) ||
(is_numeric($sec) && ($sec < 0 || $sec > 60)) (is_numeric($sec) && ($sec < 0 || $sec > 60))
) { ) {
@@ -190,17 +193,17 @@ class DateTime
list ($start_year, $start_month, $start_day) = array_pad(preg_split('/[\/-]/', $start_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); 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 // check that month & day are two digits and then combine
foreach (array('start', 'end') as $prefix) { foreach (['start', 'end'] as $prefix) {
foreach (array('month', 'day') as $date_part) { foreach (['month', 'day'] as $date_part) {
$_date = $prefix.'_'.$date_part; $_date = $prefix . '_' . $date_part;
if (isset($$_date) && $$_date < 10 && !preg_match("/^0/", $$_date)) { if (isset($$_date) && $$_date < 10 && !preg_match("/^0/", $$_date)) {
$$_date = '0'.$$_date; $$_date = '0' . $$_date;
} }
} }
$_date = $prefix.'_date'; $_date = $prefix . '_date';
$$_date = ''; $$_date = '';
foreach (array('year', 'month', 'day') as $date_part) { foreach (['year', 'month', 'day'] as $date_part) {
$_sub_date = $prefix.'_'.$date_part; $_sub_date = $prefix . '_' . $date_part;
$$_date .= $$_sub_date; $$_date .= $$_sub_date;
} }
} }
@@ -254,7 +257,7 @@ class DateTime
public static function calcDaysInterval($start_date, $end_date, bool $return_named = false): array public static function calcDaysInterval($start_date, $end_date, bool $return_named = false): array
{ {
// pos 0 all, pos 1 weekday, pos 2 weekend // pos 0 all, pos 1 weekday, pos 2 weekend
$days = array(); $days = [];
$start = new \DateTime($start_date); $start = new \DateTime($start_date);
$end = new \DateTime($end_date); $end = new \DateTime($end_date);
// so we include the last day too, we need to add +1 second in the time // so we include the last day too, we need to add +1 second in the time
@@ -275,11 +278,11 @@ class DateTime
} }
} }
if ($return_named === true) { if ($return_named === true) {
return array( return [
'overall' => $days[0], 'overall' => $days[0],
'weekday' => $days[1], 'weekday' => $days[1],
'weekend' => $days[2] 'weekend' => $days[2]
); ];
} else { } else {
return $days; return $days;
} }

View File

@@ -1,17 +1,19 @@
<?php declare(strict_types=1); <?php
/* /*
* image thumbnail, rotate, etc * image thumbnail, rotate, etc
*/ */
declare(strict_types=1);
namespace CoreLibs\Convert; namespace CoreLibs\Convert;
class Byte class Byte
{ {
// define byteFormat // define byteFormat
const BYTE_FORMAT_NOSPACE = 1; public const BYTE_FORMAT_NOSPACE = 1;
const BYTE_FORMAT_ADJUST = 2; public const BYTE_FORMAT_ADJUST = 2;
const BYTE_FORMAT_SI = 4; public const BYTE_FORMAT_SI = 4;
/** /**
* This function replaces the old byteStringFormat * This function replaces the old byteStringFormat
@@ -62,10 +64,10 @@ class Byte
$abs_bytes = $bytes == PHP_INT_MIN ? PHP_INT_MAX : abs($bytes); $abs_bytes = $bytes == PHP_INT_MIN ? PHP_INT_MAX : abs($bytes);
// smaller than unit is always B // smaller than unit is always B
if ($abs_bytes < $unit) { if ($abs_bytes < $unit) {
return $bytes.'B'; return $bytes . 'B';
} }
// labels in order of size [Y, Z] // 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 position calculation
$exp = floor(log($abs_bytes, $unit)); $exp = floor(log($abs_bytes, $unit));
// avoid printing out anything larger than max labels // avoid printing out anything larger than max labels
@@ -75,13 +77,14 @@ class Byte
// deviation calculation // deviation calculation
$dev = pow($unit, $exp) * ($unit - 0.05); $dev = pow($unit, $exp) * ($unit - 0.05);
// shift the exp +1 for on the border units // shift the exp +1 for on the border units
if ($exp < 6 && if (
$exp < 6 &&
$abs_bytes > ($dev - (((int)$dev & 0xfff) == 0xd00 ? 52 : 0)) $abs_bytes > ($dev - (((int)$dev & 0xfff) == 0xd00 ? 52 : 0))
) { ) {
$exp ++; $exp++;
} }
// label name, including leading space if flagged // 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); $bytes_calc = $abs_bytes / pow($unit, $exp);
// if original is negative, reverse // if original is negative, reverse
if ($bytes < 0) { if ($bytes < 0) {
@@ -90,7 +93,7 @@ class Byte
if ($adjust) { if ($adjust) {
return sprintf("%.2f%s", $bytes_calc, $pre); return sprintf("%.2f%s", $bytes_calc, $pre);
} else { } else {
return round($bytes_calc, 2).$pre; return round($bytes_calc, 2) . $pre;
} }
} else { } else {
// if anything other return as string // if anything other return as string
@@ -120,7 +123,11 @@ class Byte
// all valid units // all valid units
$valid_units_ = 'bkmgtpezy'; $valid_units_ = 'bkmgtpezy';
// detects up to exo bytes // 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($number),
$matches
);
if (isset($matches[1]) && isset($matches[2])) { if (isset($matches[1]) && isset($matches[2])) {
// remove all non valid characters from the number // remove all non valid characters from the number
$number = preg_replace('/[^0-9\.]/', '', $matches[1]); $number = preg_replace('/[^0-9\.]/', '', $matches[1]);

View File

@@ -1,4 +1,4 @@
<?php declare(strict_types=1); <?php
/* /*
* Convert color spaces * Convert color spaces
@@ -10,6 +10,8 @@
* hsl to rgb * hsl to rgb
*/ */
declare(strict_types=1);
namespace CoreLibs\Convert; namespace CoreLibs\Convert;
class Colors class Colors
@@ -24,7 +26,7 @@ class Colors
public static function hex2rgb(string $hexStr, bool $returnAsString = false, string $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 $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
$rgbArray = array(); $rgbArray = [];
if (strlen($hexStr) == 6) { if (strlen($hexStr) == 6) {
// If a proper hex code, convert using bitwise operation. No overhead... faster // If a proper hex code, convert using bitwise operation. No overhead... faster
$colorVal = hexdec($hexStr); $colorVal = hexdec($hexStr);
@@ -59,7 +61,7 @@ class Colors
if ($hex_prefix === true) { if ($hex_prefix === true) {
$hex_color = '#'; $hex_color = '#';
} }
foreach (array('red', 'green', 'blue') as $color) { foreach (['red', 'green', 'blue'] as $color) {
// if not valid, set to gray // if not valid, set to gray
if ($$color < 0 || $$color > 255) { if ($$color < 0 || $$color > 255) {
$$color = 125; $$color = 125;
@@ -82,7 +84,7 @@ class Colors
public static function rgb2hsb(int $red, int $green, int $blue): array public static function rgb2hsb(int $red, int $green, int $blue): array
{ {
// check that rgb is from 0 to 255 // 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) { if ($$c < 0 || $$c > 255) {
$$c = 0; $$c = 0;
} }
@@ -94,7 +96,7 @@ class Colors
$HUE = 0; $HUE = 0;
if ($MAX == $MIN) { if ($MAX == $MIN) {
return array(0, 0, round($MAX * 100)); return [0, 0, round($MAX * 100)];
} }
if ($red == $MAX) { if ($red == $MAX) {
$HUE = ($green - $blue) / ($MAX - $MIN); $HUE = ($green - $blue) / ($MAX - $MIN);
@@ -108,11 +110,11 @@ class Colors
$HUE += 360; $HUE += 360;
} }
return array( return [
(int)round($HUE), (int)round($HUE),
(int)round((($MAX - $MIN) / $MAX) * 100), (int)round((($MAX - $MIN) / $MAX) * 100),
(int)round($MAX * 100) (int)round($MAX * 100)
); ];
} }
/** /**
@@ -140,7 +142,7 @@ class Colors
$V /= 100; $V /= 100;
if ($S == 0) { if ($S == 0) {
return array($V * 255, $V * 255, $V * 255); return [$V * 255, $V * 255, $V * 255];
} }
$Hi = floor($H / 60); $Hi = floor($H / 60);
@@ -186,11 +188,11 @@ class Colors
$blue = 0; $blue = 0;
} }
return array( return [
(int)round($red * 255), (int)round($red * 255),
(int)round($green * 255), (int)round($green * 255),
(int)round($blue * 255) (int)round($blue * 255)
); ];
} }
/** /**
@@ -205,7 +207,7 @@ class Colors
public static function rgb2hsl(int $red, int $green, int $blue): array public static function rgb2hsl(int $red, int $green, int $blue): array
{ {
// check that rgb is from 0 to 255 // 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) { if ($$c < 0 || $$c > 255) {
$$c = 0; $$c = 0;
} }
@@ -270,7 +272,7 @@ class Colors
$lum /= 100; $lum /= 100;
// if saturation is 0 // if saturation is 0
if ($sat == 0) { if ($sat == 0) {
return array($lum * 255, $lum * 255, $lum * 255); return [$lum * 255, $lum * 255, $lum * 255];
} else { } else {
$m2 = $lum < 0.5 ? $lum * ($sat + 1) : ($lum + $sat) - ($lum * $sat); $m2 = $lum < 0.5 ? $lum * ($sat + 1) : ($lum + $sat) - ($lum * $sat);
$m1 = $lum * 2 - $m2; $m1 = $lum * 2 - $m2;
@@ -292,11 +294,11 @@ class Colors
return $m1; return $m1;
}; };
return array( return [
(int)round(255 * $hueue($hue + (1 / 3))), (int)round(255 * $hueue($hue + (1 / 3))),
(int)round(255 * $hueue($hue)), (int)round(255 * $hueue($hue)),
(int)round(255 * $hueue($hue - (1 / 3))) (int)round(255 * $hueue($hue - (1 / 3)))
); ];
} }
} }
} }

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* html convert functions * html convert functions
*/ */
declare(strict_types=1);
namespace CoreLibs\Convert; namespace CoreLibs\Convert;
class Html class Html
@@ -16,7 +18,7 @@ class Html
public static function htmlent($string) public static function htmlent($string)
{ {
if (is_string($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 { } else {
return $string; return $string;
} }
@@ -30,7 +32,7 @@ class Html
*/ */
public static function removeLB(string $string, string $replace = ' '): string public static function removeLB(string $string, string $replace = ' '): string
{ {
return str_replace(array("\r", "\n"), $replace, $string); return str_replace(["\r", "\n"], $replace, $string);
} }
/** /**

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* various math related function wrappers * various math related function wrappers
*/ */
declare(strict_types=1);
namespace CoreLibs\Convert; namespace CoreLibs\Convert;
class Math class Math

View File

@@ -1,10 +1,12 @@
<?php declare(strict_types=1); <?php
/* /*
* Translates a mime id string into the actual application or file name * Translates a mime id string into the actual application or file name
* for example 'text/plain' will output 'Text file' * for example 'text/plain' will output 'Text file'
*/ */
declare(strict_types=1);
namespace CoreLibs\Convert; namespace CoreLibs\Convert;
class MimeAppName class MimeAppName

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* hash wrapper functions for old problem fixes * hash wrapper functions for old problem fixes
*/ */
declare(strict_types=1);
namespace CoreLibs\Create; namespace CoreLibs\Create;
class Hash class Hash

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* html convert functions * html convert functions
*/ */
declare(strict_types=1);
namespace CoreLibs\Create; namespace CoreLibs\Create;
class RandomKey class RandomKey
@@ -39,7 +41,8 @@ class RandomKey
*/ */
private static function validateRandomKeyLenght(int $key_length): bool private static function validateRandomKeyLenght(int $key_length): bool
{ {
if (is_numeric($key_length) && if (
is_numeric($key_length) &&
$key_length > 0 && $key_length > 0 &&
$key_length <= self::$max_key_length $key_length <= self::$max_key_length
) { ) {
@@ -98,7 +101,7 @@ class RandomKey
} }
$pieces = []; $pieces = [];
for ($i = 1; $i <= $use_key_length; $i ++) { for ($i = 1; $i <= $use_key_length; $i++) {
$pieces[] = self::$key_range[random_int(0, self::$one_key_length - 1)]; $pieces[] = self::$key_range[random_int(0, self::$one_key_length - 1)];
} }
return join('', $pieces); return join('', $pieces);

View File

@@ -1,4 +1,6 @@
<?php declare(strict_types=1); <?php
declare(strict_types=1);
namespace CoreLibs\Create; namespace CoreLibs\Create;

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1); <?php
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2002/12/17 * CREATED: 2002/12/17
@@ -6,7 +7,7 @@
* RELEASED LICENSE: GNU GPL 3 * RELEASED LICENSE: GNU GPL 3
* SHORT DESC :RIPTION: * SHORT DESC :RIPTION:
* DB Array IO Class: * DB Array IO Class:
* writes, reads or deletes a complete array(one data set) in/out a * writes, reads or deletes a complete array (one data set) in/out a
* table from the connected DB. * table from the connected DB.
* you don't have to write any SQL queries, worry over update/insert * you don't have to write any SQL queries, worry over update/insert
* *
@@ -29,6 +30,8 @@
// as it actually has nothing to do with this one here ? (or at least // as it actually has nothing to do with this one here ? (or at least
// put into separete function in this class) // put into separete function in this class)
declare(strict_types=1);
namespace CoreLibs\DB\Extended; namespace CoreLibs\DB\Extended;
// subclass for one array handling // subclass for one array handling
@@ -122,7 +125,7 @@ class ArrayIO extends \CoreLibs\DB\IO
reset($this->table_array); reset($this->table_array);
$string = ''; $string = '';
foreach ($this->table_array as $column => $data_array) { foreach ($this->table_array as $column => $data_array) {
$string .= '<b>'.$column.'</b> -> '.$data_array['value'].'<br>'; $string .= '<b>' . $column . '</b> -> ' . $data_array['value'] . '<br>';
} }
// add output to internal error_msg // add output to internal error_msg
if ($write === true) { if ($write === true) {
@@ -185,22 +188,23 @@ class ArrayIO extends \CoreLibs\DB\IO
return $this->table_array; return $this->table_array;
} }
// delete query // delete query
$q = 'DELETE FROM '.$this->table_name.' WHERE '; $q = 'DELETE FROM ' . $this->table_name . ' WHERE ';
$q .= $this->pk_name.' = '.$this->table_array[$this->pk_name]['value'].' '; $q .= $this->pk_name . ' = ' . $this->table_array[$this->pk_name]['value'] . ' ';
// delete files and build FK query // delete files and build FK query
reset($this->table_array); reset($this->table_array);
$q_where = ''; $q_where = '';
foreach ($this->table_array as $column => $data_array) { foreach ($this->table_array as $column => $data_array) {
// suchen nach bildern und lschen ... // suchen nach bildern und lschen ...
if (!empty($this->table_array[$column]['file']) && if (
file_exists($this->table_array[$column]['url'].$this->table_array[$column]['value']) !empty($this->table_array[$column]['file']) &&
file_exists($this->table_array[$column]['url'] . $this->table_array[$column]['value'])
) { ) {
if (file_exists($this->table_array[$column]['path'].$this->table_array[$column]['value'])) { if (file_exists($this->table_array[$column]['path'] . $this->table_array[$column]['value'])) {
unlink($this->table_array[$column]['path'].$this->table_array[$column]['value']); unlink($this->table_array[$column]['path'] . $this->table_array[$column]['value']);
} }
$file_name = str_replace('_tn', '', $this->table_array[$column]['value']); $file_name = str_replace('_tn', '', $this->table_array[$column]['value']);
if (file_exists($this->table_array[$column]['path'].$file_name)) { if (file_exists($this->table_array[$column]['path'] . $file_name)) {
unlink($this->table_array[$column]['path'].$file_name); unlink($this->table_array[$column]['path'] . $file_name);
} }
} }
// if we have a foreign key // if we have a foreign key
@@ -209,7 +213,7 @@ class ArrayIO extends \CoreLibs\DB\IO
if ($q_where) { if ($q_where) {
$q_where .= ' AND '; $q_where .= ' AND ';
} }
$q_where .= $column.' = '.$this->table_array[$column]['value']; $q_where .= $column . ' = ' . $this->table_array[$column]['value'];
} }
// allgemeines zurcksetzen des arrays // allgemeines zurcksetzen des arrays
unset($this->table_array[$column]['value']); unset($this->table_array[$column]['value']);
@@ -217,7 +221,7 @@ class ArrayIO extends \CoreLibs\DB\IO
// attach fk row if there ... // attach fk row if there ...
if ($q_where) { if ($q_where) {
$q .= ' AND '.$q_where; $q .= ' AND ' . $q_where;
} }
// if 0, error // if 0, error
$this->pk_id = null; $this->pk_id = null;
@@ -258,16 +262,16 @@ class ArrayIO extends \CoreLibs\DB\IO
if ($q_where) { if ($q_where) {
$q_where .= ' AND '; $q_where .= ' AND ';
} }
$q_where .= $column .= ' = '.$this->table_array[$column]['value']; $q_where .= $column .= ' = ' . $this->table_array[$column]['value'];
} }
} }
$q = 'SELECT '; $q = 'SELECT ';
$q .= $q_select; $q .= $q_select;
$q .= ' FROM '.$this->table_name.' WHERE '; $q .= ' FROM ' . $this->table_name . ' WHERE ';
$q .= $this->pk_name.' = '.$this->table_array[$this->pk_name]['value'].' '; $q .= $this->pk_name . ' = ' . $this->table_array[$this->pk_name]['value'] . ' ';
if ($q_where) { if ($q_where) {
$q .= ' AND '.$q_where; $q .= ' AND ' . $q_where;
} }
// if query was executed okay, else set error // if query was executed okay, else set error
@@ -277,11 +281,13 @@ class ArrayIO extends \CoreLibs\DB\IO
foreach ($this->table_array as $column => $data_array) { foreach ($this->table_array as $column => $data_array) {
// wenn "edit" dann gib daten wie in DB zurück, ansonten aufbereiten fr ausgabe // wenn "edit" dann gib daten wie in DB zurück, ansonten aufbereiten fr ausgabe
// ?? sollte das nicht drauen ??? man weis ja net was da drin steht --> is noch zu berlegen // ?? sollte das nicht drauen ??? man weis ja net was da drin steht --> is noch zu berlegen
// echo 'EDIT: $edit | Spalte: $column | type: '.$this->table_array[$column]['type'].' | Res: '.$res[$column].'<br>'; // $this->log->debug('DB READ', 'EDIT: $edit | Spalte: $column | type: '
// .$this->table_array[$column]['type'].' | Res: '.$res[$column]);
if ($edit) { if ($edit) {
$this->table_array[$column]['value'] = $res[$column]; $this->table_array[$column]['value'] = $res[$column];
// if password, also write to hidden // if password, also write to hidden
if (isset($this->table_array[$column]['type']) && if (
isset($this->table_array[$column]['type']) &&
$this->table_array[$column]['type'] == 'password' $this->table_array[$column]['type'] == 'password'
) { ) {
$this->table_array[$column]['HIDDEN_value'] = $res[$column]; $this->table_array[$column]['HIDDEN_value'] = $res[$column];
@@ -336,12 +342,12 @@ class ArrayIO extends \CoreLibs\DB\IO
// falls in 'delete' 'ja' dann loeschen (und gibts eh nur beim update) // falls in 'delete' 'ja' dann loeschen (und gibts eh nur beim update)
if ($this->table_array[$column]['delete']) { if ($this->table_array[$column]['delete']) {
unset($this->table_array[$column]['delete']); unset($this->table_array[$column]['delete']);
if (file_exists($this->table_array[$column]['path'].$this->table_array[$column]['value'])) { if (file_exists($this->table_array[$column]['path'] . $this->table_array[$column]['value'])) {
unlink($this->table_array[$column]['path'].$this->table_array[$column]['value']); unlink($this->table_array[$column]['path'] . $this->table_array[$column]['value']);
} }
$file_name = str_replace('_tn', '', $this->table_array[$column]['value']); $file_name = str_replace('_tn', '', $this->table_array[$column]['value']);
if (file_exists($this->table_array[$column]['path'].$file_name)) { if (file_exists($this->table_array[$column]['path'] . $file_name)) {
unlink($this->table_array[$column]['path'].$file_name); unlink($this->table_array[$column]['path'] . $file_name);
} }
$this->table_array[$column]['value'] = ''; $this->table_array[$column]['value'] = '';
} else { } else {
@@ -351,26 +357,26 @@ class ArrayIO extends \CoreLibs\DB\IO
// mozilla, patch // mozilla, patch
$fn_name = explode('/', $this->table_array[$column]['dn']); $fn_name = explode('/', $this->table_array[$column]['dn']);
$this->table_array[$column]['dn'] = $fn_name[count($fn_name)-1]; $this->table_array[$column]['dn'] = $fn_name[count($fn_name) - 1];
$filename_parts = explode('.', $this->table_array[$column]['dn']); $filename_parts = explode('.', $this->table_array[$column]['dn']);
$ext = end($filename_parts); $ext = end($filename_parts);
array_splice($filename_parts, -1, 1); array_splice($filename_parts, -1, 1);
$name = str_replace(' ', '_', implode('.', $filename_parts)); $name = str_replace(' ', '_', implode('.', $filename_parts));
$file_name = $name.'.'.$ext; $file_name = $name . '.' . $ext;
//echo 'Dn: $file_name'; //echo 'Dn: $file_name';
copy($this->table_array[$column]['tmp'], $this->table_array[$column]['path'].$file_name); copy($this->table_array[$column]['tmp'], $this->table_array[$column]['path'] . $file_name);
// automatisch thumbnail generieren, geht nur mit convert (ImageMagic!!!), aber nur bei bild .. // automatisch thumbnail generieren, geht nur mit convert (ImageMagic!!!), aber nur bei bild ..
if (strtolower($ext) == 'jpeg' || strtolower($ext) == 'jpg' || strtolower($ext) == 'gif' || strtolower($ext) == 'png') { if (in_array(strtolower($ext), ['jpeg', 'jpg', 'gif', 'png'])) {
$file_name_tn = $name.'_tn.'.$ext; $file_name_tn = $name . '_tn.' . $ext;
$input = $this->table_array[$column]['path'].$file_name; $input = $this->table_array[$column]['path'] . $file_name;
$output = $this->table_array[$column]['path'].$file_name_tn; $output = $this->table_array[$column]['path'] . $file_name_tn;
$com = 'convert -geometry 115 '.$input.' '.$output; $com = 'convert -geometry 115 ' . $input . ' ' . $output;
exec($com); exec($com);
$this->table_array[$column]['value'] = $file_name_tn; $this->table_array[$column]['value'] = $file_name_tn;
} else { } else {
$this->table_array[$column]['value'] = $file_name; $this->table_array[$column]['value'] = $file_name;
} }
} elseif (file_exists($this->table_array[$column]['path'].$this->table_array[$column]['value'])) { } elseif (file_exists($this->table_array[$column]['path'] . $this->table_array[$column]['value'])) {
// mach gar nix, wenn bild schon da ??? // mach gar nix, wenn bild schon da ???
} }
} // delete or upload } // delete or upload
@@ -378,13 +384,15 @@ class ArrayIO extends \CoreLibs\DB\IO
/********************************* END FILE **************************************/ /********************************* END FILE **************************************/
// do not write 'pk' (primary key) or 'view' values // do not write 'pk' (primary key) or 'view' values
if (!isset($this->table_array[$column]['pk']) && if (
!isset($this->table_array[$column]['pk']) &&
isset($this->table_array[$column]['type']) && isset($this->table_array[$column]['type']) &&
$this->table_array[$column]['type'] != 'view' && $this->table_array[$column]['type'] != 'view' &&
strlen($column) > 0 strlen($column) > 0
) { ) {
// for password use hidden value if main is not set // for password use hidden value if main is not set
if (isset($this->table_array[$column]['type']) && if (
isset($this->table_array[$column]['type']) &&
$this->table_array[$column]['type'] == 'password' && $this->table_array[$column]['type'] == 'password' &&
empty($this->table_array[$column]['value']) empty($this->table_array[$column]['value'])
) { ) {
@@ -394,7 +402,7 @@ class ArrayIO extends \CoreLibs\DB\IO
if (strlen($q_data)) { if (strlen($q_data)) {
$q_data .= ', '; $q_data .= ', ';
} }
$q_data .= $column.' = '; $q_data .= $column . ' = ';
} else { } else {
// this is insert // this is insert
if (strlen($q_data)) { if (strlen($q_data)) {
@@ -407,15 +415,18 @@ class ArrayIO extends \CoreLibs\DB\IO
} }
// integer is different // integer is different
if (isset($this->table_array[$column]['int']) || isset($this->table_array[$column]['int_null'])) { if (isset($this->table_array[$column]['int']) || isset($this->table_array[$column]['int_null'])) {
$this->log->debug('write_check', '['.$column.']['.$this->table_array[$column]['value'].']['.$this->table_array[$column]['type'].'] '. $this->log->debug('WRITE CHECK', '[' . $column . '][' . $this->table_array[$column]['value'] . ']'
'VALUE SET: '.(string)isset($this->table_array[$column]['value']). . '[' . $this->table_array[$column]['type'] . '] '
' | INT NULL: '.(string)isset($this->table_array[$column]['int_null'])); . 'VALUE SET: ' . (string)isset($this->table_array[$column]['value'])
if (isset($this->table_array[$column]['value']) && . ' | INT NULL: ' . (string)isset($this->table_array[$column]['int_null']));
if (
isset($this->table_array[$column]['value']) &&
!$this->table_array[$column]['value'] && !$this->table_array[$column]['value'] &&
isset($this->table_array[$column]['int_null']) isset($this->table_array[$column]['int_null'])
) { ) {
$_value = 'NULL'; $_value = 'NULL';
} elseif (!isset($this->table_array[$column]['value']) || } elseif (
!isset($this->table_array[$column]['value']) ||
(isset($this->table_array[$column]['value']) && !$this->table_array[$column]['value']) (isset($this->table_array[$column]['value']) && !$this->table_array[$column]['value'])
) { ) {
$_value = 0; $_value = 0;
@@ -425,10 +436,11 @@ class ArrayIO extends \CoreLibs\DB\IO
$q_data .= $_value; $q_data .= $_value;
} elseif (isset($this->table_array[$column]['bool'])) { } elseif (isset($this->table_array[$column]['bool'])) {
// boolean storeage (reverse check on ifset) // boolean storeage (reverse check on ifset)
$q_data .= "'".$this->dbBoolean($this->table_array[$column]['value'], true)."'"; $q_data .= "'" . $this->dbBoolean($this->table_array[$column]['value'], true) . "'";
} elseif (isset($this->table_array[$column]['interval'])) { } elseif (isset($this->table_array[$column]['interval'])) {
// for interval we check if no value, then we set null // for interval we check if no value, then we set null
if (!isset($this->table_array[$column]['value']) || if (
!isset($this->table_array[$column]['value']) ||
(isset($this->table_array[$column]['value']) && !$this->table_array[$column]['value']) (isset($this->table_array[$column]['value']) && !$this->table_array[$column]['value'])
) { ) {
$_value = 'NULL'; $_value = 'NULL';
@@ -442,9 +454,14 @@ class ArrayIO extends \CoreLibs\DB\IO
} else { } else {
// if the error check is json, we set field to null if NOT set // if the error check is json, we set field to null if NOT set
// else normal string write // else normal string write
if (isset($this->table_array[$column]['error_check']) && if (
isset($this->table_array[$column]['error_check']) &&
$this->table_array[$column]['error_check'] == 'json' && $this->table_array[$column]['error_check'] == 'json' &&
(!isset($this->table_array[$column]['value']) || (isset($this->table_array[$column]['value']) && !$this->table_array[$column]['value'])) (
!isset($this->table_array[$column]['value']) ||
(isset($this->table_array[$column]['value']) &&
!$this->table_array[$column]['value'])
)
) { ) {
$q_data .= 'NULL'; $q_data .= 'NULL';
} else { } else {
@@ -452,7 +469,9 @@ class ArrayIO extends \CoreLibs\DB\IO
$q_data .= "'"; $q_data .= "'";
// if add slashes do convert & add slashes else write AS is // if add slashes do convert & add slashes else write AS is
if ($addslashes) { if ($addslashes) {
$q_data .= $this->dbEscapeString($this->convertEntities($this->table_array[$column]['value'])); $q_data .= $this->dbEscapeString(
$this->convertEntities($this->table_array[$column]['value'])
);
} else { } else {
$q_data .= $this->dbEscapeString($this->table_array[$column]['value']); $q_data .= $this->dbEscapeString($this->table_array[$column]['value']);
} }
@@ -472,14 +491,14 @@ class ArrayIO extends \CoreLibs\DB\IO
if (!empty($q_where)) { if (!empty($q_where)) {
$q_where .= ' AND '; $q_where .= ' AND ';
} }
$q_where .= $column .= ' = '.$this->table_array[$column]['value']; $q_where .= $column .= ' = ' . $this->table_array[$column]['value'];
} }
} }
// if no PK set, then get max ID from DB // if no PK set, then get max ID from DB
if (!$this->table_array[$this->pk_name]['value']) { if (!$this->table_array[$this->pk_name]['value']) {
// max id, falls INSERT // max id, falls INSERT
$q = 'SELECT MAX('.$this->pk_name.') + 1 AS pk_id FROM '.$this->table_name; $q = 'SELECT MAX(' . $this->pk_name . ') + 1 AS pk_id FROM ' . $this->table_name;
$res = $this->dbReturnRow($q); $res = $this->dbReturnRow($q);
if (!isset($res['pk_id'])) { if (!isset($res['pk_id'])) {
$res['pk_id'] = 1; $res['pk_id'] = 1;
@@ -488,19 +507,19 @@ class ArrayIO extends \CoreLibs\DB\IO
} }
if (!$insert) { if (!$insert) {
$q = 'UPDATE '.$this->table_name.' SET '; $q = 'UPDATE ' . $this->table_name . ' SET ';
$q .= $q_data; $q .= $q_data;
$q .= ' WHERE '; $q .= ' WHERE ';
$q .= $this->pk_name.' = '.$this->table_array[$this->pk_name]['value'].' '; $q .= $this->pk_name . ' = ' . $this->table_array[$this->pk_name]['value'] . ' ';
if (!empty($q_where)) { if (!empty($q_where)) {
$q .= ' AND '.$q_where; $q .= ' AND ' . $q_where;
} }
// set pk_id ... if it has changed or so // set pk_id ... if it has changed or so
$this->pk_id = $this->table_array[$this->pk_name]['value']; $this->pk_id = $this->table_array[$this->pk_name]['value'];
} else { } else {
$q = 'INSERT INTO '.$this->table_name.' '; $q = 'INSERT INTO ' . $this->table_name . ' ';
$q .= '('.$q_vars.') '; $q .= '(' . $q_vars . ') ';
$q .= 'VALUES ('.$q_data.')'; $q .= 'VALUES (' . $q_data . ')';
// write primary key too // write primary key too
// if ($q_data) // if ($q_data)
// $q .= ", "; // $q .= ", ";
@@ -520,6 +539,7 @@ class ArrayIO extends \CoreLibs\DB\IO
// return the table if needed // return the table if needed
return $this->table_array; return $this->table_array;
} }
} // end of class // end of class
}
// __END__ // __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1); <?php
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2000/11/23 * CREATED: 2000/11/23
@@ -41,7 +42,7 @@
* $class_name * $class_name
* - the name of the class * - the name of the class
* $class_version * $class_version
* - the version as an array(major, minor, patchlvl, daypatch) * - the version as an array [major, minor, patchlvl, daypatch]
* $class_last_changed * $class_last_changed
* - date (mysql format) for the last change * - date (mysql format) for the last change
* $class_created * $class_created
@@ -107,9 +108,11 @@
* _db_io() * _db_io()
* - pseudo deconstructor - functionality moved to db_close * - pseudo deconstructor - functionality moved to db_close
* $string info($show=1) * $string info($show=1)
* - returns a string various info about class (version, authoer, etc), if $show set to 0, it will not be appended to the error_msgs string * - returns a string various info about class (version, authoer, etc)
* - if $show set to 0, it will not be appended to the error_msgs string
* $string db_info($show=1) * $string db_info($show=1)
* - returns a string with info about db connection, etc, if $show set to 0, it will not be appended to the error_msgs string * - returns a string with info about db connection, etc, if $show set to 0,
* - it will not be appended to the error_msgs string
* $string db_dump_data($query=0) * $string db_dump_data($query=0)
* - returns a string with all data of that query or if no query given with all data in the cursor_ext * - returns a string with all data of that query or if no query given with all data in the cursor_ext
* 0/$cursor db_exec($query=0) * 0/$cursor db_exec($query=0)
@@ -135,19 +138,21 @@
* $string db_boolean(string) * $string db_boolean(string)
* - if the string value is 't' or 'f' it returns correct TRUE/FALSE for php * - if the string value is 't' or 'f' it returns correct TRUE/FALSE for php
* $primary_key db_write_data($write_array, $not_write_array, $primary_key, $table, $data = []) * $primary_key db_write_data($write_array, $not_write_array, $primary_key, $table, $data = [])
* - writes into one table based on arrays of columns to write and not write, reads data from global vars or optional array * - writes into one table based on arrays of columns to write and not write,
* - reads data from global vars or optional array
* $boolean db_set_schema(schema) * $boolean db_set_schema(schema)
* - sets search path to a schema * - sets search path to a schema
* $boolean db_set_encoding(encoding) * $boolean db_set_encoding(encoding)
* - sets an encoding for this database output and input * - sets an encoding for this database output and input
* $string db_time_format($age/datetime diff, $micro_time = false/true) * $string db_time_format($age/datetime diff, $micro_time = false/true)
* - returns a nice formatted time string based on a age or datetime difference (postgres only), micro time is default false * - returns a nice formatted time string based on a age or datetime difference
* - (postgres only), micro time is default false
* *
* PRIVATE METHODS * PRIVATE METHODS
* _db_error() * _db_error()
* - INTERNAL ONLY!! error that occured during execution * - INTERNAL ONLY!! error that occured during execution
* $string _print_array($array) * $string _print_array($array)
* - returns string of an array(only for interal use) * - returns string of an array (only for interal use)
* 1/0 _connect_to_db() * 1/0 _connect_to_db()
* - returns 1 for successfull DB connection or 0 for none * - returns 1 for successfull DB connection or 0 for none
* 1/0 _check_query_for_select($query) * 1/0 _check_query_for_select($query)
@@ -159,10 +164,12 @@
* string _db_debug_prepare($prepare_id, $data_array) * string _db_debug_prepare($prepare_id, $data_array)
* - returns the prepared statement with the actual data. for debug purposes only * - returns the prepared statement with the actual data. for debug purposes only
* none _db_debug($debug_id, $string, $id, $type) * none _db_debug($debug_id, $string, $id, $type)
* - wrapper for normal debug, adds prefix data from id & type and strips all HTML from the query data (color codes, etc) via flag to debug call * - wrapper for normal debug, adds prefix data from id & type and strips
* - all HTML from the query data (color codes, etc) via flag to debug call
* *
* HISTORY: * HISTORY:
* 2008/10/25 (cs) add db_boolean to fix the postgres to php boolean var problem (TODO: implement this in any select return) * 2008/10/25 (cs) add db_boolean to fix the postgres to php boolean var problem
* (TODO: implement this in any select return)
* 2008/07/03 (cs) add db_write_data function, original written for inventory tool "invSQLWriteData" * 2008/07/03 (cs) add db_write_data function, original written for inventory tool "invSQLWriteData"
* 2008/04/16 (cs) add db_escape_string function for correct string escape * 2008/04/16 (cs) add db_escape_string function for correct string escape
* 2007/11/14 (cs) add a prepare debug statement to replace the placeholders with the actual data in a prepared statement * 2007/11/14 (cs) add a prepare debug statement to replace the placeholders with the actual data in a prepared statement
@@ -241,6 +248,8 @@
* 23.11.2000: erster Test * 23.11.2000: erster Test
*********************************************************************/ *********************************************************************/
declare(strict_types=1);
namespace CoreLibs\DB; namespace CoreLibs\DB;
class IO extends \CoreLibs\Basic class IO extends \CoreLibs\Basic
@@ -279,7 +288,7 @@ class IO extends \CoreLibs\Basic
private $nbsp = ''; // used by print_array recursion function private $nbsp = ''; // used by print_array recursion function
// error & warning id // error & warning id
protected $error_id; protected $error_id;
private $had_error; private $had_error = 0;
private $warning_id; private $warning_id;
private $had_warning; private $had_warning;
// error thrown on class init if we cannot connect to db // error thrown on class init if we cannot connect to db
@@ -307,7 +316,7 @@ class IO extends \CoreLibs\Basic
/** /**
* main DB concstructor with auto connection to DB and failure set on failed connection * main DB concstructor with auto connection to DB and failure set on failed connection
* @param array $db_config DB configuration array * @param array $db_config DB configuration array
*/ */
public function __construct(array $db_config) public function __construct(array $db_config)
{ {
@@ -317,13 +326,15 @@ class IO extends \CoreLibs\Basic
if (!is_array($db_config)) { if (!is_array($db_config)) {
$db_config = []; $db_config = [];
} }
// TODO: check must set CONSTANTS
// sets the names (for connect/reconnect) // sets the names (for connect/reconnect)
$this->db_name = $db_config['db_name'] ?? ''; $this->db_name = $db_config['db_name'] ?? '';
$this->db_user = $db_config['db_user'] ?? ''; $this->db_user = $db_config['db_user'] ?? '';
$this->db_pwd = $db_config['db_pass'] ?? ''; $this->db_pwd = $db_config['db_pass'] ?? '';
$this->db_host = $db_config['db_host'] ?? ''; $this->db_host = $db_config['db_host'] ?? '';
$this->db_port = !empty($db_config['db_port']) ? $db_config['db_port'] : 5432; $this->db_port = !empty($db_config['db_port']) ? (int)$db_config['db_port'] : 5432;
$this->db_schema = !empty($db_config['db_schema']) ? $db_config['db_schema'] : ''; // do not set to 'public' if not set, because the default is already public // do not set to 'public' if not set, because the default is already public
$this->db_schema = !empty($db_config['db_schema']) ? $db_config['db_schema'] : '';
$this->db_encoding = !empty($db_config['db_encoding']) ? $db_config['db_encoding'] : ''; $this->db_encoding = !empty($db_config['db_encoding']) ? $db_config['db_encoding'] : '';
$this->db_type = $db_config['db_type'] ?? ''; $this->db_type = $db_config['db_type'] ?? '';
$this->db_ssl = !empty($db_config['db_ssl']) ? $db_config['db_ssl'] : 'allow'; $this->db_ssl = !empty($db_config['db_ssl']) ? $db_config['db_ssl'] : 'allow';
@@ -342,16 +353,19 @@ class IO extends \CoreLibs\Basic
$this->error_string['14'] = 'Can\'t connect to DB server'; $this->error_string['14'] = 'Can\'t connect to DB server';
$this->error_string['15'] = 'Can\'t select DB'; $this->error_string['15'] = 'Can\'t select DB';
$this->error_string['16'] = 'No DB Handler found / connect or reconnect failed'; $this->error_string['16'] = 'No DB Handler found / connect or reconnect failed';
$this->error_string['17'] = 'All dbReturn* methods work only with SELECT statements, please use dbExec for everything else'; $this->error_string['17'] = 'All dbReturn* methods work only with SELECT statements, '
. 'please use dbExec for everything else';
$this->error_string['18'] = 'Query not found in cache. Nothing has been reset'; $this->error_string['18'] = 'Query not found in cache. Nothing has been reset';
$this->error_string['19'] = 'Wrong PK name given or no PK name given at all, can\'t get Insert ID'; $this->error_string['19'] = 'Wrong PK name given or no PK name given at all, can\'t get Insert ID';
$this->error_string['20'] = 'Found given Prepare Statement Name in array, Query not prepared, will use existing one'; $this->error_string['20'] = 'Found given Prepare Statement Name in array, '
. 'Query not prepared, will use existing one';
$this->error_string['21'] = 'Query Prepare failed'; $this->error_string['21'] = 'Query Prepare failed';
$this->error_string['22'] = 'Query Execute failed'; $this->error_string['22'] = 'Query Execute failed';
$this->error_string['23'] = 'Query Execute failed, data array does not match placeholders'; $this->error_string['23'] = 'Query Execute failed, data array does not match placeholders';
$this->error_string['24'] = 'Missing prepared query entry for execute.'; $this->error_string['24'] = 'Missing prepared query entry for execute.';
$this->error_string['25'] = 'Prepare query data is not in array format.'; $this->error_string['25'] = 'Prepare query data is not in array format.';
$this->error_string['30'] = 'Query call in a possible endless loop. Was called more than '.$this->MAX_QUERY_CALL.' times'; $this->error_string['30'] = 'Query call in a possible endless loop. '
. 'Was called more than ' . $this->MAX_QUERY_CALL . ' times';
$this->error_string['31'] = 'Could not fetch PK after query insert'; $this->error_string['31'] = 'Could not fetch PK after query insert';
$this->error_string['32'] = 'Multiple PK return as array'; $this->error_string['32'] = 'Multiple PK return as array';
$this->error_string['33'] = 'Returning PK was not found'; $this->error_string['33'] = 'Returning PK was not found';
@@ -396,7 +410,7 @@ class IO extends \CoreLibs\Basic
public function __destruct() public function __destruct()
{ {
$this->__closeDB(); $this->__closeDB();
parent::__destruct(); // parent::__destruct();
} }
// ************************************************************* // *************************************************************
@@ -411,7 +425,14 @@ class IO extends \CoreLibs\Basic
private function __connectToDB(): bool private function __connectToDB(): bool
{ {
// generate connect string // generate connect string
$this->dbh = $this->db_functions->__dbConnect($this->db_host, $this->db_user, $this->db_pwd, $this->db_name, $this->db_port, $this->db_ssl); $this->dbh = $this->db_functions->__dbConnect(
$this->db_host,
$this->db_user,
$this->db_pwd,
$this->db_name,
$this->db_port,
$this->db_ssl
);
// if no dbh here, we couldn't connect to the DB itself // if no dbh here, we couldn't connect to the DB itself
if (!$this->dbh) { if (!$this->dbh) {
$this->error_id = 14; $this->error_id = 14;
@@ -514,13 +535,13 @@ class IO extends \CoreLibs\Basic
$array = []; $array = [];
} }
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$string .= $this->nbsp.'<b>'.$key.'</b> => '; $string .= $this->nbsp . '<b>' . $key . '</b> => ';
if (is_array($value)) { if (is_array($value)) {
$this->nbsp .= '&nbsp;&nbsp;&nbsp;'; $this->nbsp .= '&nbsp;&nbsp;&nbsp;';
$string .= '<br>'; $string .= '<br>';
$string .= $this->__printArray($value); $string .= $this->__printArray($value);
} else { } else {
$string .= $value.'<br>'; $string .= $value . '<br>';
} }
} }
$this->nbsp = substr_replace($this->nbsp, '', -18, 18); $this->nbsp = substr_replace($this->nbsp, '', -18, 18);
@@ -539,15 +560,15 @@ class IO extends \CoreLibs\Basic
{ {
$prefix = ''; $prefix = '';
if ($id) { if ($id) {
$prefix .= '[<span style="color: #920069;">'.$id.'</span>] '; $prefix .= '[<span style="color: #920069;">' . $id . '</span>] ';
} }
if ($type) { if ($type) {
$prefix .= '{<span style="font-style: italic; color: #3f0092;">'.$type.'</span>} '; $prefix .= '{<span style="font-style: italic; color: #3f0092;">' . $type . '</span>} ';
} }
if ($prefix) { if ($prefix) {
$prefix .= '- '; $prefix .= '- ';
} }
$this->log->debug($debug_id, $prefix.$error_string, true); $this->log->debug($debug_id, $error_string, true, $prefix);
} }
/** /**
@@ -575,12 +596,26 @@ class IO extends \CoreLibs\Basic
// okay, an error occured // okay, an error occured
if ($this->error_id) { if ($this->error_id) {
// write error msg ... // write error msg ...
$this->__dbDebug('db', '<span style="color: red;"><b>DB-Error</b> '.$this->error_id.': '.$this->error_string[$this->error_id].($msg ? ', '.$msg : '').'</span>', 'DB_ERROR', $where_called); $this->__dbDebug(
'db',
'<span style="color: red;"><b>DB-Error</b> ' . $this->error_id . ': '
. $this->error_string[$this->error_id] . ($msg ? ', ' . $msg : '')
. '</span>',
'DB_ERROR',
$where_called
);
$this->had_error = $this->error_id; $this->had_error = $this->error_id;
// write detailed error log // write detailed error log
} }
if ($this->warning_id) { if ($this->warning_id) {
$this->__dbDebug('db', '<span style="color: orange;"><b>DB-Warning</b> '.$this->warning_id.': '.$this->error_string[$this->warning_id].($msg ? ', '.$msg : '').'</span>', 'DB_WARNING', $where_called); $this->__dbDebug(
'db',
'<span style="color: orange;"><b>DB-Warning</b> ' . $this->warning_id . ': '
. $this->error_string[$this->warning_id]
. ($msg ? ', ' . $msg : '') . '</span>',
'DB_WARNING',
$where_called
);
$this->had_warning = $this->warning_id; $this->had_warning = $this->warning_id;
} }
// unset the error/warning vars // unset the error/warning vars
@@ -596,7 +631,8 @@ class IO extends \CoreLibs\Basic
private function __dbConvertEncoding($row) private function __dbConvertEncoding($row)
{ {
// only do if array, else pass through row (can be false) // only do if array, else pass through row (can be false)
if (!is_array($row) || empty($this->to_encoding) || empty($this->db_encoding) if (
!is_array($row) || empty($this->to_encoding) || empty($this->db_encoding)
) { ) {
return $row; return $row;
} }
@@ -622,8 +658,8 @@ class IO extends \CoreLibs\Basic
// get the keys from data array // get the keys from data array
$keys = array_keys($data); $keys = array_keys($data);
// because the placeholders start with $ and at 1, we need to increase each key and prefix it with a $ char // because the placeholders start with $ and at 1, we need to increase each key and prefix it with a $ char
for ($i = 0, $iMax = count($keys); $i < $iMax; $i ++) { for ($i = 0, $iMax = count($keys); $i < $iMax; $i++) {
$keys[$i] = '$'.($keys[$i] + 1); $keys[$i] = '$' . ($keys[$i] + 1);
} }
// simply replace the $1, $2, ... with the actual data and return it // simply replace the $1, $2, ... with the actual data and return it
return str_replace(array_reverse($keys), array_reverse($data), $this->prepare_cursor[$stm_name]['query']); return str_replace(array_reverse($keys), array_reverse($data), $this->prepare_cursor[$stm_name]['query']);
@@ -642,7 +678,7 @@ class IO extends \CoreLibs\Basic
} else { } else {
preg_match("/(INSERT INTO|DELETE FROM|UPDATE) (([\w_]+)\.)?([\w_]+) /i", $query, $matches); preg_match("/(INSERT INTO|DELETE FROM|UPDATE) (([\w_]+)\.)?([\w_]+) /i", $query, $matches);
} }
return array($matches[3], $matches[4]); return [$matches[3], $matches[4]];
} }
/** /**
@@ -659,7 +695,7 @@ class IO extends \CoreLibs\Basic
*/ */
private function __dbPrepareExec(string $query, string $pk_name) private function __dbPrepareExec(string $query, string $pk_name)
{ {
$matches= []; $matches = [];
// to either use the returning method or the guess method for getting primary keys // to either use the returning method or the guess method for getting primary keys
$this->returning_id = false; $this->returning_id = false;
// set the query // set the query
@@ -686,7 +722,8 @@ class IO extends \CoreLibs\Basic
$this->__dbError(); $this->__dbError();
return false; return false;
} }
// if we do have an insert, check if there is no RETURNING pk_id, add it if I can get the PK id // if we do have an insert, check if there is no RETURNING pk_id,
// add it if I can get the PK id
if ($this->__checkQueryForInsert($this->query, true)) { if ($this->__checkQueryForInsert($this->query, true)) {
$this->pk_name = $pk_name; $this->pk_name = $pk_name;
if ($this->pk_name != 'NULL') { if ($this->pk_name != 'NULL') {
@@ -701,13 +738,13 @@ class IO extends \CoreLibs\Basic
if (!preg_match("/ returning /i", $this->query) && $this->pk_name && $this->pk_name != 'NULL') { if (!preg_match("/ returning /i", $this->query) && $this->pk_name && $this->pk_name != 'NULL') {
// check if this query has a ; at the end and remove it // check if this query has a ; at the end and remove it
$this->query = preg_replace("/(;\s*)$/", '', $this->query); $this->query = preg_replace("/(;\s*)$/", '', $this->query);
$this->query .= " RETURNING ".$this->pk_name; $this->query .= " RETURNING " . $this->pk_name;
$this->returning_id = true; $this->returning_id = true;
} elseif (preg_match("/ returning (.*)/i", $this->query, $matches)) { } elseif (preg_match("/ returning (.*)/i", $this->query, $matches)) {
if ($this->pk_name && $this->pk_name != 'NULL') { if ($this->pk_name && $this->pk_name != 'NULL') {
// add the primary key if it is not in the returning set // add the primary key if it is not in the returning set
if (!preg_match("/$this->pk_name/", $matches[1])) { if (!preg_match("/$this->pk_name/", $matches[1])) {
$this->query .= " , ".$this->pk_name; $this->query .= " , " . $this->pk_name;
} }
} }
$this->returning_id = true; $this->returning_id = true;
@@ -735,7 +772,8 @@ class IO extends \CoreLibs\Basic
} }
// count up the run, if this is run more than the max_run then exit with error // count up the run, if this is run more than the max_run then exit with error
// if set to -1, then ignore it // if set to -1, then ignore it
if ($this->MAX_QUERY_CALL != -1 && if (
$this->MAX_QUERY_CALL != -1 &&
$this->query_called[$md5] > $this->MAX_QUERY_CALL $this->query_called[$md5] > $this->MAX_QUERY_CALL
) { ) {
$this->error_id = 30; $this->error_id = 30;
@@ -774,14 +812,15 @@ class IO extends \CoreLibs\Basic
$this->num_fields = $this->db_functions->__dbNumFields($this->cursor); $this->num_fields = $this->db_functions->__dbNumFields($this->cursor);
// set field names // set field names
$this->field_names = []; $this->field_names = [];
for ($i = 0; $i < $this->num_fields; $i ++) { for ($i = 0; $i < $this->num_fields; $i++) {
$this->field_names[] = $this->db_functions->__dbFieldName($this->cursor, $i); $this->field_names[] = $this->db_functions->__dbFieldName($this->cursor, $i);
} }
} elseif ($this->__checkQueryForInsert($this->query)) { } elseif ($this->__checkQueryForInsert($this->query)) {
// if not select do here // if not select do here
// count affected rows // count affected rows
$this->num_rows = $this->db_functions->__dbAffectedRows($this->cursor); $this->num_rows = $this->db_functions->__dbAffectedRows($this->cursor);
if (($this->__checkQueryForInsert($this->query, true) && $this->pk_name != 'NULL') || if (
($this->__checkQueryForInsert($this->query, true) && $this->pk_name != 'NULL') ||
($this->__checkQueryForUpdate($this->query) && $this->returning_id) ($this->__checkQueryForUpdate($this->query) && $this->returning_id)
) { ) {
// set insert_id // set insert_id
@@ -797,22 +836,30 @@ class IO extends \CoreLibs\Basic
// echo "** PREPARE RETURNING FOR CURSOR: ".$this->cursor."<br>"; // echo "** PREPARE RETURNING FOR CURSOR: ".$this->cursor."<br>";
// we have returning, now we need to check if we get one or many returned // we have returning, now we need to check if we get one or many returned
// we'll need to loop this, if we have multiple insert_id returns // we'll need to loop this, if we have multiple insert_id returns
while ($_insert_id = $this->db_functions->__dbFetchArray( while (
$this->cursor, $_insert_id = $this->db_functions->__dbFetchArray(
$this->db_functions->__dbResultType(true) $this->cursor,
)) { $this->db_functions->__dbResultType(true)
)
) {
// echo "*** RETURNING: ".print_r($_insert_id, true)."<br>"; // echo "*** RETURNING: ".print_r($_insert_id, true)."<br>";
$this->insert_id[] = $_insert_id; $this->insert_id[] = $_insert_id;
$this->insert_id_arr[] = $_insert_id; $this->insert_id_arr[] = $_insert_id;
} }
// if we have only one, revert from array to single // if we have only one, revert from array to single
if (count($this->insert_id) == 1) { if (count($this->insert_id) == 1) {
// echo "* SINGLE DATA CONVERT: ".count($this->insert_id[0])." => ".array_key_exists($this->pk_name, $this->insert_id[0])."<br>"; // $this->log->debug('SINGLE DATA CONVERT', count($this->insert_id[0])." => "
// echo "* PK DIRECT: ".(isset($this->insert_id[0][$this->pk_name]) ? $this->insert_id[0][$this->pk_name] : '[NO PK NAME SET]' )."<Br>"; // .array_key_exists($this->pk_name, $this->insert_id[0]));
// if this has only the pk_name, then only return this, else array of all data (but without the position) // $this->log->debug('PK DIRECT', (isset($this->insert_id[0][$this->pk_name]) ?
// example if insert_id[0]['foo'] && insert_id[0]['bar'] it will become insert_id['foo'] & insert_id['bar'] // $this->insert_id[0][$this->pk_name] : '[NO PK NAME SET]' ));
// if only ['foo_id'] and it is the PK then the PK is directly written to the insert_id // if this has only the pk_name, then only return this,
if (count($this->insert_id[0]) > 1 || // else array of all data (but without the position)
// example if insert_id[0]['foo'] && insert_id[0]['bar']
// it will become insert_id['foo'] & insert_id['bar']
// if only ['foo_id'] and it is the PK then the
// PK is directly written to the insert_id
if (
count($this->insert_id[0]) > 1 ||
!array_key_exists($this->pk_name, $this->insert_id[0]) !array_key_exists($this->pk_name, $this->insert_id[0])
) { ) {
$this->insert_id_ext = $this->insert_id[0]; $this->insert_id_ext = $this->insert_id[0];
@@ -869,6 +916,24 @@ class IO extends \CoreLibs\Basic
return $this->db_debug; return $this->db_debug;
} }
/**
* Switches db debug flag on or off
* OR
* with the optional parameter fix sets debug
* returns current set stats
* @param bool|null $debug Flag to turn debug on off
* @return bool True for debug is on, False for off
*/
public function dbToggleDebug(?bool $debug = null)
{
if ($debug !== null) {
$this->db_debug = $debug;
} else {
$this->db_debug = $this->db_debug ? false : true;
}
return $this->db_debug;
}
/** /**
* set max query calls, set to --1 to disable loop * set max query calls, set to --1 to disable loop
* protection. this will generate a warning * protection. this will generate a warning
@@ -897,11 +962,12 @@ class IO extends \CoreLibs\Basic
return false; return false;
} }
// ok entry, set // ok entry, set
if ($max_calls == -1 || if (
$max_calls == -1 ||
$max_calls > 0 $max_calls > 0
) { ) {
$this->MAX_QUERY_CALL = $max_calls; $this->MAX_QUERY_CALL = $max_calls;
$succes = true; $success = true;
} }
return $success; return $success;
} }
@@ -978,7 +1044,7 @@ class IO extends \CoreLibs\Basic
if (!$db_schema) { if (!$db_schema) {
return false; return false;
} }
$q = "SET search_path TO '".$this->dbEscapeString($db_schema)."'"; $q = "SET search_path TO '" . $this->dbEscapeString($db_schema) . "'";
return $this->dbExec($q); return $this->dbExec($q);
} }
@@ -1004,7 +1070,7 @@ class IO extends \CoreLibs\Basic
if (!$db_encoding) { if (!$db_encoding) {
return false; return false;
} }
$q = "SET client_encoding TO '".$this->dbEscapeString($db_encoding)."'"; $q = "SET client_encoding TO '" . $this->dbEscapeString($db_encoding) . "'";
return $this->dbExec($q); return $this->dbExec($q);
} }
@@ -1032,6 +1098,25 @@ class IO extends \CoreLibs\Basic
case 'user': case 'user':
$setting = $this->db_user; $setting = $this->db_user;
break; break;
case 'encoding':
$setting = $this->db_encoding;
break;
case 'schema':
$setting = $this->db_schema;
break;
case 'host':
$setting = $this->db_host;
break;
case 'port':
$setting = $this->db_port;
break;
case 'ssl':
$setting = $this->db_ssl;
break;
// we return *** and never the actual password
case 'password':
$setting = '***';
break;
default: default:
$setting = false; $setting = false;
break; break;
@@ -1048,19 +1133,21 @@ class IO extends \CoreLibs\Basic
public function dbInfo(bool $show = true): string public function dbInfo(bool $show = true): string
{ {
$string = ''; $string = '';
$string .= '<b>-DB-info-></b> Connected to db <b>\''.$this->db_name.'\'</b> '; $string .= '{b}-DB-info->{/b} Connected to db {b}\'' . $this->db_name . '\'{/b} ';
$string .= 'with schema <b>\''.$this->db_schema.'\'</b> '; $string .= 'with schema {b}\'' . $this->db_schema . '\'{/b} ';
$string .= 'as user <b>\''.$this->db_user.'\'</b> '; $string .= 'as user {b}\'' . $this->db_user . '\'{/b} ';
$string .= 'at host <b>\''.$this->db_host.'\'</b> '; $string .= 'at host {b}\'' . $this->db_host . '\'{/b} ';
$string .= 'on port <b>\''.$this->db_port.'\'</b> '; $string .= 'on port {b}\'' . $this->db_port . '\'{/b} ';
$string .= 'with ssl mode <b>\''.$this->db_ssl.'\'</b><br>'; $string .= 'with ssl mode {b}\'' . $this->db_ssl . '\'{/b}{br}';
$string .= '<b>-DB-info-></b> DB IO Class debug output: <b>'.($this->db_debug ? 'Yes' : 'No').'</b>'; $string .= '{b}-DB-info->{/b} DB IO Class debug output: {b}' . ($this->db_debug ? 'Yes' : 'No') . '{/b}';
if ($show === true) { if ($show === true) {
$this->__dbDebug('db', $string, 'dbInfo'); // if debug, remove / change b
$this->__dbDebug('db', str_replace(['{b}', '{/b}', '{br}'], ['', '', ' **** '], $string), 'dbInfo');
} else { } else {
$string = $string.'<br>'; $string = $string . '{br}';
} }
return $string; // for direct print, change to html
return str_replace(['{b}', '{/b}', '{br}'], ['<b>', '</b>', '<br>'], $string);
} }
/** /**
@@ -1099,8 +1186,12 @@ class IO extends \CoreLibs\Basic
* - if set to 3, after EACH row, the data will be reset, * - if set to 3, after EACH row, the data will be reset,
* no caching is done except for basic (count, etc) * no caching is done except for basic (count, etc)
* @param string $query Query string * @param string $query Query string
* @param int $reset reset status: 1: read cache, clean at the end, 2: read new, clean at end, 3: never cache * @param int $reset reset status:
* @param bool $assoc_only true to only returned the named and not index position ones * 1: read cache, clean at the end
* 2: read new, clean at end
* 3: never cache
* @param bool $assoc_only true to only returned the named and not
* index position ones
* @return array|bool return array data or false on error/end * @return array|bool return array data or false on error/end
* @suppress PhanTypeMismatchDimFetch * @suppress PhanTypeMismatchDimFetch
*/ */
@@ -1140,7 +1231,9 @@ class IO extends \CoreLibs\Basic
if ($reset && !$this->cursor_ext[$md5]['pos']) { if ($reset && !$this->cursor_ext[$md5]['pos']) {
$this->cursor_ext[$md5]['cursor'] = null; $this->cursor_ext[$md5]['cursor'] = null;
} }
// $this->debug('MENU', 'Reset: '.$reset.', Cursor: '.$this->cursor_ext[$md5]['cursor'].', Pos: '.$this->cursor_ext[$md5]['pos'].', Query: '.$query); // $this->debug('MENU', 'Reset: '.$reset.', Cursor: '
// .$this->cursor_ext[$md5]['cursor'].', Pos: '.$this->cursor_ext[$md5]['pos']
// .', Query: '.$query);
// if no cursor yet, execute // if no cursor yet, execute
if (!$this->cursor_ext[$md5]['cursor']) { if (!$this->cursor_ext[$md5]['cursor']) {
@@ -1182,12 +1275,18 @@ class IO extends \CoreLibs\Basic
if ($this->cursor_ext[$md5]['cursor']) { if ($this->cursor_ext[$md5]['cursor']) {
if ($this->cursor_ext[$md5]['firstcall'] == 1) { if ($this->cursor_ext[$md5]['firstcall'] == 1) {
// count the rows returned (if select) // count the rows returned (if select)
$this->cursor_ext[$md5]['num_rows'] = $this->db_functions->__dbNumRows($this->cursor_ext[$md5]['cursor']); $this->cursor_ext[$md5]['num_rows'] =
$this->db_functions->__dbNumRows($this->cursor_ext[$md5]['cursor']);
// count the fields // count the fields
$this->cursor_ext[$md5]['num_fields'] = $this->db_functions->__dbNumFields($this->cursor_ext[$md5]['cursor']); $this->cursor_ext[$md5]['num_fields'] =
$this->db_functions->__dbNumFields($this->cursor_ext[$md5]['cursor']);
// set field names // set field names
for ($i = 0; $i < $this->cursor_ext[$md5]['num_fields']; $i ++) { for ($i = 0; $i < $this->cursor_ext[$md5]['num_fields']; $i++) {
$this->cursor_ext[$md5]['field_names'][] = $this->db_functions->__dbFieldName($this->cursor_ext[$md5]['cursor'], $i); $this->cursor_ext[$md5]['field_names'][] =
$this->db_functions->__dbFieldName(
$this->cursor_ext[$md5]['cursor'],
$i
);
} }
// reset first call vars // reset first call vars
$this->cursor_ext[$md5]['firstcall'] = 0; $this->cursor_ext[$md5]['firstcall'] = 0;
@@ -1216,24 +1315,34 @@ class IO extends \CoreLibs\Basic
// check if end of output ... // check if end of output ...
if ($this->cursor_ext[$md5]['pos'] >= $this->cursor_ext[$md5]['num_rows']) { if ($this->cursor_ext[$md5]['pos'] >= $this->cursor_ext[$md5]['num_rows']) {
$this->cursor_ext[$md5]['pos'] = 0; $this->cursor_ext[$md5]['pos'] = 0;
# if not reset given, set the cursor to true, so in a cached call on a different page we don't get problems from DB connection (as those will be LOST) // if not reset given, set the cursor to true, so in a cached
// call on a different page we don't get problems from
// DB connection (as those will be LOST)
$this->cursor_ext[$md5]['cursor'] = 1; $this->cursor_ext[$md5]['cursor'] = 1;
$return = false; $return = false;
} else { } else {
// unset return value ... // unset return value ...
$return = []; $return = [];
for ($i = 0; $i < $this->cursor_ext[$md5]['num_fields']; $i ++) { for ($i = 0; $i < $this->cursor_ext[$md5]['num_fields']; $i++) {
// create mixed return array // create mixed return array
if ($assoc_only === false && isset($this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]['pos']][$i])) { if (
$assoc_only === false &&
isset($this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]['pos']][$i])
) {
$return[$i] = $this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]['pos']][$i]; $return[$i] = $this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]['pos']][$i];
} }
// named part // named part
if (isset($this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]['pos']][$i])) { if (isset($this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]['pos']][$i])) {
$return[$this->cursor_ext[$md5]['field_names'][$i]] = $this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]['pos']][$i]; $return[$this->cursor_ext[$md5]['field_names'][$i]] =
$this->cursor_ext[$md5]['data']
[$this->cursor_ext[$md5]['pos']][$i];
} else { } else {
// throws PhanTypeMismatchDimFetch error, but in this case we know we will access only named array parts // throws PhanTypeMismatchDimFetch error, but in this
// case we know we will access only named array parts
// @suppress PhanTypeMismatchDimFetch // @suppress PhanTypeMismatchDimFetch
$return[$this->cursor_ext[$md5]['field_names'][$i]] = $this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]['pos']][$this->cursor_ext[$md5]['field_names'][$i]]; $return[$this->cursor_ext[$md5]['field_names'][$i]] =
$this->cursor_ext[$md5]['data'][$this->cursor_ext[$md5]
['pos']][$this->cursor_ext[$md5]['field_names'][$i]];
} }
} }
$this->cursor_ext[$md5]['pos'] ++; $this->cursor_ext[$md5]['pos'] ++;
@@ -1350,9 +1459,10 @@ class IO extends \CoreLibs\Basic
/** /**
* checks a previous async query and returns data if finished * checks a previous async query and returns data if finished
* NEEDS : dbExecAsync * NEEDS : dbExecAsync
* @return bool true if the query is still running, false if an error occured or cursor of that query * @return bool|resource cursor resource if the query is still running,
* false if an error occured or cursor of that query
*/ */
public function dbCheckAsync(): bool public function dbCheckAsync()
{ {
// if there is actually a async query there // if there is actually a async query there
if ($this->async_running) { if ($this->async_running) {
@@ -1372,7 +1482,12 @@ class IO extends \CoreLibs\Basic
} else { } else {
// if no async running print error // if no async running print error
$this->error_id = 42; $this->error_id = 42;
$this->__dbDebug('db', '<span style="color: red;"><b>DB-Error</b> No async query has been started yet.</span>', 'DB_ERROR'); $this->__dbDebug(
'db',
'<span style="color: red;"><b>DB-Error</b> No async query '
. 'has been started yet.</span>',
'DB_ERROR'
);
return false; return false;
} }
} }
@@ -1450,7 +1565,7 @@ class IO extends \CoreLibs\Basic
$rows = []; $rows = [];
while ($res = $this->dbFetchArray($cursor, $assoc_only)) { while ($res = $this->dbFetchArray($cursor, $assoc_only)) {
$data = []; $data = [];
for ($i = 0; $i < $this->num_fields; $i ++) { for ($i = 0; $i < $this->num_fields; $i++) {
$data[$this->field_names[$i]] = $res[$this->field_names[$i]]; $data[$this->field_names[$i]] = $res[$this->field_names[$i]];
} }
$rows[] = $data; $rows[] = $data;
@@ -1498,7 +1613,7 @@ class IO extends \CoreLibs\Basic
*/ */
public function dbShowTableMetaData(string $table, string $schema = '') public function dbShowTableMetaData(string $table, string $schema = '')
{ {
$table = ($schema ? $schema.'.' : '').$table; $table = ($schema ? $schema . '.' : '') . $table;
$array = $this->db_functions->__dbMetaData($table); $array = $this->db_functions->__dbMetaData($table);
if (!is_array($array)) { if (!is_array($array)) {
@@ -1559,12 +1674,15 @@ class IO extends \CoreLibs\Basic
} }
// if no returning, then add it // if no returning, then add it
if (!preg_match("/ returning /i", $query) && $this->prepare_cursor[$stm_name]['pk_name']) { if (!preg_match("/ returning /i", $query) && $this->prepare_cursor[$stm_name]['pk_name']) {
$query .= " RETURNING ".$this->prepare_cursor[$stm_name]['pk_name']; $query .= " RETURNING " . $this->prepare_cursor[$stm_name]['pk_name'];
$this->prepare_cursor[$stm_name]['returning_id'] = true; $this->prepare_cursor[$stm_name]['returning_id'] = true;
} elseif (preg_match("/ returning (.*)/i", $query, $matches) && $this->prepare_cursor[$stm_name]['pk_name']) { } elseif (
preg_match("/ returning (.*)/i", $query, $matches) &&
$this->prepare_cursor[$stm_name]['pk_name']
) {
// if returning exists but not pk_name, add it // if returning exists but not pk_name, add it
if (!preg_match("/{$this->prepare_cursor[$stm_name]['pk_name']}/", $matches[1])) { if (!preg_match("/{$this->prepare_cursor[$stm_name]['pk_name']}/", $matches[1])) {
$query .= " , ".$this->prepare_cursor[$stm_name]['pk_name']; $query .= " , " . $this->prepare_cursor[$stm_name]['pk_name'];
} }
$this->prepare_cursor[$stm_name]['returning_id'] = true; $this->prepare_cursor[$stm_name]['returning_id'] = true;
} }
@@ -1585,7 +1703,13 @@ class IO extends \CoreLibs\Basic
} else { } else {
$this->error_id = 21; $this->error_id = 21;
$this->__dbError(); $this->__dbError();
$this->__dbDebug('db', '<span style="color: red;"><b>DB-Error</b> '.$stm_name.': Prepare field with: '.$stm_name.' | '.$query.'</span>', 'DB_ERROR'); $this->__dbDebug(
'db',
'<span style="color: red;"><b>DB-Error</b> ' . $stm_name
. ': Prepare field with: ' . $stm_name . ' | '
. $query . '</span>',
'DB_ERROR'
);
return $result; return $result;
} }
} else { } else {
@@ -1606,17 +1730,34 @@ class IO extends \CoreLibs\Basic
// if we do not have no prepare cursor array entry for this statement name, abort // if we do not have no prepare cursor array entry for this statement name, abort
if (!is_array($this->prepare_cursor[$stm_name])) { if (!is_array($this->prepare_cursor[$stm_name])) {
$this->error_id = 24; $this->error_id = 24;
$this->__dbDebug('db', '<span style="color: red;"><b>DB-Error</b> '.$stm_name.': We do not have a prepared query entry for this statement name.</span>', 'DB_ERROR'); $this->__dbDebug(
'db',
'<span style="color: red;"><b>DB-Error</b> ' . $stm_name
. ': We do not have a prepared query entry for this statement name.</span>',
'DB_ERROR'
);
return false; return false;
} }
if (!is_array($data)) { if (!is_array($data)) {
$this->error_id = 25; $this->error_id = 25;
$this->__dbDebug('db', '<span style="color: red;"><b>DB-Error</b> '.$stm_name.': Prepared query Data has to be given in array form.</span>', 'DB_ERROR'); $this->__dbDebug(
'db',
'<span style="color: red;"><b>DB-Error</b> ' . $stm_name
. ': Prepared query Data has to be given in array form.</span>',
'DB_ERROR'
);
return false; return false;
} }
if ($this->prepare_cursor[$stm_name]['count'] != count($data)) { if ($this->prepare_cursor[$stm_name]['count'] != count($data)) {
$this->error_id = 23; $this->error_id = 23;
$this->__dbDebug('db', '<span style="color: red;"><b>DB-Error</b> '.$stm_name.': Array data count does not match prepared fields. Need: '.$this->prepare_cursor[$stm_name]['count'].', has: '.count($data).'</span>', 'DB_ERROR'); $this->__dbDebug(
'db',
'<span style="color: red;"><b>DB-Error</b> ' . $stm_name
. ': Array data count does not match prepared fields. Need: '
. $this->prepare_cursor[$stm_name]['count'] . ', has: '
. count($data) . '</span>',
'DB_ERROR'
);
return false; return false;
} }
if ($this->db_debug) { if ($this->db_debug) {
@@ -1624,17 +1765,28 @@ class IO extends \CoreLibs\Basic
} }
$result = $this->db_functions->__dbExecute($stm_name, $data); $result = $this->db_functions->__dbExecute($stm_name, $data);
if (!$result) { if (!$result) {
$this->log->debug('ExecuteData', 'ERROR in STM['.$stm_name.'|'.$this->prepare_cursor[$stm_name]['result'].']: '.$this->log->prAr($data)); $this->log->debug('ExecuteData', 'ERROR in STM[' . $stm_name . '|'
. $this->prepare_cursor[$stm_name]['result'] . ']: '
. $this->log->prAr($data));
$this->error_id = 22; $this->error_id = 22;
$this->__dbError($this->prepare_cursor[$stm_name]['result']); $this->__dbError($this->prepare_cursor[$stm_name]['result']);
$this->__dbDebug('db', '<span style="color: red;"><b>DB-Error</b> '.$stm_name.': Execution failed</span>', 'DB_ERROR'); $this->__dbDebug(
'db',
'<span style="color: red;"><b>DB-Error</b> ' . $stm_name
. ': Execution failed</span>',
'DB_ERROR'
);
return false; return false;
} }
if ($this->__checkQueryForInsert($this->prepare_cursor[$stm_name]['query'], true) && if (
$this->__checkQueryForInsert($this->prepare_cursor[$stm_name]['query'], true) &&
$this->prepare_cursor[$stm_name]['pk_name'] != 'NULL' $this->prepare_cursor[$stm_name]['pk_name'] != 'NULL'
) { ) {
if (!$this->prepare_cursor[$stm_name]['returning_id']) { if (!$this->prepare_cursor[$stm_name]['returning_id']) {
$this->insert_id = $this->db_functions->__dbInsertId($this->prepare_cursor[$stm_name]['query'], $this->prepare_cursor[$stm_name]['pk_name']); $this->insert_id = $this->db_functions->__dbInsertId(
$this->prepare_cursor[$stm_name]['query'],
$this->prepare_cursor[$stm_name]['pk_name']
);
$this->insert_id_ext = $this->insert_id; $this->insert_id_ext = $this->insert_id;
$this->insert_id_arr[] = $this->insert_id; $this->insert_id_arr[] = $this->insert_id;
} elseif ($result) { } elseif ($result) {
@@ -1643,21 +1795,28 @@ class IO extends \CoreLibs\Basic
$this->insert_id_arr = []; $this->insert_id_arr = [];
// we have returning, now we need to check if we get one or many returned // we have returning, now we need to check if we get one or many returned
// we'll need to loop this, if we have multiple insert_id returns // we'll need to loop this, if we have multiple insert_id returns
while ($_insert_id = $this->db_functions->__dbFetchArray( while (
$result, $_insert_id = $this->db_functions->__dbFetchArray(
$this->db_functions->__dbResultType(true) $result,
)) { $this->db_functions->__dbResultType(true)
)
) {
$this->insert_id[] = $_insert_id; $this->insert_id[] = $_insert_id;
$this->insert_id_arr[] = $_insert_id; $this->insert_id_arr[] = $_insert_id;
} }
// if we have only one, revert from arry to single // if we have only one, revert from arry to single
if (count($this->insert_id) == 1) { if (count($this->insert_id) == 1) {
// echo "+ SINGLE DATA CONVERT: ".count($this->insert_id[0])." => ".array_key_exists($this->prepare_cursor[$stm_name]['pk_name'], $this->insert_id[0])."<br>"; // $this->log->debug('SINGLE DATA CONVERT', count($this->insert_id[0])." => "
// echo "+ PK DIRECT: ".$this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]."<Br>"; // .array_key_exists($this->prepare_cursor[$stm_name]['pk_name'], $this->insert_id[0]));
// if this has only the pk_name, then only return this, else array of all data (but without the position) // $this->log->debug('PK DIRECT', $this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]);
// example if insert_id[0]['foo'] && insert_id[0]['bar'] it will become insert_id['foo'] & insert_id['bar'] // if this has only the pk_name, then only return this,
// if only ['foo_id'] and it is the PK then the PK is directly written to the insert_id // else array of all data (but without the position)
if (count($this->insert_id[0]) > 1 || // example if insert_id[0]['foo'] && insert_id[0]['bar']
// it will become insert_id['foo'] & insert_id['bar']
// if only ['foo_id'] and it is the PK then the PK is directly
// written to the insert_id
if (
count($this->insert_id[0]) > 1 ||
!array_key_exists($this->prepare_cursor[$stm_name]['pk_name'], $this->insert_id[0]) !array_key_exists($this->prepare_cursor[$stm_name]['pk_name'], $this->insert_id[0])
) { ) {
$this->insert_id_ext = $this->insert_id[0]; $this->insert_id_ext = $this->insert_id[0];
@@ -1670,19 +1829,34 @@ class IO extends \CoreLibs\Basic
$this->insert_id = ''; $this->insert_id = '';
$this->warning_id = 33; $this->warning_id = 33;
$this->__dbError(); $this->__dbError();
$this->__dbDebug('db', '<span style="color: orange;"><b>DB-Warning</b> '.$stm_name.': insert id returned no data</span>', 'DB_WARNING'); $this->__dbDebug(
'db',
'<span style="color: orange;"><b>DB-Warning</b> ' . $stm_name
. ': insert id returned no data</span>',
'DB_WARNING'
);
} }
} }
// this error handling is only for pgsql // this error handling is only for pgsql
if (is_array($this->insert_id)) { if (is_array($this->insert_id)) {
$this->warning_id = 32; $this->warning_id = 32;
$this->__dbError(); $this->__dbError();
$this->__dbDebug('db', '<span style="color: orange;"><b>DB-Warning</b> '.$stm_name.': insert id data returned as array</span>', 'DB_WARNING'); $this->__dbDebug(
'db',
'<span style="color: orange;"><b>DB-Warning</b> ' . $stm_name
. ': insert id data returned as array</span>',
'DB_WARNING'
);
} elseif (!$this->insert_id) { } elseif (!$this->insert_id) {
// NOTE should we keep this inside // NOTE should we keep this inside
$this->warning_id = 31; $this->warning_id = 31;
$this->__dbError(); $this->__dbError();
$this->__dbDebug('db', '<span style="color: orange;"><b>DB-Warning</b> '.$stm_name.': Could not get insert id</span>', 'DB_WARNING'); $this->__dbDebug(
'db',
'<span style="color: orange;"><b>DB-Warning</b> ' . $stm_name
. ': Could not get insert id</span>',
'DB_WARNING'
);
} }
} }
return $result; return $result;
@@ -1744,14 +1918,14 @@ class IO extends \CoreLibs\Basic
if (!$compare || !$to_master || !$to_minor) { if (!$compare || !$to_master || !$to_minor) {
return false; return false;
} else { } else {
$to_version = $to_master.($to_minor < 10 ? '0' : '').$to_minor; $to_version = $to_master . ($to_minor < 10 ? '0' : '') . $to_minor;
} }
// db_version can return X.Y.Z // db_version can return X.Y.Z
// we only compare the first two // we only compare the first two
preg_match("/^(\d{1,})\.(\d{1,})\.?(\d{1,})?/", $this->dbVersion(), $matches); preg_match("/^(\d{1,})\.(\d{1,})\.?(\d{1,})?/", $this->dbVersion(), $matches);
$master = $matches[1]; $master = $matches[1];
$minor = $matches[2]; $minor = $matches[2];
$version = $master.($minor < 10 ? '0' : '').$minor; $version = $master . ($minor < 10 ? '0' : '') . $minor;
$return = false; $return = false;
// compare // compare
switch ($compare) { switch ($compare) {
@@ -1831,8 +2005,13 @@ class IO extends \CoreLibs\Basic
* @param array $data data array to override _POST data * @param array $data data array to override _POST data
* @return int|bool primary key * @return int|bool primary key
*/ */
public function dbWriteData(array $write_array, array $not_write_array, $primary_key, string $table, $data = []) public function dbWriteData(
{ array $write_array,
array $not_write_array,
int $primary_key,
string $table,
array $data = []
) {
if (!is_array($write_array)) { if (!is_array($write_array)) {
$write_array = []; $write_array = [];
} }
@@ -1843,14 +2022,21 @@ class IO extends \CoreLibs\Basic
return false; return false;
} }
$not_write_update_array = []; $not_write_update_array = [];
return $this->dbWriteDataExt($write_array, $primary_key, $table, $not_write_array, $not_write_update_array, $data); return $this->dbWriteDataExt(
$write_array,
$primary_key,
$table,
$not_write_array,
$not_write_update_array,
$data
);
} }
/** /**
* writes into one table based on array of table columns * writes into one table based on array of table columns
* PARAM INFO: $primary key * PARAM INFO: $primary key
* this can be a plain string/int and will be internal transformed into the array form * this can be a plain string/int and will be internal transformed into the array form
* or it takes the array form of array(row => column, value => pk value) * or it takes the array form of array [row => column, value => pk value]
* @param array $write_array list of elements to write * @param array $write_array list of elements to write
* @param int|string|array $primary_key primary key string or array set * @param int|string|array $primary_key primary key string or array set
* @param string $table name for the target table * @param string $table name for the target table
@@ -1869,7 +2055,7 @@ class IO extends \CoreLibs\Basic
) { ) {
if (!is_array($primary_key)) { if (!is_array($primary_key)) {
$primary_key = [ $primary_key = [
'row' => $table.'_id', 'row' => $table . '_id',
'value' => $primary_key 'value' => $primary_key
]; ];
} else { } else {
@@ -1884,13 +2070,14 @@ class IO extends \CoreLibs\Basic
$q_sub_value = ''; $q_sub_value = '';
$q_sub_data = ''; $q_sub_data = '';
// get the table layout and row types // get the table layout and row types
$table_data = $this->dbShowTableMetaData(($this->db_schema ? $this->db_schema.'.' : '').$table); $table_data = $this->dbShowTableMetaData(($this->db_schema ? $this->db_schema . '.' : '') . $table);
// @phan HACK // @phan HACK
$primary_key['value'] = $primary_key['value'] ?? ''; $primary_key['value'] = $primary_key['value'] ?? '';
$primary_key['row'] = $primary_key['row'] ?? ''; $primary_key['row'] = $primary_key['row'] ?? '';
// loop through the write array and each field to build the query // loop through the write array and each field to build the query
foreach ($write_array as $field) { foreach ($write_array as $field) {
if ((!$primary_key['value'] || if (
(!$primary_key['value'] ||
($primary_key['value'] && ($primary_key['value'] &&
!in_array($field, $not_write_update_array)) !in_array($field, $not_write_update_array))
) && ) &&
@@ -1915,8 +2102,11 @@ class IO extends \CoreLibs\Basic
} }
// we detect bool, so we can force a write on "false" // we detect bool, so we can force a write on "false"
$is_bool = $table_data[$field]['type'] == 'bool' ? true : false; $is_bool = $table_data[$field]['type'] == 'bool' ? true : false;
// write if the field has to be not null, or if there is no data and the field has no default values or if there is data or if this is an update and there is no data (set null) // write if the field has to be not null, or if there is
if (($not_null && $_data) || // no data and the field has no default values or if there
// is data or if this is an update and there is no data (set null)
if (
($not_null && $_data) ||
(!$has_default && !$_data) || (!$has_default && !$_data) ||
(is_numeric($_data) && $_data) || (is_numeric($_data) && $_data) ||
($primary_key['value'] && !$_data) || ($primary_key['value'] && !$_data) ||
@@ -1925,11 +2115,13 @@ class IO extends \CoreLibs\Basic
if ($q_sub_value && !$primary_key['value']) { if ($q_sub_value && !$primary_key['value']) {
$q_sub_value .= ', '; $q_sub_value .= ', ';
} }
if ($q_sub_data) { // && (!$primary_key || ($primary_key && !in_array($field, $not_write_array)))) if ($q_sub_data) {
// && (!$primary_key ||
// ($primary_key && !in_array($field, $not_write_array))))
$q_sub_data .= ', '; $q_sub_data .= ', ';
} }
if ($primary_key['value']) { if ($primary_key['value']) {
$q_sub_data .= $field.' = '; $q_sub_data .= $field . ' = ';
} else { } else {
$q_sub_value .= $field; $q_sub_value .= $field;
} }
@@ -1942,7 +2134,13 @@ class IO extends \CoreLibs\Basic
$q_sub_data .= is_numeric($_data) ? $_data : 'NULL'; $q_sub_data .= is_numeric($_data) ? $_data : 'NULL';
} else { } else {
// if bool -> set bool, else write data // if bool -> set bool, else write data
$q_sub_data .= isset($_data) ? "'".($is_bool ? $this->dbBoolean($_data, true) : $this->dbEscapeString($_data))."'" : 'NULL'; $q_sub_data .= isset($_data) ?
"'" . (
$is_bool ?
$this->dbBoolean($_data, true) :
$this->dbEscapeString($_data)
) . "'" :
'NULL';
} }
} }
} }
@@ -1950,12 +2148,12 @@ class IO extends \CoreLibs\Basic
// first work contact itself (we need contact id for everything else) // first work contact itself (we need contact id for everything else)
if ($primary_key['value'] && $primary_key['row']) { if ($primary_key['value'] && $primary_key['row']) {
$q = 'UPDATE '.$table.' SET '; $q = 'UPDATE ' . $table . ' SET ';
$q .= $q_sub_data.' '; $q .= $q_sub_data . ' ';
$q .= 'WHERE '.$primary_key['row'].' = '.$primary_key['value']; $q .= 'WHERE ' . $primary_key['row'] . ' = ' . $primary_key['value'];
$this->temp_sql = $q_sub_data; $this->temp_sql = $q_sub_data;
} else { } else {
$q = 'INSERT INTO '.$table.' ('; $q = 'INSERT INTO ' . $table . ' (';
$q .= $q_sub_value; $q .= $q_sub_value;
$q .= ') VALUES ('; $q .= ') VALUES (';
$q .= $q_sub_data; $q .= $q_sub_data;
@@ -1992,7 +2190,11 @@ class IO extends \CoreLibs\Basic
$seconds = $matches[4] != '00' ? preg_replace('/^0/', '', $matches[4]) : ''; $seconds = $matches[4] != '00' ? preg_replace('/^0/', '', $matches[4]) : '';
$milliseconds = $matches[6]; $milliseconds = $matches[6];
return $prefix.($hour ? $hour.'h ' : '').($minutes ? $minutes.'m ' : '').($seconds ? $seconds.'s' : '').($show_micro && $milliseconds? ' '.$milliseconds.'ms' : ''); return $prefix
. ($hour ? $hour . 'h ' : '')
. ($minutes ? $minutes . 'm ' : '')
. ($seconds ? $seconds . 's' : '')
. ($show_micro && $milliseconds ? ' ' . $milliseconds . 'ms' : '');
} }
/** /**
@@ -2022,10 +2224,10 @@ class IO extends \CoreLibs\Basic
$value = $value === '' ? "NULL" : floatval($value); $value = $value === '' ? "NULL" : floatval($value);
break; break;
case 't': case 't':
$value = $value === '' ? "NULL" : "'".$this->dbEscapeString($value)."'"; $value = $value === '' ? "NULL" : "'" . $this->dbEscapeString($value) . "'";
break; break;
case 'd': case 'd':
$value = $value === '' ? "NULL" : "'".$this->dbEscapeString($value)."'"; $value = $value === '' ? "NULL" : "'" . $this->dbEscapeString($value) . "'";
break; break;
case 'i2': case 'i2':
$value = $value === '' ? 0 : intval($value); $value = $value === '' ? 0 : intval($value);
@@ -2125,24 +2327,6 @@ class IO extends \CoreLibs\Basic
return $this->num_rows ?? null; return $this->num_rows ?? null;
} }
/**
* Switches db debug flag on or off
* OR
* with the optional parameter fix sets debug
* returns current set stats
* @param bool|null $debug Flag to turn debug on off
* @return bool True for debug is on, False for off
*/
public function dbToggleDebug(?bool $debug = null)
{
if ($debug !== null) {
$this->db_debug = $debug;
} else {
$this->db_debug = $this->db_debug ? false : true;
}
return $this->db_debug;
}
// DEPEREACTED CALLS // DEPEREACTED CALLS
/** /**
@@ -2153,7 +2337,7 @@ class IO extends \CoreLibs\Basic
*/ */
public function getInsertReturn($key = null) public function getInsertReturn($key = null)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use getReturningExt($key = null)', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use getReturningExt($key = null)', E_USER_DEPRECATED);
return $this->dbGetReturningExt($key); return $this->dbGetReturningExt($key);
} }
@@ -2164,7 +2348,7 @@ class IO extends \CoreLibs\Basic
*/ */
public function getReturning() public function getReturning()
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use dbGetReturning()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetReturning()', E_USER_DEPRECATED);
return $this->dbGetReturning(); return $this->dbGetReturning();
} }
@@ -2175,7 +2359,7 @@ class IO extends \CoreLibs\Basic
*/ */
public function getInsertPK() public function getInsertPK()
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use dbGetInsertPK()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetInsertPK()', E_USER_DEPRECATED);
return $this->dbGetReturning(); return $this->dbGetReturning();
} }
@@ -2187,7 +2371,7 @@ class IO extends \CoreLibs\Basic
*/ */
public function getReturningExt($key = null) public function getReturningExt($key = null)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use dbGetReturningExt($key = null)', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetReturningExt($key = null)', E_USER_DEPRECATED);
return $this->dbGetReturningExt($key); return $this->dbGetReturningExt($key);
} }
@@ -2199,7 +2383,7 @@ class IO extends \CoreLibs\Basic
*/ */
public function getCursorExt($q = null) public function getCursorExt($q = null)
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use dbGetCursorExt($q = null)', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetCursorExt($q = null)', E_USER_DEPRECATED);
return $this->dbGetCursorExt($q); return $this->dbGetCursorExt($q);
} }
@@ -2210,9 +2394,21 @@ class IO extends \CoreLibs\Basic
*/ */
public function getNumRows() public function getNumRows()
{ {
trigger_error('Method '.__METHOD__.' is deprecated, use dbGetNumRows()', E_USER_DEPRECATED); trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetNumRows()', E_USER_DEPRECATED);
return $this->dbGetNumRows(); return $this->dbGetNumRows();
} }
} // end if db class
/**
* Sets error number that was last
* So we always have the last error number stored even if a new one is created
*
* @return int last error number
*/
public function getHadError()
{
return $this->had_error;
}
// end if db class
}
// __END__ // __END__

View File

@@ -1,4 +1,5 @@
<?php declare(strict_types=1); <?php
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2003/04/09 * CREATED: 2003/04/09
@@ -11,7 +12,9 @@
* HISTORY: * HISTORY:
* 2008/04/16 (cs) wrapper for pg escape string * 2008/04/16 (cs) wrapper for pg escape string
* 2007/01/11 (cs) add prepare/execute for postgres * 2007/01/11 (cs) add prepare/execute for postgres
* 2006/09/12 (cs) in case db_query retuns false, save the query and run the query through the send/get procedure to get correct error data from the db * 2006/09/12 (cs) in case db_query retuns false, save the query and
* run the query through the send/get procedure to get
* correct error data from the db
* 2006/06/26 (cs) added port for db connection * 2006/06/26 (cs) added port for db connection
* 2006/04/03 (cs) added meta data for table * 2006/04/03 (cs) added meta data for table
* 2005/07/25 (cs) removed the plural s remove, not needed and not 100% working * 2005/07/25 (cs) removed the plural s remove, not needed and not 100% working
@@ -41,6 +44,8 @@
* *
*/ */
declare(strict_types=1);
namespace CoreLibs\DB\SQL; namespace CoreLibs\DB\SQL;
class PgSQL class PgSQL
@@ -258,9 +263,9 @@ class PgSQL
// if (preg_match("/.*s$/i", $table)) // if (preg_match("/.*s$/i", $table))
// $table = substr($table, 0, -1); // $table = substr($table, 0, -1);
// set pk_name to "id" // set pk_name to "id"
$pk_name = $table."_id"; $pk_name = $table . "_id";
} }
$seq = ($schema ? $schema.'.' : '').$table."_".$pk_name."_seq"; $seq = ($schema ? $schema . '.' : '') . $table . "_" . $pk_name . "_seq";
$q = "SELECT CURRVAL('$seq') AS insert_id"; $q = "SELECT CURRVAL('$seq') AS insert_id";
// I have to do manually or I overwrite the original insert internal vars ... // I have to do manually or I overwrite the original insert internal vars ...
if ($q = $this->__dbQuery($q)) { if ($q = $this->__dbQuery($q)) {
@@ -288,27 +293,28 @@ class PgSQL
$cursor = $this->__dbQuery($q); $cursor = $this->__dbQuery($q);
$search_path = $this->__dbFetchArray($cursor)['search_path']; $search_path = $this->__dbFetchArray($cursor)['search_path'];
if ($search_path != $schema) { if ($search_path != $schema) {
$table_prefix = $schema.'.'; $table_prefix = $schema . '.';
} }
} }
// read from table the PK name // read from table the PK name
// faster primary key get // faster primary key get
$q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type "; $q = "SELECT pg_attribute.attname AS column_name, "
$q .= "FROM pg_index, pg_class, pg_attribute "; . "format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type "
. "FROM pg_index, pg_class, pg_attribute ";
if ($schema) { if ($schema) {
$q .= ", pg_namespace "; $q .= ", pg_namespace ";
} }
$q .= "WHERE "; $q .= "WHERE "
// regclass translates the OID to the name // regclass translates the OID to the name
$q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND "; . "pg_class.oid = '" . $table_prefix . $table . "'::regclass AND "
$q .= "indrelid = pg_class.oid AND "; . "indrelid = pg_class.oid AND ";
if ($schema) { if ($schema) {
$q .= "nspname = '".$schema."' AND "; $q .= "nspname = '" . $schema . "' AND "
$q .= "pg_class.relnamespace = pg_namespace.oid AND "; . "pg_class.relnamespace = pg_namespace.oid AND ";
} }
$q .= "pg_attribute.attrelid = pg_class.oid AND "; $q .= "pg_attribute.attrelid = pg_class.oid AND "
$q .= "pg_attribute.attnum = any(pg_index.indkey) "; . "pg_attribute.attnum = any(pg_index.indkey) "
$q .= "AND indisprimary"; . "AND indisprimary";
$cursor = $this->__dbQuery($q); $cursor = $this->__dbQuery($q);
if ($cursor) { if ($cursor) {
return $this->__dbFetchArray($cursor)['column_name'] ?? false; return $this->__dbFetchArray($cursor)['column_name'] ?? false;
@@ -330,15 +336,23 @@ class PgSQL
* @param string $db_ssl SSL (allow is default) * @param string $db_ssl SSL (allow is default)
* @return ?resource db handler resource or null on error * @return ?resource db handler resource or null on error
*/ */
public function __dbConnect(string $db_host, string $db_user, string $db_pass, string $db_name, int $db_port = 5432, string $db_ssl = 'allow') public function __dbConnect(
{ string $db_host,
string $db_user,
string $db_pass,
string $db_name,
int $db_port = 5432,
string $db_ssl = 'allow'
) {
// to avoid empty db_port // to avoid empty db_port
if (!$db_port) { if (!$db_port) {
$db_port = 5432; $db_port = 5432;
} }
$this->dbh = pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl); $this->dbh = pg_connect("host=" . $db_host . " port=" . $db_port . " user="
. $db_user . " password=" . $db_pass . " dbname=" . $db_name . " sslmode=" . $db_ssl);
if (!$this->dbh) { if (!$this->dbh) {
die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->"); die("<!-- Can't connect [host=" . $db_host . " port=" . $db_port . " user="
. $db_user . " password=XXXX dbname=" . $db_name . " sslmode=" . $db_ssl . "] //-->");
return null; return null;
} }
return $this->dbh; return $this->dbh;
@@ -359,7 +373,7 @@ class PgSQL
$cursor = pg_get_result($this->dbh); $cursor = pg_get_result($this->dbh);
} }
if ($cursor && pg_result_error($cursor)) { if ($cursor && pg_result_error($cursor)) {
return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>"; return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> " . pg_result_error($cursor) . "</span><br>";
} else { } else {
return ''; return '';
} }

View File

@@ -1,10 +1,12 @@
<?php declare(strict_types=1); <?php
/* /*
* direct write to log file * direct write to log file
* must have BASE folder and LOG foder defined * must have BASE folder and LOG foder defined
*/ */
declare(strict_types=1);
namespace CoreLibs\Debug; namespace CoreLibs\Debug;
class FileWriter class FileWriter
@@ -40,10 +42,10 @@ class FileWriter
if (!self::$debug_filename) { if (!self::$debug_filename) {
return false; return false;
} }
if (!is_writeable(BASE.LOG)) { if (!is_writeable(BASE . LOG)) {
return false; return false;
} }
$filename = BASE.LOG.self::$debug_filename; $filename = BASE . LOG . self::$debug_filename;
$fh = fopen($filename, 'a'); $fh = fopen($filename, 'a');
if ($fh === false) { if ($fh === false) {
return false; return false;
@@ -51,7 +53,8 @@ class FileWriter
if ($enter === true) { if ($enter === true) {
$string .= "\n"; $string .= "\n";
} }
$string = "[".\CoreLibs\Debug\Support::printTime()."] [".\CoreLibs\Get\System::getPageName(2)."] - ".$string; $string = "[" . \CoreLibs\Debug\Support::printTime() . "] "
. "[" . \CoreLibs\Get\System::getPageName(2) . "] - " . $string;
fwrite($fh, $string); fwrite($fh, $string);
fclose($fh); fclose($fh);
return true; return true;

View File

@@ -1,4 +1,4 @@
<?php declare(strict_types=1); <?php
/* /*
* Debug support functions * Debug support functions
@@ -20,6 +20,8 @@
 * print_output_not  * print_output_not
*/ */
declare(strict_types=1);
namespace CoreLibs\Debug; namespace CoreLibs\Debug;
class Logging class Logging
@@ -45,6 +47,7 @@ class Logging
// debug flags/settings // debug flags/settings
private $running_uid = ''; // unique ID set on class init and used in logging as prefix private $running_uid = ''; // unique ID set on class init and used in logging as prefix
// log file name // log file name
private $log_folder = '';
private $log_file_name_ext = 'log'; // use this for date rotate private $log_file_name_ext = 'log'; // use this for date rotate
private $log_max_filesize = 0; // set in kilobytes private $log_max_filesize = 0; // set in kilobytes
private $log_print_file = 'error_msg##LOGID####LEVEL####CLASS####PAGENAME####DATE##'; private $log_print_file = 'error_msg##LOGID####LEVEL####CLASS####PAGENAME####DATE##';
@@ -60,6 +63,14 @@ class Logging
public function __construct() public function __construct()
{ {
// check must set constants
if (defined('BASE') && defined('LOG')) {
$this->log_folder = BASE . LOG;
} else {
// fallback + warning
trigger_error('constant BASE or LOG are not defined, fallback to getcwd()', E_USER_WARNING);
$this->log_folder = getcwd() . DS;
}
// running time start for script // running time start for script
$this->script_starttime = microtime(true); $this->script_starttime = microtime(true);
// set per run UID for logging // set per run UID for logging
@@ -70,7 +81,7 @@ class Logging
list($this->host_name , $this->host_port) = \CoreLibs\Get\System::getHostName(); list($this->host_name , $this->host_port) = \CoreLibs\Get\System::getHostName();
// add port to host name if not port 80 // add port to host name if not port 80
if ($this->host_port != 80) { if ($this->host_port != 80) {
$this->host_name .= ':'.$this->host_port; $this->host_name .= ':' . $this->host_port;
} }
// can be overridden with basicSetLogFileId // can be overridden with basicSetLogFileId
if (isset($GLOBALS['LOG_FILE_ID'])) { if (isset($GLOBALS['LOG_FILE_ID'])) {
@@ -143,7 +154,8 @@ class Logging
// check if we do debug, echo or print // check if we do debug, echo or print
switch ($target) { switch ($target) {
case 'debug': case 'debug':
if (( if (
(
(isset($this->debug_output[$level]) && $this->debug_output[$level]) || (isset($this->debug_output[$level]) && $this->debug_output[$level]) ||
$this->debug_output_all $this->debug_output_all
) && ) &&
@@ -155,7 +167,8 @@ class Logging
} }
break; break;
case 'echo': case 'echo':
if (( if (
(
(isset($this->echo_output[$level]) && $this->echo_output[$level]) || (isset($this->echo_output[$level]) && $this->echo_output[$level]) ||
$this->echo_output_all $this->echo_output_all
) && ) &&
@@ -167,7 +180,8 @@ class Logging
} }
break; break;
case 'print': case 'print':
if (( if (
(
(isset($this->print_output[$level]) && $this->print_output[$level]) || (isset($this->print_output[$level]) && $this->print_output[$level]) ||
$this->print_output_all $this->print_output_all
) && ) &&
@@ -191,7 +205,8 @@ class Logging
private function writeErrorMsg(string $level, string $error_string): bool private function writeErrorMsg(string $level, string $error_string): bool
{ {
// only write if write is requested // only write if write is requested
if (!($this->doDebugTrigger('debug', $level) && if (
!($this->doDebugTrigger('debug', $level) &&
$this->doDebugTrigger('print', $level)) $this->doDebugTrigger('print', $level))
) { ) {
return false; return false;
@@ -205,10 +220,10 @@ class Logging
// init output variable // init output variable
$output = $error_string; // output formated error string to output file $output = $error_string; // output formated error string to output file
// init base file path // init base file path
$fn = BASE.LOG.$this->log_print_file.'.'.$this->log_file_name_ext; $fn = $this->log_folder . $this->log_print_file . '.' . $this->log_file_name_ext;
// log ID prefix settings, if not valid, replace with empty // log ID prefix settings, if not valid, replace with empty
if (preg_match("/^[A-Za-z0-9]+$/", $this->log_file_id)) { if (preg_match("/^[A-Za-z0-9]+$/", $this->log_file_id)) {
$rpl_string = '_'.$this->log_file_id; $rpl_string = '_' . $this->log_file_id;
} else { } else {
$rpl_string = ''; $rpl_string = '';
} }
@@ -219,28 +234,33 @@ class Logging
$this->log_file_unique_id = $GLOBALS['LOG_FILE_UNIQUE_ID']; $this->log_file_unique_id = $GLOBALS['LOG_FILE_UNIQUE_ID'];
} }
if (!$this->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); $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 $rpl_string = '_' . $this->log_file_unique_id; // add 8 char unique string
} else { } else {
$rpl_string = !$this->log_print_file_date ? '' : '_'.date('Y-m-d'); // add date to file $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 $fn = str_replace('##DATE##', $rpl_string, $fn); // create output filename
$rpl_string = !$this->log_per_level ? '' : '_'.$level; // if request to write to one file $rpl_string = !$this->log_per_level ? '' : '_' . $level; // if request to write to one file
$fn = str_replace('##LEVEL##', $rpl_string, $fn); // create output filename $fn = str_replace('##LEVEL##', $rpl_string, $fn); // create output filename
// set per class, but don't use get_class as we will only get self // set per class, but don't use get_class as we will only get self
$rpl_string = !$this->log_per_class ? '' : '_'.str_replace('\\', '-', \CoreLibs\Debug\Support::getCallerClass()); // set sub class settings $rpl_string = !$this->log_per_class ? '' : '_'
// set sub class settings
. str_replace('\\', '-', \CoreLibs\Debug\Support::getCallerClass());
$fn = str_replace('##CLASS##', $rpl_string, $fn); // create output filename $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 // if request to write to one file
$rpl_string = !$this->log_per_page ? '' : '_' . \CoreLibs\Get\System::getPageName(1);
$fn = str_replace('##PAGENAME##', $rpl_string, $fn); // create output filename $fn = str_replace('##PAGENAME##', $rpl_string, $fn); // create output filename
// write to file // write to file
// first check if max file size is is set and file is bigger // 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)) { 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 // for easy purpose, rename file only to attach timestamp, nur sequence numbering
rename($fn, $fn.'.'.date("YmdHis")); rename($fn, $fn . '.' . date("YmdHis"));
} }
$fp = fopen($fn, 'a'); $fp = fopen($fn, 'a');
if ($fp !== false) { if ($fp !== false) {
@@ -293,7 +313,7 @@ class Logging
if (!in_array($type, ['debug', 'echo', 'print'])) { if (!in_array($type, ['debug', 'echo', 'print'])) {
return false; return false;
} }
return $this->{$type.'_output_all'}; return $this->{$type . '_output_all'};
} }
/** /**
@@ -309,7 +329,7 @@ class Logging
if (!in_array($type, ['debug', 'echo', 'print'])) { if (!in_array($type, ['debug', 'echo', 'print'])) {
return; return;
} }
$this->{$type.'_output_all'} = $set; $this->{$type . '_output_all'} = $set;
} }
/** /**
@@ -349,7 +369,7 @@ class Logging
array_shift($debug_on); // kick out flag (on/off) array_shift($debug_on); // kick out flag (on/off)
if (count($debug_on) >= 1) { if (count($debug_on) >= 1) {
foreach ($debug_on as $level) { foreach ($debug_on as $level) {
$switch = $type.'_output'.($flag == 'off' ? '_not' : ''); $switch = $type . '_output' . ($flag == 'off' ? '_not' : '');
$this->{$switch}[$level] = true; $this->{$switch}[$level] = true;
} }
} }
@@ -373,7 +393,7 @@ class Logging
if (!in_array($flag, ['on', 'off'])) { if (!in_array($flag, ['on', 'off'])) {
return false; return false;
} }
$switch = $type.'_output'.($flag == 'off' ? '_not' : ''); $switch = $type . '_output' . ($flag == 'off' ? '_not' : '');
// bool // bool
if ($level !== null) { if ($level !== null) {
return $this->{$switch}[$level] ?? false; return $this->{$switch}[$level] ?? false;
@@ -397,7 +417,7 @@ class Logging
if (!in_array($type, ['level', 'class', 'page', 'run'])) { if (!in_array($type, ['level', 'class', 'page', 'run'])) {
return; return;
} }
$this->{'log_per_'.$type} = $set; $this->{'log_per_' . $type} = $set;
} }
/** /**
@@ -410,7 +430,7 @@ class Logging
if (!in_array($type, ['level', 'class', 'page', 'run'])) { if (!in_array($type, ['level', 'class', 'page', 'run'])) {
return false; return false;
} }
return $this->{'log_per_'.$type}; return $this->{'log_per_' . $type};
} }
/** /**
@@ -424,7 +444,7 @@ class Logging
*/ */
public function prAr(array $a): string public function prAr(array $a): string
{ {
return '{##HTMLPRE##}'.print_r($a, true).'{##/HTMLPRE##}'; return '##HTMLPRE##' . print_r($a, true) . '##/HTMLPRE##';
} }
/** /**
@@ -434,9 +454,12 @@ class Logging
* @param bool $strip default on false, if set to true, * @param bool $strip default on false, if set to true,
* all html tags will be stripped and <br> changed to \n * all html tags will be stripped and <br> changed to \n
* this is only used for debug output * this is only used for debug output
* @param string $prefix Attach some block before $string. Will not be stripped even
* when strip is true
* if strip is false, recommended to add that to $string
* @return bool True if logged, false if not logged * @return bool True if logged, false if not logged
*/ */
public function debug(string $level, string $string, bool $strip = false): bool public function debug(string $level, string $string, bool $strip = false, string $prefix = ''): bool
{ {
if (!$this->doDebugTrigger('debug', $level)) { if (!$this->doDebugTrigger('debug', $level)) {
return false; return false;
@@ -449,25 +472,25 @@ class Logging
// write to file if set // write to file if set
$this->writeErrorMsg( $this->writeErrorMsg(
$level, $level,
'['.$timestamp.'] ' '[' . $timestamp . '] '
.'['.$this->host_name.'] ' . '[' . $this->host_name . '] '
.'['.\CoreLibs\Get\System::getPageName(2).'] ' . '[' . \CoreLibs\Get\System::getPageName(2) . '] '
.'['.$this->running_uid.'] ' . '[' . $this->running_uid . '] '
.'{'.$class.'} ' . '{' . $class . '} '
.'<'.$level.'> - ' . '<' . $level . '> - '
// strip the htmlpre special tags if exist // strip the htmlpre special tags if exist
.preg_replace( . str_replace(
"/{##HTMLPRE##}((.|\n)*?){##\/HTMLPRE##}/m", ['##HTMLPRE##', '##/HTMLPRE##'],
'\\1', '',
// if stripping all html, etc is requested, only for write error msg // if stripping all html, etc is requested, only for write error msg
($strip ? ($strip ?
// find any <br> and replace them with \n // find any <br> and replace them with \n
// strip rest of html elements (base only) // strip rest of html elements (base only)
preg_replace("/(<\/?)(\w+)([^>]*>)/", '', str_replace('<br>', "\n", $string)) : preg_replace("/(<\/?)(\w+)([^>]*>)/", '', str_replace('<br>', "\n", $prefix . $string)) :
$string $prefix . $string
) )
) )
."\n" . "\n"
); );
// write to error level msg array if there is an echo request // write to error level msg array if there is an echo request
if ($this->doDebugTrigger('echo', $level)) { if ($this->doDebugTrigger('echo', $level)) {
@@ -477,15 +500,21 @@ class Logging
} }
// HTML string // HTML string
$this->error_msg[$level][] = '<div>' $this->error_msg[$level][] = '<div>'
.'[<span style="font-weight: bold; color: #5e8600;">'.$timestamp.'</span>] ' . '[<span style="font-weight: bold; color: #5e8600;">' . $timestamp . '</span>] '
.'[<span style="font-weight: bold; color: #c56c00;">'.$level.'</span>] ' . '[<span style="font-weight: bold; color: #c56c00;">' . $level . '</span>] '
.'[<span style="color: #b000ab;">'.$this->host_name.'</span>] ' . '[<span style="color: #b000ab;">' . $this->host_name . '</span>] '
.'[<span style="color: #08b369;">'.$this->page_name.'</span>] ' . '[<span style="color: #08b369;">' . $this->page_name . '</span>] '
.'[<span style="color: #0062A2;">'.$this->running_uid.'</span>] ' . '[<span style="color: #0062A2;">' . $this->running_uid . '</span>] '
.'{<span style="font-style: italic; color: #928100;">'.$class.'</span>} - ' . '{<span style="font-style: italic; color: #928100;">' . $class . '</span>} - '
// as is prefix, allow HTML
. $prefix
// we replace special HTMLPRE with <pre> entries // we replace special HTMLPRE with <pre> entries
.preg_replace("/{##HTMLPRE##}((.|\n)*?){##\/HTMLPRE##}/m", "<pre>\\1</pre>", \CoreLibs\Convert\Html::htmlent($string)) . str_replace(
."</div><!--#BR#-->"; ['##HTMLPRE##', '##/HTMLPRE##'],
['<pre>', '</pre>'],
\CoreLibs\Convert\Html::htmlent($string)
)
. "</div><!--#BR#-->";
} }
return true; return true;
} }
@@ -521,20 +550,25 @@ class Logging
if ($this->doDebugTrigger('debug', $level)) { if ($this->doDebugTrigger('debug', $level)) {
if ($this->doDebugTrigger('echo', $level)) { if ($this->doDebugTrigger('echo', $level)) {
$string_output .= '<div style="font-size: 12px;">' $string_output .= '<div style="font-size: 12px;">'
.'[<span style="font-style: italic; color: #c56c00;">'.$level.'</span>] ' . '[<span style="font-style: italic; color: #c56c00;">' . $level . '</span>] '
.($string ? "<b>**** ".\CoreLibs\Convert\Html::htmlent($string)." ****</br>\n" : "") . ($string ? "<b>**** " . \CoreLibs\Convert\Html::htmlent($string) . " ****</br>\n" : "")
.'</div>' . '</div>'
.join('', $temp_debug_output); . join('', $temp_debug_output);
} // echo it out } // echo it out
} // do printout } // do printout
} // for each level } // for each level
// create the output wrapper around, so we have a nice formated output per class // create the output wrapper around, so we have a nice formated output per class
if ($string_output) { if ($string_output) {
$string_prefix = '<div style="text-align: left; padding: 5px; font-size: 10px; font-family: sans-serif; border-top: 1px solid black; border-bottom: 1px solid black; margin: 10px 0 10px 0; background-color: white; color: black;">' $string_prefix = '<div style="text-align: left; padding: 5px; font-size: 10px; '
.'<div style="font-size: 12px;">{<span style="font-style: italic; color: #928100;">'.\CoreLibs\Debug\Support::getCallerClass().'</span>}</div>'; . 'font-family: sans-serif; border-top: 1px solid black; '
$string_output = $string_prefix.$string_output . 'border-bottom: 1px solid black; margin: 10px 0 10px 0; '
.'<div><span style="font-style: italic; color: #108db3;">Script Run Time:</span> '.$script_end.'</div>' . 'background-color: white; color: black;">'
.'</div>'; . '<div style="font-size: 12px;">{<span style="font-style: italic; color: #928100;">'
. \CoreLibs\Debug\Support::getCallerClass() . '</span>}</div>';
$string_output = $string_prefix . $string_output
. '<div><span style="font-style: italic; color: #108db3;">Script Run Time:</span> '
. $script_end . '</div>'
. '</div>';
} }
} }
return $string_output; return $string_output;
@@ -555,6 +589,16 @@ class Logging
unset($this->error_msg[$level]); unset($this->error_msg[$level]);
} }
} }
/**
* Get current error message array
*
* @return array error messages collected
*/
public function getErrorMsg(): array
{
return $this->error_msg;
}
} }
// __END__ // __END__

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* various running time checkers * various running time checkers
*/ */
declare(strict_types=1);
namespace CoreLibs\Debug; namespace CoreLibs\Debug;
class RunningTime class RunningTime
@@ -93,11 +95,11 @@ class RunningTime
self::$runningtime_string .= $simple ? 'End: ' : "<b>Stopped at</b>: "; self::$runningtime_string .= $simple ? 'End: ' : "<b>Stopped at</b>: ";
} }
self::$runningtime_string .= date('Y-m-d H:i:s', (int)$timestamp); self::$runningtime_string .= date('Y-m-d H:i:s', (int)$timestamp);
self::$runningtime_string .= ' '.$micro.($simple ? ', ' : '<br>'); self::$runningtime_string .= ' ' . $micro . ($simple ? ', ' : '<br>');
// if both are set // if both are set
if (self::$starttime && self::$endtime) { if (self::$starttime && self::$endtime) {
$running_time = self::$endtime - self::$starttime; $running_time = self::$endtime - self::$starttime;
self::$runningtime_string .= ($simple ? 'Run: ' : "<b>Script running time</b>: ").$running_time." s"; self::$runningtime_string .= ($simple ? 'Run: ' : "<b>Script running time</b>: ") . $running_time . " s";
// reset start & end time after run // reset start & end time after run
self::$starttime = 0; self::$starttime = 0;
self::$endtime = 0; self::$endtime = 0;

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* Debug support functions * Debug support functions
*/ */
declare(strict_types=1);
namespace CoreLibs\Debug; namespace CoreLibs\Debug;
class Support class Support
@@ -34,7 +36,7 @@ class Support
*/ */
public static function printAr(array $array): string public static function printAr(array $array): string
{ {
return "<pre>".print_r($array, true)."</pre>"; return "<pre>" . print_r($array, true) . "</pre>";
} }
/** /**
@@ -68,10 +70,31 @@ class Support
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) ?? [['class' => get_called_class()]]; $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) ?? [['class' => get_called_class()]];
$class = null; $class = null;
while ($class === null) { while ($class === null) {
// if current is
// [function] => debug
// [class] => CoreLibs\Debug\Logging
// then return
// (OUTSIDE) because it was not called from a class method
// or return file name
$class = array_pop($backtrace)['class'] ?? null; $class = array_pop($backtrace)['class'] ?? null;
} }
return $class ?? ''; return $class ?? '';
} }
/**
* If a string is empty, sets '-' for return, or if given any other string
*
* @param string|null $string The string to check
* @param string $replace [default '-'] What to replace the empty string with
* @return string String itself or the replaced value
*/
public static function debugString(?string $string, string $replace = '-'): string
{
if (empty($string)) {
return $replace;
}
return $string;
}
} }
// __END__ // __END__

View File

@@ -1,9 +1,11 @@
<?php declare(strict_types=1); <?php
/* /*
* system related functions to get self name, host name, error strings * system related functions to get self name, host name, error strings
*/ */
declare(strict_types=1);
namespace CoreLibs\Get; namespace CoreLibs\Get;
class System class System
@@ -80,6 +82,16 @@ class System
return $page_temp['basename']; return $page_temp['basename'];
} }
} }
/**
* similar to getPageName, but it retuns the raw array
*
* @return array pathinfo array from PHP SELF
*/
public static function getPageNameArray(): array
{
return pathinfo($_SERVER['PHP_SELF']);
}
} }
// __END__ // __END__

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