AdminLog.php 2.0 KB

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