Completed
Push — work-fleets ( 22b5bc...08ace7 )
by SuperNova.WS
06:13
created

db_mysql::doUpdateDbQueryAdjust()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
ccs 0
cts 2
cp 0
crap 2
1
<?php
2
3
use \DBAL\DbQuery;
4
5
/**
6
 * Created by Gorlum 01.09.2015 15:58
7
 */
8
class db_mysql {
9
  const TRANSACTION_SERIALIZABLE = 'SERIALIZABLE';
10
  const TRANSACTION_REPEATABLE_READ = 'REPEATABLE READ';
11
  const TRANSACTION_READ_COMMITTED = 'READ COMMITTED';
12
  const TRANSACTION_READ_UNCOMMITTED = 'READ UNCOMMITTED';
13
14
  /**
15
   * Статус соеднения с MySQL
16
   *
17
   * @var bool
18
   */
19
  public $connected = false;
20
  /**
21
   * Префикс названий таблиц в БД
22
   *
23
   * @var string
24
   */
25
  public $db_prefix = '';
26
  /**
27
   * Список таблиц в БД
28
   *
29
   * @var array
30
   */
31
  public $table_list = array();
32
33
  /**
34
   * Настройки БД
35
   *
36
   * @var array
37
   */
38
  protected $dbsettings = array();
39
  /**
40
   * Драйвер для прямого обращения к MySQL
41
   *
42
   * @var db_mysql_v5 $driver
43
   */
44
  public $driver = null;
45
46
  /**
47
   * Общее время запросов
48
   *
49
   * @var float $time_mysql_total
50
   */
51
  public $time_mysql_total = 0.0;
52
53
  /**
54
   * Amount of queries on this DB
55
   *
56
   * @var int
57
   */
58
  public $queryCount = 0;
59
60
  public $isWatching = false;
61
62
  /**
63
   * @var \DBAL\DbTransaction $transaction
64
   */
65
  protected $transaction;
66
67
  /**
68
   * Should query check be skipped?
69
   *
70
   * Used for altering scheme of DB
71
   *
72
   * @var bool $skipQueryCheck
73
   */
74
  protected $skipQueryCheck = false;
75
76
  /**
77
   * @var SnCache $snCache
78
   */
79
  public $snCache;
80
81
  /**
82
   * db_mysql constructor.
83
   *
84
   * @param \Common\GlobalContainer $gc
85
   */
86
  public function __construct($gc) {
87
    $this->transaction = new \DBAL\DbTransaction($gc, $this);
88
    $this->snCache = new $gc->snCacheClass($gc, $this);
89
  }
90
91
  public function load_db_settings($configFile = '') {
92
    $dbsettings = array();
93
94
    empty($configFile) ? $configFile = SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX : false;
95
96
    require $configFile;
97
98
    $this->dbsettings = $dbsettings;
99
  }
100
101
  /**
102
   * @param null|array $external_db_settings
103
   *
104
   * @return bool
105
   */
106
  public function sn_db_connect($external_db_settings = null) {
107
    $this->db_disconnect();
108
109
    if (!empty($external_db_settings) && is_array($external_db_settings)) {
110
      $this->dbsettings = $external_db_settings;
111
    }
112
113
    if (empty($this->dbsettings)) {
114
      $this->load_db_settings(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
115
    }
116
117
    // TODO - фатальные (?) ошибки на каждом шагу. Хотя - скорее Эксепшны
118
    if (!empty($this->dbsettings)) {
119
      $driver_name = empty($this->dbsettings['sn_driver']) ? 'db_mysql_v5' : $this->dbsettings['sn_driver'];
120
      $this->driver = new $driver_name();
121
      $this->db_prefix = $this->dbsettings['prefix'];
122
123
      $this->connected = $this->connected || $this->driver_connect();
124
125
      if ($this->connected) {
126
        $this->table_list = $this->db_get_table_list();
127
        // TODO Проверка на пустоту
128
      }
129
    } else {
130
      $this->connected = false;
131
    }
132
133
    return $this->connected;
134
  }
135
136
  protected function driver_connect() {
137
    if (!is_object($this->driver)) {
138
      classSupernova::$debug->error_fatal('DB Error - No driver for MySQL found!');
139
    }
140
141
    if (!method_exists($this->driver, 'mysql_connect')) {
142
      classSupernova::$debug->error_fatal('DB Error - WRONG MySQL driver!');
143
    }
144
145
    return $this->driver->mysql_connect($this->dbsettings);
146
  }
147
148
  public function db_disconnect() {
149
    if ($this->connected) {
150
      $this->connected = !$this->driver_disconnect();
151
      $this->connected = false;
152
    }
153
154
    return !$this->connected;
155
  }
156
157
  /**
158
   * @param string $query
159
   *
160
   * @return mixed|string
161
   */
162
  public function replaceTablePlaceholders($query) {
163
    $sql = $query;
164
    if (strpos($sql, '{{') !== false) {
165
      foreach ($this->table_list as $tableName) {
166
        $sql = str_replace("{{{$tableName}}}", $this->db_prefix . $tableName, $sql);
167
      }
168
    }
169
170
    return $sql;
171
  }
172
173
  /**
174
   * @param $query
175
   */
176
  protected function logQuery($query) {
177
    if (!classSupernova::$config->debug) {
178
      return;
179
    }
180
181
    $this->queryCount++;
182
    $arr = debug_backtrace();
183
    $file = end(explode('/', $arr[0]['file']));
0 ignored issues
show
Bug introduced by
explode('/', $arr[0]['file']) cannot be passed to end() as the parameter $array expects a reference.
Loading history...
184
    $line = $arr[0]['line'];
185
    classSupernova::$debug->add("<tr><th>Query {$this->queryCount}: </th><th>$query</th><th>{$file} @ {$line}</th><th>&nbsp;</th></tr>");
186
  }
187
188
189
  /**
190
   * @return string
191
   */
192
  public function traceQuery() {
193
    if (!defined('DEBUG_SQL_COMMENT') || constant('DEBUG_SQL_ERROR') !== true) {
194
      return '';
195
    }
196
197
    $backtrace = debug_backtrace();
198
    $sql_comment = classSupernova::$debug->compact_backtrace($backtrace, defined('DEBUG_SQL_COMMENT_LONG'));
199
200
    if (defined('DEBUG_SQL_ERROR') && constant('DEBUG_SQL_ERROR') === true) {
201
      classSupernova::$debug->add_to_array($sql_comment);
202
    }
203
204
    $sql_commented = implode("\r\n", $sql_comment);
205
    if (defined('DEBUG_SQL_ONLINE') && constant('DEBUG_SQL_ONLINE') === true) {
206
      classSupernova::$debug->warning($sql_commented, 'SQL Debug', LOG_DEBUG_SQL);
207
    }
208
209
    return $sql_commented;
210
  }
211
212
  /**
213
   * @param string $query
214
   *
215
   * @return array|bool|mysqli_result|null
216
   */
217
  protected function queryDriver($query) {
218
    if (!$this->connected) {
219
      $this->sn_db_connect();
220
    }
221
222
    $stringQuery = $query;
223
    $stringQuery = trim($stringQuery);
224
    // You can't do it - 'cause you can break commented statement with line-end comments
225
    // $stringQuery = preg_replace("/\s+/", ' ', $stringQuery);
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
226
227
    $this->security_watch_user_queries($stringQuery);
228
    $this->security_query_check_bad_words($stringQuery);
229
    $this->logQuery($stringQuery);
230
231
    $stringQuery = $this->replaceTablePlaceholders($stringQuery);
232
233
    $queryTrace = $this->traceQuery();
234
235
    $queryResult = null;
236
    try {
237
      $queryResult = $this->db_sql_query($stringQuery . DbSqlHelper::quoteComment($queryTrace));
238
      if (!$queryResult) {
239
        throw new Exception();
240
      }
241
    } catch (Exception $e) {
242
      classSupernova::$debug->error($this->db_error() . "<br />{$query}<br />", 'SQL Error');
243
    }
244
245
    return $queryResult;
246
  }
247
248
249
  // Just wrappers to distinguish query types
250
  /**
251
   * Executes non-data manipulation statements
252
   *
253
   * Can execute queries with check skip
254
   * Honor current state of query checking
255
   *
256
   * @param string $query
257
   * @param bool   $skip_query_check
258
   *
259
   * @return array|bool|mysqli_result|null
260
   */
261
  public function doSql($query, $skip_query_check = false) {
262
    $prevState = false;
263
    if ($skip_query_check) {
264
      $prevState = $this->skipQueryCheck;
265
      $this->skipQueryCheck = true;
266
    }
267
    // TODO - disable watch ??
268
    $result = $this->queryDriver($query);
269
    if ($skip_query_check) {
270
      $this->skipQueryCheck = $prevState;
271
    }
272
273
    return $result;
274
  }
275
276
277
  // SELECTS
278
  public function doSelect($query) {
279
    return $this->doSql($query);
280
  }
281
282
  /**
283
   * @param string $query
284
   *
285
   * @return array|null
286
   */
287
  public function doSelectFetch($query) {
288
    return $this->db_fetch($this->doSelect($query));
0 ignored issues
show
Bug introduced by
$this->doSelect($query) cannot be passed to db_fetch() as the parameter $query expects a reference.
Loading history...
Bug introduced by
It seems like $this->doSelect($query) targeting db_mysql::doSelect() can also be of type boolean; however, db_mysql::db_fetch() does only seem to accept object<mysqli_result>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
289
  }
290
291
  /**
292
   * @param string $query
293
   *
294
   * @return mixed|null
295
   */
296
  public function doSelectFetchValue($query) {
297
    $row = $this->doSelectFetch($query);
298
299
    return is_array($row) ? reset($row) : null;
300
  }
301
302
303
  // INSERT/REPLACE
304
  protected function doSet($table, $fieldsAndValues, $replace = DB_INSERT_PLAIN) {
305
    $query = DbQuery::build($this)
306
      ->setTable($table)
307
      ->setValues($fieldsAndValues)
308
      ->insertSet($replace);
309
310
    return $this->doSql($query);
311
  }
312
313
  // TODO - batch insert and replace here
314
  // TODO - перед тем, как переделывать данные из депрекейтов - убедится, что
315
  // null - это null, а не строка'NULL'
316
  /**
317
   * Values should be passed as-is
318
   *
319
   * DANGER! Values should be properly escaped before passing here
320
   *
321
   * @param string   $table
322
   * @param array    $fields
323
   * @param string[] $valuesDanger
324
   * @param bool     $replace
325
   *
326
   * @return array|bool|mysqli_result|null
327
   * @deprecated
328
   */
329
  protected function doInsertBatchDanger($table, $fields, &$valuesDanger, $replace = DB_INSERT_PLAIN) {
330
    $query = DbQuery::build($this)
331
      ->setTable($table)
332
      ->setFields($fields)
333
      ->setValuesDanger($valuesDanger)
334
      ->insertBatch($replace);
335
336
    return $this->doSql($query);
337
  }
338
339
340
  // INSERTERS
341
  public function doInsertComplex($query) {
342
    return $this->doSql($query);
343
  }
344
  /**
345
   * @param string $table
346
   * @param array  $fieldsAndValues
347
   * @param int    $replace - DB_INSERT_PLAIN || DB_INSERT_IGNORE
348
   *
349
   * @return array|bool|mysqli_result|null
350
   */
351
  public function doInsertSet($table, $fieldsAndValues, $replace = DB_INSERT_PLAIN) {
352
    return $this->doSet($table, $fieldsAndValues, $replace);
353
  }
354
  /**
355
   * Values should be passed as-is
356
   *
357
   * @param string   $table
358
   * @param array    $fields
359
   * @param string[] $values
360
   *
361
   * @return array|bool|mysqli_result|null
362
   * @deprecated
363
   */
364
  public function doInsertValuesDeprecated($table, $fields, &$values) {
365
    return $this->doInsertBatchDanger($table, $fields, $values, DB_INSERT_PLAIN);
0 ignored issues
show
Documentation introduced by
DB_INSERT_PLAIN is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The method db_mysql::doInsertBatchDanger() has been deprecated.

This method has been deprecated.

Loading history...
366
  }
367
368
369
370
  // REPLACERS
371
  /**
372
   * Replaces record in DB
373
   *
374
   * There are no DANGER replace operations
375
   *
376
   * @param string $table
377
   * @param array  $fieldsAndValues
378
   *
379
   * @return array|bool|mysqli_result|null
380
   */
381
  public function doReplaceSet($table, $fieldsAndValues) {
382
    return $this->doSet($table, $fieldsAndValues, DB_INSERT_REPLACE);
383
  }
384
  /**
385
   * Values should be passed as-is
386
   *
387
   * @param string   $table
388
   * @param array    $fields
389
   * @param string[] $values
390
   *
391
   * @return array|bool|mysqli_result|null
392
   * @deprecated
393
   */
394
  public function doReplaceValuesDeprecated($table, $fields, &$values) {
395
    return $this->doInsertBatchDanger($table, $fields, $values, DB_INSERT_REPLACE);
0 ignored issues
show
Deprecated Code introduced by
The method db_mysql::doInsertBatchDanger() has been deprecated.

This method has been deprecated.

Loading history...
Documentation introduced by
DB_INSERT_REPLACE is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
396
  }
397
398
399
  // UPDATERS
400
  public function doUpdateReallyComplex($query) {
401
    return $this->doSql($query);
402
  }
403
404
  /**
405
   * Executes self-contained SQL UPDATE query
406
   *
407
   * Self-contained - means no params used
408
   * Such queries usually used to make large amount of in-base calculations
409
   *
410
   * @param $query
411
   *
412
   * @return array|bool|mysqli_result|null
413
   */
414
  public function doUpdateSqlNoParam($query) {
415
    return $this->doSql($query);
416
  }
417
418
419
420
  /**
421
   * @param $DbQuery DbQuery
422
   */
423
  protected function doUpdateDbQuery($DbQuery) {
424
    return $this->doSql($DbQuery->update());
425
  }
426
427
  /**
428
   * @param $DbQuery DbQuery
429
   */
430
  public function doUpdateDbQueryAdjust($DbQuery) {
431
    return $this->doUpdateDbQuery($DbQuery);
432
  }
433
434
435
  protected function doUpdateWhere($table, $fieldsSet, $fieldsAdjust = array(), $where = array(), $isOneRecord = DB_RECORDS_ALL, $whereDanger = array()) {
0 ignored issues
show
Unused Code introduced by
The parameter $whereDanger is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
436
//    $query = DbQuery::build($this)
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
437
//      ->setTable($table)
438
//      ->setValues($fieldsSet)
439
//      ->setAdjustDanger($fieldsAdjust)
440
//
441
//      // TODO - separate danger WHEREs
442
//      ->setWhereArray($where)
443
//      ->setWhereArrayDanger($whereDanger)
444
//      ->setOneRow($isOneRecord)
445
//
446
//      ->update();
447
//
448
    $tableSafe = $this->db_escape($table);
449
450
    $safeFields = array();
451
    // Adjusts overwritten by Sets
452
    if ($safeAdjust = implode(',', $this->safeFieldsAdjust($fieldsAdjust))) {
453
      $safeFields[] = &$safeAdjust;
454
    }
455
    if ($safeFieldsEqualValues = implode(',', $this->safeFieldsEqualValues($fieldsSet))) {
456
      $safeFields[] = &$safeFieldsEqualValues;
457
    }
458
    $safeFieldsString = implode(',', $safeFields);
459
460
    // TODO - Exception of $safeFieldsString
461
462
    $safeWhereAnd = implode(' AND ', $this->safeFieldsEqualValues($where));
463
    $query = "UPDATE `{{{$tableSafe}}}` SET {$safeFieldsString}"
464
      . (!empty($safeWhereAnd) ? " WHERE {$safeWhereAnd}" : '')
465
      . ($isOneRecord == DB_RECORD_ONE ? ' LIMIT 1' : '');
466
467
    return $this->doSql($query);
468
  }
469
470
  public function doUpdateRowSet($table, $fieldsAndValues, $where) {
471
    return $this->doUpdateWhere($table, $fieldsAndValues, array(), $where, DB_RECORD_ONE);
472
  }
473
474
  public function doUpdateTableSet($table, $fieldsAndValues, $where = array()) {
475
    return $this->doUpdateWhere($table, $fieldsAndValues, array(), $where, DB_RECORDS_ALL);
476
  }
477
478
  public function doUpdateRowAdjust($table, $fieldsSet, $fieldsAdjust, $where) {
479
    return $this->doUpdateWhere($table, $fieldsSet, $fieldsAdjust, $where, DB_RECORD_ONE);
480
  }
481
482
  public function doUpdateTableAdjust($table, $fieldsSet, $fieldsAdjust, $where, $whereDanger = array()) {
483
    return $this->doUpdateWhere($table, $fieldsSet, $fieldsAdjust, $where, DB_RECORDS_ALL, $whereDanger);
484
  }
485
486
487
  // DELETERS
488
  /**
489
   * @param string $table
490
   * @param array  $where
491
   * @param bool   $isOneRecord
492
   *
493
   * @return DbQuery
494
   */
495
  protected function buildDeleteQuery($table, $where, $isOneRecord = DB_RECORDS_ALL) {
496
    return DbQuery::build($this)
497
      ->setTable($table)
498
      ->setWhereArray($where)
499
      ->setOneRow($isOneRecord);
500
  }
501
502
  /**
503
   * @param string $table
504
   * @param array  $where - simple WHERE statement list which can be combined with AND
505
   * @param bool   $isOneRecord
506
   *
507
   * @return array|bool|mysqli_result|null
508
   */
509
  public function doDeleteWhere($table, $where, $isOneRecord = DB_RECORDS_ALL) {
510
    return $this->doSql($this->buildDeleteQuery($table, $where, $isOneRecord)->delete());
511
  }
512
513
  /**
514
   * Early deprecated function for complex delete conditions
515
   *
516
   * Used for malformed $where conditions
517
   * Also whereDanger can contain references for other {{tables}}
518
   *
519
   * @param string $table
520
   * @param array  $where
521
   * @param array  $whereDanger
522
   *
523
   * @return array|bool|mysqli_result|null
524
   * @deprecated
525
   */
526
  public function doDeleteDanger($table, $where, $whereDanger) {
527
    return $this->doSql($this->buildDeleteQuery($table, $where, DB_RECORDS_ALL)->setWhereArrayDanger($whereDanger)->delete());
0 ignored issues
show
Deprecated Code introduced by
The method DBAL\DbQuery::setWhereArrayDanger() has been deprecated.

This method has been deprecated.

Loading history...
528
  }
529
530
  /**
531
   * @param string $table
532
   * @param array  $where - simple WHERE statement list which can be combined with AND
533
   *
534
   * @return array|bool|mysqli_result|null
535
   */
536
  public function doDeleteRow($table, $where) {
537
    return $this->doDeleteWhere($table, $where, DB_RECORD_ONE);
538
  }
539
540
  /**
541
   * Perform simple delete queries on fixed tables w/o params
542
   *
543
   * @param string $query
544
   *
545
   * @return array|bool|mysqli_result|null
546
   */
547
  public function doDeleteSql($query) {
548
    return $this->doSql($query);
549
  }
550
551
552
  // Misc functions
553
  //
554 View Code Duplication
  protected function castAsDbValue($value) {
0 ignored issues
show
Duplication introduced by
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...
555
    switch (gettype($value)) {
556
      case TYPE_INTEGER:
557
      case TYPE_DOUBLE:
558
        // do nothing
559
      break;
560
561
      case TYPE_BOOLEAN:
562
        $value = $value ? 1 : 0;
563
      break;
564
565
      case TYPE_NULL:
566
        $value = 'NULL';
567
      break;
568
569
      /** @noinspection PhpMissingBreakStatementInspection */
570
      case TYPE_ARRAY:
571
        $value = serialize($value);
572
      // Continuing with serialized array value
573
      case TYPE_STRING:
574
        // Empty type is string
575
      case TYPE_EMPTY:
576
        // No-type defaults to string
577
      default:
578
        $value = "'" . $this->db_escape((string)$value) . "'";
579
      break;
580
    }
581
582
    return $value;
583
  }
584
585
  /**
586
   * Make field list safe
587
   *
588
   * Support expressions - expression index should be strictly integer!
589
   *
590
   * @param array $fields - array of pair $fieldName => $fieldValue
591
   *
592
   * @return array
593
   */
594 View Code Duplication
  protected function safeFieldsEqualValues($fields) {
0 ignored issues
show
Duplication introduced by
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...
595
    $result = array();
596
597
    if (!is_array($fields) || empty($fields)) {
598
      return $result;
599
    }
600
601
    foreach ($fields as $fieldName => $fieldValue) {
602
      // Integer $fieldName means "leave as is" - for expressions and already processed fields
603
      if (is_int($fieldName)) {
604
        $result[$fieldName] = $fieldValue;
605
      } else {
606
        $result[$fieldName] = "`{$fieldName}` = " . $this->castAsDbValue($fieldValue);
607
      }
608
    }
609
610
    return $result;
611
  }
612
613
  /**
614
   * Make fields adjustment safe
615
   *
616
   * Convert "key => value" pair to string "`key` = `key` + (value)"
617
   * Supports expressions - expression index should be strictly integer!
618
   *
619
   * @param array $fields - array of pair $fieldName => $fieldValue
620
   *
621
   * @return array
622
   */
623 View Code Duplication
  protected function safeFieldsAdjust($fields) {
0 ignored issues
show
Duplication introduced by
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...
624
    $result = array();
625
626
    if (!is_array($fields) || empty($fields)) {
627
      return $result;
628
    }
629
630
    foreach ($fields as $fieldName => $fieldValue) {
631
      // Integer $fieldName means "leave as is" - for expressions and already processed fields
632
      if (is_int($fieldName)) {
633
        $result[$fieldName] = $fieldValue;
634
      } else {
635
        $result[$fieldName] = "`{$fieldName}` = `{$fieldName}` + (" . $this->castAsDbValue($fieldValue) . ")";
636
      }
637
    }
638
639
    return $result;
640
  }
641
642
643
  /**
644
   * Returns iterator to iterate through mysqli_result
645
   *
646
   * @param string $query
647
   *
648
   * return DbResultIterator
649
   *
650
   * @return DbEmptyIterator|DbMysqliResultIterator
651
   */
652
  public function doSelectIterator($query) {
653
    $queryResult = $this->doSelect($query);
654
655
    if ($queryResult instanceof mysqli_result) {
656
      $result = new DbMysqliResultIterator($queryResult);
657
    } else {
658
      $result = new DbEmptyIterator();
659
    }
660
661
    return $result;
662
  }
663
664
  /**
665
   * @param DbQueryConstructor $stmt
666
   * @param bool               $skip_query_check
667
   */
668
  public function doStmtLockAll($stmt, $skip_query_check = false) {
669
    $this->doSql(
670
      $stmt
671
        ->select()
672
        ->field(1)
673
        ->setForUpdate()
674
        ->__toString(),
675
      $skip_query_check
676
    );
677
  }
678
679
  // TODO Заменить это на новый логгер
680
  protected function security_watch_user_queries($query) {
681
    global $user;
682
683
    if (
684
      !$this->isWatching // Not already watching
685
      && !empty(classSupernova::$config->game_watchlist_array) // There is some players in watchlist
686
      && in_array($user['id'], classSupernova::$config->game_watchlist_array) // Current player is in watchlist
687
      && !preg_match('/^(select|commit|rollback|start transaction)/i', $query) // Current query should be watched
688
    ) {
689
      $this->isWatching = true;
690
      $msg = "\$query = \"{$query}\"\n\r";
691
      if (!empty($_POST)) {
692
        $msg .= "\n\r" . dump($_POST, '$_POST');
693
      }
694
      if (!empty($_GET)) {
695
        $msg .= "\n\r" . dump($_GET, '$_GET');
696
      }
697
      classSupernova::$debug->warning($msg, "Watching user {$user['id']}", 399, array('base_dump' => true));
0 ignored issues
show
Documentation introduced by
array('base_dump' => true) is of type array<string,boolean,{"base_dump":"boolean"}>, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
698
      $this->isWatching = false;
699
    }
700
  }
701
702
703
  public function security_query_check_bad_words($query) {
704
    if ($this->skipQueryCheck) {
705
      return;
706
    }
707
708
    global $user, $dm_change_legit, $mm_change_legit;
709
710
    switch (true) {
711
      case stripos($query, 'RUNCATE TABL') != false:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'RUNCATE TABL') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
712
      case stripos($query, 'ROP TABL') != false:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'ROP TABL') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
713
      case stripos($query, 'ENAME TABL') != false:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'ENAME TABL') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
714
      case stripos($query, 'REATE DATABAS') != false:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'REATE DATABAS') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
715
      case stripos($query, 'REATE TABL') != false:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'REATE TABL') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
716
      case stripos($query, 'ET PASSWOR') != false:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'ET PASSWOR') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
717
      case stripos($query, 'EOAD DAT') != false:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'EOAD DAT') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
718
      case stripos($query, 'RPG_POINTS') != false && stripos(trim($query), 'UPDATE ') === 0 && !$dm_change_legit:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'RPG_POINTS') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
719
      case stripos($query, 'METAMATTER') != false && stripos(trim($query), 'UPDATE ') === 0 && !$mm_change_legit:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'METAMATTER') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
720
      case stripos($query, 'AUTHLEVEL') != false && $user['authlevel'] < 3 && stripos($query, 'SELECT') !== 0:
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($query, 'AUTHLEVEL') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
721
        $report = "Hacking attempt (" . date("d.m.Y H:i:s") . " - [" . time() . "]):\n";
722
        $report .= ">Database Inforamation\n";
723
        $report .= "\tID - " . $user['id'] . "\n";
724
        $report .= "\tUser - " . $user['username'] . "\n";
725
        $report .= "\tAuth level - " . $user['authlevel'] . "\n";
726
        $report .= "\tAdmin Notes - " . $user['adminNotes'] . "\n";
727
        $report .= "\tCurrent Planet - " . $user['current_planet'] . "\n";
728
        $report .= "\tUser IP - " . $user['user_lastip'] . "\n";
729
        $report .= "\tUser IP at Reg - " . $user['ip_at_reg'] . "\n";
730
        $report .= "\tUser Agent- " . $_SERVER['HTTP_USER_AGENT'] . "\n";
731
        $report .= "\tCurrent Page - " . $user['current_page'] . "\n";
732
        $report .= "\tRegister Time - " . $user['register_time'] . "\n";
733
        $report .= "\n";
734
735
        $report .= ">Query Information\n";
736
        $report .= "\tQuery - " . $query . "\n";
737
        $report .= "\n";
738
739
        $report .= ">\$_SERVER Information\n";
740
        $report .= "\tIP - " . $_SERVER['REMOTE_ADDR'] . "\n";
741
        $report .= "\tHost Name - " . $_SERVER['HTTP_HOST'] . "\n";
742
        $report .= "\tUser Agent - " . $_SERVER['HTTP_USER_AGENT'] . "\n";
743
        $report .= "\tRequest Method - " . $_SERVER['REQUEST_METHOD'] . "\n";
744
        $report .= "\tCame From - " . $_SERVER['HTTP_REFERER'] . "\n";
745
        $report .= "\tPage is - " . $_SERVER['SCRIPT_NAME'] . "\n";
746
        $report .= "\tUses Port - " . $_SERVER['REMOTE_PORT'] . "\n";
747
        $report .= "\tServer Protocol - " . $_SERVER['SERVER_PROTOCOL'] . "\n";
748
749
        $report .= "\n--------------------------------------------------------------------------------------------------\n";
750
751
        $fp = fopen(SN_ROOT_PHYSICAL . 'badqrys.txt', 'a');
752
        fwrite($fp, $report);
0 ignored issues
show
Security File Manipulation introduced by
$report can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

7 paths for user data to reach this point

  1. Path: Fetching key HTTP_REFERER from $_SERVER, and $report is assigned in includes/classes/db_mysql.php on line 744
  1. Fetching key HTTP_REFERER from $_SERVER, and $report is assigned
    in includes/classes/db_mysql.php on line 744
  2. Path: Fetching key HTTP_USER_AGENT from $_SERVER, and $report is assigned in includes/classes/db_mysql.php on line 742
  1. Fetching key HTTP_USER_AGENT from $_SERVER, and $report is assigned
    in includes/classes/db_mysql.php on line 742
  2. $report is assigned
    in includes/classes/db_mysql.php on line 744
  3. Path: Fetching key HTTP_HOST from $_SERVER, and $report is assigned in includes/classes/db_mysql.php on line 741
  1. Fetching key HTTP_HOST from $_SERVER, and $report is assigned
    in includes/classes/db_mysql.php on line 741
  2. $report is assigned
    in includes/classes/db_mysql.php on line 742
  3. $report is assigned
    in includes/classes/db_mysql.php on line 744
  4. Path: Read from $_GET in includes/classes/db_mysql.php on line 695
  1. Read from $_GET
    in includes/classes/db_mysql.php on line 695
  2. Data is passed through gettype()
    in vendor/docs/txt2html.php on line 18
  3. $msg is assigned
    in includes/classes/db_mysql.php on line 695
  4. $msg is passed to debug::warning()
    in includes/classes/db_mysql.php on line 697
  5. Data is escaped by mysqli_real_escape_string() for sql context(s)
    in vendor/includes/classes/db_mysql_v5.php on line 87
  6. $query is assigned
    in includes/classes/debug.php on line 258
  7. $query is passed to db_mysql::doSql()
    in includes/classes/debug.php on line 263
  8. $query is passed to db_mysql::queryDriver()
    in includes/classes/db_mysql.php on line 268
  9. $stringQuery is assigned
    in includes/classes/db_mysql.php on line 222
  10. $stringQuery is passed through trim(), and $stringQuery is assigned
    in includes/classes/db_mysql.php on line 223
  11. $stringQuery is passed to db_mysql::security_query_check_bad_words()
    in includes/classes/db_mysql.php on line 228
  12. $report is assigned
    in includes/classes/db_mysql.php on line 736
  13. $report is assigned
    in includes/classes/db_mysql.php on line 741
  14. $report is assigned
    in includes/classes/db_mysql.php on line 742
  15. $report is assigned
    in includes/classes/db_mysql.php on line 744
  5. Path: Read from $_POST in includes/classes/db_mysql.php on line 692
  1. Read from $_POST
    in includes/classes/db_mysql.php on line 692
  2. Data is passed through gettype()
    in vendor/docs/txt2html.php on line 18
  3. $msg is assigned
    in includes/classes/db_mysql.php on line 692
  4. $msg is passed to debug::warning()
    in includes/classes/db_mysql.php on line 697
  5. Data is escaped by mysqli_real_escape_string() for sql context(s)
    in vendor/includes/classes/db_mysql_v5.php on line 87
  6. $query is assigned
    in includes/classes/debug.php on line 258
  7. $query is passed to db_mysql::doSql()
    in includes/classes/debug.php on line 263
  8. $query is passed to db_mysql::queryDriver()
    in includes/classes/db_mysql.php on line 268
  9. $stringQuery is assigned
    in includes/classes/db_mysql.php on line 222
  10. $stringQuery is passed through trim(), and $stringQuery is assigned
    in includes/classes/db_mysql.php on line 223
  11. $stringQuery is passed to db_mysql::security_query_check_bad_words()
    in includes/classes/db_mysql.php on line 228
  12. $report is assigned
    in includes/classes/db_mysql.php on line 736
  13. $report is assigned
    in includes/classes/db_mysql.php on line 741
  14. $report is assigned
    in includes/classes/db_mysql.php on line 742
  15. $report is assigned
    in includes/classes/db_mysql.php on line 744
  6. Path: Read from $_POST in includes/general.php on line 258
  1. Read from $_POST
    in includes/general.php on line 258
  2. sys_get_param() returns tainted data
    in includes/general.php on line 290
  3. Data is passed through strip_tags(), and Data is passed through trim()
    in vendor/includes/general.php on line 1303
  4. sys_get_param_str_unsafe() returns tainted data, and sys_get_param_str_unsafe('uni_name') is passed through strip_tags(), and strip_tags(sys_get_param_str_unsafe('uni_name')) is passed through sprintf(), and sprintf(\classLocale::$lang['uni_msg_admin_rename'], $user['id'], $user['username'], $uni_price, $uni_system ? \classLocale::$lang['uni_system_of'] : \classLocale::$lang['uni_galaxy_of'], $uni_galaxy, $uni_system ? ":{$uni_system}" : '', strip_tags(sys_get_param_str_unsafe('uni_name'))) is passed to debug::warning()
    in includes/includes/uni_rename.php on line 55
  5. Data is escaped by mysqli_real_escape_string() for sql context(s)
    in vendor/includes/classes/db_mysql_v5.php on line 87
  6. $query is assigned
    in includes/classes/debug.php on line 258
  7. $query is passed to db_mysql::doSql()
    in includes/classes/debug.php on line 263
  8. $query is passed to db_mysql::queryDriver()
    in includes/classes/db_mysql.php on line 268
  9. $stringQuery is assigned
    in includes/classes/db_mysql.php on line 222
  10. $stringQuery is passed through trim(), and $stringQuery is assigned
    in includes/classes/db_mysql.php on line 223
  11. $stringQuery is passed to db_mysql::security_query_check_bad_words()
    in includes/classes/db_mysql.php on line 228
  12. $report is assigned
    in includes/classes/db_mysql.php on line 736
  13. $report is assigned
    in includes/classes/db_mysql.php on line 741
  14. $report is assigned
    in includes/classes/db_mysql.php on line 742
  15. $report is assigned
    in includes/classes/db_mysql.php on line 744
  7. Path: Fetching key HTTP_USER_AGENT from $_SERVER, and $report is assigned in includes/classes/db_mysql.php on line 730
  1. Fetching key HTTP_USER_AGENT from $_SERVER, and $report is assigned
    in includes/classes/db_mysql.php on line 730
  2. $report is assigned
    in includes/classes/db_mysql.php on line 736
  3. $report is assigned
    in includes/classes/db_mysql.php on line 741
  4. $report is assigned
    in includes/classes/db_mysql.php on line 742
  5. $report is assigned
    in includes/classes/db_mysql.php on line 744

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
753
        fclose($fp);
754
755
        $message = 'Привет, я не знаю то, что Вы пробовали сделать, но команда, которую Вы только послали базе данных, не выглядела очень дружественной и она была заблокированна.<br /><br />Ваш IP, и другие данные переданны администрации сервера. Удачи!.';
756
        die($message);
757
      break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
758
    }
759
  }
760
761
  /**
762
   * @param bool $prefixed_only
763
   *
764
   * @return array
765
   */
766
  public function db_get_table_list($prefixed_only = true) {
767
    $query = $this->mysql_get_table_list();
768
769
    $prefix_length = strlen($this->db_prefix);
770
771
    $tl = array();
772
    while ($row = $this->db_fetch($query)) {
0 ignored issues
show
Bug introduced by
It seems like $query defined by $this->mysql_get_table_list() on line 767 can also be of type boolean; however, db_mysql::db_fetch() does only seem to accept object<mysqli_result>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
773
      foreach ($row as $table_name) {
774
        if (strpos($table_name, $this->db_prefix) === 0) {
775
          $table_name = substr($table_name, $prefix_length);
776
        } elseif ($prefixed_only) {
777
          continue;
778
        }
779
        // $table_name = str_replace($db_prefix, '', $table_name);
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
780
        $tl[$table_name] = $table_name;
781
      }
782
    }
783
784
    return $tl;
785
  }
786
787
  /**
788
   * @param string $statement
789
   *
790
   * @return bool|mysqli_stmt
791
   */
792 View Code Duplication
  public function db_prepare($statement) {
0 ignored issues
show
Duplication introduced by
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...
793
    $microtime = microtime(true);
794
    $result = $this->driver->mysql_prepare($statement);
795
    $this->time_mysql_total += microtime(true) - $microtime;
796
797
    return $result;
798
  }
799
800
801
  /**
802
   * L1 perform the query
803
   *
804
   * @param $query_string
805
   *
806
   * @return bool|mysqli_result
807
   */
808 View Code Duplication
  public function db_sql_query($query_string) {
0 ignored issues
show
Duplication introduced by
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...
809
    $microtime = microtime(true);
810
    $result = $this->driver->mysql_query($query_string);
811
    $this->time_mysql_total += microtime(true) - $microtime;
812
813
    return $result;
814
  }
815
816
  /**
817
   * L1 fetch assoc array
818
   *
819
   * @param mysqli_result $query
820
   *
821
   * @return array|null
822
   */
823 View Code Duplication
  public function db_fetch(&$query) {
0 ignored issues
show
Duplication introduced by
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...
824
    $microtime = microtime(true);
825
    $result = $this->driver->mysql_fetch_assoc($query);
826
    $this->time_mysql_total += microtime(true) - $microtime;
827
828
    return $result;
829
  }
830
831
  public function db_fetch_row(&$query) {
832
    return $this->driver->mysql_fetch_row($query);
833
  }
834
835
  public function db_escape($unescaped_string) {
836
    return $this->driver->mysql_real_escape_string($unescaped_string);
837
  }
838
839
  public function driver_disconnect() {
840
    return $this->driver->mysql_close_link();
841
  }
842
843
  public function db_error() {
844
    return $this->driver->mysql_error();
845
  }
846
847
  public function db_insert_id() {
848
    return $this->driver->mysql_insert_id();
849
  }
850
851
  public function db_num_rows(&$result) {
852
    return $this->driver->mysql_num_rows($result);
853
  }
854
855
  public function db_affected_rows() {
856
    return $this->driver->mysql_affected_rows();
857
  }
858
859
  /**
860
   * @return string
861
   */
862
  public function db_get_client_info() {
863
    return $this->driver->mysql_get_client_info();
864
  }
865
866
  /**
867
   * @return string
868
   */
869
  public function db_get_server_info() {
870
    return $this->driver->mysql_get_server_info();
871
  }
872
873
  /**
874
   * @return string
875
   */
876
  public function db_get_host_info() {
877
    return $this->driver->mysql_get_host_info();
878
  }
879
880
  public function db_get_server_stat() {
881
    $result = array();
882
883
    $status = explode('  ', $this->driver->mysql_stat());
884
    foreach ($status as $value) {
885
      $row = explode(': ', $value);
886
      $result[$row[0]] = $row[1];
887
    }
888
889
    return $result;
890
  }
891
892
  /**
893
   * @return array
894
   * @throws Exception
895
   */
896
  public function db_core_show_status() {
897
    $result = array();
898
899
    $query = $this->db_sql_query('SHOW STATUS;');
900
    if (is_bool($query)) {
901
      throw new Exception('Result of SHOW STATUS command is boolean - which should never happen. Connection to DB is lost?');
902
    }
903
    while ($row = db_fetch($query)) {
904
      $result[$row['Variable_name']] = $row['Value'];
905
    }
906
907
    return $result;
908
  }
909
910
  public function mysql_get_table_list() {
911
    return $this->db_sql_query('SHOW TABLES;');
912
  }
913
914
  public function mysql_get_innodb_status() {
915
    return $this->db_sql_query('SHOW ENGINE INNODB STATUS;');
916
  }
917
918
  // Some wrappers to DbTransaction
919
  // Unused for now
920
  /**
921
   * @return \DBAL\DbTransaction
922
   */
923
  public function getTransaction() {
924
    return $this->transaction;
925
  }
926
927
  public function transactionCheck($status = null) {
928
    return $this->transaction->check($status);
929
  }
930
931
  public function transactionStart($level = '') {
932
    return $this->transaction->start($level);
933
  }
934
935
  public function transactionCommit() {
936
    return $this->transaction->commit();
937
  }
938
939
  public function transactionRollback() {
940
    return $this->transaction->rollback();
941
  }
942
943
}
944