Completed
Push — work-fleets ( 60e3d3...5fa106 )
by SuperNova.WS
06:18
created

classSupernova::cache_clear_all()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 8
ccs 0
cts 7
cp 0
crap 6
rs 9.4285
c 2
b 0
f 0
1
<?php
2
3
use Vector\Vector;
4
5
class classSupernova {
6
  /**
7
   * ex $sn_mvc
8
   *
9
   * @var array
10
   */
11
  public static $sn_mvc = array();
12
13
  /**
14
   * ex $functions
15
   *
16
   * @var array
17
   */
18
  public static $functions = array();
19
20
  /**
21
   * @var array[] $design
22
   */
23
  public static $design = array(
24
    'bbcodes' => array(),
25
    'smiles'  => array(),
26
  );
27
28
  /**
29
   * Основная БД для доступа к данным
30
   *
31
   * @var db_mysql $db
32
   */
33
  public static $db;
34
  public static $db_name = '';
35
36
  /**
37
   * Настройки из файла конфигурации
38
   *
39
   * @var string
40
   */
41
  public static $cache_prefix = '';
42
43
  public static $sn_secret_word = '';
44
45
  /**
46
   * Конфигурация игры
47
   *
48
   * @var classConfig $config
49
   */
50
  public static $config;
51
52
53
  /**
54
   * Кэш игры
55
   *
56
   * @var classCache $cache
57
   */
58
  public static $cache;
59
60
61
  /**
62
   * @var core_auth $auth
63
   */
64
  public static $auth = null;
65
66
67
  public static $db_in_transaction = false;
68
  public static $db_records_locked = false;
69
  public static $transaction_id = 0;
70
  public static $user = array();
71
  /**
72
   * @var userOptions
73
   */
74
  public static $user_options;
75
76
  /**
77
   * @var debug $debug
78
   */
79
  public static $debug = null;
80
81
  public static $options = array();
82
83
  public static $delayed_changset = array(); // Накопительный массив изменений
84
85
  // Кэш индексов - ключ MD5-строка от суммы ключевых строк через | - менять | на что-то другое перед поиском и назад - после поиска
86
  // Так же в индексах могут быть двойные вхождения - например, названия планет да и вообще
87
  // Придумать спецсимвол для NULL
88
89
  /*
90
  TODO Кэш:
91
  1. Всегда дешевле использовать процессор, чем локальную память
92
  2. Всегда дешевле использовать локальную память, чем общую память всех процессов
93
  3. Всегда дешевле использовать общую память всех процессов, чем обращаться к БД
94
95
  Кэш - многоуровневый: локальная память-общая память-БД
96
  БД может быть сверхкэширующей - см. HyperNova. Это реализуется на уровне СН-драйвера БД
97
  Предусмотреть вариант, когда уровни кэширования совпадают, например когда нет xcache и используется общая память
98
  */
99
100
  // TODO Автоматически заполнять эту таблицу. В случае кэша в памяти - делать show table при обращении к таблице
101
  public static $location_info = array(
102
    LOC_USER => array(
103
      P_TABLE_NAME => 'users',
104
      P_ID         => 'id',
105
      P_OWNER_INFO => array(),
106
    ),
107
108
    LOC_PLANET => array(
109
      P_TABLE_NAME => 'planets',
110
      P_ID         => 'id',
111
      P_OWNER_INFO => array(
112
        LOC_USER => array(
113
          P_LOCATION    => LOC_USER,
114
          P_OWNER_FIELD => 'id_owner',
115
        ),
116
      ),
117
    ),
118
119
    LOC_UNIT => array(
120
      P_TABLE_NAME => 'unit',
121
      P_ID         => 'unit_id',
122
      P_OWNER_INFO => array(
123
        LOC_USER => array(
124
          P_LOCATION    => LOC_USER,
125
          P_OWNER_FIELD => 'unit_player_id',
126
        ),
127
      ),
128
    ),
129
130
    LOC_QUE => array(
131
      P_TABLE_NAME => 'que',
132
      P_ID         => 'que_id',
133
      P_OWNER_INFO => array(
134
        array(
135
          P_LOCATION    => LOC_USER,
136
          P_OWNER_FIELD => 'que_player_id',
137
        ),
138
139
        array(
140
          P_LOCATION    => LOC_PLANET,
141
          P_OWNER_FIELD => 'que_planet_id_origin',
142
        ),
143
144
        array(
145
          P_LOCATION    => LOC_PLANET,
146
          P_OWNER_FIELD => 'que_planet_id',
147
        ),
148
      ),
149
    ),
150
151
    LOC_FLEET => array(
152
      P_TABLE_NAME => 'fleets',
153
      P_ID         => 'fleet_id',
154
      P_OWNER_INFO => array(
155
        array(
156
          P_LOCATION    => LOC_USER,
157
          P_OWNER_FIELD => 'fleet_owner',
158
        ),
159
160
        array(
161
          P_LOCATION    => LOC_USER,
162
          P_OWNER_FIELD => 'fleet_target_owner',
163
        ),
164
165
        array(
166
          P_LOCATION    => LOC_PLANET,
167
          P_OWNER_FIELD => 'fleet_start_planet_id',
168
        ),
169
170
        array(
171
          P_LOCATION    => LOC_PLANET,
172
          P_OWNER_FIELD => 'fleet_end_planet_id',
173
        ),
174
      ),
175
    ),
176
  );
177
178
  /**
179
   * @param $db db_mysql
180
   */
181
  public static function init_main_db($db) {
182
    self::$db = $db;
183
    self::$db->sn_db_connect();
184
  }
185
186
187
  public static function log_file($message, $spaces = 0) {
188
    if (self::$debug) {
189
      self::$debug->log_file($message, $spaces);
190
    }
191
  }
192
193
  public static function debug_set_handler($debug) {
194
    self::$debug = $debug;
195
  }
196
197
198
  // TODO Вынести в отдельный объект
199
  /**
200
   * Эта функция проверяет статус транзакции
201
   *
202
   * Это - низкоуровневая функция. В нормальном состоянии движка её сообщения никогда не будут видны
203
   *
204
   * @param null|true|false $status Должна ли быть запущена транзакция в момент проверки
205
   *   <p>null - транзакция НЕ должна быть запущена</p>
206
   *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
207
   *   <p>false - всё равно - для совместимости с $for_update</p>
208
   *
209
   * @return bool Текущий статус транзакции
210
   */
211
  public static function db_transaction_check($status = null) {
212
    $error_msg = false;
213
    if ($status && !static::$db_in_transaction) {
214
      $error_msg = 'No transaction started for current operation';
215
    } elseif ($status === null && static::$db_in_transaction) {
216
      $error_msg = 'Transaction is already started';
217
    }
218
219
    if (!empty($error_msg)) {
220
      // TODO - Убрать позже
221
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_transaction_check() - ' . $error_msg . '</h1>');
222
      $backtrace = debug_backtrace();
223
      array_shift($backtrace);
224
      pdump($backtrace);
225
      die($error_msg);
226
    }
227
228
    return static::$db_in_transaction;
229
  }
230
231
  public static function db_transaction_start($level = '') {
232
    static::db_transaction_check(null);
233
234
    $level ? doquery('SET TRANSACTION ISOLATION LEVEL ' . $level) : false;
235
236
    static::$transaction_id++;
237
    doquery('START TRANSACTION');
238
239
    if (classSupernova::$config->db_manual_lock_enabled) {
240
      classSupernova::$config->db_loadItem('var_db_manually_locked');
241
      classSupernova::$config->db_saveItem('var_db_manually_locked', SN_TIME_SQL);
242
    }
243
244
    static::$db_in_transaction = true;
245
    SnCache::locatorReset();
246
    SnCache::queriesReset();
247
248
    return static::$transaction_id;
249
  }
250
251
  public static function db_transaction_commit() {
252
    static::db_transaction_check(true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a null|object<true>|false.

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...
253
254
    if (!empty(static::$delayed_changset)) {
255
      static::db_changeset_apply(static::$delayed_changset, true);
256
    }
257
    doquery('COMMIT');
258
259
    return static::db_transaction_clear();
260
  }
261
262
  public static function db_transaction_rollback() {
263
    // static::db_transaction_check(true); // TODO - вообще-то тут тоже надо проверять есть ли транзакция
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...
264
265
    if (!empty(static::$delayed_changset)) {
266
//      static::db_changeset_revert();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
267
      // TODO Для этапа 1 - достаточно чистить только те таблицы, что были затронуты
268
      // Для этапа 2 - чистить только записи
269
      // Для этапа 3 - возвращать всё
270
      SnCache::cache_clear_all(true);
271
    }
272
    doquery('ROLLBACK');
273
274
    return static::db_transaction_clear();
275
  }
276
277
  protected static function db_transaction_clear() {
278
    static::$delayed_changset = array();
279
    SnCache::cache_lock_unset_all();
280
281
    static::$db_in_transaction = false;
282
    static::$db_records_locked = false;
283
    static::$transaction_id++;
284
285
    return static::$transaction_id;
286
  }
287
288
  /**
289
   * Блокирует указанные таблицу/список таблиц
290
   *
291
   * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
292
   * <p>string - название таблицы для блокировки</p>
293
   * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p>
294
   */
295
  public static function db_lock_tables($tables) {
296
    $tables = is_array($tables) ? $tables : array($tables => '');
297
    foreach ($tables as $table_name => $condition) {
298
      self::$db->doquery("SELECT 1 FROM {{{$table_name}}}" . ($condition ? ' WHERE ' . $condition : ''));
299
    }
300
  }
301
302
  /**
303
   * @param      $query
304
   * @param bool $fetch
305
   * @param bool $skip_lock
306
   *
307
   * @return array|bool|mysqli_result|null
308
   */
309
  public static function db_query($query, $fetch = false, $skip_lock = false) {
310
    $select = strpos(strtoupper($query), 'SELECT') !== false;
311
312
    $query .= $select && $fetch ? ' LIMIT 1' : '';
313
    $query .= $select && !$skip_lock && static::db_transaction_check(false) ? ' FOR UPDATE' : '';
314
315
    $result = self::$db->doquery($query, $fetch);
0 ignored issues
show
Documentation introduced by
$fetch is of type boolean, but the function expects a string.

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...
316
317
    return $result;
318
  }
319
320
  /**
321
   * Возвращает информацию о записи по её ID
322
   *
323
   * @param int       $location_type
324
   * @param int|array $record_id_unsafe
325
   *    <p>int - ID записи</p>
326
   *    <p>array - запись пользователя с установленным полем P_ID</p>
327
   * @param bool      $for_update @deprecated
328
   * @param string    $fields @deprecated список полей или '*'/'' для всех полей
329
   * @param bool      $skip_lock Указывает на то, что не нужно блокировать запись //TODO и не нужно сохранять в кэше
330
   *
331
   * @return array|false
332
   *    <p>false - Нет записи с указанным ID</p>
333
   *    <p>array - запись</p>
334
   */
335
  public static function db_get_record_by_id($location_type, $record_id_unsafe, $for_update = false, $fields = '*', $skip_lock = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $for_update 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...
Unused Code introduced by
The parameter $fields 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...
Unused Code introduced by
The parameter $skip_lock 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...
336
    $id_field = static::$location_info[$location_type][P_ID];
337
    $record_id_safe = idval(is_array($record_id_unsafe) && isset($record_id_unsafe[$id_field]) ? $record_id_unsafe[$id_field] : $record_id_unsafe);
338
339
    return static::db_get_record_list($location_type, "`{$id_field}` = {$record_id_safe}", true, false);
340
  }
341
342
  public static function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) {
343
    if (SnCache::isQueryCacheByLocationAndFilterEmpty($location_type, $filter)) {
344
      SnCache::queryCacheResetByLocationAndFilter($location_type, $filter);
345
346
      $location_info = &static::$location_info[$location_type];
347
      $id_field = $location_info[P_ID];
348
349
      if (static::db_transaction_check(false)) {
350
        // Проходим по всем родителям данной записи
351
        foreach ($location_info[P_OWNER_INFO] as $owner_data) {
352
          $owner_location_type = $owner_data[P_LOCATION];
353
          $parent_id_list = array();
354
          // Выбираем родителей данного типа и соответствующие ИД текущего типа
355
          $query = static::db_query(
356
            "SELECT
357
              distinct({{{$location_info[P_TABLE_NAME]}}}.{$owner_data[P_OWNER_FIELD]}) AS parent_id
358
            FROM {{{$location_info[P_TABLE_NAME]}}}" .
359
            ($filter ? ' WHERE ' . $filter : '') .
360
            ($fetch ? ' LIMIT 1' : ''), false, true);
361
362
          while ($row = db_fetch($query)) {
363
            // Исключаем из списка родительских ИД уже заблокированные записи
364
            if (!SnCache::cache_lock_get($owner_location_type, $row['parent_id'])) {
365
              $parent_id_list[$row['parent_id']] = $row['parent_id'];
366
            }
367
          }
368
          // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
369
          if ($indexes_str = implode(',', $parent_id_list)) {
370
            $parent_id_field = static::$location_info[$owner_location_type][P_ID];
371
            static::db_get_record_list($owner_location_type,
372
              $parent_id_field . (count($parent_id_list) > 1 ? " IN ({$indexes_str})" : " = {$indexes_str}"), $fetch, true);
373
          }
374
        }
375
      }
376
377
      $query = static::db_query(
378
        "SELECT * FROM {{{$location_info[P_TABLE_NAME]}}}" .
379
        (($filter = trim($filter)) ? " WHERE {$filter}" : '')
380
      );
381
      while ($row = db_fetch($query)) {
382
        // Caching record in row cache
383
        SnCache::cache_set($location_type, $row);
384
        // Making ref to cached record in query cache
385
        SnCache::queryCacheSetByFilter($location_type, $filter, $row[$id_field]);
386
      }
387
    }
388
389
    if ($no_return) {
390
      return true;
391
    } else {
392
      $result = false;
393
//      $queryCache = SnCache::getQueriesByLocationAndFilter($location_type, $filter);
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
394
//      if (is_array($queryCache)) {
395
//        foreach ($queryCache as $key => $value) {
396
      foreach (SnCache::getQueriesByLocationAndFilter($location_type, $filter) as $key => $value) {
397
        $result[$key] = $value;
398
        if ($fetch) {
399
          break;
400
        }
401
      }
402
403
//      }
404
405
      return $fetch ? (is_array($result) ? reset($result) : false) : $result;
406
    }
407
  }
408
409
  /**
410
   * @param int    $location_type
411
   * @param int    $record_id
412
   * @param string $set - SQL SET structure
413
   *
414
   * @return array|bool|mysqli_result|null
415
   */
416
  public static function db_upd_record_by_id($location_type, $record_id, $set) {
417
    if (!($record_id = idval($record_id)) || !($set = trim($set))) {
418
      return false;
419
    }
420
421
    $id_field = static::$location_info[$location_type][P_ID];
422
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
423
    if ($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
424
    {
425
      if (static::$db->db_affected_rows()) {
426
        // Обновляем данные только если ряд был затронут
427
        // TODO - переделать под работу со структурированными $set
428
429
        // Тут именно так, а не cache_unset - что бы в кэшах автоматически обновилась запись. Будет нужно на будущее
430
        //static::$data[$location_type][$record_id] = null;
0 ignored issues
show
Unused Code Comprehensibility introduced by
79% 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...
431
        SnCache::cacheUnsetElement($location_type, $record_id);
432
        // Вытаскиваем обновленную запись
433
        static::db_get_record_by_id($location_type, $record_id);
434
        SnCache::cache_clear($location_type, false); // Мягкий сброс - только $queries
435
      }
436
    }
437
438
    return $result;
439
  }
440
441
  public static function db_upd_record_list($location_type, $condition, $set) {
442
    if (!($set = trim($set))) {
443
      return false;
444
    }
445
446
    $condition = trim($condition);
447
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
448
449
    if ($result = static::db_query("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
450
451
      if (static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
452
        // Поскольку нам неизвестно, что и как обновилось - сбрасываем кэш этого типа полностью
453
        // TODO - когда будет структурированный $condition и $set - перепаковывать данные
454
        SnCache::cache_clear($location_type, true);
455
      }
456
    }
457
458
    return $result;
459
  }
460
461
  /**
462
   * @param int    $location_type
463
   * @param string $set
464
   *
465
   * @return array|bool|false|mysqli_result|null
466
   */
467
  public static function db_ins_record($location_type, $set) {
468
    $set = trim($set);
469
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
470 View Code Duplication
    if ($result = static::db_query("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
471
      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
472
      {
473
        $record_id = db_insert_id();
474
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
475
        $result = static::db_get_record_by_id($location_type, $record_id);
476
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
477
        // TODO - когда будет поддержка изменения индексов и локаций - можно будет вызывать её
478
        SnCache::cache_clear($location_type, false); // Мягкий сброс - только $queries
479
      }
480
    }
481
482
    return $result;
483
  }
484
485
  public static function db_ins_field_set($location_type, $field_set, $serialize = false) {
486
    // TODO multiinsert
487
    !sn_db_field_set_is_safe($field_set) ? $field_set = sn_db_field_set_make_safe($field_set, $serialize) : false;
488
    sn_db_field_set_safe_flag_clear($field_set);
489
    $values = implode(',', $field_set);
490
    $fields = implode(',', array_keys($field_set));
491
492
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
493 View Code Duplication
    if ($result = static::db_query("INSERT INTO `{{{$table_name}}}` ({$fields}) VALUES ({$values});")) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
494
      if (static::$db->db_affected_rows()) {
495
        // Обновляем данные только если ряд был затронут
496
        $record_id = db_insert_id();
497
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
498
        $result = static::db_get_record_by_id($location_type, $record_id);
499
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
500
        // TODO - когда будет поддержка изменения индексов и локаций - можно будет вызывать её
501
        SnCache::cache_clear($location_type, false); // Мягкий сброс - только $queries
502
      }
503
    }
504
505
    return $result;
506
  }
507
508
  public static function db_del_record_by_id($location_type, $safe_record_id) {
509
    if (!($safe_record_id = idval($safe_record_id))) {
510
      return false;
511
    }
512
513
    $id_field = static::$location_info[$location_type][P_ID];
514
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
515
    if ($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}")) {
516
      // Обновляем данные только если ряд был затронут
517
      if (static::$db->db_affected_rows()) {
518
        SnCache::cache_unset($location_type, $safe_record_id);
519
      }
520
    }
521
522
    return $result;
523
  }
524
525
  public static function db_del_record_list($location_type, $condition) {
526
    if (!($condition = trim($condition))) {
527
      return false;
528
    }
529
530
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
531
532
    if ($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE {$condition}")) {
533
      // Обновляем данные только если ряд был затронут
534
      if (static::$db->db_affected_rows()) {
535
        // Обнуление кэша, потому что непонятно, что поменялось
536
        // TODO - когда будет структурированный $condition можно будет делать только cache_unset по нужным записям
537
        SnCache::cache_clear($location_type);
538
      }
539
    }
540
541
    return $result;
542
  }
543
544
545
546
  // Работа с пользователями
547
  /**
548
   * Возвращает информацию о пользователе по его ID
549
   *
550
   * @param int|array $user_id_unsafe
551
   *    <p>int - ID пользователя</p>
552
   *    <p>array - запись пользователя с установленным полем ['id']</p>
553
   * @param bool      $for_update @deprecated
554
   * @param string    $fields @deprecated список полей или '*'/'' для всех полей
555
   * @param null      $player
556
   * @param bool|null $player Признак выбора записи пользователь типа "игрок"
557
   *    <p>null - Можно выбрать запись любого типа</p>
558
   *    <p>true - Выбирается только запись типа "игрок"</p>
559
   *    <p>false - Выбирается только запись типа "альянс"</p>
560
   *
561
   * @return array|false
562
   *    <p>false - Нет записи с указанным ID и $player</p>
563
   *    <p>array - запись типа $user</p>
564
   */
565
  public static function db_get_user_by_id($user_id_unsafe, $for_update = false, $fields = '*', $player = null) {
566
    $user = static::db_get_record_by_id(LOC_USER, $user_id_unsafe, $for_update, $fields);
567
568
    return (is_array($user) &&
569
      (
570
        $player === null
571
        ||
572
        ($player === true && !$user['user_as_ally'])
573
        ||
574
        ($player === false && $user['user_as_ally'])
575
      )) ? $user : false;
576
  }
577
578
  public static function db_get_user_by_username($username_unsafe, $for_update = false, $fields = '*', $player = null, $like = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $for_update 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...
Unused Code introduced by
The parameter $fields 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...
579
    // TODO Проверить, кстати - а везде ли нужно выбирать юзеров или где-то все-таки ищутся Альянсы ?
580
    if (!($username_unsafe = trim($username_unsafe))) {
581
      return false;
582
    }
583
584
    $user = null;
585
    if (SnCache::isArrayLocation(LOC_USER)) {
586
      foreach (SnCache::getData(LOC_USER) as $user_id => $user_data) {
587
        if (is_array($user_data) && isset($user_data['username'])) {
588
          // проверяем поле
589
          // TODO Возможно есть смысл всегда искать по strtolower - но может игрок захочет переименоваться с другим регистром? Проверить!
590
          if ((!$like && $user_data['username'] == $username_unsafe) || ($like && strtolower($user_data['username']) == strtolower($username_unsafe))) {
591
            // $user_as_ally = intval($user_data['user_as_ally']);
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...
592
            $user_as_ally = idval($user_data['user_as_ally']);
593
            if ($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally)) {
594
              $user = $user_data;
595
              break;
596
            }
597
          }
598
        }
599
      }
600
    }
601
602
    if ($user === null) {
603
      // Вытаскиваем запись
604
      $username_safe = db_escape($like ? strtolower($username_unsafe) : $username_unsafe); // тут на самом деле strtolower() лишняя, но пусть будет
605
606
      // TODO переписать
607
      $user = self::$db->selectRow(
608
        DBStaticUser::buildSelect()
609
          ->field('*')
610
          ->where(array("`username` " . ($like ? 'LIKE' : '=') . " '{$username_safe}'"))
611
          ->setFetchOne()
612
      );
613
614
      if (empty($user)) {
615
        $user = null;
616
      }
617
618
//      $user = static::db_query(
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% 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...
619
//        "SELECT * FROM {{users}} WHERE `username` " . ($like ? 'LIKE' : '=') . " '{$username_safe}'"
620
//        , true);
621
      SnCache::cache_set(LOC_USER, $user); // В кэш-юзер так же заполнять индексы
622
    }
623
624
    return $user;
625
  }
626
627
  // UNUSED
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
628
//  public static function db_get_user_by_email($email_unsafe, $use_both = false, $for_update = false, $fields = '*') {
629
//    if (!($email_unsafe = strtolower(trim($email_unsafe)))) {
630
//      return false;
631
//    }
632
//
633
//    $user = null;
634
//    // TODO переделать на индексы
635
//    if (is_array(static::$data[LOC_USER])) {
636
//      foreach (static::$data[LOC_USER] as $user_id => $user_data) {
637
//        if (is_array($user_data) && isset($user_data['email_2'])) {
638
//          // проверяем поле
639
//          if (strtolower($user_data['email_2']) == $email_unsafe || ($use_both && strtolower($user_data['email']) == $email_unsafe)) {
640
//            $user = $user_data;
641
//            break;
642
//          }
643
//        }
644
//      }
645
//    }
646
//
647
//    if ($user === null) {
648
//      // Вытаскиваем запись
649
//      $email_safe = db_escape($email_unsafe);
650
//      $user = static::db_query(
651
//        "SELECT * FROM {{users}} WHERE LOWER(`email_2`) = '{$email_safe}'" .
652
//        ($use_both ? " OR LOWER(`email`) = '{$email_safe}'" : '')
653
//        , true);
654
//
655
//      static::cache_set(LOC_USER, $user); // В кэш-юзер так же заполнять индексы
656
//    }
657
//
658
//    return $user;
659
//  }
660
661
  public static function db_get_user_by_where($where_safe, $for_update = false, $fields = '*') {
0 ignored issues
show
Unused Code introduced by
The parameter $for_update 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...
Unused Code introduced by
The parameter $fields 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...
662
    $user = null;
663
    // TODO переделать на индексы
664
665
    if ($user === null && !empty($where_safe)) {
666
      // Вытаскиваем запись
667
      $user = static::db_query("SELECT * FROM {{users}} WHERE {$where_safe}", true);
668
669
      SnCache::cache_set(LOC_USER, $user); // В кэш-юзер так же заполнять индексы
670
    }
671
672
    return $user;
673
  }
674
675
676 View Code Duplication
  public static function db_unit_time_restrictions($date = SN_TIME_NOW) {
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...
677
    $date = is_numeric($date) ? "FROM_UNIXTIME({$date})" : "'{$date}'";
678
679
    return
680
      "(unit_time_start IS NULL OR unit_time_start <= {$date}) AND
681
    (unit_time_finish IS NULL OR unit_time_finish = '1970-01-01 03:00:00' OR unit_time_finish >= {$date})";
682
  }
683
684
  public static function db_get_unit_by_id($unit_id, $for_update = false, $fields = '*') {
685
    // TODO запихивать в $data[LOC_LOCATION][$location_type][$location_id]
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
686
    $unit = static::db_get_record_by_id(LOC_UNIT, $unit_id, $for_update, $fields);
687
//    if (is_array($unit)) {
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...
688
//      // static::$locator[LOC_UNIT][$unit['unit_location_type']][$unit['unit_location_id']][$unit['unit_snid']] = &SnCache::$data[LOC_UNIT][$unit_id];
689
//      SnCache::$locator[LOC_UNIT][$unit['unit_location_type']][$unit['unit_location_id']][$unit['unit_snid']] = &SnCache::getDataRefByLocationAndId(LOC_UNIT, $unit_id);
690
//    }
691
    SnCache::setUnitLocator($unit, $unit_id);
692
693
    return $unit;
694
  }
695
696
  /**
697
   * @param int $user_id
698
   * @param int $location_type
699
   * @param int $location_id
700
   *
701
   * @return array|bool
702
   */
703
  public static function db_get_unit_list_by_location($user_id = 0, $location_type, $location_id) {
0 ignored issues
show
Unused Code introduced by
The parameter $user_id 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...
704
    if (!($location_type = idval($location_type)) || !($location_id = idval($location_id))) {
705
      return false;
706
    }
707
708
    if (SnCache::isUnitLocatorNotSet($location_type, $location_id)) {
709
      $got_data = static::db_get_record_list(LOC_UNIT, "unit_location_type = {$location_type} AND unit_location_id = {$location_id} AND " . static::db_unit_time_restrictions());
710
      if (!empty($got_data) && is_array($got_data)) {
711
        foreach ($got_data as $unit_id => $unit_data) {
712
          SnCache::setUnitLocatorByLocationAndIDs($location_type, $location_id, $unit_data);
713
        }
714
      }
715
    }
716
717
    $result = false;
718
    foreach (SnCache::getUnitLocatorByFullLocation($location_type, $location_id) as $key => $value) {
719
      $result[$key] = $value;
720
    }
721
722
    return $result;
723
  }
724
725
  public static function db_get_unit_by_location($user_id = 0, $location_type, $location_id, $unit_snid = 0, $for_update = false, $fields = '*') {
0 ignored issues
show
Unused Code introduced by
The parameter $for_update 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...
Unused Code introduced by
The parameter $fields 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...
726
    static::db_get_unit_list_by_location($user_id, $location_type, $location_id);
727
728
    return SnCache::getUnitLocator($location_type, $location_id, $unit_snid);
729
  }
730
731
732
  /*
733
   * С $for_update === true эта функция должна вызываться только из транзакции! Все соответствующие записи в users и planets должны быть уже блокированы!
734
   *
735
   * $que_type
736
   *   !$que_type - все очереди
737
   *   QUE_XXXXXX - конкретная очередь по планете
738
   * $user_id - ID пользователя
739
   * $planet_id
740
   *   $que_type == QUE_RESEARCH - игнорируется
741
   *   null - обработка очередей планет не производится
742
   *   false/0 - обрабатываются очереди всех планет по $user_id
743
   *   (integer) - обрабатываются локальные очереди для планеты. Нужно, например, в обработчике флотов
744
   *   иначе - $que_type для указанной планеты
745
   * $for_update - true == нужно блокировать записи
746
   *
747
   * TODO Работа при !$user_id
748
   * TODO Переформатировать вывод данных, что бы можно было возвращать данные по всем планетам и юзерам в одном запросе: добавить подмассивы 'que', 'planets', 'players'
749
   *
750
   */
751
  public static function db_que_list_by_type_location($user_id, $planet_id = null, $que_type = false, $for_update = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $for_update 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...
752
    if (!$user_id) {
753
      pdump(debug_backtrace());
754
      die('No user_id for que_get_que()');
755
    }
756
757
    $ques = array();
758
759
    $query = array();
760
761
    if ($user_id = idval($user_id)) {
762
      $query[] = "`que_player_id` = {$user_id}";
763
    }
764
765
    if ($que_type == QUE_RESEARCH || $planet_id === null) {
766
      $query[] = "`que_planet_id` IS NULL";
767
    } elseif ($planet_id) {
768
      $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
769
    }
770
    if ($que_type) {
771
      $query[] = "`que_type` = {$que_type}";
772
    }
773
774
    $ques['items'] = static::db_get_record_list(LOC_QUE, implode(' AND ', $query));
775
776
    return que_recalculate($ques);
777
  }
778
779
780 View Code Duplication
  public static function db_changeset_prepare_unit($unit_id, $unit_value, $user, $planet_id = null) {
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...
781
    if (!is_array($user)) {
782
      // TODO - remove later
783
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER is not ARRAY</h1>');
784
      pdump(debug_backtrace());
785
      die('USER is not ARRAY');
786
    }
787
    if (!isset($user['id']) || !$user['id']) {
788
      // TODO - remove later
789
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER[id] пустой</h1>');
790
      pdump($user);
791
      pdump(debug_backtrace());
792
      die('USER[id] пустой');
793
    }
794
    $planet_id = is_array($planet_id) && isset($planet_id['id']) ? $planet_id['id'] : $planet_id;
795
796
    $unit_location = sys_get_unit_location($user, array(), $unit_id);
797
    $location_id = $unit_location == LOC_USER ? $user['id'] : $planet_id;
798
    $location_id = $location_id ? $location_id : 'NULL';
799
800
    $temp = DBStaticUnit::db_unit_by_location($user['id'], $unit_location, $location_id, $unit_id, true, 'unit_id');
801
    if ($temp['unit_id']) {
802
      $db_changeset = array(
803
        'action'  => SQL_OP_UPDATE,
804
        P_VERSION => 1,
805
        'where'   => array(
806
          "unit_id" => $temp['unit_id'],
807
        ),
808
        'fields'  => array(
809
          'unit_level' => array(
810
            'delta' => $unit_value
811
          ),
812
        ),
813
      );
814
    } else {
815
      $db_changeset = array(
816
        'action' => SQL_OP_INSERT,
817
        'fields' => array(
818
          'unit_player_id'     => array(
819
            'set' => $user['id'],
820
          ),
821
          'unit_location_type' => array(
822
            'set' => $unit_location,
823
          ),
824
          'unit_location_id'   => array(
825
            'set' => $unit_location == LOC_USER ? $user['id'] : $planet_id,
826
          ),
827
          'unit_type'          => array(
828
            'set' => get_unit_param($unit_id, P_UNIT_TYPE),
829
          ),
830
          'unit_snid'          => array(
831
            'set' => $unit_id,
832
          ),
833
          'unit_level'         => array(
834
            'set' => $unit_value,
835
          ),
836
        ),
837
      );
838
    }
839
840
    return $db_changeset;
841
  }
842
843
844
  public function db_changeset_delay($table_name, $table_data) {
845
    // TODO Применять ченджсет к записям
846
    static::$delayed_changset[$table_name] = is_array(static::$delayed_changset[$table_name]) ? static::$delayed_changset[$table_name] : array();
847
    // TODO - На самом деле дурацкая оптимизация, если честно - может быть идентичные записи с идентичными дельтами - и привет. Но не должны, конечно
848
    static::$delayed_changset[$table_name] = array_merge(static::$delayed_changset[$table_name], $table_data);
849
  }
850
851
  public function db_changeset_condition_compile(&$conditions, &$table_name = '') {
852
    if (!$conditions[P_LOCATION] || $conditions[P_LOCATION] == LOC_NONE) {
853
      $conditions[P_LOCATION] = LOC_NONE;
854
      switch ($table_name) {
855
        case 'users':
856
        case LOC_USER:
857
          $conditions[P_TABLE_NAME] = $table_name = 'users';
858
          $conditions[P_LOCATION] = LOC_USER;
859
        break;
860
861
        case 'planets':
862
        case LOC_PLANET:
863
          $conditions[P_TABLE_NAME] = $table_name = 'planets';
864
          $conditions[P_LOCATION] = LOC_PLANET;
865
        break;
866
867
        case 'unit':
868
        case LOC_UNIT:
869
          $conditions[P_TABLE_NAME] = $table_name = 'unit';
870
          $conditions[P_LOCATION] = LOC_UNIT;
871
        break;
872
      }
873
    }
874
875
    $conditions[P_FIELDS_STR] = '';
876
    if ($conditions['fields']) {
877
      $fields = array();
878 View Code Duplication
      foreach ($conditions['fields'] as $field_name => $field_data) {
0 ignored issues
show
Bug introduced by
The expression $conditions['fields'] of type string is not traversable.
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
879
        $condition = "`{$field_name}` = ";
880
        $value = '';
881
        if ($field_data['delta']) {
882
          $value = "`{$field_name}`" . ($field_data['delta'] >= 0 ? '+' : '') . $field_data['delta'];
883
        } elseif ($field_data['set']) {
884
          $value = (is_string($field_data['set']) ? "'{$field_data['set']}'" : $field_data['set']);
885
        }
886
887
        if ($value) {
888
          $fields[] = $condition . $value;
889
        }
890
      }
891
      $conditions[P_FIELDS_STR] = implode(',', $fields);
892
    }
893
894
    $conditions[P_WHERE_STR] = '';
895
    if (!empty($conditions['where'])) {
896
      if ($conditions[P_VERSION] == 1) {
897
        $the_conditions = array();
898
        foreach ($conditions['where'] as $field_id => $field_value) {
0 ignored issues
show
Bug introduced by
The expression $conditions['where'] of type string is not traversable.
Loading history...
899
          // Простое условие - $field_id = $field_value
900
          if (is_string($field_id)) {
901
            $field_value =
902
              $field_value === null ? 'NULL' :
903
                (is_string($field_value) ? "'" . db_escape($field_value) . "'" :
904
                  (is_bool($field_value) ? intval($field_value) : $field_value));
905
            $the_conditions[] = "`{$field_id}` = {$field_value}";
906
          } else {
907
            die('Неподдерживаемый тип условия');
908
          }
909
        }
910
      } else {
911
        $the_conditions = &$conditions['where'];
912
      }
913
      $conditions[P_WHERE_STR] = implode(' AND ', $the_conditions);
914
    }
915
916
    switch ($conditions['action']) {
917
      case SQL_OP_DELETE:
918
        $conditions[P_ACTION_STR] = ("DELETE FROM {{{$table_name}}}");
919
      break;
920
      case SQL_OP_UPDATE:
921
        $conditions[P_ACTION_STR] = ("UPDATE {{{$table_name}}} SET");
922
      break;
923
      case SQL_OP_INSERT:
924
        $conditions[P_ACTION_STR] = ("INSERT INTO {{{$table_name}}} SET");
925
      break;
926
      // case SQL_OP_REPLACE: $result = doquery("REPLACE INTO {{{$table_name}}} SET {$fields}") && $result; break;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
927
      default:
928
        die('Неподдерживаемая операция в classSupernova::db_changeset_condition_compile');
929
    }
930
931
    $conditions[P_QUERY_STR] = $conditions[P_ACTION_STR] . ' ' . $conditions[P_FIELDS_STR] . (' WHERE ' . $conditions[P_WHERE_STR]);
932
  }
933
934
  public static function db_changeset_apply($db_changeset, $flush_delayed = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $flush_delayed 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...
935
    $result = true;
936
    if (!is_array($db_changeset) || empty($db_changeset)) {
937
      return $result;
938
    }
939
940
    foreach ($db_changeset as $table_name => &$table_data) {
941
      // TODO - delayed changeset
942
      foreach ($table_data as $record_id => &$conditions) {
943
        static::db_changeset_condition_compile($conditions, $table_name);
944
945
        if ($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) {
946
          continue;
947
        }
948
        if ($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) {
949
          continue;
950
        } // Защита от случайного удаления всех данных в таблице
951
952
        if ($conditions[P_LOCATION] != LOC_NONE) {
953
          switch ($conditions['action']) {
954
            case SQL_OP_DELETE:
955
              $result = self::db_del_record_list($conditions[P_LOCATION], $conditions[P_WHERE_STR]) && $result;
956
            break;
957
            case SQL_OP_UPDATE:
958
              $result = self::db_upd_record_list($conditions[P_LOCATION], $conditions[P_WHERE_STR], $conditions[P_FIELDS_STR]) && $result;
959
            break;
960
            case SQL_OP_INSERT:
961
              $result = self::db_ins_record($conditions[P_LOCATION], $conditions[P_FIELDS_STR]) && $result;
962
            break;
963
            default:
964
              die('Неподдерживаемая операция в classSupernova::db_changeset_apply');
965
            // case SQL_OP_REPLACE: $result = $result && doquery("REPLACE INTO {{{$table_name}}} SET {$fields}"); break;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
966
          }
967
        } else {
968
          $result = doquery($conditions[P_QUERY_STR]) && $result;
969
        }
970
      }
971
    }
972
973
    return $result;
974
  }
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
  // que_process не всегда должна работать в режиме прямой работы с БД !! Она может работать и в режиме эмуляции
1011
  // !!!!!!!! После que_get брать не [0] элемент, а first() - тогда можно в индекс элемента засовывать que_id из таблицы
1012
1013
1014
  // Это для поиска по кэшу
1015
  protected static function db_get_record_by_field($location_type) {
0 ignored issues
show
Unused Code introduced by
The parameter $location_type 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...
1016
  }
1017
1018
  // Для модулей - регистрация юнитов
1019
  public static function unit_register() {
1020
1021
  }
1022
1023
1024
  public static function init_0_prepare() {
1025
    // Отключаем magic_quotes
1026
    ini_get('magic_quotes_sybase') ? die('SN is incompatible with \'magic_quotes_sybase\' turned on. Disable it in php.ini or .htaccess...') : false;
1027
    if (@get_magic_quotes_gpc()) {
1028
      $gpcr = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
1029
      array_walk_recursive($gpcr, function (&$value, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key 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...
1030
        $value = stripslashes($value);
1031
      });
1032
    }
1033
    if (function_exists('set_magic_quotes_runtime')) {
1034
      @set_magic_quotes_runtime(0);
1035
      @ini_set('magic_quotes_runtime', 0);
1036
      @ini_set('magic_quotes_sybase', 0);
1037
    }
1038
  }
1039
1040
  public static function init_3_load_config_file() {
1041
    $dbsettings = array();
1042
1043
    require(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
1044
    self::$cache_prefix = !empty($dbsettings['cache_prefix']) ? $dbsettings['cache_prefix'] : $dbsettings['prefix'];
1045
    self::$db_name = $dbsettings['name'];
1046
    self::$sn_secret_word = $dbsettings['secretword'];
1047
    unset($dbsettings);
1048
  }
1049
1050
  public static function init_global_objects() {
1051
    self::$user_options = new userOptions(0);
1052
1053
    // Initializing global 'cacher' object
1054
    static::$cache = new classCache(classSupernova::$cache_prefix);
1055
    $sn_cache = static::$cache;
1056
    empty($sn_cache->tables) ? sys_refresh_tablelist() : false;
1057
    empty($sn_cache->tables) ? die('DB error - cannot find any table. Halting...') : false;
1058
1059
    // Initializing global "config" object
1060
    static::$config = new classConfig(classSupernova::$cache_prefix);
1061
1062
    // Initializing statics
1063
    Vector::_staticInit(static::$config);
1064
  }
1065
1066
  public static function init_debug_state() {
1067
    if ($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
1068
      define('BE_DEBUG', true);
1069
    }
1070
    // define('DEBUG_SQL_ONLINE', true); // Полный дамп запросов в рил-тайме. Подойдет любое значение
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
1071
    define('DEBUG_SQL_ERROR', true); // Выводить в сообщении об ошибке так же полный дамп запросов за сессию. Подойдет любое значение
1072
    define('DEBUG_SQL_COMMENT_LONG', true); // Добавлять SQL запрос длинные комментарии. Не зависим от всех остальных параметров. Подойдет любое значение
1073
    define('DEBUG_SQL_COMMENT', true); // Добавлять комментарии прямо в SQL запрос. Подойдет любое значение
1074
    // Включаем нужные настройки
1075
    defined('DEBUG_SQL_ONLINE') && !defined('DEBUG_SQL_ERROR') ? define('DEBUG_SQL_ERROR', true) : false;
1076
    defined('DEBUG_SQL_ERROR') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
1077
    defined('DEBUG_SQL_COMMENT_LONG') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
1078
1079
    if (defined('BE_DEBUG') || static::$config->debug) {
1080
      @define('BE_DEBUG', true);
1081
      @ini_set('display_errors', 1);
1082
      @error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
1083
    } else {
1084
      @define('BE_DEBUG', false);
1085
      @ini_set('display_errors', 0);
1086
    }
1087
1088
  }
1089
1090
  public static function checkReturnRef(&$ref1, &$ref2) {
1091
    if (isset($ref1['id'])) {
1092
      $ref1['id']++;
1093
      pdump($ref1['id']);
1094
      pdump($ref2['id']);
1095
      if ($ref2['id'] == $ref1['id']) {
1096
        pdump('ok');
1097
      } else {
1098
        pdie('failed');
1099
      }
1100
      $ref2['id']--;
1101
      if ($ref2['id'] == $ref1['id']) {
1102
        pdump('ok');
1103
      } else {
1104
        pdie('failed');
1105
      }
1106
    }
1107
1108
  }
1109
1110
}
1111