3 namespace BookStack\Actions;
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Facades\Theme;
7 use BookStack\Interfaces\Loggable;
8 use BookStack\Theming\ThemeEvents;
9 use Illuminate\Database\Eloquent\Builder;
10 use Illuminate\Support\Facades\Log;
15 * Add a generic activity event to the database.
17 * @param string|Loggable $detail
19 public function add(string $type, $detail = '')
21 $detailToStore = ($detail instanceof Loggable) ? $detail->logDescriptor() : $detail;
23 $activity = $this->newActivityForUser($type);
24 $activity->detail = $detailToStore;
26 if ($detail instanceof Entity) {
27 $activity->entity_id = $detail->id;
28 $activity->entity_type = $detail->getMorphClass();
33 $this->setNotification($type);
34 $this->dispatchWebhooks($type, $detail);
35 Theme::dispatch(ThemeEvents::ACTIVITY_LOGGED, $type, $detail);
39 * Get a new activity instance for the current user.
41 protected function newActivityForUser(string $type): Activity
43 $ip = request()->ip() ?? '';
45 return (new Activity())->forceFill([
46 'type' => strtolower($type),
47 'user_id' => user()->id,
48 'ip' => config('app.env') === 'demo' ? '127.0.0.1' : $ip,
53 * Removes the entity attachment from each of its activities
54 * and instead uses the 'extra' field with the entities name.
55 * Used when an entity is deleted.
57 public function removeEntity(Entity $entity)
59 $entity->activity()->update([
60 'detail' => $entity->name,
62 'entity_type' => null,
67 * Flashes a notification message to the session if an appropriate message is available.
69 protected function setNotification(string $type): void
71 $notificationTextKey = 'activities.' . $type . '_notification';
72 if (trans()->has($notificationTextKey)) {
73 $message = trans($notificationTextKey);
74 session()->flash('success', $message);
79 * @param string|Loggable $detail
81 protected function dispatchWebhooks(string $type, $detail): void
83 $webhooks = Webhook::query()
84 ->whereHas('trackedEvents', function (Builder $query) use ($type) {
85 $query->where('event', '=', $type)
86 ->orWhere('event', '=', 'all');
88 ->where('active', '=', true)
91 foreach ($webhooks as $webhook) {
92 dispatch(new DispatchWebhookJob($webhook, $type, $detail));
97 * Log out a failed login attempt, Providing the given username
98 * as part of the message if the '%u' string is used.
100 public function logFailedLogin(string $username)
102 $message = config('logging.failed_login.message');
107 $message = str_replace('%u', $username, $message);
108 $channel = config('logging.failed_login.channel');
109 Log::channel($channel)->warning($message);