| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397 |
- <?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 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)) {
- UI::alert('info', "is POST - history.pushState");
- echo UI::h('script', [], "
- history.replaceState(null, 'Debug', window.location.href);
- ");
- }
- try {
- echo UI::h('h1', [], [
- "Debug ",
- UI::h('small', [], "(" . (DBG::isActive() ? "włączony" : "wyłączony") . ") "),
- UI::hButtonPost((DBG::isActive()) ? "Wyłącz debug" : "Włącz debug", [
- 'class' => "btn-success btn-xs",
- 'data' => [
- '_route' => 'Debug',
- '_task' => DBG::isActive() ? 'deactivateDebug' : 'activateDebug'
- ]
- ])
- ]);
- 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' => "index.php?_route=Debug&_task=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 ('/tmp/se-debug-' != substr($logFile, 0, strlen('/tmp/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('/tmp/se-debug-'), -4);
- list($logYear, $logMonth, $logDay, $logUser, $logIP, $logSessId, $logReqDate) = explode('-', $logName);
- return [
- '#' => UI::h('a', [
- 'href' => "index.php?_route=Debug&_task=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("/tmp/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 viewLatestUserLogAction() {
- session_write_close();
- UI::gora();
- // UI::menu();
- UI::setTitle("Debug");
- echo UI::h('div', ['class'=>'container'], [
- UI::h('a', ['href'=>'index.php?_route=Debug'], "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 /tmp/se-debug-{$today}-*.log | tail -5";
- V::exec($cmd, $out, $ret);
- if (empty($out)) {
- UI::alert('warning', "No logs today. Searching previous...");
- $cmd = "ls -1rt /tmp/se-debug-*.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 ('/tmp/se-debug-' != substr($logName, 0, strlen('/tmp/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('/tmp/se-debug-'), -1 * strlen('.log'));
- }
- }
- $this->printLogFileView($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'=>'index.php?_route=Debug'], "wróć")
- ]);
- try {
- $logName = V::get('name', '', $_REQUEST);
- $this->printLogFileView($logName);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- }
- UI::dol();
- }
- public function printLogFileView($logName) {
- if (empty($logName)) throw new Exception("Missing name");
- $logName = $this->validateParamLogName($logName);
- $logPath = "/tmp/se-debug-{$logName}.log";
- if (!file_exists($logPath)) throw new Exception("Log file not exists");
- $content = file_get_contents($logPath);
- UI::table([
- 'cols' => [
- 'date',
- 'type',
- 'msg',
- 'log',
- 'trace',
- ],
- 'cols_help' => [
- 'trace' => "Cick to show trace"
- ],
- 'rows' => array_map(
- function ($line) {
- 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()
- ];
- }
- return [
- 'date' => '<nobr>' . $dbg['date'] . '</nobr>',
- 'type' => $dbg['type'],
- 'msg' => $dbg['msg'],
- // 'log' => (!empty($dbg['log'])) ? json_encode($dbg['log']) : '',
- 'log' => 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)",
- 'style' => "cursor:pointer"
- ], str_replace(array('\n', '\t'), ' ', substr(htmlspecialchars(json_encode($dbg['log'])), 0, 100)) . ' ...'
- ),
- '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']}"
- : '...'
- ),
- ];
- },
- explode("\n", $content)
- ),
- ]);
- echo UI::h('script', [], "
- function p5DBG__showLogTrace(n, e) {
- if (!e) return false;
- if (e.target && 'PRE' == e.target.tagName) return false;
- if (n.lastChild.tagName == 'PRE') {
- if ('none' == n.lastChild.style.display) {
- n.lastChild.style.display = 'block'
- } else {
- n.lastChild.style.display = 'none'
- }
- } else {
- var pre = document.createElement('pre')
- pre.appendChild( document.createTextNode(n.title) )
- n.appendChild(pre)
- }
- }
- ");
- }
- 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 /tmp/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 /tmp/se-debug-*.log | grep -v '/tmp/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 /tmp/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 /tmp/se-debug-*-{$userLogin}-*.log | grep -v '/tmp/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 = "/tmp/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()));
- }
- }
- }
|