]> BookStack Code Mirror - bookstack/blob - app/Settings/SettingService.php
Played around with a new app structure
[bookstack] / app / Settings / SettingService.php
1 <?php
2
3 namespace BookStack\Settings;
4
5 use BookStack\Users\Models\User;
6
7 /**
8  * Class SettingService
9  * The settings are a simple key-value database store.
10  * For non-authenticated users, user settings are stored via the session instead.
11  * A local array-based cache is used to for setting accesses across a request.
12  */
13 class SettingService
14 {
15     protected array $localCache = [];
16
17     /**
18      * Gets a setting from the database,
19      * If not found, Returns default, Which is false by default.
20      */
21     public function get(string $key, $default = null): mixed
22     {
23         if (is_null($default)) {
24             $default = config('setting-defaults.' . $key, false);
25         }
26
27         $value = $this->getValueFromStore($key) ?? $default;
28         return $this->formatValue($value, $default);
29     }
30
31     /**
32      * Get a value from the session instead of the main store option.
33      */
34     protected function getFromSession(string $key, $default = false)
35     {
36         $value = session()->get($key, $default);
37
38         return $this->formatValue($value, $default);
39     }
40
41     /**
42      * Get a user-specific setting from the database or cache.
43      */
44     public function getUser(User $user, string $key, $default = null)
45     {
46         if (is_null($default)) {
47             $default = config('setting-defaults.user.' . $key, false);
48         }
49
50         if ($user->isDefault()) {
51             return $this->getFromSession($key, $default);
52         }
53
54         return $this->get($this->userKey($user->id, $key), $default);
55     }
56
57     /**
58      * Get a value for the current logged-in user.
59      */
60     public function getForCurrentUser(string $key, $default = null)
61     {
62         return $this->getUser(user(), $key, $default);
63     }
64
65     /**
66      * Gets a setting value from the local cache.
67      * Will load the local cache if not previously loaded.
68      */
69     protected function getValueFromStore(string $key): mixed
70     {
71         $cacheCategory = $this->localCacheCategory($key);
72         if (!isset($this->localCache[$cacheCategory])) {
73             $this->loadToLocalCache($cacheCategory);
74         }
75
76         return $this->localCache[$cacheCategory][$key] ?? null;
77     }
78
79     /**
80      * Put the given value into the local cached under the given key.
81      */
82     protected function putValueIntoLocalCache(string $key, mixed $value): void
83     {
84         $cacheCategory = $this->localCacheCategory($key);
85         if (!isset($this->localCache[$cacheCategory])) {
86             $this->loadToLocalCache($cacheCategory);
87         }
88
89         $this->localCache[$cacheCategory][$key] = $value;
90     }
91
92     /**
93      * Get the category for the given setting key.
94      * Will return 'app' for a general app setting otherwise 'user:<user_id>' for a user setting.
95      */
96     protected function localCacheCategory(string $key): string
97     {
98         if (str_starts_with($key, 'user:')) {
99             return implode(':', array_slice(explode(':', $key), 0, 2));
100         }
101
102         return 'app';
103     }
104
105     /**
106      * For the given category, load the relevant settings from the database into the local cache.
107      */
108     protected function loadToLocalCache(string $cacheCategory): void
109     {
110         $query = Setting::query();
111
112         if ($cacheCategory === 'app') {
113             $query->where('setting_key', 'not like', 'user:%');
114         } else {
115             $query->where('setting_key', 'like', $cacheCategory . ':%');
116         }
117         $settings = $query->toBase()->get();
118
119         if (!isset($this->localCache[$cacheCategory])) {
120             $this->localCache[$cacheCategory] = [];
121         }
122
123         foreach ($settings as $setting) {
124             $value = $setting->value;
125
126             if ($setting->type === 'array') {
127                 $value = json_decode($value, true) ?? [];
128             }
129
130             $this->localCache[$cacheCategory][$setting->setting_key] = $value;
131         }
132     }
133
134     /**
135      * Format a settings value.
136      */
137     protected function formatValue(mixed $value, mixed $default): mixed
138     {
139         // Change string booleans to actual booleans
140         if ($value === 'true') {
141             $value = true;
142         } elseif ($value === 'false') {
143             $value = false;
144         }
145
146         // Set to default if empty
147         if ($value === '') {
148             $value = $default;
149         }
150
151         return $value;
152     }
153
154     /**
155      * Checks if a setting exists.
156      */
157     public function has(string $key): bool
158     {
159         $setting = $this->getSettingObjectByKey($key);
160
161         return $setting !== null;
162     }
163
164     /**
165      * Add a setting to the database.
166      * Values can be an array or a string.
167      */
168     public function put(string $key, mixed $value): bool
169     {
170         $setting = Setting::query()->firstOrNew([
171             'setting_key' => $key,
172         ]);
173
174         $setting->type = 'string';
175         $setting->value = $value;
176
177         if (is_array($value)) {
178             $setting->type = 'array';
179             $setting->value = $this->formatArrayValue($value);
180         }
181
182         $setting->save();
183         $this->putValueIntoLocalCache($key, $value);
184
185         return true;
186     }
187
188     /**
189      * Format an array to be stored as a setting.
190      * Array setting types are expected to be a flat array of child key=>value array items.
191      * This filters out any child items that are empty.
192      */
193     protected function formatArrayValue(array $value): string
194     {
195         $values = collect($value)->values()->filter(function (array $item) {
196             return count(array_filter($item)) > 0;
197         });
198
199         return json_encode($values);
200     }
201
202     /**
203      * Put a user-specific setting into the database.
204      * Can only take string value types since this may use
205      * the session which is less flexible to data types.
206      */
207     public function putUser(User $user, string $key, string $value): bool
208     {
209         if ($user->isDefault()) {
210             session()->put($key, $value);
211
212             return true;
213         }
214
215         return $this->put($this->userKey($user->id, $key), $value);
216     }
217
218     /**
219      * Put a user-specific setting into the database for the current access user.
220      * Can only take string value types since this may use
221      * the session which is less flexible to data types.
222      */
223     public function putForCurrentUser(string $key, string $value): bool
224     {
225         return $this->putUser(user(), $key, $value);
226     }
227
228     /**
229      * Convert a setting key into a user-specific key.
230      */
231     protected function userKey(string $userId, string $key = ''): string
232     {
233         return 'user:' . $userId . ':' . $key;
234     }
235
236     /**
237      * Removes a setting from the database.
238      */
239     public function remove(string $key): void
240     {
241         $setting = $this->getSettingObjectByKey($key);
242         if ($setting) {
243             $setting->delete();
244         }
245
246         $cacheCategory = $this->localCacheCategory($key);
247         if (isset($this->localCache[$cacheCategory])) {
248             unset($this->localCache[$cacheCategory][$key]);
249         }
250     }
251
252     /**
253      * Delete settings for a given user id.
254      */
255     public function deleteUserSettings(string $userId): void
256     {
257         Setting::query()
258             ->where('setting_key', 'like', $this->userKey($userId) . '%')
259             ->delete();
260     }
261
262     /**
263      * Gets a setting model from the database for the given key.
264      */
265     protected function getSettingObjectByKey(string $key): ?Setting
266     {
267         return Setting::query()
268             ->where('setting_key', '=', $key)
269             ->first();
270     }
271
272     /**
273      * Empty the local setting value cache used by this service.
274      */
275     public function flushCache(): void
276     {
277         $this->localCache = [];
278     }
279 }