Completed
Push — trunk ( 09520e...7ac6b6 )
by SuperNova.WS
03:48
created

db_mysql::load_db_settings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
use \Common\GlobalContainer;
4
use \DBAL\DbMysqliResultIterator;
5
6
/**
7
 * User: Gorlum
8
 * Date: 01.09.2015
9
 * Time: 15:58
10
 */
11
class db_mysql {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
12
  const DB_MYSQL_TRANSACTION_SERIALIZABLE = 'SERIALIZABLE';
13
  const DB_MYSQL_TRANSACTION_REPEATABLE_READ = 'REPEATABLE READ';
14
  const DB_MYSQL_TRANSACTION_READ_COMMITTED = 'READ COMMITTED';
15
  const DB_MYSQL_TRANSACTION_READ_UNCOMMITTED = 'READ UNCOMMITTED';
16
17
  /**
18
   * Статус соеднения с MySQL
19
   *
20
   * @var bool
21
   */
22
  public $connected = false;
23
  /**
24
   * Префикс названий таблиц в БД
25
   *
26
   * @var string
27
   */
28
  public $db_prefix = '';
29
  /**
30
   * Настройки БД
31
   *
32
   * @var array
33
   */
34
  protected $dbsettings = array();
35
  /**
36
   * Драйвер для прямого обращения к MySQL
37
   *
38
   * @var db_mysql_v5 $driver
39
   */
40
  public $driver = null;
41
42
  /**
43
   * Общее время запросов
44
   *
45
   * @var float $time_mysql_total
46
   */
47
  public $time_mysql_total = 0.0;
48
49
  /**
50
   * DB schemes
51
   *
52
   * @var \DBAL\Schema|null $schema
53
   */
54
  protected static $schema = null;
55
56
  /**
57
   * db_mysql constructor.
58
   *
59
   * @param GlobalContainer $gc
60
   */
61
  public function __construct($gc) {
0 ignored issues
show
Unused Code introduced by
The parameter $gc is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

61
  public function __construct(/** @scrutinizer ignore-unused */ $gc) {

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

Loading history...
62
//    $this->transaction = new \DBAL\DbTransaction($gc, $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...
63
//    $this->snCache = new $gc->snCacheClass($gc, $this);
64
//    $this->operator = new DbRowDirectOperator($this);
65
  }
66
67
  public function schema() {
68
    if (!isset(self::$schema)) {
69
      self::$schema = new \DBAL\Schema($this);
70
    }
71
72
    return self::$schema;
73
  }
74
75
  public function load_db_settings() {
76
    $dbsettings = array();
77
78
    require(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
79
80
    $this->dbsettings = $dbsettings;
81
  }
82
83
  public function sn_db_connect($external_db_settings = null) {
84
    $this->db_disconnect();
85
86
    if (!empty($external_db_settings) && is_array($external_db_settings)) {
87
      $this->dbsettings = $external_db_settings;
88
    }
89
90
    if (empty($this->dbsettings)) {
91
      $this->load_db_settings();
92
    }
93
94
    // TODO - фатальные (?) ошибки на каждом шагу. Хотя - скорее Эксепшны
95
    if (!empty($this->dbsettings)) {
96
      $driver_name = empty($this->dbsettings['sn_driver']) ? 'db_mysql_v5' : $this->dbsettings['sn_driver'];
97
      $this->driver = new $driver_name();
98
      $this->db_prefix = $this->dbsettings['prefix'];
99
100
      $this->connected = $this->connected || $this->driver_connect();
101
102
      if ($this->connected && empty($this->schema()->getSnTables())) {
103
        die('DB error - cannot find any table. Halting...');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
104
      }
105
106
      $this->doQueryFast('SET SESSION TRANSACTION ISOLATION LEVEL ' . self::DB_MYSQL_TRANSACTION_SERIALIZABLE);
107
    } else {
108
      $this->connected = false;
109
    }
110
111
    return $this->connected;
112
  }
113
114
  public function driver_connect() {
115
    global $debug;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
116
117
    if (!is_object($this->driver)) {
118
      $debug->error_fatal('DB Error - No driver for MySQL found!');
119
    }
120
121
    if (!method_exists($this->driver, 'mysql_connect')) {
122
      $debug->error_fatal('DB Error - WRONG MySQL driver!');
123
    }
124
125
    return $this->driver->mysql_connect($this->dbsettings);
126
  }
127
128
  public function db_disconnect() {
129
    if ($this->connected) {
130
      $this->connected = !$this->driver_disconnect();
131
      $this->connected = false;
132
    }
133
134
    return !$this->connected;
135
  }
136
137
  /**
138
   * @param int    $errno
139
   * @param string $errstr
140
   * @param string $errfile
141
   * @param int    $errline
142
   * @param array  $errcontext
143
   */
144
  public function handlerQueryWarning($errno, $errstr, $errfile, $errline, $errcontext) {
0 ignored issues
show
Unused Code introduced by
The parameter $errstr is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

144
  public function handlerQueryWarning($errno, /** @scrutinizer ignore-unused */ $errstr, $errfile, $errline, $errcontext) {

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

Loading history...
Unused Code introduced by
The parameter $errfile is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

144
  public function handlerQueryWarning($errno, $errstr, /** @scrutinizer ignore-unused */ $errfile, $errline, $errcontext) {

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

Loading history...
Unused Code introduced by
The parameter $errno is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

144
  public function handlerQueryWarning(/** @scrutinizer ignore-unused */ $errno, $errstr, $errfile, $errline, $errcontext) {

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

Loading history...
Unused Code introduced by
The parameter $errline is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

144
  public function handlerQueryWarning($errno, $errstr, $errfile, /** @scrutinizer ignore-unused */ $errline, $errcontext) {

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

Loading history...
Unused Code introduced by
The parameter $errcontext is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

144
  public function handlerQueryWarning($errno, $errstr, $errfile, $errline, /** @scrutinizer ignore-unused */ $errcontext) {

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

Loading history...
145
    static $alreadyHandled;
146
147
    // Error was suppressed with the @-operator
148
    if (0 === error_reporting()) {
149
      return false;
150
    }
151
152
    if (!$alreadyHandled) {
153
      print(SN_TIME_SQL . '<br />Server is busy. Please try again in several minutes...<br />Сервер занят. Попробуйте снова через несколько минут...<br />Server zanyat. Poprobujte snova cherez neskolko minut...');
154
      $alreadyHandled = true;
155
    }
156
157
    return true;
158
  }
159
160
  public function prefixReplace($sql) {
161
    if (strpos($sql, '{{') !== false) {
162
      foreach ($this->schema()->getSnTables() as $tableName) {
163
        $sql = str_replace("{{{$tableName}}}", $this->db_prefix . $tableName, $sql);
164
      }
165
    }
166
167
    return $sql;
168
  }
169
170
  public function doquery($query, $table = '', $fetch = false, $skip_query_check = false) {
171
    global $numqueries, $debug, $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
172
173
    if (!is_string($table)) {
174
      $fetch = $table;
175
    }
176
177
    if (!$this->connected) {
178
      $this->sn_db_connect();
179
    }
180
181
    $query = trim($query);
182
    $this->security_watch_user_queries($query);
183
    $skip_query_check or $this->security_query_check_bad_words($query);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
184
185
    $sql = $this->prefixReplace($query);
186
//    $sql = $query;
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...
187
//    if (strpos($sql, '{{') !== false) {
188
//      foreach ($this->schema()->getSnTables() as $tableName) {
189
//        $sql = str_replace("{{{$tableName}}}", $this->db_prefix . $tableName, $sql);
190
//      }
191
//    }
192
193
    if ($config->debug) {
194
      $numqueries++;
195
      $arr = debug_backtrace();
196
      $file = end(explode('/', $arr[0]['file']));
197
      $line = $arr[0]['line'];
198
      $debug->add("<tr><th>Query $numqueries: </th><th>$query</th><th>$file($line)</th><th>$table</th><th>$fetch</th></tr>");
199
    }
200
201
    if (defined('DEBUG_SQL_COMMENT')) {
202
      $backtrace = debug_backtrace();
203
      $sql_comment = $debug->compact_backtrace($backtrace, defined('DEBUG_SQL_COMMENT_LONG'));
204
205
      $sql_commented = '/* ' . implode("<br />", $sql_comment) . '<br /> */ ' . preg_replace("/\s+/", ' ', $sql);
206
      if (defined('DEBUG_SQL_ONLINE')) {
207
        $debug->warning($sql_commented, 'SQL Debug', LOG_DEBUG_SQL);
208
      }
209
210
      if (defined('DEBUG_SQL_ERROR')) {
211
        array_unshift($sql_comment, preg_replace("/\s+/", ' ', $sql));
212
        $debug->add_to_array($sql_comment);
213
        // $debug->add_to_array($sql_comment . preg_replace("/\s+/", ' ', $sql));
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
214
      }
215
      $sql = $sql_commented;
216
    }
217
218
    set_error_handler([$this, 'handlerQueryWarning']);
219
    $sqlquery = $this->db_sql_query($sql) or $debug->error(db_error() . "<br />$sql<br />", 'SQL Error');
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
220
    restore_error_handler();
221
222
    return $fetch ? $this->db_fetch($sqlquery) : $sqlquery;
0 ignored issues
show
Bug introduced by
It seems like $sqlquery can also be of type boolean; however, parameter $query_result of db_mysql::db_fetch() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

222
    return $fetch ? $this->db_fetch(/** @scrutinizer ignore-type */ $sqlquery) : $sqlquery;
Loading history...
223
  }
224
225
  public function doQueryFast($query, $fetch = false) {
226
    $sql = $this->prefixReplace($query);
227
228
    set_error_handler([$this, 'handlerQueryWarning']);
229
    $sqlquery = $this->db_sql_query($sql) or SN::$debug->error(db_error() . "<br />$sql<br />", 'SQL Error');
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
230
    restore_error_handler();
231
232
    return $fetch ? $this->db_fetch($sqlquery) : $sqlquery;
0 ignored issues
show
Bug introduced by
It seems like $sqlquery can also be of type boolean; however, parameter $query_result of db_mysql::db_fetch() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

232
    return $fetch ? $this->db_fetch(/** @scrutinizer ignore-type */ $sqlquery) : $sqlquery;
Loading history...
233
  }
234
235
  /**
236
   * @param string $query
237
   * @param bool   $skip_query_check
238
   *
239
   * @return DbMysqliResultIterator
240
   */
241
  public function selectIterator($query, $skip_query_check = false) {
242
    return new DbMysqliResultIterator($this->doquery($query, '', false, $skip_query_check));
243
  }
244
245
  /**
246
   * @param string $query
247
   * @param bool   $skip_query_check
248
   *
249
   * @return int|null
250
   */
251
  public function selectValue($query, $skip_query_check = false) {
252
    $row = $this->doquery($query, '', true, $skip_query_check);
253
254
    return !empty($row) ? intval(reset($row)) : null;
255
  }
256
257
  /**
258
   * @param \DBAL\DbQuery $dbQuery
259
   *
260
   * @return array|null
261
   */
262
  public function dbqSelectAndFetch(\DBAL\DbQuery $dbQuery) {
263
    return $this->doquery($dbQuery->select(), true);
264
  }
265
266
267
  public function security_watch_user_queries($query) {
268
    // TODO Заменить это на новый логгер
269
    global $config, $is_watching, $user, $debug;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
270
271
    if (!$is_watching && $config->game_watchlist_array && in_array($user['id'], $config->game_watchlist_array)) {
272
      if (!preg_match('/^(select|commit|rollback|start transaction)/i', $query)) {
273
        $is_watching = true;
274
        $msg = "\$query = \"{$query}\"\n\r";
275
        if (!empty($_POST)) {
276
          $msg .= "\n\r" . dump($_POST, '$_POST');
277
        }
278
        if (!empty($_GET)) {
279
          $msg .= "\n\r" . dump($_GET, '$_GET');
280
        }
281
        $debug->warning($msg, "Watching user {$user['id']}", 399, array('base_dump' => true));
282
        $is_watching = false;
283
      }
284
    }
285
  }
286
287
288
  public function security_query_check_bad_words($query) {
289
    global $user, $dm_change_legit, $mm_change_legit;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
290
291
    switch (true) {
292
      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...
293
      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...
294
      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...
295
      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...
296
      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...
297
      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...
298
      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...
299
      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...
300
      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...
301
      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...
302
        $report = "Hacking attempt (" . date("d.m.Y H:i:s") . " - [" . time() . "]):\n";
303
        $report .= ">Database Inforamation\n";
304
        $report .= "\tID - " . $user['id'] . "\n";
305
        $report .= "\tUser - " . $user['username'] . "\n";
306
        $report .= "\tAuth level - " . $user['authlevel'] . "\n";
307
        $report .= "\tAdmin Notes - " . $user['adminNotes'] . "\n";
308
        $report .= "\tCurrent Planet - " . $user['current_planet'] . "\n";
309
        $report .= "\tUser IP - " . $user['user_lastip'] . "\n";
310
        $report .= "\tUser IP at Reg - " . $user['ip_at_reg'] . "\n";
311
        $report .= "\tUser Agent- " . $_SERVER['HTTP_USER_AGENT'] . "\n";
312
        $report .= "\tCurrent Page - " . $user['current_page'] . "\n";
313
        $report .= "\tRegister Time - " . $user['register_time'] . "\n";
314
        $report .= "\n";
315
316
        $report .= ">Query Information\n";
317
        $report .= "\tQuery - " . $query . "\n";
318
        $report .= "\n";
319
320
        $report .= ">\$_SERVER Information\n";
321
        $report .= "\tIP - " . $_SERVER['REMOTE_ADDR'] . "\n";
322
        $report .= "\tHost Name - " . $_SERVER['HTTP_HOST'] . "\n";
323
        $report .= "\tUser Agent - " . $_SERVER['HTTP_USER_AGENT'] . "\n";
324
        $report .= "\tRequest Method - " . $_SERVER['REQUEST_METHOD'] . "\n";
325
        $report .= "\tCame From - " . $_SERVER['HTTP_REFERER'] . "\n";
326
        $report .= "\tPage is - " . $_SERVER['SCRIPT_NAME'] . "\n";
327
        $report .= "\tUses Port - " . $_SERVER['REMOTE_PORT'] . "\n";
328
        $report .= "\tServer Protocol - " . $_SERVER['SERVER_PROTOCOL'] . "\n";
329
330
        $report .= "\n--------------------------------------------------------------------------------------------------\n";
331
332
        $fp = fopen(SN_ROOT_PHYSICAL . 'badqrys.txt', 'a');
333
        fwrite($fp, $report);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

333
        fwrite(/** @scrutinizer ignore-type */ $fp, $report);
Loading history...
334
        fclose($fp);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

334
        fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
335
336
        $message = 'Привет, я не знаю то, что Вы пробовали сделать, но команда, которую Вы только послали базе данных, не выглядела очень дружественной и она была заблокированна.<br /><br />Ваш IP, и другие данные переданны администрации сервера. Удачи!.';
337
        die($message);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
338
      break;
339
    }
340
  }
341
342
  public function mysql_get_table_list() {
343
    return $this->db_sql_query('SHOW TABLES;');
344
  }
345
346
  public function mysql_get_innodb_status() {
347
    return $this->db_sql_query('SHOW ENGINE INNODB STATUS;');
348
  }
349
350
  /**
351
   * @param string $tableName_unsafe
352
   *
353
   * @return array[]
354
   */
355
  public function mysql_get_fields($tableName_unsafe) {
356
    $result = [];
357
358
    $prefixedTableName_safe = $this->db_escape($this->db_prefix . $tableName_unsafe);
359
    $q1 = $this->db_sql_query("SHOW FULL COLUMNS FROM `{$prefixedTableName_safe}`;");
360
    while ($r1 = db_fetch($q1)) {
361
      $result[$r1['Field']] = $r1;
362
    }
363
364
    return $result;
365
  }
366
367
  /**
368
   * @param string $tableName_unsafe
369
   *
370
   * @return array[]
371
   */
372
  public function mysql_get_indexes($tableName_unsafe) {
373
    $result = [];
374
375
    $prefixedTableName_safe = $this->db_escape($this->db_prefix . $tableName_unsafe);
376
    $q1 = $this->db_sql_query("SHOW INDEX FROM {$prefixedTableName_safe};");
377
    while ($r1 = db_fetch($q1)) {
378
      $indexName = $r1['Key_name'];
379
380
      $result[$indexName]['name'] = $r1['Key_name'];
381
      $result[$indexName]['signature'][] = $r1['Column_name'];
382
      $result[$indexName]['fields'][$r1['Column_name']] = $r1;
383
    }
384
385
    foreach ($result as &$indexDescription) {
386
      $indexDescription['signature'] = implode(',', $indexDescription['signature']);
387
    }
388
389
    return $result;
390
  }
391
392
  /**
393
   * @param string $tableName_unsafe
394
   *
395
   * @return array[]
396
   */
397
  public function mysql_get_constraints($tableName_unsafe) {
398
    $result = [];
399
400
    $prefixedTableName_safe = $this->db_escape($this->db_prefix . $tableName_unsafe);
401
402
    $q1 = $this->db_sql_query("SELECT * FROM `information_schema`.`KEY_COLUMN_USAGE` WHERE `TABLE_SCHEMA` = '" . db_escape(SN::$db_name) . "' AND `TABLE_NAME` = '{$prefixedTableName_safe}' AND `REFERENCED_TABLE_NAME` IS NOT NULL;");
403
    while ($r1 = db_fetch($q1)) {
404
      $indexName = $r1['CONSTRAINT_NAME'];
405
406
      $table_referenced = str_replace($this->db_prefix, '', $r1['REFERENCED_TABLE_NAME']);
407
408
      $result[$indexName]['name'] = $indexName;
409
      $result[$indexName]['signature'][] = "{$r1['COLUMN_NAME']}=>{$table_referenced}.{$r1['REFERENCED_COLUMN_NAME']}";
410
      $r1['REFERENCED_TABLE_NAME'] = $table_referenced;
411
      $r1['TABLE_NAME'] = $tableName_unsafe;
412
      $result[$indexName]['fields'][$r1['COLUMN_NAME']] = $r1;
413
    }
414
415
    foreach ($result as &$constraint) {
416
      $constraint['signature'] = implode(',', $constraint['signature']);
417
    }
418
419
    return $result;
420
  }
421
422
423
  public function db_sql_query($query_string) {
424
    $microtime = microtime(true);
425
    $result = $this->driver->mysql_query($query_string);
426
    $this->time_mysql_total += microtime(true) - $microtime;
427
428
    return $result;
429
//    return $this->driver->mysql_query($query_string);
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...
430
  }
431
432
  /**
433
   * @param mysqli_result $query_result
434
   *
435
   * @return array|null
436
   */
437
  public function db_fetch(&$query_result) {
438
    $microtime = microtime(true);
439
    $result = $this->driver->mysql_fetch_assoc($query_result);
440
    $this->time_mysql_total += microtime(true) - $microtime;
441
442
    return $result;
443
//    return $this->driver->mysql_fetch_assoc($query);
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...
444
  }
445
446
  public function db_fetch_row(&$query) {
447
    return $this->driver->mysql_fetch_row($query);
448
  }
449
450
  public function db_escape($unescaped_string) {
451
    return $this->driver->mysql_real_escape_string($unescaped_string);
452
  }
453
454
  public function driver_disconnect() {
455
    return $this->driver->mysql_close_link();
456
  }
457
458
  public function db_error() {
459
    return $this->driver->mysql_error();
460
  }
461
462
  /**
463
   * @return int|string
464
   */
465
  public function db_insert_id() {
466
    return $this->driver->mysql_insert_id();
467
  }
468
469
  public function db_num_rows(&$result) {
470
    return $this->driver->mysql_num_rows($result);
471
  }
472
473
  public function db_affected_rows() {
474
    return $this->driver->mysql_affected_rows();
475
  }
476
477
  public function db_get_client_info() {
478
    return $this->driver->mysql_get_client_info();
479
  }
480
481
  public function db_get_server_info() {
482
    return $this->driver->mysql_get_server_info();
483
  }
484
485
  public function db_get_host_info() {
486
    return $this->driver->mysql_get_host_info();
487
  }
488
489
  public function db_get_server_stat() {
490
    return $this->driver->mysql_stat();
491
  }
492
493
}
494