AppController::setObjectNav()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 5
nop 1
dl 0
loc 18
rs 9.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2022 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
namespace App\Controller;
14
15
use App\Form\Form;
16
use App\Utility\DateRangesTools;
17
use Authentication\Identity;
18
use BEdita\WebTools\ApiClientProvider;
19
use Cake\Controller\Controller;
20
use Cake\Controller\Exception\SecurityException;
21
use Cake\Core\Configure;
22
use Cake\Event\EventInterface;
23
use Cake\Http\Exception\BadRequestException;
24
use Cake\Http\Response;
25
use Cake\Utility\Hash;
26
27
/**
28
 * Base Application Controller.
29
 *
30
 * @property \Authentication\Controller\Component\AuthenticationComponent $Authentication
31
 * @property \App\Controller\Component\CategoriesComponent $Categories
32
 * @property \App\Controller\Component\ConfigComponent $Config
33
 * @property \App\Controller\Component\FlashComponent $Flash
34
 * @property \App\Controller\Component\ModulesComponent $Modules
35
 * @property \App\Controller\Component\SchemaComponent $Schema
36
 */
37
class AppController extends Controller
38
{
39
    /**
40
     * BEdita4 API client
41
     *
42
     * @var \BEdita\SDK\BEditaClient
43
     */
44
    protected $apiClient = null;
45
46
    /**
47
     * @inheritDoc
48
     */
49
    public function initialize(): void
50
    {
51
        parent::initialize();
52
53
        $this->loadComponent('RequestHandler', ['enableBeforeRedirect' => false]);
54
        $this->loadComponent('App.Flash', ['clear' => true]);
55
        $this->loadComponent('Security');
56
57
        // API config may not be set in `login` for a multi-project setup
58
        if (Configure::check('API.apiBaseUrl')) {
59
            $this->apiClient = ApiClientProvider::getApiClient();
60
        }
61
62
        $this->loadComponent('Authentication.Authentication', [
63
            'logoutRedirect' => '/login',
64
        ]);
65
66
        $this->loadComponent('Modules', [
67
            'currentModuleName' => $this->name,
68
        ]);
69
        $this->loadComponent('Schema');
70
        $this->loadComponent('Categories');
71
72
        /** @var \Authentication\Identity|null $identity */
73
        $identity = $this->Authentication->getIdentity();
74
        if ($identity && $identity->get('tokens')) {
75
            $this->apiClient->setupTokens($identity->get('tokens'));
76
        }
77
    }
78
79
    /**
80
     * @inheritDoc
81
     */
82
    public function beforeFilter(EventInterface $event): ?Response
83
    {
84
        /** @var \Authentication\Identity|null $identity */
85
        $identity = $this->Authentication->getIdentity();
86
        if (!($identity && $identity->get('tokens')) && !in_array(rtrim($this->getRequest()->getPath(), '/'), ['/login'])) {
87
            $route = $this->loginRedirectRoute();
88
            $this->Flash->error(__('Login required'));
89
90
            return $this->redirect($route);
91
        }
92
        $this->setupOutputTimezone();
93
        $this->Security->setConfig('blackHoleCallback', 'blackhole');
94
95
        return null;
96
    }
97
98
    /**
99
     * Handle security blackhole with logs for now
100
     *
101
     * @param string $type Exception type
102
     * @param \Cake\Controller\Exception\SecurityException $exception Raised exception
103
     * @return void
104
     * @throws \Cake\Http\Exception\BadRequestException
105
     * @codeCoverageIgnore
106
     */
107
    public function blackhole(string $type, SecurityException $exception): void
108
    {
109
        // Log original exception
110
        $this->log($exception->getMessage(), 'error');
111
112
        // Log form data & session id
113
        $token = (array)$this->getRequest()->getData('_Token');
114
        unset($token['debug']);
115
        $this->log('[Blackhole] type: ' . $type, 'debug');
116
        $this->log('[Blackhole] form token: ' . json_encode($token), 'debug');
117
        $this->log('[Blackhole] form fields: ' . json_encode(array_keys((array)$this->getRequest()->getData())), 'debug');
118
        $this->log('[Blackhole] form session id: ' . (string)$this->getRequest()->getData('_session_id'), 'debug');
119
        $sessionId = $this->getRequest()->getSession()->id();
120
        $this->log('[Blackhole] current session id: ' . $sessionId, 'debug');
121
122
        // Throw a generic bad request exception.
123
        throw new BadRequestException();
124
    }
125
126
    /**
127
     * Return route array for login redirect.
128
     * When request is not a get, return route without redirect.
129
     * When request uri path equals request attribute webroot (the app 'webroot'), return route without redirect.
130
     * Return route with redirect, otherwise.
131
     *
132
     * @return array
133
     */
134
    protected function loginRedirectRoute(): array
135
    {
136
        $route = ['_name' => 'login'];
137
138
        // if request is not a get, return route without redirect.
139
        if (!$this->getRequest()->is('get')) {
140
            return $route;
141
        }
142
143
        // if redirect is app webroot, return route without redirect.
144
        $redirect = $this->getRequest()->getUri()->getPath();
145
        if ($redirect === $this->getRequest()->getAttribute('webroot')) {
146
            return $route;
147
        }
148
149
        return $route + ['?' => compact('redirect')];
150
    }
151
152
    /**
153
     * Setup output timezone from user session
154
     *
155
     * @return void
156
     */
157
    protected function setupOutputTimezone(): void
158
    {
159
        /** @var \Authentication\Identity|null $identity */
160
        $identity = $this->Authentication->getIdentity();
161
        if (!$identity) {
162
            return;
163
        }
164
165
        $timezone = $identity->get('timezone');
166
        if (!$timezone) {
167
            return;
168
        }
169
170
        Configure::write('I18n.timezone', $timezone);
171
    }
172
173
    /**
174
     * {@inheritDoc}
175
     *
176
     * Update session tokens if updated/refreshed by client
177
     */
178
    public function beforeRender(EventInterface $event): ?Response
179
    {
180
        /** @var \Authentication\Identity|null $user */
181
        $user = $this->Authentication->getIdentity();
182
        if ($user) {
183
            $tokens = $this->apiClient->getTokens();
184
            if ($tokens && $user->get('tokens') !== $tokens) {
185
                $data = compact('tokens') + (array)$user->getOriginalData();
186
                $user = new Identity($data);
187
                $this->Authentication->setIdentity($user);
188
            }
189
190
            $this->set(compact('user'));
191
        }
192
193
        $path = $this->viewBuilder()->getTemplatePath();
194
        $this->viewBuilder()->setTemplatePath('Pages/' . $path);
195
196
        return null;
197
    }
198
199
    /**
200
     * Prepare request, set properly json data.
201
     *
202
     * @param string $type Object type
203
     * @return array request data
204
     */
205
    protected function prepareRequest($type): array
206
    {
207
        $data = (array)$this->getRequest()->getData();
208
209
        $this->specialAttributes($data);
210
        $this->setupParentsRelation($type, $data);
211
        $this->prepareRelations($data);
212
        $this->changedAttributes($data);
213
        $this->filterEmpty($data);
214
215
        return $data;
216
    }
217
218
    /**
219
     * Setup special attributes to be saved.
220
     *
221
     * @param array $data Request data
222
     * @return void
223
     */
224
    protected function specialAttributes(array &$data): void
225
    {
226
        // remove temporary session id
227
        unset($data['_session_id']);
228
        unset($data['selectedCategories']);
229
230
        // if password is empty, unset it
231
        if (array_key_exists('password', $data) && empty($data['password'])) {
232
            unset($data['password']);
233
            unset($data['confirm-password']);
234
        }
235
236
        $this->decodeJsonAttributes($data);
237
238
        $this->prepareDateRanges($data);
239
240
        // prepare categories
241
        if (!empty($data['categories'])) {
242
            $data['categories'] = json_decode($data['categories'], true);
243
            $data['categories'] = array_map(function ($category) {
244
                return ['name' => $category];
245
            }, $data['categories']);
246
        }
247
248
        // decode json fields
249
        $types = (array)Hash::get($data, '_types');
250
        if (!empty($types)) {
251
            foreach ($types as $field => $type) {
252
                if ($type === 'json' && is_string($data[$field])) {
253
                    $data[$field] = json_decode($data[$field], true);
254
                }
255
            }
256
            unset($data['_types']);
257
        }
258
    }
259
260
    /**
261
     * Decodes JSON attributes.
262
     *
263
     * @param array $data Request data
264
     * @return void
265
     */
266
    protected function decodeJsonAttributes(array &$data): void
267
    {
268
        if (empty($data['_jsonKeys'])) {
269
            return;
270
        }
271
272
        $keys = array_unique(explode(',', (string)$data['_jsonKeys']));
273
        foreach ($keys as $key) {
274
            $value = Hash::get($data, $key);
275
            $decoded = json_decode((string)$value, true);
276
            if ($decoded === []) {
277
                // decode as empty object in case of empty array
278
                $decoded = json_decode((string)$value);
279
            }
280
            $data = Hash::insert($data, $key, $decoded);
281
        }
282
        unset($data['_jsonKeys']);
283
    }
284
285
    /**
286
     * Prepare date ranges.
287
     * Remove empty date ranges.
288
     * Fix end date time to 23:59:59.000 if end_date contains '23:59:00.000'.
289
     *
290
     * @param array $data The data to prepare
291
     * @return void
292
     */
293
    protected function prepareDateRanges(array &$data): void
294
    {
295
        if (empty($data['date_ranges'])) {
296
            return;
297
        }
298
        $data['date_ranges'] = is_array($data['date_ranges']) ? $data['date_ranges'] : json_decode($data['date_ranges'], true);
299
        $data['date_ranges'] = DateRangesTools::prepare(Hash::get($data, 'date_ranges'));
300
    }
301
302
    /**
303
     * Prepare request relation data.
304
     *
305
     * @param array $data Request data
306
     * @return void
307
     */
308
    protected function prepareRelations(array &$data): void
309
    {
310
        // relations data for view/save - prepare api calls
311
        if (!empty($data['relations'])) {
312
            $api = [];
313
            foreach ($data['relations'] as $relation => $relationData) {
314
                $id = $data['id'];
315
                foreach ($relationData as $method => $ids) {
316
                    $relatedIds = $this->relatedIds($ids);
317
                    if ($method === 'replaceRelated' || !empty($relatedIds)) {
318
                        $api[] = compact('method', 'id', 'relation', 'relatedIds');
319
                    }
320
                }
321
            }
322
            $data['_api'] = $api;
323
        }
324
        unset($data['relations']);
325
    }
326
327
    /**
328
     * Get related ids from items array.
329
     * If items is string, it is json encoded array.
330
     * If items is array, it can be json encoded array or array of id/type data.
331
     */
332
    protected function relatedIds($items): array
333
    {
334
        if (empty($items)) {
335
            return [];
336
        }
337
        if (is_string($items)) {
338
            return json_decode($items, true);
339
        }
340
        if (is_string(Hash::get($items, 0))) {
341
            return array_map(
342
                function ($json) {
343
                    return json_decode($json, true);
344
                },
345
                $items
346
            );
347
        }
348
349
        return $items;
350
    }
351
352
    /**
353
     * Handle `parents` or `parent` relationship looking at `_changedParents` input
354
     *
355
     * @param string $type Object type
356
     * @param array $data Form data
357
     * @return void
358
     */
359
    protected function setupParentsRelation(string $type, array &$data): void
360
    {
361
        $changedParents = (string)Hash::get($data, '_changedParents');
362
        $relation = $type === 'folders' ? 'parent' : 'parents';
363
        if (empty($changedParents)) {
364
            unset($data['relations'][$relation], $data['_changedParents'], $data['_originalParents']);
365
366
            return;
367
        }
368
        $changedParents = array_unique(explode(',', $changedParents));
369
        $originalParents = array_filter(explode(',', (string)Hash::get($data, '_originalParents')));
370
        unset($data['_changedParents'], $data['_originalParents']);
371
        $replaceRelated = array_reduce(
372
            (array)Hash::get($data, sprintf('relations.%s.replaceRelated', $relation)),
373
            function ($acc, $obj) {
374
                $jsonObj = (array)json_decode($obj, true);
375
                $acc[(string)Hash::get($jsonObj, 'id')] = $jsonObj;
376
377
                return $acc;
378
            },
379
            []
380
        );
381
        $addRelated = array_map(
382
            function ($id) use ($replaceRelated) {
383
                return Hash::get($replaceRelated, $id);
384
            },
385
            $changedParents
386
        );
387
        $addRelated = array_filter(
388
            $addRelated,
389
            function ($elem) {
390
                return !empty($elem);
391
            }
392
        );
393
        $data['relations'][$relation]['addRelated'] = $addRelated;
394
395
        // no need to remove when relation is "parent"
396
        // ParentsComponent::addRelated already performs a replaceRelated
397
        if ($relation !== 'parent') {
398
            $rem = array_diff($originalParents, array_keys($replaceRelated));
399
            $data['relations'][$relation]['removeRelated'] = array_map(
400
                function ($id) {
401
                    return ['id' => $id, 'type' => 'folders'];
402
                },
403
                $rem
404
            );
405
        }
406
        unset($data['relations'][$relation]['replaceRelated']);
407
    }
408
409
    /**
410
     * Setup changed attributes to be saved.
411
     * Remove unchanged attributes from $data array.
412
     *
413
     * @param array $data Request data
414
     * @return void
415
     */
416
    protected function changedAttributes(array &$data): void
417
    {
418
        if (empty($data['_actualAttributes'])) {
419
            return;
420
        }
421
        $attributes = json_decode($data['_actualAttributes'], true);
422
        if ($attributes === null) {
423
            $this->log(sprintf('Wrong _actualAttributes, not a json string: %s', $data['_actualAttributes']), 'error');
424
            unset($data['_actualAttributes']);
425
426
            return;
427
        }
428
        foreach ($attributes as $key => $value) {
429
            if (!array_key_exists($key, $data)) {
430
                continue;
431
            }
432
            if ($data[$key] === Form::NULL_VALUE) {
433
                $data[$key] = null;
434
            }
435
            // remove unchanged attributes from $data
436
            if (!$this->hasFieldChanged($value, $data[$key], $key)) {
437
                unset($data[$key]);
438
            }
439
        }
440
        unset($data['_actualAttributes']);
441
    }
442
443
    /**
444
     * Return true if $oldValue equals $newValue or both are empty (null|'')
445
     *
446
     * @param mixed $oldValue The first value | field value in model data (db)
447
     * @param mixed $newValue The second value | field value from form
448
     * @param string $key The field key
449
     * @return bool
450
     */
451
    protected function hasFieldChanged($oldValue, $newValue, string $key): bool
452
    {
453
        if ($oldValue === $newValue) {
454
            return false; // not changed
455
        }
456
        if (($oldValue === null || $oldValue === '') && ($newValue === null || $newValue === '')) {
457
            return false; // not changed
458
        }
459
        if ($key === 'categories' || $key === 'tags') {
460
            return $this->Categories->hasChanged($oldValue, $newValue);
461
        }
462
        $booleanItems = ['0', '1', 'true', 'false', 0, 1];
463
        if (is_bool($oldValue) && !is_bool($newValue) && in_array($newValue, $booleanItems, true)) { // i.e. true / "1"
464
            return $oldValue !== boolval($newValue);
465
        }
466
        if (is_numeric($oldValue) && is_string($newValue)) {
467
            return (string)$oldValue !== $newValue;
468
        }
469
        if (is_string($oldValue) && is_numeric($newValue)) {
470
            return $oldValue !== (string)$newValue;
471
        }
472
473
        return $oldValue !== $newValue;
474
    }
475
476
    /**
477
     * Check request data by options.
478
     *
479
     *  - $options['allowedMethods']: check allowed method(s)
480
     *  - $options['requiredParameters']: check required parameter(s)
481
     *
482
     * @param array $options The options for request check(s)
483
     * @return array The request data for required parameters, if any
484
     * @throws \Cake\Http\Exception\BadRequestException on empty request or empty data by parameter
485
     */
486
    protected function checkRequest(array $options = []): array
487
    {
488
        // check allowed methods
489
        if (!empty($options['allowedMethods'])) {
490
            $this->getRequest()->allowMethod($options['allowedMethods']);
491
        }
492
493
        // check request required parameters, if any
494
        $data = [];
495
        if (!empty($options['requiredParameters'])) {
496
            foreach ($options['requiredParameters'] as $param) {
497
                $val = $this->getRequest()->getData($param);
498
                if (empty($val)) {
499
                    throw new BadRequestException(sprintf('Empty %s', $param));
500
                }
501
                $data[$param] = $val;
502
            }
503
        }
504
505
        return $data;
506
    }
507
508
    /**
509
     * Apply session filter (if any): if found, redirect properly.
510
     * Session key: '{$currentModuleName}.filter'
511
     * Scenarios:
512
     *
513
     * Query parameter 'reset=1': remove session key and redirect
514
     * Query parameters found: write them on session with proper key ({currentModuleName}.filter)
515
     * Session data for session key: build uri from session data and redirect to new uri.
516
     *
517
     * @return \Cake\Http\Response|null
518
     */
519
    protected function applySessionFilter(): ?Response
520
    {
521
        $session = $this->getRequest()->getSession();
522
        $sessionKey = sprintf('%s.filter', $this->Modules->getConfig('currentModuleName'));
523
524
        // if reset request, delete session data by key and redirect to proper uri
525
        if ($this->getRequest()->getQuery('reset') === '1') {
526
            $session->delete($sessionKey);
527
528
            return $this->redirect((string)$this->getRequest()->getUri()->withQuery(''));
529
        }
530
531
        // write request query parameters (if any) in session
532
        $params = $this->getRequest()->getQueryParams();
533
        if (!empty($params)) {
534
            unset($params['_search']);
535
            $session->write($sessionKey, $params);
536
537
            return null;
538
        }
539
540
        // read request query parameters from session and redirect to proper page
541
        $params = (array)$session->read($sessionKey);
542
        if (!empty($params)) {
543
            $query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
544
545
            return $this->redirect((string)$this->getRequest()->getUri()->withQuery($query));
546
        }
547
548
        return null;
549
    }
550
551
    /**
552
     * Set objectNav array and objectNavModule.
553
     * Objects can be in different modules:
554
     *
555
     *  - a document is in "documents" and "objects" index
556
     *  - an image is in "images" and "media" index
557
     *  - etc.
558
     *
559
     * The session variable objectNavModule stores the last module index visited;
560
     * this is used then in controller view, to obtain the proper object nav (@see \App\Controller\AppController::getObjectNav)
561
     *
562
     * @param array $objects The objects to parse to set prev and next data
563
     * @return void
564
     */
565
    protected function setObjectNav($objects): void
566
    {
567
        $moduleName = $this->Modules->getConfig('currentModuleName');
568
        $total = count(array_keys($objects));
569
        $objectNav = [];
570
        /** @var int $i */
571
        foreach ($objects as $i => $object) {
572
            $objectNav[$moduleName][$object['id']] = [
573
                'prev' => $i > 0 ? Hash::get($objects, sprintf('%d.id', $i - 1)) : null,
574
                'next' => $i + 1 < $total ? Hash::get($objects, sprintf('%d.id', $i + 1)) : null,
575
                'index' => $i + 1,
576
                'total' => $total,
577
                'object_type' => Hash::get($objects, sprintf('%d.object_type', $i)),
578
            ];
579
        }
580
        $session = $this->getRequest()->getSession();
581
        $session->write('objectNav', $objectNav);
582
        $session->write('objectNavModule', $moduleName);
583
    }
584
585
    /**
586
     * Get objectNav for ID and current module name
587
     *
588
     * @param string $id The object ID
589
     * @return array
590
     */
591
    protected function getObjectNav($id): array
592
    {
593
        // get objectNav from session
594
        $session = $this->getRequest()->getSession();
595
        $objectNav = (array)$session->read('objectNav');
596
        if (empty($objectNav)) {
597
            return [];
598
        }
599
600
        // get objectNav by session objectNavModule
601
        $objectNavModule = (string)$session->read('objectNavModule');
602
603
        return (array)Hash::get($objectNav, sprintf('%s.%s', $objectNavModule, $id), []);
604
    }
605
606
    /**
607
     * Cake 4 compatibility wrapper method: set items to serialize for the view
608
     *
609
     * In Cake 3 => $this->set('_serialize', ['data']);
610
     * In Cake 4 => $this->viewBuilder()->setOption('serialize', ['data'])
611
     *
612
     * @param array $items Items to serialize
613
     * @return void
614
     * @codeCoverageIgnore
615
     */
616
    protected function setSerialize(array $items): void
617
    {
618
        $this->viewBuilder()->setOption('serialize', $items);
619
    }
620
621
    /**
622
     * Remove empty fields when saving new resource.
623
     *
624
     * @param array $data The form data
625
     * @return void
626
     */
627
    protected function filterEmpty(array &$data): void
628
    {
629
        if (!empty($data['id'])) {
630
            return;
631
        }
632
        $data = array_filter($data, function ($item) {
633
            return $item === '0' ? true : !empty($item);
634
        });
635
    }
636
}
637