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.

ActiveRecord.php (2 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
 * 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
21
namespace Kumbia\ActiveRecord;
22
23
/**
24
 * Implementación de patrón ActiveRecord con ayudantes de consultas sql.
25
 */
26
class ActiveRecord extends LiteRecord implements \JsonSerializable
27
{
28
    const BELONG_TO = 1;
29
    const HAS_MANY = 2;
30
    const HAS_ONE = 3;
31
32
    /**
33
     * Describe the relationships.
34
     *
35
     * @var array
36
     */
37
    protected static $relations = [];
38
39
    public static function resolver($relations, $obj)
40
    {
41
        $model = $relations->model;
42
        if ($relations->type === self::HAS_MANY) {
43
            return $model::allBy($relations->via, $obj->pk());
44
        }
45
46
        return $model::first($relations->via, $obj->pk());
47
    }
48
49 View Code Duplication
    public static function hasMany($name, $class, $via = null)
50
    {
51
        $str = strtolower($name);
52
        $name = static::getTable();
53
        static::$relations[$str] = (object) [
54
            'model' => $class,
55
            'type' => self::HAS_MANY,
56
            'via' => $via ? $via : "{$name}_id",
57
        ];
58
    }
59
60 View Code Duplication
    public static function hasOne($name, $class, $via = null)
61
    {
62
        $str = strtolower($name);
63
        $name = static::getTable();
64
        static::$relations[$str] = (object) [
65
            'model' => $class,
66
            'type' => self::HAS_ONE,
67
            'via' => $via ? $via : "{$name}_id",
68
        ];
69
    }
70
71
    /**
72
     * json_encode() method.
73
     */
74
    public function jsonSerialize()
75
    {
76
        return $this; //TODO: populate relations before
77
    }
78
79
    public function __get($key)
80
    {
81
        if (property_exists($this, $key)) {
82
            return $this->$key;
83
        }
84
        //it's a relationship
85
        if (isset(static::$relations[$key])) {
86
            $this->populate($key);
87
88
            return $this->$key;
89
        }
90
91
        return null; //TODO: change for error
92
    }
93
94
    protected static function getRelationship($rel)
95
    {
96
        if (!isset(static::$relations[$rel])) {
97
            throw new \RuntimeException("Invalid relationship '$rel'", 500);
98
        }
99
100
        return static::$relations[$rel];
101
    }
102
103
    public function populate($rel)
104
    {
105
        $relations = static::getRelationship($rel);
106
        $this->$rel = static::resolver($relations, $this);
107
    }
108
109
    /**
110
     * Pagination of Results.
111
     *
112
     * @param array $params   [description]
113
     * @param array $values   [description]
114
     * @param int   $page     [description]
115
     * @param int   $per_page [description]
116
     *
117
     * @return Paginator [description]
118
     */
119
    public static function pagination($params = [], $values = [], $page = 1, $per_page = 10)
120
    {
121
        $model = get_called_class();
122
        unset($params['limit'], $params['offset']);
123
        $sql = QueryGenerator::select($model::getSource(), $model::getDriver(), $params);
124
125
        return new Paginator($model, $sql, $page, $per_page, $values);
126
    }
127
128
    /**
129
     * Actualizar registros.
130
     *
131
     * @param array  $fields
132
     * @param string $where  condiciones
133
     * @param array  $values valores para condiciones
134
     *
135
     * @return int numero de registros actualizados
136
     */
137 View Code Duplication
    public static function updateAll(array $fields, $where = null, array $values = [])
138
    {
139
        if ($values !== null && !is_array($values)) {
140
            $values = \array_slice(\func_get_args(), 2);
141
        }
142
        $sql = QueryGenerator::updateAll(\get_called_class(), $fields, $values, $where);
143
        $sth = self::prepare($sql);
144
        $sth->execute($values);
145
146
        return $sth->rowCount();
147
    }
148
149
    /**
150
     * Eliminar registro.
151
     *
152
     * @param string        $where  condiciones
153
     * @param array |string $values valores
154
     *
155
     * @return int numero de registros eliminados
156
     */
157
    public static function deleteAll($where = null, $values = null)
158
    {
159
        $source = static::getSource();
160
        $sql = QueryGenerator::deleteAll($source, $where);
161
        $sth = self::query($sql, $values);
162
163
        return $sth->rowCount();
164
    }
165
166
    /**
167
     * Elimina caracteres que podrian ayudar a ejecutar
168
     * un ataque de Inyeccion SQL.
169
     *
170
     * @param string $sqlItem
171
     *
172
     * @return string
173
     * @throw KumbiaException
174
     */
175
    public static function sqlItemSanitize($sqlItem)
176
    {
177
        $sqlItem = \trim($sqlItem);
178
        if ($sqlItem !== '' && $sqlItem !== null) {
179
            $sql_temp = \preg_replace('/\s+/', '', $sqlItem);
180
            if (!\preg_match('/^[a-zA-Z0-9_\.]+$/', $sql_temp)) {
181
                throw new \RuntimeException('Se está tratando de ejecutar un SQL peligroso!');
182
            }
183
        }
184
185
        return $sqlItem;
186
    }
187
188
    /**
189
     * Obtener la primera coincidencia por el campo indicado.
190
     *
191
     * @param string $field  campo
192
     * @param string $value  valor
193
     * @param array  $params parametros adicionales
194
     *                       order: criterio de ordenamiento
195
     *                       fields: lista de campos
196
     *                       join: joins de tablas
197
     *                       group: agrupar campos
198
     *                       having: condiciones de grupo
199
     *                       offset: valor offset
200
     *
201
     * @return ActiveRecord
202
     */
203 View Code Duplication
    public static function firstBy($field, $value, $params = [])
204
    {
205
        $field = self::sqlItemSanitize($field);
206
        $params['where'] = "$field = ?";
207
208
        return self::first($params, $value);
209
    }
210
211
    /**
212
     * Obtener la primera coincidencia de las condiciones indicadas.
213
     *
214
     * @param array $params parametros adicionales
215
     *                      order: criterio de ordenamiento
216
     *                      fields: lista de campos
217
     *                      group: agrupar campos
218
     *                      join: joins de tablas
219
     *                      having: condiciones de grupo
220
     *                      offset: valor offset queda
221
     * @param array $values valores de busqueda
222
     *
223
     * @return ActiveRecord
224
     */
225
    public static function first($params = [], $values = [])
226
    {
227
        $args = func_get_args();
228
        /*Reescribe el limit*/
229
        $args[0]['limit'] = 1;
230
        $res = self::doQuery($args);
231
232
        return $res->fetch();
233
    }
234
235
    /**
236
     * Obtener todos los registros.
237
     *
238
     * @param array $params
239
     *                      where: condiciones where
240
     *                      order: criterio de ordenamiento
241
     *                      fields: lista de campos
242
     *                      join: joins de tablas
243
     *                      group: agrupar campos
244
     *                      having: condiciones de grupo
245
     *                      limit: valor limit
246
     *                      offset: valor offset
247
     * @param array $values valores de busqueda
248
     *
249
     * @return \PDOStatement
250
     */
251
    public static function all($params = [], $values = [])
252
    {
253
        $res = self::doQuery(func_get_args());
254
255
        return $res->fetchAll();
256
    }
257
258
    /**
259
     * Do a query.
260
     *
261
     * @param array $array params of query
262
     *
263
     * @return \PDOStatement|false
264
     */
265
    protected static function doQuery(array $array)
266
    {
267
        $params = self::getParam($array);
268
        $values = self::getValues($array);
269
        $sql = QueryGenerator::select(static::getSource(), static::getDriver(), $params);
270
        $sth = static::query($sql, $values);
271
272
        return $sth;
273
    }
274
275
    /**
276
     * Retorna los parametros para el doQuery.
277
     *
278
     * @param array $array
279
     *
280
     * @return array
281
     */
282
    protected static function getParam(array &$array)
283
    {
284
        $val = array_shift($array);
285
286
        return is_null($val) ? [] : $val;
287
    }
288
289
    /**
290
     * Retorna los values para el doQuery.
291
     *
292
     * @param array $array
293
     *
294
     * @return array
295
     */
296
    protected static function getValues(array $array)
297
    {
298
        return isset($array[0]) ?
299
        is_array($array[0]) ? $array[0] : [$array[0]] : $array;
300
    }
301
302
    /**
303
     * Obtener todas las coincidencias por el campo indicado.
304
     *
305
     * @param string $field  campo
306
     * @param string $value  valor
307
     * @param array  $params
308
     *                       order: criterio de ordenamiento
309
     *                       fields: lista de campos
310
     *                       join: joins de tablas
311
     *                       group: agrupar campos
312
     *                       having: condiciones de grupo
313
     *                       limit: valor limit
314
     *                       offset: valor offset
315
     *
316
     * @return \PDOStatement
317
     */
318 View Code Duplication
    public static function allBy($field, $value, $params = [])
319
    {
320
        $field = self::sqlItemSanitize($field);
321
        $params['where'] = "$field = ?";
322
323
        return self::all($params, $value);
324
    }
325
326
    /**
327
     * Cuenta los registros que coincidan con las condiciones indicadas.
328
     *
329
     * @param string $where  condiciones
330
     * @param array  $values valores
331
     *
332
     * @return int
333
     */
334 View Code Duplication
    public static function count($where = null, $values = null)
335
    {
336
        $source = static::getSource();
337
        $sql = QueryGenerator::count($source, $where);
338
        if ($values !== null && !is_array($values)) {
339
            $values = \array_slice(\func_get_args(), 1);
340
        }
341
        $sth = static::query($sql, $values);
342
343
        return $sth->fetch()->count;
344
    }
345
346
    /**
347
     * Paginar.
348
     *
349
     * @param array $params
350
     * @param int   $page    numero de pagina
351
     * @param int   $perPage cantidad de items por pagina
352
     * @param array $values  valores
353
     *
354
     * @return Paginator
355
     */
356
    public static function paginate(array $params, $page, $perPage, $values = null)
357
    {
358
        unset($params['limit'], $params['offset']);
359
        $sql = QueryGenerator::select(static::getSource(), static::getDriver(), $params);
360
361
        // Valores para consulta
362
        if ($values !== null && !\is_array($values)) {
363
            $values = \array_slice(func_get_args(), 3);
364
        }
365
366
        return new Paginator(\get_called_class(), $sql, (int) $page, (int) $perPage, $values);
367
    }
368
369
    /**
370
     * Obtiene todos los registros de la consulta sql.
371
     *
372
     * @param string         $sql
373
     * @param string | array $values
374
     *
375
     * @return array
376
     */
377 View Code Duplication
    public static function allBySql($sql, $values = null)
378
    {
379
        if (!is_array($values)) {
380
            $values = \array_slice(\func_get_args(), 1);
381
        }
382
383
        return parent::all($sql, $values);
0 ignored issues
show
Comprehensibility Bug introduced by Emilio Silveira
It seems like you call parent on a different method (all() instead of allBySql()). Are you sure this is correct? If so, you might want to change this to $this->all().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
384
    }
385
386
    /**
387
     * Obtiene el primer registro de la consulta sql.
388
     *
389
     * @param string         $sql
390
     * @param string | array $values
391
     *
392
     * @return array
393
     */
394 View Code Duplication
    public static function firstBySql($sql, $values = null)
395
    {
396
        if (!is_array($values)) {
397
            $values = \array_slice(\func_get_args(), 1);
398
        }
399
400
        return parent::first($sql, $values);
0 ignored issues
show
Comprehensibility Bug introduced by Emilio Silveira
It seems like you call parent on a different method (first() instead of firstBySql()). Are you sure this is correct? If so, you might want to change this to $this->first().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
401
    }
402
}
403