DBG.php 16 KB

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