WebOrbiton
v1.0.0.0

StocketBase

46 lines · 1.7 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. final class ActivityLog
  6. {
  7. public static function isEnabled(): bool
  8. {
  9. try {
  10. $statement = Database::site()->prepare('SELECT setting_value FROM site_settings WHERE setting_key = :key LIMIT 1');
  11. $statement->execute(['key' => 'activity_log_enabled']);
  12. ​
  13. return $statement->fetchColumn() === '1';
  14. } catch (PDOException $e) {
  15. return false;
  16. }
  17. }
  18. ​
  19. public static function record(string $action, ?string $entityType = null, ?int $entityId = null, ?string $details = null, bool $asSystem = false): void
  20. {
  21. if (!self::isEnabled()) {
  22. return;
  23. }
  24. ​
  25. $user = !$asSystem && class_exists('Auth', false) ? Auth::user() : null;
  26. ​
  27. try {
  28. $statement = Database::site()->prepare(
  29. 'INSERT INTO activity_log (user_id, user_name, action, entity_type, entity_id, details, ip_address)
  30. VALUES (:user_id, :user_name, :action, :entity_type, :entity_id, :details, :ip)'
  31. );
  32. $statement->execute([
  33. 'user_id' => $user['id'] ?? null,
  34. 'user_name' => mb_substr((string) ($user['display_name'] ?? 'System'), 0, 120),
  35. 'action' => mb_substr($action, 0, 60),
  36. 'entity_type' => $entityType,
  37. 'entity_id' => $entityId,
  38. 'details' => $details !== null ? mb_substr($details, 0, 500) : null,
  39. 'ip' => mb_substr((string) ($_SERVER['REMOTE_ADDR'] ?? ''), 0, 45),
  40. ]);
  41. } catch (PDOException $e) {
  42. error_log('StocketBase: could not write activity log: ' . $e->getMessage());
  43. }
  44. }
  45. }
  46. ​