Piotr Labudda vor 9 Jahren
Ursprung
Commit
fffb640993
2 geänderte Dateien mit 283 neuen und 34 gelöschten Zeilen
  1. 53 16
      SE/se-lib/DBG.php
  2. 230 18
      SE/se-lib/Route/Debug.php

+ 53 - 16
SE/se-lib/DBG.php

@@ -236,17 +236,36 @@ class DBG {
 		if (!self::isActive()) return;
 		if ('Debug' == V::get('_route', '', $_REQUEST) && !V::get('DBG', '', $_REQUEST)) return;
 		static $_firstRun = true;
+		$logFileName = '/tmp/se-debug-' . implode('-', [
+			date("Y-m-d"),
+			User::getLogin(),
+			Request::getUserIp(),
+			substr(session_id(), 0, 6),
+			V::get('REQUEST_TIME', '', $_SERVER)// [REQUEST_TIME] => 1485770466
+		]) . '.log';
 		if ($_firstRun) {
 			$_firstRun = false;
-			self::_log([
-				'msg' => V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER),
-				'POST' => $_POST,
-				'GET' => $_GET,
-			]);
+			$firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
+			self::_log([ 'POST' => $_POST, 'GET' => $_GET ], 'array', $firstMsg, $logFileName);
 		}
-		self::_log($mixedArg, $type, $msg);
+		self::_log($mixedArg, $type, $msg, $logFileName);
 	}
-	public static function _log($mixedArg, $type = '', $msg = '') {
+	public static function logAuth($mixedArg, $msg = '') {
+		if ('Debug' == V::get('_route', '', $_REQUEST) && !V::get('DBG', '', $_REQUEST)) return;
+		static $_firstRun = true;
+		$logFileName = '/tmp/se-auth-' . implode('-', [
+			date("Y-m-d"),
+			Request::getUserIp(),
+			V::get('REQUEST_TIME', '', $_SERVER)// [REQUEST_TIME] => 1485770466
+		]) . '.log';
+		if ($_firstRun) {
+			$_firstRun = false;
+			$firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
+			self::_log(['POST' => $_POST, 'GET' => $_GET], 'array', $firstMsg, $logFileName);
+		}
+		self::_log($mixedArg, $type = 'array', $msg, $logFileName);
+	}
+	public static function _log($mixedArg, $type, $msg, $logFileName) {
 		// * TODO: debug to file based on session_id (/tmp/se-debug-{$date("Y-m-d")}-{$login}_{$ip}_{$session_id}.log)
 		$logInfo = [
 			'date' => date("Y-m-d H:i:s"),
@@ -272,8 +291,13 @@ class DBG {
 				$logInfo['log'] = $mixedArg;
 			} else {
 				if (empty($logInfo['type'])) $logInfo['type'] = 'string';
-				$logInfo['msg'] = $mixedArg;
-				$logInfo['log'] = '';
+				if (empty($msg)) {
+					$logInfo['msg'] = $mixedArg;
+					$logInfo['log'] = '';
+				} else {
+					$logInfo['msg'] = $msg;
+					$logInfo['log'] = $mixedArg;
+				}
 			}
 			ob_start();
 			debug_print_backtrace();
@@ -299,14 +323,27 @@ class DBG {
 		error_log(
 			json_encode($logInfo) . "\n"
 			, 3
-			, '/tmp/se-debug-' . implode('-', [
-				date("Y-m-d"),
-				User::getLogin(),
-				Request::getUserIp(),
-				substr(session_id(), 0, 6),
-				V::get('REQUEST_TIME', '', $_SERVER)// [REQUEST_TIME] => 1485770466
-			]) . '.log'
+			, $logFileName
 		);
 	}
 
+	public static function simpleLog($type, $msg) {
+		static $_idRequest = null;
+		$logFileName = "/tmp/se-log-{$type}.tsv.log";
+		if (null === $_idRequest) {
+			$_idRequest = substr(md5(date("Y-m-d") . Request::getUserIp() . V::get('REQUEST_TIME', '', $_SERVER)), 0, 6);
+			$firstMsg = V::get('REQUEST_METHOD', '', $_SERVER) . " " . V::get('REQUEST_URI', '', $_SERVER);
+			self::_simpleLogFile($firstMsg, $_idRequest, $logFileName);
+			self::_simpleLogFile("USER IP: " . Request::getUserIp(), $_idRequest, $logFileName);
+		}
+		self::_simpleLogFile($msg, $_idRequest, $logFileName);
+	}
+	public static function _simpleLogFile($msg, $idRequest, $logFileName) {
+		error_log(implode("\t", [
+			date("Y-m-d H:i:s"),
+			$idRequest,
+			$msg
+		]) . "\n", 3, $logFileName);
+	}
+
 }

+ 230 - 18
SE/se-lib/Route/Debug.php

@@ -28,23 +28,28 @@ class Route_Debug extends RouteBase {
     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);
-      ");
-    }
+    if (!empty($_POST)) echo UI::h('script', [], "history.replaceState(null, 'Debug', window.location.href);");
     try {
-      echo UI::h('h1', [], [
+      echo UI::h('div', ['class'=>"breadcrumb"], [
         "Debug ",
-        UI::h('small', [], "(" . (DBG::isActive() ? "włączony" : "wyłączony") . ") "),
+        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"),
       ]);
       echo $flashMsg;
 
@@ -58,7 +63,7 @@ class Route_Debug extends RouteBase {
 
       UI::table([
         'caption' => "Log Files " . UI::h('a', [
-          'href' => "index.php?_route=Debug&_task=viewLatestUserLog",
+          'href' => $this->getLink("viewLatestUserLog"),
           'class' => "btn btn-xs btn-primary"
         ], "Pokaż ostatni log") . " " . UI::hButtonPost("Usuń wszystkie swoje pliki", [
           'class' => "btn-danger btn-xs",
@@ -92,7 +97,7 @@ class Route_Debug extends RouteBase {
 
               return [
                 '#' => UI::h('a', [
-                  'href' => "index.php?_route=Debug&_task=viewLog&name={$logName}"
+                  'href' => $this->getLink("viewLog", ['name' => $logName])
                 ], "Pokaż"),
                 'request date' => ($logReqDate) ? date("Y-m-d H:i:s", $logReqDate) : '',// 1485775975
                 'file' => $logFile,
@@ -133,13 +138,104 @@ class Route_Debug extends RouteBase {
     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 ('/tmp/se-auth-' != substr($logFile, 0, strlen('/tmp/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('/tmp/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("/tmp/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");
     echo UI::h('div', ['class'=>'container'], [
-      UI::h('a', ['href'=>'index.php?_route=Debug'], "wróć")
+      UI::h('a', ['href'=>$this->getLink()], "wróć")
     ]);
     try {
       $filerUser = V::get('user', '', $_REQUEST);// TODO: show another user debug
@@ -167,7 +263,47 @@ class Route_Debug extends RouteBase {
           $logName = substr($logName, strlen('/tmp/se-debug-'), -1 * strlen('.log'));
         }
       }
-      $this->printLogFileView($logName);
+      $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 /tmp/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 /tmp/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 ('/tmp/se-auth-' != substr($logName, 0, strlen('/tmp/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('/tmp/se-auth-'), -1 * strlen('.log'));
+        }
+      }
+      $this->printLogFileView('auth', $logName);
     } catch (Exception $e) {
       UI::alert('danger', $e->getMessage());
     }
@@ -179,20 +315,36 @@ class Route_Debug extends RouteBase {
     // UI::menu();
     UI::setTitle("Debug");
     echo UI::h('div', ['class'=>'container'], [
-      UI::h('a', ['href'=>'index.php?_route=Debug'], "wróć")
+      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($logName);
+      $this->printLogFileView('auth', $logName);
     } catch (Exception $e) {
       UI::alert('danger', $e->getMessage());
     }
     UI::dol();
   }
-  public function printLogFileView($logName) {
+  public function printLogFileView($type, $logName) {
     if (empty($logName)) throw new Exception("Missing name");
     $logName = $this->validateParamLogName($logName);
-    $logPath = "/tmp/se-debug-{$logName}.log";
+    $logPath = "/tmp/se-{$type}-{$logName}.log";
     if (!file_exists($logPath)) throw new Exception("Log file not exists");
     $content = file_get_contents($logPath);
     UI::table([
@@ -260,7 +412,7 @@ class Route_Debug extends RouteBase {
           }
         } else {
           var pre = document.createElement('pre')
-          pre.appendChild( document.createTextNode(n.title) )
+          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)
@@ -403,5 +555,65 @@ class Route_Debug extends RouteBase {
       $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 /tmp/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">&times;</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 /tmp/se-auth-*.log | grep -v '/tmp/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">&times;</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 = "/tmp/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()));
+    }
+  }
 
 }