Issues (14)

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.

src/Db/Pdo.php (8 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
 * Jaeger
4
 *
5
 * @copyright	Copyright (c) 2015-2016, mithra62
6
 * @link		http://jaeger-app.com
7
 * @version		1.0
8
 * @filesource 	./Db/Pdo.php
9
 */
10
 
11
namespace JaegerApp\Db;
12
13
use Aura\Sql\ExtendedPdo; 
14
use Aura\SqlQuery\QueryFactory;
15
16
/**
17
 * Jaeger - PDO Database Object
18
 *
19
 * Wrapper for a simple PDO abstraction
20
 *
21
 * @package Database
22
 * @author Eric Lamb <[email protected]>
23
 */
24
class Pdo implements DbInterface
25
{
26
    /**
27
     * The primary table we're working with
28
     * @var string
29
     */
30
    protected $table = null;
31
    
32
    /**
33
     * Any filtering for a WHERE SQL clause
34
     * @var mixed
35
     */
36
    protected $where = false;
37
    
38
    /**
39
     * The database connection credentials
40
     * @var array
41
     */
42
    protected $credentials = array();
43
    
44
    /**
45
     * The database object we're piggybacking on
46
     * @var \Aura\Sql\ExtendedPdo
47
     */
48
    protected $db = null;
49
    
50
    /**
51
     * A matched array of "bad" characters our string manipulation hates
52
     * @var array
53
     */
54
    protected $escape_chars = array(
55
        'search' => array("\\", "\0", "\n", "\r", "\x1a", "'", '"'),
56
        'replace' => array("\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"')
57
    );
58
    
59
    /**
60
     * (non-PHPdoc)
61
     * @see \JaegerApp\Db\DbInterface::select()
62
     */
63
    public function select($table, $where)
64
    {
65
        $this->table = $table;
66
        $this->where = $where;
67
        return $this;
68
    }
69
    
70
    /**
71
     * (non-PHPdoc)
72
     * @see \JaegerApp\Db\DbInterface::insert()
73
     */
74
    public function insert($table, array $data = array())
75
    {
76
        $query_factory = new QueryFactory('mysql');
77
        $insert = $query_factory->newInsert();
78
        $insert->into($table);
79
        $cols = $bind = array();
80
        foreach($data AS $key => $value)
81
        {
82
            $cols[] = $key;
83
            $bind[$key] = $value;
84
        }
85
        
86
        $insert->cols($cols)->bindValues($bind);
87
        $sth = $this->getDb()->prepare($insert->getStatement());
88
        $sth->execute($insert->getBindValues());
89
        
90
        $name = $insert->getLastInsertIdName('id');
91
        return $this->getDb()->lastInsertId($name);
92
    }
93
    
94
    /**
95
     * (non-PHPdoc)
96
     * @see \JaegerApp\Db\DbInterface::update()
97
     */
98
    public function update($table, $data, $where)
99
    {
100
        $query_factory = new QueryFactory('mysql');
101
        $update = $query_factory->newUpdate()->table($table);
0 ignored issues
show
It seems like you code against a specific sub-type and not the parent class Aura\SqlQuery\AbstractQuery as the method table() does only exist in the following sub-classes of Aura\SqlQuery\AbstractQuery: Aura\SqlQuery\Common\Update, Aura\SqlQuery\Mysql\Update, Aura\SqlQuery\Pgsql\Update, Aura\SqlQuery\Sqlite\Update, Aura\SqlQuery\Sqlsrv\Update. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
102
        $cols = $bind = array();
103
        foreach($data AS $key => $value)
104
        {
105
            $cols[] = $key;
106
            $bind[$key] = $value;
107
        }
108
        
109
        if (is_string($where)) {
110
            $where = $this->escape($where);
111
        } elseif (is_array($where)) {
112
            $where = $this->parseArrayPair($where, 'AND');
113
        } else {
114
            $where = '';
115
        }        
116
        
117
        $update->cols($cols)->where($where)->bindValues($bind);
118
        $sth = $this->getDb()->prepare($update->getStatement());
119
        return $sth->execute($update->getBindValues());
120
    }
121
    
122
    /**
123
     * (non-PHPdoc)
124
     * @see \Aura\Sql\ExtendedPdo::query()
125
     */
126
    public function query($sql = '', $return = false)
127
    {
128
        if( strtolower(substr($sql,0, 6)) == 'select' || strtolower(substr($sql,0, 4)) == 'show' ){
129
            return $this->getDb()->fetchAll($sql);
130
        } else {
131
            return $this->getDb()->exec($sql);
132
        }
133
    }
134
    
135
    /**
136
     * (non-PHPdoc)
137
     * @see \JaegerApp\Db\DbInterface::escape()
138
     */
139
    public function escape($string)
140
    {
141
        return str_replace($this->escape_chars['search'], $this->escape_chars['replace'], $string);  
142
    }
143
    
144
    /**
145
     * (non-PHPdoc)
146
     * @see \JaegerApp\Db\DbInterface::getAllTables()
147
     */
148
    public function getAllTables()
149
    {
150
        $sql = 'SHOW TABLES';
151
        return $this->getDb()->fetchAll($sql);
152
    }
153
    
154
    /**
155
     * (non-PHPdoc)
156
     * @see \JaegerApp\Db\DbInterface::getTableStatus()
157
     */
158
    public function getTableStatus()
159
    {
160
        $sql = 'SHOW TABLE STATUS';
161
        return $this->getDb()->fetchAll($sql);  
162
    }
163
    
164
    /**
165
     * (non-PHPdoc)
166
     * @see \JaegerApp\Db\DbInterface::getCreateTable()
167
     */
168
    public function getCreateTable($table, $if_not_exists = false)
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...
169
    {
170
        $sql = sprintf('SHOW CREATE TABLE `%s` ;', $table);
171
        $statement = $this->query($sql, true);
172
        $string = false;
173
        if (! empty($statement['0']['Create Table'])) {
174
            $string = $statement['0']['Create Table'];
175
        }
176
        
177
        if ($if_not_exists) {
178
            $replace = substr($string, 0, 12);
179
            if ($replace == 'CREATE TABLE') {
180
                $string = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS ', $string);
181
            }
182
        }
183
        
184
        return $string;
185
    }
186
    
187
    /**
188
     * (non-PHPdoc)
189
     * @see \JaegerApp\Db\DbInterface::clear()
190
     */
191
    public function clear()
192
    {
193
        $this->table = null;
194
        $this->where = null;
195
        return $this;
196
    }
197
    
198
    /**
199
     * (non-PHPdoc)
200
     * @see \JaegerApp\Db\DbInterface::totalRows()
201
     */
202
    public function totalRows($table)
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...
203
    {
204
        $sql = sprintf('SELECT COUNT(*) AS count FROM `%s`', $table);
205
        $statement = $this->query($sql, true);
206
        if ($statement) {
207
            if (isset($statement['0']['count'])) {
208
                return $statement['0']['count'];
209
            }
210
        }
211
        
212
        return '0';
213
    }
214
    
215
    /**
216
     * (non-PHPdoc)
217
     * @see \JaegerApp\Db\DbInterface::getColumns()
218
     */
219 View Code Duplication
    public function getColumns($table)
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...
220
    {
221
        $sql = sprintf('SHOW COLUMNS FROM `%s`', $table);
222
        $statement = $this->query($sql, true);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->query($sql, true); of type array|integer adds the type integer to the return on line 224 which is incompatible with the return type declared by the interface JaegerApp\Db\DbInterface::getColumns of type array.
Loading history...
223
        if ($statement) {
224
            return $statement;
225
        }
226
        return array();
227
    }
228
    
229
    /**
230
     * (non-PHPdoc)
231
     * @see \JaegerApp\Db\DbInterface::get()
232
     */
233
    public function get()
234
    {
235
        $query_factory = new QueryFactory('mysql');
236
        $select = $query_factory->newSelect();
237
        $select->cols(array('*'))->from($this->table);
238
        
239
        if (is_string($this->where)) {
240
            $where = $this->escape($this->where);
241
        } elseif (is_array($this->where)) {
242
            $where = $this->parseArrayPair($this->where, 'AND');
243
        } else {
244
            $where = '';
245
        }
246
        
247
        $select->where($where);
248
        
249
        $sql = $select->getStatement();
250
        
251
        $return = $this->getDb()->fetchAll($sql);
252
        if($return)
0 ignored issues
show
Bug Best Practice introduced by
The expression $return 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...
253
        {
254
            return $return;
255
        }
256
        return array();    
257
    }
258
    
259
    /**
260
     * 
261
     * @param array $credentials
262
     * @return \JaegerApp\Db\Mysqli
263
     */
264
    public function setCredentials(array $credentials)
265
    {
266
        $this->credentials = $credentials;
267
        return $this;
268
    }
269
    
270
    /**
271
     * (non-PHPdoc)
272
     * @see \JaegerApp\Db\DbInterface::getDb()
273
     */
274
    public function getDb($force = false)
275
    {
276
        if (is_null($this->db) || $force) {
277
        
278
            $this->db = new ExtendedPdo(
279
                'mysql:host='.$this->credentials['host'].';dbname='.$this->credentials['database'],
280
                $this->credentials['user'],
281
                $this->credentials['password'],
282
                array(), // driver options as key-value pairs
283
                array()  // attributes as key-value pairs
284
            );
285
            
286
            $this->db->setAttribute(ExtendedPdo::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
287
        }
288
        
289
        return $this->db;
290
    }
291
    
292
    /**
293
     * 
294
     * @param unknown $db_name
295
     */
296
    public function setDbName($db_name)
297
    {
298
        $this->credentials['database'] = $db_name;
299
        $this->getDb(true);
300
        return $this;
301
    }
302
    
303
    /**
304
     * Takes the WHERE array clause and prepairs it for use
305
     * @param array $arrayPair
306
     * @param string $glue
307
     */
308
    protected function parseArrayPair($arrayPair, $glue = ',')
309
    {
310
        // init
311
        $sql = '';
312
        $pairs = array();
313
    
314
        if (!empty($arrayPair)) {
315
    
316
            foreach ($arrayPair as $_key => $_value) {
317
                $_connector = '=';
318
                $_key_upper = strtoupper($_key);
319
    
320
                if (strpos($_key_upper, ' NOT') !== false) {
321
                    $_connector = 'NOT';
322
                }
323
    
324
                if (strpos($_key_upper, ' IS') !== false) {
325
                    $_connector = 'IS';
326
                }
327
    
328
                if (strpos($_key_upper, ' IS NOT') !== false) {
329
                    $_connector = 'IS NOT';
330
                }
331
    
332
                if (strpos($_key_upper, ' IN') !== false) {
333
                    $_connector = 'IN';
334
                }
335
    
336
                if (strpos($_key_upper, ' NOT IN') !== false) {
337
                    $_connector = 'NOT IN';
338
                }
339
    
340
                if (strpos($_key_upper, ' BETWEEN') !== false) {
341
                    $_connector = 'BETWEEN';
342
                }
343
    
344
                if (strpos($_key_upper, ' NOT BETWEEN') !== false) {
345
                    $_connector = 'NOT BETWEEN';
346
                }
347
    
348
                if (strpos($_key_upper, ' LIKE') !== false) {
349
                    $_connector = 'LIKE';
350
                }
351
    
352
                if (strpos($_key_upper, ' NOT LIKE') !== false) {
353
                    $_connector = 'NOT LIKE';
354
                }
355
    
356
                if (strpos($_key_upper, ' >') !== false && strpos($_key_upper, ' =') === false) {
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...
357
                    $_connector = '>';
358
                }
359
    
360
                if (strpos($_key_upper, ' <') !== false && strpos($_key_upper, ' =') === false) {
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...
361
                    $_connector = '<';
362
                }
363
    
364
                if (strpos($_key_upper, ' >=') !== false) {
365
                    $_connector = '>=';
366
                }
367
    
368
                if (strpos($_key_upper, ' <=') !== false) {
369
                    $_connector = '<=';
370
                }
371
    
372
                if (strpos($_key_upper, ' <>') !== false) {
373
                    $_connector = '<>';
374
                }
375
    
376
                if (
377
                    is_array($_value)
378
                    &&
379
                    (
380
                        $_connector == 'NOT IN'
381
                        ||
382
                        $_connector == 'IN'
383
                    )
384
                ) {
385
                    foreach ($_value as $oldKey => $oldValue) {
386
                        /** @noinspection AlterInForeachInspection */
387
                        $_value[$oldKey] = $this->escape($oldValue);
388
                    }
389
                    $_value = '(' . implode(',', $_value) . ')';
390
                } elseif (
391
                    is_array($_value)
392
                    &&
393
                    (
394
                        $_connector == 'NOT BETWEEN'
395
                        ||
396
                        $_connector == 'BETWEEN'
397
                    )
398
                ) {
399
                    foreach ($_value as $oldKey => $oldValue) {
400
                        /** @noinspection AlterInForeachInspection */
401
                        $_value[$oldKey] = $this->escape($oldValue);
402
                    }
403
                    $_value = '(' . implode(' AND ', $_value) . ')';
404
                } else {
405
                    $_value = $this->getDb()->quote($_value);
406
                }
407
    
408
                $quoteString = '`'.$_key.'`';
409
                $pairs[] = ' ' . $quoteString . ' ' . $_connector . ' ' . $_value . " \n";
410
            }
411
    
412
            $sql = implode($glue, $pairs);
413
        }
414
    
415
        return $sql;
416
    }    
417
}