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