Completed
Push — master ( a13fc6...7ee90b )
by Philip
02:42
created

ControllerProvider::staticFile()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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

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 82
  4. Response::setContent() uses property Response::$content for writing
    in vendor/Response.php on line 406
  5. Property Response::$content is used in echo
    in vendor/Response.php on line 365

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...
638
    }
639
}
640