| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417 |
- <?php
- Lib::loadClass('User');
- Lib::loadClass('UI');
- Lib::loadClass('Request');
- class DBG {
- public static function isActive($mode = null) {
- return (isset($_SESSION)) ? (true == V::get('_DBG_ON', false, $_SESSION)) : false;
- }
- public static function activate($mode = null) {// @used in User::auth()
- if (isset($_SESSION)) $_SESSION['_DBG_ON'] = true;
- }
- public static function deactivate($mode = 'all') {
- if (isset($_SESSION)) $_SESSION['_DBG_ON'] = false;
- }
- /**
- * @param $reqKqy - key in $_REQUEST array (if true then always show)
- * @param $reqValueExpr - expression to compare req value
- * true - always visible - only for fast DBG without $reqKey in REQUEST
- * '>*', '>=*', '<*', '<=*' - compare $reqValue
- * examples:
- * - show when $_REQUEST['DBG_SCH'] == '1'
- * DBG::_('DBG_SCH', '1', "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
- * - show when $_REQUEST['DBG_SCH'] > '1'
- * DBG::_('DBG_SCH', '>1', "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
- * - show when any value: strlen($_REQUEST['DBG_SCH']) > 0
- * DBG::_('DBG_SCH', true, "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
- * - always show
- * DBG::_(true, true, "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
- */
- public static function _($reqKey, $reqValueExpr, $label, $variable, $className, $functionName, $lineNumber, $borderColor = 'red') {
- if (!DBG::isActive()) return;
- $showDBG = false;
- $reqValue = (true === $reqKey || !$reqKey)? '' : V::get($reqKey, '', $_GET);
- if (true === $reqKey) {
- $showDBG = true;
- }
- else if (strlen($reqValue) == 0) {
- return;
- }
- else if ($reqValue == $reqValueExpr) {
- $showDBG = true;
- }
- else if (true === $reqValueExpr) {
- $showDBG = true;
- }
- else {
- if ('>=' == substr($reqValueExpr, 0, 2)) {
- if ($reqValue >= substr($reqValueExpr, 2)) {
- $showDBG = true;
- }
- }
- else if ('>' == substr($reqValueExpr, 0, 1)) {
- if ($reqValue > substr($reqValueExpr, 1)) {
- $showDBG = true;
- }
- }
- else if ('<=' == substr($reqValueExpr, 0, 2)) {
- if ($reqValue <= substr($reqValueExpr, 2)) {
- $showDBG = true;
- }
- }
- else if ('<' == substr($reqValueExpr, 0, 1)) {
- if ($reqValue < substr($reqValueExpr, 1)) {
- $showDBG = true;
- }
- }
- else {
- if ($reqValue = $reqValueExpr) {
- $showDBG = true;
- }
- }
- }
- if ($showDBG) {
- ?>
- <pre style="max-height:200px;max-width:800px;overflow:auto;border:1px solid <?php echo $borderColor; ?>;text-align:left;"
- ><?php echo "{$label} ({$className}::{$functionName}:{$lineNumber}):\n"; ?>
- <?php print_r($variable);?>
- </pre>
- <?php
- }
- }
- public static function tableInFrame($label, $table, $className, $functionName, $lineNumber) {
- ?>
- <div class="container" style="margin-top:10px; margin-bottom:10px; background:#ddd">
- <h3 style="margin:10px 0"><?php echo "{$label} <small>({$className}::{$functionName}:{$lineNumber}):</small>"; ?></h3>
- <div style="max-height:300px;overflow:scroll;border:1px solid #ddd; background:#fff">
- <?php self::table($label, $table, $className, $functionName, $lineNumber); ?>
- </div>
- </div>
- <?php
- }
- public static function table($label, $rows, $className, $functionName, $lineNumber) {
- $params = array();
- $params['caption'] = "{$label} ({$className}::{$functionName}:{$lineNumber}):";
- $params['rows'] = $rows;
- UI::table($params);
- }
- public static function diffTable($label, $table, $params = array(), $className, $functionName, $lineNumber) {
- $cols = array();
- if (is_array($table) && !empty($table)) {
- $firstRow = array();
- foreach ($table as $row) {
- $firstRow = $row;
- break;
- }
- if (is_array($firstRow)) {
- $cols = array_keys($firstRow);
- }
- else if (is_object($firstRow)) {
- $cols = array_keys((array)$firstRow);
- }
- else {
- return;// bad table item type
- }
- }
- $diffPrefix = V::get('diff_prefix', 'diff_', $params);
- $diffTblOnePrefix = V::get('diff_tbl_one', '', $params);
- $diffTblTwoPrefix = V::get('diff_tbl_two', '', $params);
- $diffColsSplit = array();
- {
- $diffPrefixLen = strlen($diffPrefix);
- foreach ($cols as $colName) {
- if ($diffPrefix == substr($colName, 0, $diffPrefixLen)) {
- $diffColsSplit[substr($colName, $diffPrefixLen)] = array();
- }
- }
- //self::_(true, true, "diffColsSplit.1", $diffColsSplit, __CLASS__, __FUNCTION__, __LINE__);
- foreach ($cols as $colName) {
- $exp = explode("_", $colName, 2);
- if (2 != count($exp)) continue;
- if (array_key_exists($exp[1], $diffColsSplit)) {
- $prefix = "{$exp[0]}_";
- $diffColsSplit[$exp[1]][] = $prefix;
- if ($prefix != $diffPrefix) {
- if (null == $diffTblOnePrefix) $diffTblOnePrefix = $prefix;
- else if (null == $diffTblTwoPrefix) $diffTblTwoPrefix = $prefix;
- }
- }
- }
- //elf::_(true, true, "diffColsSplit.2", $diffColsSplit, __CLASS__, __FUNCTION__, __LINE__);
- if (null == $diffTblOnePrefix && null == $diffTblTwoPrefix) echo "Error prefix for tables not set!";
- $notDiffCols = array();
- foreach ($cols as $colName) {
- if ("{$diffPrefix}" != substr($colName, 0, $diffPrefixLen)
- && "{$diffTblOnePrefix}" != substr($colName, 0, strlen($diffTblOnePrefix))
- && "{$diffTblTwoPrefix}" != substr($colName, 0, strlen($diffTblTwoPrefix))
- )
- $notDiffCols[] = $colName;
- }
- //self::_(true, true, "notDiffCols", $notDiffCols, __CLASS__, __FUNCTION__, __LINE__);
- }
- ?>
- <table class="table table-bordered table-hover">
- <caption><?php echo "{$label} ({$className}::{$functionName}:{$lineNumber}):"; ?></caption>
- <thead>
- <tr>
- <th style="padding:2px;">Lp.</th>
- <?php foreach ($notDiffCols as $colName) : ?>
- <th style="padding:2px;"><?php echo $colName; ?></th>
- <?php endforeach; ?>
- <?php foreach ($diffColsSplit as $colName => $prefixes) : ?>
- <th style="padding:2px;"><?php echo $colName; ?></th>
- <?php endforeach; ?>
- </tr>
- </thead>
- <tbody>
- <?php $i = 0; foreach ($table as $row) : $i++; ?>
- <tr>
- <td style="padding:2px;"><?php echo $i; ?></td>
- <?php foreach ($notDiffCols as $colName) : ?>
- <td style="padding:2px;"><?php echo V::get($colName, '', $row); ?></td>
- <?php endforeach; ?>
- <?php foreach ($diffColsSplit as $colName => $prefixes) : ?>
- <?php $isDiff = ('1' == V::get("{$diffPrefix}{$colName}", '', $row)); ?>
- <?php $stl = ($isDiff)? 'border:2px solid #F2DEDE;color:#a94442;' : 'border:2px solid #DFF0D8;color:#3c763d;'; ?>
- <td style="padding:2px;<?php echo $stl; ?>;font-family:monospace;white-space:nowrap;">
- <span style="color:#666"><?php echo str_pad($diffTblOnePrefix, 4, ".", STR_PAD_LEFT); ?>: </span>"<?php echo V::get("{$diffTblOnePrefix}{$colName}", '', $row); ?>"
- <div style="border-top:1px solid #fff">
- <span style="color:#666"><?php echo str_pad($diffTblTwoPrefix, 4, ".", STR_PAD_LEFT); ?>: </span>"<?php echo V::get("{$diffTblTwoPrefix}{$colName}", '', $row); ?>"
- </div>
- </td>
- <?php endforeach; ?>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- <?php
- }
- public static function nicePrint($variable, $varName, $params = []) {
- $col = ['green'=>'#96c178', 'red'=>'#de6b74', 'blue'=>'#55b5c1', 'bg-dark'=>'#282c34', 'white'=>'#abb2bf', 'orange'=>'#d19a66', 'violet'=>'#c476db'];
- $cnt = '';
- ob_start();
- print_r($variable);
- $cnt = ob_get_clean();
- $outLines = array();
- $lines = explode("\n", $cnt);
- foreach ($lines as $line) {
- if ('(' == trim($line)) continue;
- if (')' == trim($line)) continue;
- if ('' == trim($line)) continue;
- if ('Array' == substr($line, -5) || 'stdClass' == substr($line, -5)) {
- $line = str_replace('Array', '<span style="color:'.$col['blue'].'">Array</span>', $line);
- $line = str_replace('stdClass', '<span style="color:'.$col['blue'].'">stdClass</span>', $line);
- $line .= ':';
- }
- if (($firstBracket = strpos($line, '[')) > 0) {
- $line = str_replace("\t", ' ', $line);
- $splitPos = ($firstBracket > 4)? ($firstBracket - 4) / 2 + 4 : 4;
- $line = substr($line, $firstBracket - $splitPos);
- $line = preg_replace('/\[(\w+)\]/', '[<span style="color:'.$col['green'].'">\1</span>]', $line);
- $line = preg_replace('/\] \=\> (.+)$/', '] => <span style="color:'.$col['orange'].'">\1</span>', $line);
- }
- $outLines[] = $line;
- }
- if ($varName) $outLines[0] = '<b style="color:'.$col['red'].'">' . $varName . "</b> => {$outLines[0]}";
- $maxHeight = V::get('maxHeight', '400px', $params);
- echo UI::h('details', ['style'=>"max-width:800px"], [
- UI::h('summary', ['style'=>"padding:3px 8px;border:1px solid #ccc;background-color:{$col['bg-dark']};color:{$col['white']};font-size:small"], array_shift($outLines)),
- UI::h('pre', [
- 'style' => implode(";", [
- 'background-color:'.$col['bg-dark'],
- 'color:'.$col['white'],
- 'border:1px solid #ccc;border-radius:0',
- 'font-size:x-small',
- ($maxHeight) ? "max-height:{$maxHeight};overflow:scroll" : ''
- ])
- ], implode("\n", $outLines))
- ]) . "\n";
- }
- /**
- * @param $mixedArg string or Exception
- */
- public static function log($mixedArg, $type = '', $msg = '') {
- if (!self::isActive() && !self::isLogActiveByAdmin()) return;
- if ('Debug' == V::get('_route', '', $_REQUEST) && !V::get('DBG', '', $_REQUEST)) return;
- static $_firstRun = true;
- $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
- $logFileName = "/tmp/{$prefix}se-debug-" . implode('-', [
- date("Y-m-d"),
- User::getLogin(),
- Request::getUserIp(),
- substr(session_id(), 0, 6),
- V::get('REQUEST_TIME', '', $_SERVER)// [REQUEST_TIME] => 1485770466
- ]) . '.log';
- if ($_firstRun) {
- $_firstRun = false;
- $firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
- self::_log([ 'POST' => $_POST, 'GET' => $_GET, 'POST_BODY' => Request::getRequestBody() ], 'array', $firstMsg, $logFileName);
- }
- self::_log($mixedArg, $type, $msg, $logFileName);
- }
- public static function logAuth($mixedArg, $msg = '') {
- if ('Debug' == V::get('_route', '', $_REQUEST) && !V::get('DBG', '', $_REQUEST)) return;
- static $_firstRun = true;
- $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
- $logFileName = "/tmp/{$prefix}se-auth-" . implode('-', [
- date("Y-m-d"),
- Request::getUserIp(),
- V::get('REQUEST_TIME', '', $_SERVER)// [REQUEST_TIME] => 1485770466
- ]) . '.log';
- if ($_firstRun) {
- $_firstRun = false;
- $firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
- self::_log(['POST' => $_POST, 'GET' => $_GET], 'array', $firstMsg, $logFileName);
- }
- self::_log($mixedArg, $type = 'array', $msg, $logFileName);
- }
- public static function _log($mixedArg, $type, $msg, $logFileName) {
- $logInfo = [
- 'date' => date("Y-m-d H:i:s") . substr((string)microtime(), 1, 6),
- 'type' => $type,
- 'msg' => $msg,
- 'log' => '',
- 'trace' => '',
- ];
- if ($mixedArg instanceof Exception) {
- $logInfo['type'] = 'Exception';
- if (!empty($logInfo['msg'])) $logInfo['msg'] .= ". ";
- $logInfo['msg'] .= $mixedArg->getMessage();
- $logInfo['log'] = [
- 'code' => $mixedArg->getCode(),
- 'line' => $mixedArg->getLine(),
- 'file' => str_replace(APP_PATH_ROOT, 'SE', $mixedArg->getFile()),
- ];
- $logInfo['trace'] = $mixedArg->getTraceAsString();// getTrace
- } else if (is_string($mixedArg)) {
- if ('sql' == $type) {
- if (!$logInfo['type']) $logInfo['type'] = 'sql';
- if (empty($logInfo['msg'])) $logInfo['msg'] = "sql";
- $logInfo['log'] = $mixedArg;
- } else {
- if (empty($logInfo['type'])) $logInfo['type'] = 'string';
- if (empty($msg)) {
- $logInfo['msg'] = $mixedArg;
- $logInfo['log'] = '';
- } else {
- $logInfo['msg'] = $msg;
- $logInfo['log'] = $mixedArg;
- }
- }
- ob_start();
- debug_print_backtrace();
- $logInfo['trace'] = ob_get_clean();
- } else if ('array' == $type || is_array($mixedArg)) {
- $mixedArg = (array)$mixedArg;
- if (!$logInfo['type']) $logInfo['type'] = 'array';
- if (!empty($logInfo['msg']) && !empty($mixedArg['msg'])) $logInfo['msg'] .= ". {$mixedArg['msg']}";
- else if (empty($logInfo['msg']) && !empty($mixedArg['msg'])) $logInfo['msg'] = $mixedArg['msg'];
- if (!empty($mixedArg['msg'])) unset($mixedArg['msg']);
- $logInfo['log'] = $mixedArg;
- ob_start();
- debug_print_backtrace();
- $logInfo['trace'] = ob_get_clean();
- }
- if (!empty($logInfo['trace']) && 'Exception' !== $logInfo['type']) {// remove #0 and #1 (DBG::log and DBG::_log)
- $pos = strpos($logInfo['trace'], "\n#2");
- // if (false !== $pos) $logInfo['trace'] = substr($logInfo['trace'], $pos + 1); // TODO
- }
- $logInfo['trace'] = str_replace(APP_PATH_ROOT, 'SE', $logInfo['trace']);
- $logInfo['trace'] .= (("\n" == substr($logInfo['trace'], -1)) ? '' : "\n") . "#URI: " . V::get('REQUEST_URI', '', $_SERVER);
- if (!$logInfo['type']) $logInfo['type'] = 'unknown';
- if (!empty($logInfo['trace'])) {
- $trace = array_map(function ($part) {
- if ('URI: ' === substr($part, 0, strlen('URI: '))) return "#{$part}";
- if ($pos = strpos($part, '{closure}')) {
- // #10 Route_Storage_AclStruct->{closure}(Array ([namespace] => default_db/BI_audit_ENERGA_PRAC ... )
- return "#" . substr($part, 0, 200) . ( strlen($part) > 200 ? '...' : '' );
- }
- if ($pos = strrpos($part, ' called at [')) {
- $spacePos = strpos($part, ' ');
- $spacePos = (' ' === $part[$spacePos + 1]) ? $spacePos + 1 : $spacePos;
- $spacePos = (' ' === $part[$spacePos + 1]) ? $spacePos + 1 : $spacePos;
- $spacePos += 1;
- $called = substr($part, $pos + strlen(' called at ['), -1);
- $nr = substr($part, 0, $spacePos);
- $line = substr($part, $spacePos, ($pos > 200) ? 200 : $pos - $spacePos);
- if ($pos > 200) $line .= "...";
- $line = str_replace("\n", '\\n', $line);
- return "#{$nr}{$called}: {$line}";
- }
- return "#" . substr($part, 0, 200) . ( strlen($part) > 200 ? '...' : '' );
- }, explode("\n#", $logInfo['trace']));
- array_shift($trace);
- $logInfo['trace'] = implode("\n", $trace);
- }
- error_log(
- json_encode($logInfo) . "\n"
- , 3
- , $logFileName
- );
- }
- public static function simpleLog($type, $msg) {
- static $_idRequest = null;
- $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
- $logFileName = "/tmp/{$prefix}se-log-{$type}.tsv.log";
- if (null === $_idRequest) {
- $_idRequest = substr(md5(date("Y-m-d") . Request::getUserIp() . V::get('REQUEST_TIME', '', $_SERVER)), 0, 6);
- $firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
- self::_simpleLogFile($firstMsg, $_idRequest, $logFileName);
- self::_simpleLogFile("USER IP: " . Request::getUserIp(), $_idRequest, $logFileName);
- }
- self::_simpleLogFile($msg, $_idRequest, $logFileName);
- }
- public static function _simpleLogFile($msg, $idRequest, $logFileName) {
- error_log(implode("\t", [
- date("Y-m-d H:i:s"),
- $idRequest,
- $msg
- ]) . "\n", 3, $logFileName);
- }
- public static function isLogActiveByAdmin() {
- static $_isLogActiveByAdmin = null;
- if (null !== $_isLogActiveByAdmin) return $_isLogActiveByAdmin;
- $_isLogActiveByAdmin = self::_isLogActiveByAdmin();
- return $_isLogActiveByAdmin;
- }
- public static function _isLogActiveByAdmin() {
- if (!User::logged()) return false;
- if (!User::getID()) return false;
- return self::hasUserDebug(User::getID());
- }
- public static function hasUserDebug($idUser, $idAdmin = null) {
- $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
- if (!$idAdmin) {
- $output = (int)@shell_exec("ls -1 /tmp/{$prefix}se-user_debug-{$idUser}-by_admin-*.log 2>/dev/null | wc -l");
- return $output > 0;
- }
- return file_exists("/tmp/{$prefix}se-user_debug-{$idUser}-by_admin-{$idAdmin}.log");
- }
- public static function startUserDebug($idUser, $idAdmin) {
- $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
- @touch("/tmp/{$prefix}se-user_debug-{$idUser}-by_admin-{$idAdmin}.log");
- }
- public static function stopUserDebug($idUser, $idAdmin) {
- $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
- @unlink("/tmp/{$prefix}se-user_debug-{$idUser}-by_admin-{$idAdmin}.log");
- }
- }
|