Debug.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. /**
  4. * TODO: debug to file based on session_id (/tmp/se-debug-{$date("Y-m-d")}-{$login}_{$ip}_{$session_id}.log)
  5. * TODO: function if loggind enabled, then save to file and print in default page
  6. * - DBG::log(string $msg or Exception $e)
  7. * TODO: better wfs log by fingerprint (User::getLogin() + IP + UserAgent)
  8. */
  9. class Route_Debug extends RouteBase {
  10. public $logPathPrefix = '/tmp/se-todo-';
  11. public function __construct() {
  12. $this->logPathPrefix = '/tmp/' . ('production' == V::get('P5_ENV', 'production', $_SERVER) ? "" : "dev-");
  13. }
  14. public function handleAuth() {
  15. if (!User::logged()) {
  16. throw new HttpException('Unauthorized', 401);
  17. }
  18. if (!User::hasAccess('dbg')) {// User::get('ADM_ADMIN_LEVEL') == 0
  19. throw new HttpException('Unauthorized - required dbg access', 401);
  20. }
  21. }
  22. public function defaultAction() {
  23. session_write_close();
  24. $this->defaultView();
  25. }
  26. public function defaultView($flashMsg = '') {
  27. UI::gora();
  28. UI::menu();
  29. UI::setTitle("Debug");
  30. if (!empty($_POST)) echo UI::h('script', [], "history.replaceState(null, 'Debug', window.location.href);");
  31. try {
  32. echo UI::h('div', ['class'=>"breadcrumb"], [
  33. "Debug ",
  34. UI::h('strong', [], "(" . (DBG::isActive() ? "włączony" : "wyłączony") . ") "),
  35. UI::h('a', [
  36. 'href' => $this->getLink(),
  37. 'class' => "btn btn-xs btn-default"
  38. ], "Odśwież"),
  39. " ",
  40. UI::hButtonPost((DBG::isActive()) ? "Wyłącz debug" : "Włącz debug", [
  41. 'class' => "btn-success btn-xs",
  42. 'data' => [
  43. '_route' => 'Debug',
  44. '_task' => DBG::isActive() ? 'deactivateDebug' : 'activateDebug'
  45. ]
  46. ]),
  47. " ",
  48. UI::h('a', [
  49. 'href' => $this->getLink('auth'),
  50. 'class' => "btn btn-xs btn-link"
  51. ], "auth log"),
  52. $this->adminWidgetDebugUserLink(),
  53. ]);
  54. echo $flashMsg;
  55. // DBG::nicePrint($_SERVER, '$_SERVER');
  56. // DBG::nicePrint([
  57. // 'date' => date("Y-m-d"),
  58. // 'login' => User::getLogin(),
  59. // 'ip' => Request::getUserIp(),
  60. // 'session_id' => session_id()
  61. // ], 'dbg');
  62. UI::table([
  63. 'caption' => "Log Files " . UI::h('a', [
  64. 'href' => $this->getLink("viewLatestUserLog"),
  65. 'class' => "btn btn-xs btn-primary"
  66. ], "Pokaż ostatni log") . " " . UI::hButtonPost("Usuń wszystkie swoje pliki", [
  67. 'class' => "btn-danger btn-xs",
  68. 'data' => [
  69. '_route' => 'Debug',
  70. '_task' => 'rmAllUserLogFiles'
  71. ]
  72. ]) . " " . UI::hButtonPost("Usuń stare pliki", [
  73. 'class' => "btn-warning btn-xs",
  74. 'data' => [
  75. '_route' => 'Debug',
  76. '_task' => 'rmOldUserLogFiles'
  77. ]
  78. ]),
  79. 'cols' => [
  80. '#',
  81. 'file',
  82. 'user',
  83. 'request date',
  84. 'ip',
  85. 'rm',
  86. ],
  87. 'rows' => array_map(
  88. function ($logFile) {
  89. // /tmp/se-debug-2017-01-25-plabudda-192.168.61.206-4qqrd0.log
  90. try {
  91. if ("{$this->logPathPrefix}se-debug-" != substr($logFile, 0, strlen("{$this->logPathPrefix}se-debug-"))) throw new Exception("Wrong log file name '{$logFile}'");
  92. if ('.log' != substr($logFile, -4)) throw new Exception("Wrong log file name extension '{$logFile}'");
  93. $logName = substr($logFile, strlen("{$this->logPathPrefix}se-debug-"), -4);
  94. list($logYear, $logMonth, $logDay, $logUser, $logIP, $logSessId, $logReqDate) = explode('-', $logName);
  95. return [
  96. '#' => UI::h('a', [
  97. 'href' => $this->getLink("viewLog", ['name' => $logName])
  98. ], "Pokaż"),
  99. 'request date' => ($logReqDate) ? date("Y-m-d H:i:s", $logReqDate) : '',// 1485775975
  100. 'file' => $logFile,
  101. 'user' => $logUser,
  102. 'ip' => $logIP,
  103. 'rm' => UI::hButtonPost("Usuń", [
  104. 'class' => 'btn-default btn-xs',
  105. 'data' => [
  106. '_route' => 'Debug',
  107. '_task' => 'rmLogFile',
  108. 'logName' => $logName
  109. ]
  110. ]),
  111. ];
  112. } catch (Exception $e) {
  113. return [
  114. '#' => '',
  115. 'file' => $e->getMessage(),
  116. ];
  117. }
  118. }
  119. , glob("{$this->logPathPrefix}se-debug-*.log", GLOB_NOSORT)
  120. )
  121. ]);
  122. echo UI::hButtonPost("Test dbg with sleep", [
  123. 'class' => "btn-warning btn-xs",
  124. 'data' => [
  125. '_route' => 'Debug',
  126. '_task' => 'testDebugWithSleep'
  127. ]
  128. ]);
  129. } catch (Exception $e) {
  130. UI::alert('danger', $e->getMessage());
  131. DBG::log($e);
  132. }
  133. UI::dol();
  134. }
  135. public function adminWidgetDebugUserLink() {
  136. if (0 != User::get('ADM_ADMIN_LEVEL')) return '';
  137. return UI::h('a', [
  138. 'href' => $this->getLink('adminUserDebug'),
  139. 'class' => "btn btn-xs btn-link"
  140. ], "debug another user");
  141. }
  142. public function adminUserDebugAction() {
  143. UI::gora();
  144. UI::menu();
  145. UI::startContainer();
  146. try {
  147. // $idUser = V::get('idUser', 0, $_GET, 'int'); // TODO: add link for this user debug? use main debug files list and viewLatestUserLog
  148. // if ($idUser > 0) {
  149. // } else {
  150. Router::getRoute('Status')->viewStatusUsers();
  151. // }
  152. } catch (Exception $e) {
  153. UI::alert('danger', $e->getMessage());
  154. DBG::log($e);
  155. }
  156. UI::endContainer();
  157. UI::dol();
  158. }
  159. public function authAction() {
  160. session_write_close();
  161. $this->authView();
  162. }
  163. public function authView($flashMsg = '') {
  164. UI::gora();
  165. UI::menu();
  166. UI::setTitle("Debug");
  167. if (!empty($_POST)) echo UI::h('script', [], "history.replaceState(null, 'Debug', window.location.href);");
  168. try {
  169. echo UI::h('div', ['class'=>"breadcrumb"], [
  170. UI::h('a', [
  171. 'href' => $this->getLink(),
  172. 'class' => "btn btn-link"
  173. ], "Debug"),
  174. " / ",
  175. UI::h('a', [
  176. 'href' => $this->getLink('auth'),
  177. 'class' => "btn btn-link"
  178. ], "Auth (Odśwież)"),
  179. ]);
  180. echo $flashMsg;
  181. UI::table([
  182. 'caption' => "Log Files " . UI::h('a', [
  183. 'href' => $this->getLink("viewLatestAuthLog"),
  184. 'class' => "btn btn-xs btn-primary"
  185. ], "Pokaż ostatni log") . " " . UI::hButtonPost("Usuń wszystkie pliki", [
  186. 'class' => "btn-danger btn-xs",
  187. 'data' => [
  188. '_route' => 'Debug',
  189. '_task' => 'rmAllAuthLogFiles'
  190. ]
  191. ]) . " " . UI::hButtonPost("Usuń stare pliki", [
  192. 'class' => "btn-warning btn-xs",
  193. 'data' => [
  194. '_route' => 'Debug',
  195. '_task' => 'rmOldAuthLogFiles'
  196. ]
  197. ]),
  198. 'cols' => [
  199. '#',
  200. 'file',
  201. 'user',
  202. 'request date',
  203. 'ip',
  204. 'rm',
  205. ],
  206. 'rows' => array_map(
  207. function ($logFile) {
  208. // /tmp/se-debug-2017-01-25-plabudda-192.168.61.206-4qqrd0.log
  209. try {
  210. if ("{$this->logPathPrefix}se-auth-" != substr($logFile, 0, strlen("{$this->logPathPrefix}se-auth-"))) throw new Exception("Wrong log file name '{$logFile}'");
  211. if ('.log' != substr($logFile, -4)) throw new Exception("Wrong log file name extension '{$logFile}'");
  212. $logName = substr($logFile, strlen("{$this->logPathPrefix}se-auth-"), -4);
  213. list($logYear, $logMonth, $logDay, $logIP, $logReqDate) = explode('-', $logName);
  214. return [
  215. '#' => UI::h('a', [
  216. 'href' => $this->getLink('viewAuthLog', ['name'=>$logName])
  217. ], "Pokaż"),
  218. 'request date' => ($logReqDate) ? date("Y-m-d H:i:s", $logReqDate) : '',// 1485775975
  219. 'file' => $logFile,
  220. 'user' => $logUser,
  221. 'ip' => $logIP,
  222. 'rm' => UI::hButtonPost("Usuń", [
  223. 'class' => 'btn-default btn-xs',
  224. 'data' => [
  225. '_route' => 'Debug',
  226. '_task' => 'rmAuthLogFile',
  227. 'logName' => $logName
  228. ]
  229. ]),
  230. ];
  231. } catch (Exception $e) {
  232. return [
  233. '#' => '',
  234. 'file' => $e->getMessage(),
  235. ];
  236. }
  237. }
  238. , glob("{$this->logPathPrefix}se-auth-*.log", GLOB_NOSORT)
  239. )
  240. ]);
  241. } catch (Exception $e) {
  242. UI::alert('danger', $e->getMessage());
  243. DBG::log($e);
  244. }
  245. UI::dol();
  246. }
  247. public function viewLatestUserLogAction() {
  248. session_write_close();
  249. UI::gora();
  250. // UI::menu();
  251. UI::setTitle("Debug");
  252. try {
  253. $filerUser = V::get('user', '', $_REQUEST);// TODO: show another user debug
  254. $logName = V::get('name', '', $_REQUEST);
  255. $uiWarning = null;
  256. $uiLogFiles = null;
  257. if (!$logName) {
  258. $today = date("Y-m-d");
  259. $cmd = "ls -1rt {$this->logPathPrefix}se-debug-{$today}-*.log | tail -5";
  260. V::exec($cmd, $out, $ret);
  261. if (empty($out)) {
  262. $uiWarning = "No logs today. Searching previous...";
  263. $cmd = "ls -1rt {$this->logPathPrefix}se-debug-*.log | tail -5";
  264. V::exec($cmd, $out, $ret);
  265. }
  266. if (!empty($out)) {
  267. $uiLogFiles = [ 'ret' => $ret, 'cmd' => $cmd, 'out' => $out ];
  268. $logName = end($out);// /tmp/se-debug-2017-01-30-plabudda-192.168.61.206-4qqrd0-1485775975.log
  269. {
  270. if ("{$this->logPathPrefix}se-debug-" != substr($logName, 0, strlen("{$this->logPathPrefix}se-debug-"))) throw new Exception("Wrong log name prefix");
  271. if ('.log' != substr($logName, -1 * strlen('.log'))) throw new Exception("Wrong log name suffix");
  272. $logName = substr($logName, strlen("{$this->logPathPrefix}se-debug-"), -1 * strlen('.log'));
  273. }
  274. }
  275. }
  276. echo UI::h('div', ['class'=>'container', 'style'=>'position:fixed; top:0; left:0; background-color:#ddd; padding:3px; width:100%'], [
  277. UI::h('a', ['href'=>$this->getLink()], "wróć"),
  278. UI::h('span', ['style'=>'padding:0 6px'], "|"),
  279. UI::h('span', ['class' => 'label label-'.(DBG::isActive() ? "success" : "danger")], "(Debug - " . (DBG::isActive() ? "włączony" : "wyłączony") . ") "),
  280. UI::h('span', ['style'=>'padding:0 6px'], "|"),
  281. UI::h('button', ['onClick'=>'location.reload()', 'class'=>"btn btn-xs btn-default"], "odśwież"),
  282. ($logName) ? UI::h('span', ['style'=>'padding:0 6px'], "|") : '',
  283. ($logName)
  284. ? UI::h('a', ['target'=>"_blank", 'href'=>$this->getLink('viewLog', ['name'=>$logName]), 'class'=>"btn btn-xs btn-default"], [
  285. "otwórz w nowym oknie ",
  286. UI::h('i', ['class'=>'glyphicon glyphicon-new-window']),
  287. ])
  288. : '',
  289. ]);
  290. echo UI::h('div', ['style'=>'height:32px']);
  291. if ($uiWarning) UI::alert('warning', $uiWarning);
  292. if (!$logName && null === $uiLogFiles) throw new Exception("Log files not found");
  293. if (null !== $uiLogFiles) {
  294. echo UI::h('div', ['class'=>"alert alert-info"], [
  295. "Last log files",
  296. " (return code: {$uiLogFiles['ret']})",
  297. "<br>cmd: <code>{$uiLogFiles['cmd']}</code>",
  298. UI::h('pre', [], implode("\n", $uiLogFiles['out']))
  299. ]);
  300. }
  301. $this->printLogFileView('debug', $logName);
  302. } catch (Exception $e) {
  303. UI::alert('danger', $e->getMessage());
  304. }
  305. UI::dol();
  306. }
  307. public function viewLatestAuthLogAction() {
  308. session_write_close();
  309. UI::gora();
  310. // UI::menu();
  311. UI::setTitle("Debug");
  312. echo UI::h('div', ['class'=>'container'], [
  313. UI::h('a', ['href'=>$this->getLink('auth')], "wróć")
  314. ]);
  315. try {
  316. $filerUser = V::get('user', '', $_REQUEST);// TODO: show another user debug
  317. $logName = V::get('name', '', $_REQUEST);
  318. if (!$logName) {
  319. $today = date("Y-m-d");
  320. $cmd = "ls -1rt {$this->logPathPrefix}se-auth-{$today}-*.log | tail -5";
  321. V::exec($cmd, $out, $ret);
  322. if (empty($out)) {
  323. UI::alert('warning', "No logs today. Searching previous...");
  324. $cmd = "ls -1rt {$this->logPathPrefix}se-auth-*.log | tail -5";
  325. V::exec($cmd, $out, $ret);
  326. if (empty($out)) throw new Exception("Log files not found");
  327. }
  328. echo UI::h('div', ['class'=>"alert alert-info"], [
  329. "Last log files",
  330. " (return code: {$ret})",
  331. "<br>cmd: <code>{$cmd}</code>",
  332. UI::h('pre', [], implode("\n", $out))
  333. ]);
  334. $logName = end($out);// /tmp/se-debug-2017-01-30-plabudda-192.168.61.206-4qqrd0-1485775975.log
  335. {
  336. if ("{$this->logPathPrefix}se-auth-" != substr($logName, 0, strlen("{$this->logPathPrefix}se-auth-"))) throw new Exception("Wrong log name prefix");
  337. if ('.log' != substr($logName, -1 * strlen('.log'))) throw new Exception("Wrong log name suffix");
  338. $logName = substr($logName, strlen("{$this->logPathPrefix}se-auth-"), -1 * strlen('.log'));
  339. }
  340. }
  341. $this->printLogFileView('auth', $logName);
  342. } catch (Exception $e) {
  343. UI::alert('danger', $e->getMessage());
  344. }
  345. UI::dol();
  346. }
  347. public function viewLogAction() {
  348. session_write_close();
  349. UI::gora();
  350. // UI::menu();
  351. UI::setTitle("Debug");
  352. echo UI::h('div', ['class'=>'container'], [
  353. UI::h('a', ['href'=>$this->getLink()], "wróć")
  354. ]);
  355. try {
  356. $logName = V::get('name', '', $_REQUEST);
  357. $this->printLogFileView('debug', $logName);
  358. } catch (Exception $e) {
  359. UI::alert('danger', $e->getMessage());
  360. }
  361. UI::dol();
  362. }
  363. public function viewAuthLogAction() {
  364. session_write_close();
  365. UI::gora();
  366. // UI::menu();
  367. UI::setTitle("Debug");
  368. echo UI::h('div', ['class'=>'container'], [
  369. UI::h('a', ['href'=>$this->getLink('auth')], "wróć")
  370. ]);
  371. try {
  372. $logName = V::get('name', '', $_REQUEST);
  373. $this->printLogFileView('auth', $logName);
  374. } catch (Exception $e) {
  375. UI::alert('danger', $e->getMessage());
  376. }
  377. UI::dol();
  378. }
  379. public function printLogFileView($type, $logName) {
  380. if (empty($logName)) throw new Exception("Missing name");
  381. $logName = $this->validateParamLogName($logName);
  382. $logPath = "{$this->logPathPrefix}se-{$type}-{$logName}.log";
  383. if (!file_exists($logPath)) throw new Exception("Log file not exists");
  384. // $content = file_get_contents($logPath);
  385. // $contentLines = explode("\n", $content);
  386. V::exec("head -100 '{$logPath}'", $contentLines, $ret);
  387. $hasMoreRows = ( count($contentLines) >= 100 );
  388. if ($hasMoreRows) array_pop($contentLines);
  389. $lastTime = '';
  390. UI::table([
  391. 'cols' => [
  392. 'date',
  393. 'diff',
  394. 'type',
  395. 'msg',
  396. 'trace',
  397. ],
  398. 'cols_help' => [
  399. 'trace' => "Cick to show trace"
  400. ],
  401. 'rows' => array_merge( array_map(
  402. function ($line) use (&$lastTime) {
  403. if (empty($line)) return [];
  404. $dbg = @json_decode($line, $assoc = true);
  405. if (null == $dbg && 0 !== json_last_error()) {
  406. return [
  407. 'type' => 'decode json error',
  408. 'msg' => "Error Processing Request - Parse json error: " . json_last_error()
  409. ];
  410. }
  411. $ret = $this->viewDebugRow($dbg, $lastTime);
  412. $lastTime = $dbg['date'];
  413. return $ret;
  414. },
  415. $contentLines
  416. ),
  417. ($hasMoreRows)
  418. ? [[ 'msg' => UI::h('div', [], [
  419. UI::hButtonAjax("Pobierz kolejne 100 linii ...", 'fetchMoreDbgLines', [
  420. 'class' => "btn btn-xs btn-primary",
  421. 'href' => $this->getLink('fetchMoreDbgLinesAjax'),
  422. 'data' => [
  423. 'logPath' => $logPath,
  424. 'from' => 100,
  425. 'limit' => 100,
  426. ],
  427. ]),
  428. UI::hButtonAjax("Pobierz kolejne 1000 linii ...", 'fetchMoreDbgLines', [
  429. 'class' => "btn btn-xs btn-default",
  430. 'href' => $this->getLink('fetchMoreDbgLinesAjax'),
  431. 'data' => [
  432. 'logPath' => $logPath,
  433. 'from' => 100,
  434. 'limit' => 1000,
  435. ],
  436. ]),
  437. ]) ]]
  438. : []
  439. ),
  440. ]);
  441. UI::hButtonAjaxOnResponse('fetchMoreDbgLines', /* payload, n */ "
  442. console.log('fetchMoreDbgLines: payload, n', payload, n)
  443. var cols = [
  444. 'lp',
  445. 'date',
  446. 'diff',
  447. 'type',
  448. 'msg',
  449. 'trace',
  450. ];
  451. var outHtml = ''
  452. var rows = (payload && payload.body && payload.body.rows && payload.body.rows.length > 0) ? payload.body.rows : []
  453. if (rows) {
  454. rows.forEach(function (row) {
  455. outHtml += ( '@class' in row ) ? '<tr class=\"' + row['@class'] + '\">' : '<tr>'
  456. outHtml += cols.map(function (col) {
  457. var colStyleField = '@style['+col+']'
  458. if ('lp' === col) row[colStyleField] = [ row[colStyleField], 'color:#ccc;' ].join(';')
  459. return '<td style=\"padding:2px' + ( colStyleField in row ? ';' + row[colStyleField] : '' ) + '\">' + row[col] + '</td>'
  460. }).join('')
  461. outHtml += '</tr>'
  462. })
  463. } else {
  464. outHtml += '<tr><td colspan=\"4\"></td><td colspan=\"2\">' + 'Brak danych' + '</td></tr>'
  465. }
  466. var fetchMoreLink = (payload && payload.body && payload.body.fetchMoreLink && payload.body.fetchMoreLink.length > 0) ? payload.body.fetchMoreLink : ''
  467. if (fetchMoreLink) {
  468. outHtml += '<tr><td colspan=\"4\"></td><td colspan=\"2\">' + fetchMoreLink + '</td></tr>'
  469. }
  470. console.log('rows', rows)
  471. console.log('outHtml', outHtml)
  472. jQuery(n).parent().parent().parent().replaceWith(outHtml)
  473. ");
  474. echo UI::h('script', [], "
  475. function p5DBG__showLogTrace(n, e, maxWidth) {
  476. var maxWidth = maxWidth || null
  477. if (!e) return false;
  478. if (e.target && 'PRE' == e.target.tagName) return false;
  479. var preNode = n.parentNode.lastChild
  480. if (preNode.tagName == 'PRE') {
  481. if ('none' == preNode.style.display) {
  482. preNode.style.display = 'block'
  483. } else {
  484. preNode.style.display = 'none'
  485. }
  486. } else {
  487. var pre = document.createElement('pre')
  488. pre.appendChild( document.createTextNode(n.title.replace(/=>\W*array \(/g, '=> [')) )
  489. if (maxWidth) pre.style.maxWidth = maxWidth
  490. pre.style.fontSize = 'x-small'
  491. n.parentNode.appendChild(pre)
  492. }
  493. }
  494. ");
  495. }
  496. public function viewDebugRow($dbg, $lastTime) {
  497. $timeDiff = (!$lastTime)
  498. ? ''
  499. : V::milisecondsStringDiff($dbg['date'], $lastTime)
  500. ;
  501. $uiTimeDiffClass = '';
  502. if ($timeDiff > 0.5) $uiTimeDiffClass = 'danger';
  503. else if ($timeDiff > 0.1) $uiTimeDiffClass = 'warning';
  504. else if ($timeDiff > 0.01) $uiTimeDiffClass = 'info';
  505. $trace = htmlspecialchars($dbg['trace']);
  506. $trace = str_replace("\n", "\n<br>", $trace);
  507. if ('#' === substr($trace, 0, 1)) $trace = "<br>{$trace}";
  508. $trace = preg_replace('/<br>#(\d+\W+)([a-zA-Z0-9-_:\.\/]*)\((\d+)\):/', '<br>#${1}${2}:${3}:', $trace);
  509. $trace = preg_replace('/<br>#(\d+\W+)([a-zA-Z0-9-_:\.\/]*):/', '#${1}<a href="http://localhost:9876/?project=se&file=${2}" target="_blank">${2}</a>:', $trace);
  510. $trace = str_replace("\n<br>", "\n", $trace);
  511. return array_merge([
  512. 'date' => '<nobr>' . substr($dbg['date'], 11) . '</nobr>',
  513. 'diff' => '<nobr>' . $timeDiff . '</nobr>',
  514. '@style[date]' => "width:1%",
  515. 'type' => $dbg['type'],
  516. '@style[type]' => "width:1%",
  517. '@style[msg]' => "min-width:540px; max-width:700px",
  518. '@style[trace]' => "min-width:120px",
  519. 'msg' => UI::h('div', [], [
  520. UI::h('details', [], [
  521. UI::h('summary', [], [
  522. ( ( $dbg['msg'] && 'sql' !== $dbg['msg'] ) ? "{$dbg['msg']} " : '' ),
  523. UI::h('span', [ 'style' => "color:silver" ], str_replace(array('\n', '\t'), ' ', substr(htmlspecialchars(json_encode($dbg['log'])), 0, 140)) . ' ...'),
  524. " (rozwiń)"
  525. ]),
  526. UI::h('pre', [ 'style' => "font-size:x-small" ], htmlspecialchars( ('sql' == $dbg['type'] && is_string($dbg['log'])) ? $dbg['log'] : var_export($dbg['log'], true) )),
  527. ]),
  528. // UI::h('div', [
  529. // 'title' => htmlspecialchars( ('sql' == $dbg['type'] && is_string($dbg['log'])) ? $dbg['log'] : var_export($dbg['log'], true) ),
  530. // 'onClick' => "return p5DBG__showLogTrace(this, event, '600px')",
  531. // 'style' => "cursor:pointer"
  532. // ], str_replace(array('\n', '\t'), ' ', substr(htmlspecialchars(json_encode($dbg['log'])), 0, 100)) . ' ...')
  533. ]),
  534. 'trace' => UI::h('div', [], [
  535. UI::h('details', [], [
  536. UI::h('summary', [], "trace: (rozwiń)"),
  537. UI::h('pre', [ 'style' => "font-size:x-small" ], $trace),
  538. UI::h('div', [
  539. 'title' => htmlspecialchars($dbg['trace']),
  540. 'onClick' => "return p5DBG__showLogTrace(this, event)",
  541. 'style' => "cursor:pointer"
  542. ], ('Exception' == $dbg['type'])
  543. ? "Code: {$dbg['log']['code']}, File: {$dbg['log']['file']}"
  544. : '...'
  545. ),
  546. ]),
  547. ]),
  548. ],
  549. ($uiTimeDiffClass) ? [ '@class' => $uiTimeDiffClass ] : []
  550. );
  551. }
  552. public function fetchMoreDbgLinesAjaxAction() {
  553. Lib::loadClass('Response');
  554. Response::sendTryCatchJson([$this, 'fetchMoreDbgLinesAjax'], $_REQUEST);
  555. }
  556. public function fetchMoreDbgLinesAjax($args) {
  557. $logPath = V::get('logPath', '', $args);
  558. if (!$logPath) throw new Exception("Missing logPath");
  559. $from = V::get('from', 0, $args, 'int');
  560. $limit = V::get('limit', 100, $args, 'int');
  561. // $content = file_get_contents($logPath);
  562. // $contentLines = explode("\n", $content);
  563. V::exec("tail -n +{$from} '{$logPath}' | head -" . ($limit + 1) . " ", $contentLines, $ret);
  564. $hasMoreRows = ( count($contentLines) > $limit );
  565. if ($hasMoreRows) array_pop($contentLines);
  566. $lastTime = null;
  567. $lp = $from;
  568. return [
  569. 'msg' => "TODO: ... ret({$ret}) lines(".count($contentLines).") ",
  570. 'type' => "error",
  571. 'body' => [
  572. 'rows' => array_values(array_filter(
  573. array_map(function ($line) use (&$lastTime, &$lp) {
  574. if (empty($line)) return null;
  575. $dbg = @json_decode($line, $assoc = true);
  576. if (null == $dbg && 0 !== json_last_error()) {
  577. return [
  578. 'type' => 'decode json error',
  579. 'msg' => "Error Processing Request - Parse json error: " . json_last_error()
  580. ];
  581. }
  582. $ret = $this->viewDebugRow($dbg, $lastTime);
  583. $ret['lp'] = $lp++;
  584. $lastTime = $dbg['date'];
  585. return $ret;
  586. }, $contentLines)
  587. , function ($line) { return null !== $line; }
  588. )),
  589. 'fetchMoreLink' =>
  590. ($hasMoreRows)
  591. ? UI::h('div', [], [
  592. UI::hButtonAjax("Pobierz kolejne {$limit} linii ...", 'fetchMoreDbgLines', [
  593. 'class' => "btn btn-xs btn-primary",
  594. 'href' => $this->getLink('fetchMoreDbgLinesAjax'),
  595. 'data' => [
  596. 'logPath' => $logPath,
  597. 'from' => $from + $limit,
  598. 'limit' => $limit,
  599. ],
  600. ]),
  601. UI::hButtonAjax("Pobierz wszystkie", 'fetchMoreDbgLines', [
  602. 'class' => "btn btn-xs btn-default",
  603. 'href' => $this->getLink('fetchMoreDbgLinesAjax'),
  604. 'data' => [
  605. 'logPath' => $logPath,
  606. 'from' => $from + $limit,
  607. 'limit' => 1000,
  608. ],
  609. ]),
  610. ])
  611. : null,
  612. ]
  613. ];
  614. }
  615. public function activateDebugAction() {
  616. DBG::activate();
  617. $this->defaultView();
  618. }
  619. public function deactivateDebugAction() {
  620. DBG::deactivate();
  621. $this->defaultView();
  622. }
  623. public function testDebugWithSleepAction() {
  624. session_write_close();
  625. UI::gora();
  626. UI::setTitle("Debug Test Sleep");
  627. flush();
  628. for ($i = 0; $i < 10; $i++) {
  629. echo "TEST {$i}<br>";
  630. DBG::log("TEST {$i}");
  631. flush();
  632. sleep(2);
  633. }
  634. echo "DONE";
  635. DBG::log("DONE");
  636. UI::dol();
  637. }
  638. public function validateParamLogName($logName) {
  639. if (empty($logName)) throw new Exception("Missing log file name");
  640. if (!preg_match('/^[\-\.a-zA-Z0-9]+$/', $logName)) throw new Exception("Wrong log file name format");
  641. return $logName;
  642. }
  643. public function rmAllLogFilesAction() {
  644. session_write_close();
  645. try {
  646. $today = date("Y-m-d");
  647. $cmd = "rm -v {$this->logPathPrefix}se-debug-*.log 2>&1";
  648. V::exec($cmd, $out, $ret);
  649. $this->defaultView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
  650. '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>',
  651. (0 === $ret) ? "All Log Files Removed" : "Error?",
  652. " (return code: {$ret})",
  653. "<br>cmd: <code>{$cmd}</code>",
  654. UI::h('pre', [], implode("\n", $out))
  655. ]));
  656. } catch (AlertSuccessException $e) {
  657. $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
  658. } catch (AlertWarningException $e) {
  659. $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
  660. } catch (Exception $e) {
  661. $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
  662. }
  663. }
  664. public function rmOldLogFilesAction() {
  665. session_write_close();
  666. try {
  667. $today = date("Y-m-d");
  668. $cmd = "ls -1 {$this->logPathPrefix}se-debug-*.log | grep -v '{$this->logPathPrefix}se-debug-{$today}-' | xargs rm -v 2>&1";
  669. V::exec($cmd, $out, $ret);
  670. $this->defaultView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
  671. '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>',
  672. (0 === $ret) ? "Old Log Files Removed" : "Error?",
  673. " (return code: {$ret})",
  674. "<br>cmd: <code>{$cmd}</code>",
  675. UI::h('pre', [], implode("\n", $out))
  676. ]));
  677. } catch (AlertSuccessException $e) {
  678. $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
  679. } catch (AlertWarningException $e) {
  680. $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
  681. } catch (Exception $e) {
  682. $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
  683. }
  684. }
  685. public function rmAllUserLogFilesAction() {
  686. session_write_close();
  687. try {
  688. $userLogin = User::getLogin();
  689. $today = date("Y-m-d");
  690. $cmd = "rm -v {$this->logPathPrefix}se-debug-*-{$userLogin}-*.log 2>&1";
  691. V::exec($cmd, $out, $ret);
  692. $this->defaultView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
  693. '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>',
  694. (0 === $ret) ? "All Log Files Removed" : "Error?",
  695. " (return code: {$ret})",
  696. "<br>cmd: <code>{$cmd}</code>",
  697. UI::h('pre', [], implode("\n", $out))
  698. ]));
  699. } catch (AlertSuccessException $e) {
  700. $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
  701. } catch (AlertWarningException $e) {
  702. $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
  703. } catch (Exception $e) {
  704. $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
  705. }
  706. }
  707. public function rmOldUserLogFilesAction() {
  708. session_write_close();
  709. try {
  710. $userLogin = User::getLogin();
  711. $today = date("Y-m-d");
  712. $cmd = "ls -1 {$this->logPathPrefix}se-debug-*-{$userLogin}-*.log | grep -v '{$this->logPathPrefix}se-debug-{$today}-' | xargs rm -v 2>&1";
  713. V::exec($cmd, $out, $ret);
  714. $this->defaultView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
  715. '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>',
  716. (0 === $ret) ? "Old Log Files Removed" : "Error?",
  717. " (return code: {$ret})",
  718. "<br>cmd: <code>{$cmd}</code>",
  719. UI::h('pre', [], implode("\n", $out))
  720. ]));
  721. } catch (AlertSuccessException $e) {
  722. $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
  723. } catch (AlertWarningException $e) {
  724. $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
  725. } catch (Exception $e) {
  726. $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
  727. }
  728. }
  729. public function rmLogFileAction() {
  730. session_write_close();
  731. try {
  732. $logName = $this->validateParamLogName(V::get('logName', '', $_REQUEST));
  733. $logPath = "{$this->logPathPrefix}se-debug-{$logName}.log";
  734. if (!file_exists($logPath)) throw new AlertWarningException("Log file not exists");
  735. unlink($logPath);
  736. throw new AlertSuccessException("File Removed");
  737. } catch (AlertSuccessException $e) {
  738. $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
  739. } catch (AlertWarningException $e) {
  740. $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
  741. } catch (Exception $e) {
  742. $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
  743. }
  744. }
  745. public function rmAllAuthLogFilesAction() {
  746. session_write_close();
  747. try {
  748. $userLogin = User::getLogin();
  749. $today = date("Y-m-d");
  750. $cmd = "rm -v {$this->logPathPrefix}se-auth-*.log 2>&1";
  751. V::exec($cmd, $out, $ret);
  752. $this->authView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
  753. '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>',
  754. (0 === $ret) ? "All Log Files Removed" : "Error?",
  755. " (return code: {$ret})",
  756. "<br>cmd: <code>{$cmd}</code>",
  757. UI::h('pre', [], implode("\n", $out))
  758. ]));
  759. } catch (AlertSuccessException $e) {
  760. $this->authView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
  761. } catch (AlertWarningException $e) {
  762. $this->authView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
  763. } catch (Exception $e) {
  764. $this->authView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
  765. }
  766. }
  767. public function rmOldAuthLogFilesAction() {
  768. session_write_close();
  769. try {
  770. $userLogin = User::getLogin();
  771. $today = date("Y-m-d");
  772. $cmd = "ls -1 {$this->logPathPrefix}se-auth-*.log | grep -v '{$this->logPathPrefix}se-auth-{$today}-' | xargs rm -v 2>&1";
  773. V::exec($cmd, $out, $ret);
  774. $this->authView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
  775. '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>',
  776. (0 === $ret) ? "Old Log Files Removed" : "Error?",
  777. " (return code: {$ret})",
  778. "<br>cmd: <code>{$cmd}</code>",
  779. UI::h('pre', [], implode("\n", $out))
  780. ]));
  781. } catch (AlertSuccessException $e) {
  782. $this->authView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
  783. } catch (AlertWarningException $e) {
  784. $this->authView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
  785. } catch (Exception $e) {
  786. $this->authView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
  787. }
  788. }
  789. public function rmAuthLogFileAction() {
  790. session_write_close();
  791. try {
  792. $logName = $this->validateParamLogName(V::get('logName', '', $_REQUEST));
  793. $logPath = "{$this->logPathPrefix}se-auth-{$logName}.log";
  794. if (!file_exists($logPath)) throw new AlertWarningException("Log file not exists");
  795. unlink($logPath);
  796. throw new AlertSuccessException("File Removed");
  797. } catch (AlertSuccessException $e) {
  798. $this->authView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
  799. } catch (AlertWarningException $e) {
  800. $this->authView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
  801. } catch (Exception $e) {
  802. $this->authView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
  803. }
  804. }
  805. }