3 namespace BookStack\Activity\Tools;
5 use BookStack\Activity\DispatchWebhookJob;
6 use BookStack\Activity\Models\Activity;
7 use BookStack\Activity\Models\Loggable;
8 use BookStack\Activity\Models\Webhook;
9 use BookStack\Entities\Models\Entity;
10 use BookStack\Facades\Theme;
11 use BookStack\Theming\ThemeEvents;
12 use Illuminate\Database\Eloquent\Builder;
13 use Illuminate\Support\Facades\Log;
18 * Add a generic activity event to the database.
20 * @param string|Loggable $detail
22 public function add(string $type, $detail = '')
24 $detailToStore = ($detail instanceof Loggable) ? $detail->logDescriptor() : $detail;
26 $activity = $this->newActivityForUser($type);
27 $activity->detail = $detailToStore;
29 if ($detail instanceof Entity) {
30 $activity->entity_id = $detail->id;
31 $activity->entity_type = $detail->getMorphClass();
36 $this->setNotification($type);
37 $this->dispatchWebhooks($type, $detail);
38 Theme::dispatch(ThemeEvents::ACTIVITY_LOGGED, $type, $detail);
42 * Get a new activity instance for the current user.
44 protected function newActivityForUser(string $type): Activity
46 return (new Activity())->forceFill([
47 'type' => strtolower($type),
48 'user_id' => user()->id,
49 'ip' => IpFormatter::fromCurrentRequest()->format(),
54 * Removes the entity attachment from each of its activities
55 * and instead uses the 'extra' field with the entities name.
56 * Used when an entity is deleted.
58 public function removeEntity(Entity $entity)
60 $entity->activity()->update([
61 'detail' => $entity->name,
63 'entity_type' => null,
68 * Flashes a notification message to the session if an appropriate message is available.
70 protected function setNotification(string $type): void
72 $notificationTextKey = 'activities.' . $type . '_notification';
73 if (trans()->has($notificationTextKey)) {
74 $message = trans($notificationTextKey);
75 session()->flash('success', $message);
80 * @param string|Loggable $detail
82 protected function dispatchWebhooks(string $type, $detail): void
84 $webhooks = Webhook::query()
85 ->whereHas('trackedEvents', function (Builder $query) use ($type) {
86 $query->where('event', '=', $type)
87 ->orWhere('event', '=', 'all');
89 ->where('active', '=', true)
92 foreach ($webhooks as $webhook) {
93 dispatch(new DispatchWebhookJob($webhook, $type, $detail));
98 * Log out a failed login attempt, Providing the given username
99 * as part of the message if the '%u' string is used.
101 public function logFailedLogin(string $username)
103 $message = config('logging.failed_login.message');
108 $message = str_replace('%u', $username, $message);
109 $channel = config('logging.failed_login.channel');
110 Log::channel($channel)->warning($message);