Issues (1704)

Branch: master

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.

Bundle/QueryBundle/Helper/QueryHelper.php (9 issues)

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
namespace Victoire\Bundle\QueryBundle\Helper;
4
5
use Doctrine\Common\Annotations\Reader;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\EntityRepository;
8
use Doctrine\ORM\Mapping\ManyToMany;
9
use Doctrine\ORM\Mapping\ManyToOne;
10
use Doctrine\ORM\Mapping\OneToMany;
11
use Doctrine\ORM\Mapping\OneToOne;
12
use Doctrine\ORM\QueryBuilder;
13
use FOS\UserBundle\Model\UserInterface;
14
use Knp\DoctrineBehaviors\Model\Translatable\Translatable;
15
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
16
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
17
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
18
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
19
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
20
use Victoire\Bundle\CoreBundle\Entity\View;
21
use Victoire\Bundle\CoreBundle\Helper\CurrentViewHelper;
22
use Victoire\Bundle\QueryBundle\Entity\VictoireQueryInterface;
23
use Victoire\Bundle\WidgetBundle\Entity\Widget;
24
25
/**
26
 * The QueryHelper helps to build query in Victoire's components
27
 * ref: victoire_query.query_helper.
28
 */
29
class QueryHelper
30
{
31
    protected $businessEntityHelper = null;
32
    protected $currentView;
33
    protected $reader;
34
    protected $tokenStorage;
35
    /**
36
     * @var EntityRepository
37
     */
38
    private $businessEntityRepository;
39
40
    /**
41
     * Constructor.
42
     *
43
     * @param BusinessEntityHelper $businessEntityHelper
44
     * @param CurrentViewHelper    $currentView
45
     * @param Reader               $reader
46
     * @param TokenStorage         $tokenStorage
47
     * @param EntityRepository     $businessEntityRepository
48
     */
49
    public function __construct(BusinessEntityHelper $businessEntityHelper, CurrentViewHelper $currentView, Reader $reader, TokenStorage $tokenStorage, EntityRepository $businessEntityRepository)
50
    {
51
        $this->businessEntityHelper = $businessEntityHelper;
52
        $this->currentView = $currentView;
53
        $this->reader = $reader;
54
        $this->tokenStorage = $tokenStorage;
55
        $this->businessEntityRepository = $businessEntityRepository;
56
    }
57
58
    /**
0 ignored issues
show
Doc comment for parameter "$em" missing
Loading history...
59
     * Get the query builder base. This makes a "select  from item XXX"
60
     * use the item for doing the left join or where dql.
61
     *
62
     * @param \Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate $containerEntity
63
     *
64
     * @throws \Exception
65
     *
66
     * @return QueryBuilder
67
     */
68
    public function getQueryBuilder(VictoireQueryInterface $containerEntity, EntityManager $em)
69
    {
70
        if ($containerEntity === null) {
71
            throw new \Exception('The container entity parameter must not be null.');
72
        }
73
74
        //the business name of the container entity
75
        if ($containerEntity->getBusinessEntity()) {
76
            $businessEntity = $containerEntity->getBusinessEntity();
77
        } else {
78
            $businessEntity = $containerEntity->getEntityProxy()->getBusinessEntity();
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Victoire\Bundle\QueryBun...\VictoireQueryInterface as the method getEntityProxy() does only exist in the following implementations of said interface: Victoire\Bundle\WidgetBundle\Entity\Widget, Victoire\Widget\ForceBundle\Entity\WidgetForce, Victoire\Widget\LightSab...Entity\WidgetLightSaber.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
79
        }
80
        $businessEntityId = $businessEntity->getName();
81
82
        //test that there is a business entity name
83
        if ($businessEntityId === null || $businessEntityId === '') {
84
            $containerId = $containerEntity->getId();
85
            throw new \Exception('The container entity ['.$containerId.'] does not have any businessEntityId.');
86
        }
87
88
        //the business class of the container entity
89
        $businessEntity = $this->businessEntityRepository->findOneBy(['name' => strtolower($businessEntityId)]);
90
        //test that there was a businessEntity
91
        if ($businessEntity === null) {
92
            throw new \Exception('The business entity was not found for the id:['.$businessEntityId.']');
93
        }
94
95
        $businessClass = $businessEntity->getClass();
96
97
        $itemsQueryBuilder = $em
98
            ->createQueryBuilder()
99
            ->select('main_item')
100
            ->from($businessClass, 'main_item')
101
            ->andWhere('main_item.visibleOnFront = 1');
102
103
        $view = null;
104
        if ($containerEntity instanceof View) {
105
            $view = $containerEntity;
106
        } elseif ($containerEntity instanceof Widget) {
107
            $view = $containerEntity->getCurrentView();
108
        }
109
110
        // when the businessClass is translatable, join translations for the current locale
111
        if ($view && in_array(Translatable::class, class_uses($businessClass))) {
112
            $itemsQueryBuilder->join('main_item.translations', 'translation')
113
                ->andWhere('translation.locale = :locale')
114
                ->setParameter(':locale', $view->getCurrentLocale());
115
        }
116
117
        $refClass = new \ReflectionClass($businessClass);
118
        if ($refClass->hasMethod('getDeletedAt')) {
119
            $itemsQueryBuilder->andWhere('main_item.deletedAt IS NULL');
120
        }
121
122
        return $itemsQueryBuilder;
123
    }
124
125
    /**
0 ignored issues
show
Doc comment for parameter "$em" missing
Loading history...
126
     * Get the results from the sql after adding the.
127
     *
128
     * @param VictoireQueryInterface $containerEntity
129
     * @param QueryBuilder           $itemsQueryBuilder
130
     *
131
     * @throws \Exception
132
     *
133
     * @return QueryBuilder The QB to list of objects
134
     */
135
    public function buildWithSubQuery(VictoireQueryInterface $containerEntity, QueryBuilder $itemsQueryBuilder, EntityManager $em)
136
    {
137
        //get the query of the container entity
138
        $query = $containerEntity->getQuery();
139
        if (method_exists($containerEntity, 'additionnalQueryPart')) {
140
            $query = $containerEntity->additionnalQueryPart();
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Victoire\Bundle\QueryBun...\VictoireQueryInterface as the method additionnalQueryPart() does only exist in the following implementations of said interface: Victoire\Bundle\BlogBundle\Entity\ArticleTemplate.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
141
        }
142
143
        if ($query !== '' && $query !== null) {
144
            $subQuery = $em->createQueryBuilder()
145
                                ->select('item.id')
146
                                ->from($itemsQueryBuilder->getRootEntities()[0], 'item');
147
148
            $itemsQueryBuilder->andWhere(
149
                sprintf('main_item.id IN (%s %s)', $subQuery->getQuery()->getDql(), $query)
150
            );
151
        }
152
153
        //Add ORDER BY if set
154
        if ($orderBy = json_decode($containerEntity->getOrderBy(), true)) {
155
            foreach ($orderBy as $addOrderBy) {
156
                $reflectionClass = new \ReflectionClass($itemsQueryBuilder->getRootEntities()[0]);
157
                $reflectionProperty = $reflectionClass->getProperty($addOrderBy['by']);
158
159
                //If ordering field is an association, treat it as a boolean
160
                if ($this->isAssociationField($reflectionProperty)) {
161
                    $itemsQueryBuilder->addSelect('CASE WHEN main_item.'.$addOrderBy['by'].' IS NULL THEN 0 ELSE 1 END AS HIDDEN caseOrder');
162
                    $itemsQueryBuilder->addOrderBy('caseOrder', $addOrderBy['order']);
163
                } else {
164
                    $itemsQueryBuilder->addOrderBy('main_item.'.$addOrderBy['by'], $addOrderBy['order']);
165
                }
166
            }
167
        }
168
169
        $currentView = $this->currentView;
170
171
        // If the current page is a BEP, we parse all its properties and inject them as query parameters
172
        if ($currentView() && $currentView() instanceof BusinessPage && null !== $currentEntity = $currentView()->getBusinessEntity()) {
0 ignored issues
show
Blank line found at start of control structure
Loading history...
173
174
            // NEW
175
            $metadatas = $em->getClassMetadata(get_class($currentEntity));
176 View Code Duplication
            foreach ($metadatas->fieldMappings as $fieldName => $field) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
                if (strpos($query, ':'.$fieldName) !== false) {
178
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName));
179
                }
180
            }
181 View Code Duplication
            foreach ($metadatas->associationMappings as $fieldName => $field) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
182
                if (strpos($query, ':'.$fieldName) !== false) {
183
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName)->getId());
184
                }
185
            }
186
187
            if (strpos($query, ':currentEntity') !== false) {
188
                $itemsQueryBuilder->setParameter('currentEntity', $currentEntity->getId());
189
            }
190
        } elseif ($currentView() instanceof BusinessTemplate && strpos($query, ':currentEntity') !== false) {
191
            $itemsQueryBuilder->setParameter('currentEntity', $containerEntity->getEntity()->getId());
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Victoire\Bundle\QueryBun...\VictoireQueryInterface as the method getEntity() does only exist in the following implementations of said interface: Victoire\Bundle\WidgetBundle\Entity\Widget, Victoire\Widget\ForceBundle\Entity\WidgetForce, Victoire\Widget\LightSab...Entity\WidgetLightSaber.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
192
        }
193
194
        if (strpos($query, ':currentUser') !== false && is_object($this->getCurrentUser())) {
195
            if (is_object($this->getCurrentUser())) {
196
                $itemsQueryBuilder->setParameter('currentUser', $this->getCurrentUser()->getId());
197
            } else {
198
                throw new AccessDeniedException();
199
            }
200
        }
201
202
        return $itemsQueryBuilder;
203
    }
204
205
    /**
206
     * Check if field is a OneToOne, OneToMany, ManyToOne or ManyToMany association.
207
     *
208
     * @param \ReflectionProperty $field
209
     *
210
     * @return bool
211
     */
212
    private function isAssociationField(\ReflectionProperty $field)
213
    {
214
        $annotations = $this->reader->getPropertyAnnotations($field);
215
        foreach ($annotations as $key => $annotationObj) {
216
            if ($annotationObj instanceof OneToOne || $annotationObj instanceof OneToMany || $annotationObj instanceof ManyToOne || $annotationObj instanceof ManyToMany) {
217
                return true;
218
            }
219
        }
220
221
        return false;
222
    }
223
224
    /**
225
     * @return UserInterface|string
226
     */
227
    public function getCurrentUser()
0 ignored issues
show
Declare public methods first,then protected ones and finally private ones
Loading history...
228
    {
229
        return $this->tokenStorage->getToken()->getUser();
230
    }
231
}
232