Completed
Push — trunk ( 91a948...0e7a2e )
by SuperNova.WS
05:44
created

FleetDispatcher::flt_flyingFleetsSort()   B

Complexity

Conditions 8
Paths 128

Size

Total Lines 15
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
cc 8
eloc 5
nc 128
nop 2
dl 0
loc 15
ccs 0
cts 8
cp 0
crap 72
rs 7
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by Gorlum 15.06.2017 4:12
4
 */
5
6
namespace Fleet;
7
8
use classConfig;
9
use debug;
10
use DBAL\OldDbChangeSet;
11
use Planet\DBStaticPlanet;
12
use SN;
13
14
/**
15
 * Class Fleet\FleetDispatcher
16
 *
17
 */
18
class FleetDispatcher {
19
  /**
20
   * @var \Common\GlobalContainer $gc
21
   */
22
  protected $gc;
23
24
  /**
25
   * @var classConfig $gameConfig
26
   */
27
  protected $gameConfig;
28
29
  /**
30
   * @var debug $debug
31
   */
32
  protected $debug;
33
34
  /**
35
   * List of timed events
36
   *
37
   * [
38
   *   'start'
39
   *   'finish'
40
   * ]
41
   *
42
   * @var float[] $timers
43
   */
44
  protected $timers;
45
46
47
  public function __construct(\Common\GlobalContainer $gc) {
48
    $this->gc = $gc;
49
50
    $this->gameConfig = $gc->config;
51
    $this->debug = $gc->debug;
52
  }
53
54
  public function dispatch() {
55
    if (
56
      SN::$options[PAGE_OPTION_FLEET_UPDATE_SKIP]
57
      ||
58
      SN::gameIsDisabled()
59
      ||
60
      !$this->getLock()
61
    ) {
62
      return;
63
    }
64
65
    $this->flt_flying_fleet_handler();
66
67
    $this->releaseLock();
68
69
    set_time_limit(60);
70
  }
71
72
73
  /**
74
   * @return bool
75
   */
76
  protected function getLock() {
77
    sn_db_transaction_start();
78
79
    // Watchdog timer
80
    if ($this->gameConfig->db_loadItem('fleet_update_lock')) {
81
//      var_dump($this->gameConfig->db_loadItem('fleet_update_lock'));
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...
82
//      var_dump(SN_TIME_NOW - strtotime($this->gameConfig->fleet_update_lock));
83
//      if (SN_TIME_NOW - strtotime($this->gameConfig->fleet_update_lock) <= mt_rand(90, 120)) {
84
      if (SN_TIME_NOW - strtotime($this->gameConfig->fleet_update_lock) <= mt_rand(20, 40)) {
85
        sn_db_transaction_rollback();
86
87
        return false;
88
      } else {
89
        $this->debug->warning('Fleet dispatcher was locked too long - watchdog unlocked', 'FFH Error', 504);
90
      }
91
    }
92
93
    $this->gameConfig->db_saveItem('fleet_update_last', SN_TIME_SQL);
94
    $this->gameConfig->db_saveItem('fleet_update_lock', SN_TIME_SQL);
95
    sn_db_transaction_commit();
96
97
    return true;
98
  }
99
100
  protected function releaseLock() {
101
    sn_db_transaction_start();
102
    $this->gameConfig->db_saveItem('fleet_update_lock', '');
103
    sn_db_transaction_commit();
104
  }
105
106
  /**
107
   * Gets active fleets on current tick for Flying Fleet Handler
108
   *
109
   * @return array
110
   */
111
  protected function fleet_list_current_tick() {
112
    return db_fleet_list(
113
      "
114
    (`fleet_start_time` <= " . SN_TIME_NOW . " AND `fleet_mess` = 0)
115
    OR
116
    (`fleet_end_stay` <= " . SN_TIME_NOW . " AND `fleet_end_stay` > 0 AND `fleet_mess` = 0)
117
    OR
118
    (`fleet_end_time` <= " . SN_TIME_NOW . ")"
119
      , DB_SELECT_PLAIN
120
    );
121
  }
122
123
124
  // ------------------------------------------------------------------
125
  protected function flt_flying_fleet_handler() {
126
    /*
127
128
    [*] Нужно ли заворачивать ВСЕ в одну транзакцию?
129
        С одной стороны - да, что бы данные были гарантированно на момент снапшота
130
        С другой стороны - нет, потому что при большой активности это все будет блокировать слишком много рядов, да и таймаут будет большой для ожидания всего разлоченного
131
        Стоит завернуть каждую миссию отдельно? Это сильно увеличит количество запросов, зато так же сильно снизит количество блокировок.
132
133
        Resume: НЕТ! Надо оставить все в одной транзакции! Так можно будет поддерживать consistency кэша. Там буквально сантисекунды блокировки
134
135
    [*] Убрать кэшированние данных о пользователях и планета. Офигенно освободит память - проследить!
136
        НЕТ! Считать, скольким флотам нужна будет инфа и кэшировать только то, что используется больше раза!
137
        Заодно можно будет исключить перересчет очередей/ресурсов - сильно ускорит дело!
138
        Особенно будет актуально, когда все бонусы будут в одной таблице
139
        Ну и никто не заставляет как сейчас брать ВСЕ из таблицы - только по полям. Гемор, но не сильный - сделать запрос по группам sn_data
140
        И писать в БД только один раз результат
141
142
    [*] Нужно ли на этом этапе знать полную информацию о флотах?
143
        Заблокировать флоты можно и неполным запросом. Блокировка флотов - это не страшно. Ну, не пройдет одна-две отмены - так никто и не гарантировал реалтайма!
144
        С одной стороны - да, уменьшит количество запросов
145
        С другой стооны - расход памяти
146
        Все равно надо будет знать полную инфу о флоте в момент обработки
147
148
    [*] Сделать тестовую БД для расчетов
149
150
    [*] Но не раньше, чем переписать все миссии
151
152
    */
153
    global $config, $debug, $lang;
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...
154
155
    $workBegin = microtime(true);
156
//log_file('Начинаем обсчёт флотов');
157
158
//log_file('Обсчёт ракет');
159
    sn_db_transaction_start();
160
    coe_o_missile_calculate();
161
    sn_db_transaction_commit();
162
163
    $fleet_list = array();
164
    $fleet_event_list = array();
165
    $missions_used = array();
166
167
    $fleet_list_current_tick = $this->fleet_list_current_tick();
168
    foreach ($fleet_list_current_tick as $fleet_row) {
169
      set_time_limit(15);
170
      // TODO - Унифицировать код с темплейтным разбором эвентов на планете!
171
      $fleet_list[$fleet_row['fleet_id']] = $fleet_row;
172
      $missions_used[$fleet_row['fleet_mission']] = 1;
173
      if ($fleet_row['fleet_start_time'] <= SN_TIME_NOW && $fleet_row['fleet_mess'] == 0) {
174
        $fleet_event_list[] = array(
175
          'fleet_row'   => &$fleet_list[$fleet_row['fleet_id']],
176
          'fleet_time'  => $fleet_list[$fleet_row['fleet_id']]['fleet_start_time'],
177
          'fleet_event' => EVENT_FLT_ARRIVE,
178
        );
179
      }
180
181
      if ($fleet_row['fleet_end_stay'] > 0 && $fleet_row['fleet_end_stay'] <= SN_TIME_NOW && $fleet_row['fleet_mess'] == 0) {
182
        $fleet_event_list[] = array(
183
          'fleet_row'   => &$fleet_list[$fleet_row['fleet_id']],
184
          'fleet_time'  => $fleet_list[$fleet_row['fleet_id']]['fleet_end_stay'],
185
          'fleet_event' => EVENT_FLT_ACOMPLISH,
186
        );
187
      }
188
189
      if ($fleet_row['fleet_end_time'] <= SN_TIME_NOW) {
190
        $fleet_event_list[] = array(
191
          'fleet_row'   => &$fleet_list[$fleet_row['fleet_id']],
192
          'fleet_time'  => $fleet_list[$fleet_row['fleet_id']]['fleet_end_time'],
193
          'fleet_event' => EVENT_FLT_RETURN,
194
        );
195
      }
196
    }
197
198
    set_time_limit(5);
199
//log_file('Сортировка и подгрузка модулей');
200
    uasort($fleet_event_list, array($this, 'flt_flyingFleetsSort'));
201
//  unset($fleets_query);
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
202
203
// TODO: Грузить только используемые модули из $missions_used
204
    $mission_files = array(
205
      MT_ATTACK  => 'flt_mission_attack',
206
      MT_AKS     => 'flt_mission_attack',
207
      // MT_DESTROY => 'flt_mission_destroy.php',
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
208
      MT_DESTROY => 'flt_mission_attack',
209
210
      MT_TRANSPORT => 'flt_mission_transport',
211
      MT_RELOCATE  => 'flt_mission_relocate',
212
      MT_HOLD      => 'flt_mission_hold',
213
      MT_SPY       => '',
214
      MT_COLONIZE  => 'flt_mission_colonize',
215
      MT_RECYCLE   => 'flt_mission_recycle',
216
//    MT_MISSILE => 'flt_mission_missile.php',
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
217
      MT_EXPLORE   => 'flt_mission_explore',
218
    );
219
    foreach ($missions_used as $mission_id => $cork) {
220
      if (empty($mission_files[$mission_id])) {
221
        continue;
222
      }
223
224
      require_once(SN_ROOT_PHYSICAL . "includes/includes/{$mission_files[$mission_id]}" . DOT_PHP_EX);
225
    }
226
227
228
//log_file('Обработка миссий');
229
    $lastEventBegin = microtime(true);
230
    $lastMission = MT_NONE;
231
    $eventsProcessed = 0;
232
    $lastEvent = EVENT_FLEET_NONE;
233
234
    $sn_groups_mission = sn_get_groups('missions');
235
    foreach ($fleet_event_list as $fleet_event) {
236
      $lastEventEnd = microtime(true);
237
      // Watchdog timer
238
      // If flying fleet handler works more then 10 seconds - stopping it
239
      // Let next run handle rest of fleets
240
      $workTime = microtime(true) - $workBegin;
241
      if ($workTime > GAME_FLEET_HANDLER_MAX_TIME) {
242
        $debug->warning(sprintf(
243
          'Flying fleet handler works %1$s (> %2$s) seconds - skip rest. Processed %3$d events. Last event: mission %4$s event %6$s (%5$ss)',
244
          number_format($workTime, 4),
245
          GAME_FLEET_HANDLER_MAX_TIME,
246
          $eventsProcessed,
247
          $lang['type_mission'][$lastMission],
248
          number_format($lastEventEnd - $lastEventBegin, 4),
249
          $lang['fleet_events'][$lastEvent]
250
        ),
251
          'FFH Warning',
252
          504
253
        );
254
        break;
255
      }
256
257
      // TODO: Указатель тут потом сделать
258
      // TODO: СЕЙЧАС НАДО ПРОВЕРЯТЬ ПО БАЗЕ - А ЖИВОЙ ЛИ ФЛОТ?!
259
      $fleet_row = $fleet_event['fleet_row'];
260
      if (!$fleet_row) {
261
        // Fleet was destroyed in course of previous actions
262
        continue;
263
      }
264
265
      $lastEventBegin = microtime(true);
266
      $lastMission = $fleet_row['fleet_mission'];
267
      $lastEvent = $fleet_event['fleet_event'];
268
      $eventsProcessed++;
269
270
//log_file('Миссия');
271
      // TODO Обернуть всё в транзакции. Начинать надо заранее, блокируя все таблицы внутренним локом SELECT 1 FROM {{users}}
272
      sn_db_transaction_start();
273
      // а текущее время
274
      $config->db_saveItem('fleet_update_last', date(FMT_DATE_TIME_SQL, time()));
275
276
      $mission_data = $sn_groups_mission[$fleet_row['fleet_mission']];
277
      // Формируем запрос, блокирующий сразу все нужные записи
278
279
      db_fleet_lock_flying($fleet_row['fleet_id'], $mission_data);
280
281
//    $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE fleet_id = {$fleet_row['fleet_id']} FOR UPDATE", true);
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...
282
      $fleet_row = db_fleet_get($fleet_row['fleet_id']);
283
      if (!$fleet_row || empty($fleet_row)) {
284
        // Fleet was destroyed in course of previous actions
285
        sn_db_transaction_commit();
286
        continue;
287
      }
288
289
      if ($fleet_event['fleet_event'] == EVENT_FLT_RETURN) {
290
        // Fleet returns to planet
291
        RestoreFleetToPlanet($fleet_row, true, false, true);
0 ignored issues
show
Deprecated Code introduced by
The function RestoreFleetToPlanet() 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

291
        /** @scrutinizer ignore-deprecated */ RestoreFleetToPlanet($fleet_row, true, false, true);
Loading history...
292
        sn_db_transaction_commit();
293
        continue;
294
      }
295
296
      if ($fleet_event['fleet_event'] == EVENT_FLT_ARRIVE && $fleet_row['fleet_mess'] != 0) {
297
        // При событии EVENT_FLT_ARRIVE флот всегда должен иметь fleet_mess == 0
298
        // В противном случае это означает, что флот уже был обработан ранее - например, при САБе
299
        sn_db_transaction_commit();
300
        continue;
301
      }
302
303
      // TODO: Здесь тоже указатели
304
      // TODO: Кэширование
305
      // TODO: Выбирать только нужные поля
306
307
      // шпионаж не дает нормальный ID fleet_end_planet_id 'dst_planet'
308
      $mission_data = array(
309
        'fleet'       => &$fleet_row,
310
        'dst_user'    => $mission_data['dst_user'] || $mission_data['dst_planet'] ? db_user_by_id($fleet_row['fleet_target_owner'], true) : null,
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() 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

310
        'dst_user'    => $mission_data['dst_user'] || $mission_data['dst_planet'] ? /** @scrutinizer ignore-deprecated */ db_user_by_id($fleet_row['fleet_target_owner'], true) : null,
Loading history...
311
        // TODO 'dst_planet' => $mission_data['dst_planet'] ? db_planet_by_id($fleet_row['fleet_end_planet_id'], true) : null,
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...
312
        'dst_planet'  => $mission_data['dst_planet'] ? DBStaticPlanet::db_planet_by_vector($fleet_row, 'fleet_end_', true, '`id`, `id_owner`, `name`') : null,
313
        'src_user'    => $mission_data['src_user'] || $mission_data['src_planet'] ? db_user_by_id($fleet_row['fleet_owner'], true) : null,
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() 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

313
        'src_user'    => $mission_data['src_user'] || $mission_data['src_planet'] ? /** @scrutinizer ignore-deprecated */ db_user_by_id($fleet_row['fleet_owner'], true) : null,
Loading history...
314
        // TODO 'src_planet' => $mission_data['src_planet'] ? db_planet_by_id($fleet_row['fleet_start_planet_id'], true) : null,
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...
315
        'src_planet'  => $mission_data['src_planet'] ? DBStaticPlanet::db_planet_by_vector($fleet_row, 'fleet_start_', true, '`id`, `id_owner`, `name`') : null,
316
        'fleet_event' => $fleet_event['fleet_event'],
317
      );
318
319
      if ($mission_data['dst_planet']) {
320
        // $mission_data['dst_planet'] = sys_o_get_updated($mission_data['dst_user'], $mission_data['dst_planet']['id'], $fleet_row['fleet_start_time']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% 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...
321
        if ($mission_data['dst_planet']['id_owner']) {
322
          $mission_data['dst_planet'] = sys_o_get_updated($mission_data['dst_planet']['id_owner'], $mission_data['dst_planet']['id'], $fleet_row['fleet_start_time']);
323
        }
324
        $mission_data['dst_user'] = $mission_data['dst_user'] ? $mission_data['dst_planet']['user'] : null;
325
        $mission_data['dst_planet'] = $mission_data['dst_planet']['planet'];
326
      }
327
328
      switch ($fleet_row['fleet_mission']) {
329
        // Для боевых атак нужно обновлять по САБу и по холду - таки надо возвращать данные из обработчика миссий!
330
        case MT_AKS:
331
        case MT_ATTACK:
332
        case MT_DESTROY:
333
          $attack_result = flt_mission_attack($mission_data);
0 ignored issues
show
Unused Code introduced by
The assignment to $attack_result is dead and can be removed.
Loading history...
334
          $mission_result = CACHE_COMBAT;
0 ignored issues
show
Unused Code introduced by
The assignment to $mission_result is dead and can be removed.
Loading history...
335
        break;
336
337
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% 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...
338
        case MT_DESTROY:
339
          $attack_result = flt_mission_destroy($mission_data);
340
          $mission_result = CACHE_COMBAT;
341
        break;
342
        */
343
344
        case MT_TRANSPORT:
345
          $mission_result = flt_mission_transport($mission_data);
346
        break;
347
348
        case MT_HOLD:
349
          $mission_result = flt_mission_hold($mission_data);
350
        break;
351
352
        case MT_RELOCATE:
353
          $mission_result = flt_mission_relocate($mission_data);
354
        break;
355
356
        case MT_EXPLORE:
357
          $mission_result = flt_mission_explore($mission_data);
358
//          $theMission = \Fleet\MissionExplore::buildFromArray($mission_data);
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...
359
//          $theMission->process();
360
//
361
//          unset($theMission);
362
        break;
363
364
        case MT_RECYCLE:
365
          $mission_result = flt_mission_recycle($mission_data);
366
        break;
367
368
        case MT_COLONIZE:
369
          $mission_result = flt_mission_colonize($mission_data);
370
        break;
371
372
        case MT_SPY:
373
          require_once(SN_ROOT_PHYSICAL . 'includes/includes/coe_simulator_helpers.php');
374
375
          $theMission = \Fleet\MissionEspionage::buildFromArray($mission_data);
376
          $theMission->flt_mission_spy();
377
378
          unset($theMission);
379
        break;
380
381
        case MT_MISSILE:  // Missiles !!
382
        break;
383
384
//      default:
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...
385
//        doquery("DELETE FROM `{{fleets}}` WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
386
//      break;
387
      }
388
      sn_db_transaction_commit();
389
    }
390
391
//  log_file('Закончили обсчёт флотов');
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...
392
  }
393
394
395
  /**
396
   * @param array $fleet_row
397
   * @param bool  $start
398
   * @param bool  $only_resources
399
   * @param bool  $safe_fleet
400
   * @param mixed $result
401
   *
402
   * @return int
403
   * @deprecated
404
   */
405
  public function sn_RestoreFleetToPlanet(&$fleet_row, $start = true, $only_resources = false, $safe_fleet = false, &$result) {
0 ignored issues
show
Unused Code introduced by
The parameter $safe_fleet 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

405
  public function sn_RestoreFleetToPlanet(&$fleet_row, $start = true, $only_resources = false, /** @scrutinizer ignore-unused */ $safe_fleet = false, &$result) {

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...
406
    sn_db_transaction_check(true);
407
408
    $result = CACHE_NOTHING;
409
    if (!is_array($fleet_row)) {
410
      return $result;
411
    }
412
413
    $prefix = $start ? 'start' : 'end';
414
415
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
416
    // TODO Проеверить от многократного срабатывания !!!
417
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
418
//  $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1", true);
419
    // Узнаем ИД владельца планеты - без блокировки
420
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
421
    $user_id = DBStaticPlanet::db_planet_by_vector($fleet_row, "fleet_{$prefix}_", false, 'id_owner');
422
    $user_id = $user_id['id_owner'];
423
    // Блокируем пользователя
424
    $user = db_user_by_id($user_id, true);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() 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

424
    $user = /** @scrutinizer ignore-deprecated */ db_user_by_id($user_id, true);
Loading history...
425
    // Блокируем планету
426
    $planet_arrival = DBStaticPlanet::db_planet_by_vector($fleet_row, "fleet_{$prefix}_", true);
427
    // Блокируем флот
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% 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...
428
//  $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1 FOR UPDATE;", true);
429
430
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
431
    if (!$fleet_row || !is_array($fleet_row) || ($fleet_row['fleet_mess'] == 1 && $only_resources)) {
432
      return $result;
433
    }
434
435
    // Флот, который возвращается на захваченную планету, пропадает
436
    if ($start && $fleet_row['fleet_mess'] == 1 && $planet_arrival['id_owner'] != $fleet_row['fleet_owner']) {
437
      db_fleet_delete($fleet_row['fleet_id']);
438
439
      return $result;
440
    }
441
442
    $db_changeset = array();
443
    if (!$only_resources) {
444
      db_fleet_delete($fleet_row['fleet_id']);
445
446
      if ($fleet_row['fleet_owner'] == $planet_arrival['id_owner']) {
447
        $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
448
        foreach ($fleet_array as $ship_id => $ship_count) {
449
          if ($ship_count) {
450
            $db_changeset['unit'][] = OldDbChangeSet::db_changeset_prepare_unit($ship_id, $ship_count, $user, $planet_arrival['id']);
451
          }
452
        }
453
      } else {
454
        return CACHE_NOTHING;
455
      }
456
    } else {
457
      $fleet_set = array(
458
        'fleet_resource_metal'     => 0,
459
        'fleet_resource_crystal'   => 0,
460
        'fleet_resource_deuterium' => 0,
461
        'fleet_mess'               => 1,
462
      );
463
      fleet_update_set($fleet_row['fleet_id'], $fleet_set);
464
    }
465
466
    if (!empty($db_changeset)) {
467
      OldDbChangeSet::db_changeset_apply($db_changeset);
468
    }
469
470
    DBStaticPlanet::db_planet_set_by_id($planet_arrival['id'],
471
      "`metal` = `metal` + '{$fleet_row['fleet_resource_metal']}', `crystal` = `crystal` + '{$fleet_row['fleet_resource_crystal']}', `deuterium` = `deuterium` + '{$fleet_row['fleet_resource_deuterium']}'");
472
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
473
474
    return $result;
475
  }
476
477
478
  /**
479
   * Sort flying fleets events by time+event
480
   *
481
   * @param $a
482
   * @param $b
483
   *
484
   * @return int
485
   */
486
  protected function flt_flyingFleetsSort($a, $b) {
487
    return
488
      // Сравниваем время флотов - кто раньше, тот и первый обрабатывается
489
      $a['fleet_time'] > $b['fleet_time'] ? 1 : ($a['fleet_time'] < $b['fleet_time'] ? -1 :
490
        // Если время - одинаковое, сравниваем события флотов
491
        // Если события - одинаковые, то флоты равны
492
        ($a['fleet_event'] == $b['fleet_event'] ? 0 :
493
          // Если события разные - первыми считаем прибывающие флоты
494
          ($a['fleet_event'] == EVENT_FLT_ARRIVE ? 1 : ($b['fleet_event'] == EVENT_FLT_ARRIVE ? -1 :
495
            // Если нет прибывающих флотов - дальше считаем флоты, которые закончили миссию
496
            ($a['fleet_event'] == EVENT_FLT_ACOMPLISH ? 1 : ($b['fleet_event'] == EVENT_FLT_ACOMPLISH ? -1 :
497
              // Если нет флотов, закончивших задание - остались возвращающиеся флоты, которые равны между собой
498
              // TODO: Добавить еще проверку по ID флота и/или времени запуска - что бы обсчитывать их в порядке запуска
499
              (
500
              0 // Вообще сюда доходить не должно - будет отсекаться на равенстве событий
501
              )
502
            ))
503
          ))
504
        )
505
      );
506
  }
507
508
  /**
509
   * @param string $msg
510
   */
511
  protected function log_file($msg) {
512
    static $handler;
513
514
    if (!$handler) {
515
      $handler = fopen('event.log', 'a+');
516
    }
517
518
    fwrite($handler, date(FMT_DATE_TIME_SQL, time()) . ' ' . $msg . "\r\n");
519
  }
520
521
}
522