AdminLog.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace app\admin\model;
  3. use app\admin\library\Auth;
  4. use think\Model;
  5. use think\Loader;
  6. class AdminLog extends Model
  7. {
  8. // 开启自动写入时间戳字段
  9. protected $autoWriteTimestamp = 'int';
  10. // 定义时间戳字段名
  11. protected $createTime = 'createtime';
  12. protected $updateTime = '';
  13. //自定义日志标题
  14. protected static $title = '';
  15. //自定义日志内容
  16. protected static $content = '';
  17. public static function setTitle($title)
  18. {
  19. self::$title = $title;
  20. }
  21. public static function setContent($content)
  22. {
  23. self::$content = $content;
  24. }
  25. public static function record($title = '')
  26. {
  27. $auth = Auth::instance();
  28. $admin_id = $auth->isLogin() ? $auth->id : 0;
  29. $username = $auth->isLogin() ? $auth->username : __('Unknown');
  30. $content = self::$content;
  31. if (!$content) {
  32. $content = request()->param('', null, 'trim,strip_tags,htmlspecialchars');
  33. foreach ($content as $k => $v) {
  34. if (is_string($v) && strlen($v) > 200 || stripos($k, 'password') !== false) {
  35. unset($content[$k]);
  36. }
  37. }
  38. }
  39. $title = self::$title;
  40. if (!$title) {
  41. $title = [];
  42. $controllername = Loader::parseName(request()->controller());
  43. $actionname = strtolower(request()->action());
  44. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  45. $breadcrumb = Auth::instance()->getBreadcrumb($path);
  46. foreach ($breadcrumb as $k => $v) {
  47. $title[] = $v['title'];
  48. }
  49. $title = implode(' / ', $title);
  50. }
  51. self::create([
  52. 'title' => $title,
  53. 'content' => !is_scalar($content) ? json_encode($content) : $content,
  54. 'url' => substr(request()->url(), 0, 1500),
  55. 'admin_id' => $admin_id,
  56. 'username' => $username,
  57. 'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
  58. 'ip' => request()->ip()
  59. ]);
  60. }
  61. public function admin()
  62. {
  63. return $this->belongsTo('Admin', 'admin_id')->setEagerlyType(0);
  64. }
  65. }