Test Failed
Push — trunk ( dc8fe4...b76cfb )
by SuperNova.WS
10:59
created

SN::db_unit_time_restrictions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
crap 6
1
<?php /** @noinspection SqlResolve */
2
3
use DBAL\db_mysql;
4
use Player\userOptions;
5
use Common\Vector;
6
use Core\GlobalContainer;
7
use Unit\DBStaticUnit;
8
9
/**
10
 * Class SN
11
 *
12
 * Singleton
13
 */
14
class SN {
15
  const DB_TRANSACTION_SHOULD_NOT_BE = null;
16
  const DB_TRANSACTION_SHOULD_BE = true;
17
  const DB_TRANSACTION_WHATEVER = false;
18
  /**
19
   * Flag that something was rendered
20
   *
21
   * @var bool
22
   */
23
  public static $gSomethingWasRendered = false;
24
25
  /**
26
   * @var SN $_sn
27
   */
28
  protected static $_sn;
29
30
  /**
31
   * @var GlobalContainer $gc
32
   */
33
  public static $gc;
34
35
  /**
36
   * Основная БД для доступа к данным
37
   *
38
   * @var db_mysql $db
39
   */
40
  public static $db;
41
  public static $db_name = '';
42
43
  /**
44
   * Настройки из файла конфигурации
45
   *
46
   * @var string
47
   */
48
  public static $cache_prefix = 'sn_';
49
  public static $sn_secret_word = '';
50
51
  /**
52
   * Конфигурация игры
53
   *
54
   * @var classConfig $config
55
   */
56
  public static $config;
57
58
59
  /**
60
   * Кэш игры
61
   *
62
   * @var classCache $cache
63
   */
64
  public static $cache;
65
66
  /**
67
   * @var classLocale $lang
68
   */
69
  public static $lang;
70
71
72
  /**
73
   * @var core_auth $auth
74
   */
75
  public static $auth = null;
76
77
78
  public static $db_in_transaction = false;
79
  public static $transaction_id = 0;
80
  public static $user = array();
81
  /**
82
   * @var userOptions
83
   */
84
  public static $user_options;
85
86
  /**
87
   * @var debug $debug
88
   */
89
  public static $debug = null;
90
91
92
  public static $options = array();
93
94
  /**
95
   * Is header already rendered?
96
   *
97
   * @var bool $headerRendered
98
   */
99
  public static $headerRendered = false;
100
101
  /*
102
  TODO Кэш:
103
  1. Всегда дешевле использовать процессор, чем локальную память
104
  2. Всегда дешевле использовать локальную память, чем общую память всех процессов
105
  3. Всегда дешевле использовать общую память всех процессов, чем обращаться к БД
106
107
  Кэш - многоуровневый: локальная память-общая память-БД
108
  БД может быть сверхкэширующей - см. HyperNova. Это реализуется на уровне СН-драйвера БД
109
  Предусмотреть вариант, когда уровни кэширования совпадают, например когда нет xcache и используется общая память
110
  */
111
  //public static $cache; // Объект-кэшер - либо встроенная память, либо мемкэш с блокировками - находится внутри $db!!!!
112
  //public static $db; // Объект-БД - либок кэшер с блокировками, либо БД
113
114
  // protected static $info = array(); // Кэш информации - инфо о юнитах, инфо о группах итд
115
116
  // TODO Автоматически заполнять эту таблицу. В случае кэша в памяти - делать show table при обращении к таблице
117
  public static $location_info = array(
118
    LOC_USER => array(
119
      P_TABLE_NAME => 'users',
120
      P_ID         => 'id',
121
      P_OWNER_INFO => array(),
122
    ),
123
124
    LOC_PLANET => array(
125
      P_TABLE_NAME => 'planets',
126
      P_ID         => 'id',
127
      P_OWNER_INFO => array(
128
        LOC_USER => array(
129
          P_LOCATION    => LOC_USER,
130
          P_OWNER_FIELD => 'id_owner',
131
        ),
132
      ),
133
    ),
134
135
    LOC_UNIT => array(
136
      P_TABLE_NAME => 'unit',
137
      P_ID         => 'unit_id',
138
      P_OWNER_INFO => array(
139
        LOC_USER => array(
140
          P_LOCATION    => LOC_USER,
141
          P_OWNER_FIELD => 'unit_player_id',
142
        ),
143
      ),
144
    ),
145
146
    LOC_QUE => array(
147
      P_TABLE_NAME => 'que',
148
      P_ID         => 'que_id',
149
      P_OWNER_INFO => array(
150
        array(
151
          P_LOCATION    => LOC_USER,
152
          P_OWNER_FIELD => 'que_player_id',
153
        ),
154
155
        array(
156
          P_LOCATION    => LOC_PLANET,
157
          P_OWNER_FIELD => 'que_planet_id_origin',
158
        ),
159
160
        array(
161
          P_LOCATION    => LOC_PLANET,
162
          P_OWNER_FIELD => 'que_planet_id',
163
        ),
164
      ),
165
    ),
166
167
    LOC_FLEET => array(
168
      P_TABLE_NAME => 'fleets',
169
      P_ID         => 'fleet_id',
170
      P_OWNER_INFO => array(
171
        array(
172
          P_LOCATION    => LOC_USER,
173
          P_OWNER_FIELD => 'fleet_owner',
174
        ),
175
176
        array(
177
          P_LOCATION    => LOC_USER,
178
          P_OWNER_FIELD => 'fleet_target_owner',
179
        ),
180
181
        array(
182
          P_LOCATION    => LOC_PLANET,
183
          P_OWNER_FIELD => 'fleet_start_planet_id',
184
        ),
185
186
        array(
187
          P_LOCATION    => LOC_PLANET,
188
          P_OWNER_FIELD => 'fleet_end_planet_id',
189
        ),
190
      ),
191
    ),
192
  );
193
194
  /**
195
   * @var callable[] $afterInit
196
   */
197
  public static $afterInit = [];
198
199
//  /**
200
//   * @return SN
201
//   */
202
//  public static function sn() {
203
//    if (!isset(self::$_sn)) {
204
//      self::$_sn = new self();
205
//    }
206
//
207
//    return self::$_sn;
208
//  }
209
210
  public function __construct() {
211
212
  }
213
214
215
  public static function log_file($message, $spaces = 0) {
216
    if (self::$debug) {
217
      self::$debug->log_file($message, $spaces);
218
    }
219
  }
220
221
222
223
224
225
  // TODO Вынести в отдельный объект
226
227
  /**
228
   * Эта функция проверяет статус транзакции
229
   *
230
   * Это - низкоуровневая функция. В нормальном состоянии движка её сообщения никогда не будут видны
231
   *
232
   * @param null|true|false $status Должна ли быть запущена транзакция в момент проверки
233
   *   <p>null - транзакция НЕ должна быть запущена</p>
234
   *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
235
   *   <p>false - всё равно - для совместимости с $for_update</p>
236
   *
237
   * @return bool Текущий статус транзакции
238
   */
239
  public static function db_transaction_check($status = self::DB_TRANSACTION_WHATEVER) {
240
    $error_msg = false;
241
    if ($status && !static::$db_in_transaction) {
242
      $error_msg = 'No transaction started for current operation';
243
    } elseif ($status === null && static::$db_in_transaction) {
244
      $error_msg = 'Transaction is already started';
245
    }
246
247
    if ($error_msg) {
248
      // TODO - Убрать позже
249
      print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_transaction_check() - ' . $error_msg . '</h1>');
250
      $backtrace = debug_backtrace();
251
      array_shift($backtrace);
252
      pdump($backtrace);
253
      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...
254
    }
255
256
    return static::$db_in_transaction;
257
  }
258
259
  public static function db_transaction_start($level = '') {
260
    static::db_transaction_check(null);
261
262
    static::$gc->db->transactionStart($level);
263
264
    static::$transaction_id++;
265
266
    if (static::$config->db_manual_lock_enabled) {
267
      static::$config->db_loadItem('var_db_manually_locked');
268
      static::$config->db_saveItem('var_db_manually_locked', SN_TIME_SQL);
269
    }
270
271
    static::$db_in_transaction = true;
272
    DBStaticUnit::cache_clear();
273
274
    //print('<hr/>TRANSACTION START id' . static::$transaction_id . '<br />');
275
276
    return static::$transaction_id;
277
  }
278
279
  public static function db_transaction_commit() {
280
    static::db_transaction_check(true);
281
282
    DBStaticUnit::cache_clear();
283
    SN::$gc->db->transactionCommit();
284
285
    //print('<br/>TRANSACTION COMMIT id' . static::$transaction_id . '<hr />');
286
    static::$db_in_transaction = false;
287
288
    return static::$transaction_id++;
289
  }
290
291
  public static function db_transaction_rollback() {
292
    // static::db_transaction_check(true); // TODO - вообще-то тут тоже надо проверять есть ли транзакция
293
    DBStaticUnit::cache_clear();
294
295
    SN::$gc->db->transactionRollback();
296
297
    //print('<br/>TRANSACTION ROLLBACK id' . static::$transaction_id . '<hr />');
298
    static::$db_in_transaction = false;
299
    static::$transaction_id++;
300
301
    return static::$transaction_id;
302
  }
303
304
  /**
305
   * Блокирует указанные таблицу/список таблиц
306
   *
307
   * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
308
   * <p>string - название таблицы для блокировки</p>
309
   * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p>
310
   */
311
  public static function db_lock_tables($tables) {
312
    $tables = is_array($tables) ? $tables : array($tables => '');
313
    foreach ($tables as $table_name => $condition) {
314
      self::$db->doquery(
315
        "SELECT 1 FROM {{{$table_name}}}" . ($condition ? ' WHERE ' . $condition : '')
316
      );
317
    }
318
  }
319
320
  /**
321
   * @param      $query
322
   * @param bool $fetch
323
   * @param bool $skip_lock
324
   *
325
   * @return array|bool|mysqli_result|null
326
   * @deprecated
327
   */
328
  public static function db_query_select($query, $fetch = false, $skip_lock = false) {
329
    $select = strpos(strtoupper($query), 'SELECT') !== false;
330
331
    $query .= $select && $fetch ? ' LIMIT 1' : '';
332
    $query .= $select && !$skip_lock && static::db_transaction_check(false) ? ' FOR UPDATE' : '';
333
334
    $result = self::$db->doquery($query, $fetch);
335
336
    return $result;
337
  }
338
339
  /**
340
   * @param $query
341
   *
342
   * @return array|bool|mysqli_result|null
343
   * @deprecated
344
   */
345
  public static function db_query_update($query) {
346
    return self::$db->doquery($query, false);
347
  }
348
349
  /**
350
   * @param $query
351
   *
352
   * @return array|bool|mysqli_result|null
353
   * @deprecated
354
   */
355
  public static function db_query_delete($query) {
356
    return self::$db->doquery($query, false);
357
  }
358
359
  /**
360
   * @param $query
361
   *
362
   * @return array|bool|mysqli_result|null
363
   * @deprecated
364
   */
365
  public static function db_query_insert($query) {
366
    return self::$db->doquery($query, false);
367
  }
368
369
  /**
370
   * Возвращает информацию о записи по её ID
371
   *
372
   * @param int       $location_type
373
   * @param int|array $record_id_unsafe
374
   *    <p>int - ID записи</p>
375
   *    <p>array - запись пользователя с установленным полем P_ID</p>
376
   *
377
   * @return array|false
378
   *    <p>false - Нет записи с указанным ID</p>
379
   *    <p>array - запись</p>
380
   */
381
  public static function db_get_record_by_id($location_type, $record_id_unsafe) {
382
    $id_field = static::$location_info[$location_type][P_ID];
383
    $record_id_safe = idval(is_array($record_id_unsafe) && isset($record_id_unsafe[$id_field]) ? $record_id_unsafe[$id_field] : $record_id_unsafe);
384
385
    return static::db_get_record_list($location_type, "`{$id_field}` = {$record_id_safe}", true, false);
386
  }
387
388
  public static function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) {
389
    $location_info = &static::$location_info[$location_type];
390
    $id_field = $location_info[P_ID];
391
//    $query_cache = [];
392
//
393
//    // Always - disabled query cache
394
//    {
395
//      if (static::db_transaction_check(false)) {
396
//        // Проходим по всем родителям данной записи
397
//        foreach ($location_info[P_OWNER_INFO] as $owner_data) {
398
//          $owner_location_type = $owner_data[P_LOCATION];
399
//          $parent_id_list = [];
400
//          // Выбираем родителей данного типа и соответствующие ИД текущего типа
401
//          $query = static::db_query_select(
402
//            "SELECT
403
//              distinct({{{$location_info[P_TABLE_NAME]}}}.{$owner_data[P_OWNER_FIELD]}) AS parent_id
404
//            FROM {{{$location_info[P_TABLE_NAME]}}}" .
405
//            ($filter ? ' WHERE ' . $filter : '') .
406
//            ($fetch ? ' LIMIT 1' : ''),
407
//            false,
408
//            true
409
//          );
410
//
411
//          while ($row = db_fetch($query)) {
412
//            // Исключаем из списка родительских ИД уже заблокированные записи
413
//            if (!_SnCacheInternal::cache_lock_get($owner_location_type, $row['parent_id'])) {
414
//              $parent_id_list[$row['parent_id']] = $row['parent_id'];
415
//            }
416
//          }
417
//
418
//          // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
419
//          if ($indexes_str = implode(',', $parent_id_list)) {
420
//            $parent_id_field = static::$location_info[$owner_location_type][P_ID];
421
//            static::db_get_record_list($owner_location_type,
422
//              $parent_id_field . (count($parent_id_list) > 1 ? " IN ({$indexes_str})" : " = {$indexes_str}"), $fetch, true);
423
//          }
424
//        }
425
//      }
426
427
      $result = false;
428
429
      $query = static::db_query_select(
0 ignored issues
show
Deprecated Code introduced by
The function SN::db_query_select() has been deprecated. ( Ignorable by Annotation )

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

429
      $query = /** @scrutinizer ignore-deprecated */ static::db_query_select(
Loading history...
430
        "SELECT * FROM {{{$location_info[P_TABLE_NAME]}}}" . (($filter = trim($filter)) ? " WHERE {$filter}" : '')
431
      );
432
      while ($row = db_fetch($query)) {
433
        $result[$row[$id_field]] = $row;
434
        if ($fetch) {
435
          break;
436
        }
437
      }
438
//    }
439
440
    if ($no_return) {
441
      return true;
442
    } else {
443
      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...
444
    }
445
  }
446
447
  public static function db_upd_record_by_id($location_type, $record_id, $set) {
448
    if (!($record_id = idval($record_id)) || !($set = trim($set))) {
449
      return false;
450
    }
451
452
    $location_info = &static::$location_info[$location_type];
453
    $id_field = $location_info[P_ID];
454
    $table_name = $location_info[P_TABLE_NAME];
455
    if ($result = static::db_query_update("UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
0 ignored issues
show
Deprecated Code introduced by
The function SN::db_query_update() has been deprecated. ( Ignorable by Annotation )

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

455
    if ($result = /** @scrutinizer ignore-deprecated */ static::db_query_update("UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
Loading history...
456
    {
457
      if (static::$db->db_affected_rows()) {
458
        // Обновляем данные только если ряд был затронут
459
        DBStaticUnit::cache_clear();
460
      }
461
    }
462
463
    return $result;
464
  }
465
466
  public static function db_upd_record_list($location_type, $condition, $set) {
467
    if (!($set = trim($set))) {
468
      return false;
469
    }
470
471
    $condition = trim($condition);
472
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
473
474
    if ($result = static::db_query_update("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
0 ignored issues
show
Deprecated Code introduced by
The function SN::db_query_update() has been deprecated. ( Ignorable by Annotation )

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

474
    if ($result = /** @scrutinizer ignore-deprecated */ static::db_query_update("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
Loading history...
475
476
      if (static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
477
        // Поскольку нам неизвестно, что и как обновилось - сбрасываем кэш этого типа полностью
478
        DBStaticUnit::cache_clear();
479
      }
480
    }
481
482
    return $result;
483
  }
484
485
  public static function db_ins_record($location_type, $set) {
486
    $set = trim($set);
487
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
488
    if ($result = static::db_query_insert("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
0 ignored issues
show
Deprecated Code introduced by
The function SN::db_query_insert() has been deprecated. ( Ignorable by Annotation )

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

488
    if ($result = /** @scrutinizer ignore-deprecated */ static::db_query_insert("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
Loading history...
489
      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
490
      {
491
        $record_id = SN::$db->db_insert_id();
492
        // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
493
        $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 array|integer, 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

493
        $result = static::db_get_record_by_id($location_type, /** @scrutinizer ignore-type */ $record_id);
Loading history...
494
        // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
495
        DBStaticUnit::cache_clear();
496
      }
497
    }
498
499
    return $result;
500
  }
501
502
  public static function db_del_record_by_id($location_type, $safe_record_id) {
503
    if (!($safe_record_id = idval($safe_record_id))) {
504
      return false;
505
    }
506
507
    $location_info = &static::$location_info[$location_type];
508
    $id_field = $location_info[P_ID];
509
    $table_name = $location_info[P_TABLE_NAME];
510
    if ($result = static::db_query_delete("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}")) {
0 ignored issues
show
Deprecated Code introduced by
The function SN::db_query_delete() has been deprecated. ( Ignorable by Annotation )

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

510
    if ($result = /** @scrutinizer ignore-deprecated */ static::db_query_delete("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}")) {
Loading history...
511
      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
512
      {
513
        DBStaticUnit::cache_clear();
514
      }
515
    }
516
517
    return $result;
518
  }
519
520
  public static function db_del_record_list($location_type, $condition) {
521
    if (!($condition = trim($condition))) {
522
      return false;
523
    }
524
525
    $table_name = static::$location_info[$location_type][P_TABLE_NAME];
526
527
    if ($result = static::db_query_delete("DELETE FROM `{{{$table_name}}}` WHERE {$condition}")) {
0 ignored issues
show
Deprecated Code introduced by
The function SN::db_query_delete() has been deprecated. ( Ignorable by Annotation )

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

527
    if ($result = /** @scrutinizer ignore-deprecated */ static::db_query_delete("DELETE FROM `{{{$table_name}}}` WHERE {$condition}")) {
Loading history...
528
      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
529
      {
530
        // Обнуление кэша, потому что непонятно, что поменялось
531
        DBStaticUnit::cache_clear();
532
      }
533
    }
534
535
    return $result;
536
  }
537
538
539
  /*
540
   * С $for_update === true эта функция должна вызываться только из транзакции! Все соответствующие записи в users и planets должны быть уже блокированы!
541
   *
542
   * $que_type
543
   *   !$que_type - все очереди
544
   *   QUE_XXXXXX - конкретная очередь по планете
545
   * $user_id - ID пользователя
546
   * $planet_id
547
   *   $que_type == QUE_RESEARCH - игнорируется
548
   *   null - обработка очередей планет не производится
549
   *   false/0 - обрабатываются очереди всех планет по $user_id
550
   *   (integer) - обрабатываются локальные очереди для планеты. Нужно, например, в обработчике флотов
551
   *   иначе - $que_type для указанной планеты
552
   * $for_update - true == нужно блокировать записи
553
   *
554
   * TODO Работа при !$user_id
555
   * TODO Переформатировать вывод данных, что бы можно было возвращать данные по всем планетам и юзерам в одном запросе: добавить подмассивы 'que', 'planets', 'players'
556
   *
557
   */
558
  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

558
  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...
559
    if (!$user_id) {
560
      pdump(debug_backtrace());
561
      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...
562
    }
563
564
    $ques = array();
565
566
    $query = array();
567
568
    if ($user_id = idval($user_id)) {
569
      $query[] = "`que_player_id` = {$user_id}";
570
    }
571
572
    if ($que_type == QUE_RESEARCH || $planet_id === null) {
573
      $query[] = "`que_planet_id` IS NULL";
574
    } elseif ($planet_id) {
575
      $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
576
    }
577
    if ($que_type) {
578
      $query[] = "`que_type` = {$que_type}";
579
    }
580
581
    $ques['items'] = static::db_get_record_list(LOC_QUE, implode(' AND ', $query));
582
583
    return que_recalculate($ques);
584
  }
585
586
587
588
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
  public static function loadFileSettings() {
663
    $dbsettings = array();
664
665
    require(SN_CONFIG_PATH);
666
    //self::$db_prefix = $dbsettings['prefix'];
667
    self::$cache_prefix = !empty($dbsettings['cache_prefix']) ? $dbsettings['cache_prefix'] : $dbsettings['prefix'];
668
    self::$db_name = $dbsettings['name'];
669
    self::$sn_secret_word = $dbsettings['secretword'];
670
671
    self::services();
672
673
    unset($dbsettings);
674
  }
675
676
  public static function init_global_objects() {
677
    global $sn_cache, $config, $debug;
678
679
    $debug = self::$debug = self::$gc->debug;
680
    self::$db = self::$gc->db;
681
    self::$db->sn_db_connect();
682
683
    self::$user_options = new userOptions(0);
684
685
    // Initializing global `cache` object
686
    $sn_cache = static::$cache = self::$gc->cache;
687
    $tables = SN::$db->schema()->getSnTables();
688
    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...
689
690
    // Initializing global `config` object
691
    $config = static::$config = self::$gc->config;
692
693
    // Initializing statics
694
    Vector::_staticInit(static::$config);
695
696
    // After init callbacks
697
    foreach (static::$afterInit as $callback) {
698
      if (is_callable($callback)) {
699
        $callback();
700
      }
701
    }
702
  }
703
704
  /**
705
   * @param int    $newStatus
706
   * @param string $newMessage
707
   *
708
   * @return int
709
   */
710
  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

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