-
-
Notifications
You must be signed in to change notification settings - Fork 167
/
View.php
384 lines (335 loc) · 10.2 KB
/
View.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
<?php
namespace Kirby\Panel;
use Kirby\Cms\App;
use Kirby\Exception\Exception;
use Kirby\Http\Response;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
use Throwable;
/**
* The View response class handles Fiber
* requests to render either a JSON object
* or a full HTML document for Panel views
* @since 3.6.0
*
* @package Kirby Panel
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class View
{
/**
* Filters the data array based on headers or
* query parameters. Requests can return only
* certain data fields that way or globals can
* be injected on demand.
*/
public static function apply(array $data): array
{
$request = App::instance()->request();
$only = $request->header('X-Fiber-Only') ?? $request->get('_only');
if (empty($only) === false) {
return static::applyOnly($data, $only);
}
$globals =
$request->header('X-Fiber-Globals') ??
$request->get('_globals');
if (empty($globals) === false) {
return static::applyGlobals($data, $globals);
}
return A::apply($data);
}
/**
* Checks if globals should be included in a JSON Fiber request. They are normally
* only loaded with the full document request, but sometimes need to be updated.
*
* A global request can be activated with the `X-Fiber-Globals` header or the
* `_globals` query parameter.
*/
public static function applyGlobals(
array $data,
string|null $globals = null
): array {
// split globals string into an array of fields
$globalKeys = Str::split($globals, ',');
// add requested globals
if (empty($globalKeys) === true) {
return $data;
}
$globals = static::globals();
foreach ($globalKeys as $globalKey) {
if (isset($globals[$globalKey]) === true) {
$data[$globalKey] = $globals[$globalKey];
}
}
// merge with shared data
return A::apply($data);
}
/**
* Checks if the request should only return a limited
* set of data. This can be activated with the `X-Fiber-Only`
* header or the `_only` query parameter in a request.
*
* Such requests can fetch shared data or globals.
* Globals will be loaded on demand.
*/
public static function applyOnly(
array $data,
string|null $only = null
): array {
// split include string into an array of fields
$onlyKeys = Str::split($only, ',');
// if a full request is made, return all data
if (empty($onlyKeys) === true) {
return $data;
}
// otherwise filter data based on
// dot notation, e.g. `$props.tab.columns`
$result = [];
// check if globals are requested and need to be merged
if (Str::contains($only, '$')) {
$data = array_merge_recursive(static::globals(), $data);
}
// make sure the data is already resolved to make
// nested data fetching work
$data = A::apply($data);
// build a new array with all requested data
foreach ($onlyKeys as $onlyKey) {
$result[$onlyKey] = A::get($data, $onlyKey);
}
// Nest dotted keys in array but ignore $translation
return A::nest($result, ['$translation']);
}
/**
* Creates the shared data array for the individual views
* The full shared data is always sent on every JSON and
* full document request unless the `X-Fiber-Only` header or
* the `_only` query parameter is set.
*/
public static function data(array $view = [], array $options = []): array
{
$kirby = App::instance();
// multilang setup check
$multilang = Panel::multilang();
// get the authenticated user
$user = $kirby->user();
// user permissions
$permissions = $user?->role()->permissions()->toArray() ?? [];
// current content language
$language = $kirby->language();
// shared data for all requests
return [
'$direction' => function () use ($kirby, $multilang, $language, $user) {
if ($multilang === true && $language && $user) {
$default = $kirby->defaultLanguage();
if (
$language->direction() !== $default->direction() &&
$language->code() !== $user->language()
) {
return $language->direction();
}
}
},
'$dialog' => null,
'$drawer' => null,
'$language' => function () use ($kirby, $multilang, $language) {
if ($multilang === true && $language) {
return [
'code' => $language->code(),
'default' => $language->isDefault(),
'direction' => $language->direction(),
'name' => $language->name(),
'rules' => $language->rules(),
];
}
},
'$languages' => function () use ($kirby, $multilang): array {
if ($multilang === true) {
return $kirby->languages()->values(fn ($language) => [
'code' => $language->code(),
'default' => $language->isDefault(),
'direction' => $language->direction(),
'name' => $language->name(),
'rules' => $language->rules(),
]);
}
return [];
},
'$menu' => function () use ($options, $permissions) {
$menu = new Menu(
$options['areas'] ?? [],
$permissions,
$options['area']['id'] ?? null
);
return $menu->entries();
},
'$permissions' => $permissions,
'$license' => $kirby->system()->license()->status()->value(),
'$multilang' => $multilang,
'$searches' => static::searches($options['areas'] ?? [], $permissions),
'$url' => $kirby->request()->url()->toString(),
'$user' => function () use ($user) {
if ($user) {
return [
'email' => $user->email(),
'id' => $user->id(),
'language' => $user->language(),
'role' => $user->role()->id(),
'username' => $user->username(),
];
}
return null;
},
'$view' => function () use ($kirby, $options, $view) {
$defaults = [
'breadcrumb' => [],
'code' => 200,
'path' => Str::after($kirby->path(), '/'),
'props' => [],
'query' => App::instance()->request()->query()->toArray(),
'referrer' => Panel::referrer(),
'search' => $kirby->option('panel.search.type', 'pages'),
'timestamp' => (int)(microtime(true) * 1000),
];
$view = array_replace_recursive(
$defaults,
$options['area'] ?? [],
$view
);
// make sure that views and dialogs are gone
unset(
$view['dialogs'],
$view['drawers'],
$view['dropdowns'],
$view['requests'],
$view['searches'],
$view['views']
);
// resolve all callbacks in the view array
return A::apply($view);
}
];
}
/**
* Renders the error view with provided message
*/
public static function error(string $message, int $code = 404)
{
return [
'code' => $code,
'component' => 'k-error-view',
'error' => $message,
'props' => [
'error' => $message,
'layout' => Panel::hasAccess(App::instance()->user()) ? 'inside' : 'outside'
],
'title' => 'Error'
];
}
/**
* Creates global data for the Panel.
* This will be injected in the full Panel
* view via the script tag. Global data
* is only requested once on the first page load.
* It can be loaded partially later if needed,
* but is otherwise not included in Fiber calls.
*/
public static function globals(): array
{
$kirby = App::instance();
return [
'$config' => fn () => [
'debug' => $kirby->option('debug', false),
'kirbytext' => $kirby->option('panel.kirbytext', true),
'translation' => $kirby->option('panel.language', 'en'),
],
'$system' => function () use ($kirby) {
$locales = [];
foreach ($kirby->translations() as $translation) {
$locales[$translation->code()] = $translation->locale();
}
return [
'ascii' => Str::$ascii,
'csrf' => $kirby->auth()->csrfFromSession(),
'isLocal' => $kirby->system()->isLocal(),
'locales' => $locales,
'slugs' => Str::$language,
'title' => $kirby->site()->title()->or('Kirby Panel')->toString()
];
},
'$translation' => function () use ($kirby) {
if ($user = $kirby->user()) {
$translation = $kirby->translation($user->language());
} else {
$translation = $kirby->translation($kirby->panelLanguage());
}
return [
'code' => $translation->code(),
'data' => $translation->dataWithFallback(),
'direction' => $translation->direction(),
'name' => $translation->name(),
];
},
'$urls' => fn () => [
'api' => $kirby->url('api'),
'site' => $kirby->url('index')
]
];
}
/**
* Renders the main panel view either as
* JSON response or full HTML document based
* on the request header or query params
*/
public static function response($data, array $options = []): Response
{
// handle redirects
if ($data instanceof Redirect) {
return Response::redirect($data->location(), $data->code());
// handle Kirby exceptions
} elseif ($data instanceof Exception) {
$data = static::error($data->getMessage(), $data->getHttpCode());
// handle regular exceptions
} elseif ($data instanceof Throwable) {
$data = static::error($data->getMessage(), 500);
// only expect arrays from here on
} elseif (is_array($data) === false) {
$data = static::error('Invalid Panel response', 500);
}
// get all data for the request
$fiber = static::data($data, $options);
// if requested, send $fiber data as JSON
if (Panel::isFiberRequest() === true) {
// filter data, if only or globals headers or
// query parameters are set
$fiber = static::apply($fiber);
return Panel::json($fiber, $fiber['$view']['code'] ?? 200);
}
// load globals for the full document response
$globals = static::globals();
// resolve and merge globals and shared data
$fiber = array_merge_recursive(A::apply($globals), A::apply($fiber));
// render the full HTML document
return Document::response($fiber);
}
public static function searches(array $areas, array $permissions): array
{
$searches = [];
foreach ($areas as $areaId => $area) {
// by default, all areas are accessible unless
// the permissions are explicitly set to false
if (($permissions['access'][$areaId] ?? true) !== false) {
foreach ($area['searches'] ?? [] as $id => $params) {
$searches[$id] = [
'icon' => $params['icon'] ?? 'search',
'label' => $params['label'] ?? Str::ucfirst($id),
'id' => $id
];
}
}
}
return $searches;
}
}