Passed
Push — master ( 34beb8...79bf97 )
by Alberto
14:24 queued 13s
created

AppController::setupParentsRelation()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 44
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

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