DBG.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. Lib::loadClass('User');
  3. class DBG {
  4. public static function isActive($mode = null) {
  5. return (isset($_SESSION)) ? (true == V::get('_DBG_ON', false, $_SESSION)) : false;
  6. }
  7. public static function activate($mode = null) {// @used in User::auth()
  8. if (isset($_SESSION)) $_SESSION['_DBG_ON'] = true;
  9. }
  10. public static function deactivate($mode = 'all') {
  11. if (isset($_SESSION)) $_SESSION['_DBG_ON'] = false;
  12. }
  13. /**
  14. * @param $reqKqy - key in $_REQUEST array (if true then always show)
  15. * @param $reqValueExpr - expression to compare req value
  16. * true - always visible - only for fast DBG without $reqKey in REQUEST
  17. * '>*', '>=*', '<*', '<=*' - compare $reqValue
  18. * examples:
  19. * - show when $_REQUEST['DBG_SCH'] == '1'
  20. * DBG::_('DBG_SCH', '1', "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  21. * - show when $_REQUEST['DBG_SCH'] > '1'
  22. * DBG::_('DBG_SCH', '>1', "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  23. * - show when any value: strlen($_REQUEST['DBG_SCH']) > 0
  24. * DBG::_('DBG_SCH', true, "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  25. * - always show
  26. * DBG::_(true, true, "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  27. */
  28. public static function _($reqKey, $reqValueExpr, $label, $variable, $className, $functionName, $lineNumber, $borderColor = 'red') {
  29. if (!DBG::isActive()) return;
  30. $showDBG = false;
  31. $reqValue = (true === $reqKey || !$reqKey)? '' : V::get($reqKey, '', $_GET);
  32. if (true === $reqKey) {
  33. $showDBG = true;
  34. }
  35. else if (strlen($reqValue) == 0) {
  36. return;
  37. }
  38. else if ($reqValue == $reqValueExpr) {
  39. $showDBG = true;
  40. }
  41. else if (true === $reqValueExpr) {
  42. $showDBG = true;
  43. }
  44. else {
  45. if ('>=' == substr($reqValueExpr, 0, 2)) {
  46. if ($reqValue >= substr($reqValueExpr, 2)) {
  47. $showDBG = true;
  48. }
  49. }
  50. else if ('>' == substr($reqValueExpr, 0, 1)) {
  51. if ($reqValue > substr($reqValueExpr, 1)) {
  52. $showDBG = true;
  53. }
  54. }
  55. else if ('<=' == substr($reqValueExpr, 0, 2)) {
  56. if ($reqValue <= substr($reqValueExpr, 2)) {
  57. $showDBG = true;
  58. }
  59. }
  60. else if ('<' == substr($reqValueExpr, 0, 1)) {
  61. if ($reqValue < substr($reqValueExpr, 1)) {
  62. $showDBG = true;
  63. }
  64. }
  65. else {
  66. if ($reqValue = $reqValueExpr) {
  67. $showDBG = true;
  68. }
  69. }
  70. }
  71. if ($showDBG) {
  72. ?>
  73. <pre style="max-height:200px;max-width:800px;overflow:auto;border:1px solid <?php echo $borderColor; ?>;text-align:left;"
  74. ><?php echo "{$label} ({$className}::{$functionName}:{$lineNumber}):\n"; ?>
  75. <?php print_r($variable);?>
  76. </pre>
  77. <?php
  78. }
  79. }
  80. public static function tableInFrame($label, $table, $className, $functionName, $lineNumber) {
  81. ?>
  82. <div class="container" style="margin-top:10px; margin-bottom:10px; background:#ddd">
  83. <h3 style="margin:10px 0"><?php echo "{$label} <small>({$className}::{$functionName}:{$lineNumber}):</small>"; ?></h3>
  84. <div style="max-height:300px;overflow:scroll;border:1px solid #ddd; background:#fff">
  85. <?php self::table($label, $table, $className, $functionName, $lineNumber); ?>
  86. </div>
  87. </div>
  88. <?php
  89. }
  90. public static function table($label, $rows, $className, $functionName, $lineNumber) {
  91. $params = array();
  92. $params['caption'] = "{$label} ({$className}::{$functionName}:{$lineNumber}):";
  93. $params['rows'] = $rows;
  94. UI::table($params);
  95. }
  96. public static function diffTable($label, $table, $params = array(), $className, $functionName, $lineNumber) {
  97. $cols = array();
  98. if (is_array($table) && !empty($table)) {
  99. $firstRow = array();
  100. foreach ($table as $row) {
  101. $firstRow = $row;
  102. break;
  103. }
  104. if (is_array($firstRow)) {
  105. $cols = array_keys($firstRow);
  106. }
  107. else if (is_object($firstRow)) {
  108. $cols = array_keys((array)$firstRow);
  109. }
  110. else {
  111. return;// bad table item type
  112. }
  113. }
  114. $diffPrefix = V::get('diff_prefix', 'diff_', $params);
  115. $diffTblOnePrefix = V::get('diff_tbl_one', '', $params);
  116. $diffTblTwoPrefix = V::get('diff_tbl_two', '', $params);
  117. $diffColsSplit = array();
  118. {
  119. $diffPrefixLen = strlen($diffPrefix);
  120. foreach ($cols as $colName) {
  121. if ($diffPrefix == substr($colName, 0, $diffPrefixLen)) {
  122. $diffColsSplit[substr($colName, $diffPrefixLen)] = array();
  123. }
  124. }
  125. //self::_(true, true, "diffColsSplit.1", $diffColsSplit, __CLASS__, __FUNCTION__, __LINE__);
  126. foreach ($cols as $colName) {
  127. $exp = explode("_", $colName, 2);
  128. if (2 != count($exp)) continue;
  129. if (array_key_exists($exp[1], $diffColsSplit)) {
  130. $prefix = "{$exp[0]}_";
  131. $diffColsSplit[$exp[1]][] = $prefix;
  132. if ($prefix != $diffPrefix) {
  133. if (null == $diffTblOnePrefix) $diffTblOnePrefix = $prefix;
  134. else if (null == $diffTblTwoPrefix) $diffTblTwoPrefix = $prefix;
  135. }
  136. }
  137. }
  138. //elf::_(true, true, "diffColsSplit.2", $diffColsSplit, __CLASS__, __FUNCTION__, __LINE__);
  139. if (null == $diffTblOnePrefix && null == $diffTblTwoPrefix) echo "Error prefix for tables not set!";
  140. $notDiffCols = array();
  141. foreach ($cols as $colName) {
  142. if ("{$diffPrefix}" != substr($colName, 0, $diffPrefixLen)
  143. && "{$diffTblOnePrefix}" != substr($colName, 0, strlen($diffTblOnePrefix))
  144. && "{$diffTblTwoPrefix}" != substr($colName, 0, strlen($diffTblTwoPrefix))
  145. )
  146. $notDiffCols[] = $colName;
  147. }
  148. //self::_(true, true, "notDiffCols", $notDiffCols, __CLASS__, __FUNCTION__, __LINE__);
  149. }
  150. ?>
  151. <table class="table table-bordered table-hover">
  152. <caption><?php echo "{$label} ({$className}::{$functionName}:{$lineNumber}):"; ?></caption>
  153. <thead>
  154. <tr>
  155. <th style="padding:2px;">Lp.</th>
  156. <?php foreach ($notDiffCols as $colName) : ?>
  157. <th style="padding:2px;"><?php echo $colName; ?></th>
  158. <?php endforeach; ?>
  159. <?php foreach ($diffColsSplit as $colName => $prefixes) : ?>
  160. <th style="padding:2px;"><?php echo $colName; ?></th>
  161. <?php endforeach; ?>
  162. </tr>
  163. </thead>
  164. <tbody>
  165. <?php $i = 0; foreach ($table as $row) : $i++; ?>
  166. <tr>
  167. <td style="padding:2px;"><?php echo $i; ?></td>
  168. <?php foreach ($notDiffCols as $colName) : ?>
  169. <td style="padding:2px;"><?php echo V::get($colName, '', $row); ?></td>
  170. <?php endforeach; ?>
  171. <?php foreach ($diffColsSplit as $colName => $prefixes) : ?>
  172. <?php $isDiff = ('1' == V::get("{$diffPrefix}{$colName}", '', $row)); ?>
  173. <?php $stl = ($isDiff)? 'border:2px solid #F2DEDE;color:#a94442;' : 'border:2px solid #DFF0D8;color:#3c763d;'; ?>
  174. <td style="padding:2px;<?php echo $stl; ?>;font-family:monospace;white-space:nowrap;">
  175. <span style="color:#666"><?php echo str_pad($diffTblOnePrefix, 4, ".", STR_PAD_LEFT); ?>: </span>"<?php echo V::get("{$diffTblOnePrefix}{$colName}", '', $row); ?>"
  176. <div style="border-top:1px solid #fff">
  177. <span style="color:#666"><?php echo str_pad($diffTblTwoPrefix, 4, ".", STR_PAD_LEFT); ?>: </span>"<?php echo V::get("{$diffTblTwoPrefix}{$colName}", '', $row); ?>"
  178. </div>
  179. </td>
  180. <?php endforeach; ?>
  181. </tr>
  182. <?php endforeach; ?>
  183. </tbody>
  184. </table>
  185. <?php
  186. }
  187. public static function nicePrint($variable, $varName) {
  188. $col = ['green'=>'#96c178', 'red'=>'#de6b74', 'blue'=>'#55b5c1', 'bg-dark'=>'#282c34', 'white'=>'#abb2bf', 'orange'=>'#d19a66', 'violet'=>'#c476db'];
  189. $cnt = '';
  190. ob_start();
  191. print_r($variable);
  192. $cnt = ob_get_contents();
  193. ob_end_clean();
  194. $outLines = array();
  195. $lines = explode("\n", $cnt);
  196. foreach ($lines as $line) {
  197. if ('(' == trim($line)) continue;
  198. if (')' == trim($line)) continue;
  199. if ('' == trim($line)) continue;
  200. if ('Array' == substr($line, -5) || 'stdClass' == substr($line, -5)) {
  201. $line = str_replace('Array', '<span style="color:'.$col['blue'].'">Array</span>', $line);
  202. $line = str_replace('stdClass', '<span style="color:'.$col['blue'].'">stdClass</span>', $line);
  203. $line .= ':';
  204. }
  205. if (($firstBracket = strpos($line, '[')) > 0) {
  206. $line = str_replace("\t", ' ', $line);
  207. $splitPos = ($firstBracket > 4)? ($firstBracket - 4) / 2 + 4 : 4;
  208. $line = substr($line, $firstBracket - $splitPos);
  209. $line = preg_replace('/\[(\w+)\]/', '[<span style="color:'.$col['green'].'">\1</span>]', $line);
  210. $line = preg_replace('/\] \=\> (.+)$/', '] => <span style="color:'.$col['orange'].'">\1</span>', $line);
  211. }
  212. $outLines[] = $line;
  213. }
  214. if ($varName) $outLines[0] = '<b style="color:'.$col['red'].'">' . $varName . "</b> => {$outLines[0]}";
  215. $outLines = implode("\n", $outLines);
  216. echo '<pre style="background-color:'.$col['bg-dark'].'; color:'.$col['white'].'; font-size:x-small">' . $outLines . '</pre>' . "\n";
  217. }
  218. /**
  219. * @param $mixedArg string or Exception
  220. */
  221. public static function log($mixedArg, $type = '', $msg = '') {
  222. if (!self::isActive()) return;
  223. if ('Debug' == V::get('_route', '', $_REQUEST) && !V::get('DBG', '', $_REQUEST)) return;
  224. static $_firstRun = true;
  225. if ($_firstRun) {
  226. $_firstRun = false;
  227. self::_log([
  228. 'msg' => V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER),
  229. 'POST' => $_POST,
  230. 'GET' => $_GET,
  231. ]);
  232. }
  233. self::_log($mixedArg, $type, $msg);
  234. }
  235. public static function _log($mixedArg, $type = '', $msg = '') {
  236. // * TODO: debug to file based on session_id (/tmp/se-debug-{$date("Y-m-d")}-{$login}_{$ip}_{$session_id}.log)
  237. $logInfo = [
  238. 'date' => date("Y-m-d H:i:s"),
  239. 'type' => $type,
  240. 'msg' => $msg,
  241. 'log' => '',
  242. 'trace' => '',
  243. ];
  244. if ($mixedArg instanceof Exception) {
  245. $logInfo['type'] = 'Exception';
  246. if (!empty($logInfo['msg'])) $logInfo['msg'] .= ". ";
  247. $logInfo['msg'] .= $mixedArg->getMessage();
  248. $logInfo['log'] = [
  249. 'code' => $mixedArg->getCode(),
  250. 'line' => $mixedArg->getLine(),
  251. 'file' => str_replace(APP_PATH_ROOT, 'SE', $mixedArg->getFile()),
  252. ];
  253. $logInfo['trace'] = $mixedArg->getTraceAsString();// getTrace
  254. } else if (is_string($mixedArg)) {
  255. if ('sql' == $type) {
  256. if (!$logInfo['type']) $logInfo['type'] = 'sql';
  257. if (empty($logInfo['msg'])) $logInfo['msg'] = "sql";
  258. $logInfo['log'] = $mixedArg;
  259. } else {
  260. if (empty($logInfo['type'])) $logInfo['type'] = 'string';
  261. $logInfo['msg'] = $mixedArg;
  262. $logInfo['log'] = '';
  263. }
  264. ob_start();
  265. debug_print_backtrace();
  266. $logInfo['trace'] = ob_get_clean();
  267. } else if ('array' == $type || is_array($mixedArg)) {
  268. $mixedArg = (array)$mixedArg;
  269. if (!$logInfo['type']) $logInfo['type'] = 'array';
  270. if (!empty($logInfo['msg']) && !empty($mixedArg['msg'])) $logInfo['msg'] .= ". {$mixedArg['msg']}";
  271. else if (empty($logInfo['msg']) && !empty($mixedArg['msg'])) $logInfo['msg'] = $mixedArg['msg'];
  272. if (!empty($mixedArg['msg'])) unset($mixedArg['msg']);
  273. $logInfo['log'] = $mixedArg;
  274. ob_start();
  275. debug_print_backtrace();
  276. $logInfo['trace'] = ob_get_clean();
  277. }
  278. $logInfo['trace'] = str_replace(APP_PATH_ROOT, 'SE', $logInfo['trace']);
  279. $logInfo['trace'] .= (("\n" == substr($logInfo['trace'], -1)) ? '' : "\n") . "URI: " . V::get('REQUEST_URI', '', $_SERVER);
  280. if (!$logInfo['type']) $logInfo['type'] = 'unknown';
  281. error_log(
  282. json_encode($logInfo) . "\n"
  283. , 3
  284. , '/tmp/se-debug-' . implode('-', [
  285. date("Y-m-d"),
  286. User::getLogin(),
  287. Request::getUserIp(),
  288. substr(session_id(), 0, 6),
  289. V::get('REQUEST_TIME', '', $_SERVER)// [REQUEST_TIME] => 1485770466
  290. ]) . '.log'
  291. );
  292. }
  293. }