| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834 |
- <?php
- Lib::loadClass('RouteBase');
- /**
- * TODO: debug to file based on session_id (/tmp/se-debug-{$date("Y-m-d")}-{$login}_{$ip}_{$session_id}.log)
- * TODO: function if loggind enabled, then save to file and print in default page
- * - DBG::log(string $msg or Exception $e)
- * TODO: better wfs log by fingerprint (User::getLogin() + IP + UserAgent)
- */
- class Route_Debug extends RouteBase {
- public $logPathPrefix = '/tmp/se-todo-';
- public function __construct() {
- $this->logPathPrefix = '/tmp/' . ('production' == V::get('P5_ENV', 'production', $_SERVER) ? "" : "dev-");
- }
- public function handleAuth() {
- if (!User::logged()) {
- throw new HttpException('Unauthorized', 401);
- }
- if (!User::hasAccess('dbg')) {// User::get('ADM_ADMIN_LEVEL') == 0
- throw new HttpException('Unauthorized - required dbg access', 401);
- }
- }
- public function defaultAction() {
- session_write_close();
- $this->defaultView();
- }
- public function defaultView($flashMsg = '') {
- UI::gora();
- UI::menu();
- UI::setTitle("Debug");
- if (!empty($_POST)) echo UI::h('script', [], "history.replaceState(null, 'Debug', window.location.href);");
- try {
- echo UI::h('div', ['class'=>"breadcrumb"], [
- "Debug ",
- UI::h('strong', [], "(" . (DBG::isActive() ? "włączony" : "wyłączony") . ") "),
- UI::h('a', [
- 'href' => $this->getLink(),
- 'class' => "btn btn-xs btn-default"
- ], "Odśwież"),
- " ",
- UI::hButtonPost((DBG::isActive()) ? "Wyłącz debug" : "Włącz debug", [
- 'class' => "btn-success btn-xs",
- 'data' => [
- '_route' => 'Debug',
- '_task' => DBG::isActive() ? 'deactivateDebug' : 'activateDebug'
- ]
- ]),
- " ",
- UI::h('a', [
- 'href' => $this->getLink('auth'),
- 'class' => "btn btn-xs btn-link"
- ], "auth log"),
- $this->adminWidgetDebugUserLink(),
- ]);
- echo $flashMsg;
- // DBG::nicePrint($_SERVER, '$_SERVER');
- // DBG::nicePrint([
- // 'date' => date("Y-m-d"),
- // 'login' => User::getLogin(),
- // 'ip' => Request::getUserIp(),
- // 'session_id' => session_id()
- // ], 'dbg');
- UI::table([
- 'caption' => "Log Files " . UI::h('a', [
- 'href' => $this->getLink("viewLatestUserLog"),
- 'class' => "btn btn-xs btn-primary"
- ], "Pokaż ostatni log") . " " . UI::hButtonPost("Usuń wszystkie swoje pliki", [
- 'class' => "btn-danger btn-xs",
- 'data' => [
- '_route' => 'Debug',
- '_task' => 'rmAllUserLogFiles'
- ]
- ]) . " " . UI::hButtonPost("Usuń stare pliki", [
- 'class' => "btn-warning btn-xs",
- 'data' => [
- '_route' => 'Debug',
- '_task' => 'rmOldUserLogFiles'
- ]
- ]),
- 'cols' => [
- '#',
- 'file',
- 'user',
- 'request date',
- 'ip',
- 'rm',
- ],
- 'rows' => array_map(
- function ($logFile) {
- // /tmp/se-debug-2017-01-25-plabudda-192.168.61.206-4qqrd0.log
- try {
- if ("{$this->logPathPrefix}se-debug-" != substr($logFile, 0, strlen("{$this->logPathPrefix}se-debug-"))) throw new Exception("Wrong log file name '{$logFile}'");
- if ('.log' != substr($logFile, -4)) throw new Exception("Wrong log file name extension '{$logFile}'");
- $logName = substr($logFile, strlen("{$this->logPathPrefix}se-debug-"), -4);
- list($logYear, $logMonth, $logDay, $logUser, $logIP, $logSessId, $logReqDate) = explode('-', $logName);
- return [
- '#' => UI::h('a', [
- 'href' => $this->getLink("viewLog", ['name' => $logName])
- ], "Pokaż"),
- 'request date' => ($logReqDate) ? date("Y-m-d H:i:s", $logReqDate) : '',// 1485775975
- 'file' => $logFile,
- 'user' => $logUser,
- 'ip' => $logIP,
- 'rm' => UI::hButtonPost("Usuń", [
- 'class' => 'btn-default btn-xs',
- 'data' => [
- '_route' => 'Debug',
- '_task' => 'rmLogFile',
- 'logName' => $logName
- ]
- ]),
- ];
- } catch (Exception $e) {
- return [
- '#' => '',
- 'file' => $e->getMessage(),
- ];
- }
- }
- , glob("{$this->logPathPrefix}se-debug-*.log", GLOB_NOSORT)
- )
- ]);
- echo UI::hButtonPost("Test dbg with sleep", [
- 'class' => "btn-warning btn-xs",
- 'data' => [
- '_route' => 'Debug',
- '_task' => 'testDebugWithSleep'
- ]
- ]);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- DBG::log($e);
- }
- UI::dol();
- }
- public function adminWidgetDebugUserLink() {
- if (0 != User::get('ADM_ADMIN_LEVEL')) return '';
- return UI::h('a', [
- 'href' => $this->getLink('adminUserDebug'),
- 'class' => "btn btn-xs btn-link"
- ], "debug another user");
- }
- public function adminUserDebugAction() {
- UI::gora();
- UI::menu();
- UI::startContainer();
- try {
- // $idUser = V::get('idUser', 0, $_GET, 'int'); // TODO: add link for this user debug? use main debug files list and viewLatestUserLog
- // if ($idUser > 0) {
- // } else {
- Router::getRoute('Status')->viewStatusUsers();
- // }
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- DBG::log($e);
- }
- UI::endContainer();
- UI::dol();
- }
- public function authAction() {
- session_write_close();
- $this->authView();
- }
- public function authView($flashMsg = '') {
- UI::gora();
- UI::menu();
- UI::setTitle("Debug");
- if (!empty($_POST)) echo UI::h('script', [], "history.replaceState(null, 'Debug', window.location.href);");
- try {
- echo UI::h('div', ['class'=>"breadcrumb"], [
- UI::h('a', [
- 'href' => $this->getLink(),
- 'class' => "btn btn-link"
- ], "Debug"),
- " / ",
- UI::h('a', [
- 'href' => $this->getLink('auth'),
- 'class' => "btn btn-link"
- ], "Auth (Odśwież)"),
- ]);
- echo $flashMsg;
- UI::table([
- 'caption' => "Log Files " . UI::h('a', [
- 'href' => $this->getLink("viewLatestAuthLog"),
- 'class' => "btn btn-xs btn-primary"
- ], "Pokaż ostatni log") . " " . UI::hButtonPost("Usuń wszystkie pliki", [
- 'class' => "btn-danger btn-xs",
- 'data' => [
- '_route' => 'Debug',
- '_task' => 'rmAllAuthLogFiles'
- ]
- ]) . " " . UI::hButtonPost("Usuń stare pliki", [
- 'class' => "btn-warning btn-xs",
- 'data' => [
- '_route' => 'Debug',
- '_task' => 'rmOldAuthLogFiles'
- ]
- ]),
- 'cols' => [
- '#',
- 'file',
- 'user',
- 'request date',
- 'ip',
- 'rm',
- ],
- 'rows' => array_map(
- function ($logFile) {
- // /tmp/se-debug-2017-01-25-plabudda-192.168.61.206-4qqrd0.log
- try {
- if ("{$this->logPathPrefix}se-auth-" != substr($logFile, 0, strlen("{$this->logPathPrefix}se-auth-"))) throw new Exception("Wrong log file name '{$logFile}'");
- if ('.log' != substr($logFile, -4)) throw new Exception("Wrong log file name extension '{$logFile}'");
- $logName = substr($logFile, strlen("{$this->logPathPrefix}se-auth-"), -4);
- list($logYear, $logMonth, $logDay, $logIP, $logReqDate) = explode('-', $logName);
- return [
- '#' => UI::h('a', [
- 'href' => $this->getLink('viewAuthLog', ['name'=>$logName])
- ], "Pokaż"),
- 'request date' => ($logReqDate) ? date("Y-m-d H:i:s", $logReqDate) : '',// 1485775975
- 'file' => $logFile,
- 'user' => $logUser,
- 'ip' => $logIP,
- 'rm' => UI::hButtonPost("Usuń", [
- 'class' => 'btn-default btn-xs',
- 'data' => [
- '_route' => 'Debug',
- '_task' => 'rmAuthLogFile',
- 'logName' => $logName
- ]
- ]),
- ];
- } catch (Exception $e) {
- return [
- '#' => '',
- 'file' => $e->getMessage(),
- ];
- }
- }
- , glob("{$this->logPathPrefix}se-auth-*.log", GLOB_NOSORT)
- )
- ]);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- DBG::log($e);
- }
- UI::dol();
- }
- public function viewLatestUserLogAction() {
- session_write_close();
- UI::gora();
- // UI::menu();
- UI::setTitle("Debug");
- try {
- $filerUser = V::get('user', '', $_REQUEST);// TODO: show another user debug
- $logName = V::get('name', '', $_REQUEST);
- $uiWarning = null;
- $uiLogFiles = null;
- if (!$logName) {
- $today = date("Y-m-d");
- $cmd = "ls -1rt {$this->logPathPrefix}se-debug-{$today}-*.log | tail -5";
- V::exec($cmd, $out, $ret);
- if (empty($out)) {
- $uiWarning = "No logs today. Searching previous...";
- $cmd = "ls -1rt {$this->logPathPrefix}se-debug-*.log | tail -5";
- V::exec($cmd, $out, $ret);
- }
- if (!empty($out)) {
- $uiLogFiles = [ 'ret' => $ret, 'cmd' => $cmd, 'out' => $out ];
- $logName = end($out);// /tmp/se-debug-2017-01-30-plabudda-192.168.61.206-4qqrd0-1485775975.log
- {
- if ("{$this->logPathPrefix}se-debug-" != substr($logName, 0, strlen("{$this->logPathPrefix}se-debug-"))) throw new Exception("Wrong log name prefix");
- if ('.log' != substr($logName, -1 * strlen('.log'))) throw new Exception("Wrong log name suffix");
- $logName = substr($logName, strlen("{$this->logPathPrefix}se-debug-"), -1 * strlen('.log'));
- }
- }
- }
- echo UI::h('div', ['class'=>'container', 'style'=>'position:fixed; top:0; left:0; background-color:#ddd; padding:3px; width:100%'], [
- UI::h('a', ['href'=>$this->getLink()], "wróć"),
- UI::h('span', ['style'=>'padding:0 6px'], "|"),
- UI::h('span', ['class' => 'label label-'.(DBG::isActive() ? "success" : "danger")], "(Debug - " . (DBG::isActive() ? "włączony" : "wyłączony") . ") "),
- UI::h('span', ['style'=>'padding:0 6px'], "|"),
- UI::h('button', ['onClick'=>'location.reload()', 'class'=>"btn btn-xs btn-default"], "odśwież"),
- ($logName) ? UI::h('span', ['style'=>'padding:0 6px'], "|") : '',
- ($logName)
- ? UI::h('a', ['target'=>"_blank", 'href'=>$this->getLink('viewLog', ['name'=>$logName]), 'class'=>"btn btn-xs btn-default"], [
- "otwórz w nowym oknie ",
- UI::h('i', ['class'=>'glyphicon glyphicon-new-window']),
- ])
- : '',
- ]);
- echo UI::h('div', ['style'=>'height:32px']);
- if ($uiWarning) UI::alert('warning', $uiWarning);
- if (!$logName && null === $uiLogFiles) throw new Exception("Log files not found");
- if (null !== $uiLogFiles) {
- echo UI::h('div', ['class'=>"alert alert-info"], [
- "Last log files",
- " (return code: {$uiLogFiles['ret']})",
- "<br>cmd: <code>{$uiLogFiles['cmd']}</code>",
- UI::h('pre', [], implode("\n", $uiLogFiles['out']))
- ]);
- }
- $this->printLogFileView('debug', $logName);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- }
- UI::dol();
- }
- public function viewLatestAuthLogAction() {
- session_write_close();
- UI::gora();
- // UI::menu();
- UI::setTitle("Debug");
- echo UI::h('div', ['class'=>'container'], [
- UI::h('a', ['href'=>$this->getLink('auth')], "wróć")
- ]);
- try {
- $filerUser = V::get('user', '', $_REQUEST);// TODO: show another user debug
- $logName = V::get('name', '', $_REQUEST);
- if (!$logName) {
- $today = date("Y-m-d");
- $cmd = "ls -1rt {$this->logPathPrefix}se-auth-{$today}-*.log | tail -5";
- V::exec($cmd, $out, $ret);
- if (empty($out)) {
- UI::alert('warning', "No logs today. Searching previous...");
- $cmd = "ls -1rt {$this->logPathPrefix}se-auth-*.log | tail -5";
- V::exec($cmd, $out, $ret);
- if (empty($out)) throw new Exception("Log files not found");
- }
- echo UI::h('div', ['class'=>"alert alert-info"], [
- "Last log files",
- " (return code: {$ret})",
- "<br>cmd: <code>{$cmd}</code>",
- UI::h('pre', [], implode("\n", $out))
- ]);
- $logName = end($out);// /tmp/se-debug-2017-01-30-plabudda-192.168.61.206-4qqrd0-1485775975.log
- {
- if ("{$this->logPathPrefix}se-auth-" != substr($logName, 0, strlen("{$this->logPathPrefix}se-auth-"))) throw new Exception("Wrong log name prefix");
- if ('.log' != substr($logName, -1 * strlen('.log'))) throw new Exception("Wrong log name suffix");
- $logName = substr($logName, strlen("{$this->logPathPrefix}se-auth-"), -1 * strlen('.log'));
- }
- }
- $this->printLogFileView('auth', $logName);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- }
- UI::dol();
- }
- public function viewLogAction() {
- session_write_close();
- UI::gora();
- // UI::menu();
- UI::setTitle("Debug");
- echo UI::h('div', ['class'=>'container'], [
- UI::h('a', ['href'=>$this->getLink()], "wróć")
- ]);
- try {
- $logName = V::get('name', '', $_REQUEST);
- $this->printLogFileView('debug', $logName);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- }
- UI::dol();
- }
- public function viewAuthLogAction() {
- session_write_close();
- UI::gora();
- // UI::menu();
- UI::setTitle("Debug");
- echo UI::h('div', ['class'=>'container'], [
- UI::h('a', ['href'=>$this->getLink('auth')], "wróć")
- ]);
- try {
- $logName = V::get('name', '', $_REQUEST);
- $this->printLogFileView('auth', $logName);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- }
- UI::dol();
- }
- public function printLogFileView($type, $logName) {
- if (empty($logName)) throw new Exception("Missing name");
- $logName = $this->validateParamLogName($logName);
- $logPath = "{$this->logPathPrefix}se-{$type}-{$logName}.log";
- if (!file_exists($logPath)) throw new Exception("Log file not exists");
- // $content = file_get_contents($logPath);
- // $contentLines = explode("\n", $content);
- V::exec("head -100 '{$logPath}'", $contentLines, $ret);
- $hasMoreRows = ( count($contentLines) >= 100 );
- if ($hasMoreRows) array_pop($contentLines);
- $lastTime = '';
- UI::table([
- 'cols' => [
- 'date',
- 'diff',
- 'type',
- 'msg',
- 'trace',
- ],
- 'cols_help' => [
- 'trace' => "Cick to show trace"
- ],
- 'rows' => array_merge( array_map(
- function ($line) use (&$lastTime) {
- if (empty($line)) return [];
- $dbg = @json_decode($line, $assoc = true);
- if (null == $dbg && 0 !== json_last_error()) {
- return [
- 'type' => 'decode json error',
- 'msg' => "Error Processing Request - Parse json error: " . json_last_error()
- ];
- }
- $ret = $this->viewDebugRow($dbg, $lastTime);
- $lastTime = $dbg['date'];
- return $ret;
- },
- $contentLines
- ),
- ($hasMoreRows)
- ? [[ 'msg' => UI::h('div', [], [
- UI::hButtonAjax("Pobierz kolejne 100 linii ...", 'fetchMoreDbgLines', [
- 'class' => "btn btn-xs btn-primary",
- 'href' => $this->getLink('fetchMoreDbgLinesAjax'),
- 'data' => [
- 'logPath' => $logPath,
- 'from' => 100,
- 'limit' => 100,
- ],
- ]),
- UI::hButtonAjax("Pobierz kolejne 1000 linii ...", 'fetchMoreDbgLines', [
- 'class' => "btn btn-xs btn-default",
- 'href' => $this->getLink('fetchMoreDbgLinesAjax'),
- 'data' => [
- 'logPath' => $logPath,
- 'from' => 100,
- 'limit' => 1000,
- ],
- ]),
- ]) ]]
- : []
- ),
- ]);
- UI::hButtonAjaxOnResponse('fetchMoreDbgLines', /* payload, n */ "
- console.log('fetchMoreDbgLines: payload, n', payload, n)
- var cols = [
- 'lp',
- 'date',
- 'diff',
- 'type',
- 'msg',
- 'trace',
- ];
- var outHtml = ''
- var rows = (payload && payload.body && payload.body.rows && payload.body.rows.length > 0) ? payload.body.rows : []
- if (rows) {
- rows.forEach(function (row) {
- outHtml += ( '@class' in row ) ? '<tr class=\"' + row['@class'] + '\">' : '<tr>'
- outHtml += cols.map(function (col) {
- var colStyleField = '@style['+col+']'
- if ('lp' === col) row[colStyleField] = [ row[colStyleField], 'color:#ccc;' ].join(';')
- return '<td style=\"padding:2px' + ( colStyleField in row ? ';' + row[colStyleField] : '' ) + '\">' + row[col] + '</td>'
- }).join('')
- outHtml += '</tr>'
- })
- } else {
- outHtml += '<tr><td colspan=\"4\"></td><td colspan=\"2\">' + 'Brak danych' + '</td></tr>'
- }
- var fetchMoreLink = (payload && payload.body && payload.body.fetchMoreLink && payload.body.fetchMoreLink.length > 0) ? payload.body.fetchMoreLink : ''
- if (fetchMoreLink) {
- outHtml += '<tr><td colspan=\"4\"></td><td colspan=\"2\">' + fetchMoreLink + '</td></tr>'
- }
- console.log('rows', rows)
- console.log('outHtml', outHtml)
- jQuery(n).parent().parent().parent().replaceWith(outHtml)
- ");
- echo UI::h('script', [], "
- function p5DBG__showLogTrace(n, e, maxWidth) {
- var maxWidth = maxWidth || null
- if (!e) return false;
- if (e.target && 'PRE' == e.target.tagName) return false;
- var preNode = n.parentNode.lastChild
- if (preNode.tagName == 'PRE') {
- if ('none' == preNode.style.display) {
- preNode.style.display = 'block'
- } else {
- preNode.style.display = 'none'
- }
- } else {
- var pre = document.createElement('pre')
- pre.appendChild( document.createTextNode(n.title.replace(/=>\W*array \(/g, '=> [')) )
- if (maxWidth) pre.style.maxWidth = maxWidth
- pre.style.fontSize = 'x-small'
- n.parentNode.appendChild(pre)
- }
- }
- ");
- }
- public function viewDebugRow($dbg, $lastTime) {
- $timeDiff = (!$lastTime)
- ? ''
- : V::milisecondsStringDiff($dbg['date'], $lastTime)
- ;
- $uiTimeDiffClass = '';
- if ($timeDiff > 0.5) $uiTimeDiffClass = 'danger';
- else if ($timeDiff > 0.1) $uiTimeDiffClass = 'warning';
- else if ($timeDiff > 0.01) $uiTimeDiffClass = 'info';
- $trace = htmlspecialchars($dbg['trace']);
- $trace = str_replace("\n", "\n<br>", $trace);
- if ('#' === substr($trace, 0, 1)) $trace = "<br>{$trace}";
- $trace = preg_replace('/<br>#(\d+\W+)([a-zA-Z0-9-_:\.\/]*)\((\d+)\):/', '<br>#${1}${2}:${3}:', $trace);
- $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);
- $trace = str_replace("\n<br>", "\n", $trace);
- return array_merge([
- 'date' => '<nobr>' . substr($dbg['date'], 11) . '</nobr>',
- 'diff' => '<nobr>' . $timeDiff . '</nobr>',
- '@style[date]' => "width:1%",
- 'type' => $dbg['type'],
- '@style[type]' => "width:1%",
- '@style[msg]' => "min-width:540px; max-width:700px",
- '@style[trace]' => "min-width:120px",
- 'msg' => UI::h('div', [], [
- UI::h('details', [], [
- UI::h('summary', [], [
- ( ( $dbg['msg'] && 'sql' !== $dbg['msg'] ) ? "{$dbg['msg']} " : '' ),
- UI::h('span', [ 'style' => "color:silver" ], str_replace(array('\n', '\t'), ' ', substr(htmlspecialchars(json_encode($dbg['log'])), 0, 140)) . ' ...'),
- " (rozwiń)"
- ]),
- UI::h('pre', [ 'style' => "font-size:x-small" ], htmlspecialchars( ('sql' == $dbg['type'] && is_string($dbg['log'])) ? $dbg['log'] : var_export($dbg['log'], true) )),
- ]),
- // UI::h('div', [
- // 'title' => htmlspecialchars( ('sql' == $dbg['type'] && is_string($dbg['log'])) ? $dbg['log'] : var_export($dbg['log'], true) ),
- // 'onClick' => "return p5DBG__showLogTrace(this, event, '600px')",
- // 'style' => "cursor:pointer"
- // ], str_replace(array('\n', '\t'), ' ', substr(htmlspecialchars(json_encode($dbg['log'])), 0, 100)) . ' ...')
- ]),
- 'trace' => UI::h('div', [], [
- UI::h('details', [], [
- UI::h('summary', [], "trace: (rozwiń)"),
- UI::h('pre', [ 'style' => "font-size:x-small" ], $trace),
- UI::h('div', [
- 'title' => htmlspecialchars($dbg['trace']),
- 'onClick' => "return p5DBG__showLogTrace(this, event)",
- 'style' => "cursor:pointer"
- ], ('Exception' == $dbg['type'])
- ? "Code: {$dbg['log']['code']}, File: {$dbg['log']['file']}"
- : '...'
- ),
- ]),
- ]),
- ],
- ($uiTimeDiffClass) ? [ '@class' => $uiTimeDiffClass ] : []
- );
- }
- public function fetchMoreDbgLinesAjaxAction() {
- Lib::loadClass('Response');
- Response::sendTryCatchJson([$this, 'fetchMoreDbgLinesAjax'], $_REQUEST);
- }
- public function fetchMoreDbgLinesAjax($args) {
- $logPath = V::get('logPath', '', $args);
- if (!$logPath) throw new Exception("Missing logPath");
- $from = V::get('from', 0, $args, 'int');
- $limit = V::get('limit', 100, $args, 'int');
- // $content = file_get_contents($logPath);
- // $contentLines = explode("\n", $content);
- V::exec("tail -n +{$from} '{$logPath}' | head -" . ($limit + 1) . " ", $contentLines, $ret);
- $hasMoreRows = ( count($contentLines) > $limit );
- if ($hasMoreRows) array_pop($contentLines);
- $lastTime = null;
- $lp = $from;
- return [
- 'msg' => "TODO: ... ret({$ret}) lines(".count($contentLines).") ",
- 'type' => "error",
- 'body' => [
- 'rows' => array_values(array_filter(
- array_map(function ($line) use (&$lastTime, &$lp) {
- if (empty($line)) return null;
- $dbg = @json_decode($line, $assoc = true);
- if (null == $dbg && 0 !== json_last_error()) {
- return [
- 'type' => 'decode json error',
- 'msg' => "Error Processing Request - Parse json error: " . json_last_error()
- ];
- }
- $ret = $this->viewDebugRow($dbg, $lastTime);
- $ret['lp'] = $lp++;
- $lastTime = $dbg['date'];
- return $ret;
- }, $contentLines)
- , function ($line) { return null !== $line; }
- )),
- 'fetchMoreLink' =>
- ($hasMoreRows)
- ? UI::h('div', [], [
- UI::hButtonAjax("Pobierz kolejne {$limit} linii ...", 'fetchMoreDbgLines', [
- 'class' => "btn btn-xs btn-primary",
- 'href' => $this->getLink('fetchMoreDbgLinesAjax'),
- 'data' => [
- 'logPath' => $logPath,
- 'from' => $from + $limit,
- 'limit' => $limit,
- ],
- ]),
- UI::hButtonAjax("Pobierz wszystkie", 'fetchMoreDbgLines', [
- 'class' => "btn btn-xs btn-default",
- 'href' => $this->getLink('fetchMoreDbgLinesAjax'),
- 'data' => [
- 'logPath' => $logPath,
- 'from' => $from + $limit,
- 'limit' => 1000,
- ],
- ]),
- ])
- : null,
- ]
- ];
- }
- public function activateDebugAction() {
- DBG::activate();
- $this->defaultView();
- }
- public function deactivateDebugAction() {
- DBG::deactivate();
- $this->defaultView();
- }
- public function testDebugWithSleepAction() {
- session_write_close();
- UI::gora();
- UI::setTitle("Debug Test Sleep");
- flush();
- for ($i = 0; $i < 10; $i++) {
- echo "TEST {$i}<br>";
- DBG::log("TEST {$i}");
- flush();
- sleep(2);
- }
- echo "DONE";
- DBG::log("DONE");
- UI::dol();
- }
- public function validateParamLogName($logName) {
- if (empty($logName)) throw new Exception("Missing log file name");
- if (!preg_match('/^[\-\.a-zA-Z0-9]+$/', $logName)) throw new Exception("Wrong log file name format");
- return $logName;
- }
- public function rmAllLogFilesAction() {
- session_write_close();
- try {
- $today = date("Y-m-d");
- $cmd = "rm -v {$this->logPathPrefix}se-debug-*.log 2>&1";
- V::exec($cmd, $out, $ret);
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
- '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>',
- (0 === $ret) ? "All Log Files Removed" : "Error?",
- " (return code: {$ret})",
- "<br>cmd: <code>{$cmd}</code>",
- UI::h('pre', [], implode("\n", $out))
- ]));
- } catch (AlertSuccessException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
- } catch (AlertWarningException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
- } catch (Exception $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
- }
- }
- public function rmOldLogFilesAction() {
- session_write_close();
- try {
- $today = date("Y-m-d");
- $cmd = "ls -1 {$this->logPathPrefix}se-debug-*.log | grep -v '{$this->logPathPrefix}se-debug-{$today}-' | xargs rm -v 2>&1";
- V::exec($cmd, $out, $ret);
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
- '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>',
- (0 === $ret) ? "Old Log Files Removed" : "Error?",
- " (return code: {$ret})",
- "<br>cmd: <code>{$cmd}</code>",
- UI::h('pre', [], implode("\n", $out))
- ]));
- } catch (AlertSuccessException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
- } catch (AlertWarningException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
- } catch (Exception $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
- }
- }
- public function rmAllUserLogFilesAction() {
- session_write_close();
- try {
- $userLogin = User::getLogin();
- $today = date("Y-m-d");
- $cmd = "rm -v {$this->logPathPrefix}se-debug-*-{$userLogin}-*.log 2>&1";
- V::exec($cmd, $out, $ret);
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
- '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>',
- (0 === $ret) ? "All Log Files Removed" : "Error?",
- " (return code: {$ret})",
- "<br>cmd: <code>{$cmd}</code>",
- UI::h('pre', [], implode("\n", $out))
- ]));
- } catch (AlertSuccessException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
- } catch (AlertWarningException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
- } catch (Exception $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
- }
- }
- public function rmOldUserLogFilesAction() {
- session_write_close();
- try {
- $userLogin = User::getLogin();
- $today = date("Y-m-d");
- $cmd = "ls -1 {$this->logPathPrefix}se-debug-*-{$userLogin}-*.log | grep -v '{$this->logPathPrefix}se-debug-{$today}-' | xargs rm -v 2>&1";
- V::exec($cmd, $out, $ret);
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
- '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>',
- (0 === $ret) ? "Old Log Files Removed" : "Error?",
- " (return code: {$ret})",
- "<br>cmd: <code>{$cmd}</code>",
- UI::h('pre', [], implode("\n", $out))
- ]));
- } catch (AlertSuccessException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
- } catch (AlertWarningException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
- } catch (Exception $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
- }
- }
- public function rmLogFileAction() {
- session_write_close();
- try {
- $logName = $this->validateParamLogName(V::get('logName', '', $_REQUEST));
- $logPath = "{$this->logPathPrefix}se-debug-{$logName}.log";
- if (!file_exists($logPath)) throw new AlertWarningException("Log file not exists");
- unlink($logPath);
- throw new AlertSuccessException("File Removed");
- } catch (AlertSuccessException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
- } catch (AlertWarningException $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
- } catch (Exception $e) {
- $this->defaultView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
- }
- }
- public function rmAllAuthLogFilesAction() {
- session_write_close();
- try {
- $userLogin = User::getLogin();
- $today = date("Y-m-d");
- $cmd = "rm -v {$this->logPathPrefix}se-auth-*.log 2>&1";
- V::exec($cmd, $out, $ret);
- $this->authView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
- '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>',
- (0 === $ret) ? "All Log Files Removed" : "Error?",
- " (return code: {$ret})",
- "<br>cmd: <code>{$cmd}</code>",
- UI::h('pre', [], implode("\n", $out))
- ]));
- } catch (AlertSuccessException $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
- } catch (AlertWarningException $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
- } catch (Exception $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
- }
- }
- public function rmOldAuthLogFilesAction() {
- session_write_close();
- try {
- $userLogin = User::getLogin();
- $today = date("Y-m-d");
- $cmd = "ls -1 {$this->logPathPrefix}se-auth-*.log | grep -v '{$this->logPathPrefix}se-auth-{$today}-' | xargs rm -v 2>&1";
- V::exec($cmd, $out, $ret);
- $this->authView(UI::h('div', ['class'=>"alert alert-success alert-dismissible"], [
- '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>',
- (0 === $ret) ? "Old Log Files Removed" : "Error?",
- " (return code: {$ret})",
- "<br>cmd: <code>{$cmd}</code>",
- UI::h('pre', [], implode("\n", $out))
- ]));
- } catch (AlertSuccessException $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
- } catch (AlertWarningException $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
- } catch (Exception $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
- }
- }
- public function rmAuthLogFileAction() {
- session_write_close();
- try {
- $logName = $this->validateParamLogName(V::get('logName', '', $_REQUEST));
- $logPath = "{$this->logPathPrefix}se-auth-{$logName}.log";
- if (!file_exists($logPath)) throw new AlertWarningException("Log file not exists");
- unlink($logPath);
- throw new AlertSuccessException("File Removed");
- } catch (AlertSuccessException $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-success"], $e->getMessage()));
- } catch (AlertWarningException $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-warning"], $e->getMessage()));
- } catch (Exception $e) {
- $this->authView(UI::h('div', ['class'=>"alert alert-danger"], $e->getMessage()));
- }
- }
- }
|