Issues (243)

Security Analysis    2 potential vulnerabilities

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 (2)
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/widget/GridViewWidget.php (15 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 /** MicroGridViewWidget */
2
3
namespace Micro\Widget;
4
5
use Micro\Base\Exception;
6
use Micro\Db\Injector;
7
use Micro\File\Type;
8
use Micro\Mvc\Models\IModel;
9
use Micro\Mvc\Models\IQuery;
10
use Micro\Mvc\Models\Query;
11
use Micro\Mvc\Widget;
12
use Micro\Web\Html\Html;
13
use Micro\Web\RequestInjector;
14
15
/**
16
 * GridViewWidget class file.
17
 *
18
 * @author Oleg Lunegov <[email protected]>
19
 * @link https://github.com/linpax/microphp-framework
20
 * @copyright Copyright (c) 2013 Oleg Lunegov
21
 * @license https://github.com/linpax/microphp-framework/blob/master/LICENSE
22
 * @package Micro
23
 * @subpackage Widget
24
 * @version 1.0
25
 * @since 1.0
26
 */
27
class GridViewWidget extends Widget
28
{
29
    /** @var int $page Current page on table */
30
    public $page = 0;
31
    /** @var int $limit Limit current rows */
32
    public $limit = 10;
33
    /** @var bool $filters Usage filters */
34
    public $filters = true;
35
    /** @var string $template Template render */
36
    public $template = '{counter}{table}{pager}';
37
    /** @var string $templateTable Template table render */
38
    public $templateTable = '{headers}{filters}{rows}';
39
    /** @var string $textCounter text for before counter */
40
    public $counterText = 'Sum: ';
41
    /** @var string $emptyText text to render if rows not found */
42
    public $emptyText = 'Elements not found';
43
    /** @var array $attributesEmpty Attributes for empty text */
44
    public $attributesEmpty = [];
45
    /** @var array $attributes attributes for table */
46
    public $attributes = [];
47
    /** @var array $attributesCounter attributes for counter */
48
    public $attributesCounter = [];
49
    /** @var array $attributesHeading attributes for heading */
50
    public $attributesHeading = [];
51
    /** @var array $attributesFilter attributes for filter row */
52
    public $attributesFilter = [];
53
    /** @var array $attributesFilterForm attributes for filter form */
54
    public $attributesFilterForm = [];
55
    /** @var array $tableConfig table configuration */
56
    public $tableConfig = [];
57
    /** @var array $paginationConfig parameters for PaginationWidget */
58
    public $paginationConfig = [];
59
60
    /** @var array $rows Rows from data */
61
    protected $rows;
62
    /** @var array $fields Fields of data */
63
    protected $fields = [];
64
    /** @var int $rowsCount Count rows */
65
    protected $rowsCount = 0;
66
    /** @var int $totalCount Total count data */
67
    protected $totalCount = 0;
68
    /** @var string $filterPrefix prefix for filter name */
69
    protected $filterPrefix;
70
71
72
    /**
73
     * Re-declare widget constructor
74
     *
75
     * @access public
76
     *
77
     * @param array $args arguments
78
     *
79
     * @result void
80
     * @throws Exception
81
     */
82
    public function __construct(array $args = [])
83
    {
84
        parent::__construct($args);
85
86
        if (!array_key_exists('data', $args)) {
87
            throw new Exception('Argument "data" not initialized into GridViewWidget');
88
        }
89
90
        $this->limit = ($this->limit < 10) ? 10 : $this->limit;
91
        $this->page = ($this->page < 0) ? 0 : $this->page;
92
93
        /** @var IQuery|array $data */
94
        $data = $args['data'];
95
96
        if ($data instanceof IQuery) {
97 View Code Duplication
            if ($data->objectName) {
0 ignored issues
show
Accessing objectName on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
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...
98
                /** @var IModel $cls */
99
                $cls = $data->objectName;
0 ignored issues
show
Accessing objectName on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
100
                /** @noinspection PhpUndefinedFieldInspection */
101
                $data->table = $cls::$tableName;
0 ignored issues
show
Accessing table on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
102
            } elseif (!$args['data']->table) {
103
                throw new Exception('Data query not set table or objectName');
104
            }
105
106
            if ($data->having || $data->group) {
0 ignored issues
show
Accessing having on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Accessing group on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
107
                $res = new Query((new Injector)->getDriver());
108
                $res->select = 'COUNT(*)';
109
                $res->table = '('.$data->getQuery().') micro_count';
110
                $res->single = true;
111
            } else {
112
                /** @var Query $res */
113
                $res = clone $data;
114
                $res->objectName = null;
115
                $res->select = 'COUNT(*)';
116
                $res->single = true;
117
            }
118
119
            /** @var array $a */
120
            $this->totalCount = ($a = $res->run(\PDO::FETCH_NUM)) ? $a[0] : 0;
121
            $this->filterPrefix = $data->table;
0 ignored issues
show
Accessing table on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
122
123
            $data->offset = $this->page * $this->limit;
0 ignored issues
show
Accessing offset on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
124
            $data->limit = $this->limit;
0 ignored issues
show
Accessing limit on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
125
            $data = $data->run($data->objectName ? \PDO::FETCH_CLASS : \PDO::FETCH_ASSOC);
0 ignored issues
show
Accessing objectName on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
126
        } else { // array
127
            $this->totalCount = count($data);
128
            $data = array_slice($data, $this->page * $this->limit, $this->limit);
129
        }
130
131
        /** @noinspection ForeachSourceInspection */
132
        foreach ($data AS $model) {
133
            $this->rows[] = is_subclass_of($model, 'Micro\Mvc\Models\Model') ? $model : (object)$model;
134
        }
135
    }
136
137
    /**
138
     * Initialize widget
139
     *
140
     * @access public
141
     *
142
     * @result void
143
     */
144
    public function init()
145
    {
146
        $this->filterPrefix = ucfirst($this->filterPrefix ?: 'data'.$this->totalCount);
147
        $this->fields = (null !== $this->rows) ? array_keys(Type::getVars($this->rows[0])) : [];
148
        $this->rowsCount = count($this->rows);
149
        $this->paginationConfig['countRows'] = $this->totalCount;
150
        $this->paginationConfig['limit'] = $this->limit;
151
        $this->paginationConfig['currentPage'] = $this->page;
152
        $this->tableConfig = $this->tableConfig ?: $this->fields;
153
154
        foreach ($this->tableConfig AS $key => $conf) {
155
            unset($this->tableConfig[$key]);
156
157
            $this->tableConfig[is_string($conf) ? $conf : $key] = array_merge([
158
                'attributesHeader' => !empty($conf['attributesHeader']) ? $conf['attributesHeader'] : [],
159
                'attributesFilter' => !empty($conf['attributesFilter']) ? $conf['attributesFilter'] : [],
160
                'attributes' => !empty($conf['attributes']) ? $conf['attributes'] : []
161
            ], is_array($conf) ? $conf : []);
162
        }
163
    }
164
165
    /**
166
     * Running widget
167
     *
168
     * @access public
169
     *
170
     * @return string
171
     * @throws Exception
172
     */
173
    public function run()
174
    {
175 View Code Duplication
        if (!$this->rows) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->rows of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
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...
176
            return Html::openTag('div', $this->attributesEmpty).$this->emptyText.Html::closeTag('div');
177
        }
178
179
        ob_start();
180
        echo str_replace(
181
            ['{counter}', '{pager}', '{table}'],
182
            [$this->getCounter(), $this->getPager(), $this->getTable()],
183
            $this->template
184
        );
185
186
        return ob_get_clean();
187
    }
188
189
    /**
190
     * Get counter
191
     *
192
     * @access protected
193
     *
194
     * @return string
195
     */
196
    protected function getCounter()
197
    {
198
        return Html::openTag('div', $this->attributesCounter).
199
        $this->counterText.$this->totalCount.Html::closeTag('div');
200
    }
201
202
    /**
203
     * Get pager
204
     *
205
     * @access protected
206
     *
207
     * @return string
208
     */
209 View Code Duplication
    protected function getPager()
0 ignored issues
show
This method seems to be duplicated in 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...
210
    {
211
        if (!$this->rows) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->rows of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
212
            return '';
213
        }
214
215
        $pager = new PaginationWidget($this->paginationConfig);
216
        $pager->init();
217
218
        return $pager->run();
219
    }
220
221
    /**
222
     * Get table
223
     *
224
     * @access protected
225
     *
226
     * @return string
227
     * @throws Exception
228
     */
229
    protected function getTable()
230
    {
231
        $table = str_replace(
232
            ['{headers}', '{filters}', '{rows}'],
233
            [$this->renderHeading(), $this->renderFilters(), $this->renderRows()],
234
            $this->templateTable
235
        );
236
237
        return Html::openTag('table', $this->attributes).$table.Html::closeTag('table');
238
    }
239
240
    /**
241
     * Render heading
242
     *
243
     * @access protected
244
     *
245
     * @return string
246
     */
247
    protected function renderHeading()
248
    {
249
        $result = Html::openTag('tr', $this->attributesHeading);
250
        foreach ($this->tableConfig AS $key => $row) {
251
            $result .= Html::openTag('th', $row['attributesHeader']);
252
            if (!empty($row['header'])) {
253
                $result .= $row['header'];
254
            } else {
255
                if (is_string($key)) {
256
                    /** @noinspection PhpUndefinedMethodInspection */
257
                    $result .= is_subclass_of($this->rows[0],
258
                        'Micro\\Mvc\\Models\\Model') ? $this->rows[0]->getLabel($key) : ucfirst($key);
259
                }
260
            }
261
            $result .= Html::closeTag('th');
262
        }
263
264
        return $result.Html::closeTag('tr');
265
    }
266
267
    /**
268
     * Render filters
269
     *
270
     * @access protected
271
     *
272
     * @return null|string
273
     * @throws Exception
274
     */
275
    protected function renderFilters()
276
    {
277
        if (!$this->filters) {
278
            return null;
279
        }
280
        /** @var array $filtersData */
281
        $query = (new RequestInjector)->build()->getQueryParams();
282
        $filtersData = array_key_exists($this->filterPrefix, $query) ? $query[$this->filterPrefix] : null;
283
284
        $result = Html::beginForm(null, 'get', $this->attributesFilterForm);
285
        $result .= Html::openTag('tr', $this->attributesFilter);
286
287
        foreach ($this->tableConfig AS $key => $row) {
288
            $result .= Html::openTag('td', $row['attributesFilter']);
289
            if (array_key_exists('filter', $row) && $row['filter'] === false) {
290
                continue;
291
            }
292
            if (!empty($row['filter'])) {
293
                $result .= $row['filter'];
294
            } else {
295
                $buffer = is_array($row) ? $key : $row;
296
                $fieldName = $this->filterPrefix.'['.$buffer.']';
297
                $fieldId = $this->filterPrefix.'_'.$buffer;
298
                $val = !empty($filtersData[$buffer]) ? $filtersData[$buffer] : '';
299
                $result .= Html::textField($fieldName, $val, ['id' => $fieldId]);
300
            }
301
            $result .= Html::closeTag('td');
302
        }
303
304
        return $result.Html::closeTag('tr').Html::endForm();
305
    }
306
307
    /**
308
     * Render rows
309
     *
310
     * @access protected
311
     *
312
     * @return null|string
313
     */
314
    protected function renderRows()
315
    {
316
        $result = null;
317
318
        if (0 === count($this->rows)) {
319
            return Html::openTag('tr').
320
            Html::openTag('td', ['cols' => count($this->fields)]).$this->emptyText.Html::closeTag('td').
321
            Html::closeTag('tr');
322
        }
323
324
        foreach ($this->rows AS $data) {
325
            $result .= Html::openTag('tr');
326
327
            foreach ($this->tableConfig AS $key => $row) {
328
                $result .= Html::openTag('td', $row['attributes']);
329
330
                if (!empty($row['class']) && is_subclass_of($row['class'], 'Micro\\Widget\\GridColumn')) {
331
                    $primaryKey = $data->{!empty($row['key']) ? $row['key'] : 'id'};
332
                    $result .= (string)new $row['class'](
333
                        $row + ['str' => (null === $data) ?: $data, 'pKey' => $primaryKey]
334
                    );
335
                } elseif (!empty($row['value'])) {
336
                    $result .= eval('return '.$row['value'].';');
0 ignored issues
show
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
337
                } else {
338
                    $result .= property_exists($data, $key) ? $data->$key : null;
339
                }
340
                $result .= Html::closeTag('td');
341
            }
342
            $result .= Html::closeTag('tr');
343
        }
344
345
        return $result;
346
    }
347
}
348