Issues (655)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Admin/AdminHelper.php (2 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\AdminBundle\Admin;
15
16
use Doctrine\Common\Collections\Collection;
17
use Doctrine\ODM\MongoDB\PersistentCollection;
18
use Doctrine\ORM\PersistentCollection as DoctrinePersistentCollection;
19
use Sonata\AdminBundle\Exception\NoValueException;
20
use Sonata\AdminBundle\Manipulator\ObjectManipulator;
21
use Sonata\AdminBundle\Util\FormBuilderIterator;
22
use Sonata\AdminBundle\Util\FormViewIterator;
23
use Symfony\Component\Form\FormBuilderInterface;
24
use Symfony\Component\Form\FormView;
25
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
26
27
/**
28
 * @final since sonata-project/admin-bundle 3.52
29
 *
30
 * @author Thomas Rabaix <[email protected]>
31
 */
32
class AdminHelper
33
{
34
    /**
35
     * @var string
36
     */
37
    private const FORM_FIELD_DELETE = '_delete';
38
39
    /**
40
     * @var PropertyAccessorInterface
41
     */
42
    protected $propertyAccessor;
43
44
    public function __construct(PropertyAccessorInterface $propertyAccessor)
45
    {
46
        $this->propertyAccessor = $propertyAccessor;
47
    }
48
49
    /**
50
     * @throws \RuntimeException
51
     */
52
    public function getChildFormBuilder(FormBuilderInterface $formBuilder, string $elementId): ?FormBuilderInterface
53
    {
54
        foreach (new FormBuilderIterator($formBuilder) as $name => $formBuilder) {
55
            if ($name === $elementId) {
56
                return $formBuilder;
57
            }
58
        }
59
60
        return null;
61
    }
62
63
    public function getChildFormView(FormView $formView, string $elementId): ?FormView
64
    {
65
        foreach (new \RecursiveIteratorIterator(new FormViewIterator($formView), \RecursiveIteratorIterator::SELF_FIRST) as $name => $formView) {
66
            if ($name === $elementId) {
67
                return $formView;
68
            }
69
        }
70
71
        return null;
72
    }
73
74
    /**
75
     * Note:
76
     *   This code is ugly, but there is no better way of doing it.
77
     *
78
     * @throws \RuntimeException
79
     * @throws \Exception
80
     */
81
    public function appendFormFieldElement(AdminInterface $admin, object $subject, string $elementId): array
82
    {
83
        // child rows marked as toDelete
84
        $toDelete = [];
85
86
        $formBuilder = $admin->getFormBuilder();
87
88
        // get the field element
89
        $childFormBuilder = $this->getChildFormBuilder($formBuilder, $elementId);
90
91
        if ($childFormBuilder) {
92
            $formData = $admin->getRequest()->get($formBuilder->getName(), []);
93
            if (\array_key_exists($childFormBuilder->getName(), $formData)) {
94
                $formData = $admin->getRequest()->get($formBuilder->getName(), []);
95
                $i = 0;
96
                foreach ($formData[$childFormBuilder->getName()] as $name => &$field) {
97
                    $toDelete[$i] = false;
98
                    if (\array_key_exists(self::FORM_FIELD_DELETE, $field)) {
99
                        $toDelete[$i] = true;
100
                        unset($field[self::FORM_FIELD_DELETE]);
101
                    }
102
                    ++$i;
103
                }
104
            }
105
            $admin->getRequest()->request->set($formBuilder->getName(), $formData);
106
        }
107
108
        $form = $formBuilder->getForm();
109
        $form->setData($subject);
110
        $form->handleRequest($admin->getRequest());
111
112
        //Child form not found (probably nested one)
113
        //if childFormBuilder was not found resulted in fatal error getName() method call on non object
114
        if (!$childFormBuilder) {
115
            $path = $this->getElementAccessPath($elementId, $subject);
116
117
            $collection = $this->propertyAccessor->getValue($subject, $path);
118
119
            if ($collection instanceof DoctrinePersistentCollection || $collection instanceof PersistentCollection) {
0 ignored issues
show
The class Doctrine\ORM\PersistentCollection does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
The class Doctrine\ODM\MongoDB\PersistentCollection does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
120
                //since doctrine 2.4
121
                $modelClassName = $collection->getTypeClass()->getName();
122
            } elseif ($collection instanceof Collection) {
123
                $modelClassName = $this->getModelClassName($admin, explode('.', preg_replace('#\[\d*?\]#', '', $path)));
124
            } else {
125
                throw new \Exception('unknown collection class');
126
            }
127
128
            $collection->add(new $modelClassName());
129
            $this->propertyAccessor->setValue($subject, $path, $collection);
130
131
            $fieldDescription = null;
132
        } else {
133
            // retrieve the FieldDescription
134
            $fieldDescription = $admin->getFormFieldDescription($childFormBuilder->getName());
135
136
            try {
137
                $value = $fieldDescription->getValue($form->getData());
138
            } catch (NoValueException $e) {
139
                $value = null;
140
            }
141
142
            // retrieve the posted data
143
            $data = $admin->getRequest()->get($formBuilder->getName());
144
145
            if (!isset($data[$childFormBuilder->getName()])) {
146
                $data[$childFormBuilder->getName()] = [];
147
            }
148
149
            $objectCount = null === $value ? 0 : \count($value);
150
            $postCount = \count($data[$childFormBuilder->getName()]);
151
152
            $associationAdmin = $fieldDescription->getAssociationAdmin();
153
154
            // add new elements to the subject
155
            while ($objectCount < $postCount) {
156
                // append a new instance into the object
157
                ObjectManipulator::addInstance($form->getData(), $associationAdmin->getNewInstance(), $fieldDescription);
158
                ++$objectCount;
159
            }
160
161
            $newInstance = ObjectManipulator::addInstance($form->getData(), $associationAdmin->getNewInstance(), $fieldDescription);
162
163
            $associationAdmin->setSubject($newInstance);
164
        }
165
166
        $finalForm = $admin->getFormBuilder()->getForm();
167
        $finalForm->setData($subject);
168
169
        // bind the data
170
        $finalForm->setData($form->getData());
171
172
        // back up delete field
173
        if (\count($toDelete) > 0) {
174
            $i = 0;
175
            foreach ($finalForm->get($childFormBuilder->getName()) as $childField) {
176
                if ($childField->has(self::FORM_FIELD_DELETE)) {
177
                    $childField->get(self::FORM_FIELD_DELETE)->setData($toDelete[$i] ?? false);
178
                }
179
                ++$i;
180
            }
181
        }
182
183
        return [$fieldDescription, $finalForm];
184
    }
185
186
    /**
187
     * Get access path to element which works with PropertyAccessor.
188
     *
189
     * @param string $elementId expects string in format used in form id field.
190
     *                          (uniqueIdentifier_model_sub_model or uniqueIdentifier_model_1_sub_model etc.)
191
     * @param mixed  $model
192
     *
193
     * @throws \Exception
194
     */
195
    public function getElementAccessPath(string $elementId, $model): string
196
    {
197
        $idWithoutIdentifier = preg_replace('/^[^_]*_/', '', $elementId);
198
        $initialPath = preg_replace('#(_(\d+)_)#', '[$2]_', $idWithoutIdentifier);
199
200
        $parts = explode('_', $initialPath);
201
        $totalPath = '';
202
        $currentPath = '';
203
204
        foreach ($parts as $part) {
205
            $currentPath .= empty($currentPath) ? $part : '_'.$part;
206
            $separator = empty($totalPath) ? '' : '.';
207
208
            if ($this->propertyAccessor->isReadable($model, $totalPath.$separator.$currentPath)) {
209
                $totalPath .= $separator.$currentPath;
210
                $currentPath = '';
211
            }
212
        }
213
214
        if (!empty($currentPath)) {
215
            throw new \Exception(sprintf(
216
                'Could not get element id from %s Failing part: %s',
217
                $elementId,
218
                $currentPath
219
            ));
220
        }
221
222
        return $totalPath;
223
    }
224
225
    /**
226
     * Recursively find the class name of the admin responsible for the element at the end of an association chain.
227
     */
228
    protected function getModelClassName(AdminInterface $admin, array $elements): string
229
    {
230
        $element = array_shift($elements);
231
        $associationAdmin = $admin->getFormFieldDescription($element)->getAssociationAdmin();
232
        if (0 === \count($elements)) {
233
            return $associationAdmin->getClass();
234
        }
235
236
        return $this->getModelClassName($associationAdmin, $elements);
237
    }
238
}
239