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