Completed
Push — work-fleets ( 2c97e5...fff2b6 )
by SuperNova.WS
05:26
created

Fleet::groupCheck()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 3
eloc 8
nc 3
nop 0
1
<?php
2
3
/**
4
 * Class Fleet
5
 *
6
 * @property int dbId
7
 * @property int playerOwnerId
8
 * @property int group_id
9
 * @property int mission_type
10
 * @property int target_owner_id
11
 * @property int is_returning
12
 *
13
 * @property int time_launch
14
 * @property int time_arrive_to_target
15
 * @property int time_mission_job_complete
16
 * @property int time_return_to_source
17
 *
18
 * @property int fleet_start_planet_id
19
 * @property int fleet_start_galaxy
20
 * @property int fleet_start_system
21
 * @property int fleet_start_planet
22
 * @property int fleet_start_type
23
 *
24
 * @property int fleet_end_planet_id
25
 * @property int fleet_end_galaxy
26
 * @property int fleet_end_system
27
 * @property int fleet_end_planet
28
 * @property int fleet_end_type
29
 *
30
 */
31
class Fleet extends UnitContainer {
32
33
  // DBRow inheritance *************************************************************************************************
34
35
  /**
36
   * Table name in DB
37
   *
38
   * @var string
39
   */
40
  protected static $_table = 'fleets';
41
  /**
42
   * Name of ID field in DB
43
   *
44
   * @var string
45
   */
46
  protected static $_dbIdFieldName = 'fleet_id';
47
  /**
48
   * DB_ROW to Class translation scheme
49
   *
50
   * @var array
51
   */
52
  protected static $_properties = array(
53
    'dbId'          => array(
54
      P_DB_FIELD => 'fleet_id',
55
    ),
56
    'playerOwnerId' => array(
57
      P_METHOD_EXTRACT => 'ownerExtract',
58
      P_METHOD_INJECT  => 'ownerInject',
59
//      P_DB_FIELD => 'fleet_owner',
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...
60
    ),
61
    'mission_type'  => array(
62
      P_DB_FIELD   => 'fleet_mission',
63
      P_FUNC_INPUT => 'intval',
64
    ),
65
66
    'target_owner_id' => array(
67
      P_DB_FIELD => 'fleet_target_owner',
68
    ),
69
    'group_id'        => array(
70
      P_DB_FIELD => 'fleet_group',
71
    ),
72
    'is_returning'    => array(
73
      P_DB_FIELD   => 'fleet_mess',
74
      P_FUNC_INPUT => 'intval',
75
    ),
76
77
    'shipCount' => array(
78
      P_DB_FIELD  => 'fleet_amount',
79
// TODO - CHECK !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
80
//      P_FUNC_OUTPUT => 'get_ship_count',
81
//      P_DB_FIELDS_LINKED => array(
82
//        'fleet_amount',
83
//      ),
84
      P_READ_ONLY => true,
85
    ),
86
87
    'time_launch' => array(
88
      P_DB_FIELD => 'start_time',
89
    ),
90
91
    'time_arrive_to_target'     => array(
92
      P_DB_FIELD => 'fleet_start_time',
93
    ),
94
    'time_mission_job_complete' => array(
95
      P_DB_FIELD => 'fleet_end_stay',
96
    ),
97
    'time_return_to_source'     => array(
98
      P_DB_FIELD => 'fleet_end_time',
99
    ),
100
101
    'fleet_start_planet_id' => array(
102
      P_DB_FIELD   => 'fleet_start_planet_id',
103
      P_FUNC_INPUT => 'nullIfEmpty',
104
    ),
105
106
    'fleet_start_galaxy' => array(
107
      P_DB_FIELD => 'fleet_start_galaxy',
108
    ),
109
    'fleet_start_system' => array(
110
      P_DB_FIELD => 'fleet_start_system',
111
    ),
112
    'fleet_start_planet' => array(
113
      P_DB_FIELD => 'fleet_start_planet',
114
    ),
115
    'fleet_start_type'   => array(
116
      P_DB_FIELD => 'fleet_start_type',
117
    ),
118
119
    'fleet_end_planet_id' => array(
120
      P_DB_FIELD   => 'fleet_end_planet_id',
121
      P_FUNC_INPUT => 'nullIfEmpty',
122
    ),
123
    'fleet_end_galaxy'    => array(
124
      P_DB_FIELD => 'fleet_end_galaxy',
125
    ),
126
    'fleet_end_system'    => array(
127
      P_DB_FIELD => 'fleet_end_system',
128
    ),
129
    'fleet_end_planet'    => array(
130
      P_DB_FIELD => 'fleet_end_planet',
131
    ),
132
    'fleet_end_type'      => array(
133
      P_DB_FIELD => 'fleet_end_type',
134
    ),
135
136
    'resource_list' => array(
137
      P_METHOD_EXTRACT   => 'resourcesExtract',
138
      P_METHOD_INJECT    => 'resourcesInject',
139
      P_DB_FIELDS_LINKED => array(
140
        'fleet_resource_metal',
141
        'fleet_resource_crystal',
142
        'fleet_resource_deuterium',
143
      ),
144
    ),
145
  );
146
147
148
  // UnitContainer inheritance *****************************************************************************************
149
  /**
150
   * Type of this location
151
   *
152
   * @var int $locationType
153
   */
154
  protected static $locationType = LOC_FLEET;
155
156
157
  // New properties ****************************************************************************************************
158
  /**
159
   * `fleet_owner`
160
   *
161
   * @var int
162
   */
163
  protected $_playerOwnerId = 0;
164
  /**
165
   * `fleet_group`
166
   *
167
   * @var int
168
   */
169
  protected $_group_id = 0;
170
  public $acs = array();
171
172
  /**
173
   * `fleet_mission`
174
   *
175
   * @var int
176
   */
177
  protected $_mission_type = 0;
178
179
  /**
180
   * `fleet_target_owner`
181
   *
182
   * @var int
183
   */
184
  protected $_target_owner_id = null;
185
186
  /**
187
   * @var array
188
   */
189
  public $resource_list = array(
190
    RES_METAL     => 0,
191
    RES_CRYSTAL   => 0,
192
    RES_DEUTERIUM => 0,
193
  );
194
195
196
  /**
197
   * `fleet__mess` - Флаг возвращающегося флота
198
   *
199
   * @var int
200
   */
201
  protected $_is_returning = 0;
202
  /**
203
   * `start_time` - Время отправления - таймштамп взлёта флота из точки отправления
204
   *
205
   * @var int $_time_launch
206
   */
207
  protected $_time_launch = 0; // `start_time` = SN_TIME_NOW
208
  /**
209
   * `fleet_start_time` - Время прибытия в точку миссии/время начала выполнения миссии
210
   *
211
   * @var int $_time_arrive_to_target
212
   */
213
  protected $_time_arrive_to_target = 0; // `fleet_start_time` = SN_TIME_NOW + $time_travel
214
  /**
215
   * `fleet_end_stay` - Время окончания миссии в точке назначения
216
   *
217
   * @var int $_time_mission_job_complete
218
   */
219
  protected $_time_mission_job_complete = 0; // `fleet_end_stay`
220
  /**
221
   * `fleet_end_time` - Время возвращения флота после окончания миссии
222
   *
223
   * @var int $_time_return_to_source
224
   */
225
  protected $_time_return_to_source = 0; // `fleet_end_time`
226
227
228
  protected $_fleet_start_planet_id = null;
229
  protected $_fleet_start_galaxy = 0;
230
  protected $_fleet_start_system = 0;
231
  protected $_fleet_start_planet = 0;
232
  protected $_fleet_start_type = PT_ALL;
233
234
  protected $_fleet_end_planet_id = null;
235
  protected $_fleet_end_galaxy = 0;
236
  protected $_fleet_end_system = 0;
237
  protected $_fleet_end_planet = 0;
238
  protected $_fleet_end_type = PT_ALL;
239
240
  // Missile properties
241
  public $missile_target = 0;
242
243
  // Fleet event properties
244
  public $fleet_start_name = '';
245
  public $fleet_end_name = '';
246
  public $ov_label = '';
247
  public $ov_this_planet = '';
248
  public $event_time = 0;
249
250
  protected $resource_delta = array();
251
  protected $resource_replace = array();
252
253
254
//
255
256
257
  /**
258
   * @var array $allowed_missions
259
   */
260
  public $allowed_missions = array();
261
  /**
262
   * @var array $exists_missions
263
   */
264
  public $exists_missions = array();
265
  public $allowed_planet_types = array(
266
    // PT_NONE => PT_NONE,
267
    PT_PLANET => PT_PLANET,
268
    PT_MOON   => PT_MOON,
269
    PT_DEBRIS => PT_DEBRIS
270
  );
271
272
  // TODO - Move to Player
273
  public $dbOwnerRow = array();
274
  public $dbSourcePlanetRow = array();
275
276
  /**
277
   * GSPT coordinates of target
278
   *
279
   * @var Vector
280
   */
281
  public $targetVector = array();
282
  /**
283
   * Target planet row
284
   *
285
   * @var array
286
   */
287
  public $dbTargetRow = array();
288
  public $dbTargetOwnerRow = array();
289
290
  /**
291
   * Fleet speed - old in 1/10 of 100%
292
   *
293
   * @var int
294
   */
295
  public $oldSpeedInTens = 0;
296
297
  public $tempPlayerMaxFleets = 0;
298
  public $travelData = array();
299
300
  public $isRealFlight = false;
301
302
  /**
303
   * @var int $targetedUnitId
304
   */
305
  public $targetedUnitId = 0;
306
307
  /**
308
   * @var array $captain
309
   */
310
  public $captain = array();
311
  /**
312
   * @var int $captainId
313
   */
314
  public $captainId = 0;
315
316
  /**
317
   * Fleet constructor.
318
   */
319
  public function __construct() {
320
    parent::__construct();
321
    $this->exists_missions = sn_get_groups('missions');
322
    $this->allowed_missions = $this->exists_missions;
323
  }
324
325
  /**
326
   * @param array $template_result
327
   * @param array $playerRow
328
   * @param array $planetRow
329
   */
330
  // TODO - redo to unit/unitlist renderer
331
  public function renderAvailableShips(&$template_result, $playerRow, $planetRow) {
332
    $record_index = 0;
333
    $ship_list = array();
334
    foreach (sn_get_groups('fleet') as $n => $unit_id) {
335
      $unit_level = mrc_get_level($playerRow, $planetRow, $unit_id, false, true);
336
      if ($unit_level <= 0) {
337
        continue;
338
      }
339
      $ship_data = get_ship_data($unit_id, $playerRow);
340
      $ship_list[$unit_id] = array(
341
        '__INDEX'          => $record_index++,
342
        'ID'               => $unit_id,
343
        'NAME'             => classLocale::$lang['tech'][$unit_id],
344
        'AMOUNT'           => $unit_level,
345
        'AMOUNT_TEXT'      => pretty_number($unit_level),
346
        'CONSUMPTION'      => $ship_data['consumption'],
347
        'CONSUMPTION_TEXT' => pretty_number($ship_data['consumption']),
348
        'SPEED'            => $ship_data['speed'],
349
        'SPEED_TEXT'       => pretty_number($ship_data['speed']),
350
        'CAPACITY'         => $ship_data['capacity'],
351
        'CAPACITY_TEXT'    => pretty_number($ship_data['capacity']),
352
      );
353
    }
354
355
    sortUnitRenderedList($ship_list, classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT], classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE]);
356
357
    foreach ($ship_list as $ship_data) {
358
      $template_result['.']['ships'][] = $ship_data;
359
    }
360
  }
361
362
  public function isEmpty() {
363
    return !$this->resourcesGetTotal() && !$this->shipsGetTotal();
364
  }
365
366
//  public function getPlayerOwnerId() {
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...
367
//    return $this->playerOwnerId;
368
//  }
369
370
  /**
371
   * Initializes Fleet from user params and posts it to DB
372
   */
373
  public function dbInsert() {
374
    // WARNING! MISSION TIMES MUST BE SET WITH set_times() method!
375
    // TODO - more checks!
376
    if (empty($this->_time_launch)) {
377
      die('Fleet time not set!');
378
    }
379
380
    parent::dbInsert();
381
  }
382
383
384
  /* FLEET DB ACCESS =================================================================================================*/
385
386
  /**
387
   * LOCK - Lock all records which can be used with mission
388
   *
389
   * @param $mission_data
390
   *
391
   * @return array|bool|mysqli_result|null
392
   */
393
  public function dbLockFlying(&$mission_data) {
394
    // Тупо лочим всех юзеров, чьи флоты летят или улетают с координат отбытия/прибытия $fleet_row
395
    // Что бы делать это умно - надо учитывать fleet__mess во $fleet_row и в таблице fleets
396
397
    $fleet_id_safe = idval($this->_dbId);
398
399
    return doquery(
400
    // Блокировка самого флота
401
      "SELECT 1 FROM {{fleets}} AS f " .
402
403
      // Блокировка всех юнитов, принадлежащих этому флоту
404
      "LEFT JOIN {{unit}} as unit ON unit.unit_location_type = " . static::$locationType . " AND unit.unit_location_id = f.fleet_id " .
405
406
      // Блокировка всех прилетающих и улетающих флотов, если нужно
407
      // TODO - lock fleets by COORDINATES
408
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{fleets}} AS fd ON fd.fleet_end_planet_id = f.fleet_end_planet_id OR fd.fleet_start_planet_id = f.fleet_end_planet_id " : '') .
409
      // Блокировка всех юнитов, принадлежащих прилетающим и улетающим флотам - ufd = unit_fleet_destination
410
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{unit}} AS ufd ON ufd.unit_location_type = " . static::$locationType . " AND ufd.unit_location_id = fd.fleet_id " : '') .
411
412
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{users}} AS ud ON ud.id = f.fleet_target_owner " : '') .
413
      // Блокировка всех юнитов, принадлежащих владельцу планеты-цели
414
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS unit_player_dest ON unit_player_dest.unit_player_id = ud.id " : '') .
415
      // Блокировка планеты-цели
416
      ($mission_data['dst_planet'] ? "LEFT JOIN {{planets}} AS pd ON pd.id = f.fleet_end_planet_id " : '') .
417
      // Блокировка всех юнитов, принадлежащих планете-цели - НЕ НУЖНО. Уже залочили ранее, как принадлежащие игроку-цели
418
//      ($mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS upd ON upd.unit_location_type = " . LOC_PLANET . " AND upd.unit_location_id = pd.id " : '') .
419
420
421
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{users}} AS us ON us.id = f.fleet_owner " : '') .
422
      // Блокировка всех юнитов, принадлежащих владельцу флота
423
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS unit_player_src ON unit_player_src.unit_player_id = us.id " : '') .
424
      // Блокировка планеты отправления
425
      ($mission_data['src_planet'] ? "LEFT JOIN {{planets}} AS ps ON ps.id = f.fleet_start_planet_id " : '') .
426
      // Блокировка всех юнитов, принадлежащих планете с которой юниты были отправлены - НЕ НУЖНО. Уже залочили ранее, как принадлежащие владельцу флота
427
//      ($mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS ups ON ups.unit_location_type = " . LOC_PLANET . " AND ups.unit_location_id = ps.id " : '') .
428
429
      "WHERE f.fleet_id = {$fleet_id_safe} GROUP BY 1 FOR UPDATE"
430
    );
431
  }
432
433
  /**
434
   * Lock all fields that belongs to operation
435
   *
436
   * @param $dbId
437
   */
438
  // TODO = make static
439
  public function dbGetLockById($dbId) {
440
    doquery(
441
    // Блокировка самого флота
442
      "SELECT 1 FROM {{fleets}} AS FLEET0 " .
443
      // Lock fleet owner
444
      "LEFT JOIN {{users}} as USER0 on USER0.id = FLEET0.fleet_owner " .
445
      // Блокировка всех юнитов, принадлежащих этому флоту
446
      "LEFT JOIN {{unit}} as UNIT0 ON UNIT0.unit_location_type = " . LOC_FLEET . " AND UNIT0.unit_location_id = FLEET0.fleet_id " .
447
448
      // Без предварительной выборки неизвестно - куда летит этот флот.
449
      // Поэтому надо выбирать флоты, чьи координаты прибытия ИЛИ отбытия совпадают с координатами прибытия ИЛИ отбытия текущего флота.
450
      // Получаем матрицу 2х2 - т.е. 4 подзапроса.
451
      // При блокировке всегда нужно выбирать И лпанету, И луну - поскольку при бое на орбите луны обломки падают на орбиту планеты.
452
      // Поэтому тип планеты не указывается
453
454
      // Lock fleet heading to destination planet. Only if FLEET0.fleet_mess == 0
455
      "LEFT JOIN {{fleets}} AS FLEET1 ON
456
        FLEET1.fleet_mess = 0 AND FLEET0.fleet_mess = 0 AND
457
        FLEET1.fleet_end_galaxy = FLEET0.fleet_end_galaxy AND
458
        FLEET1.fleet_end_system = FLEET0.fleet_end_system AND
459
        FLEET1.fleet_end_planet = FLEET0.fleet_end_planet
460
      " .
461
      // Блокировка всех юнитов, принадлежащих этим флотам
462
      "LEFT JOIN {{unit}} as UNIT1 ON UNIT1.unit_location_type = " . LOC_FLEET . " AND UNIT1.unit_location_id = FLEET1.fleet_id " .
463
      // Lock fleet owner
464
      "LEFT JOIN {{users}} as USER1 on USER1.id = FLEET1.fleet_owner " .
465
466
      "LEFT JOIN {{fleets}} AS FLEET2 ON
467
        FLEET2.fleet_mess = 1   AND FLEET0.fleet_mess = 0 AND
468
        FLEET2.fleet_start_galaxy = FLEET0.fleet_end_galaxy AND
469
        FLEET2.fleet_start_system = FLEET0.fleet_end_system AND
470
        FLEET2.fleet_start_planet = FLEET0.fleet_end_planet
471
      " .
472
      // Блокировка всех юнитов, принадлежащих этим флотам
473
      "LEFT JOIN {{unit}} as UNIT2 ON
474
        UNIT2.unit_location_type = " . LOC_FLEET . " AND
475
        UNIT2.unit_location_id = FLEET2.fleet_id
476
      " .
477
      // Lock fleet owner
478
      "LEFT JOIN {{users}} as USER2 on
479
        USER2.id = FLEET2.fleet_owner
480
      " .
481
482
      // Lock fleet heading to source planet. Only if FLEET0.fleet_mess == 1
483
      "LEFT JOIN {{fleets}} AS FLEET3 ON
484
        FLEET3.fleet_mess = 0 AND FLEET0.fleet_mess = 1 AND
485
        FLEET3.fleet_end_galaxy = FLEET0.fleet_start_galaxy AND
486
        FLEET3.fleet_end_system = FLEET0.fleet_start_system AND
487
        FLEET3.fleet_end_planet = FLEET0.fleet_start_planet
488
      " .
489
      // Блокировка всех юнитов, принадлежащих этим флотам
490
      "LEFT JOIN {{unit}} as UNIT3 ON
491
        UNIT3.unit_location_type = " . LOC_FLEET . " AND
492
        UNIT3.unit_location_id = FLEET3.fleet_id
493
      " .
494
      // Lock fleet owner
495
      "LEFT JOIN {{users}} as USER3 on USER3.id = FLEET3.fleet_owner " .
496
497
      "LEFT JOIN {{fleets}} AS FLEET4 ON
498
        FLEET4.fleet_mess = 1   AND FLEET0.fleet_mess = 1 AND
499
        FLEET4.fleet_start_galaxy = FLEET0.fleet_start_galaxy AND
500
        FLEET4.fleet_start_system = FLEET0.fleet_start_system AND
501
        FLEET4.fleet_start_planet = FLEET0.fleet_start_planet
502
      " .
503
      // Блокировка всех юнитов, принадлежащих этим флотам
504
      "LEFT JOIN {{unit}} as UNIT4 ON
505
        UNIT4.unit_location_type = " . LOC_FLEET . " AND
506
        UNIT4.unit_location_id = FLEET4.fleet_id
507
      " .
508
      // Lock fleet owner
509
      "LEFT JOIN {{users}} as USER4 on
510
        USER4.id = FLEET4.fleet_owner
511
      " .
512
513
514
      // Locking start planet
515
      "LEFT JOIN {{planets}} AS PLANETS5 ON
516
        FLEET0.fleet_mess = 1 AND
517
        PLANETS5.galaxy = FLEET0.fleet_start_galaxy AND
518
        PLANETS5.system = FLEET0.fleet_start_system AND
519
        PLANETS5.planet = FLEET0.fleet_start_planet
520
      " .
521
      // Lock planet owner
522
      "LEFT JOIN {{users}} as USER5 on
523
        USER5.id = PLANETS5.id_owner
524
      " .
525
      // Блокировка всех юнитов, принадлежащих этой планете
526
      "LEFT JOIN {{unit}} as UNIT5 ON
527
        UNIT5.unit_location_type = " . LOC_PLANET . " AND
528
        UNIT5.unit_location_id = PLANETS5.id
529
      " .
530
531
532
      // Locking destination planet
533
      "LEFT JOIN {{planets}} AS PLANETS6 ON
534
        FLEET0.fleet_mess = 0 AND
535
        PLANETS6.galaxy = FLEET0.fleet_end_galaxy AND
536
        PLANETS6.system = FLEET0.fleet_end_system AND
537
        PLANETS6.planet = FLEET0.fleet_end_planet
538
      " .
539
      // Lock planet owner
540
      "LEFT JOIN {{users}} as USER6 on
541
        USER6.id = PLANETS6.id_owner
542
      " .
543
      // Блокировка всех юнитов, принадлежащих этой планете
544
      "LEFT JOIN {{unit}} as UNIT6 ON
545
        UNIT6.unit_location_type = " . LOC_PLANET . " AND
546
        UNIT6.unit_location_id = PLANETS6.id
547
      " .
548
      "WHERE FLEET0.fleet_id = {$dbId} GROUP BY 1 FOR UPDATE"
549
    );
550
  }
551
552
553
  public function dbRowParse($db_row) {
554
    parent::dbRowParse($db_row); // TODO: Change the autogenerated stub
555
    $player = new Player();
556
    $player->dbLoad($db_row['fleet_owner']);
557
    $this->setLocatedAt($player);
558
  }
559
560
  /* FLEET HELPERS =====================================================================================================*/
561
  /**
562
   * Forcibly returns fleet before time outs
563
   */
564
  public function commandReturn() {
565
    $ReturnFlyingTime = ($this->_time_mission_job_complete != 0 && $this->_time_arrive_to_target < SN_TIME_NOW ? $this->_time_arrive_to_target : SN_TIME_NOW) - $this->_time_launch + SN_TIME_NOW + 1;
566
567
    $this->markReturned();
568
569
    // Считаем, что флот уже долетел TODO
570
    $this->time_arrive_to_target = SN_TIME_NOW;
571
    // Убираем флот из группы
572
    $this->group_id = 0;
573
    // Отменяем работу в точке назначения
574
    $this->time_mission_job_complete = 0;
575
    // TODO - правильно вычслять время возвращения - по проделанному пути, а не по старому времени возвращения
576
    $this->time_return_to_source = $ReturnFlyingTime;
577
578
    // Записываем изменения в БД
579
    $this->dbSave();
580
581
    if ($this->_group_id) {
582
      // TODO: Make here to delete only one AKS - by adding aks_fleet_count to AKS table
583
      db_fleet_aks_purge();
584
    }
585
  }
586
587
588
  /**
589
   * @return array
590
   */
591
  public function target_coordinates_without_type() {
592
    return array(
593
      'galaxy' => $this->_fleet_end_galaxy,
594
      'system' => $this->_fleet_end_system,
595
      'planet' => $this->_fleet_end_planet,
596
    );
597
  }
598
599
  /**
600
   * @return array
601
   */
602
  public function target_coordinates_typed() {
603
    return array(
604
      'galaxy' => $this->_fleet_end_galaxy,
605
      'system' => $this->_fleet_end_system,
606
      'planet' => $this->_fleet_end_planet,
607
      'type'   => $this->_fleet_end_type,
608
    );
609
  }
610
611
  /**
612
   * @return array
613
   */
614
  public function launch_coordinates_typed() {
615
    return array(
616
      'galaxy' => $this->_fleet_start_galaxy,
617
      'system' => $this->_fleet_start_system,
618
      'planet' => $this->_fleet_start_planet,
619
      'type'   => $this->_fleet_start_type,
620
    );
621
  }
622
623
624
  /**
625
   * Sets object fields for fleet return
626
   */
627
  public function markReturned() {
628
    // TODO - Проверка - а не возвращается ли уже флот?
629
    $this->is_returning = 1;
630
  }
631
632
  public function isReturning() {
633
    return 1 == $this->_is_returning;
634
  }
635
636
  public function markReturnedAndSave() {
637
    $this->markReturned();
638
    $this->dbSave();
639
  }
640
641
  /**
642
   * Parses extended unit_array which can include not only ships but resources, captains etc
643
   *
644
   * @param $unit_array
645
   *
646
   * @throws Exception
647
   */
648
  // TODO - separate shipList and unitList
649
  public function unitsSetFromArray($unit_array) {
650
    if (empty($unit_array) || !is_array($unit_array)) {
651
      return;
652
    }
653
    foreach ($unit_array as $unit_id => $unit_count) {
654
      $unit_count = floatval($unit_count);
655
      if (!$unit_count) {
656
        continue;
657
      }
658
659
      if ($this->isShip($unit_id)) {
660
        $this->unitList->unitSetCount($unit_id, $unit_count);
661
      } elseif ($this->isResource($unit_id)) {
662
        $this->resource_list[$unit_id] = $unit_count;
663
      } else {
664
        throw new Exception('Trying to pass to fleet non-resource and non-ship ' . var_export($unit_array, true), ERR_ERROR);
665
      }
666
    }
667
  }
668
669
670
  /**
671
   * Sets fleet timers based on flight duration, time on mission (HOLD/EXPLORE) and fleet departure time.
672
   *
673
   * @param int $time_to_travel - flight duration in seconds
674
   * @param int $time_on_mission - time on mission in seconds
675
   * @param int $flight_departure - fleet departure from source planet timestamp. Allows to send fleet in future or in past
676
   */
677
  public function set_times($time_to_travel, $time_on_mission = 0, $flight_departure = SN_TIME_NOW) {
678
    $this->_time_launch = $flight_departure;
679
680
    $this->_time_arrive_to_target = $this->_time_launch + $time_to_travel;
681
    $this->_time_mission_job_complete = $time_on_mission ? $this->_time_arrive_to_target + $time_on_mission : 0;
682
    $this->_time_return_to_source = ($this->_time_mission_job_complete ? $this->_time_mission_job_complete : $this->_time_arrive_to_target) + $time_to_travel;
683
  }
684
685
686
  public function parse_missile_db_row($missile_db_row) {
687
//    $this->_reset();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
688
689
    if (empty($missile_db_row) || !is_array($missile_db_row)) {
690
      return;
691
    }
692
693
//      $planet_start = db_planet_by_vector($irak_original, 'fleet_start_', false, 'name');
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% 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...
694
//      $irak_original['fleet_start_name'] = $planet_start['name'];
695
    $this->missile_target = $missile_db_row['primaer'];
696
697
    $this->_dbId = -$missile_db_row['id'];
698
    $this->_playerOwnerId = $missile_db_row['fleet_owner'];
699
    $this->_mission_type = MT_MISSILE;
700
701
    $this->_target_owner_id = $missile_db_row['fleet_target_owner'];
702
703
    $this->_group_id = 0;
704
    $this->_is_returning = 0;
705
706
    $this->_time_launch = 0; // $irak['start_time'];
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...
707
    $this->_time_arrive_to_target = 0; // $irak['fleet_start_time'];
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...
708
    $this->_time_mission_job_complete = 0; // $irak['fleet_end_stay'];
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...
709
    $this->_time_return_to_source = $missile_db_row['fleet_end_time'];
710
711
    $this->_fleet_start_planet_id = !empty($missile_db_row['fleet_start_planet_id']) ? $missile_db_row['fleet_start_planet_id'] : null;
712
    $this->_fleet_start_galaxy = $missile_db_row['fleet_start_galaxy'];
713
    $this->_fleet_start_system = $missile_db_row['fleet_start_system'];
714
    $this->_fleet_start_planet = $missile_db_row['fleet_start_planet'];
715
    $this->_fleet_start_type = $missile_db_row['fleet_start_type'];
716
717
    $this->_fleet_end_planet_id = !empty($missile_db_row['fleet_end_planet_id']) ? $missile_db_row['fleet_end_planet_id'] : null;
718
    $this->_fleet_end_galaxy = $missile_db_row['fleet_end_galaxy'];
719
    $this->_fleet_end_system = $missile_db_row['fleet_end_system'];
720
    $this->_fleet_end_planet = $missile_db_row['fleet_end_planet'];
721
    $this->_fleet_end_type = $missile_db_row['fleet_end_type'];
722
723
    $this->unitList->unitSetCount(UNIT_DEF_MISSILE_INTERPLANET, $missile_db_row['fleet_amount']);
724
  }
725
726
727
  /**
728
   * @param $from
729
   */
730
  public function set_start_planet($from) {
731
    $this->fleet_start_planet_id = intval($from['id']) ? $from['id'] : null;
732
    $this->fleet_start_galaxy = $from['galaxy'];
733
    $this->fleet_start_system = $from['system'];
734
    $this->fleet_start_planet = $from['planet'];
735
    $this->fleet_start_type = $from['planet_type'];
736
  }
737
738
  /**
739
   * @param $to
740
   */
741
  public function set_end_planet($to) {
742
    $this->target_owner_id = intval($to['id_owner']) ? $to['id_owner'] : 0;
743
    $this->fleet_end_planet_id = intval($to['id']) ? $to['id'] : null;
744
    $this->fleet_end_galaxy = $to['galaxy'];
745
    $this->fleet_end_system = $to['system'];
746
    $this->fleet_end_planet = $to['planet'];
747
    $this->fleet_end_type = $to['planet_type'];
748
  }
749
750
  /**
751
   * @param Vector $to
752
   */
753
  public function setTargetFromVectorObject($to) {
754
    $this->_fleet_end_galaxy = $to->galaxy;
755
    $this->_fleet_end_system = $to->system;
756
    $this->_fleet_end_planet = $to->planet;
757
    $this->_fleet_end_type = $to->type;
758
  }
759
760
  /**
761
   * @param array $db_row
762
   */
763
  protected function ownerExtract(array &$db_row) {
764
    $player = new Player();
765
    $player->dbLoad($db_row['fleet_owner']);
766
    $this->setLocatedAt($player);
767
  }
768
769
  /**
770
   * @param array $db_row
771
   */
772
  protected function ownerInject(array &$db_row) {
773
    $db_row['fleet_owner'] = $this->getPlayerOwnerId();
774
  }
775
776
777
778
779
  // UnitList/Ships access ***************************************************************************************************
780
781
  // TODO - перекрывать пожже - для миссайл-флотов и дефенс-флотов
782
  protected function isShip($unit_id) {
783
    return UnitShip::is_in_group($unit_id);
784
  }
785
786
  /**
787
   * Set unit count of $unit_id to $unit_count
788
   * If there is no $unit_id - it will be created and saved to DB on dbSave
789
   *
790
   * @param int $unit_id
791
   * @param int $unit_count
792
   */
793
  public function shipSetCount($unit_id, $unit_count = 0) {
794
    $this->shipAdjustCount($unit_id, $unit_count, true);
795
  }
796
797
  /**
798
   * Adjust unit count of $unit_id by $unit_count - or just replace value
799
   * If there is no $unit_id - it will be created and saved to DB on dbSave
800
   *
801
   * @param int  $unit_id
802
   * @param int  $unit_count
803
   * @param bool $replace_value
804
   */
805
  public function shipAdjustCount($unit_id, $unit_count = 0, $replace_value = false) {
806
    $this->unitList->unitAdjustCount($unit_id, $unit_count, $replace_value);
807
  }
808
809
  public function shipGetCount($unit_id) {
810
    return $this->unitList->unitGetCount($unit_id);
811
  }
812
813
  public function shipsCountApplyLossMultiplier($ships_lost_multiplier) {
814
    $this->unitList->unitsCountApplyLossMultiplier($ships_lost_multiplier);
815
  }
816
817
  /**
818
   * Returns ship list in fleet
819
   */
820
  public function shipsGetArray() {
821
    return $this->unitList->unitsGetArray();
822
  }
823
824
  public function shipsGetTotal() {
825
    return $this->unitList->unitsCount();
826
  }
827
828
  public function shipsGetCapacity() {
829
    return $this->unitList->shipsCapacity();
830
  }
831
832
  public function shipsGetHoldFree() {
833
    return max(0, $this->shipsGetCapacity() - $this->resourcesGetTotal());
834
  }
835
836
  /**
837
   * Get count of ships with $ship_id
838
   *
839
   * @param int $ship_id
840
   *
841
   * @return int
842
   */
843
  public function shipsGetTotalById($ship_id) {
844
    return $this->unitList->unitsCountById($ship_id);
845
  }
846
847
  /**
848
   * Возвращает ёмкость переработчиков во флоте
849
   *
850
   * @param array $recycler_info
851
   *
852
   * @return int
853
   *
854
   * @version 41a6.97
855
   */
856
  public function shipsGetCapacityRecyclers(array $recycler_info) {
857
    $recyclers_incoming_capacity = 0;
858
    $fleet_data = $this->shipsGetArray();
859
    foreach ($recycler_info as $recycler_id => $recycler_data) {
860
      $recyclers_incoming_capacity += $fleet_data[$recycler_id] * $recycler_data['capacity'];
861
    }
862
863
    return $recyclers_incoming_capacity;
864
  }
865
866
  /**
867
   * @return bool
868
   */
869
  public function shipsIsEnoughOnPlanet() {
870
    return $this->unitList->shipsIsEnoughOnPlanet($this->fleet->dbSourcePlanetRow);
871
  }
872
873
  /**
874
   * @return bool
875
   */
876
  public function shipsAllPositive() {
877
    return $this->unitList->unitsPositive();
878
  }
879
880
  /**
881
   * @return bool
882
   */
883
  public function shipsAllFlying() {
884
    return $this->unitList->unitsInGroup(sn_get_groups(array('fleet', 'missile')));
885
  }
886
887
  /**
888
   * @return bool
889
   */
890
  public function shipsAllMovable() {
891
    return $this->unitList->unitsIsAllMovable($this->fleet->dbOwnerRow);
892
  }
893
894
  /**
895
   * Restores fleet or resources to planet
896
   *
897
   * @param bool $start
898
   * @param int  $result
899
   *
900
   * @return int
901
   */
902
  // TODO - split to functions
903
  public function shipsLand($start = true, &$result = CACHE_NOTHING) {
904
    sn_db_transaction_check(true);
905
906
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
907
    if ($this->isEmpty()) {
908
      return $result;
909
    }
910
911
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
912
913
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
914
    // TODO Проверить от многократного срабатывания !!!
915
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
916
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
917
918
    // Узнаем ИД владельца планеты.
919
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
920
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
921
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
922
    // Блокируем пользователя
923
    // TODO - вообще-то нам уже известен пользователь в МЛФ - так что можно просто передать его сюда
924
    $user = db_user_by_id($planet_arrival['id_owner'], true);
925
926
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
927
    // Флот, который возвращается на захваченную планету, пропадает
928
    // Ship landing is possible only to fleet owner's planet
929
    if ($this->getPlayerOwnerId() == $planet_arrival['id_owner']) {
930
      $db_changeset = array();
931
932
      $fleet_array = $this->shipsGetArray();
933
      foreach ($fleet_array as $ship_id => $ship_count) {
934
        if ($ship_count) {
935
          $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
936
        }
937
      }
938
939
      // Adjusting ship amount on planet
940
      if (!empty($db_changeset)) {
941
        db_changeset_apply($db_changeset);
942
      }
943
944
      // Restoring resources to planet
945
      $this->resourcesUnload($start, $result);
946
    }
947
948
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
949
950
    $result = RestoreFleetToPlanet($this, $start, $result);
951
952
    $this->dbDelete();
953
954
    return $result;
955
  }
956
957
958
  // Resources access ***************************************************************************************************
959
960
  /**
961
   * Extracts resources value from db_row
962
   *
963
   * @param array $db_row
964
   *
965
   * @internal param Fleet $that
966
   * @version 41a6.97
967
   */
968
  protected function resourcesExtract(array &$db_row) {
969
    $this->resource_list = array(
970
      RES_METAL     => !empty($db_row['fleet_resource_metal']) ? floor($db_row['fleet_resource_metal']) : 0,
971
      RES_CRYSTAL   => !empty($db_row['fleet_resource_crystal']) ? floor($db_row['fleet_resource_crystal']) : 0,
972
      RES_DEUTERIUM => !empty($db_row['fleet_resource_deuterium']) ? floor($db_row['fleet_resource_deuterium']) : 0,
973
    );
974
  }
975
976
  protected function resourcesInject(array &$db_row) {
977
    $db_row['fleet_resource_metal'] = $this->resource_list[RES_METAL];
978
    $db_row['fleet_resource_crystal'] = $this->resource_list[RES_CRYSTAL];
979
    $db_row['fleet_resource_deuterium'] = $this->resource_list[RES_DEUTERIUM];
980
  }
981
982
  /**
983
   * Set current resource list from array of units
984
   *
985
   * @param array $resource_list
986
   */
987
  public function resourcesSet($resource_list) {
988
    if (!empty($this->propertiesAdjusted['resource_list'])) {
989
      throw new PropertyAccessException('Property "resource_list" already was adjusted so no SET is possible until dbSave in ' . get_called_class() . '::unitSetResourceList', ERR_ERROR);
990
    }
991
    $this->resourcesAdjust($resource_list, true);
992
  }
993
994
  /**
995
   * Updates fleet resource list with deltas
996
   *
997
   * @param array $resource_delta_list
998
   * @param bool  $replace_value
999
   *
1000
   * @throws Exception
1001
   */
1002
  public function resourcesAdjust($resource_delta_list, $replace_value = false) {
1003
    !is_array($resource_delta_list) ? $resource_delta_list = array() : false;
1004
1005
    foreach ($resource_delta_list as $resource_id => $unit_delta) {
1006
      if (!UnitResourceLoot::is_in_group($resource_id) || !($unit_delta = floor($unit_delta))) {
1007
        // Not a resource or no resources - continuing
1008
        continue;
1009
      }
1010
1011
      if ($replace_value) {
1012
        $this->resource_list[$resource_id] = $unit_delta;
1013
      } else {
1014
        $this->resource_list[$resource_id] += $unit_delta;
1015
        // Preparing changes
1016
        $this->resource_delta[$resource_id] += $unit_delta;
1017
        $this->propertiesAdjusted['resource_list'] = 1;
1018
      }
1019
1020
      // Check for negative unit value
1021
      if ($this->resource_list[$resource_id] < 0) {
1022
        // TODO
1023
        throw new Exception('Resource ' . $resource_id . ' will become negative in ' . get_called_class() . '::unitAdjustResourceList', ERR_ERROR);
1024
      }
1025
    }
1026
  }
1027
1028
  public function resourcesGetTotal() {
1029
    return empty($this->resource_list) || !is_array($this->resource_list) ? 0 : array_sum($this->resource_list);
1030
  }
1031
1032
  /**
1033
   * @param array $rate
1034
   *
1035
   * @return float
1036
   */
1037
  public function resourcesGetTotalInMetal(array $rate) {
1038
    return
1039
      $this->resource_list[RES_METAL] * $rate[RES_METAL]
1040
      + $this->resource_list[RES_CRYSTAL] * $rate[RES_CRYSTAL] / $rate[RES_METAL]
1041
      + $this->resource_list[RES_DEUTERIUM] * $rate[RES_DEUTERIUM] / $rate[RES_METAL];
1042
  }
1043
1044
  /**
1045
   * Returns resource list in fleet
1046
   */
1047
  // TODO
1048
  public function resourcesGetList() {
1049
    return $this->resource_list;
1050
  }
1051
1052
  public function resourcesReset() {
1053
    $this->resourcesSet(array(
1054
      RES_METAL     => 0,
1055
      RES_CRYSTAL   => 0,
1056
      RES_DEUTERIUM => 0,
1057
    ));
1058
  }
1059
1060
  /**
1061
   * Restores fleet or resources to planet
1062
   *
1063
   * @param bool $start
1064
   * @param bool $only_resources
0 ignored issues
show
Bug introduced by
There is no parameter named $only_resources. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1065
   * @param int  $result
1066
   *
1067
   * @return int
1068
   */
1069
  public function resourcesUnload($start = true, &$result = CACHE_NOTHING) {
1070
    sn_db_transaction_check(true);
1071
1072
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
1073
    if (!$this->resourcesGetTotal()) {
1074
      return $result;
1075
    }
1076
1077
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
1078
1079
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
1080
    // TODO Проверить от многократного срабатывания !!!
1081
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
1082
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
1083
1084
1085
    // Узнаем ИД владельца планеты.
1086
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
1087
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
1088
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
1089
1090
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
1091
1092
    // Restoring resources to planet
1093
    if ($this->resourcesGetTotal()) {
1094
      $fleet_resources = $this->resourcesGetList();
1095
      db_planet_set_by_id($planet_arrival['id'],
1096
        "`metal` = `metal` + '{$fleet_resources[RES_METAL]}', `crystal` = `crystal` + '{$fleet_resources[RES_CRYSTAL]}', `deuterium` = `deuterium` + '{$fleet_resources[RES_DEUTERIUM]}'");
1097
    }
1098
1099
    $this->resourcesReset();
1100
    $this->markReturned();
1101
1102
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
1103
1104
    return $result;
1105
  }
1106
1107
1108
  protected function isResource($unit_id) {
1109
    return UnitResourceLoot::is_in_group($unit_id);
1110
  }
1111
1112
  /**
1113
   * @param int $speed_percent
1114
   *
1115
   * @return array
1116
   */
1117
  protected function flt_travel_data($speed_percent = 10) {
1118
    $distance = $this->targetVector->distanceFromCoordinates($this->dbSourcePlanetRow);
1119
1120
    return $this->unitList->travelData($speed_percent, $distance, $this->dbOwnerRow);
1121
  }
1122
1123
1124
  /**
1125
   * @param array  $dbPlayerRow
1126
   * @param array  $dbPlanetRow
1127
   * @param Vector $targetVector
1128
   *
1129
   */
1130
  public function initDefaults($dbPlayerRow, $dbPlanetRow, $targetVector, $mission, $ships, $fleet_group_mr, $oldSpeedInTens = 10, $targetedUnitId = 0, $captainId = 0, $resources = array()) {
0 ignored issues
show
Unused Code introduced by
The parameter $resources is not used and could be removed.

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

Loading history...
1131
    $objFleet5Player = new Player();
1132
    $objFleet5Player->dbRowParse($dbPlayerRow);
1133
    $this->setLocatedAt($objFleet5Player);
1134
1135
    $this->mission_type = $mission;
1136
1137
    $this->dbOwnerRow = $dbPlayerRow;
1138
1139
    $this->set_start_planet($dbPlanetRow);
1140
    $this->dbSourcePlanetRow = $dbPlanetRow;
1141
1142
    $this->setTargetFromVectorObject($targetVector);
1143
    $this->targetVector = $targetVector;
1144
1145
    $this->populateTargetPlanet();
1146
1147
    $this->unitsSetFromArray($ships);
1148
1149
    $this->_group_id = intval($fleet_group_mr);
1150
1151
    $this->oldSpeedInTens = $oldSpeedInTens;
1152
1153
    $this->targetedUnitId = $targetedUnitId;
1154
1155
    $this->captainId = $captainId;
1156
1157
    $this->_time_launch = SN_TIME_NOW;
1158
1159
    $this->renderParamCoordinates();
1160
1161
  }
1162
1163
  protected function restrictTargetTypeByMission() {
1164
    if ($this->_mission_type == MT_MISSILE) {
1165
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1166
    } elseif ($this->_mission_type == MT_COLONIZE || $this->_mission_type == MT_EXPLORE) {
1167
      // TODO - PT_NONE
1168
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1169
    } elseif ($this->_mission_type == MT_RECYCLE) {
1170
      $this->allowed_planet_types = array(PT_DEBRIS => PT_DEBRIS);
1171
    } elseif ($this->_mission_type == MT_DESTROY) {
1172
      $this->allowed_planet_types = array(PT_MOON => PT_MOON);
1173
    } else {
1174
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET, PT_MOON => PT_MOON);
1175
    }
1176
  }
1177
1178
  protected function populateTargetPlanet() {
1179
    $targetPlanetCoords = $this->targetVector;
1180
    if ($this->mission_type != MT_NONE) {
1181
      $this->restrictTargetTypeByMission();
1182
1183
      // TODO - Нельзя тут просто менять тип планеты или координат!
1184
      // If current planet type is not allowed on mission - switch planet type
1185
      if (empty($this->allowed_planet_types[$this->targetVector->type])) {
1186
        $targetPlanetCoords->type = reset($this->allowed_planet_types);
1187
      }
1188
    }
1189
1190
    $this->dbTargetRow = db_planet_by_vector_object($targetPlanetCoords);
1191
  }
1192
1193
1194
  protected function printErrorIfNoShips() {
1195
    if ($this->unitList->unitsCount() <= 0) {
1196
      message(classLocale::$lang['fl_err_no_ships'], classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 5);
1197
    }
1198
  }
1199
1200
  /**
1201
   */
1202
  public function renderParamCoordinates() {
1203
    global $template_result;
1204
    $template_result += array(
1205
      'thisgalaxy'      => $this->dbSourcePlanetRow['galaxy'],
1206
      'thissystem'      => $this->dbSourcePlanetRow['system'],
1207
      'thisplanet'      => $this->dbSourcePlanetRow['planet'],
1208
      'thisplanet_type' => $this->dbSourcePlanetRow['planet_type'],
1209
1210
      'galaxy'         => $this->targetVector->galaxy,
1211
      'system'         => $this->targetVector->system,
1212
      'planet'         => $this->targetVector->planet,
1213
      'planet_type'    => $this->targetVector->type,
1214
      'target_mission' => $this->_mission_type,
1215
      'MISSION_NAME'   => $this->_mission_type ? classLocale::$lang['type_mission'][$this->_mission_type] : '',
1216
1217
      'MT_COLONIZE' => MT_COLONIZE,
1218
    );
1219
  }
1220
1221
1222
  protected function renderFleetCoordinates($missionStartTimeStamp = SN_TIME_NOW, $timeMissionJob = 0) {
1223
    $timeToReturn = $this->travelData['duration'] * 2 + $timeMissionJob;
1224
1225
    return array(
1226
      'ID'                 => 1,
1227
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$this->dbSourcePlanetRow['planet_type']],
1228
      'START_COORDS'       => uni_render_coordinates($this->dbSourcePlanetRow),
1229
      'START_NAME'         => $this->dbSourcePlanetRow['name'],
1230
      'START_TIME_TEXT'    => date(FMT_DATE_TIME, $missionStartTimeStamp + $timeToReturn + SN_CLIENT_TIME_DIFF),
1231
      'START_LEFT'         => floor($this->travelData['duration'] * 2 + $timeMissionJob),
1232
      'END_TYPE_TEXT_SH'   =>
1233
        !empty($this->targetVector->type)
1234
          ? classLocale::$lang['sys_planet_type_sh'][$this->targetVector->type]
1235
          : '',
1236
      'END_COORDS'         => uniRenderVector($this->targetVector),
1237
      'END_NAME'           => !empty($this->dbTargetRow['name']) ? $this->dbTargetRow['name'] : '',
1238
      'END_TIME_TEXT'      => date(FMT_DATE_TIME, $missionStartTimeStamp + $this->travelData['duration'] + SN_CLIENT_TIME_DIFF),
1239
      'END_LEFT'           => floor($this->travelData['duration']),
1240
    );
1241
  }
1242
1243
  /**
1244
   * @param int $missionStartTimeStamp
1245
   * @param int $timeMissionJob
1246
   *
1247
   * @return array
1248
   *
1249
   * @throws Exception
1250
   */
1251
  protected function renderFleet($missionStartTimeStamp = SN_TIME_NOW, $timeMissionJob = 0) {
1252
    $this->printErrorIfNoShips();
1253
1254
    $result = $this->renderFleetCoordinates($missionStartTimeStamp, $timeMissionJob);
1255
    $result['.']['ships'] = $this->unitList->unitsRender();
1256
1257
    return $result;
1258
  }
1259
1260
  /**
1261
   * @return array
1262
   */
1263
  protected function renderAllowedMissions() {
1264
    $result = array();
1265
1266
    ksort($this->allowed_missions);
1267
    // If mission is not set - setting first mission from allowed
1268
    if (empty($this->_mission_type) && is_array($this->allowed_missions)) {
1269
      reset($this->allowed_missions);
1270
      $this->_mission_type = key($this->allowed_missions);
1271
    }
1272
    foreach ($this->allowed_missions as $key => $value) {
1273
      $result[] = array(
1274
        'ID'   => $key,
1275
        'NAME' => classLocale::$lang['type_mission'][$key],
1276
      );
1277
    };
1278
1279
    return $result;
1280
  }
1281
1282
  /**
1283
   * @param $max_duration
1284
   *
1285
   * @return array
1286
   */
1287
  protected function renderDuration($max_duration) {
1288
    $result = array();
1289
1290
    if (!$max_duration) {
1291
      return $result;
1292
    }
1293
1294
    $config_game_speed_expedition = ($this->_mission_type == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1);
1295
    for ($i = 1; $i <= $max_duration; $i++) {
1296
      $result[] = array(
1297
        'ID'   => $i,
1298
        'TIME' => pretty_time(ceil($i * 3600 / $config_game_speed_expedition)),
1299
      );
1300
    }
1301
1302
    return $result;
1303
  }
1304
1305
  /**
1306
   * @param array $planetResources
1307
   *
1308
   * @return array
1309
   */
1310
  // TODO - REDO to resource_id
1311
  protected function renderPlanetResources(&$planetResources) {
1312
    $result = array();
1313
1314
    $i = 0;
1315
    foreach ($planetResources as $resource_id => $resource_amount) {
1316
      $result[] = array(
1317
        'ID'        => $i++, // $resource_id,
1318
        'ON_PLANET' => $resource_amount,
1319
        'TEXT'      => pretty_number($resource_amount),
1320
        'NAME'      => classLocale::$lang['tech'][$resource_id],
1321
      );
1322
    }
1323
1324
    return $result;
1325
  }
1326
1327
  /**
1328
   * @return array
1329
   */
1330
  protected function renderAllowedPlanetTypes() {
1331
    $result = array();
1332
1333
    foreach ($this->allowed_planet_types as $possible_planet_type_id) {
1334
      $result[] = array(
1335
        'ID'         => $possible_planet_type_id,
1336
        'NAME'       => classLocale::$lang['sys_planet_type'][$possible_planet_type_id],
1337
        'NAME_SHORT' => classLocale::$lang['sys_planet_type_sh'][$possible_planet_type_id],
1338
      );
1339
    }
1340
1341
    return $result;
1342
  }
1343
1344
1345
  protected function renderFleet1TargetSelect(&$shortcut) {
1346
    global $note_priority_classes;
1347
1348
    $name = !empty($shortcut['title']) ? $shortcut['title'] : $shortcut['name'];
1349
1350
    $result = array(
1351
      'NAME'       => $name,
1352
      'GALAXY'     => $shortcut['galaxy'],
1353
      'SYSTEM'     => $shortcut['system'],
1354
      'PLANET'     => $shortcut['planet'],
1355
      'TYPE'       => $shortcut['planet_type'],
1356
      'TYPE_PRINT' => classLocale::$lang['fl_shrtcup'][$shortcut['planet_type']],
1357
    );
1358
1359
    if (isset($shortcut['priority'])) {
1360
      $result += array(
1361
        'PRIORITY'       => $shortcut['priority'],
1362
        'PRIORITY_CLASS' => $note_priority_classes[$shortcut['priority']],
1363
      );
1364
    }
1365
1366
    if (isset($shortcut['id'])) {
1367
      $result += array(
1368
        'ID' => $shortcut['id'],
1369
      );
1370
    }
1371
1372
    return $result;
1373
  }
1374
1375
  /**
1376
   * @return array
1377
   */
1378
  protected function renderFleetShortcuts() {
1379
    $result = array();
1380
1381
    // Building list of shortcuts
1382
    $query = db_note_list_select_by_owner_and_planet($this->dbOwnerRow);
1383
    while ($row = db_fetch($query)) {
1384
      $result[] = $this->renderFleet1TargetSelect($row);
1385
    }
1386
1387
    return $result;
1388
  }
1389
1390
  /**
1391
   * Building list of own planets & moons
1392
   *
1393
   * @return array
1394
   */
1395
  protected function renderOwnPlanets() {
1396
    $result = array();
1397
1398
    $colonies = db_planet_list_sorted($this->dbOwnerRow);
1399
    if (count($colonies) <= 1) {
1400
      return $result;
1401
    }
1402
1403
    foreach ($colonies as $row) {
1404
      if ($row['id'] == $this->dbSourcePlanetRow['id']) {
1405
        continue;
1406
      }
1407
1408
      $result[] = $this->renderFleet1TargetSelect($row);
1409
    }
1410
1411
    return $result;
1412
  }
1413
1414
  /**
1415
   * @return array
1416
   */
1417
  protected function renderACSList() {
1418
    $result = array();
1419
1420
    $query = db_acs_get_list();
1421
    while ($row = db_fetch($query)) {
1422
      $members = explode(',', $row['eingeladen']);
1423
      foreach ($members as $a => $b) {
1424
        if ($b == $this->dbOwnerRow['id']) {
1425
          $result[] = $this->renderFleet1TargetSelect($row);
1426
        }
1427
      }
1428
    }
1429
1430
    return $result;
1431
  }
1432
1433
1434
  /**
1435
   * @param $template_result
1436
   */
1437
  protected function renderShipSortOptions(&$template_result) {
1438
    foreach (classLocale::$lang['player_option_fleet_ship_sort'] as $sort_id => $sort_text) {
1439
      $template_result['.']['ship_sort_list'][] = array(
1440
        'VALUE' => $sort_id,
1441
        'TEXT'  => $sort_text,
1442
      );
1443
    }
1444
    $template_result += array(
1445
      'FLEET_SHIP_SORT'         => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT],
1446
      'FLEET_SHIP_SORT_INVERSE' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE],
1447
    );
1448
  }
1449
1450
1451
  /**
1452
   *
1453
   */
1454
  public function fleetPage0() {
1455
    global $template_result;
1456
1457
    lng_include('overview');
1458
1459
    if (empty($this->dbSourcePlanetRow)) {
1460
      message(classLocale::$lang['fl_noplanetrow'], classLocale::$lang['fl_error']);
1461
    }
1462
1463
    // TODO - redo to unitlist render/unit render
1464
    $this->renderAvailableShips($template_result, $this->dbOwnerRow, $this->dbSourcePlanetRow);
1465
1466
    $this->renderShipSortOptions($template_result);
1467
1468
    /**
1469
     * @var Player $playerOwner
1470
     */
1471
    $playerOwner = $this->getLocatedAt();
1472
1473
    $template_result += array(
1474
      'FLYING_FLEETS'      => $playerOwner->fleetsFlying(),
1475
      'MAX_FLEETS'         => $playerOwner->fleetsMax(),
1476
      'FREE_FLEETS'        => $playerOwner->fleetsMax() - $playerOwner->fleetsFlying(),
1477
      'FLYING_EXPEDITIONS' => $playerOwner->expeditionsFlying(),
1478
      'MAX_EXPEDITIONS'    => $playerOwner->expeditionsMax(),
1479
      'FREE_EXPEDITIONS'   => $playerOwner->expeditionsMax() - $playerOwner->expeditionsFlying(),
1480
      'COLONIES_CURRENT'   => $playerOwner->coloniesCurrent(),
1481
      'COLONIES_MAX'       => $playerOwner->coloniesMax(),
1482
1483
      'TYPE_NAME' => classLocale::$lang['fl_planettype'][$this->targetVector->type],
1484
1485
      'speed_factor' => flt_server_flight_speed_multiplier(),
1486
1487
      'PLANET_RESOURCES' => pretty_number($this->dbSourcePlanetRow['metal'] + $this->dbSourcePlanetRow['crystal'] + $this->dbSourcePlanetRow['deuterium']),
1488
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1489
1490
      'PLAYER_OPTION_FLEET_SHIP_SELECT_OLD'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SELECT_OLD],
1491
      'PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED],
1492
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY'    => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY],
1493
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION],
1494
    );
1495
1496
    $template = gettemplate('fleet0', true);
1497
    $template->assign_recursive($template_result);
1498
    display($template, classLocale::$lang['fl_title']);
1499
  }
1500
1501
  /**
1502
   *
1503
   */
1504
  public function fleetPage1() {
1505
    global $template_result;
1506
1507
    $template_result['.']['fleets'][] = $this->renderFleet(SN_TIME_NOW);
1508
    $template_result['.']['possible_planet_type_id'] = $this->renderAllowedPlanetTypes();
1509
    $template_result['.']['colonies'] = $this->renderOwnPlanets();
1510
    $template_result['.']['shortcut'] = $this->renderFleetShortcuts();
1511
    $template_result['.']['acss'] = $this->renderACSList();
1512
1513
    $template_result += array(
1514
      'speed_factor' => flt_server_flight_speed_multiplier(),
1515
1516
      'fleet_speed'    => flt_fleet_speed($this->dbOwnerRow, $this->shipsGetArray()),
1517
      'fleet_capacity' => $this->shipsGetCapacity(),
1518
1519
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1520
1521
      'PAGE_HINT' => classLocale::$lang['fl_page1_hint'],
1522
    );
1523
1524
    $template = gettemplate('fleet1', true);
1525
    $template->assign_recursive($template_result);
1526
    display($template, classLocale::$lang['fl_title']);
1527
  }
1528
1529
  /**
1530
   *
1531
   */
1532
  public function fleetPage2() {
1533
    global $template_result;
1534
1535
    $this->travelData = $this->flt_travel_data($this->oldSpeedInTens);
1536
    $planetResources = $this->resourcesGetOnPlanet();
1537
    try {
1538
      $validator = new FleetValidator($this);
1539
      $validator->validate();
1540
    } catch (Exception $e) {
1541
      // TODO - MESSAGE BOX
1542
      sn_db_transaction_rollback();
1543
      pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
1544
    }
1545
1546
    // Flight allowed here
1547
    pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1548
1549
    $template_result['.']['missions'] = $this->renderAllowedMissions();
1550
1551
    $template_result['.']['fleets'][] = $this->renderFleet(SN_TIME_NOW);
1552
1553
    $max_duration =
1554
      $this->_mission_type == MT_EXPLORE
1555
        ? get_player_max_expedition_duration($this->dbOwnerRow)
1556
        : (isset($this->allowed_missions[MT_HOLD]) ? 12 : 0);
1557
    $template_result['.']['duration'] = $this->renderDuration($max_duration);
1558
1559
    $this->captainGet();
1560
    $template_result += $this->renderCaptain();
1561
1562
    $template_result['.']['resources'] = $this->renderPlanetResources($planetResources);
1563
1564
    $template_result += array(
1565
      'planet_metal'     => $planetResources[RES_METAL],
1566
      'planet_crystal'   => $planetResources[RES_CRYSTAL],
1567
      'planet_deuterium' => $planetResources[RES_DEUTERIUM],
1568
1569
      'fleet_capacity' => $this->shipsGetCapacity() - $this->travelData['consumption'],
1570
      'speed'          => $this->oldSpeedInTens,
1571
      'fleet_group'    => $this->_group_id,
1572
1573
      'MAX_DURATION'          => $max_duration,
1574
1575
      // TODO - remove
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...
1576
//      'IS_TRANSPORT_MISSIONS' => !empty($this->allowed_missions[$this->_mission_type]['transport']),
1577
      'IS_TRANSPORT_MISSIONS' => true,
1578
1579
      'PLAYER_COLONIES_CURRENT' => get_player_current_colonies($this->dbOwnerRow),
1580
      'PLAYER_COLONIES_MAX'     => get_player_max_colonies($this->dbOwnerRow),
1581
    );
1582
1583
    $template = gettemplate('fleet2', true);
1584
    $template->assign_recursive($template_result);
1585
    display($template, classLocale::$lang['fl_title']);
1586
  }
1587
1588
  /**
1589
   *
1590
   */
1591
  public function fleetPage3() {
1592
    global $template_result;
1593
1594
    $this->isRealFlight = true;
1595
1596
    sn_db_transaction_start();
1597
1598
    db_user_lock_with_target_owner_and_acs($this->dbOwnerRow, $this->dbTargetRow);
1599
1600
    // Checking for group
1601
    $this->groupCheck();
1602
1603
    $this->dbOwnerRow = db_user_by_id($this->dbOwnerRow['id'], true);
0 ignored issues
show
Documentation Bug introduced by
It seems like db_user_by_id($this->dbOwnerRow['id'], true) can also be of type false. However, the property $dbOwnerRow is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1604
    $this->dbSourcePlanetRow = db_planet_by_id($this->dbSourcePlanetRow['id'], true);
1605
    if (!empty($this->dbTargetRow['id'])) {
1606
      $this->dbTargetRow = db_planet_by_id($this->dbTargetRow['id'], true);
1607
    }
1608
    if (!empty($this->dbTargetRow['id_owner'])) {
1609
      $this->dbTargetOwnerRow = db_planet_by_id($this->dbTargetRow['id_owner'], true);
1610
    }
1611
1612
    $this->resource_list = array(
1613
      RES_METAL     => max(0, floor(sys_get_param_float('resource0'))),
1614
      RES_CRYSTAL   => max(0, floor(sys_get_param_float('resource1'))),
1615
      RES_DEUTERIUM => max(0, floor(sys_get_param_float('resource2'))),
1616
    );
1617
1618
    $this->captainGet();
1619
1620
    $this->travelData = $this->flt_travel_data($this->oldSpeedInTens);
1621
1622
    try {
1623
      $validator = new FleetValidator($this);
1624
      $validator->validate();
1625
    } catch (Exception $e) {
1626
      // TODO - MESSAGE BOX
1627
      sn_db_transaction_rollback();
1628
      pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
1629
    }
1630
1631
    // Flight allowed here
1632
    pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1633
1634
1635
    // TODO check for empty mission AKA mission allowed
1636
/*
1637
    $timeMissionJob = 0;
1638
    if ($this->_mission_type == MT_ACS && $aks) {
1639
      $acsTimeToArrive = $aks['ankunft'] - SN_TIME_NOW;
1640
      if ($acsTimeToArrive < $this->travelData['duration']) {
1641
        message(classLocale::$lang['fl_aks_too_slow'] . 'Fleet arrival: ' . date(FMT_DATE_TIME, SN_TIME_NOW + $this->travelData['duration']) . " AKS arrival: " . date(FMT_DATE_TIME, $aks['ankunft']), classLocale::$lang['fl_error']);
1642
      }
1643
      // Set time to travel to ACS' TTT
1644
      $this->travelData['duration'] = $acsTimeToArrive;
1645
*/
1646
      if ($this->_mission_type != MT_ACS) {
1647
      if ($this->_mission_type == MT_EXPLORE || $this->_mission_type == MT_HOLD) {
1648
        $max_duration = $this->_mission_type == MT_EXPLORE ? get_player_max_expedition_duration($this->dbOwnerRow) : ($this->_mission_type == MT_HOLD ? 12 : 0);
1649
        if ($max_duration) {
1650
          $mission_time_in_hours = sys_get_param_id('missiontime');
1651
          if ($mission_time_in_hours > $max_duration || $mission_time_in_hours < 1) {
1652
            classSupernova::$debug->warning('Supplying wrong mission time', 'Hack attempt', 302, array('base_dump' => true));
0 ignored issues
show
Documentation introduced by
array('base_dump' => true) is of type array<string,boolean,{"base_dump":"boolean"}>, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1653
            die();
1654
          }
1655
          $timeMissionJob = ceil($mission_time_in_hours * 3600 / ($this->_mission_type == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1));
1656
        }
1657
      }
1658
    }
1659
1660
    //
1661
    //
1662
    //
1663
    //
1664
    //
1665
    //
1666
    //
1667
    //
1668
    // ---------------- END OF CHECKS ------------------------------------------------------
1669
1670
    $this->set_times($this->travelData['duration'], $timeMissionJob);
0 ignored issues
show
Bug introduced by
The variable $timeMissionJob does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1671
    $this->dbInsert();
1672
1673
    db_planet_set_by_id($this->dbSourcePlanetRow['id'],
1674
      "`metal` = `metal` - {$this->resource_list[RES_METAL]},
1675
      `crystal` = `crystal` - {$this->resource_list[RES_CRYSTAL]},
1676
      `deuterium` = `deuterium` - {$this->resource_list[RES_DEUTERIUM]} - {$this->travelData['consumption']}"
1677
    );
1678
1679
    $db_changeset = $this->unitList->db_prepare_old_changeset_for_planet($this->dbOwnerRow, $this->dbSourcePlanetRow['id']);
1680
    db_changeset_apply($db_changeset);
1681
1682
1683
    if (!empty($captain['unit_id'])) {
0 ignored issues
show
Bug introduced by
The variable $captain seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
1684
      db_unit_set_by_id($captain['unit_id'], "`unit_location_type` = " . LOC_FLEET . ", `unit_location_id` = {$this->_dbId}");
1685
    }
1686
1687
//    return $this->fleet->acs['ankunft'] - $this->fleet->time_launch >= $this->fleet->travelData['duration'];
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...
1688
//
1689
//    // Set time to travel to ACS' TTT
1690
//    $this->fleet->travelData['duration'] = $acsTimeToArrive;
1691
1692
1693
    $template_result['.']['fleets'][] = $this->renderFleet(SN_TIME_NOW, $timeMissionJob);
1694
1695
    $template_result += array(
1696
      'mission'         => classLocale::$lang['type_mission'][$this->_mission_type] . ($this->_mission_type == MT_EXPLORE || $this->_mission_type == MT_HOLD ? ' ' . pretty_time($timeMissionJob) : ''),
1697
      'dist'            => pretty_number($this->travelData['distance']),
1698
      'speed'           => pretty_number($this->travelData['fleet_speed']),
1699
      'deute_need'      => pretty_number($this->travelData['consumption']),
1700
      'from'            => "{$this->dbSourcePlanetRow['galaxy']}:{$this->dbSourcePlanetRow['system']}:{$this->dbSourcePlanetRow['planet']}",
1701
      'time_go'         => date(FMT_DATE_TIME, $this->_time_arrive_to_target),
1702
      'time_go_local'   => date(FMT_DATE_TIME, $this->_time_arrive_to_target + SN_CLIENT_TIME_DIFF),
1703
      'time_back'       => date(FMT_DATE_TIME, $this->_time_return_to_source),
1704
      'time_back_local' => date(FMT_DATE_TIME, $this->_time_return_to_source + SN_CLIENT_TIME_DIFF),
1705
    );
1706
1707
    $this->dbSourcePlanetRow = db_planet_by_id($this->dbSourcePlanetRow['id']);
1708
1709
    pdie('Stop for debug');
1710
1711
    sn_db_transaction_commit();
1712
1713
    $template = gettemplate('fleet3', true);
1714
    $template->assign_recursive($template_result);
1715
    display($template, classLocale::$lang['fl_title']);
1716
  }
1717
1718
  protected function groupCheck() {
1719
    if (empty($this->_group_id)) {
1720
      return;
1721
    }
1722
1723
    // ACS attack must exist (if acs fleet has arrived this will also return false (2 checks in 1!!!)
1724
    $this->acs = db_acs_get_by_group_id($this->_group_id);
1725
    if (empty($this->acs)) {
1726
      $this->_group_id = 0;
1727
    } else {
1728
      $this->targetVector->convertToVector($this->acs);
1729
    }
1730
  }
1731
1732
1733
  /**
1734
   * @return array
1735
   */
1736
  protected function resourcesGetOnPlanet() {
1737
    $planetResources = array();
1738
1739
    $sn_group_resources = sn_get_groups('resources_loot');
1740
    foreach ($sn_group_resources as $resource_id) {
1741
      $planetResources[$resource_id] = floor(mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, $resource_id) - ($resource_id == RES_DEUTERIUM ? $this->travelData['consumption'] : 0));
1742
    }
1743
1744
    return $planetResources;
1745
  }
1746
1747
  /**
1748
   */
1749
  public function captainGet() {
1750
    $this->captain = array();
1751
1752
    /**
1753
     * @var unit_captain $moduleCaptain
1754
     */
1755
    $moduleCaptain = !empty(sn_module::$sn_module['unit_captain']) ? sn_module::$sn_module['unit_captain'] : null;
1756
1757
    if (
1758
      !empty($moduleCaptain)
1759
      &&
1760
      $moduleCaptain->manifest['active']
1761
    ) {
1762
      $this->captain = $moduleCaptain->unit_captain_get($this->dbSourcePlanetRow['id']);
1763
    }
1764
  }
1765
1766
  /**
1767
   * @return array
1768
   */
1769
  protected function renderCaptain() {
1770
    $result = array();
1771
1772
    if (!empty($this->captain['unit_id']) && $this->captain['unit_location_type'] == LOC_PLANET) {
1773
      $result = array(
1774
        'CAPTAIN_ID'     => $this->captain['unit_id'],
1775
        'CAPTAIN_LEVEL'  => $this->captain['captain_level'],
1776
        'CAPTAIN_SHIELD' => $this->captain['captain_shield'],
1777
        'CAPTAIN_ARMOR'  => $this->captain['captain_armor'],
1778
        'CAPTAIN_ATTACK' => $this->captain['captain_attack'],
1779
      );
1780
    }
1781
1782
    return $result;
1783
  }
1784
1785
}
1786