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