]> BookStack Code Mirror - bookstack/blob - app/Actions/ActivityService.php
Typo.
[bookstack] / app / Actions / ActivityService.php
1 <?php
2
3 namespace BookStack\Actions;
4
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Interfaces\Loggable;
11 use Illuminate\Database\Eloquent\Builder;
12 use Illuminate\Database\Eloquent\Relations\Relation;
13 use Illuminate\Support\Facades\Log;
14
15 class ActivityService
16 {
17     protected $activity;
18     protected $permissionService;
19
20     public function __construct(Activity $activity, PermissionService $permissionService)
21     {
22         $this->activity = $activity;
23         $this->permissionService = $permissionService;
24     }
25
26     /**
27      * Add activity data to database for an entity.
28      */
29     public function addForEntity(Entity $entity, string $type)
30     {
31         $activity = $this->newActivityForUser($type);
32         $entity->activity()->save($activity);
33         $this->setNotification($type);
34     }
35
36     /**
37      * Add a generic activity event to the database.
38      *
39      * @param string|Loggable $detail
40      */
41     public function add(string $type, $detail = '')
42     {
43         if ($detail instanceof Loggable) {
44             $detail = $detail->logDescriptor();
45         }
46
47         $activity = $this->newActivityForUser($type);
48         $activity->detail = $detail;
49         $activity->save();
50         $this->setNotification($type);
51     }
52
53     /**
54      * Get a new activity instance for the current user.
55      */
56     protected function newActivityForUser(string $type): Activity
57     {
58         return $this->activity->newInstance()->forceFill([
59             'type'     => strtolower($type),
60             'user_id'  => user()->id,
61         ]);
62     }
63
64     /**
65      * Removes the entity attachment from each of its activities
66      * and instead uses the 'extra' field with the entities name.
67      * Used when an entity is deleted.
68      */
69     public function removeEntity(Entity $entity)
70     {
71         $entity->activity()->update([
72             'detail'       => $entity->name,
73             'entity_id'    => null,
74             'entity_type'  => null,
75         ]);
76     }
77
78     /**
79      * Gets the latest activity.
80      */
81     public function latest(int $count = 20, int $page = 0): array
82     {
83         $activityList = $this->permissionService
84             ->filterRestrictedEntityRelations($this->activity->newQuery(), 'activities', 'entity_id', 'entity_type')
85             ->orderBy('created_at', 'desc')
86             ->with(['user', 'entity'])
87             ->skip($count * $page)
88             ->take($count)
89             ->get();
90
91         return $this->filterSimilar($activityList);
92     }
93
94     /**
95      * Gets the latest activity for an entity, Filtering out similar
96      * items to prevent a message activity list.
97      */
98     public function entityActivity(Entity $entity, int $count = 20, int $page = 1): array
99     {
100         /** @var [string => int[]] $queryIds */
101         $queryIds = [$entity->getMorphClass() => [$entity->id]];
102
103         if ($entity->isA('book')) {
104             $queryIds[(new Chapter())->getMorphClass()] = $entity->chapters()->visible()->pluck('id');
105         }
106         if ($entity->isA('book') || $entity->isA('chapter')) {
107             $queryIds[(new Page())->getMorphClass()] = $entity->pages()->visible()->pluck('id');
108         }
109
110         $query = $this->activity->newQuery();
111         $query->where(function (Builder $query) use ($queryIds) {
112             foreach ($queryIds as $morphClass => $idArr) {
113                 $query->orWhere(function (Builder $innerQuery) use ($morphClass, $idArr) {
114                     $innerQuery->where('entity_type', '=', $morphClass)
115                         ->whereIn('entity_id', $idArr);
116                 });
117             }
118         });
119
120         $activity = $query->orderBy('created_at', 'desc')
121             ->with(['entity' => function (Relation $query) {
122                 $query->withTrashed();
123             }, 'user.avatar'])
124             ->skip($count * ($page - 1))
125             ->take($count)
126             ->get();
127
128         return $this->filterSimilar($activity);
129     }
130
131     /**
132      * Get latest activity for a user, Filtering out similar items.
133      */
134     public function userActivity(User $user, int $count = 20, int $page = 0): array
135     {
136         $activityList = $this->permissionService
137             ->filterRestrictedEntityRelations($this->activity->newQuery(), 'activities', 'entity_id', 'entity_type')
138             ->orderBy('created_at', 'desc')
139             ->where('user_id', '=', $user->id)
140             ->skip($count * $page)
141             ->take($count)
142             ->get();
143
144         return $this->filterSimilar($activityList);
145     }
146
147     /**
148      * Filters out similar activity.
149      *
150      * @param Activity[] $activities
151      *
152      * @return array
153      */
154     protected function filterSimilar(iterable $activities): array
155     {
156         $newActivity = [];
157         $previousItem = null;
158
159         foreach ($activities as $activityItem) {
160             if (!$previousItem || !$activityItem->isSimilarTo($previousItem)) {
161                 $newActivity[] = $activityItem;
162             }
163
164             $previousItem = $activityItem;
165         }
166
167         return $newActivity;
168     }
169
170     /**
171      * Flashes a notification message to the session if an appropriate message is available.
172      */
173     protected function setNotification(string $type)
174     {
175         $notificationTextKey = 'activities.' . $type . '_notification';
176         if (trans()->has($notificationTextKey)) {
177             $message = trans($notificationTextKey);
178             session()->flash('success', $message);
179         }
180     }
181
182     /**
183      * Log out a failed login attempt, Providing the given username
184      * as part of the message if the '%u' string is used.
185      */
186     public function logFailedLogin(string $username)
187     {
188         $message = config('logging.failed_login.message');
189         if (!$message) {
190             return;
191         }
192
193         $message = str_replace('%u', $username, $message);
194         $channel = config('logging.failed_login.channel');
195         Log::channel($channel)->warning($message);
196     }
197 }