]> BookStack Code Mirror - bookstack/blob - app/Settings/SettingService.php
Update TrashCan.php
[bookstack] / app / Settings / SettingService.php
1 <?php namespace BookStack\Settings;
2
3 use BookStack\Auth\User;
4 use Illuminate\Contracts\Cache\Repository as Cache;
5
6 /**
7  * Class SettingService
8  * The settings are a simple key-value database store.
9  * For non-authenticated users, user settings are stored via the session instead.
10  */
11 class SettingService
12 {
13     protected $setting;
14     protected $cache;
15     protected $localCache = [];
16
17     protected $cachePrefix = 'setting-';
18
19     /**
20      * SettingService constructor.
21      */
22     public function __construct(Setting $setting, Cache $cache)
23     {
24         $this->setting = $setting;
25         $this->cache = $cache;
26     }
27
28     /**
29      * Gets a setting from the database,
30      * If not found, Returns default, Which is false by default.
31      */
32     public function get(string $key, $default = false)
33     {
34         if ($default === false) {
35             $default = config('setting-defaults.' . $key, false);
36         }
37
38         if (isset($this->localCache[$key])) {
39             return $this->localCache[$key];
40         }
41
42         $value = $this->getValueFromStore($key) ?? $default;
43         $formatted = $this->formatValue($value, $default);
44         $this->localCache[$key] = $formatted;
45         return $formatted;
46     }
47
48     /**
49      * Get a value from the session instead of the main store option.
50      */
51     protected function getFromSession(string $key, $default = false)
52     {
53         $value = session()->get($key, $default);
54         return $this->formatValue($value, $default);
55     }
56
57     /**
58      * Get a user-specific setting from the database or cache.
59      */
60     public function getUser(User $user, string $key, $default = false)
61     {
62         if ($user->isDefault()) {
63             return $this->getFromSession($key, $default);
64         }
65         return $this->get($this->userKey($user->id, $key), $default);
66     }
67
68     /**
69      * Get a value for the current logged-in user.
70      */
71     public function getForCurrentUser(string $key, $default = false)
72     {
73         return $this->getUser(user(), $key, $default);
74     }
75
76     /**
77      * Gets a setting value from the cache or database.
78      * Looks at the system defaults if not cached or in database.
79      * Returns null if nothing is found.
80      */
81     protected function getValueFromStore(string $key)
82     {
83         // Check the cache
84         $cacheKey = $this->cachePrefix . $key;
85         $cacheVal = $this->cache->get($cacheKey, null);
86         if ($cacheVal !== null) {
87             return $cacheVal;
88         }
89
90         // Check the database
91         $settingObject = $this->getSettingObjectByKey($key);
92         if ($settingObject !== null) {
93             $value = $settingObject->value;
94
95             if ($settingObject->type === 'array') {
96                 $value = json_decode($value, true) ?? [];
97             }
98
99             $this->cache->forever($cacheKey, $value);
100             return $value;
101         }
102
103         return null;
104     }
105
106     /**
107      * Clear an item from the cache completely.
108      */
109     protected function clearFromCache(string $key)
110     {
111         $cacheKey = $this->cachePrefix . $key;
112         $this->cache->forget($cacheKey);
113         if (isset($this->localCache[$key])) {
114             unset($this->localCache[$key]);
115         }
116     }
117
118     /**
119      * Format a settings value
120      */
121     protected function formatValue($value, $default)
122     {
123         // Change string booleans to actual booleans
124         if ($value === 'true') {
125             $value = true;
126         } else if ($value === 'false') {
127             $value = false;
128         }
129
130         // Set to default if empty
131         if ($value === '') {
132             $value = $default;
133         }
134         return $value;
135     }
136
137     /**
138      * Checks if a setting exists.
139      */
140     public function has(string $key): bool
141     {
142         $setting = $this->getSettingObjectByKey($key);
143         return $setting !== null;
144     }
145
146     /**
147      * Add a setting to the database.
148      * Values can be an array or a string.
149      */
150     public function put(string $key, $value): bool
151     {
152         $setting = $this->setting->newQuery()->firstOrNew([
153             'setting_key' => $key
154         ]);
155         $setting->type = 'string';
156
157         if (is_array($value)) {
158             $setting->type = 'array';
159             $value = $this->formatArrayValue($value);
160         }
161
162         $setting->value = $value;
163         $setting->save();
164         $this->clearFromCache($key);
165         return true;
166     }
167
168     /**
169      * Format an array to be stored as a setting.
170      * Array setting types are expected to be a flat array of child key=>value array items.
171      * This filters out any child items that are empty.
172      */
173     protected function formatArrayValue(array $value): string
174     {
175         $values = collect($value)->values()->filter(function(array $item) {
176             return count(array_filter($item)) > 0;
177         });
178         return json_encode($values);
179     }
180
181     /**
182      * Put a user-specific setting into the database.
183      */
184     public function putUser(User $user, string $key, string $value): bool
185     {
186         if ($user->isDefault()) {
187             session()->put($key, $value);
188             return true;
189         }
190
191         return $this->put($this->userKey($user->id, $key), $value);
192     }
193
194     /**
195      * Convert a setting key into a user-specific key.
196      */
197     protected function userKey(string $userId, string $key = ''): string
198     {
199         return 'user:' . $userId . ':' . $key;
200     }
201
202     /**
203      * Removes a setting from the database.
204      */
205     public function remove(string $key): void
206     {
207         $setting = $this->getSettingObjectByKey($key);
208         if ($setting) {
209             $setting->delete();
210         }
211         $this->clearFromCache($key);
212     }
213
214     /**
215      * Delete settings for a given user id.
216      */
217     public function deleteUserSettings(string $userId)
218     {
219         return $this->setting->newQuery()
220             ->where('setting_key', 'like', $this->userKey($userId) . '%')
221             ->delete();
222     }
223
224     /**
225      * Gets a setting model from the database for the given key.
226      */
227     protected function getSettingObjectByKey(string $key): ?Setting
228     {
229         return $this->setting->newQuery()
230             ->where('setting_key', '=', $key)->first();
231     }
232 }