Passed
Push — master ( 813691...f7f51f )
by Stefano
01:29
created

AppController::filterEmpty()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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