Completed
Push — master ( 5e7f91...e0cb69 )
by Philip
08:11 queued 05:45
created

ControllerProvider::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
crap 1
1
<?php
2
3
/*
4
 * This file is part of the CRUDlex package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CRUDlex;
13
14
use League\Flysystem\Util\MimeType;
15
use Silex\Api\ControllerProviderInterface;
16
use Silex\Application;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\HttpFoundation\StreamedResponse;
20
21
/**
22
 * This is the ControllerProvider offering all CRUD pages.
23
 *
24
 * It offers this routes:
25
 *
26
 * "/resource/static" serving static resources
27
 *
28
 * "/{entity}/create" creation page of the entity
29
 *
30
 * "/{entity}" list page of the entity
31
 *
32
 * "/{entity}/{id}" details page of a single entity instance
33
 *
34
 * "/{entity}/{id}/edit" edit page of a single entity instance
35
 *
36
 * "/{entity}/{id}/delete" POST only deletion route for an entity instance
37
 *
38
 * "/{entity}/{id}/{field}/file" renders a file field of an entity instance
39
 *
40
 * "/{entity}/{id}/{field}/delete" POST only deletion of a file field of an entity instance
41
 */
42
class ControllerProvider implements ControllerProviderInterface
43
{
44
45
    /**
46
     * Generates the not found page.
47
     *
48
     * @param Application $app
49
     * the Silex application
50
     * @param string $error
51
     * the cause of the not found error
52
     *
53
     * @return Response
54
     * the rendered not found page with the status code 404
55
     */
56 9
    protected function getNotFoundPage(Application $app, $error)
57
    {
58 9
        return new Response($app['twig']->render('@crud/notFound.twig', [
59 9
            'crud' => $app['crud'],
60 9
            'error' => $error,
61 9
            'crudEntity' => '',
62 9
            'layout' => $app['crud']->getTemplate('layout', '', '')
63 9
        ]), 404);
64
    }
65
66
    /**
67
     * Postprocesses the entity after modification by handling the uploaded
68
     * files and setting the flash.
69
     *
70
     * @param Application $app
71
     * the current application
72
     * @param AbstractData $crudData
73
     * the data instance of the entity
74
     * @param Entity $instance
75
     * the entity
76
     * @param string $entity
77
     * the name of the entity
78
     * @param string $mode
79
     * whether to 'edit' or to 'create' the entity
80
     *
81
     * @return null|\Symfony\Component\HttpFoundation\RedirectResponse
82
     * the HTTP response of this modification
83
     */
84 4
    protected function modifyFilesAndSetFlashBag(Application $app, AbstractData $crudData, Entity $instance, $entity, $mode)
85
    {
86 4
        $id          = $instance->get('id');
87 4
        $request     = $app['request_stack']->getCurrentRequest();
88 4
        $fileHandler = new FileHandler($app['crud.filesystem'], $crudData->getDefinition());
89 4
        $result      = $mode == 'edit' ? $fileHandler->updateFiles($crudData, $request, $instance, $entity) : $fileHandler->createFiles($crudData, $request, $instance, $entity);
90 4
        if (!$result) {
91 2
            return null;
92
        }
93 4
        $app['session']->getFlashBag()->add('success', $app['translator']->trans('crudlex.'.$mode.'.success', [
94 4
            '%label%' => $crudData->getDefinition()->getLabel(),
95 4
            '%id%' => $id
96
        ]));
97 4
        return $app->redirect($app['url_generator']->generate('crudShow', ['entity' => $entity, 'id' => $id]));
98
    }
99
100
    /**
101
     * Sets the flashes of a failed entity modification.
102
     *
103
     * @param Application $app
104
     * the current application
105
     * @param boolean $optimisticLocking
106
     * whether the optimistic locking failed
107
     * @param string $mode
108
     * the modification mode, either 'create' or 'edit'
109
     */
110 2
    protected function setValidationFailedFlashes(Application $app, $optimisticLocking, $mode)
111
    {
112 2
        $app['session']->getFlashBag()->add('danger', $app['translator']->trans('crudlex.'.$mode.'.error'));
113 2
        if ($optimisticLocking) {
114 1
            $app['session']->getFlashBag()->add('danger', $app['translator']->trans('crudlex.edit.locked'));
115
        }
116 2
    }
117
118
    /**
119
     * Validates and saves the new or updated entity and returns the appropriate HTTP
120
     * response.
121
     *
122
     * @param Application $app
123
     * the current application
124
     * @param AbstractData $crudData
125
     * the data instance of the entity
126
     * @param Entity $instance
127
     * the entity
128
     * @param string $entity
129
     * the name of the entity
130
     * @param boolean $edit
131
     * whether to edit (true) or to create (false) the entity
132
     *
133
     * @return Response
134
     * the HTTP response of this modification
135
     */
136 5
    protected function modifyEntity(Application $app, AbstractData $crudData, Entity $instance, $entity, $edit)
137
    {
138 5
        $fieldErrors = [];
139 5
        $mode        = $edit ? 'edit' : 'create';
140 5
        $request     = $app['request_stack']->getCurrentRequest();
141 5
        if ($request->getMethod() == 'POST') {
142 4
            $instance->populateViaRequest($request);
143 4
            $validator  = new EntityValidator($instance);
144 4
            $validation = $validator->validate($crudData, intval($request->get('version')));
145
146 4
            $fieldErrors = $validation['errors'];
147 4
            if (!$validation['valid']) {
148 2
                $optimisticLocking = isset($fieldErrors['version']);
149 2
                $this->setValidationFailedFlashes($app, $optimisticLocking, $mode);
150
            } else {
151 4
                $modified = $edit ? $crudData->update($instance) : $crudData->create($instance);
152 4
                $response = $modified ? $this->modifyFilesAndSetFlashBag($app, $crudData, $instance, $entity, $mode) : false;
153 4
                if ($response) {
154 4
                    return $response;
155
                }
156 2
                $app['session']->getFlashBag()->add('danger', $app['translator']->trans('crudlex.'.$mode.'.failed'));
157
            }
158
        }
159
160 3
        return $app['twig']->render($app['crud']->getTemplate('template', 'form', $entity), [
161 3
            'crud' => $app['crud'],
162 3
            'crudEntity' => $entity,
163 3
            'crudData' => $crudData,
164 3
            'entity' => $instance,
165 3
            'mode' => $mode,
166 3
            'fieldErrors' => $fieldErrors,
167 3
            'layout' => $app['crud']->getTemplate('layout', $mode, $entity)
168
        ]);
169
    }
170
171
    /**
172
     * Gets the parameters for the redirection after deleting an entity.
173
     *
174
     * @param Request $request
175
     * the current request
176
     * @param string $entity
177
     * the entity name
178
     * @param string $redirectPage
179
     * reference, where the page to redirect to will be stored
180
     *
181
     * @return array<string,string>
182
     * the parameters of the redirection, entity and id
183
     */
184 1
    protected function getAfterDeleteRedirectParameters(Request $request, $entity, &$redirectPage)
185
    {
186 1
        $redirectPage       = 'crudList';
187 1
        $redirectParameters = ['entity' => $entity];
188 1
        $redirectEntity     = $request->get('redirectEntity');
189 1
        $redirectId         = $request->get('redirectId');
190 1
        if ($redirectEntity && $redirectId) {
191 1
            $redirectPage       = 'crudShow';
192
            $redirectParameters = [
193 1
                'entity' => $redirectEntity,
194 1
                'id' => $redirectId
195
            ];
196
        }
197 1
        return $redirectParameters;
198
    }
199
200
    /**
201
     * Builds up the parameters of the list page filters.
202
     *
203
     * @param Request $request
204
     * the current application
205
     * @param EntityDefinition $definition
206
     * the current entity definition
207
     * @param array &$filter
208
     * will hold a map of fields to request parameters for the filters
209
     * @param boolean $filterActive
210
     * reference, will be true if at least one filter is active
211
     * @param array $filterToUse
212
     * reference, will hold a map of fields to integers (0 or 1) which boolean filters are active
213
     * @param array $filterOperators
214
     * reference, will hold a map of fields to operators for AbstractData::listEntries()
215
     */
216 4
    protected function buildUpListFilter(Request $request, EntityDefinition $definition, &$filter, &$filterActive, &$filterToUse, &$filterOperators)
217
    {
218 4
        foreach ($definition->getFilter() as $filterField) {
219 4
            $type                 = $definition->getType($filterField);
220 4
            $filter[$filterField] = $request->get('crudFilter'.$filterField);
221 4
            if ($filter[$filterField]) {
222 1
                $filterActive                  = true;
223 1
                $filterToUse[$filterField]     = $filter[$filterField];
224 1
                $filterOperators[$filterField] = '=';
225 1
                if ($type === 'boolean') {
226 1
                    $filterToUse[$filterField] = $filter[$filterField] == 'true' ? 1 : 0;
227 1
                } else if ($type === 'reference') {
228 1
                    $filter[$filterField] = ['id' => $filter[$filterField]];
229 1
                } else if ($type === 'many') {
230
                    $filter[$filterField] = array_map(function($value) {
231 1
                        return ['id' => $value];
232 1
                    }, $filter[$filterField]);
233 1
                    $filterToUse[$filterField] = $filter[$filterField];
234 1
                } else if (in_array($type, ['text', 'multiline', 'fixed'])){
235 1
                    $filterToUse[$filterField]     = '%'.$filter[$filterField].'%';
236 4
                    $filterOperators[$filterField] = 'LIKE';
237
                }
238
            }
239
        }
240 4
    }
241
242
    /**
243
     * Setups the templates.
244
     *
245
     * @param Application $app
246
     * the Application instance of the Silex application
247
     */
248 10
    protected function setupTemplates(Application $app)
249
    {
250 10
        if ($app->offsetExists('twig.loader.filesystem')) {
251 10
            $app['twig.loader.filesystem']->addPath(__DIR__.'/../views/', 'crud');
252
        }
253 10
    }
254
255
    /**
256
     * Setups the routes.
257
     *
258
     * @param Application $app
259
     * the Application instance of the Silex application
260
     *
261
     * @return mixed
262
     * the created controller factory
263
     */
264 10
    protected function setupRoutes(Application $app)
265
    {
266
267 10
        $self                 = $this;
268
        $localeAndCheckEntity = function(Request $request, Application $app) use ($self) {
269 9
            $locale = $app['translator']->getLocale();
270 9
            $app['crud']->setLocale($locale);
271 9
            if (!$app['crud']->getData($request->get('entity'))) {
272 7
                return $self->getNotFoundPage($app, $app['translator']->trans('crudlex.entityNotFound'));
273
            }
274 10
        };
275
276 10
        $class   = get_class($this);
277 10
        $factory = $app['controllers_factory'];
278 10
        $factory->get('/resource/static', $class.'::staticFile')->bind('crudStatic');
279 10
        $factory->match('/{entity}/create', $class.'::create')->bind('crudCreate')->before($localeAndCheckEntity, 10);
280 10
        $factory->get('/{entity}', $class.'::showList')->bind('crudList')->before($localeAndCheckEntity, 10);
281 10
        $factory->get('/{entity}/{id}', $class.'::show')->bind('crudShow')->before($localeAndCheckEntity, 10);
282 10
        $factory->match('/{entity}/{id}/edit', $class.'::edit')->bind('crudEdit')->before($localeAndCheckEntity, 10);
283 10
        $factory->post('/{entity}/{id}/delete', $class.'::delete')->bind('crudDelete')->before($localeAndCheckEntity, 10);
284 10
        $factory->get('/{entity}/{id}/{field}/file', $class.'::renderFile')->bind('crudRenderFile')->before($localeAndCheckEntity, 10);
285 10
        $factory->post('/{entity}/{id}/{field}/delete', $class.'::deleteFile')->bind('crudDeleteFile')->before($localeAndCheckEntity, 10);
286 10
        $factory->get('/setting/locale/{locale}', $class.'::setLocale')->bind('crudSetLocale');
287
288 10
        return $factory;
289
    }
290
291
    /**
292
     * Setups i18n.
293
     *
294
     * @param Application $app
295
     * the Application instance of the Silex application
296
     */
297
    protected function setupI18n(Application $app)
298
    {
299 10
        $app->before(function(Request $request, Application $app) {
300 10
            $manageI18n = $app['crud']->isManageI18n();
301 10
            if ($manageI18n) {
302 10
                $locale = $app['session']->get('locale', 'en');
303 10
                $app['translator']->setLocale($locale);
304
            }
305 10
        }, 1);
306 10
    }
307
308
    /**
309
     * Implements ControllerProviderInterface::connect() connecting this
310
     * controller.
311
     *
312
     * @param Application $app
313
     * the Application instance of the Silex application
314
     *
315
     * @return \Silex\ControllerCollection
316
     * this method is expected to return the used ControllerCollection instance
317
     */
318 10
    public function connect(Application $app)
319
    {
320 10
        $this->setupTemplates($app);
321 10
        $factory = $this->setupRoutes($app);
322 10
        $this->setupI18n($app);
323 10
        return $factory;
324
    }
325
326
    /**
327
     * The controller for the "create" action.
328
     *
329
     * @param Application $app
330
     * the Silex application
331
     * @param string $entity
332
     * the current entity
333
     *
334
     * @return Response
335
     * the HTTP response of this action
336
     */
337 4
    public function create(Application $app, $entity)
338
    {
339 4
        $crudData = $app['crud']->getData($entity);
340 4
        $instance = $crudData->createEmpty();
341 4
        $request  = $app['request_stack']->getCurrentRequest();
342 4
        $instance->populateViaRequest($request);
343 4
        return $this->modifyEntity($app, $crudData, $instance, $entity, false);
344
    }
345
346
    /**
347
     * The controller for the "show list" action.
348
     *
349
     * @param Request $request
350
     * the current request
351
     * @param Application $app
352
     * the Silex application
353
     * @param string $entity
354
     * the current entity
355
     *
356
     * @return Response
357
     * the HTTP response of this action or 404 on invalid input
358
     */
359 4
    public function showList(Request $request, Application $app, $entity)
360
    {
361 4
        $crudData   = $app['crud']->getData($entity);
362 4
        $definition = $crudData->getDefinition();
363
364 4
        $filter          = [];
365 4
        $filterActive    = false;
366 4
        $filterToUse     = [];
367 4
        $filterOperators = [];
368 4
        $this->buildUpListFilter($request, $definition, $filter, $filterActive, $filterToUse, $filterOperators);
369
370 4
        $pageSize = $definition->getPageSize();
371 4
        $total    = $crudData->countBy($definition->getTable(), $filterToUse, $filterOperators, true);
372 4
        $page     = abs(intval($request->get('crudPage', 0)));
373 4
        $maxPage  = intval($total / $pageSize);
374 4
        if ($total % $pageSize == 0) {
375 4
            $maxPage--;
376
        }
377 4
        if ($page > $maxPage) {
378 4
            $page = $maxPage;
379
        }
380 4
        $skip = $page * $pageSize;
381
382 4
        $sortField            = $request->get('crudSortField', $definition->getInitialSortField());
383 4
        $sortAscendingRequest = $request->get('crudSortAscending');
384 4
        $sortAscending        = $sortAscendingRequest !== null ? $sortAscendingRequest === 'true' : $definition->isInitialSortAscending();
385
386 4
        $entities = $crudData->listEntries($filterToUse, $filterOperators, $skip, $pageSize, $sortField, $sortAscending);
387
388 4
        return $app['twig']->render($app['crud']->getTemplate('template', 'list', $entity), [
389 4
            'crud' => $app['crud'],
390 4
            'crudEntity' => $entity,
391 4
            'crudData' => $crudData,
392 4
            'definition' => $definition,
393 4
            'entities' => $entities,
394 4
            'pageSize' => $pageSize,
395 4
            'maxPage' => $maxPage,
396 4
            'page' => $page,
397 4
            'total' => $total,
398 4
            'filter' => $filter,
399 4
            'filterActive' => $filterActive,
400 4
            'sortField' => $sortField,
401 4
            'sortAscending' => $sortAscending,
402 4
            'layout' => $app['crud']->getTemplate('layout', 'list', $entity)
403
        ]);
404
    }
405
406
    /**
407
     * The controller for the "show" action.
408
     *
409
     * @param Application $app
410
     * the Silex application
411
     * @param string $entity
412
     * the current entity
413
     * @param string $id
414
     * the instance id to show
415
     *
416
     * @return Response
417
     * the HTTP response of this action or 404 on invalid input
418
     */
419 6
    public function show(Application $app, $entity, $id)
420
    {
421 6
        $crudData = $app['crud']->getData($entity);
422 6
        $instance = $crudData->get($id);
423 6
        if (!$instance) {
424 1
            return $this->getNotFoundPage($app, $app['translator']->trans('crudlex.instanceNotFound'));
425
        }
426 6
        $definition = $crudData->getDefinition();
427
428 6
        $childrenLabelFields = $definition->getChildrenLabelFields();
429 6
        $children            = [];
430 6
        if (count($childrenLabelFields) > 0) {
431 3
            foreach ($definition->getChildren() as $child) {
432 3
                $childField      = $child[1];
433 3
                $childEntity     = $child[2];
434 3
                $childLabelField = array_key_exists($childEntity, $childrenLabelFields) ? $childrenLabelFields[$childEntity] : 'id';
435 3
                $childCrud       = $app['crud']->getData($childEntity);
436 3
                $children[]      = [
437 3
                    $childCrud->getDefinition()->getLabel(),
438 3
                    $childEntity,
439 3
                    $childLabelField,
440 3
                    $childCrud->listEntries([$childField => $instance->get('id')]),
441 3
                    $childField
442
                ];
443
            }
444
        }
445
446 6
        return $app['twig']->render($app['crud']->getTemplate('template', 'show', $entity), [
447 6
            'crud' => $app['crud'],
448 6
            'crudEntity' => $entity,
449 6
            'entity' => $instance,
450 6
            'children' => $children,
451 6
            'layout' => $app['crud']->getTemplate('layout', 'show', $entity)
452
        ]);
453
    }
454
455
    /**
456
     * The controller for the "edit" action.
457
     *
458
     * @param Application $app
459
     * the Silex application
460
     * @param string $entity
461
     * the current entity
462
     * @param string $id
463
     * the instance id to edit
464
     *
465
     * @return Response
466
     * the HTTP response of this action or 404 on invalid input
467
     */
468 1
    public function edit(Application $app, $entity, $id)
469
    {
470 1
        $crudData = $app['crud']->getData($entity);
471 1
        $instance = $crudData->get($id);
472 1
        if (!$instance) {
473 1
            return $this->getNotFoundPage($app, $app['translator']->trans('crudlex.instanceNotFound'));
474
        }
475
476 1
        return $this->modifyEntity($app, $crudData, $instance, $entity, true);
477
    }
478
479
    /**
480
     * The controller for the "delete" action.
481
     *
482
     * @param Application $app
483
     * the Silex application
484
     * @param string $entity
485
     * the current entity
486
     * @param string $id
487
     * the instance id to delete
488
     *
489
     * @return Response
490
     * redirects to the entity list page or 404 on invalid input
491
     */
492 1
    public function delete(Application $app, $entity, $id)
493
    {
494 1
        $crudData = $app['crud']->getData($entity);
495 1
        $instance = $crudData->get($id);
496 1
        if (!$instance) {
497 1
            return $this->getNotFoundPage($app, $app['translator']->trans('crudlex.instanceNotFound'));
498
        }
499
500 1
        $fileHandler  = new FileHandler($app['crud.filesystem'], $crudData->getDefinition());
501 1
        $filesDeleted = $fileHandler->deleteFiles($crudData, $instance, $entity);
502 1
        $deleted      = $filesDeleted ? $crudData->delete($instance) : AbstractData::DELETION_FAILED_EVENT;
503
504 1
        if ($deleted === AbstractData::DELETION_FAILED_EVENT) {
505 1
            $app['session']->getFlashBag()->add('danger', $app['translator']->trans('crudlex.delete.failed'));
506 1
            return $app->redirect($app['url_generator']->generate('crudShow', ['entity' => $entity, 'id' => $id]));
507 1
        } elseif ($deleted === AbstractData::DELETION_FAILED_STILL_REFERENCED) {
508 1
            $app['session']->getFlashBag()->add('danger', $app['translator']->trans('crudlex.delete.error', [
509 1
                '%label%' => $crudData->getDefinition()->getLabel()
510
            ]));
511 1
            return $app->redirect($app['url_generator']->generate('crudShow', ['entity' => $entity, 'id' => $id]));
512
        }
513
514 1
        $redirectPage       = 'crudList';
515 1
        $redirectParameters = $this->getAfterDeleteRedirectParameters($app['request_stack']->getCurrentRequest(), $entity, $redirectPage);
516
517 1
        $app['session']->getFlashBag()->add('success', $app['translator']->trans('crudlex.delete.success', [
518 1
            '%label%' => $crudData->getDefinition()->getLabel()
519
        ]));
520 1
        return $app->redirect($app['url_generator']->generate($redirectPage, $redirectParameters));
521
    }
522
523
    /**
524
     * The controller for the "render file" action.
525
     *
526
     * @param Application $app
527
     * the Silex application
528
     * @param string $entity
529
     * the current entity
530
     * @param string $id
531
     * the instance id
532
     * @param string $field
533
     * the field of the file to render of the instance
534
     *
535
     * @return Response
536
     * the rendered file
537
     */
538 1
    public function renderFile(Application $app, $entity, $id, $field)
539
    {
540 1
        $crudData   = $app['crud']->getData($entity);
541 1
        $instance   = $crudData->get($id);
542 1
        $definition = $crudData->getDefinition();
543 1
        if (!$instance || $definition->getType($field) != 'file' || !$instance->get($field)) {
544 1
            return $this->getNotFoundPage($app, $app['translator']->trans('crudlex.instanceNotFound'));
545
        }
546 1
        $fileHandler = new FileHandler($app['crud.filesystem'], $definition);
547 1
        return $fileHandler->renderFile($instance, $entity, $field);
548
    }
549
550
    /**
551
     * The controller for the "delete file" action.
552
     *
553
     * @param Application $app
554
     * the Silex application
555
     * @param string $entity
556
     * the current entity
557
     * @param string $id
558
     * the instance id
559
     * @param string $field
560
     * the field of the file to delete of the instance
561
     *
562
     * @return Response
563
     * redirects to the instance details page or 404 on invalid input
564
     */
565 1
    public function deleteFile(Application $app, $entity, $id, $field)
566
    {
567 1
        $crudData = $app['crud']->getData($entity);
568 1
        $instance = $crudData->get($id);
569 1
        if (!$instance) {
570 1
            return $this->getNotFoundPage($app, $app['translator']->trans('crudlex.instanceNotFound'));
571
        }
572 1
        $fileHandler = new FileHandler($app['crud.filesystem'], $crudData->getDefinition());
573 1
        if (!$crudData->getDefinition()->getField($field, 'required', false) && $fileHandler->deleteFile($crudData, $instance, $entity, $field)) {
574 1
            $instance->set($field, '');
575 1
            $crudData->update($instance);
576 1
            $app['session']->getFlashBag()->add('success', $app['translator']->trans('crudlex.file.deleted'));
577
        } else {
578 1
            $app['session']->getFlashBag()->add('danger', $app['translator']->trans('crudlex.file.notDeleted'));
579
        }
580 1
        return $app->redirect($app['url_generator']->generate('crudShow', ['entity' => $entity, 'id' => $id]));
581
    }
582
583
    /**
584
     * The controller for serving static files.
585
     *
586
     * @param Request $request
587
     * the current request
588
     * @param Application $app
589
     * the Silex application
590
     *
591
     * @return Response
592
     * redirects to the instance details page or 404 on invalid input
593
     */
594 1
    public function staticFile(Request $request, Application $app)
595
    {
596 1
        $fileParam = str_replace('..', '', $request->get('file'));
597 1
        $file      = __DIR__.'/../static/'.$fileParam;
598 1
        if (!$fileParam || !file_exists($file)) {
599 1
            return $this->getNotFoundPage($app, $app['translator']->trans('crudlex.resourceNotFound'));
600
        }
601
602 1
        $mimeType = MimeType::detectByFilename($file);
603 1
        $size     = filesize($file);
604
605 1
        $streamedFileResponse = new StreamedFileResponse();
606 1
        $response             = new StreamedResponse($streamedFileResponse->getStreamedFileFunction($file), 200, [
607 1
            'Content-Type' => $mimeType,
608 1
            'Content-Disposition' => 'attachment; filename="'.basename($file).'"',
609 1
            'Content-length' => $size
610
        ]);
611
612 1
        $response->setETag(filemtime($file))->setPublic()->isNotModified($request);
613 1
        $response->send();
614
615 1
        return $response;
616
    }
617
618
    /**
619
     * The controller for setting the locale.
620
     *
621
     * @param Request $request
622
     * the current request
623
     * @param Application $app
624
     * the Silex application
625
     * @param string $locale
626
     * the new locale
627
     *
628
     * @return Response
629
     * redirects to the instance details page or 404 on invalid input
630
     */
631 1
    public function setLocale(Request $request, Application $app, $locale)
632
    {
633
634 1
        if (!in_array($locale, $app['crud']->getLocales())) {
635 1
            return $this->getNotFoundPage($app, 'Locale '.$locale.' not found.');
636
        }
637
638 1
        $manageI18n = $app['crud']->isManageI18n();
639 1
        if ($manageI18n) {
640 1
            $app['session']->set('locale', $locale);
641
        }
642 1
        $redirect = $request->get('redirect');
643 1
        return $app->redirect($redirect);
0 ignored issues
show
Security Cross-Site Scripting introduced by
$redirect can contain request data and is used in output context(s) leading to a potential security vulnerability.

8 paths for user data to reach this point

  1. Path: $this->parameters['HTTP_AUTHORIZATION'] seems to return tainted data, and $authorizationHeader is assigned in ServerBag.php on line 62
  1. $this->parameters['HTTP_AUTHORIZATION'] seems to return tainted data, and $authorizationHeader is assigned
    in vendor/ServerBag.php on line 62
  2. ParameterBag::$parameters is assigned
    in vendor/ServerBag.php on line 77
  3. Tainted property ParameterBag::$parameters is read
    in vendor/ParameterBag.php on line 84
  4. ParameterBag::get() returns tainted data, and $result is assigned
    in vendor/Request.php on line 817
  5. Request::get() returns tainted data, and $redirect is assigned
    in src/CRUDlex/ControllerProvider.php on line 642
  2. Path: Read from $_POST, and $_POST is passed to Request::createRequestFromFactory() in Request.php on line 314
  1. Read from $_POST, and $_POST is passed to Request::createRequestFromFactory()
    in vendor/Request.php on line 314
  2. $request is passed to Request::__construct()
    in vendor/Request.php on line 2068
  3. $request is passed to Request::initialize()
    in vendor/Request.php on line 255
  4. $request is passed to ParameterBag::__construct()
    in vendor/Request.php on line 273
  5. ParameterBag::$parameters is assigned
    in vendor/ParameterBag.php on line 31
  6. Tainted property ParameterBag::$parameters is read
    in vendor/ParameterBag.php on line 84
  7. ParameterBag::get() returns tainted data, and $result is assigned
    in vendor/Request.php on line 817
  8. Request::get() returns tainted data, and $redirect is assigned
    in src/CRUDlex/ControllerProvider.php on line 642
  3. Path: Read from $_SERVER, and $server is assigned in Request.php on line 304
  1. Read from $_SERVER, and $server is assigned
    in vendor/Request.php on line 304
  2. $server is passed to Request::createRequestFromFactory()
    in vendor/Request.php on line 314
  3. $server is passed to Request::__construct()
    in vendor/Request.php on line 2068
  4. $server is passed to Request::initialize()
    in vendor/Request.php on line 255
  5. $server is passed to ParameterBag::__construct()
    in vendor/Request.php on line 278
  6. ParameterBag::$parameters is assigned
    in vendor/ParameterBag.php on line 31
  7. Tainted property ParameterBag::$parameters is read
    in vendor/ParameterBag.php on line 84
  8. ParameterBag::get() returns tainted data, and $result is assigned
    in vendor/Request.php on line 817
  9. Request::get() returns tainted data, and $redirect is assigned
    in src/CRUDlex/ControllerProvider.php on line 642
  4. Path: Fetching key HTTP_CONTENT_LENGTH from $_SERVER, and $server is assigned in Request.php on line 307
  1. Fetching key HTTP_CONTENT_LENGTH from $_SERVER, and $server is assigned
    in vendor/Request.php on line 307
  2. $server is passed to Request::createRequestFromFactory()
    in vendor/Request.php on line 314
  3. $server is passed to Request::__construct()
    in vendor/Request.php on line 2068
  4. $server is passed to Request::initialize()
    in vendor/Request.php on line 255
  5. $server is passed to ParameterBag::__construct()
    in vendor/Request.php on line 278
  6. ParameterBag::$parameters is assigned
    in vendor/ParameterBag.php on line 31
  7. Tainted property ParameterBag::$parameters is read
    in vendor/ParameterBag.php on line 84
  8. ParameterBag::get() returns tainted data, and $result is assigned
    in vendor/Request.php on line 817
  9. Request::get() returns tainted data, and $redirect is assigned
    in src/CRUDlex/ControllerProvider.php on line 642
  5. Path: Fetching key HTTP_CONTENT_TYPE from $_SERVER, and $server is assigned in Request.php on line 310
  1. Fetching key HTTP_CONTENT_TYPE from $_SERVER, and $server is assigned
    in vendor/Request.php on line 310
  2. $server is passed to Request::createRequestFromFactory()
    in vendor/Request.php on line 314
  3. $server is passed to Request::__construct()
    in vendor/Request.php on line 2068
  4. $server is passed to Request::initialize()
    in vendor/Request.php on line 255
  5. $server is passed to ParameterBag::__construct()
    in vendor/Request.php on line 278
  6. ParameterBag::$parameters is assigned
    in vendor/ParameterBag.php on line 31
  7. Tainted property ParameterBag::$parameters is read
    in vendor/ParameterBag.php on line 84
  8. ParameterBag::get() returns tainted data, and $result is assigned
    in vendor/Request.php on line 817
  9. Request::get() returns tainted data, and $redirect is assigned
    in src/CRUDlex/ControllerProvider.php on line 642
  6. Path: $server['HTTP_HOST'] seems to return tainted data, and $server is assigned in Request.php on line 380
  1. $server['HTTP_HOST'] seems to return tainted data, and $server is assigned
    in vendor/Request.php on line 380
  2. $server is assigned
    in vendor/Request.php on line 428
  3. $server is assigned
    in vendor/Request.php on line 429
  4. $server is passed to Request::createRequestFromFactory()
    in vendor/Request.php on line 431
  5. $server is passed to Request::__construct()
    in vendor/Request.php on line 2068
  6. $server is passed to Request::initialize()
    in vendor/Request.php on line 255
  7. $server is passed to ParameterBag::__construct()
    in vendor/Request.php on line 278
  8. ParameterBag::$parameters is assigned
    in vendor/ParameterBag.php on line 31
  9. Tainted property ParameterBag::$parameters is read
    in vendor/ParameterBag.php on line 84
  10. ParameterBag::get() returns tainted data, and $result is assigned
    in vendor/Request.php on line 817
  11. Request::get() returns tainted data, and $redirect is assigned
    in src/CRUDlex/ControllerProvider.php on line 642
  7. Path: $this->parameters['PHP_AUTH_USER'] seems to return tainted data, and $headers is assigned in ServerBag.php on line 43
  1. $this->parameters['PHP_AUTH_USER'] seems to return tainted data, and $headers is assigned
    in vendor/ServerBag.php on line 43
  2. $headers is assigned
    in vendor/ServerBag.php on line 44
  3. ServerBag::getHeaders() returns tainted data, and $this->server->getHeaders() is passed to HeaderBag::__construct()
    in vendor/Request.php on line 279
  4. $values is assigned
    in vendor/HeaderBag.php on line 29
  5. $values is passed to HeaderBag::set()
    in vendor/HeaderBag.php on line 30
  6. $values is passed through array_values(), and $values is assigned
    in vendor/HeaderBag.php on line 142
  7. HeaderBag::$headers is assigned
    in vendor/HeaderBag.php on line 145
  8. Tainted property HeaderBag::$headers is read
    in vendor/HeaderBag.php on line 65
  9. HeaderBag::all() returns tainted data, and $headers is assigned
    in vendor/HeaderBag.php on line 113
  10. HeaderBag::get() returns tainted data, and $requestUri is assigned
    in vendor/Request.php on line 1831
  11. $requestUri is passed to ParameterBag::set()
    in vendor/Request.php on line 1862
  12. ParameterBag::$parameters is assigned
    in vendor/ParameterBag.php on line 95
  13. Tainted property ParameterBag::$parameters is read
    in vendor/ParameterBag.php on line 84
  14. ParameterBag::get() returns tainted data, and $result is assigned
    in vendor/Request.php on line 817
  15. Request::get() returns tainted data, and $redirect is assigned
    in src/CRUDlex/ControllerProvider.php on line 642
  8. Path: $this->parameters['PHP_AUTH_PW'] seems to return tainted data, and $headers is assigned in ServerBag.php on line 44
  1. $this->parameters['PHP_AUTH_PW'] seems to return tainted data, and $headers is assigned
    in vendor/ServerBag.php on line 44
  2. ServerBag::getHeaders() returns tainted data, and $this->server->getHeaders() is passed to HeaderBag::__construct()
    in vendor/Request.php on line 279
  3. $values is assigned
    in vendor/HeaderBag.php on line 29
  4. $values is passed to HeaderBag::set()
    in vendor/HeaderBag.php on line 30
  5. $values is passed through array_values(), and $values is assigned
    in vendor/HeaderBag.php on line 142
  6. HeaderBag::$headers is assigned
    in vendor/HeaderBag.php on line 145
  7. Tainted property HeaderBag::$headers is read
    in vendor/HeaderBag.php on line 65
  8. HeaderBag::all() returns tainted data, and $headers is assigned
    in vendor/HeaderBag.php on line 113
  9. HeaderBag::get() returns tainted data, and $requestUri is assigned
    in vendor/Request.php on line 1831
  10. $requestUri is passed to ParameterBag::set()
    in vendor/Request.php on line 1862
  11. ParameterBag::$parameters is assigned
    in vendor/ParameterBag.php on line 95
  12. Tainted property ParameterBag::$parameters is read
    in vendor/ParameterBag.php on line 84
  13. ParameterBag::get() returns tainted data, and $result is assigned
    in vendor/Request.php on line 817
  14. Request::get() returns tainted data, and $redirect is assigned
    in src/CRUDlex/ControllerProvider.php on line 642

Used in output context

  1. Application::redirect() uses RedirectResponse::__construct() ($url)
    in vendor/src/Silex/Application.php on line 376
  2. RedirectResponse::__construct() uses RedirectResponse::setTargetUrl() ($url)
    in vendor/RedirectResponse.php on line 39
  3. RedirectResponse::setTargetUrl() uses Response::setContent() ($content)
    in vendor/RedirectResponse.php on line 92
  4. Response::setContent() uses property Response::$content for writing
    in vendor/Response.php on line 399
  5. Property Response::$content is used in echo
    in vendor/Response.php on line 358

Preventing Cross-Site-Scripting Attacks

Cross-Site-Scripting allows an attacker to inject malicious code into your website - in particular Javascript code, and have that code executed with the privileges of a visiting user. This can be used to obtain data, or perform actions on behalf of that visiting user.

In order to prevent this, make sure to escape all user-provided data:

// for HTML
$sanitized = htmlentities($tainted, ENT_QUOTES);

// for URLs
$sanitized = urlencode($tainted);

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
644
    }
645
}
646