Completed
Push — work-fleets ( 98be23...4e14e1 )
by SuperNova.WS
05:25
created

db_mysql::db_prepare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 7
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 1
dl 7
loc 7
rs 9.4285
1
<?php
2
3
/**
4
 * User: Gorlum
5
 * Date: 01.09.2015
6
 * Time: 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
  public function __construct() {
63
  }
64
65
  public function load_db_settings() {
66
    $dbsettings = array();
67
68
    require(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
69
70
    $this->dbsettings = $dbsettings;
71
  }
72
73
  public function sn_db_connect($external_db_settings = null) {
74
    $this->db_disconnect();
75
76
    if (!empty($external_db_settings) && is_array($external_db_settings)) {
77
      $this->dbsettings = $external_db_settings;
78
    }
79
80
    if (empty($this->dbsettings)) {
81
      $this->load_db_settings();
82
    }
83
84
    // TODO - фатальные (?) ошибки на каждом шагу. Хотя - скорее Эксепшны
85
    if (!empty($this->dbsettings)) {
86
      $driver_name = empty($this->dbsettings['sn_driver']) ? 'db_mysql_v5' : $this->dbsettings['sn_driver'];
87
      $this->driver = new $driver_name();
88
      $this->db_prefix = $this->dbsettings['prefix'];
89
90
      $this->connected = $this->connected || $this->driver_connect();
91
92
      if ($this->connected) {
93
        $this->table_list = $this->db_get_table_list();
94
        // TODO Проверка на пустоту
95
      }
96
    } else {
97
      $this->connected = false;
98
    }
99
100
    return $this->connected;
101
  }
102
103
  protected function driver_connect() {
104
    if (!is_object($this->driver)) {
105
      classSupernova::$debug->error_fatal('DB Error - No driver for MySQL found!');
106
    }
107
108
    if (!method_exists($this->driver, 'mysql_connect')) {
109
      classSupernova::$debug->error_fatal('DB Error - WRONG MySQL driver!');
110
    }
111
112
    return $this->driver->mysql_connect($this->dbsettings);
113
  }
114
115
  public function db_disconnect() {
116
    if ($this->connected) {
117
      $this->connected = !$this->driver_disconnect();
118
      $this->connected = false;
119
    }
120
121
    return !$this->connected;
122
  }
123
124
  /**
125
   * @param string $query
126
   *
127
   * @return mixed|string
128
   */
129
  public function replaceTablePlaceholders($query) {
130
    $sql = $query;
131
    if (strpos($sql, '{{') !== false) {
132
      foreach ($this->table_list as $tableName) {
133
        $sql = str_replace("{{{$tableName}}}", $this->db_prefix . $tableName, $sql);
134
      }
135
    }
136
137
    return $sql;
138
  }
139
140
  /**
141
   * @param       $query
142
   * @param       $fetch
143
   */
144
  protected function logQuery($query, $fetch) {
145
    if (!classSupernova::$config->debug) {
146
      return;
147
    }
148
149
    $this->queryCount++;
150
    $arr = debug_backtrace();
151
    $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...
152
    $line = $arr[0]['line'];
153
    classSupernova::$debug->add("<tr><th>Query {$this->queryCount}: </th><th>$query</th><th>{$file} @ {$line}</th><th>&nbsp;</th><th> " . ($fetch ? '+' : '&nbsp;') . " </th></tr>");
154
  }
155
156
157
  /**
158
   * @return string
159
   */
160
  public function queryTrace() {
161
    if (!defined('DEBUG_SQL_COMMENT') || constant('DEBUG_SQL_ERROR') !== true) {
162
      return '';
163
    }
164
    $backtrace = debug_backtrace();
165
    $sql_comment = classSupernova::$debug->compact_backtrace($backtrace, defined('DEBUG_SQL_COMMENT_LONG'));
166
167
    if (defined('DEBUG_SQL_ERROR') && constant('DEBUG_SQL_ERROR') === true) {
168
//      array_unshift($sql_comment, $sql_one_liner);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
169
      classSupernova::$debug->add_to_array($sql_comment);
170
    }
171
172
    $sql_commented = '/* ' . implode("<br />", $sql_comment) . '<br /> */ ';
173
    if (defined('DEBUG_SQL_ONLINE') && constant('DEBUG_SQL_ONLINE') === true) {
174
      classSupernova::$debug->warning($sql_commented, 'SQL Debug', LOG_DEBUG_SQL);
175
    }
176
177
    return $sql_commented;
178
  }
179
180
  /**
181
   * @param DbSqlStatement $statement
182
   *
183
   * @return array|bool|mysqli_result|null
184
   */
185
  public function execute($statement) {
186
    return $this->doquery((string)$statement);
187
  }
188
189
  /**
190
   * @param DbSqlStatement $statement
191
   *
192
   * @return array|null
193
   */
194
  public function fetchOne($statement) {
195
    $query = $this->execute($statement->fetchOne());
196
197
    return $this->db_fetch($query);
198
  }
199
200
  /**
201
   * @param string|DbSqlPrepare $query
202
   * @param string              $table
203
   * @param bool                $fetch
204
   * @param bool                $skip_query_check
205
   *
206
   * @return array|bool|mysqli_result|null
207
   */
208
  public function doquery($query, $table = '', $fetch = false, $skip_query_check = false) {
209
    if (!is_string($table)) {
210
      $fetch = $table;
211
    }
212
213
    if (!$this->connected) {
214
      $this->sn_db_connect();
215
    }
216
217
    $stringQuery = $query instanceof DbSqlPrepare ? $query->query : $query;
218
    $stringQuery = trim($stringQuery);
219
    $stringQuery = preg_replace("/\s+/", ' ', $stringQuery);
220
221
    $this->security_watch_user_queries($stringQuery);
222
    $this->security_query_check_bad_words($stringQuery, $skip_query_check);
223
    $this->logQuery($stringQuery, $fetch);
224
225
    $stringQuery = $this->replaceTablePlaceholders($stringQuery);
226
227
    $queryTrace = $this->queryTrace();
228
229
    $queryResult = null;
230
    try {
231
      if ($query instanceof DbSqlPrepare) {
232
        // MYSQLI ONLY!!!
1 ignored issue
show
Unused Code Comprehensibility introduced by
43% 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...
233
        $queryResult = $query
234
          ->setQuery($stringQuery)
235
          ->comment($queryTrace)
236
          ->compileMySqlI()
237
          ->statementGet($this)
238
          ->execute()
239
          ->getResult();
240
      } else {
241
        $queryResult = $this->db_sql_query($stringQuery . $queryTrace);
242
      }
243
      if (!$queryResult) {
244
        throw new Exception();
245
      }
246
    } catch (Exception $e) {
247
      classSupernova::$debug->error($this->db_error() . "<br />{$query}<br />", 'SQL Error');
248
    }
249
250
    if ($fetch) {
251
      $queryResult = $this->db_fetch($queryResult);
252
      // DO NOT CLOSE STATEMENT HERE TO MAKE STATEMENT CACHING WORK!
253
    }
254
255
    return $queryResult;
256
  }
257
258
259
  // TODO Заменить это на новый логгер
260
  protected function security_watch_user_queries($query) {
261
    global $user;
262
263
    if (
264
      !$this->isWatching // Not already watching
265
      && !empty(classSupernova::$config->game_watchlist_array) // There is some players in watchlist
266
      && in_array($user['id'], classSupernova::$config->game_watchlist_array) // Current player is in watchlist
267
      && !preg_match('/^(select|commit|rollback|start transaction)/i', $query) // Current query should be watched
268
    ) {
269
      $this->isWatching = true;
270
      $msg = "\$query = \"{$query}\"\n\r";
271
      if (!empty($_POST)) {
272
        $msg .= "\n\r" . dump($_POST, '$_POST');
273
      }
274
      if (!empty($_GET)) {
275
        $msg .= "\n\r" . dump($_GET, '$_GET');
276
      }
277
      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...
278
      $this->isWatching = false;
279
    }
280
  }
281
282
283
  public function security_query_check_bad_words($query, $skip_query_check = false) {
284
    if ($skip_query_check) {
285
      return;
286
    }
287
288
    global $user, $dm_change_legit, $mm_change_legit;
289
290
    switch (true) {
291
      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...
292
      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...
293
      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...
294
      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...
295
      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...
296
      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...
297
      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...
298
      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...
299
      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...
300
      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...
301
        $report = "Hacking attempt (" . date("d.m.Y H:i:s") . " - [" . time() . "]):\n";
302
        $report .= ">Database Inforamation\n";
303
        $report .= "\tID - " . $user['id'] . "\n";
304
        $report .= "\tUser - " . $user['username'] . "\n";
305
        $report .= "\tAuth level - " . $user['authlevel'] . "\n";
306
        $report .= "\tAdmin Notes - " . $user['adminNotes'] . "\n";
307
        $report .= "\tCurrent Planet - " . $user['current_planet'] . "\n";
308
        $report .= "\tUser IP - " . $user['user_lastip'] . "\n";
309
        $report .= "\tUser IP at Reg - " . $user['ip_at_reg'] . "\n";
310
        $report .= "\tUser Agent- " . $_SERVER['HTTP_USER_AGENT'] . "\n";
311
        $report .= "\tCurrent Page - " . $user['current_page'] . "\n";
312
        $report .= "\tRegister Time - " . $user['register_time'] . "\n";
313
        $report .= "\n";
314
315
        $report .= ">Query Information\n";
316
        $report .= "\tQuery - " . $query . "\n";
317
        $report .= "\n";
318
319
        $report .= ">\$_SERVER Information\n";
320
        $report .= "\tIP - " . $_SERVER['REMOTE_ADDR'] . "\n";
321
        $report .= "\tHost Name - " . $_SERVER['HTTP_HOST'] . "\n";
322
        $report .= "\tUser Agent - " . $_SERVER['HTTP_USER_AGENT'] . "\n";
323
        $report .= "\tRequest Method - " . $_SERVER['REQUEST_METHOD'] . "\n";
324
        $report .= "\tCame From - " . $_SERVER['HTTP_REFERER'] . "\n";
325
        $report .= "\tPage is - " . $_SERVER['SCRIPT_NAME'] . "\n";
326
        $report .= "\tUses Port - " . $_SERVER['REMOTE_PORT'] . "\n";
327
        $report .= "\tServer Protocol - " . $_SERVER['SERVER_PROTOCOL'] . "\n";
328
329
        $report .= "\n--------------------------------------------------------------------------------------------------\n";
330
331
        $fp = fopen(SN_ROOT_PHYSICAL . 'badqrys.txt', 'a');
332
        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.

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...
333
        fclose($fp);
334
335
        $message = 'Привет, я не знаю то, что Вы пробовали сделать, но команда, которую Вы только послали базе данных, не выглядела очень дружественной и она была заблокированна.<br /><br />Ваш IP, и другие данные переданны администрации сервера. Удачи!.';
336
        die($message);
337
      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...
338
    }
339
  }
340
341
  /**
342
   * @param bool $prefixed_only
343
   *
344
   * @return array
345
   */
346
  public function db_get_table_list($prefixed_only = true) {
347
    $query = $this->mysql_get_table_list();
348
349
    $prefix_length = strlen($this->db_prefix);
350
351
    $tl = array();
352
    while ($row = $this->db_fetch($query)) {
353
      foreach ($row as $table_name) {
354
        if (strpos($table_name, $this->db_prefix) === 0) {
355
          $table_name = substr($table_name, $prefix_length);
356
        } elseif ($prefixed_only) {
357
          continue;
358
        }
359
        // $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...
360
        $tl[$table_name] = $table_name;
361
      }
362
    }
363
364
    return $tl;
365
  }
366
367
  /**
368
   * @param string $statement
369
   *
370
   * @return bool|mysqli_stmt
371
   */
372 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...
373
    $microtime = microtime(true);
374
    $result = $this->driver->mysql_prepare($statement);
375
    $this->time_mysql_total += microtime(true) - $microtime;
376
377
    return $result;
378
  }
379
380
381
  /**
382
   * L1 perform the query
383
   *
384
   * @param $query_string
385
   *
386
   * @return bool|mysqli_result
387
   */
388 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...
389
    $microtime = microtime(true);
390
    $result = $this->driver->mysql_query($query_string);
391
    $this->time_mysql_total += microtime(true) - $microtime;
392
393
    return $result;
394
  }
395
396
  /**
397
   * L1 fetch assoc array
398
   *
399
   * @param $query
400
   *
401
   * @return array|null
402
   */
403 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...
404
    $microtime = microtime(true);
405
    $result = $this->driver->mysql_fetch_assoc($query);
406
    $this->time_mysql_total += microtime(true) - $microtime;
407
408
    return $result;
409
  }
410
411
  public function db_fetch_row(&$query) {
412
    return $this->driver->mysql_fetch_row($query);
413
  }
414
415
  public function db_escape($unescaped_string) {
416
    return $this->driver->mysql_real_escape_string($unescaped_string);
417
  }
418
419
  public function driver_disconnect() {
420
    return $this->driver->mysql_close_link();
421
  }
422
423
  public function db_error() {
424
    return $this->driver->mysql_error();
425
  }
426
427
  public function db_insert_id() {
428
    return $this->driver->mysql_insert_id();
429
  }
430
431
  public function db_num_rows(&$result) {
432
    return $this->driver->mysql_num_rows($result);
433
  }
434
435
  public function db_affected_rows() {
436
    return $this->driver->mysql_affected_rows();
437
  }
438
439
  /**
440
   * @return string
441
   */
442
  public function db_get_client_info() {
443
    return $this->driver->mysql_get_client_info();
444
  }
445
446
  /**
447
   * @return string
448
   */
449
  public function db_get_server_info() {
450
    return $this->driver->mysql_get_server_info();
451
  }
452
453
  /**
454
   * @return string
455
   */
456
  public function db_get_host_info() {
457
    return $this->driver->mysql_get_host_info();
458
  }
459
460
  public function db_get_server_stat() {
461
    $result = array();
462
463
    $status = explode('  ', $this->driver->mysql_stat());
464
    foreach ($status as $value) {
465
      $row = explode(': ', $value);
466
      $result[$row[0]] = $row[1];
467
    }
468
469
    return $result;
470
  }
471
472
  /**
473
   * @return array
474
   * @throws Exception
475
   */
476
  public function db_core_show_status() {
477
    $result = array();
478
479
    $query = $this->db_sql_query('SHOW STATUS;');
480
    if (is_bool($query)) {
481
      throw new Exception('Result of SHOW STATUS command is boolean - which should never happen. Connection to DB is lost?');
482
    }
483
    while ($row = db_fetch($query)) {
484
      $result[$row['Variable_name']] = $row['Value'];
485
    }
486
487
    return $result;
488
  }
489
490
  public function mysql_get_table_list() {
491
    return $this->db_sql_query('SHOW TABLES;');
492
  }
493
494
  public function mysql_get_innodb_status() {
495
    return $this->db_sql_query('SHOW ENGINE INNODB STATUS;');
496
  }
497
498
}
499