3 namespace BookStack\Actions;
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Interfaces\Loggable;
8 use Illuminate\Database\Eloquent\Builder;
9 use Illuminate\Support\Facades\Log;
13 protected $permissionService;
15 public function __construct(PermissionService $permissionService)
17 $this->permissionService = $permissionService;
21 * Add a generic activity event to the database.
23 * @param string|Loggable $detail
25 public function add(string $type, $detail = '')
27 $detailToStore = ($detail instanceof Loggable) ? $detail->logDescriptor() : $detail;
29 $activity = $this->newActivityForUser($type);
30 $activity->detail = $detailToStore;
32 if ($detail instanceof Entity) {
33 $activity->entity_id = $detail->id;
34 $activity->entity_type = $detail->getMorphClass();
38 $this->setNotification($type);
39 $this->dispatchWebhooks($type, $detail);
43 * Get a new activity instance for the current user.
45 protected function newActivityForUser(string $type): Activity
47 $ip = request()->ip() ?? '';
49 return (new Activity())->forceFill([
50 'type' => strtolower($type),
51 'user_id' => user()->id,
52 'ip' => config('app.env') === 'demo' ? '127.0.0.1' : $ip,
57 * Removes the entity attachment from each of its activities
58 * and instead uses the 'extra' field with the entities name.
59 * Used when an entity is deleted.
61 public function removeEntity(Entity $entity)
63 $entity->activity()->update([
64 'detail' => $entity->name,
66 'entity_type' => null,
71 * Flashes a notification message to the session if an appropriate message is available.
73 protected function setNotification(string $type): void
75 $notificationTextKey = 'activities.' . $type . '_notification';
76 if (trans()->has($notificationTextKey)) {
77 $message = trans($notificationTextKey);
78 session()->flash('success', $message);
83 * @param string|Loggable $detail
85 protected function dispatchWebhooks(string $type, $detail): void
87 $webhooks = Webhook::query()
88 ->whereHas('trackedEvents', function(Builder $query) use ($type) {
89 $query->where('event', '=', $type)
90 ->orWhere('event', '=', 'all');
92 ->where('active', '=', true)
95 foreach ($webhooks as $webhook) {
96 dispatch(new DispatchWebhookJob($webhook, $type, $detail));
101 * Log out a failed login attempt, Providing the given username
102 * as part of the message if the '%u' string is used.
104 public function logFailedLogin(string $username)
106 $message = config('logging.failed_login.message');
111 $message = str_replace('%u', $username, $message);
112 $channel = config('logging.failed_login.channel');
113 Log::channel($channel)->warning($message);