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