Completed
Push — work-fleets ( 069d1a...74a0d7 )
by SuperNova.WS
04:58
created

classSupernova::cache_set()   C

Complexity

Conditions 8
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
rs 6.6037
cc 8
eloc 13
nc 4
nop 5
1
<?php
2
3
class classSupernova {
4
  /**
5
   * ex $sn_mvc
6
   *
7
   * @var array
8
   */
9
  public static $sn_mvc = array();
10
11
  /**
12
   * ex $functions
13
   *
14
   * @var array
15
   */
16
  public static $functions = array();
17
18
  /**
19
   * @var array[] $design
20
   */
21
  public $design = array(
22
    'bbcodes' => array(),
23
    'smiles'  => array(),
24
  );
25
26
  /**
27
   * Основная БД для доступа к данным
28
   *
29
   * @var db_mysql $db
30
   */
31
  public static $db;
32
  public static $db_name = '';
33
34
  /**
35
   * Настройки из файла конфигурации
36
   *
37
   * @var string
38
   */
39
  public static $cache_prefix = '';
40
  // public static $db_prefix = '';
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...
41
  public static $sn_secret_word = '';
42
43
  /**
44
   * Конфигурация игры
45
   *
46
   * @var classConfig $config
47
   */
48
  public static $config;
49
50
51
  /**
52
   * Кэш игры
53
   *
54
   * @var classCache $cache
55
   */
56
  public static $cache;
57
58
59
  /**
60
   * @var core_auth $auth
61
   */
62
  public static $auth = null;
63
64
65
  public static $db_in_transaction = false;
66
  public static $transaction_id = 0;
67
  public static $user = array();
68
  /**
69
   * @var userOptions
70
   */
71
  public static $user_options;
72
73
  /**
74
   * @var debug $debug
75
   */
76
  public static $debug = null;
77
78
  public $options = array();
79
80
  /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
81
  // protected static $user = null;
82
  // protected static $planet = null;
83
  // protected static $ally = null;
84
  */
85
86
  public static $data = array(); // Кэш данных - юзера, планеты, юниты, очередь, альянсы итд
87
  public static $locks = array(); // Информация о блокировках
88
  public static $queries = array(); // Кэш запросов
89
90
  // Массив $locator - хранит отношения между записями для быстрого доступа по тип_записи:тип_локации:ид_локации:внутренний_ид_записи=>информация
91
  // Для LOC_UNIT внутренний ИД - это SNID, а информация - это ссылка на запись `unit`
92
  // Для LOC_QUE внутренний ИД - это тип очереди, а информация - массив ссылок на `que`
93
  public static $locator = array(); // Кэширует соответствия между расположением объектов - в частности юнитов и очередей
94
95
  public static $delayed_changset = array(); // Накопительный массив изменений
96
97
  // Кэш индексов - ключ MD5-строка от суммы ключевых строк через | - менять | на что-то другое перед поиском и назад - после поиска
98
  // Так же в индексах могут быть двойные вхождения - например, названия планет да и вообще
99
  // Придумать спецсимвол для NULL
100
  // protected static $indexes = array();
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
101
102
  /*
103
  TODO Кэш:
104
  1. Всегда дешевле использовать процессор, чем локальную память
105
  2. Всегда дешевле использовать локальную память, чем общую память всех процессов
106
  3. Всегда дешевле использовать общую память всех процессов, чем обращаться к БД
107
108
  Кэш - многоуровневый: локальная память-общая память-БД
109
  БД может быть сверхкэширующей - см. HyperNova. Это реализуется на уровне СН-драйвера БД
110
  Предусмотреть вариант, когда уровни кэширования совпадают, например когда нет xcache и используется общая память
111
  */
112
  //public static $cache; // Объект-кэшер - либо встроенная память, либо мемкэш с блокировками - находится внутри $db!!!!
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
113
  //public static $db; // Объект-БД - либок кэшер с блокировками, либо БД
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
114
115
  // protected static $info = array(); // Кэш информации - инфо о юнитах, инфо о группах итд
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...
116
117
  // TODO Автоматически заполнять эту таблицу. В случае кэша в памяти - делать show table при обращении к таблице
118
  public static $location_info = array(
119
    LOC_USER => array(
120
      P_TABLE_NAME => 'users',
121
      P_ID         => 'id',
122
      P_OWNER_INFO => array(),
123
    ),
124
125
    LOC_PLANET => array(
126
      P_TABLE_NAME => 'planets',
127
      P_ID         => 'id',
128
      P_OWNER_INFO => array(
129
        LOC_USER => array(
130
          P_LOCATION    => LOC_USER,
131
          P_OWNER_FIELD => 'id_owner',
132
        ),
133
      ),
134
    ),
135
136
    LOC_UNIT => array(
137
      P_TABLE_NAME => 'unit',
138
      P_ID         => 'unit_id',
139
      P_OWNER_INFO => array(
140
        LOC_USER => array(
141
          P_LOCATION    => LOC_USER,
142
          P_OWNER_FIELD => 'unit_player_id',
143
        ),
144
      ),
145
    ),
146
147
    LOC_QUE => array(
148
      P_TABLE_NAME => 'que',
149
      P_ID         => 'que_id',
150
      P_OWNER_INFO => array(
151
        array(
152
          P_LOCATION    => LOC_USER,
153
          P_OWNER_FIELD => 'que_player_id',
154
        ),
155
156
        array(
157
          P_LOCATION    => LOC_PLANET,
158
          P_OWNER_FIELD => 'que_planet_id_origin',
159
        ),
160
161
        array(
162
          P_LOCATION    => LOC_PLANET,
163
          P_OWNER_FIELD => 'que_planet_id',
164
        ),
165
      ),
166
    ),
167
168
    LOC_FLEET => array(
169
      P_TABLE_NAME => 'fleets',
170
      P_ID         => 'fleet_id',
171
      P_OWNER_INFO => array(
172
        array(
173
          P_LOCATION    => LOC_USER,
174
          P_OWNER_FIELD => 'fleet_owner',
175
        ),
176
177
        array(
178
          P_LOCATION    => LOC_USER,
179
          P_OWNER_FIELD => 'fleet_target_owner',
180
        ),
181
182
        array(
183
          P_LOCATION    => LOC_PLANET,
184
          P_OWNER_FIELD => 'fleet_start_planet_id',
185
        ),
186
187
        array(
188
          P_LOCATION    => LOC_PLANET,
189
          P_OWNER_FIELD => 'fleet_end_planet_id',
190
        ),
191
      ),
192
    ),
193
  );
194
195
  /**
196
   * @param $db db_mysql
197
   */
198
  public static function init_main_db($db) {
199
    self::$db = $db;
200
    self::$db->sn_db_connect();
201
  }
202
203
204
  public static function log_file($message, $spaces = 0) {
205
    if(self::$debug) {
206
      self::$debug->log_file($message, $spaces);
207
    }
208
  }
209
210
  public static function debug_set_handler(&$debug) {
211
    self::$debug = $debug;
212
  }
213
214
  // Перепаковывает массив на заданную глубину, убирая поля с null
215
  public static function array_repack(&$array, $level = 0) {
216
    // TODO $lock_table не нужна тут
217
    if(!is_array($array)) {
218
      return;
219
    }
220
221
    foreach($array as $key => &$value) {
222
      if($value === null) {
223
        unset($array[$key]);
224
      } elseif($level > 0 && is_array($value)) {
225
        static::array_repack($value, $level - 1);
226
        if(empty($value)) {
227
          unset($array[$key]);
228
        }
229
      }
230
    }
231
  }
232
233
234
  // TODO Вынести в отдельный объект
235
  public static function cache_repack($location_type, $record_id = 0) {
236
    // Если есть $user_id - проверяем, а надо ли перепаковывать?
237
    if($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) {
238
      return;
239
    }
240
241
    static::array_repack(static::$data[$location_type]);
242
    static::array_repack(static::$locator[$location_type], 3); // TODO У каждого типа локации - своя глубина!!!! Но можно и глубже ???
243
    static::array_repack(static::$queries[$location_type], 1);
244
  }
245
246
  public static function cache_clear($location_type, $hard = true) {
247
    //print("<br />CACHE CLEAR {$cache_id} " . ($hard ? 'HARD' : 'SOFT') . "<br />");
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...
248
    if($hard && !empty(static::$data[$location_type])) {
249
      // Здесь нельзя делать unset - надо записывать NULL, что бы это отразилось на зависимых записях
250
      array_walk(static::$data[$location_type], function (&$item) { $item = null; });
251
    }
252
    static::$locator[$location_type] = array();
253
    static::$queries[$location_type] = array();
254
    static::cache_repack($location_type); // Перепаковываем внутренние структуры, если нужно
255
  }
256
257
  public static function cache_clear_all($hard = true) {
258
    //print('<br />CACHE CLEAR ALL<br />');
259
    if($hard) {
260
      static::$data = array();
261
      static::cache_lock_unset_all();
262
    }
263
    static::$locator = array();
264
    static::$queries = array();
265
  }
266
267
  public static function cache_get($location_type, $record_id) {
268
    return isset(static::$data[$location_type][$record_id]) ? static::$data[$location_type][$record_id] : null;
269
  }
270
271
  public static function cache_isset($location_type, $record_id) {
272
    return isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null;
273
  }
274
275
  /* Кэшируем запись в соответствующий кэш
276
277
  Писать в кэш:
278
  1. Если записи не существует в кэше
279
  2. Если стоит $force_overwrite
280
  3. Если во время транзакции существующая запись не заблокирована
281
282
  Блокировать запись:
283
  1. Если идет транзакция и запись не заблокирована
284
  2. Если не стоит скип-лок
285
  */
286
  public static function cache_set($location_type, $record_id, $record, $force_overwrite = false, $skip_lock = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $record_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...
287
    // нет идентификатора - выход
288
    if(!($record_id = $record[static::$location_info[$location_type][P_ID]])) {
289
      return;
290
    }
291
292
    $in_transaction = static::db_transaction_check(false);
293
    if(
294
      $force_overwrite
295
      ||
296
      // Не заменяются заблокированные записи во время транзакции
297
      ($in_transaction && !static::cache_lock_get($location_type, $record_id))
298
      ||
299
      // !isset(static::$data[$location_type][$record_id]) || static::$data[$location_type][$record_id] === null
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% 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...
300
      !static::cache_isset($location_type, $record_id)
301
    ) {
302
      static::$data[$location_type][$record_id] = $record;
303
      if($in_transaction && !$skip_lock) {
304
        static::cache_lock_set($location_type, $record_id);
305
      }
306
    }
307
  }
308
309
  public static function cache_unset($cache_id, $safe_record_id) {
310
    // $record_id должен быть проверен заранее !
311
    if(isset(static::$data[$cache_id][$safe_record_id]) && static::$data[$cache_id][$safe_record_id] !== null) {
312
      // Выставляем запись в null
313
      static::$data[$cache_id][$safe_record_id] = null;
314
      // Очищаем кэш мягко - что бы удалить очистить связанные данные - кэш локаций и кэш запоросов и всё, что потребуется впредь
315
      static::cache_clear($cache_id, false);
316
    }
317
  }
318
319
  public static function cache_lock_get($location_type, $record_id) {
320
    return isset(static::$locks[$location_type][$record_id]);
321
  }
322
323
  public static function cache_lock_set($location_type, $record_id) {
324
    return static::$locks[$location_type][$record_id] = true; // Не всегда - от результата
325
  }
326
327
  public static function cache_lock_unset($location_type, $record_id) {
328
    if(isset(static::$locks[$location_type][$record_id])) {
329
      unset(static::$locks[$location_type][$record_id]);
330
    }
331
332
    return true; // Не всегда - от результата
333
  }
334
335
  public static function cache_lock_unset_all() {
336
    // Когда будем работать с xcache - это понадобиться, что бы снимать в xcache блокировки с записей
337
    // Пройти по массиву - снять блокировки для кэшера в памяти
338
    static::$locks = array();
339
340
    return true; // Не всегда - от результата
341
  }
342
343
344
345
346
347
  // TODO Вынести в отдельный объект
348
  /**
349
   * Эта функция проверяет статус транзакции
350
   *
351
   * Это - низкоуровневая функция. В нормальном состоянии движка её сообщения никогда не будут видны
352
   *
353
   * @param null|true|false $status Должна ли быть запущена транзакция в момент проверки
354
   *   <p>null - транзакция НЕ должна быть запущена</p>
355
   *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
356
   *   <p>false - всё равно - для совместимости с $for_update</p>
357
   *
358
   * @return bool Текущий статус транзакции
359
   */
360
  public static function db_transaction_check($status = null) {
361
    $error_msg = false;
362
    if($status && !static::$db_in_transaction) {
363
      $error_msg = 'No transaction started for current operation';
364
    } elseif($status === null && static::$db_in_transaction) {
365
      $error_msg = 'Transaction is already started';
366
    }
367
368
    if($error_msg) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $error_msg of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
369
      // TODO - Убрать позже
370
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_transaction_check() - ' . $error_msg . '</h1>');
371
      $backtrace = debug_backtrace();
372
      array_shift($backtrace);
373
      pdump($backtrace);
374
      die($error_msg);
375
    }
376
377
    return static::$db_in_transaction;
378
  }
379
380
  public static function db_transaction_start($level = '') {
381
    global $config;
382
383
    static::db_transaction_check(null);
384
385
    $level ? doquery('SET TRANSACTION ISOLATION LEVEL ' . $level) : false;
386
387
    static::$transaction_id++;
388
    doquery('START TRANSACTION');
389
390
    if($config->db_manual_lock_enabled) {
391
      $config->db_loadItem('var_db_manually_locked');
392
      $config->db_saveItem('var_db_manually_locked', SN_TIME_SQL);
393
    }
394
395
    static::$db_in_transaction = true;
396
    static::$locator = array();
397
    static::$queries = array();
398
399
    //print('<hr/>TRANSACTION START id' . static::$transaction_id . '<br />');
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...
400
401
    return static::$transaction_id;
402
  }
403
404
  public static function db_transaction_commit() {
405
    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...
406
407
    if(!empty(static::$delayed_changset)) {
408
      static::db_changeset_apply(static::$delayed_changset, true);
409
      // pdump(static::$delayed_changset);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
410
    }
411
    static::$delayed_changset = array();
412
    static::cache_lock_unset_all();
413
    doquery('COMMIT');
414
415
    //print('<br/>TRANSACTION COMMIT id' . static::$transaction_id . '<hr />');
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...
416
    static::$db_in_transaction = false;
417
418
    return static::$transaction_id++;
419
  }
420
421
  public static function db_transaction_rollback() {
422
    // 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...
423
    if(!empty(static::$delayed_changset)) {
424
      static::db_changeset_revert();
425
    }
426
    static::$delayed_changset = array();
427
    static::cache_lock_unset_all();
428
    doquery('ROLLBACK');
429
430
    //print('<br/>TRANSACTION ROLLBACK id' . static::$transaction_id . '<hr />');
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...
431
    static::$db_in_transaction = false;
432
    static::$transaction_id++;
433
434
    return static::$transaction_id;
435
  }
436
437
  /**
438
   * Блокирует указанные таблицу/список таблиц
439
   *
440
   * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
441
   * <p>string - название таблицы для блокировки</p>
442
   * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p>
443
   */
444
  public static function db_lock_tables($tables) {
445
    $tables = is_array($tables) ? $tables : array($tables => '');
446
    foreach($tables as $table_name => $condition) {
447
      self::$db->doquery("SELECT 1 FROM {{{$table_name}}}" . ($condition ? ' WHERE ' . $condition : ''));
448
    }
449
  }
450
451
  public static function db_query($query, $fetch = false, $skip_lock = false) {
452
    $select = strpos(strtoupper($query), 'SELECT') !== false;
453
454
    $query .= $select && $fetch ? ' LIMIT 1' : '';
455
    $query .= $select && !$skip_lock && static::db_transaction_check(false) ? ' FOR UPDATE' : '';
456
457
    $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...
458
459
    return $result;
460
  }
461
462
  /**
463
   * Возвращает информацию о записи по её ID
464
   *
465
   * @param int       $location_type
466
   * @param int|array $record_id_unsafe
467
   *    <p>int - ID записи</p>
468
   *    <p>array - запись пользователя с установленным полем P_ID</p>
469
   * @param bool      $for_update @deprecated
470
   * @param string    $fields @deprecated список полей или '*'/'' для всех полей
471
   * @param bool      $skip_lock Указывает на то, что не нужно блокировать запись //TODO и не нужно сохранять в кэше
472
   *
473
   * @return array|false
474
   *    <p>false - Нет записи с указанным ID</p>
475
   *    <p>array - запись</p>
476
   */
477
  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...
478
    $id_field = static::$location_info[$location_type][P_ID];
479
    // $record_id = intval(is_array($record_id) && isset($record_id[$id_field]) ? $record_id[$id_field] : $record_id);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
480
    $record_id_safe = idval(is_array($record_id_unsafe) && isset($record_id_unsafe[$id_field]) ? $record_id_unsafe[$id_field] : $record_id_unsafe);
481
482
    return static::db_get_record_list($location_type, "`{$id_field}` = {$record_id_safe}", true, false);
483
  }
484
485
  public static function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) {
486
    //pdump($filter, 'Выбираем ' . $location_type);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
487
    $query_cache = &static::$queries[$location_type][$filter];
488
489
    if(!isset($query_cache) || $query_cache === null) {
490
      // pdump($filter, 'Кэш пустой, начинаем возню');
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...
491
      $location_info = &static::$location_info[$location_type];
492
      $id_field = $location_info[P_ID];
493
      $query_cache = array();
494
495
      if(static::db_transaction_check(false)) {
496
        //pdump($filter, 'Транзакция - блокируем ' . $location_type);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
497
        // Проходим по всем родителям данной записи
498
        // foreach($location_info[P_OWNER_INFO] as $owner_location_type => $owner_data)
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
499
        foreach($location_info[P_OWNER_INFO] as $owner_data) {
500
          $owner_location_type = $owner_data[P_LOCATION];
501
          //pdump($filter, 'Транзакция - блокируем родителя ' . $owner_location_type);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
502
          $parent_id_list = array();
503
          // Выбираем родителей данного типа и соответствующие ИД текущего типа
504
          $query = static::db_query(
505
            "SELECT
506
              distinct({{{$location_info[P_TABLE_NAME]}}}.{$owner_data[P_OWNER_FIELD]}) AS parent_id
507
            FROM {{{$location_info[P_TABLE_NAME]}}}" .
508
            ($filter ? ' WHERE ' . $filter : '') .
509
            ($fetch ? ' LIMIT 1' : ''), false, true);
510
511
          //pdump($q, 'Запрос блокировки');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
512
          while($row = db_fetch($query)) {
513
            // Исключаем из списка родительских ИД уже заблокированные записи
514
            if(!static::cache_lock_get($owner_location_type, $row['parent_id'])) {
515
              $parent_id_list[$row['parent_id']] = $row['parent_id'];
516
            }
517
          }
518
          //pdump($parent_id_list, 'Выбраны родители');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
519
          // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
520
          if($indexes_str = implode(',', $parent_id_list)) {
521
            //pdump($indexes_str, '$indexes_str');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
522
            $parent_id_field = static::$location_info[$owner_location_type][P_ID];
523
            static::db_get_record_list($owner_location_type,
524
              $parent_id_field . (count($parent_id_list) > 1 ? " IN ({$indexes_str})" : " = {$indexes_str}"), $fetch, true);
525
          }
526
          //pdump($filter, 'Транзакция - родители заблокированы ' . $owner_location_type);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
527
        }
528
      }
529
530
      //pdump($filter, 'Выбираем записи и заносим их в кыш-память ' . $owner_location_type);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
531
      $query = static::db_query(
532
        "SELECT * FROM {{{$location_info[P_TABLE_NAME]}}}" .
533
        (($filter = trim($filter)) ? " WHERE {$filter}" : '')
534
      );
535
      while($row = db_fetch($query)) {
536
        // static::db_get_record_by_id($location_type, $row[$id_field]);
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...
537
        static::cache_set($location_type, $row[$id_field], $row);
538
        $query_cache[$row[$id_field]] = &static::$data[$location_type][$row[$id_field]];
539
        //pdump(static::$data[$location_type][$row[$id_field]]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
94% 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...
540
      }
541
    }
542
543
    if($no_return) {
544
      return true;
545
    } else {
546
      $result = false;
547
      if(is_array($query_cache)) {
548
        foreach($query_cache as $key => $value) {
549
          $result[$key] = $value;
550
          if($fetch) {
551
            break;
552
          }
553
        }
554
      }
555
556
      return $fetch ? (is_array($result) ? reset($result) : false) : $result;
557
    }
558
  }
559
560
  /**
561
   * @param int    $location_type
562
   * @param int    $record_id
563
   * @param string $set - SQL SET structure
564
   *
565
   * @return array|bool|mysqli_result|null
566
   */
567
  public static function db_upd_record_by_id($location_type, $record_id, $set) {
568
    //if(!($record_id = intval($record_id)) || !($set = trim($set))) return false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
569
    if(!($record_id = idval($record_id)) || !($set = trim($set))) {
570
      return false;
571
    }
572
573
    $location_info = &static::$location_info[$location_type];
574
    $id_field = $location_info[P_ID];
575
    $table_name = $location_info[P_TABLE_NAME];
576
    if($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
577
    {
578
      if(static::$db->db_affected_rows()) {
579
        // Обновляем данные только если ряд был затронут
580
        // TODO - переделать под работу со структурированными $set
581
582
        // Тут именно так, а не cache_unset - что бы в кэшах автоматически обновилась запись. Будет нужно на будущее
583
        static::$data[$location_type][$record_id] = null;
584
        // Вытаскиваем обновленную запись
585
        static::db_get_record_by_id($location_type, $record_id);
586
        static::cache_clear($location_type, false); // Мягкий сброс - только $queries
587
      }
588
    }
589
590
    return $result;
591
  }
592
593
  public static function db_upd_record_list($location_type, $condition, $set) {
594
    if(!($set = trim($set))) {
595
      return false;
596
    }
597
598
    $condition = trim($condition);
599
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
600
601
//static::db_get_record_list($location_type, $condition, false, true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
602
603
    if($result = static::db_query("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
604
605
      if(static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
606
        // Поскольку нам неизвестно, что и как обновилось - сбрасываем кэш этого типа полностью
607
        // TODO - когда будет структурированный $condition и $set - перепаковывать данные
608
        static::cache_clear($location_type, true);
609
      }
610
    }
611
612
    return $result;
613
  }
614
615
  /**
616
   * @param int    $location_type
617
   * @param string $set
618
   *
619
   * @return array|bool|false|mysqli_result|null
620
   */
621
  public static function db_ins_record($location_type, $set) {
622
    $set = trim($set);
623
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
624 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...
625
      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
626
      {
627
        $record_id = db_insert_id();
628
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
629
        $result = static::db_get_record_by_id($location_type, $record_id);
630
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
631
        // TODO - когда будет поддержка изменения индексов и локаций - можно будет вызывать её
632
        static::cache_clear($location_type, false); // Мягкий сброс - только $queries
633
      }
634
    }
635
636
    return $result;
637
  }
638
639
  public static function db_ins_field_set($location_type, $field_set, $serialize = false) {
640
    // TODO multiinsert
641
    !sn_db_field_set_is_safe($field_set) ? $field_set = sn_db_field_set_make_safe($field_set, $serialize) : false;
642
    sn_db_field_set_safe_flag_clear($field_set);
643
    $values = implode(',', $field_set);
644
    $fields = implode(',', array_keys($field_set));
645
646
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
647 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...
648
      if(static::$db->db_affected_rows()) {
649
        // Обновляем данные только если ряд был затронут
650
        $record_id = db_insert_id();
651
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
652
        $result = static::db_get_record_by_id($location_type, $record_id);
653
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
654
        // TODO - когда будет поддержка изменения индексов и локаций - можно будет вызывать её
655
        static::cache_clear($location_type, false); // Мягкий сброс - только $queries
656
      }
657
    }
658
659
    return $result;
660
  }
661
662
  public static function db_del_record_by_id($location_type, $safe_record_id) {
663
    // if(!($safe_record_id = intval($safe_record_id))) return false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
664
    if(!($safe_record_id = idval($safe_record_id))) {
665
      return false;
666
    }
667
668
    $location_info = &static::$location_info[$location_type];
669
    $id_field = $location_info[P_ID];
670
    $table_name = $location_info[P_TABLE_NAME];
671
    if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}")) {
672
      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
673
      {
674
        static::cache_unset($location_type, $safe_record_id);
675
      }
676
    }
677
678
    return $result;
679
  }
680
681
  public static function db_del_record_list($location_type, $condition) {
682
    if(!($condition = trim($condition))) {
683
      return false;
684
    }
685
686
    $location_info = &static::$location_info[$location_type];
687
    $table_name = $location_info[P_TABLE_NAME];
688
689
//static::db_get_record_list($location_type, $condition, false, true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
690
691
    if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE {$condition}")) {
692
      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
693
      {
694
        // Обнуление кэша, потому что непонятно, что поменялось
695
        // TODO - когда будет структурированный $condition можно будет делать только cache_unset по нужным записям
696
        static::cache_clear($location_type);
697
      }
698
    }
699
700
    return $result;
701
  }
702
703
704
705
  // Работа с пользователями
706
  /**
707
   * Возвращает информацию о пользователе по его ID
708
   *
709
   * @param int|array $user_id_unsafe
710
   *    <p>int - ID пользователя</p>
711
   *    <p>array - запись пользователя с установленным полем ['id']</p>
712
   * @param bool      $for_update @deprecated
713
   * @param string    $fields @deprecated список полей или '*'/'' для всех полей
714
   * @param null      $player
715
   * @param bool|null $player Признак выбора записи пользователь типа "игрок"
716
   *    <p>null - Можно выбрать запись любого типа</p>
717
   *    <p>true - Выбирается только запись типа "игрок"</p>
718
   *    <p>false - Выбирается только запись типа "альянс"</p>
719
   *
720
   * @return array|false
721
   *    <p>false - Нет записи с указанным ID и $player</p>
722
   *    <p>array - запись типа $user</p>
723
   */
724
  public static function db_get_user_by_id($user_id_unsafe, $for_update = false, $fields = '*', $player = null) {
725
    $user = static::db_get_record_by_id(LOC_USER, $user_id_unsafe, $for_update, $fields);
726
727
    return (is_array($user) &&
728
      (
729
        $player === null
730
        ||
731
        ($player === true && !$user['user_as_ally'])
732
        ||
733
        ($player === false && $user['user_as_ally'])
734
      )) ? $user : false;
735
  }
736
737
  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...
738
    // TODO Проверить, кстати - а везде ли нужно выбирать юзеров или где-то все-таки ищутся Альянсы ?
739
    if(!($username_unsafe = trim($username_unsafe))) {
740
      return false;
741
    }
742
743
    $user = null;
744
    if(is_array(static::$data[LOC_USER])) {
745
      foreach(static::$data[LOC_USER] as $user_id => $user_data) {
746
        if(is_array($user_data) && isset($user_data['username'])) {
747
          // проверяем поле
748
          // TODO Возможно есть смысл всегда искать по strtolower - но может игрок захочет переименоваться с другим регистром? Проверить!
749
          if((!$like && $user_data['username'] == $username_unsafe) || ($like && strtolower($user_data['username']) == strtolower($username_unsafe))) {
750
            // $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...
751
            $user_as_ally = idval($user_data['user_as_ally']);
752
            if($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally)) {
753
              $user = $user_data;
754
              break;
755
            }
756
          }
757
        }
758
      }
759
    }
760
761 View Code Duplication
    if($user === null) {
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...
762
      // Вытаскиваем запись
763
      $username_safe = db_escape($like ? strtolower($username_unsafe) : $username_unsafe); // тут на самом деле strtolower() лишняя, но пусть будет
764
765
      // TODO переписать
766
      // self::db_get_record_list(LOC_USER, "`username` " . ($like ? 'LIKE' : '='). " '{$username_safe}'");
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
767
768
      $user = static::db_query(
769
        "SELECT * FROM {{users}} WHERE `username` " . ($like ? 'LIKE' : '=') . " '{$username_safe}'"
770
        , true);
771
      static::cache_set(LOC_USER, $user['id'], $user); // В кэш-юзер так же заполнять индексы
772
    }
773
774
    return $user;
775
  }
776
777
  // UNUSED
778
  public static function db_get_user_by_email($email_unsafe, $use_both = false, $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...
779
    if(!($email_unsafe = strtolower(trim($email_unsafe)))) {
780
      return false;
781
    }
782
783
    $user = null;
784
    // TODO переделать на индексы
785
    if(is_array(static::$data[LOC_USER])) {
786
      foreach(static::$data[LOC_USER] as $user_id => $user_data) {
787
        if(is_array($user_data) && isset($user_data['email_2'])) {
788
          // проверяем поле
789
          if(strtolower($user_data['email_2']) == $email_unsafe || ($use_both && strtolower($user_data['email']) == $email_unsafe)) {
790
            $user = $user_data;
791
            break;
792
          }
793
        }
794
      }
795
    }
796
797 View Code Duplication
    if($user === null) {
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...
798
      // Вытаскиваем запись
799
      $email_safe = db_escape($email_unsafe);
800
      $user = static::db_query(
801
        "SELECT * FROM {{users}} WHERE LOWER(`email_2`) = '{$email_safe}'" .
802
        ($use_both ? " OR LOWER(`email`) = '{$email_safe}'" : '')
803
        , true);
804
805
      static::cache_set(LOC_USER, $user['id'], $user); // В кэш-юзер так же заполнять индексы
806
    }
807
808
    return $user;
809
  }
810
811
  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...
812
//    if(!($email_unsafe = strtolower(trim($email_unsafe)))) return false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% 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...
813
    $user = null;
814
    // TODO переделать на индексы
815
816
    if($user === null && !empty($where_safe)) {
817
      // Вытаскиваем запись
818
      $user = static::db_query("SELECT * FROM {{users}} WHERE {$where_safe}", true);
819
820
      static::cache_set(LOC_USER, $user['id'], $user); // В кэш-юзер так же заполнять индексы
821
    }
822
823
    return $user;
824
  }
825
826
827 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...
828
    $date = is_numeric($date) ? "FROM_UNIXTIME({$date})" : "'{$date}'";
829
830
    return
831
      "(unit_time_start IS NULL OR unit_time_start <= {$date}) AND
832
    (unit_time_finish IS NULL OR unit_time_finish = '1970-01-01 03:00:00' OR unit_time_finish >= {$date})";
833
  }
834
835
  public static function db_get_unit_by_id($unit_id, $for_update = false, $fields = '*') {
836
    // 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...
837
    $unit = static::db_get_record_by_id(LOC_UNIT, $unit_id, $for_update, $fields);
838
    if(is_array($unit)) {
839
      static::$locator[LOC_UNIT][$unit['unit_location_type']][$unit['unit_location_id']][$unit['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
840
    }
841
842
    return $unit;
843
  }
844
845
  /**
846
   * @param int $user_id
847
   * @param     $location_type
848
   * @param     $location_id
849
   *
850
   * @return array|bool
851
   */
852
  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...
853
    //if(!($location_type = intval($location_type)) || !($location_id = intval($location_id))) return false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
854
    if(!($location_type = idval($location_type)) || !($location_id = idval($location_id))) {
855
      return false;
856
    }
857
858
    $query_cache = &static::$locator[LOC_UNIT][$location_type][$location_id];
859
    if(!isset($query_cache)) {
860
      $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());
861
      if(is_array($got_data)) {
862
        foreach($got_data as $unit_id => $unit_data) {
863
          // static::$data[LOC_LOCATION][$location_type][$location_id][$unit_data['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% 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...
864
          $query_cache[$unit_data['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
865
        }
866
      }
867
    }
868
869
    $result = false;
870
    if(is_array($query_cache)) {
871
      foreach($query_cache as $key => $value) {
872
        $result[$key] = $value;
873
      }
874
    }
875
876
    return $result;
877
  }
878
879
  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...
880
    static::db_get_unit_list_by_location($user_id, $location_type, $location_id);
881
882
    return $unit_snid ? static::$locator[LOC_UNIT][$location_type][$location_id][$unit_snid] : static::$locator[LOC_UNIT][$location_type][$location_id];
883
  }
884
885
886
  /*
887
   * С $for_update === true эта функция должна вызываться только из транзакции! Все соответствующие записи в users и planets должны быть уже блокированы!
888
   *
889
   * $que_type
890
   *   !$que_type - все очереди
891
   *   QUE_XXXXXX - конкретная очередь по планете
892
   * $user_id - ID пользователя
893
   * $planet_id
894
   *   $que_type == QUE_RESEARCH - игнорируется
895
   *   null - обработка очередей планет не производится
896
   *   false/0 - обрабатываются очереди всех планет по $user_id
897
   *   (integer) - обрабатываются локальные очереди для планеты. Нужно, например, в обработчике флотов
898
   *   иначе - $que_type для указанной планеты
899
   * $for_update - true == нужно блокировать записи
900
   *
901
   * TODO Работа при !$user_id
902
   * TODO Переформатировать вывод данных, что бы можно было возвращать данные по всем планетам и юзерам в одном запросе: добавить подмассивы 'que', 'planets', 'players'
903
   *
904
   */
905
  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...
906
    if(!$user_id) {
907
      pdump(debug_backtrace());
908
      die('No user_id for que_get_que()');
909
    }
910
911
    $ques = array();
912
913
    $query = array();
914
915
    // if($user_id = intval($user_id))
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
916
    if($user_id = idval($user_id)) {
917
      $query[] = "`que_player_id` = {$user_id}";
918
    }
919
920
    if($que_type == QUE_RESEARCH || $planet_id === null) {
921
      $query[] = "`que_planet_id` IS NULL";
922
    } elseif($planet_id) {
923
      $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
924
    }
925
    if($que_type) {
926
      $query[] = "`que_type` = {$que_type}";
927
    }
928
929
    /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
51% 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...
930
    $sql = '';
931
    $sql .= $user_id ? " AND `que_player_id` = {$user_id}" : '';
932
    $sql .= $que_type == QUE_RESEARCH || $planet_id === null ? " AND `que_planet_id` IS NULL" :
933
      ($planet_id ? " AND (`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")" : '');
934
    $sql .= $que_type ? " AND `que_type` = {$que_type}" : '';
935
    pdump($sql);
936
    pdump(implode(' AND ', $query));
937
938
    $que_query = ($sql = implode(' AND ', $query))
939
      ? doquery("SELECT * FROM {{que}} WHERE {$sql} ORDER BY que_id" . ($for_update ? ' FOR UPDATE' : ''))
940
      : false;
941
942
    if($que_query)
943
    {
944
      while($row = db_fetch($que_query))
945
      {
946
        $ques['items'][] = $row;
947
      }
948
    }
949
    */
950
951
    $ques['items'] = static::db_get_record_list(LOC_QUE, implode(' AND ', $query));
952
953
    return que_recalculate($ques);
954
  }
955
956
957 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...
958
    if(!is_array($user)) {
959
      // TODO - remove later
960
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER is not ARRAY</h1>');
961
      pdump(debug_backtrace());
962
      die('USER is not ARRAY');
963
    }
964
    if(!isset($user['id']) || !$user['id']) {
965
      // TODO - remove later
966
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER[id] пустой</h1>');
967
      pdump($user);
968
      pdump(debug_backtrace());
969
      die('USER[id] пустой');
970
    }
971
    $planet_id = is_array($planet_id) && isset($planet_id['id']) ? $planet_id['id'] : $planet_id;
972
973
    $unit_location = sys_get_unit_location($user, array(), $unit_id);
974
    $location_id = $unit_location == LOC_USER ? $user['id'] : $planet_id;
975
    $location_id = $location_id ? $location_id : 'NULL';
976
977
    $db_changeset = array();
0 ignored issues
show
Unused Code introduced by
$db_changeset is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
978
    $temp = db_unit_by_location($user['id'], $unit_location, $location_id, $unit_id, true, 'unit_id');
979
    if($temp['unit_id']) {
980
      $db_changeset = array(
981
        'action'  => SQL_OP_UPDATE,
982
        P_VERSION => 1,
983
        'where'   => array(
984
          "unit_id" => $temp['unit_id'],
985
        ),
986
        'fields'  => array(
987
          'unit_level' => array(
988
            'delta' => $unit_value
989
          ),
990
        ),
991
      );
992
    } else {
993
      $db_changeset = array(
994
        'action' => SQL_OP_INSERT,
995
        'fields' => array(
996
          'unit_player_id'     => array(
997
            'set' => $user['id'],
998
          ),
999
          'unit_location_type' => array(
1000
            'set' => $unit_location,
1001
          ),
1002
          'unit_location_id'   => array(
1003
            'set' => $unit_location == LOC_USER ? $user['id'] : $planet_id,
1004
          ),
1005
          'unit_type'          => array(
1006
            'set' => get_unit_param($unit_id, P_UNIT_TYPE),
1007
          ),
1008
          'unit_snid'          => array(
1009
            'set' => $unit_id,
1010
          ),
1011
          'unit_level'         => array(
1012
            'set' => $unit_value,
1013
          ),
1014
        ),
1015
      );
1016
    }
1017
1018
    return $db_changeset;
1019
  }
1020
1021
1022
  public function db_changeset_delay($table_name, $table_data) {
1023
    // TODO Применять ченджсет к записям
1024
    static::$delayed_changset[$table_name] = is_array(static::$delayed_changset[$table_name]) ? static::$delayed_changset[$table_name] : array();
1025
    // TODO - На самом деле дурацкая оптимизация, если честно - может быть идентичные записи с идентичными дельтами - и привет. Но не должны, конечно
1026
    /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% 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...
1027
    foreach($table_data as $key => $value)
1028
    {
1029
      if(array_search($value, static::$delayed_changset[$table_name]) !== false)
1030
      {
1031
        unset($table_data[$key]);
1032
      }
1033
    }
1034
    */
1035
    static::$delayed_changset[$table_name] = array_merge(static::$delayed_changset[$table_name], $table_data);
1036
    // pdump(static::$delayed_changset);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
1037
    // die();
1038
  }
1039
1040
  public function db_changeset_revert() {
1041
    // TODO Для этапа 1 - достаточно чистить только те таблицы, что были затронуты
1042
    // Для этапа 2 - чистить только записи
1043
    // Для этапа 3 - возвращать всё
1044
    static::cache_clear_all(true);
1045
  }
1046
1047
  public function db_changeset_condition_compile(&$conditions, &$table_name = '') {
1048
    if(!$conditions[P_LOCATION] || $conditions[P_LOCATION] == LOC_NONE) {
1049
      $conditions[P_LOCATION] = LOC_NONE;
1050
      switch($table_name) {
1051
        case 'users':
1052
        case LOC_USER:
1053
          $conditions[P_TABLE_NAME] = $table_name = 'users';
1054
          $conditions[P_LOCATION] = LOC_USER;
1055
        break;
1056
1057
        case 'planets':
1058
        case LOC_PLANET:
1059
          $conditions[P_TABLE_NAME] = $table_name = 'planets';
1060
          $conditions[P_LOCATION] = LOC_PLANET;
1061
        break;
1062
1063
        case 'unit':
1064
        case LOC_UNIT:
1065
          $conditions[P_TABLE_NAME] = $table_name = 'unit';
1066
          $conditions[P_LOCATION] = LOC_UNIT;
1067
        break;
1068
      }
1069
    }
1070
1071
    $conditions[P_FIELDS_STR] = '';
1072
    if($conditions['fields']) {
1073
      $fields = array();
1074 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...
1075
        $condition = "`{$field_name}` = ";
1076
        $value = '';
1077
        if($field_data['delta']) {
1078
          $value = "`{$field_name}`" . ($field_data['delta'] >= 0 ? '+' : '') . $field_data['delta'];
1079
        } elseif($field_data['set']) {
1080
          $value = (is_string($field_data['set']) ? "'{$field_data['set']}'" : $field_data['set']);
1081
        }
1082
1083
        if($value) {
1084
          $fields[] = $condition . $value;
1085
        }
1086
      }
1087
      $conditions[P_FIELDS_STR] = implode(',', $fields);
1088
    }
1089
1090
    $conditions[P_WHERE_STR] = '';
1091
    if(!empty($conditions['where'])) {
1092
      if($conditions[P_VERSION] == 1) {
1093
        $the_conditions = array();
1094
        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...
1095
          // Простое условие - $field_id = $field_value
1096
          if(is_string($field_id)) {
1097
            $field_value =
1098
              $field_value === null ? 'NULL' :
1099
                (is_string($field_value) ? "'" . db_escape($field_value) . "'" :
1100
                  (is_bool($field_value) ? intval($field_value) : $field_value));
1101
            $the_conditions[] = "`{$field_id}` = {$field_value}";
1102
          } else {
1103
            die('Неподдерживаемый тип условия');
1104
          }
1105
        }
1106
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% 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...
1107
        print('<h1>НЕ СООБЩАТЬ! НЕ ОШИБКА!</h1>');
1108
        pdump($conditions['where']);
1109
        pdump($the_conditions);
1110
        */
1111
      } else {
1112
        $the_conditions = &$conditions['where'];
1113
      }
1114
      $conditions[P_WHERE_STR] = implode(' AND ', $the_conditions);
1115
    }
1116
1117
    switch($conditions['action']) {
1118
      case SQL_OP_DELETE:
1119
        $conditions[P_ACTION_STR] = ("DELETE FROM {{{$table_name}}}");
1120
      break;
1121
      case SQL_OP_UPDATE:
1122
        $conditions[P_ACTION_STR] = ("UPDATE {{{$table_name}}} SET");
1123
      break;
1124
      case SQL_OP_INSERT:
1125
        $conditions[P_ACTION_STR] = ("INSERT INTO {{{$table_name}}} SET");
1126
      break;
1127
      // 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...
1128
      default:
1129
        die('Неподдерживаемая операция в classSupernova::db_changeset_condition_compile');
1130
    }
1131
1132
    $conditions[P_QUERY_STR] = $conditions[P_ACTION_STR] . ' ' . $conditions[P_FIELDS_STR] . (' WHERE ' . $conditions[P_WHERE_STR]);
1133
  }
1134
1135
  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...
1136
    $result = true;
1137
    if(!is_array($db_changeset) || empty($db_changeset)) {
1138
      return $result;
1139
    }
1140
1141
    foreach($db_changeset as $table_name => &$table_data) {
1142
      // TODO - delayed changeset
1143
      /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
1144
      if(static::db_transaction_check(false) && !$flush_delayed && ($table_name == 'users' || $table_name == 'planets' || $table_name == 'unit'))
1145
      {
1146
        static::db_changeset_delay($table_name, $table_data);
1147
        continue;
1148
      }
1149
      */
1150
      foreach($table_data as $record_id => &$conditions) {
1151
        static::db_changeset_condition_compile($conditions, $table_name);
1152
1153
        if($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) {
1154
          continue;
1155
        }
1156
        if($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) {
1157
          continue;
1158
        } // Защита от случайного удаления всех данных в таблице
1159
1160
        if($conditions[P_LOCATION] != LOC_NONE) {
1161
          //die('spec ops supernova.php line 928 Добавить работу с кэшем юнитов итд');
1162
          switch($conditions['action']) {
1163
            case SQL_OP_DELETE:
1164
              $result = self::db_del_record_list($conditions[P_LOCATION], $conditions[P_WHERE_STR]) && $result;
1165
            break;
1166
            case SQL_OP_UPDATE:
1167
              $result = self::db_upd_record_list($conditions[P_LOCATION], $conditions[P_WHERE_STR], $conditions[P_FIELDS_STR]) && $result;
1168
            break;
1169
            case SQL_OP_INSERT:
1170
              $result = self::db_ins_record($conditions[P_LOCATION], $conditions[P_FIELDS_STR]) && $result;
1171
            break;
1172
            default:
1173
              die('Неподдерживаемая операция в classSupernova::db_changeset_apply');
1174
            // 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...
1175
          }
1176
        } else {
1177
          $result = doquery($conditions[P_QUERY_STR]) && $result;
1178
        }
1179
      }
1180
    }
1181
1182
    return $result;
1183
  }
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
  // que_process не всегда должна работать в режиме прямой работы с БД !! Она может работать и в режиме эмуляции
1220
  // !!!!!!!! После que_get брать не [0] элемент, а first() - тогда можно в индекс элемента засовывать que_id из таблицы
1221
1222
1223
  // TODO - это вообще-то надо хранить в конфигурации
1224
  public static function db_get_user_player_username_last_registered() {
1225
    $user = static::db_query('SELECT * FROM {{users}} WHERE `user_as_ally` IS NULL ORDER BY `id` DESC', true);
1226
    static::cache_set(LOC_USER, $user['id'], $user);
1227
1228
    return isset($user['username']) ? $user['username'] : '';
1229
  }
1230
1231
  // Это для поиска по кэшу
1232
  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...
1233
  }
1234
1235
  // Для модулей - регистрация юнитов
1236
  public static function unit_register() {
1237
1238
  }
1239
1240
1241
  public static function init_0_prepare() {
1242
    // Отключаем magic_quotes
1243
    ini_get('magic_quotes_sybase') ? die('SN is incompatible with \'magic_quotes_sybase\' turned on. Disable it in php.ini or .htaccess...') : false;
1244
    if(@get_magic_quotes_gpc()) {
1245
      $gpcr = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
1246
      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...
1247
        $value = stripslashes($value);
1248
      });
1249
    }
1250
    if(function_exists('set_magic_quotes_runtime')) {
1251
      @set_magic_quotes_runtime(0);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1252
      @ini_set('magic_quotes_runtime', 0);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1253
      @ini_set('magic_quotes_sybase', 0);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1254
    }
1255
  }
1256
1257
  public static function init_1_constants() {
1258
//    global $phpEx, $phpbb_root_path; // Это нужно для работы PTL
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
1259
1260
//    define('SN_TIME_NOW', intval(SN_TIME_MICRO));
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
1261
//    define('SN_TIME_ZONE_OFFSET', date('Z'));
1262
//
1263
//    define('FMT_DATE_TIME_SQL', 'Y-m-d H:i:s');
1264
//    define('SN_TIME_SQL', date(FMT_DATE_TIME_SQL, SN_TIME_NOW));
1265
1266
//    if(strpos(strtolower($_SERVER['SERVER_NAME']), 'google.') !== false) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
1267
//      define('SN_GOOGLE', true);
1268
//    }
1269
1270
//    $phpEx = strpos($phpEx = substr(strrchr(__FILE__, '.'), 1), '/') === false ? $phpEx : '';
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...
1271
//    define('PHP_EX', $phpEx); // PHP extension on this server
1272
//    define('DOT_PHP_EX', '.' . PHP_EX); // PHP extension on this server
1273
1274
//    $sn_root_relative = str_replace('\\', '/', getcwd());
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...
1275
//    $sn_root_relative .= $sn_root_relative[strlen($sn_root_relative) - 1] == '/' ? '' : '/';
1276
//    $sn_root_relative = str_replace(SN_ROOT_PHYSICAL, '', $sn_root_relative);
1277
//    $sn_root_relative .= basename($_SERVER['SCRIPT_NAME']);
1278
//    $sn_root_relative = str_replace($sn_root_relative, '', $_SERVER['SCRIPT_NAME']);
1279
//    define('SN_ROOT_RELATIVE', $sn_root_relative);
1280
1281
//    define('SN_ROOT_VIRTUAL' , 'http' . (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . SN_ROOT_RELATIVE);
0 ignored issues
show
Unused Code Comprehensibility introduced by
51% 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...
1282
//    define('SN_ROOT_VIRTUAL_PARENT' , str_replace('//google.', '//', SN_ROOT_VIRTUAL));
1283
//
1284
//    $phpbb_root_path = SN_ROOT_PHYSICAL; // Это нужно для работы PTL
1285
  }
1286
1287
  public static function init_3_load_config_file() {
1288
    $dbsettings = array();
1289
1290
    require(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
1291
    //self::$db_prefix = $dbsettings['prefix'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
1292
    self::$cache_prefix = !empty($dbsettings['cache_prefix']) ? $dbsettings['cache_prefix'] : $dbsettings['prefix'];
1293
    self::$db_name = $dbsettings['name'];
1294
    self::$sn_secret_word = $dbsettings['secretword'];
1295
    unset($dbsettings);
1296
  }
1297
1298
  public static function init_global_objects() {
1299
    /**
1300
     * @var classSupernova $supernova
1301
     */
1302
    global $supernova, $sn_cache, $config;
1303
1304
    self::$user_options = new userOptions(0);
1305
1306
    /**
1307
     * @var classSupernova $supernova
1308
     */
1309
    $supernova = new classSupernova();
1310
1311
    // Initializing global 'cacher' object
1312
    static::$cache = new classCache(classSupernova::$cache_prefix);
1313
    $sn_cache = static::$cache;
1314
    empty($sn_cache->tables) && sys_refresh_tablelist();
0 ignored issues
show
Documentation introduced by
The property tables does not exist on object<classCache>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1315
    empty($sn_cache->tables) && die('DB error - cannot find any table. Halting...');
0 ignored issues
show
Documentation introduced by
The property tables does not exist on object<classCache>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1316
1317
    // Initializing global "config" object
1318
    static::$config = new classConfig(classSupernova::$cache_prefix);
1319
    $config = static::$config;
1320
    //$config->db_prefix = classSupernova::$db_prefix;
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...
1321
    //$config->secret_word = classSupernova::$sn_secret_word;
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...
1322
    //$config->db_saveItem('secret_word', classSupernova::$sn_secret_word);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
1323
    //$config->db_saveItem('db_prefix', classSupernova::$db_prefix);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
1324
    //$config->db_saveItem('cache_prefix', classSupernova::$cache_prefix);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
1325
  }
1326
1327
  public static function init_debug_state() {
1328
    if($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
1329
      define('BE_DEBUG', true);
1330
    }
1331
// 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...
1332
    define('DEBUG_SQL_ERROR', true); // Выводить в сообщении об ошибке так же полный дамп запросов за сессию. Подойдет любое значение
1333
    define('DEBUG_SQL_COMMENT_LONG', true); // Добавлять SQL запрос длинные комментарии. Не зависим от всех остальных параметров. Подойдет любое значение
1334
    define('DEBUG_SQL_COMMENT', true); // Добавлять комментарии прямо в SQL запрос. Подойдет любое значение
1335
// Включаем нужные настройки
1336
    defined('DEBUG_SQL_ONLINE') && !defined('DEBUG_SQL_ERROR') ? define('DEBUG_SQL_ERROR', true) : false;
1337
    defined('DEBUG_SQL_ERROR') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
1338
    defined('DEBUG_SQL_COMMENT_LONG') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
1339
1340
    if(defined('BE_DEBUG') || static::$config->debug) {
0 ignored issues
show
Documentation introduced by
The property debug does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1341
      @define('BE_DEBUG', true);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1342
      @ini_set('display_errors', 1);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1343
      @error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1344
    } else {
1345
      @define('BE_DEBUG', false);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1346
      @ini_set('display_errors', 0);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1347
    }
1348
1349
  }
1350
1351
}
1352