3 namespace BookStack\Actions;
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Interfaces\Loggable;
7 use Illuminate\Database\Eloquent\Builder;
8 use Illuminate\Support\Facades\Log;
13 * Add a generic activity event to the database.
15 * @param string|Loggable $detail
17 public function add(string $type, $detail = '')
19 $detailToStore = ($detail instanceof Loggable) ? $detail->logDescriptor() : $detail;
21 $activity = $this->newActivityForUser($type);
22 $activity->detail = $detailToStore;
24 if ($detail instanceof Entity) {
25 $activity->entity_id = $detail->id;
26 $activity->entity_type = $detail->getMorphClass();
30 $this->setNotification($type);
31 $this->dispatchWebhooks($type, $detail);
35 * Get a new activity instance for the current user.
37 protected function newActivityForUser(string $type): Activity
39 $ip = request()->ip() ?? '';
41 return (new Activity())->forceFill([
42 'type' => strtolower($type),
43 'user_id' => user()->id,
44 'ip' => config('app.env') === 'demo' ? '127.0.0.1' : $ip,
49 * Removes the entity attachment from each of its activities
50 * and instead uses the 'extra' field with the entities name.
51 * Used when an entity is deleted.
53 public function removeEntity(Entity $entity)
55 $entity->activity()->update([
56 'detail' => $entity->name,
58 'entity_type' => null,
63 * Flashes a notification message to the session if an appropriate message is available.
65 protected function setNotification(string $type): void
67 $notificationTextKey = 'activities.' . $type . '_notification';
68 if (trans()->has($notificationTextKey)) {
69 $message = trans($notificationTextKey);
70 session()->flash('success', $message);
75 * @param string|Loggable $detail
77 protected function dispatchWebhooks(string $type, $detail): void
79 $webhooks = Webhook::query()
80 ->whereHas('trackedEvents', function (Builder $query) use ($type) {
81 $query->where('event', '=', $type)
82 ->orWhere('event', '=', 'all');
84 ->where('active', '=', true)
87 foreach ($webhooks as $webhook) {
88 dispatch(new DispatchWebhookJob($webhook, $type, $detail));
93 * Log out a failed login attempt, Providing the given username
94 * as part of the message if the '%u' string is used.
96 public function logFailedLogin(string $username)
98 $message = config('logging.failed_login.message');
103 $message = str_replace('%u', $username, $message);
104 $channel = config('logging.failed_login.channel');
105 Log::channel($channel)->warning($message);