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']})",
"
cmd: {$uiLogFiles['cmd']}",
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})",
"
cmd: {$cmd}",
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);
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' => '' . $dbg['date'] . '',
'@style[date]' => "width:1%",
'type' => $dbg['type'],
'@style[type]' => "width:1%",
'msg' => UI::h('div', ['style'=>'max-width:360px; overflow-x:auto'], $dbg['msg']),
// 'log' => (!empty($dbg['log'])) ? json_encode($dbg['log']) : '',
'@style[msg]' => "width:360px",
'log' => UI::h('div', [], [
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('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, 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 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}
";
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"], [
'',
(0 === $ret) ? "All Log Files Removed" : "Error?",
" (return code: {$ret})",
"
cmd: {$cmd}",
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"], [
'',
(0 === $ret) ? "Old Log Files Removed" : "Error?",
" (return code: {$ret})",
"
cmd: {$cmd}",
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"], [
'',
(0 === $ret) ? "All Log Files Removed" : "Error?",
" (return code: {$ret})",
"
cmd: {$cmd}",
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"], [
'',
(0 === $ret) ? "Old Log Files Removed" : "Error?",
" (return code: {$ret})",
"
cmd: {$cmd}",
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"], [
'',
(0 === $ret) ? "All Log Files Removed" : "Error?",
" (return code: {$ret})",
"
cmd: {$cmd}",
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"], [
'',
(0 === $ret) ? "Old Log Files Removed" : "Error?",
" (return code: {$ret})",
"
cmd: {$cmd}",
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()));
}
}
}