Passed
Branch dev (4236f0)
by Sergey
10:08
created

EntriesController::editProcess()   B

Complexity

Conditions 8
Paths 26

Size

Total Lines 78
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 44
nc 26
nop 2
dl 0
loc 78
rs 7.9715
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Flextype;
4
5
use Flextype\Component\Filesystem\Filesystem;
0 ignored issues
show
Bug introduced by
The type Flextype\Component\Filesystem\Filesystem was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Flextype\Component\Session\Session;
0 ignored issues
show
Bug introduced by
The type Flextype\Component\Session\Session was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Flextype\Component\Arr\Arr;
0 ignored issues
show
Bug introduced by
The type Flextype\Component\Arr\Arr was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use function Flextype\Component\I18n\__;
0 ignored issues
show
introduced by
The function Flextype\Component\I18n\__ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
9
use Respect\Validation\Validator as v;
0 ignored issues
show
Bug introduced by
The type Respect\Validation\Validator was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Intervention\Image\ImageManagerStatic as Image;
0 ignored issues
show
Bug introduced by
The type Intervention\Image\ImageManagerStatic was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Psr\Http\Message\ResponseInterface as Response;
0 ignored issues
show
Bug introduced by
The type Psr\Http\Message\ResponseInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Psr\Http\Message\ServerRequestInterface as Request;
0 ignored issues
show
Bug introduced by
The type Psr\Http\Message\ServerRequestInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Ramsey\Uuid\Uuid;
0 ignored issues
show
Bug introduced by
The type Ramsey\Uuid\Uuid was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
0 ignored issues
show
Bug introduced by
The type Ramsey\Uuid\Exception\Un...fiedDependencyException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
16
17
/**
18
 * @property View $view
19
 * @property Router $router
20
 * @property Registry $registry
21
 * @property Entries $entries
22
 * @property Fieldsets $fieldsets
23
 * @property Flash $flash
24
 * @property Csrf $csrf
25
 * @property Themes $themes
26
 * @property Slugify $slugify
27
 * @property Forms $forms
28
 */
29
class EntriesController extends Container
0 ignored issues
show
Bug introduced by
The type Flextype\Container was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
{
31
32
    /**
33
     * Get Entry ID
34
     *
35
     * @param array Query
0 ignored issues
show
Bug introduced by
The type Flextype\Query was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
36
     */
37
    protected function getEntryID($query)
38
    {
39
        if (isset($query['id'])) {
40
            $_id = $query['id'];
41
        } else {
42
            $_id = '';
43
        }
44
45
        return $_id;
46
    }
47
48
    /**
49
     * Index page
50
     *
51
     * @param Request  $request  PSR7 request
52
     * @param Response $response PSR7 response
53
     *
54
     * @return Response
55
     */
56
    public function index(Request $request, Response $response) : Response
57
    {
58
        // Get Query Params
59
        $query = $request->getQueryParams();
60
61
        // Set Entries ID in parts
62
        if (isset($query['id'])) {
63
            $parts = explode("/", $query['id']);
64
        } else {
65
            $parts = [0 => ''];
66
        }
67
68
        // Init Fieldsets
69
        $fieldsets = [];
70
71
        // Get fieldsets files
72
        $fieldsets_list = Filesystem::listContents(PATH['site'] . '/fieldsets/');
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
73
74
        // If there is any fieldset file then go...
75
        if (count($fieldsets_list) > 0) {
76
            foreach ($fieldsets_list as $fieldset) {
77
                if ($fieldset['type'] == 'file' && $fieldset['extension'] == 'yaml') {
78
                    $fieldset_content = $this->parser->decode(Filesystem::read($fieldset['path']), 'yaml');
79
                    if (isset($fieldset_content['sections']) &&
80
                        isset($fieldset_content['sections']['main']) &&
81
                        isset($fieldset_content['sections']['main']['form']['fields']) &&
82
                        isset($fieldset_content['sections']['main']['form']['fields']['title'])) {
83
                        if (isset($fieldset_content['hide']) && $fieldset_content['hide'] == true) {
84
                            continue;
85
                        }
86
                        $fieldsets[$fieldset['basename']] = $fieldset_content;
87
                    }
88
                }
89
            }
90
        }
91
92
        $entry_current = $this->entries->fetch($this->getEntryID($query));
93
94
        if (isset($entry_current['items_view'])) {
95
            $items_view = $entry_current['items_view'];
96
        } else {
97
            $items_view = $this->registry->get('plugins.admin.settings.entries.items_view_default');
98
        }
99
100
        return $this->twig->render(
101
            $response,
102
            'plugins/admin/templates/content/entries/index.html',
103
            [
104
                            'entries_list' => $this->entries->fetch($this->getEntryID($query), ['order_by' => ['field' => 'published_at', 'direction' => 'desc']]),
105
                            'id_current' => $this->getEntryID($query),
106
                            'entry_current' => $entry_current,
107
                            'items_view' => $items_view,
108
                            'menu_item' => 'entries',
109
                            'fieldsets' => $fieldsets,
110
                            'parts' => $parts,
111
                            'i' => count($parts),
112
                            'last' => Arr::last($parts),
113
                            'links' => [
114
                                        'entries' => [
115
                                                'link' => $this->router->pathFor('admin.entries.index'),
116
                                                'title' => __('admin_entries'),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

116
                                                'title' => /** @scrutinizer ignore-call */ __('admin_entries'),
Loading history...
117
                                                'active' => true
118
                                            ]
119
                                        ],
120
                            'buttons'  => [
121
                                        'create' => [
122
                                                'link'    => 'javascript:;',
123
                                                'title'   => __('admin_create_new_entry'),
124
                                                'onclick' => 'event.preventDefault(); selectEntryType("'.$this->getEntryID($query).'", 0);'
125
                                            ]
126
                                        ]
127
                            ]
128
        );
129
    }
130
131
    /**
132
     * Create new entry page
133
     *
134
     * @param Request  $request  PSR7 request
135
     * @param Response $response PSR7 response
136
     *
137
     * @return Response
138
     */
139
    public function add(Request $request, Response $response) : Response
140
    {
141
        // Get Query Params
142
        $query = $request->getQueryParams();
143
144
        // Set Entries ID in parts
145
        if (isset($query['id'])) {
146
            $parts = explode("/", $query['id']);
147
        } else {
148
            $parts = [0 => ''];
149
        }
150
151
        $type = isset($query['type']) ? $query['type']: '';
152
153
        return $this->twig->render(
154
            $response,
155
            'plugins/admin/templates/content/entries/add.html',
156
            [
157
                            'entries_list' => $this->entries->fetch($this->getEntryID($query), ['order_by' => ['field' => 'title', 'direction' => 'asc']]),
158
                            'menu_item' => 'entries',
159
                            'current_id' => $this->getEntryID($query),
160
                            'parts' => $parts,
161
                            'i' => count($parts),
162
                            'last' => Arr::last($parts),
163
                            'type' => $type,
164
                            'links' => [
165
                                        'entries' => [
166
                                            'link' => $this->router->pathFor('admin.entries.index'),
167
                                            'title' => __('admin_entries'),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

167
                                            'title' => /** @scrutinizer ignore-call */ __('admin_entries'),
Loading history...
168
169
                                        ],
170
                                        'entries_add' => [
171
                                            'link' => $this->router->pathFor('admin.entries.add') . '?id=' . $this->getEntryID($query),
172
                                            'title' => __('admin_create_new_entry'),
173
                                            'active' => true
174
                                            ]
175
                                        ]
176
                        ]
177
        );
178
    }
179
180
    /**
181
     * Select Entry Type - process
182
     *
183
     * @param Request  $request  PSR7 request
184
     * @param Response $response PSR7 response
185
     *
186
     * @return Response
187
     */
188
    public function selectEntryTypeProcess(Request $request, Response $response) : Response
189
    {
190
        // Get data from POST
191
        $data = $request->getParsedBody();
192
193
        return $response->withRedirect($this->router->pathFor('admin.entries.add') . '?id=' . $data['id'] . '&type=' . $data['type']);
194
    }
195
196
    /**
197
     * Create new entry - process
198
     *
199
     * @param Request  $request  PSR7 request
200
     * @param Response $response PSR7 response
201
     *
202
     * @return Response
203
     */
204
    public function addProcess(Request $request, Response $response) : Response
205
    {
206
        // Get data from POST
207
        $data = $request->getParsedBody();
208
209
        // Set parent Entry ID
210
        if ($data['current_id']) {
211
            $parent_entry_id = $data['current_id'];
212
        } else {
213
            $parent_entry_id = '';
214
        }
215
216
        // Set new Entry ID
217
        if ($this->registry->get('plugins.admin.settings.entries.slugify') == true) {
218
            $id = $parent_entry_id . '/' . $this->slugify->slugify($data['id']);
219
        } else {
220
            $id = $parent_entry_id . '/' . $data['id'];
221
        }
222
223
        // Check if entry exists then try to create
224
        if (!$this->entries->has($id)) {
225
226
            // Check if we have fieldset for this entry
227
            if ($this->fieldsets->has($data['fieldset'])) {
228
229
                // Get fieldset
230
                $fieldset = $this->fieldsets->fetch($data['fieldset']);
231
232
                // We need to check if template for current fieldset is exists
233
                // if template is not exist then `default` template will be used!
234
                $template_path = PATH['themes'] . '/' . $this->registry->get('flextype.theme') . '/templates/' . $data['fieldset'] . '.html';
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
235
                $template = (Filesystem::has($template_path)) ? $data['fieldset'] : 'default';
236
237
                // Init entry data
238
                $data_from_post          = [];
239
                $data_from_post_override = [];
240
                $data_result             = [];
241
242
                // Define data values based on POST data
243
                $data_from_post['title']      = $data['title'];
244
                $data_from_post['template']   = $template;
245
                $data_from_post['fieldset']   = $data['fieldset'];
246
                $data_from_post['visibility'] = $data['visibility'];
247
                $data_from_post['routable']   = isset($data['routable']) ? (bool) $data['routable'] : false;
248
249
                // Predefine data values based on fieldset default values
250
                foreach ($fieldset['sections'] as $section_name => $section_body) {
251
                    foreach ($section_body['fields'] as $field => $properties) {
252
253
                        // Ingnore fields where property: heading
254
                        if ($properties['type'] == 'heading') {
255
                            continue;
256
                        }
257
258
                        // Get values from $data_from_post
259
                        if (isset($data_from_post[$field])) {
260
                            $value = $data_from_post[$field];
261
262
                        // Get values from fieldsets predefined field values
263
                        } elseif (isset($properties['value'])) {
264
                            $value = $properties['value'];
265
266
                        // or set empty value
267
                        } else {
268
                            $value = '';
269
                        }
270
271
                        $data_from_post_override[$field] = $value;
272
273
                    }
274
                }
275
276
                // Merge data
277
                if (count($data_from_post_override) > 0) {
278
                    $data_result = array_replace_recursive($data_from_post_override, $data_from_post);
279
                } else {
280
                    $data_result = $data_from_post;
281
                }
282
283
                if ($this->entries->create($id, $data_result)) {
284
285
                    if (! Filesystem::has(PATH['site'] . '/uploads' . '/entries/' . $id)) {
286
                        Filesystem::createDir(PATH['site'] . '/uploads' . '/entries/' . $id);
287
                    }
288
289
                    $this->clearEntryCounter($parent_entry_id);
290
                    $this->flash->addMessage('success', __('admin_message_entry_created'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

290
                    $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_created'));
Loading history...
291
                } else {
292
                    $this->flash->addMessage('error', __('admin_message_entry_was_not_created'));
293
                }
294
            } else {
295
                $this->flash->addMessage('error', __('admin_message_fieldset_not_found'));
296
            }
297
        } else {
298
            $this->flash->addMessage('error', __('admin_message_entry_was_not_created'));
299
        }
300
301
        if (isset($data['create-and-edit'])) {
302
            return $response->withRedirect($this->router->pathFor('admin.entries.edit') . '?id=' . $data['id'] . '&type=editor');
303
        } else {
304
            return $response->withRedirect($this->router->pathFor('admin.entries.index') . '?id=' . $parent_entry_id);
305
        }
306
    }
307
308
    /**
309
     * Change entry type
310
     *
311
     * @param Request  $request  PSR7 request
312
     * @param Response $response PSR7 response
313
     *
314
     * @return Response
315
     */
316
    public function type(Request $request, Response $response) : Response
317
    {
318
        // Get Query Params
319
        $query = $request->getQueryParams();
320
321
        // Set Entries ID in parts
322
        if (isset($query['id'])) {
323
            $parts = explode("/", $query['id']);
324
        } else {
325
            $parts = [0 => ''];
326
        }
327
328
        $entry = $this->entries->fetch($this->getEntryID($query));
329
330
        $fieldsets = [];
331
332
        // Get fieldsets files
333
        $_fieldsets = Filesystem::listContents(PATH['site'] . '/fieldsets/');
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
334
335
        // If there is any template file then go...
336
        if (count($_fieldsets) > 0) {
337
            foreach ($_fieldsets as $fieldset) {
338
                if ($fieldset['type'] == 'file' && $fieldset['extension'] == 'yaml') {
339
                    $fieldset_content = $this->parser->decode(Filesystem::read($fieldset['path']), 'yaml');
340
                    if (isset($fieldset_content['sections']) &&
341
                        isset($fieldset_content['sections']['main']) &&
342
                        isset($fieldset_content['sections']['main']['fields']) &&
343
                        isset($fieldset_content['sections']['main']['fields']['title'])) {
344
                        if (isset($fieldset_content['hide']) && $fieldset_content['hide'] == true) {
345
                            continue;
346
                        }
347
                        $fieldsets[$fieldset['basename']] = $fieldset_content['title'];
348
                    }
349
                }
350
            }
351
        }
352
353
        return $this->twig->render(
354
            $response,
355
            'plugins/admin/templates/content/entries/type.html',
356
            [
357
                            'fieldset' => $entry['fieldset'],
358
                            'fieldsets' => $fieldsets,
359
                            'id' => $this->getEntryID($query),
360
                            'menu_item' => 'entries',
361
                            'parts' => $parts,
362
                            'i' => count($parts),
363
                            'last' => Arr::last($parts),
364
                            'links' => [
365
                                'entries' => [
366
                                    'link' => $this->router->pathFor('admin.entries.index'),
367
                                    'title' => __('admin_entries'),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

367
                                    'title' => /** @scrutinizer ignore-call */ __('admin_entries'),
Loading history...
368
369
                                ],
370
                                'entries_type' => [
371
                                    'link' => $this->router->pathFor('admin.entries.type') . '?id=' . $this->getEntryID($query),
372
                                    'title' => __('admin_type'),
373
                                    'active' => true
374
                                    ]
375
                                ]
376
                        ]
377
        );
378
    }
379
380
    /**
381
     * Change entry type - process
382
     *
383
     * @param Request  $request  PSR7 request
384
     * @param Response $response PSR7 response
385
     *
386
     * @return Response
387
     */
388
    public function typeProcess(Request $request, Response $response) : Response
389
    {
390
        $post_data = $request->getParsedBody();
391
392
        $id = $post_data['id'];
393
394
        $entry = $this->entries->fetch($id);
395
396
        Arr::delete($entry, 'slug');
397
        Arr::delete($entry, 'modified_at');
398
        Arr::delete($entry, 'created_at');
399
        Arr::delete($entry, 'published_at');
400
401
        Arr::delete($post_data, 'csrf_name');
402
        Arr::delete($post_data, 'csrf_value');
403
        Arr::delete($post_data, 'save_entry');
404
        Arr::delete($post_data, 'id');
405
406
        $post_data['published_by'] = Session::get('uuid');
407
408
        $data = array_merge($entry, $post_data);
409
410
        if ($this->entries->update(
411
            $id,
412
            $data
413
        )) {
414
            $this->flash->addMessage('success', __('admin_message_entry_changes_saved'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

414
            $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_changes_saved'));
Loading history...
415
        } else {
416
            $this->flash->addMessage('error', __('admin_message_entry_was_not_moved'));
417
        }
418
419
        return $response->withRedirect($this->router->pathFor('admin.entries.index') . '?id=' . implode('/', array_slice(explode("/", $id), 0, -1)));
420
    }
421
422
    /**
423
     * Move entry
424
     *
425
     * @param Request  $request  PSR7 request
426
     * @param Response $response PSR7 response
427
     *
428
     * @return Response
429
     */
430
    public function move(Request $request, Response $response) : Response
431
    {
432
        // Get Query Params
433
        $query = $request->getQueryParams();
434
435
        // Get Entry from Query Params
436
        $entry_id = $this->getEntryID($query);
437
438
        // Get current Entry ID
439
        $entry_id_current = Arr::last(explode("/", $entry_id));
440
441
        // Fetch entry
442
        $entry = $this->entries->fetch($this->getEntryID($query));
0 ignored issues
show
Unused Code introduced by
The assignment to $entry is dead and can be removed.
Loading history...
443
444
        // Set Entries IDs in parts
445
        if (isset($query['id'])) {
446
            $parts = explode("/", $query['id']);
447
        } else {
448
            $parts = [0 => ''];
449
        }
450
451
        // Get entries list
452
        $entries_list['/'] = '/';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$entries_list was never initialized. Although not strictly required by PHP, it is generally a good practice to add $entries_list = array(); before regardless.
Loading history...
453
        foreach ($this->entries->fetch('', ['order_by' => ['field' => ['slug']], 'recursive' => true]) as $_entry) {
454
            if ($_entry['slug'] != '') {
455
                $entries_list[$_entry['slug']] = $_entry['slug'];
456
            } else {
457
                $entries_list[$this->registry->get('flextype.entries.main')] = $this->registry->get('flextype.entries.main');
458
            }
459
        }
460
461
        return $this->twig->render(
462
            $response,
463
            'plugins/admin/templates/content/entries/move.html',
464
            [
465
                            'menu_item' => 'entries',
466
                            'entries_list' => $entries_list,
467
                            'entry_id_current' => $entry_id_current,
468
                            'entry_id_path_current' => $entry_id,
469
                            'entry_id_path_parent' => implode('/', array_slice(explode("/", $entry_id), 0, -1)),
470
                            'parts' => $parts,
471
                            'i' => count($parts),
472
                            'last' => Arr::last($parts),
473
                            'links' => [
474
                                'entries' => [
475
                                    'link' => $this->router->pathFor('admin.entries.index'),
476
                                    'title' => __('admin_entries'),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

476
                                    'title' => /** @scrutinizer ignore-call */ __('admin_entries'),
Loading history...
477
478
                                ],
479
                                'entries_move' => [
480
                                    'link' => $this->router->pathFor('admin.entries.move'),
481
                                    'title' => __('admin_move'),
482
                                    'active' => true
483
                                    ]
484
                                ]
485
                        ]
486
        );
487
    }
488
489
    /**
490
     * Move entry - process
491
     *
492
     * @param Request  $request  PSR7 request
493
     * @param Response $response PSR7 response
494
     *
495
     * @return Response
496
     */
497
    public function moveProcess(Request $request, Response $response)
498
    {
499
        // Get data from POST
500
        $data = $request->getParsedBody();
501
502
        // Set entry id current
503
        $entry_id_current = $data['entry_id_current'];
504
505
        if (!$this->entries->has($data['parent_entry'] . '/' . $entry_id_current)) {
506
            if ($this->entries->rename(
507
                $data['entry_id_path_current'],
508
                $data['parent_entry'] . '/' . $entry_id_current
509
            )) {
510
                rename(PATH['site'] . '/uploads' . '/entries/' . $data['entry_id_path_current'], PATH['site'] . '/uploads' . '/entries/' . $data['parent_entry'] . '/' . $entry_id_current);
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
511
                $this->clearEntryCounter($data['parent_entry']);
512
                $this->flash->addMessage('success', __('admin_message_entry_moved'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

512
                $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_moved'));
Loading history...
513
            } else {
514
                $this->flash->addMessage('error', __('admin_message_entry_was_not_moved'));
515
            }
516
        } else {
517
            $this->flash->addMessage('error', __('admin_message_entry_was_not_moved'));
518
        }
519
520
        return $response->withRedirect($this->router->pathFor('admin.entries.index') . '?id=' . (($data['parent_entry'] == '/') ? '' : $data['parent_entry']));
521
    }
522
523
    /**
524
     * Rename entry
525
     *
526
     * @param Request  $request  PSR7 request
527
     * @param Response $response PSR7 response
528
     *
529
     * @return Response
530
     */
531
    public function rename(Request $request, Response $response) : Response
532
    {
533
        // Get Query Params
534
        $query = $request->getQueryParams();
535
536
        // Set Entries ID in parts
537
        if (isset($query['id'])) {
538
            $parts = explode("/", $query['id']);
539
        } else {
540
            $parts = [0 => ''];
541
        }
542
543
        return $this->twig->render(
544
            $response,
545
            'plugins/admin/templates/content/entries/rename.html',
546
            [
547
                            'name_current' => Arr::last(explode("/", $this->getEntryID($query))),
548
                            'entry_path_current' => $this->getEntryID($query),
549
                            'entry_parent' => implode('/', array_slice(explode("/", $this->getEntryID($query)), 0, -1)),
550
                            'menu_item' => 'entries',
551
                            'parts' => $parts,
552
                            'i' => count($parts),
553
                            'last' => Arr::last($parts),
554
                            'links' => [
555
                                'entries' => [
556
                                    'link' => $this->router->pathFor('admin.entries.index'),
557
                                    'title' => __('admin_entries'),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

557
                                    'title' => /** @scrutinizer ignore-call */ __('admin_entries'),
Loading history...
558
559
                                ],
560
                                'entries_type' => [
561
                                    'link' => $this->router->pathFor('admin.entries.rename') . '?id=' . $this->getEntryID($query),
562
                                    'title' => __('admin_rename'),
563
                                    'active' => true
564
                                    ]
565
                                ]
566
                        ]
567
        );
568
    }
569
570
    /**
571
     * Rename entry - process
572
     *
573
     * @param Request  $request  PSR7 request
574
     * @param Response $response PSR7 response
575
     *
576
     * @return Response
577
     */
578
    public function renameProcess(Request $request, Response $response) : Response
579
    {
580
        $data = $request->getParsedBody();
581
582
        // Set name
583
        if ($this->registry->get('plugins.admin.settings.entries.slugify') == true) {
584
            $name = $this->slugify->slugify($data['name']);
585
        } else {
586
            $name = $data['name'];
587
        }
588
589
        if ($this->entries->rename(
590
            $data['entry_path_current'],
591
            $data['entry_parent'] . '/' . $name)
592
        ) {
593
            rename(PATH['site'] . '/uploads' . '/entries/' . $data['entry_path_current'], PATH['site'] . '/uploads' . '/entries/' . $data['entry_parent'] . '/' . $this->slugify->slugify($data['name']));
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
594
            $this->clearEntryCounter($data['entry_path_current']);
595
            $this->flash->addMessage('success', __('admin_message_entry_renamed'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

595
            $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_renamed'));
Loading history...
596
        } else {
597
            $this->flash->addMessage('error', __('admin_message_entry_was_not_created'));
598
        }
599
600
        return $response->withRedirect($this->router->pathFor('admin.entries.index') . '?id=' . $data['entry_parent']);
601
    }
602
603
    /**
604
     * Delete entry - process
605
     *
606
     * @param Request  $request  PSR7 request
607
     * @param Response $response PSR7 response
608
     *
609
     * @return Response
610
     */
611
    public function deleteProcess(Request $request, Response $response) : Response
612
    {
613
        $data = $request->getParsedBody();
614
615
        $id = $data['id'];
616
        $id_current = $data['id-current'];
617
618
        if ($this->entries->delete($id)) {
619
620
            Filesystem::deleteDir(PATH['site'] . '/uploads' . '/entries/' . $id);
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
621
622
            $this->clearEntryCounter($id_current);
623
624
            $this->flash->addMessage('success', __('admin_message_entry_deleted'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

624
            $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_deleted'));
Loading history...
625
        } else {
626
            $this->flash->addMessage('error', __('admin_message_entry_was_not_deleted'));
627
        }
628
629
        return $response->withRedirect($this->router->pathFor('admin.entries.index') . '?id=' . $id_current);
630
    }
631
632
    /**
633
     * Duplicate entry - process
634
     *
635
     * @param Request  $request  PSR7 request
636
     * @param Response $response PSR7 response
637
     *
638
     * @return Response
639
     */
640
    public function duplicateProcess(Request $request, Response $response) : Response
641
    {
642
        $data = $request->getParsedBody();
643
644
        $id = $data['id'];
645
        $parent_id = implode('/', array_slice(explode("/", $id), 0, -1));
646
647
        $random_date = date("Ymd_His");
648
649
        $this->entries->copy($id, $id . '-duplicate-' . $random_date, true);
650
651
        if (Filesystem::has(PATH['site'] . '/uploads' . '/entries/' . $id)) {
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
652
            Filesystem::copy(PATH['site'] . '/uploads' . '/entries/' . $id, PATH['site'] . '/uploads' . '/entries/' . $id . '-duplicate-' . $random_date, true);
653
        } else {
654
            Filesystem::createDir(PATH['site'] . '/uploads' . '/entries/' . $id . '-duplicate-' . $random_date);
655
        }
656
657
        $this->clearEntryCounter($parent_id);
658
659
        $this->flash->addMessage('success', __('admin_message_entry_duplicated'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

659
        $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_duplicated'));
Loading history...
660
661
        return $response->withRedirect($this->router->pathFor('admin.entries.index') . '?id=' . $parent_id);
662
    }
663
664
    /**
665
     * Edit entry
666
     *
667
     * @param Request  $request  PSR7 request
668
     * @param Response $response PSR7 response
669
     *
670
     * @return Response
671
     */
672
    public function edit(Request $request, Response $response) : Response
673
    {
674
        // Get Query Params
675
        $query = $request->getQueryParams();
676
677
        // Set Entries ID in parts
678
        if (isset($query['id'])) {
679
            $parts = explode("/", $query['id']);
680
        } else {
681
            $parts = [0 => ''];
682
        }
683
684
        // Get Entry type
685
        $type = $request->getQueryParams()['type'];
686
687
        // Get Entry
688
        $entry = $this->entries->fetch($this->getEntryID($query));
689
        Arr::delete($entry, 'slug');
690
        Arr::delete($entry, 'modified_at');
691
692
        // Fieldsets for current entry template
693
        $fieldsets_path = PATH['site'] . '/fieldsets/' . (isset($entry['fieldset']) ? $entry['fieldset'] : 'default') . '.yaml';
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
694
        $fieldsets = $this->parser->decode(Filesystem::read($fieldsets_path), 'yaml');
695
        is_null($fieldsets) and $fieldsets = [];
696
697
        if ($type == 'source') {
698
            $entry['published_at'] = date($this->registry->get('flextype.settings.date_format'), $entry['published_at']);
699
            $entry['created_at'] = date($this->registry->get('flextype.settings.date_format'), $entry['created_at']);
700
701
            return $this->twig->render(
702
                $response,
703
                'plugins/admin/templates/content/entries/source.html',
704
                [
705
                        'parts' => $parts,
706
                        'i' => count($parts),
707
                        'last' => Arr::last($parts),
708
                        'id' => $this->getEntryID($query),
709
                        'data' => $this->parser->encode($entry, 'frontmatter'),
710
                        'type' => $type,
711
                        'menu_item' => 'entries',
712
                        'links' => [
713
                            'entries' => [
714
                                'link' => $this->router->pathFor('admin.entries.index') . '?id=' . implode('/', array_slice(explode("/", $this->getEntryID($query)), 0, -1)),
715
                                'title' => __('admin_entries'),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

715
                                'title' => /** @scrutinizer ignore-call */ __('admin_entries'),
Loading history...
716
717
                            ],
718
                            'edit_entry' => [
719
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query). '&type=editor',
720
                                'title' => __('admin_editor'),
721
722
                            ],
723
                            'edit_entry_media' => [
724
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query) . '&type=media',
725
                                'title' => __('admin_media'),
726
727
                            ],
728
                            'edit_entry_source' => [
729
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query) . '&type=source',
730
                                'title' => __('admin_source'),
731
                                'active' => true
732
                            ],
733
                        ],
734
                        'buttons' => [
735
                            'save_entry' => [
736
                                            'link'       => 'javascript:;',
737
                                            'title'      => __('admin_save'),
738
                                            'type' => 'action'
739
                                        ],
740
                        ]
741
                ]
742
            );
743
        } elseif ($type == 'media') {
744
            return $this->twig->render(
745
                $response,
746
                'plugins/admin/templates/content/entries/media.html',
747
                [
748
                        'parts' => $parts,
749
                        'i' => count($parts),
750
                        'last' => Arr::last($parts),
751
                        'id' => $this->getEntryID($query),
752
                        'files' => $this->getMediaList($this->getEntryID($query), true),
753
                        'menu_item' => 'entries',
754
                        'links' => [
755
                            'entries' => [
756
                                'link' => $this->router->pathFor('admin.entries.index') . '?id=' . implode('/', array_slice(explode("/", $this->getEntryID($query)), 0, -1)),
757
                                'title' => __('admin_entries'),
758
759
                            ],
760
                            'edit_entry' => [
761
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query) . '&type=editor',
762
                                'title' => __('admin_editor'),
763
764
                            ],
765
                            'edit_entry_media' => [
766
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query) . '&type=media',
767
                                'title' => __('admin_media'),
768
                                'active' => true
769
                            ],
770
                            'edit_entry_source' => [
771
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query) . '&type=source',
772
                                'title' => __('admin_source'),
773
                            ],
774
                        ]
775
                ]
776
            );
777
        } else {
778
779
            // Merge current entry fieldset with global fildset
780
            if (isset($entry['entry_fieldset'])) {
781
                $form = $this->form->render(array_replace_recursive($fieldsets, $entry['entry_fieldset']), $entry);
782
            } else {
783
                $form = $this->form->render($fieldsets, $entry);
784
            }
785
786
            return $this->twig->render(
787
                $response,
788
                'plugins/admin/templates/content/entries/edit.html',
789
                [
790
                        'parts' => $parts,
791
                        'i' => count($parts),
792
                        'last' => Arr::last($parts),
793
                        'form' => $form,
794
                        'menu_item' => 'entries',
795
                        'links' => [
796
                            'entries' => [
797
                                'link' => $this->router->pathFor('admin.entries.index') . '?id=' . implode('/', array_slice(explode("/", $this->getEntryID($query)), 0, -1)),
798
                                'title' => __('admin_entries')
799
                            ],
800
                            'edit_entry' => [
801
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query) . '&type=editor',
802
                                'title' => __('admin_editor'),
803
                                'active' => true
804
                            ],
805
                            'edit_entry_media' => [
806
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query) . '&type=media',
807
                                'title' => __('admin_media')
808
                            ],
809
                            'edit_entry_source' => [
810
                                'link' => $this->router->pathFor('admin.entries.edit') . '?id=' . $this->getEntryID($query) . '&type=source',
811
                                'title' => __('admin_source')
812
                            ],
813
                        ],
814
                        'buttons' => [
815
                            'save_entry' => [
816
                                            'link'       => 'javascript:;',
817
                                            'title'      => __('admin_save'),
818
                                            'type' => 'action'
819
                                        ],
820
                        ]
821
                ]
822
            );
823
        }
824
    }
825
826
    /**
827
     * Edit entry process
828
     *
829
     * @param Request  $request  PSR7 request
830
     * @param Response $response PSR7 response
831
     *
832
     * @return Response
833
     */
834
    public function editProcess(Request $request, Response $response) : Response
835
    {
836
        $query = $request->getQueryParams();
837
838
        // Get Entry ID and TYPE from GET param
839
        $id = $query['id'];
840
        $type = $query['type'];
841
842
        if ($type == 'source') {
843
844
            // Data from POST
845
            $data = $request->getParsedBody();
846
847
            $entry = $this->parser->decode($data['data'], 'frontmatter');
848
849
            $entry['published_by'] = Session::get('uuid');
850
851
            Arr::delete($entry, 'slug');
852
            Arr::delete($entry, 'modified_at');
853
854
            // Update entry
855
            if (Filesystem::write(PATH['entries'] . '/' . $id . '/entry.md', $this->parser->encode($entry, 'frontmatter'))) {
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
856
                $this->flash->addMessage('success', __('admin_message_entry_changes_saved'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

856
                $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_changes_saved'));
Loading history...
857
            } else {
858
                $this->flash->addMessage('error', __('admin_message_entry_changes_not_saved'));
859
            }
860
        } else {
861
            // Result data to save
862
            $result_data = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $result_data is dead and can be removed.
Loading history...
863
864
            // Data from POST
865
            $data = $request->getParsedBody();
866
867
            // Delete system fields
868
            Arr::delete($data, 'slug');
869
            Arr::delete($data, 'csrf_value');
870
            Arr::delete($data, 'csrf_name');
871
            Arr::delete($data, 'action');
872
873
            $data['published_by'] = Session::get('uuid');
874
875
            // Fetch entry
876
            $entry = $this->entries->fetch($id);
877
            Arr::delete($entry, 'slug');
878
            Arr::delete($entry, 'modified_at');
879
880
            if (isset($data['created_at'])) {
881
                $data['created_at'] = date($this->registry->get('flextype.settings.date_format'), strtotime($data['created_at']));
882
            } else {
883
                $data['created_at'] = date($this->registry->get('flextype.settings.date_format'), $entry['created_at']);
884
            }
885
886
            if (isset($data['published_at'])) {
887
                $data['published_at'] = (string) date($this->registry->get('flextype.settings.date_format'), strtotime($data['published_at']));
888
            } else {
889
                $data['published_at'] = (string) date($this->registry->get('flextype.settings.date_format'), $entry['published_at']);
890
            }
891
892
            if (isset($data['routable'])) {
893
                $data['routable'] = (bool) $data['routable'];
894
            } elseif(isset($entry['routable'])) {
895
                $data['routable'] = (bool) $entry['routable'];
896
            } else {
897
                $data['routable'] = true;
898
            }
899
900
            // Merge entry data with $data
901
            $result_data = array_merge($entry, $data);
902
903
            // Update entry
904
            if ($this->entries->update($id, $result_data)) {
905
                $this->flash->addMessage('success', __('admin_message_entry_changes_saved'));
906
            } else {
907
                $this->flash->addMessage('error', __('admin_message_entry_changes_not_saved'));
908
            }
909
        }
910
911
        return $response->withRedirect($this->router->pathFor('admin.entries.edit') . '?id=' . $id . '&type=' . $type);
912
    }
913
914
    /**
915
     * Delete media file - process
916
     *
917
     * @param Request  $request  PSR7 request
918
     * @param Response $response PSR7 response
919
     *
920
     * @return Response
921
     */
922
    public function deleteMediaFileProcess(Request $request, Response $response) : Response
923
    {
924
        $data = $request->getParsedBody();
925
926
        $entry_id = $data['entry-id'];
927
        $media_id = $data['media-id'];
928
929
        $files_directory = PATH['site'] . '/uploads' . '/entries/' . $entry_id . '/' . $media_id;
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
930
931
        Filesystem::delete($files_directory);
932
933
        $this->flash->addMessage('success', __('admin_message_entry_file_deleted'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

933
        $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_file_deleted'));
Loading history...
934
935
        return $response->withRedirect($this->router->pathFor('admin.entries.edit') . '?id=' . $entry_id . '&type=media');
936
    }
937
938
    /**
939
     * Upload media file - process
940
     *
941
     * @param Request  $request  PSR7 request
942
     * @param Response $response PSR7 response
943
     *
944
     * @return Response
945
     */
946
    public function uploadMediaFileProcess(Request $request, Response $response) : Response
947
    {
948
        $data = $request->getParsedBody();
949
950
        $id = $data['entry-id'];
951
952
        $files_directory = PATH['site'] . '/uploads' . '/entries/' . $id . '/';
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
953
954
        $file = $this->_uploadFile($_FILES['file'], $files_directory, $this->registry->get('plugins.admin.settings.entries.media.accept_file_types'), 27000000);
955
956
        if ($file !== false) {
0 ignored issues
show
introduced by
The condition $file !== false is always true.
Loading history...
957
            if (in_array(pathinfo($file)['extension'], ['jpg', 'jpeg', 'png', 'gif'])) {
958
                // open an image file
959
                $img = Image::make($file);
960
                // now you are able to resize the instance
961
                if ($this->registry->get('plugins.admin.settings.entries.media.upload_images_width') > 0 && $this->registry->get('plugins.admin.settings.entries.media.upload_images_height') > 0) {
962
                    $img->resize($this->registry->get('plugins.admin.settings.entries.media.upload_images_width'), $this->registry->get('plugins.admin.settings.entries.media.upload_images_height'), function($constraint) {
963
                        $constraint->aspectRatio();
964
                        $constraint->upsize();
965
                    });
966
                } elseif ($this->registry->get('plugins.admin.settings.entries.media.upload_images_width') > 0) {
967
                    $img->resize($this->registry->get('plugins.admin.settings.entries.media.upload_images_width'), null, function($constraint) {
968
                        $constraint->aspectRatio();
969
                        $constraint->upsize();
970
                    });
971
                } elseif ($this->registry->get('plugins.admin.settings.entries.media.upload_images_height') > 0) {
972
                    $img->resize(null, $this->registry->get('plugins.admin.settings.entries.media.upload_images_height'), function($constraint) {
973
                        $constraint->aspectRatio();
974
                        $constraint->upsize();
975
                    });
976
                }
977
                // finally we save the image as a new file
978
                $img->save($file, $this->registry->get('plugins.admin.settings.entries.media.upload_images_quality'));
979
980
                // destroy
981
                $img->destroy();
982
            }
983
984
            $this->flash->addMessage('success', __('admin_message_entry_file_uploaded'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

984
            $this->flash->addMessage('success', /** @scrutinizer ignore-call */ __('admin_message_entry_file_uploaded'));
Loading history...
985
        } else {
986
            $this->flash->addMessage('error', __('admin_message_entry_file_not_uploaded'));
987
        }
988
989
        return $response->withRedirect($this->router->pathFor('admin.entries.edit') . '?id=' . $id . '&type=media');
990
    }
991
992
    /**
993
     * Upload files on the Server with several type of Validations!
994
     *
995
     * _uploadFile($_FILES['file'], $files_directory);
996
     *
997
     * @param   array   $file             Uploaded file data
998
     * @param   string  $upload_directory Upload directory
999
     * @param   string  $allowed          Allowed file extensions
1000
     * @param   int     $max_size         Max file size in bytes
1001
     * @param   string  $filename         New filename
1002
     * @param   bool    $remove_spaces    Remove spaces from the filename
1003
     * @param   int     $max_width        Maximum width of image
1004
     * @param   int     $max_height       Maximum height of image
1005
     * @param   bool    $exact            Match width and height exactly?
1006
     * @param   int     $chmod            Chmod mask
1007
     * @return  string  on success, full path to new file
1008
     * @return  false   on failure
1009
     */
1010
    public function _uploadFile(
1011
        array $file,
1012
        string $upload_directory,
1013
        string $allowed = 'jpeg, png, gif, jpg',
1014
        int $max_size = 5000000,
1015
        string $filename = null,
1016
        bool $remove_spaces = true,
1017
        int $max_width = null,
1018
        int $max_height = null,
1019
        bool $exact = false,
1020
        int $chmod = 0644
1021
    ) {
1022
        //
1023
        // Tests if a successful upload has been made.
1024
        //
1025
        if (isset($file['error'])
1026
            and isset($file['tmp_name'])
1027
            and $file['error'] === UPLOAD_ERR_OK
1028
            and is_uploaded_file($file['tmp_name'])) {
1029
            //
1030
            // Tests if upload data is valid, even if no file was uploaded.
1031
            //
1032
            if (isset($file['error'])
1033
                    and isset($file['name'])
1034
                    and isset($file['type'])
1035
                    and isset($file['tmp_name'])
1036
                    and isset($file['size'])) {
1037
                //
1038
                // Test if an uploaded file is an allowed file type, by extension.
1039
                //
1040
                if (strpos($allowed, strtolower(pathinfo($file['name'], PATHINFO_EXTENSION))) !== false) {
1041
                    //
1042
                    // Validation rule to test if an uploaded file is allowed by file size.
1043
                    //
1044
                    if (($file['error'] != UPLOAD_ERR_INI_SIZE)
1045
                                  and ($file['error'] == UPLOAD_ERR_OK)
1046
                                  and ($file['size'] <= $max_size)) {
1047
                        //
1048
                        // Validation rule to test if an upload is an image and, optionally, is the correct size.
1049
                        //
1050
                        if (in_array(mime_content_type($file['tmp_name']), ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'])) {
1051
                            function validateImage($file, $max_width, $max_height, $exact)
1052
                            {
1053
                                try {
1054
                                    // Get the width and height from the uploaded image
1055
                                    list($width, $height) = getimagesize($file['tmp_name']);
1056
                                } catch (ErrorException $e) {
0 ignored issues
show
Bug introduced by
The type Flextype\ErrorException was not found. Did you mean ErrorException? If so, make sure to prefix the type with \.
Loading history...
1057
                                    // Ignore read errors
1058
                                }
1059
                                if (empty($width) or empty($height)) {
1060
                                    // Cannot get image size, cannot validate
1061
                                    return false;
1062
                                }
1063
                                if (!$max_width) {
1064
                                    // No limit, use the image width
1065
                                    $max_width = $width;
1066
                                }
1067
                                if (!$max_height) {
1068
                                    // No limit, use the image height
1069
                                    $max_height = $height;
1070
                                }
1071
                                if ($exact) {
1072
                                    // Check if dimensions match exactly
1073
                                    return ($width === $max_width and $height === $max_height);
1074
                                } else {
1075
                                    // Check if size is within maximum dimensions
1076
                                    return ($width <= $max_width and $height <= $max_height);
1077
                                }
1078
                                return false;
0 ignored issues
show
Unused Code introduced by
return false is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1079
                            }
1080
                            if (validateImage($file, $max_width, $max_height, $exact) === false) {
1081
                                return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
1082
                            }
1083
                        }
1084
                        if (!isset($file['tmp_name']) or !is_uploaded_file($file['tmp_name'])) {
1085
                            // Ignore corrupted uploads
1086
                            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
1087
                        }
1088
                        if ($filename === null) {
1089
                            // Use the default filename
1090
                            $filename = $file['name'];
1091
                        }
1092
                        if ($remove_spaces === true) {
1093
                            // Remove spaces from the filename
1094
                            $filename = $this->slugify->slugify(pathinfo($filename)['filename']) . '.' . pathinfo($filename)['extension'];
1095
                        }
1096
                        if (!is_dir($upload_directory) or !is_writable(realpath($upload_directory))) {
1097
                            throw new \RuntimeException("Directory {$upload_directory} must be writable");
1098
                        }
1099
                        // Make the filename into a complete path
1100
                        $filename = realpath($upload_directory) . DIRECTORY_SEPARATOR . $filename;
1101
                        if (move_uploaded_file($file['tmp_name'], $filename)) {
1102
                            // Set permissions on filename
1103
                            chmod($filename, $chmod);
1104
                            // Return new file path
1105
                            return $filename;
1106
                        }
1107
                    }
1108
                }
1109
            }
1110
        }
1111
1112
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
1113
    }
1114
1115
    /**
1116
     * Get media list
1117
     *
1118
     * @param string $id Entry ID
1119
     * @param bool   $path if true returns with url paths
1120
     *
1121
     * @return array
1122
     */
1123
    public function getMediaList(string $id, bool $path = false) : array
1124
    {
1125
        $base_url = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER))->getBaseUrl();
0 ignored issues
show
Bug introduced by
The type Slim\Http\Uri was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type Slim\Http\Environment was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1126
        $files = [];
1127
1128
        if (!Filesystem::has(PATH['site'] . '/uploads' . '/entries/' . $id)) {
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1129
            Filesystem::createDir(PATH['site'] . '/uploads' . '/entries/' . $id);
1130
        }
1131
1132
        foreach (array_diff(scandir(PATH['site'] . '/uploads' . '/entries/' . $id), ['..', '.']) as $file) {
0 ignored issues
show
Bug introduced by
It seems like scandir(Flextype\PATH['s...s' . '/entries/' . $id) can also be of type false; however, parameter $array1 of array_diff() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1132
        foreach (array_diff(/** @scrutinizer ignore-type */ scandir(PATH['site'] . '/uploads' . '/entries/' . $id), ['..', '.']) as $file) {
Loading history...
1133
            if (strpos($this->registry->get('plugins.admin.settings.entries.media.accept_file_types'), $file_ext = substr(strrchr($file, '.'), 1)) !== false) {
1134
                if (strpos($file, strtolower($file_ext), 1)) {
1135
                    if ($file !== 'entry.md') {
1136
                        if ($path) {
1137
                            $files[$base_url . '/' . $id . '/' . $file] = $base_url . '/' . $id . '/' . $file;
1138
                        } else {
1139
                            $files[$file] = $file;
1140
                        }
1141
                    }
1142
                }
1143
            }
1144
        }
1145
        return $files;
1146
    }
1147
1148
    /**
1149
     * Display view - process
1150
     *
1151
     * @param Request  $request  PSR7 request
1152
     * @param Response $response PSR7 response
1153
     */
1154
    public function displayViewProcess(Request $request, Response $response) : Response
1155
    {
1156
        // Get POST data
1157
        $post_data = $request->getParsedBody();
1158
1159
        if ($post_data['id'] == '') {
1160
            $data = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
1161
            $admin_plugin_settings = $this->parser->decode(Filesystem::read(PATH['site'] . '/config/' . '/plugins/admin/settings.yaml'), 'yaml');
0 ignored issues
show
Bug introduced by
The constant Flextype\PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1162
            $admin_plugin_settings['entries']['items_view_default'] = $post_data['items_view'];
1163
            Filesystem::write(PATH['site'] . '/config/' . '/plugins/admin/settings.yaml', $this->parser->encode($admin_plugin_settings, 'yaml'));
1164
        } else {
1165
            $this->entries->update($post_data['id'], ['items_view' => $post_data['items_view']]);
1166
        }
1167
1168
        return $response->withRedirect($this->router->pathFor('admin.entries.index') . '?id=' . $post_data['id']);
1169
    }
1170
1171
    /**
1172
     * Clear entry counter
1173
     *
1174
     * @param string $id Entry ID
1175
     */
1176
    public function clearEntryCounter($id) : void
1177
    {
1178
        if ($this->cache->contains($id . '_counter')) {
1179
            $this->cache->delete($id . '_counter');
1180
        }
1181
    }
1182
}
1183