DBG.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php
  2. Lib::loadClass('User');
  3. Lib::loadClass('UI');
  4. Lib::loadClass('Request');
  5. class DBG {
  6. public static function isActive($mode = null) {
  7. return (isset($_SESSION)) ? (true == V::get('_DBG_ON', false, $_SESSION)) : false;
  8. }
  9. public static function activate($mode = null) {// @used in User::auth()
  10. if (isset($_SESSION)) $_SESSION['_DBG_ON'] = true;
  11. }
  12. public static function deactivate($mode = 'all') {
  13. if (isset($_SESSION)) $_SESSION['_DBG_ON'] = false;
  14. }
  15. /**
  16. * @param $reqKqy - key in $_REQUEST array (if true then always show)
  17. * @param $reqValueExpr - expression to compare req value
  18. * true - always visible - only for fast DBG without $reqKey in REQUEST
  19. * '>*', '>=*', '<*', '<=*' - compare $reqValue
  20. * examples:
  21. * - show when $_REQUEST['DBG_SCH'] == '1'
  22. * DBG::_('DBG_SCH', '1', "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  23. * - show when $_REQUEST['DBG_SCH'] > '1'
  24. * DBG::_('DBG_SCH', '>1', "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  25. * - show when any value: strlen($_REQUEST['DBG_SCH']) > 0
  26. * DBG::_('DBG_SCH', true, "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  27. * - always show
  28. * DBG::_(true, true, "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  29. */
  30. public static function _($reqKey, $reqValueExpr, $label, $variable, $className, $functionName, $lineNumber, $borderColor = 'red') {
  31. if (!DBG::isActive()) return;
  32. $showDBG = false;
  33. $reqValue = (true === $reqKey || !$reqKey)? '' : V::get($reqKey, '', $_GET);
  34. if (true === $reqKey) {
  35. $showDBG = true;
  36. }
  37. else if (strlen($reqValue) == 0) {
  38. return;
  39. }
  40. else if ($reqValue == $reqValueExpr) {
  41. $showDBG = true;
  42. }
  43. else if (true === $reqValueExpr) {
  44. $showDBG = true;
  45. }
  46. else {
  47. if ('>=' == substr($reqValueExpr, 0, 2)) {
  48. if ($reqValue >= substr($reqValueExpr, 2)) {
  49. $showDBG = true;
  50. }
  51. }
  52. else if ('>' == substr($reqValueExpr, 0, 1)) {
  53. if ($reqValue > substr($reqValueExpr, 1)) {
  54. $showDBG = true;
  55. }
  56. }
  57. else if ('<=' == substr($reqValueExpr, 0, 2)) {
  58. if ($reqValue <= substr($reqValueExpr, 2)) {
  59. $showDBG = true;
  60. }
  61. }
  62. else if ('<' == substr($reqValueExpr, 0, 1)) {
  63. if ($reqValue < substr($reqValueExpr, 1)) {
  64. $showDBG = true;
  65. }
  66. }
  67. else {
  68. if ($reqValue = $reqValueExpr) {
  69. $showDBG = true;
  70. }
  71. }
  72. }
  73. if ($showDBG) {
  74. ?>
  75. <pre style="max-height:200px;max-width:800px;overflow:auto;border:1px solid <?php echo $borderColor; ?>;text-align:left;"
  76. ><?php echo "{$label} ({$className}::{$functionName}:{$lineNumber}):\n"; ?>
  77. <?php print_r($variable);?>
  78. </pre>
  79. <?php
  80. }
  81. }
  82. public static function tableInFrame($label, $table, $className, $functionName, $lineNumber) {
  83. ?>
  84. <div class="container" style="margin-top:10px; margin-bottom:10px; background:#ddd">
  85. <h3 style="margin:10px 0"><?php echo "{$label} <small>({$className}::{$functionName}:{$lineNumber}):</small>"; ?></h3>
  86. <div style="max-height:300px;overflow:scroll;border:1px solid #ddd; background:#fff">
  87. <?php self::table($label, $table, $className, $functionName, $lineNumber); ?>
  88. </div>
  89. </div>
  90. <?php
  91. }
  92. public static function table($label, $rows, $className, $functionName, $lineNumber) {
  93. $params = array();
  94. $params['caption'] = "{$label} ({$className}::{$functionName}:{$lineNumber}):";
  95. $params['rows'] = $rows;
  96. UI::table($params);
  97. }
  98. public static function diffTable($label, $table, $params = array(), $className, $functionName, $lineNumber) {
  99. $cols = array();
  100. if (is_array($table) && !empty($table)) {
  101. $firstRow = array();
  102. foreach ($table as $row) {
  103. $firstRow = $row;
  104. break;
  105. }
  106. if (is_array($firstRow)) {
  107. $cols = array_keys($firstRow);
  108. }
  109. else if (is_object($firstRow)) {
  110. $cols = array_keys((array)$firstRow);
  111. }
  112. else {
  113. return;// bad table item type
  114. }
  115. }
  116. $diffPrefix = V::get('diff_prefix', 'diff_', $params);
  117. $diffTblOnePrefix = V::get('diff_tbl_one', '', $params);
  118. $diffTblTwoPrefix = V::get('diff_tbl_two', '', $params);
  119. $diffColsSplit = array();
  120. {
  121. $diffPrefixLen = strlen($diffPrefix);
  122. foreach ($cols as $colName) {
  123. if ($diffPrefix == substr($colName, 0, $diffPrefixLen)) {
  124. $diffColsSplit[substr($colName, $diffPrefixLen)] = array();
  125. }
  126. }
  127. //self::_(true, true, "diffColsSplit.1", $diffColsSplit, __CLASS__, __FUNCTION__, __LINE__);
  128. foreach ($cols as $colName) {
  129. $exp = explode("_", $colName, 2);
  130. if (2 != count($exp)) continue;
  131. if (array_key_exists($exp[1], $diffColsSplit)) {
  132. $prefix = "{$exp[0]}_";
  133. $diffColsSplit[$exp[1]][] = $prefix;
  134. if ($prefix != $diffPrefix) {
  135. if (null == $diffTblOnePrefix) $diffTblOnePrefix = $prefix;
  136. else if (null == $diffTblTwoPrefix) $diffTblTwoPrefix = $prefix;
  137. }
  138. }
  139. }
  140. //elf::_(true, true, "diffColsSplit.2", $diffColsSplit, __CLASS__, __FUNCTION__, __LINE__);
  141. if (null == $diffTblOnePrefix && null == $diffTblTwoPrefix) echo "Error prefix for tables not set!";
  142. $notDiffCols = array();
  143. foreach ($cols as $colName) {
  144. if ("{$diffPrefix}" != substr($colName, 0, $diffPrefixLen)
  145. && "{$diffTblOnePrefix}" != substr($colName, 0, strlen($diffTblOnePrefix))
  146. && "{$diffTblTwoPrefix}" != substr($colName, 0, strlen($diffTblTwoPrefix))
  147. )
  148. $notDiffCols[] = $colName;
  149. }
  150. //self::_(true, true, "notDiffCols", $notDiffCols, __CLASS__, __FUNCTION__, __LINE__);
  151. }
  152. ?>
  153. <table class="table table-bordered table-hover">
  154. <caption><?php echo "{$label} ({$className}::{$functionName}:{$lineNumber}):"; ?></caption>
  155. <thead>
  156. <tr>
  157. <th style="padding:2px;">Lp.</th>
  158. <?php foreach ($notDiffCols as $colName) : ?>
  159. <th style="padding:2px;"><?php echo $colName; ?></th>
  160. <?php endforeach; ?>
  161. <?php foreach ($diffColsSplit as $colName => $prefixes) : ?>
  162. <th style="padding:2px;"><?php echo $colName; ?></th>
  163. <?php endforeach; ?>
  164. </tr>
  165. </thead>
  166. <tbody>
  167. <?php $i = 0; foreach ($table as $row) : $i++; ?>
  168. <tr>
  169. <td style="padding:2px;"><?php echo $i; ?></td>
  170. <?php foreach ($notDiffCols as $colName) : ?>
  171. <td style="padding:2px;"><?php echo V::get($colName, '', $row); ?></td>
  172. <?php endforeach; ?>
  173. <?php foreach ($diffColsSplit as $colName => $prefixes) : ?>
  174. <?php $isDiff = ('1' == V::get("{$diffPrefix}{$colName}", '', $row)); ?>
  175. <?php $stl = ($isDiff)? 'border:2px solid #F2DEDE;color:#a94442;' : 'border:2px solid #DFF0D8;color:#3c763d;'; ?>
  176. <td style="padding:2px;<?php echo $stl; ?>;font-family:monospace;white-space:nowrap;">
  177. <span style="color:#666"><?php echo str_pad($diffTblOnePrefix, 4, ".", STR_PAD_LEFT); ?>: </span>"<?php echo V::get("{$diffTblOnePrefix}{$colName}", '', $row); ?>"
  178. <div style="border-top:1px solid #fff">
  179. <span style="color:#666"><?php echo str_pad($diffTblTwoPrefix, 4, ".", STR_PAD_LEFT); ?>: </span>"<?php echo V::get("{$diffTblTwoPrefix}{$colName}", '', $row); ?>"
  180. </div>
  181. </td>
  182. <?php endforeach; ?>
  183. </tr>
  184. <?php endforeach; ?>
  185. </tbody>
  186. </table>
  187. <?php
  188. }
  189. public static function nicePrint($variable, $varName, $params = []) {
  190. $col = ['green'=>'#96c178', 'red'=>'#de6b74', 'blue'=>'#55b5c1', 'bg-dark'=>'#282c34', 'white'=>'#abb2bf', 'orange'=>'#d19a66', 'violet'=>'#c476db'];
  191. $cnt = '';
  192. ob_start();
  193. print_r($variable);
  194. $cnt = ob_get_clean();
  195. $outLines = array();
  196. $lines = explode("\n", $cnt);
  197. foreach ($lines as $line) {
  198. if ('(' == trim($line)) continue;
  199. if (')' == trim($line)) continue;
  200. if ('' == trim($line)) continue;
  201. if ('Array' == substr($line, -5) || 'stdClass' == substr($line, -5)) {
  202. $line = str_replace('Array', '<span style="color:'.$col['blue'].'">Array</span>', $line);
  203. $line = str_replace('stdClass', '<span style="color:'.$col['blue'].'">stdClass</span>', $line);
  204. $line .= ':';
  205. }
  206. if (($firstBracket = strpos($line, '[')) > 0) {
  207. $line = str_replace("\t", ' ', $line);
  208. $splitPos = ($firstBracket > 4)? ($firstBracket - 4) / 2 + 4 : 4;
  209. $line = substr($line, $firstBracket - $splitPos);
  210. $line = preg_replace('/\[(\w+)\]/', '[<span style="color:'.$col['green'].'">\1</span>]', $line);
  211. $line = preg_replace('/\] \=\> (.+)$/', '] => <span style="color:'.$col['orange'].'">\1</span>', $line);
  212. }
  213. $outLines[] = $line;
  214. }
  215. if ($varName) $outLines[0] = '<b style="color:'.$col['red'].'">' . $varName . "</b> => {$outLines[0]}";
  216. $maxHeight = V::get('maxHeight', '400px', $params);
  217. echo UI::h('details', ['style'=>"max-width:800px"], [
  218. 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)),
  219. UI::h('pre', [
  220. 'style' => implode(";", [
  221. 'background-color:'.$col['bg-dark'],
  222. 'color:'.$col['white'],
  223. 'border:1px solid #ccc;border-radius:0',
  224. 'font-size:x-small',
  225. ($maxHeight) ? "max-height:{$maxHeight};overflow:scroll" : ''
  226. ])
  227. ], implode("\n", $outLines))
  228. ]) . "\n";
  229. }
  230. /**
  231. * @param $mixedArg string or Exception
  232. */
  233. public static function log($mixedArg, $type = '', $msg = '') {
  234. if (!self::isActive() && !self::isLogActiveByAdmin()) return;
  235. if ('Debug' == V::get('_route', '', $_REQUEST) && !V::get('DBG', '', $_REQUEST)) return;
  236. static $_firstRun = true;
  237. $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
  238. $logFileName = "/tmp/{$prefix}se-debug-" . implode('-', [
  239. date("Y-m-d"),
  240. User::getLogin(),
  241. Request::getUserIp(),
  242. substr(session_id(), 0, 6),
  243. V::get('REQUEST_TIME', '', $_SERVER)// [REQUEST_TIME] => 1485770466
  244. ]) . '.log';
  245. if ($_firstRun) {
  246. $_firstRun = false;
  247. $firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
  248. self::_log([ 'POST' => $_POST, 'GET' => $_GET, 'POST_BODY' => Request::getRequestBody() ], 'array', $firstMsg, $logFileName);
  249. }
  250. self::_log($mixedArg, $type, $msg, $logFileName);
  251. }
  252. public static function logAuth($mixedArg, $msg = '') {
  253. if ('Debug' == V::get('_route', '', $_REQUEST) && !V::get('DBG', '', $_REQUEST)) return;
  254. static $_firstRun = true;
  255. $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
  256. $logFileName = "/tmp/{$prefix}se-auth-" . implode('-', [
  257. date("Y-m-d"),
  258. Request::getUserIp(),
  259. V::get('REQUEST_TIME', '', $_SERVER)// [REQUEST_TIME] => 1485770466
  260. ]) . '.log';
  261. if ($_firstRun) {
  262. $_firstRun = false;
  263. $firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
  264. self::_log(['POST' => $_POST, 'GET' => $_GET], 'array', $firstMsg, $logFileName);
  265. }
  266. self::_log($mixedArg, $type = 'array', $msg, $logFileName);
  267. }
  268. public static function _log($mixedArg, $type, $msg, $logFileName) {
  269. $logInfo = [
  270. 'date' => date("Y-m-d H:i:s") . substr((string)microtime(), 1, 6),
  271. 'type' => $type,
  272. 'msg' => $msg,
  273. 'log' => '',
  274. 'trace' => '',
  275. ];
  276. if ($mixedArg instanceof Exception) {
  277. $logInfo['type'] = 'Exception';
  278. if (!empty($logInfo['msg'])) $logInfo['msg'] .= ". ";
  279. $logInfo['msg'] .= $mixedArg->getMessage();
  280. $logInfo['log'] = [
  281. 'code' => $mixedArg->getCode(),
  282. 'line' => $mixedArg->getLine(),
  283. 'file' => str_replace(APP_PATH_ROOT, 'SE', $mixedArg->getFile()),
  284. ];
  285. $logInfo['trace'] = $mixedArg->getTraceAsString();// getTrace
  286. } else if (is_string($mixedArg)) {
  287. if ('sql' == $type) {
  288. if (!$logInfo['type']) $logInfo['type'] = 'sql';
  289. if (empty($logInfo['msg'])) $logInfo['msg'] = "sql";
  290. $logInfo['log'] = $mixedArg;
  291. } else {
  292. if (empty($logInfo['type'])) $logInfo['type'] = 'string';
  293. if (empty($msg)) {
  294. $logInfo['msg'] = $mixedArg;
  295. $logInfo['log'] = '';
  296. } else {
  297. $logInfo['msg'] = $msg;
  298. $logInfo['log'] = $mixedArg;
  299. }
  300. }
  301. ob_start();
  302. debug_print_backtrace();
  303. $logInfo['trace'] = ob_get_clean();
  304. } else if ('array' == $type || is_array($mixedArg)) {
  305. $mixedArg = (array)$mixedArg;
  306. if (!$logInfo['type']) $logInfo['type'] = 'array';
  307. if (!empty($logInfo['msg']) && !empty($mixedArg['msg'])) $logInfo['msg'] .= ". {$mixedArg['msg']}";
  308. else if (empty($logInfo['msg']) && !empty($mixedArg['msg'])) $logInfo['msg'] = $mixedArg['msg'];
  309. if (!empty($mixedArg['msg'])) unset($mixedArg['msg']);
  310. $logInfo['log'] = $mixedArg;
  311. ob_start();
  312. debug_print_backtrace();
  313. $logInfo['trace'] = ob_get_clean();
  314. }
  315. if (!empty($logInfo['trace']) && 'Exception' !== $logInfo['type']) {// remove #0 and #1 (DBG::log and DBG::_log)
  316. $pos = strpos($logInfo['trace'], "\n#2");
  317. // if (false !== $pos) $logInfo['trace'] = substr($logInfo['trace'], $pos + 1); // TODO
  318. }
  319. $logInfo['trace'] = str_replace(APP_PATH_ROOT, 'SE', $logInfo['trace']);
  320. $logInfo['trace'] .= (("\n" == substr($logInfo['trace'], -1)) ? '' : "\n") . "#URI: " . V::get('REQUEST_URI', '', $_SERVER);
  321. if (!$logInfo['type']) $logInfo['type'] = 'unknown';
  322. if (!empty($logInfo['trace'])) {
  323. $trace = array_map(function ($part) {
  324. if ('URI: ' === substr($part, 0, strlen('URI: '))) return "#{$part}";
  325. if ($pos = strpos($part, '{closure}')) {
  326. // #10 Route_Storage_AclStruct->{closure}(Array ([namespace] => default_db/BI_audit_ENERGA_PRAC ... )
  327. return "#" . substr($part, 0, 200) . ( strlen($part) > 200 ? '...' : '' );
  328. }
  329. if ($pos = strrpos($part, ' called at [')) {
  330. $spacePos = strpos($part, ' ');
  331. $spacePos = (' ' === $part[$spacePos + 1]) ? $spacePos + 1 : $spacePos;
  332. $spacePos = (' ' === $part[$spacePos + 1]) ? $spacePos + 1 : $spacePos;
  333. $spacePos += 1;
  334. $called = substr($part, $pos + strlen(' called at ['), -1);
  335. $nr = substr($part, 0, $spacePos);
  336. $line = substr($part, $spacePos, ($pos > 200) ? 200 : $pos - $spacePos);
  337. if ($pos > 200) $line .= "...";
  338. $line = str_replace("\n", '\\n', $line);
  339. return "#{$nr}{$called}: {$line}";
  340. }
  341. return "#" . substr($part, 0, 200) . ( strlen($part) > 200 ? '...' : '' );
  342. }, explode("\n#", $logInfo['trace']));
  343. array_shift($trace);
  344. $logInfo['trace'] = implode("\n", $trace);
  345. }
  346. error_log(
  347. json_encode($logInfo) . "\n"
  348. , 3
  349. , $logFileName
  350. );
  351. }
  352. public static function simpleLog($type, $msg) {
  353. static $_idRequest = null;
  354. $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
  355. $logFileName = "/tmp/{$prefix}se-log-{$type}.tsv.log";
  356. if (null === $_idRequest) {
  357. $_idRequest = substr(md5(date("Y-m-d") . Request::getUserIp() . V::get('REQUEST_TIME', '', $_SERVER)), 0, 6);
  358. $firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
  359. self::_simpleLogFile($firstMsg, $_idRequest, $logFileName);
  360. self::_simpleLogFile("USER IP: " . Request::getUserIp(), $_idRequest, $logFileName);
  361. }
  362. self::_simpleLogFile($msg, $_idRequest, $logFileName);
  363. }
  364. public static function _simpleLogFile($msg, $idRequest, $logFileName) {
  365. error_log(implode("\t", [
  366. date("Y-m-d H:i:s"),
  367. $idRequest,
  368. $msg
  369. ]) . "\n", 3, $logFileName);
  370. }
  371. public static function isLogActiveByAdmin() {
  372. static $_isLogActiveByAdmin = null;
  373. if (null !== $_isLogActiveByAdmin) return $_isLogActiveByAdmin;
  374. $_isLogActiveByAdmin = self::_isLogActiveByAdmin();
  375. return $_isLogActiveByAdmin;
  376. }
  377. public static function _isLogActiveByAdmin() {
  378. if (!User::logged()) return false;
  379. if (!User::getID()) return false;
  380. return self::hasUserDebug(User::getID());
  381. }
  382. public static function hasUserDebug($idUser, $idAdmin = null) {
  383. $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
  384. if (!$idAdmin) {
  385. $output = (int)@shell_exec("ls -1 /tmp/{$prefix}se-user_debug-{$idUser}-by_admin-*.log 2>/dev/null | wc -l");
  386. return $output > 0;
  387. }
  388. return file_exists("/tmp/{$prefix}se-user_debug-{$idUser}-by_admin-{$idAdmin}.log");
  389. }
  390. public static function startUserDebug($idUser, $idAdmin) {
  391. $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
  392. @touch("/tmp/{$prefix}se-user_debug-{$idUser}-by_admin-{$idAdmin}.log");
  393. }
  394. public static function stopUserDebug($idUser, $idAdmin) {
  395. $prefix = ('production' == V::get('P5_ENV', 'production', $_SERVER)) ? "" : "dev-";
  396. @unlink("/tmp/{$prefix}se-user_debug-{$idUser}-by_admin-{$idAdmin}.log");
  397. }
  398. }