Issues (19)

Security Analysis    no request data  

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.

QueryGenerator.php (2 issues)

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
 * KumbiaPHP web & app Framework.
4
 *
5
 * LICENSE
6
 *
7
 * This source file is subject to the new BSD license that is bundled
8
 * with this package in the file LICENSE.txt.
9
 * It is also available through the world-wide-web at this URL:
10
 * http://wiki.kumbiaphp.com/Licencia
11
 * If you did not receive a copy of the license and are unable to
12
 * obtain it through the world-wide-web, please send an email
13
 * to [email protected] so we can send you a copy immediately.
14
 *
15
 * @category   Kumbia
16
 *
17
 * @copyright  2005 - 2016  Kumbia Team (http://www.kumbiaphp.com)
18
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
19
 */
20
namespace Kumbia\ActiveRecord;
21
22
/**
23
 * Generador de codigo SQL.
24
 */
25
class QueryGenerator
26
{
27
    /**
28
     * Construye una consulta select desde una lista de parametros.
29
     *
30
     * @param array  $params parametros de consulta select
31
     *                       where: condiciones where
32
     *                       order: criterio de ordenamiento
33
     *                       fields: lista de campos
34
     *                       join: joins de tablas
35
     *                       group: agrupar campos
36
     *                       having: condiciones de grupo
37
     *                       limit: valor limit
38
     *                       offset: valor offset
39
     * @param string $source
40
     * @param string $type
41
     *
42
     * @return string
43
     */
44
    public static function select($source, $type, array $params)
45
    {
46
        $params = array_merge([
47
            'fields' => '*',
48
            'join'   => '',
49
            'limit'  => null,
50
            'offset' => null,
51
            'where'  => null,
52
            'group'  => null,
53
            'having' => null,
54
            'order'  => null,
55
        ], $params);
56
57
        list($where, $group, $having, $order) = static::prepareParam($params);
58
        $sql = "SELECT {$params['fields']} FROM $source {$params['join']} $where $group $having $order";
59
60
        if (!is_null($params['limit']) || !is_null($params['offset'])) {
61
            $sql = self::query($type, 'limit', $sql, $params['limit'], $params['offset']);
62
        }
63
64
        return $sql;
65
    }
66
67
    /**
68
     * Permite construir el WHERE, GROUP BY, HAVING y ORDER BY de una consulta SQL
69
     * en base a los parámetros $params.
70
     *
71
     * @param array $params
72
     * @return array
73
     */
74
    protected static function prepareParam(array $params)
75
    {
76
        return [
77
            static::where($params['where']),
78
            static::group($params['group']),
79
            static::having($params['having']),
80
            static::order($params['order']),
81
        ];
82
    }
83
84
    /**
85
     * Genera una sentencia where.
86
     *
87
     * @param $where
88
     * @return string
89
     */
90
    protected static function where($where)
91
    {
92
        return empty($where)  ? '' : "WHERE $where";
93
    }
94
95
    /**
96
     * Genera una sentencia GROUP.
97
     *
98
     * @param $group
99
     * @return string
100
     */
101
    protected static function group($group)
102
    {
103
        return empty($group)  ? '' : "GROUP BY $group";
104
    }
105
106
    /**
107
     * Genera una sentencia HAVING.
108
     *
109
     * @param $having
110
     * @return string
111
     */
112
    protected static function having($having)
113
    {
114
        return empty($having)  ? '' : "HAVING $having";
115
    }
116
117
    /**
118
     * Genera una sentencia ORDER BY.
119
     *
120
     * @param $order
121
     * @return string
122
     */
123
    protected static function order($order)
124
    {
125
        return empty($order)  ? '' : "ORDER BY $order";
126
    }
127
128
    /**
129
     * Construye una consulta INSERT.
130
     *
131
     * @param \Kumbia\ActiveRecord\LiteRecord $model Modelo a actualizar
132
     * @param array                           $data  Datos pasados a la consulta preparada
133
     *
134
     * @return string
135
     */
136
    public static function insert(\Kumbia\ActiveRecord\LiteRecord $model, &$data)
137
    {
138
        $meta = $model::metadata();
139
        $data = [];
140
        $columns = [];
141
        $values = [];
142
143
        // Preparar consulta
144
        foreach ($meta->getFieldsList() as $field) {
145
            $columns[] = $field;
146
            static::insertField($field, $model, $data, $values);
147
        }
148
        $columns = \implode(',', $columns);
149
        $values = \implode(',', $values);
150
        $source = $model::getSource();
151
152
        return "INSERT INTO $source ($columns) VALUES ($values)";
153
    }
154
155
    /**
156
     * Agrega un campo a para generar una consulta preparada para un INSERT.
157
     *
158
     * @param string     $field  Nombre del campo
159
     * @param LiteRecord $model  valor del campo
160
     * @param array      $data   array de datos
161
     * @param array      $values array de valores
162
     *
163
     * @return void
164
     */
165
    protected static function insertField($field, LiteRecord $model, array &$data, array &$values)
166
    {
167
        $meta = $model::metadata();
168
        $withDefault = $meta->getWithDefault();
0 ignored issues
show
$withDefault is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
169
        $autoFields = $meta->getAutoFields();
0 ignored issues
show
$autoFields is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
170
        if (self::haveValue($model, $field)) {
171
            $data[":$field"] = $model->$field;
172
            $values[] = ":$field";
173
        } else{//if (!\in_array($field, $withDefault) && !\in_array($field, $autoFields)) {
174
            $values[] = 'NULL';
175
        }
176
    }
177
178
    /**
179
     * Permite conocer si la columna debe definirse como nula.
180
     *
181
     * @param LiteRecord $model
182
     * @param string     $field
183
     *
184
     * @return bool
185
     */
186
    protected static function haveValue(LiteRecord $model, $field)
187
    {
188
        return isset($model->$field) && $model->$field !== '';
189
    }
190
191
    /**
192
     * Construye una consulta UPDATE.
193
     *
194
     * @param \Kumbia\ActiveRecord\LiteRecord $model Modelo a actualizar
195
     * @param array                           $data  Datos pasados a la consulta preparada
196
     *
197
     * @return string
198
     */
199
    public static function update(\Kumbia\ActiveRecord\LiteRecord $model, array &$data)
200
    {
201
        $set = [];
202
        $pk = $model::getPK();
203
        /*elimina la clave primaria*/
204
        $list = array_diff($model::metadata()->getFieldsList(), [$pk]);
205
        foreach ($list as $field) {
206
            $value = isset($model->$field) ? $model->$field : null;
207
            static::updateField($field, $value, $data, $set);
208
        }
209
        $set = \implode(', ', $set);
210
        $source = $model::getSource();
211
        $data[":$pk"] = $model->$pk;
212
213
        return "UPDATE $source SET $set WHERE $pk = :$pk";
214
    }
215
216
    /**
217
     * Generate SQL for DELETE sentence.
218
     *
219
     * @param string $source source
220
     * @param string $where  condition
221
     *
222
     * @return string SQL
223
     */
224
    public static function deleteAll($source, $where)
225
    {
226
        return "DELETE FROM $source ".static::where($where);
227
    }
228
229
    /**
230
     * Generate SQL for COUNT sentence.
231
     *
232
     * @param string $source source
233
     * @param string $where  condition
234
     *
235
     * @return string SQL
236
     */
237
    public static function count($source, $where)
238
    {
239
        return "SELECT COUNT(*) AS count FROM $source ".static::where($where);
240
    }
241
242
    /**
243
     * Agrega un campo a para generar una consulta preparada para un UPDATE.
244
     *
245
     * @param string $field Nombre del campo
246
     * @param mixed  $value valor
247
     * @param array  $data  array de datos
248
     * @param array  $set   array de valores
249
     *
250
     * @return void
251
     */
252
    protected static function updateField($field, $value, array &$data, array &$set)
253
    {
254
        if (!empty($value)) {
255
            $data[":$field"] = $value;
256
            $set[] = "$field = :$field";
257
        } else {
258
            $set[] = "$field = NULL";
259
        }
260
    }
261
262
    /**
263
     * Construye una consulta UPDATE.
264
     *
265
     * @param string      $model  nombre del modelo a actualizar
266
     * @param array       $fields campos a actualizar
267
     * @param array       $data   Datos pasados a la consulta preparada
268
     * @param string|null $where
269
     *
270
     * @todo ┬┐Hay que escapar los nombres de los campos?
271
     *
272
     * @return string
273
     */
274
    public static function updateAll($model, array $fields, array &$data, $where)
275
    {
276
        $set = [];
277
        //$pk = $model::getPK();
278
        /*elimina la clave primaria*/
279
        foreach ($fields as $field => $value) {
280
            static::updateField($field, $value, $data, $set);
281
        }
282
        $set = \implode(', ', $set);
283
        $source = $model::getSource();
284
        $where = static::where($where);
285
286
        return "UPDATE $source SET $set $where";
287
    }
288
289
    /**
290
     * Ejecuta una consulta.
291
     *
292
     * @param string $type           tipo de driver
293
     * @param string $query_function nombre de funcion
294
     *
295
     * @return mixed
296
     * @thow KumbiaException
297
     */
298
    public static function query($type, $query_function)
299
    {
300
        $query_function = "{$type}_{$query_function}";
301
302
        require_once __DIR__."/Query/{$query_function}.php";
303
304
        $args = \array_slice(\func_get_args(), 2);
305
306
        return call_user_func_array(__NAMESPACE__."\\Query\\$query_function", $args);
307
    }
308
}
309