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

SN::db_lock_tables()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 3
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 4
rs 9.2
ccs 0
cts 4
cp 0
crap 20
1
<?php
2
3
use Vector\Vector;
4
use Common\GlobalContainer;
5
6
/**
7
 * Class SN
8
 *
9
 * Singleton
10
 */
11
class SN {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

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

namespace YourVendor;

class YourClass { }

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

Loading history...
12
  /**
13
   * @var SN $_sn
14
   */
15
  protected static $_sn;
16
17
  /**
18
   * @var GlobalContainer $gc
19
   */
20
  public static $gc;
21
22
  /**
23
   * Основная БД для доступа к данным
24
   *
25
   * @var db_mysql $db
26
   */
27
  public static $db;
28
  public static $db_name = '';
29
30
  /**
31
   * Настройки из файла конфигурации
32
   *
33
   * @var string
34
   */
35
  public static $cache_prefix = 'sn_';
36
  public static $sn_secret_word = '';
37
38
  /**
39
   * Конфигурация игры
40
   *
41
   * @var classConfig $config
42
   */
43
  public static $config;
44
45
46
  /**
47
   * Кэш игры
48
   *
49
   * @var classCache $cache
50
   */
51
  public static $cache;
52
53
  /**
54
   * @var classLocale $lang
55
   */
56
  public static $lang;
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
79
  public static $options = array();
80
81
  /**
82
   * Is header already rendered?
83
   *
84
   * @var bool $headerRendered
85
   */
86
  public static $headerRendered = false;
87
88
  /*
89
  TODO Кэш:
90
  1. Всегда дешевле использовать процессор, чем локальную память
91
  2. Всегда дешевле использовать локальную память, чем общую память всех процессов
92
  3. Всегда дешевле использовать общую память всех процессов, чем обращаться к БД
93
94
  Кэш - многоуровневый: локальная память-общая память-БД
95
  БД может быть сверхкэширующей - см. HyperNova. Это реализуется на уровне СН-драйвера БД
96
  Предусмотреть вариант, когда уровни кэширования совпадают, например когда нет xcache и используется общая память
97
  */
98
  //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...
99
  //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...
100
101
  // 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...
102
103
  // TODO Автоматически заполнять эту таблицу. В случае кэша в памяти - делать show table при обращении к таблице
104
  public static $location_info = array(
105
    LOC_USER => array(
106
      P_TABLE_NAME => 'users',
107
      P_ID         => 'id',
108
      P_OWNER_INFO => array(),
109
    ),
110
111
    LOC_PLANET => array(
112
      P_TABLE_NAME => 'planets',
113
      P_ID         => 'id',
114
      P_OWNER_INFO => array(
115
        LOC_USER => array(
116
          P_LOCATION    => LOC_USER,
117
          P_OWNER_FIELD => 'id_owner',
118
        ),
119
      ),
120
    ),
121
122
    LOC_UNIT => array(
123
      P_TABLE_NAME => 'unit',
124
      P_ID         => 'unit_id',
125
      P_OWNER_INFO => array(
126
        LOC_USER => array(
127
          P_LOCATION    => LOC_USER,
128
          P_OWNER_FIELD => 'unit_player_id',
129
        ),
130
      ),
131
    ),
132
133
    LOC_QUE => array(
134
      P_TABLE_NAME => 'que',
135
      P_ID         => 'que_id',
136
      P_OWNER_INFO => array(
137
        array(
138
          P_LOCATION    => LOC_USER,
139
          P_OWNER_FIELD => 'que_player_id',
140
        ),
141
142
        array(
143
          P_LOCATION    => LOC_PLANET,
144
          P_OWNER_FIELD => 'que_planet_id_origin',
145
        ),
146
147
        array(
148
          P_LOCATION    => LOC_PLANET,
149
          P_OWNER_FIELD => 'que_planet_id',
150
        ),
151
      ),
152
    ),
153
154
    LOC_FLEET => array(
155
      P_TABLE_NAME => 'fleets',
156
      P_ID         => 'fleet_id',
157
      P_OWNER_INFO => array(
158
        array(
159
          P_LOCATION    => LOC_USER,
160
          P_OWNER_FIELD => 'fleet_owner',
161
        ),
162
163
        array(
164
          P_LOCATION    => LOC_USER,
165
          P_OWNER_FIELD => 'fleet_target_owner',
166
        ),
167
168
        array(
169
          P_LOCATION    => LOC_PLANET,
170
          P_OWNER_FIELD => 'fleet_start_planet_id',
171
        ),
172
173
        array(
174
          P_LOCATION    => LOC_PLANET,
175
          P_OWNER_FIELD => 'fleet_end_planet_id',
176
        ),
177
      ),
178
    ),
179
  );
180
181
//  /**
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% 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...
182
//   * @return SN
183
//   */
184
//  public static function sn() {
185
//    if (!isset(self::$_sn)) {
186
//      self::$_sn = new self();
187
//    }
188
//
189
//    return self::$_sn;
190
//  }
191
192
  public function __construct() {
193
194
  }
195
196
197
  public static function log_file($message, $spaces = 0) {
198
    if (self::$debug) {
199
      self::$debug->log_file($message, $spaces);
200
    }
201
  }
202
203
204
205
206
207
  // TODO Вынести в отдельный объект
208
209
  /**
210
   * Эта функция проверяет статус транзакции
211
   *
212
   * Это - низкоуровневая функция. В нормальном состоянии движка её сообщения никогда не будут видны
213
   *
214
   * @param null|true|false $status Должна ли быть запущена транзакция в момент проверки
215
   *   <p>null - транзакция НЕ должна быть запущена</p>
216
   *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
217
   *   <p>false - всё равно - для совместимости с $for_update</p>
218
   *
219
   * @return bool Текущий статус транзакции
220
   */
221
  public static function db_transaction_check($status = null) {
222
    $error_msg = false;
223
    if ($status && !static::$db_in_transaction) {
224
      $error_msg = 'No transaction started for current operation';
225
    } elseif ($status === null && static::$db_in_transaction) {
226
      $error_msg = 'Transaction is already started';
227
    }
228
229
    if ($error_msg) {
230
      // TODO - Убрать позже
231
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_transaction_check() - ' . $error_msg . '</h1>');
232
      $backtrace = debug_backtrace();
233
      array_shift($backtrace);
234
      pdump($backtrace);
235
      die($error_msg);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
236
    }
237
238
    return static::$db_in_transaction;
239
  }
240
241
  public static function db_transaction_start($level = '') {
242
    global $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
243
244
    static::db_transaction_check(null);
245
246
    $level ? doquery('SET TRANSACTION ISOLATION LEVEL ' . $level) : false;
247
248
    static::$transaction_id++;
249
    doquery('START TRANSACTION');
250
251
    if ($config->db_manual_lock_enabled) {
252
      $config->db_loadItem('var_db_manually_locked');
253
      $config->db_saveItem('var_db_manually_locked', SN_TIME_SQL);
254
    }
255
256
    static::$db_in_transaction = true;
257
    _SnCacheInternal::cache_locator_unset_all();
258
    _SnCacheInternal::cache_queries_unset_all();
259
260
    //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...
261
262
    return static::$transaction_id;
263
  }
264
265
  public static function db_transaction_commit() {
266
    static::db_transaction_check(true);
267
268
    _SnCacheInternal::cache_lock_unset_all();
269
    doquery('COMMIT');
270
271
    //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...
272
    static::$db_in_transaction = false;
273
274
    return static::$transaction_id++;
275
  }
276
277
  public static function db_transaction_rollback() {
278
    // 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...
279
    _SnCacheInternal::cache_lock_unset_all();
280
    doquery('ROLLBACK');
281
282
    //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...
283
    static::$db_in_transaction = false;
284
    static::$transaction_id++;
285
286
    return static::$transaction_id;
287
  }
288
289
  /**
290
   * Блокирует указанные таблицу/список таблиц
291
   *
292
   * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
293
   * <p>string - название таблицы для блокировки</p>
294
   * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p>
295
   */
296
  public static function db_lock_tables($tables) {
297
    $tables = is_array($tables) ? $tables : array($tables => '');
298
    foreach ($tables as $table_name => $condition) {
299
      self::$db->doquery("SELECT 1 FROM {{{$table_name}}}" . ($condition ? ' WHERE ' . $condition : ''));
300
    }
301
  }
302
303
  public static function db_query_select($query, $fetch = false, $skip_lock = false) {
304
    $select = strpos(strtoupper($query), 'SELECT') !== false;
305
306
    $query .= $select && $fetch ? ' LIMIT 1' : '';
307
    $query .= $select && !$skip_lock && static::db_transaction_check(false) ? ' FOR UPDATE' : '';
308
309
    $result = self::$db->doquery($query, $fetch);
310
311
    return $result;
312
  }
313
314
  public static function db_query_update($query) {
315
    return self::$db->doquery($query, false);
316
  }
317
318
  public static function db_query_delete($query) {
319
    return self::$db->doquery($query, false);
320
  }
321
322
  public static function db_query_insert($query) {
323
    return self::$db->doquery($query, false);
324
  }
325
326
  /**
327
   * Возвращает информацию о записи по её ID
328
   *
329
   * @param int       $location_type
330
   * @param int|array $record_id_unsafe
331
   *    <p>int - ID записи</p>
332
   *    <p>array - запись пользователя с установленным полем P_ID</p>
333
   *
334
   * @return array|false
335
   *    <p>false - Нет записи с указанным ID</p>
336
   *    <p>array - запись</p>
337
   */
338
  public static function db_get_record_by_id($location_type, $record_id_unsafe) {
339
    $id_field = static::$location_info[$location_type][P_ID];
340
    $record_id_safe = idval(is_array($record_id_unsafe) && isset($record_id_unsafe[$id_field]) ? $record_id_unsafe[$id_field] : $record_id_unsafe);
341
342
    return static::db_get_record_list($location_type, "`{$id_field}` = {$record_id_safe}", true, false);
343
  }
344
345
  public static function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) {
346
    $query_cache = &_SnCacheInternal::$queries[$location_type][$filter];
347
348
    if (!isset($query_cache) || $query_cache === null) {
349
      $location_info = &static::$location_info[$location_type];
350
      $id_field = $location_info[P_ID];
351
      $query_cache = array();
352
353
      if (static::db_transaction_check(false)) {
354
        // Проходим по всем родителям данной записи
355
        foreach ($location_info[P_OWNER_INFO] as $owner_data) {
356
          $owner_location_type = $owner_data[P_LOCATION];
357
          $parent_id_list = array();
358
          // Выбираем родителей данного типа и соответствующие ИД текущего типа
359
          $query = static::db_query_select(
360
            "SELECT
361
              distinct({{{$location_info[P_TABLE_NAME]}}}.{$owner_data[P_OWNER_FIELD]}) AS parent_id
362
            FROM {{{$location_info[P_TABLE_NAME]}}}" .
363
            ($filter ? ' WHERE ' . $filter : '') .
364
            ($fetch ? ' LIMIT 1' : ''),
365
            false,
366
            true
367
          );
368
369
          while ($row = db_fetch($query)) {
370
            // Исключаем из списка родительских ИД уже заблокированные записи
371
            if (!_SnCacheInternal::cache_lock_get($owner_location_type, $row['parent_id'])) {
372
              $parent_id_list[$row['parent_id']] = $row['parent_id'];
373
            }
374
          }
375
376
          // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
377
          if ($indexes_str = implode(',', $parent_id_list)) {
378
            $parent_id_field = static::$location_info[$owner_location_type][P_ID];
379
            static::db_get_record_list($owner_location_type,
380
              $parent_id_field . (count($parent_id_list) > 1 ? " IN ({$indexes_str})" : " = {$indexes_str}"), $fetch, true);
381
          }
382
        }
383
      }
384
385
      $query = static::db_query_select(
386
        "SELECT * FROM {{{$location_info[P_TABLE_NAME]}}}" . (($filter = trim($filter)) ? " WHERE {$filter}" : '')
387
      );
388
      while ($row = db_fetch($query)) {
389
        _SnCacheInternal::cache_set($location_type, $row[$id_field], $row);
390
        $query_cache[$row[$id_field]] = &_SnCacheInternal::$data[$location_type][$row[$id_field]];
391
      }
392
    }
393
394
    if ($no_return) {
395
      return true;
396
    } else {
397
      $result = false;
398
      if (is_array($query_cache)) {
399
        foreach ($query_cache as $key => $value) {
400
          $result[$key] = $value;
401
          if ($fetch) {
402
            break;
403
          }
404
        }
405
      }
406
407
      return $fetch ? (is_array($result) ? reset($result) : false) : $result;
0 ignored issues
show
introduced by
The condition is_array($result) is always false.
Loading history...
408
    }
409
  }
410
411
  public static function db_upd_record_by_id($location_type, $record_id, $set) {
412
    if (!($record_id = idval($record_id)) || !($set = trim($set))) {
413
      return false;
414
    }
415
416
    $location_info = &static::$location_info[$location_type];
417
    $id_field = $location_info[P_ID];
418
    $table_name = $location_info[P_TABLE_NAME];
419
    if ($result = static::db_query_update("UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
420
    {
421
      if (static::$db->db_affected_rows()) {
422
        // Обновляем данные только если ряд был затронут
423
        // TODO - переделать под работу со структурированными $set
424
425
        // Тут именно так, а не cache_unset - что бы в кэшах автоматически обновилась запись. Будет нужно на будущее
426
        _SnCacheInternal::$data[$location_type][$record_id] = null;
427
        // Вытаскиваем обновленную запись
428
        static::db_get_record_by_id($location_type, $record_id);
0 ignored issues
show
Bug introduced by
It seems like $record_id can also be of type double; however, parameter $record_id_unsafe of SN::db_get_record_by_id() does only seem to accept integer|array, maybe add an additional type check? ( Ignorable by Annotation )

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

428
        static::db_get_record_by_id($location_type, /** @scrutinizer ignore-type */ $record_id);
Loading history...
429
        _SnCacheInternal::cache_clear($location_type, false); // Мягкий сброс - только $queries
430
      }
431
    }
432
433
    return $result;
434
  }
435
436
  public static function db_upd_record_list($location_type, $condition, $set) {
437
    if (!($set = trim($set))) {
438
      return false;
439
    }
440
441
    $condition = trim($condition);
442
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
443
444
    if ($result = static::db_query_update("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
445
446
      if (static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
447
        // Поскольку нам неизвестно, что и как обновилось - сбрасываем кэш этого типа полностью
448
        // TODO - когда будет структурированный $condition и $set - перепаковывать данные
449
        _SnCacheInternal::cache_clear($location_type, true);
450
      }
451
    }
452
453
    return $result;
454
  }
455
456
  public static function db_ins_record($location_type, $set) {
457
    $set = trim($set);
458
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
459
    if ($result = static::db_query_insert("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
460
      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
461
      {
462
        $record_id = db_insert_id();
463
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
464
        $result = static::db_get_record_by_id($location_type, $record_id);
0 ignored issues
show
Bug introduced by
It seems like $record_id can also be of type string; however, parameter $record_id_unsafe of SN::db_get_record_by_id() does only seem to accept integer|array, maybe add an additional type check? ( Ignorable by Annotation )

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

464
        $result = static::db_get_record_by_id($location_type, /** @scrutinizer ignore-type */ $record_id);
Loading history...
465
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
466
        // TODO - когда будет поддержка изменения индексов и локаций - можно будет вызывать её
467
        _SnCacheInternal::cache_clear($location_type, false); // Мягкий сброс - только $queries
468
      }
469
    }
470
471
    return $result;
472
  }
473
474
  public static function db_del_record_by_id($location_type, $safe_record_id) {
475
    if (!($safe_record_id = idval($safe_record_id))) {
476
      return false;
477
    }
478
479
    $location_info = &static::$location_info[$location_type];
480
    $id_field = $location_info[P_ID];
481
    $table_name = $location_info[P_TABLE_NAME];
482
    if ($result = static::db_query_delete("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}")) {
483
      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
484
      {
485
        _SnCacheInternal::cache_unset($location_type, $safe_record_id);
486
      }
487
    }
488
489
    return $result;
490
  }
491
492
  public static function db_del_record_list($location_type, $condition) {
493
    if (!($condition = trim($condition))) {
494
      return false;
495
    }
496
497
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
498
499
    if ($result = static::db_query_delete("DELETE FROM `{{{$table_name}}}` WHERE {$condition}")) {
500
      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
501
      {
502
        // Обнуление кэша, потому что непонятно, что поменялось
503
        _SnCacheInternal::cache_clear($location_type);
504
      }
505
    }
506
507
    return $result;
508
  }
509
510
511
512
  public static function db_unit_time_restrictions($date = SN_TIME_NOW) {
513
    $date = is_numeric($date) ? "FROM_UNIXTIME({$date})" : "'{$date}'";
514
515
    return
516
      "(unit_time_start IS NULL OR unit_time_start <= {$date}) AND
517
    (unit_time_finish IS NULL OR unit_time_finish = '1970-01-01 03:00:00' OR unit_time_finish >= {$date})";
518
  }
519
520
  /**
521
   * @param int $user_id
522
   * @param     $location_type
523
   * @param     $location_id
524
   *
525
   * @return array|false
526
   */
527
  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. ( Ignorable by Annotation )

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

527
  public static function db_get_unit_list_by_location(/** @scrutinizer ignore-unused */ $user_id = 0, $location_type, $location_id) {

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

Loading history...
528
    if (!($location_type = idval($location_type)) || !($location_id = idval($location_id))) {
529
      return false;
530
    }
531
532
    if (!_SnCacheInternal::unit_locatorIsSet($location_type, $location_id)) {
533
      $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());
534
      if (is_array($got_data)) {
0 ignored issues
show
introduced by
The condition is_array($got_data) is always false.
Loading history...
535
        foreach ($got_data as $unit_db_id => $unitRow) {
536
          _SnCacheInternal::unit_linkLocatorToData($unitRow, $unit_db_id);
537
        }
538
      }
539
    }
540
541
    return _SnCacheInternal::unit_locatorGetAllFromLocation($location_type, $location_id);
542
  }
543
544
  /*
545
   * С $for_update === true эта функция должна вызываться только из транзакции! Все соответствующие записи в users и planets должны быть уже блокированы!
546
   *
547
   * $que_type
548
   *   !$que_type - все очереди
549
   *   QUE_XXXXXX - конкретная очередь по планете
550
   * $user_id - ID пользователя
551
   * $planet_id
552
   *   $que_type == QUE_RESEARCH - игнорируется
553
   *   null - обработка очередей планет не производится
554
   *   false/0 - обрабатываются очереди всех планет по $user_id
555
   *   (integer) - обрабатываются локальные очереди для планеты. Нужно, например, в обработчике флотов
556
   *   иначе - $que_type для указанной планеты
557
   * $for_update - true == нужно блокировать записи
558
   *
559
   * TODO Работа при !$user_id
560
   * TODO Переформатировать вывод данных, что бы можно было возвращать данные по всем планетам и юзерам в одном запросе: добавить подмассивы 'que', 'planets', 'players'
561
   *
562
   */
563
  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. ( Ignorable by Annotation )

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

563
  public static function db_que_list_by_type_location($user_id, $planet_id = null, $que_type = false, /** @scrutinizer ignore-unused */ $for_update = false) {

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

Loading history...
564
    if (!$user_id) {
565
      pdump(debug_backtrace());
566
      die('No user_id for que_get_que()');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
567
    }
568
569
    $ques = array();
570
571
    $query = array();
572
573
    if ($user_id = idval($user_id)) {
574
      $query[] = "`que_player_id` = {$user_id}";
575
    }
576
577
    if ($que_type == QUE_RESEARCH || $planet_id === null) {
578
      $query[] = "`que_planet_id` IS NULL";
579
    } elseif ($planet_id) {
580
      $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
581
    }
582
    if ($que_type) {
583
      $query[] = "`que_type` = {$que_type}";
584
    }
585
586
    $ques['items'] = static::db_get_record_list(LOC_QUE, implode(' AND ', $query));
587
588
    return que_recalculate($ques);
589
  }
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
  public static function loadFileSettings() {
668
    $dbsettings = array();
669
670
    require(SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX);
671
    //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...
672
    self::$cache_prefix = !empty($dbsettings['cache_prefix']) ? $dbsettings['cache_prefix'] : $dbsettings['prefix'];
673
    self::$db_name = $dbsettings['name'];
674
    self::$sn_secret_word = $dbsettings['secretword'];
675
676
    self::services();
677
678
    unset($dbsettings);
679
  }
680
681
  public static function init_global_objects() {
682
    global $sn_cache, $config, $debug;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
683
684
    $debug = self::$debug = self::$gc->debug;
685
    self::$db = self::$gc->db;
686
    self::$db->sn_db_connect();
687
688
    self::$user_options = new userOptions(0);
689
690
    // Initializing global 'cache' object
691
    $sn_cache = static::$cache = self::$gc->cache;
692
    $tables = SN::$db->schema()->getSnTables();
693
    empty($tables) && die('DB error - cannot find any table. Halting...');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
694
695
    // Initializing global "config" object
696
    $config = static::$config = self::$gc->config;
697
698
    // Initializing statics
699
    Vector::_staticInit(static::$config);
700
  }
701
702
  /**
703
   * @param int    $newStatus
704
   * @param string $newMessage
705
   *
706
   * @return int
707
   */
708
  public static function gameDisable($newStatus = GAME_DISABLE_REASON, $newMessage = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $newMessage is not used and could be removed. ( Ignorable by Annotation )

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

708
  public static function gameDisable($newStatus = GAME_DISABLE_REASON, /** @scrutinizer ignore-unused */ $newMessage = '') {

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

Loading history...
709
    $old_server_status = intval(self::$config->db_loadItem('game_disable'));
710
    self::$config->db_saveItem('game_disable', $newStatus);
711
712
    return $old_server_status;
713
  }
714
715
  public static function gameEnable() {
716
    self::$config->db_saveItem('game_disable', GAME_DISABLE_NONE);
717
  }
718
719
  /**
720
   * Is game disabled?
721
   *
722
   * @return bool
723
   */
724
  public static function gameIsDisabled() {
725
    return self::$config->game_disable != GAME_DISABLE_NONE;
726
  }
727
728
729
  /**
730
   * @return GlobalContainer
731
   */
732
  public static function services() {
733
    if (empty(self::$gc)) {
734
      self::$gc = new GlobalContainer(array(
735
        'cachePrefix' => self::$cache_prefix,
736
      ));
737
    }
738
739
    return self::$gc;
740
  }
741
742
}
743