]> BookStack Code Mirror - bookstack/blob - app/Actions/ActivityService.php
Fixed occurances of altered titles in search results
[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         $ip = request()->ip() ?? '';
59
60         return $this->activity->newInstance()->forceFill([
61             'type'     => strtolower($type),
62             'user_id'  => user()->id,
63             'ip'       => config('app.env') === 'demo' ? '127.0.0.1' : $ip,
64         ]);
65     }
66
67     /**
68      * Removes the entity attachment from each of its activities
69      * and instead uses the 'extra' field with the entities name.
70      * Used when an entity is deleted.
71      */
72     public function removeEntity(Entity $entity)
73     {
74         $entity->activity()->update([
75             'detail'       => $entity->name,
76             'entity_id'    => null,
77             'entity_type'  => null,
78         ]);
79     }
80
81     /**
82      * Gets the latest activity.
83      */
84     public function latest(int $count = 20, int $page = 0): array
85     {
86         $activityList = $this->permissionService
87             ->filterRestrictedEntityRelations($this->activity->newQuery(), 'activities', 'entity_id', 'entity_type')
88             ->orderBy('created_at', 'desc')
89             ->with(['user', 'entity'])
90             ->skip($count * $page)
91             ->take($count)
92             ->get();
93
94         return $this->filterSimilar($activityList);
95     }
96
97     /**
98      * Gets the latest activity for an entity, Filtering out similar
99      * items to prevent a message activity list.
100      */
101     public function entityActivity(Entity $entity, int $count = 20, int $page = 1): array
102     {
103         /** @var [string => int[]] $queryIds */
104         $queryIds = [$entity->getMorphClass() => [$entity->id]];
105
106         if ($entity->isA('book')) {
107             $queryIds[(new Chapter())->getMorphClass()] = $entity->chapters()->visible()->pluck('id');
108         }
109         if ($entity->isA('book') || $entity->isA('chapter')) {
110             $queryIds[(new Page())->getMorphClass()] = $entity->pages()->visible()->pluck('id');
111         }
112
113         $query = $this->activity->newQuery();
114         $query->where(function (Builder $query) use ($queryIds) {
115             foreach ($queryIds as $morphClass => $idArr) {
116                 $query->orWhere(function (Builder $innerQuery) use ($morphClass, $idArr) {
117                     $innerQuery->where('entity_type', '=', $morphClass)
118                         ->whereIn('entity_id', $idArr);
119                 });
120             }
121         });
122
123         $activity = $query->orderBy('created_at', 'desc')
124             ->with(['entity' => function (Relation $query) {
125                 $query->withTrashed();
126             }, 'user.avatar'])
127             ->skip($count * ($page - 1))
128             ->take($count)
129             ->get();
130
131         return $this->filterSimilar($activity);
132     }
133
134     /**
135      * Get latest activity for a user, Filtering out similar items.
136      */
137     public function userActivity(User $user, int $count = 20, int $page = 0): array
138     {
139         $activityList = $this->permissionService
140             ->filterRestrictedEntityRelations($this->activity->newQuery(), 'activities', 'entity_id', 'entity_type')
141             ->orderBy('created_at', 'desc')
142             ->where('user_id', '=', $user->id)
143             ->skip($count * $page)
144             ->take($count)
145             ->get();
146
147         return $this->filterSimilar($activityList);
148     }
149
150     /**
151      * Filters out similar activity.
152      *
153      * @param Activity[] $activities
154      *
155      * @return array
156      */
157     protected function filterSimilar(iterable $activities): array
158     {
159         $newActivity = [];
160         $previousItem = null;
161
162         foreach ($activities as $activityItem) {
163             if (!$previousItem || !$activityItem->isSimilarTo($previousItem)) {
164                 $newActivity[] = $activityItem;
165             }
166
167             $previousItem = $activityItem;
168         }
169
170         return $newActivity;
171     }
172
173     /**
174      * Flashes a notification message to the session if an appropriate message is available.
175      */
176     protected function setNotification(string $type)
177     {
178         $notificationTextKey = 'activities.' . $type . '_notification';
179         if (trans()->has($notificationTextKey)) {
180             $message = trans($notificationTextKey);
181             session()->flash('success', $message);
182         }
183     }
184
185     /**
186      * Log out a failed login attempt, Providing the given username
187      * as part of the message if the '%u' string is used.
188      */
189     public function logFailedLogin(string $username)
190     {
191         $message = config('logging.failed_login.message');
192         if (!$message) {
193             return;
194         }
195
196         $message = str_replace('%u', $username, $message);
197         $channel = config('logging.failed_login.channel');
198         Log::channel($channel)->warning($message);
199     }
200 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.