Completed
Push — work-fleets ( e7900f...9522d3 )
by SuperNova.WS
05:39
created

Fleet::restrictMissionMissile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 21
rs 9.3142
cc 3
eloc 13
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
34
  // DBRow inheritance *************************************************************************************************
35
36
  /**
37
   * Table name in DB
38
   *
39
   * @var string
40
   */
41
  protected static $_table = 'fleets';
42
  /**
43
   * Name of ID field in DB
44
   *
45
   * @var string
46
   */
47
  protected static $_dbIdFieldName = 'fleet_id';
48
  /**
49
   * DB_ROW to Class translation scheme
50
   *
51
   * @var array
52
   */
53
  protected static $_properties = array(
54
    'dbId'          => array(
55
      P_DB_FIELD => 'fleet_id',
56
    ),
57
    'playerOwnerId' => array(
58
      P_METHOD_EXTRACT => 'ownerExtract',
59
      P_METHOD_INJECT  => 'ownerInject',
60
//      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...
61
    ),
62
    'mission_type'  => array(
63
      P_DB_FIELD   => 'fleet_mission',
64
      P_FUNC_INPUT => 'intval',
65
    ),
66
67
    'target_owner_id' => array(
68
      P_DB_FIELD => 'fleet_target_owner',
69
    ),
70
    'group_id'        => array(
71
      P_DB_FIELD => 'fleet_group',
72
    ),
73
    'is_returning'    => array(
74
      P_DB_FIELD   => 'fleet_mess',
75
      P_FUNC_INPUT => 'intval',
76
    ),
77
78
    'shipCount' => array(
79
      P_DB_FIELD  => 'fleet_amount',
80
// 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...
81
//      P_FUNC_OUTPUT => 'get_ship_count',
82
//      P_DB_FIELDS_LINKED => array(
83
//        'fleet_amount',
84
//      ),
85
      P_READ_ONLY => true,
86
    ),
87
88
    'time_launch' => array(
89
      P_DB_FIELD => 'start_time',
90
    ),
91
92
    'time_arrive_to_target'     => array(
93
      P_DB_FIELD => 'fleet_start_time',
94
    ),
95
    'time_mission_job_complete' => array(
96
      P_DB_FIELD => 'fleet_end_stay',
97
    ),
98
    'time_return_to_source'     => array(
99
      P_DB_FIELD => 'fleet_end_time',
100
    ),
101
102
    'fleet_start_planet_id' => array(
103
      P_DB_FIELD   => 'fleet_start_planet_id',
104
      P_FUNC_INPUT => 'nullIfEmpty',
105
    ),
106
107
    'fleet_start_galaxy' => array(
108
      P_DB_FIELD => 'fleet_start_galaxy',
109
    ),
110
    'fleet_start_system' => array(
111
      P_DB_FIELD => 'fleet_start_system',
112
    ),
113
    'fleet_start_planet' => array(
114
      P_DB_FIELD => 'fleet_start_planet',
115
    ),
116
    'fleet_start_type'   => array(
117
      P_DB_FIELD => 'fleet_start_type',
118
    ),
119
120
    'fleet_end_planet_id' => array(
121
      P_DB_FIELD   => 'fleet_end_planet_id',
122
      P_FUNC_INPUT => 'nullIfEmpty',
123
    ),
124
    'fleet_end_galaxy'    => array(
125
      P_DB_FIELD => 'fleet_end_galaxy',
126
    ),
127
    'fleet_end_system'    => array(
128
      P_DB_FIELD => 'fleet_end_system',
129
    ),
130
    'fleet_end_planet'    => array(
131
      P_DB_FIELD => 'fleet_end_planet',
132
    ),
133
    'fleet_end_type'      => array(
134
      P_DB_FIELD => 'fleet_end_type',
135
    ),
136
137
    'resource_list' => array(
138
      P_METHOD_EXTRACT   => 'resourcesExtract',
139
      P_METHOD_INJECT    => 'resourcesInject',
140
      P_DB_FIELDS_LINKED => array(
141
        'fleet_resource_metal',
142
        'fleet_resource_crystal',
143
        'fleet_resource_deuterium',
144
      ),
145
    ),
146
  );
147
148
149
  // UnitContainer inheritance *****************************************************************************************
150
  /**
151
   * Type of this location
152
   *
153
   * @var int $locationType
154
   */
155
  protected static $locationType = LOC_FLEET;
156
157
158
  // New properties ****************************************************************************************************
159
  /**
160
   * `fleet_owner`
161
   *
162
   * @var int
163
   */
164
  protected $_playerOwnerId = 0;
165
  /**
166
   * `fleet_group`
167
   *
168
   * @var int
169
   */
170
  protected $_group_id = 0;
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
  protected $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
  protected $allowed_missions = array();
258
  protected $allowed_planet_types = array(
259
    // PT_NONE => PT_NONE,
260
    PT_PLANET => PT_PLANET,
261
    PT_MOON   => PT_MOON,
262
    PT_DEBRIS => PT_DEBRIS
263
  );
264
265
  // TODO - Move to Player
266
  public $dbOwnerRow = array();
267
  public $dbSourcePlanetRow = array();
268
269
  /**
270
   * GSPT coordinates of target
271
   *
272
   * @var Vector
273
   */
274
  public $targetVector = array();
275
  /**
276
   * Target planet row
277
   *
278
   * @var array
279
   */
280
  public $dbTargetRow = array();
281
282
283
  /**
284
   * Returns location's player owner ID
285
   *
286
   * @return int
287
   */
288
  // TODO - REMOVE! TEMPORARY UNTIL THERE BE FULLLY FUNCTIONAL Player CLASS AND FLEETS WOULD BE LOCATED ON PLANET OR PLAYER!!!!!
289
//  public function getPlayerOwnerId() {
290
//    return $this->_dbId;
291
//  }
292
293
  /**
294
   * Fleet constructor.
295
   */
296
  public function __construct() {
297
    parent::__construct();
298
    $this->allowed_missions = sn_get_groups('missions');
0 ignored issues
show
Documentation Bug introduced by
It seems like sn_get_groups('missions') of type * is incompatible with the declared type array of property $allowed_missions.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
299
  }
300
301
  /**
302
   * @param array $playerRow
303
   * @param array $planetRow
304
   *
305
   * @return array
306
   */
307
  public function tplRenderAvailableShips($playerRow, $planetRow) {
308
    $record_index = 0;
309
    $ship_list = array();
310
    foreach(sn_get_groups('fleet') as $n => $unit_id) {
311
      $unit_level = mrc_get_level($playerRow, $planetRow, $unit_id, false, true);
312
      if($unit_level <= 0) {
313
        continue;
314
      }
315
      $ship_data = get_ship_data($unit_id, $playerRow);
316
      $ship_list[$unit_id] = array(
317
        '__INDEX'          => $record_index++,
318
        'ID'               => $unit_id,
319
        'NAME'             => classLocale::$lang['tech'][$unit_id],
320
        'AMOUNT'           => $unit_level,
321
        'AMOUNT_TEXT'      => pretty_number($unit_level),
322
        'CONSUMPTION'      => $ship_data['consumption'],
323
        'CONSUMPTION_TEXT' => pretty_number($ship_data['consumption']),
324
        'SPEED'            => $ship_data['speed'],
325
        'SPEED_TEXT'       => pretty_number($ship_data['speed']),
326
        'CAPACITY'         => $ship_data['capacity'],
327
        'CAPACITY_TEXT'    => pretty_number($ship_data['capacity']),
328
      );
329
    }
330
331
    return $ship_list;
332
  }
333
334
  /**
335
   * @param $ship_list
336
   */
337
  public function tplSortShipList(&$ship_list) {
338
    $fleet_ship_sort = classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT];
339
    $fleet_ship_sort_inverse = classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE];
340
    if($fleet_ship_sort || $fleet_ship_sort_inverse != PLAYER_OPTION_SORT_ORDER_PLAIN) {
341
      switch($fleet_ship_sort) {
342
        case PLAYER_OPTION_SORT_NAME:
343
          $fleet_ship_sort_field = 'NAME';
344
        break;
345
        case PLAYER_OPTION_SORT_SPEED:
346
          $fleet_ship_sort_field = 'SPEED';
347
        break;
348
        case PLAYER_OPTION_SORT_COUNT:
349
          $fleet_ship_sort_field = 'AMOUNT';
350
        break;
351
        case PLAYER_OPTION_SORT_ID:
352
          $fleet_ship_sort_field = 'ID';
353
        break;
354
        default:
355
          $fleet_ship_sort_field = '__INDEX';
356
        break;
357
      }
358
      $fleet_ship_sort_inverse_a = $fleet_ship_sort_inverse ? -1 : 1;
359
      usort($ship_list, function ($a, $b) use ($fleet_ship_sort_field, $fleet_ship_sort_inverse_a) {
360
        return $a[$fleet_ship_sort_field] < $b[$fleet_ship_sort_field] ? -1 * $fleet_ship_sort_inverse_a : (
361
        $a[$fleet_ship_sort_field] > $b[$fleet_ship_sort_field] ? 1 * $fleet_ship_sort_inverse_a : 0
362
        );
363
      });
364
    }
365
  }
366
367
  public function isEmpty() {
368
    return !$this->resourcesGetTotal() && !$this->shipsGetTotal();
369
  }
370
371
//  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...
372
//    return $this->playerOwnerId;
373
//  }
374
375
  /**
376
   * Initializes Fleet from user params and posts it to DB
377
   */
378
  public function dbInsert() {
379
    // WARNING! MISSION TIMES MUST BE SET WITH set_times() method!
380
    // TODO - more checks!
381
    if(empty($this->_time_launch)) {
382
      die('Fleet time not set!');
383
    }
384
385
    parent::dbInsert();
386
  }
387
388
389
  /* FLEET DB ACCESS =================================================================================================*/
390
391
  /**
392
   * LOCK - Lock all records which can be used with mission
393
   *
394
   * @param $mission_data
395
   * @param $fleet_id
396
   *
397
   * @return array|bool|mysqli_result|null
398
   */
399
  public function dbLockFlying(&$mission_data) {
400
    // Тупо лочим всех юзеров, чьи флоты летят или улетают с координат отбытия/прибытия $fleet_row
401
    // Что бы делать это умно - надо учитывать fleet__mess во $fleet_row и в таблице fleets
402
403
    $fleet_id_safe = idval($this->_dbId);
404
405
    return doquery(
406
    // Блокировка самого флота
407
      "SELECT 1 FROM {{fleets}} AS f " .
408
409
      // Блокировка всех юнитов, принадлежащих этому флоту
410
      "LEFT JOIN {{unit}} as unit ON unit.unit_location_type = " . static::$locationType . " AND unit.unit_location_id = f.fleet_id " .
411
412
      // Блокировка всех прилетающих и улетающих флотов, если нужно
413
      // TODO - lock fleets by COORDINATES
414
      ($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 " : '') .
415
      // Блокировка всех юнитов, принадлежащих прилетающим и улетающим флотам - ufd = unit_fleet_destination
416
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{unit}} AS ufd ON ufd.unit_location_type = " . static::$locationType . " AND ufd.unit_location_id = fd.fleet_id " : '') .
417
418
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{users}} AS ud ON ud.id = f.fleet_target_owner " : '') .
419
      // Блокировка всех юнитов, принадлежащих владельцу планеты-цели
420
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS unit_player_dest ON unit_player_dest.unit_player_id = ud.id " : '') .
421
      // Блокировка планеты-цели
422
      ($mission_data['dst_planet'] ? "LEFT JOIN {{planets}} AS pd ON pd.id = f.fleet_end_planet_id " : '') .
423
      // Блокировка всех юнитов, принадлежащих планете-цели - НЕ НУЖНО. Уже залочили ранее, как принадлежащие игроку-цели
424
//      ($mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS upd ON upd.unit_location_type = " . LOC_PLANET . " AND upd.unit_location_id = pd.id " : '') .
425
426
427
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{users}} AS us ON us.id = f.fleet_owner " : '') .
428
      // Блокировка всех юнитов, принадлежащих владельцу флота
429
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS unit_player_src ON unit_player_src.unit_player_id = us.id " : '') .
430
      // Блокировка планеты отправления
431
      ($mission_data['src_planet'] ? "LEFT JOIN {{planets}} AS ps ON ps.id = f.fleet_start_planet_id " : '') .
432
      // Блокировка всех юнитов, принадлежащих планете с которой юниты были отправлены - НЕ НУЖНО. Уже залочили ранее, как принадлежащие владельцу флота
433
//      ($mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS ups ON ups.unit_location_type = " . LOC_PLANET . " AND ups.unit_location_id = ps.id " : '') .
434
435
      "WHERE f.fleet_id = {$fleet_id_safe} GROUP BY 1 FOR UPDATE"
436
    );
437
  }
438
439
  /**
440
   * Lock all fields that belongs to operation
441
   *
442
   * @param $dbId
443
   *
444
   * @internal param DBLock $dbRow - Object that accumulates locks
445
   *
446
   */
447
  // TODO = make static
448
  public function dbGetLockById($dbId) {
449
    doquery(
450
    // Блокировка самого флота
451
      "SELECT 1 FROM {{fleets}} AS FLEET0 " .
452
      // Lock fleet owner
453
      "LEFT JOIN {{users}} as USER0 on USER0.id = FLEET0.fleet_owner " .
454
      // Блокировка всех юнитов, принадлежащих этому флоту
455
      "LEFT JOIN {{unit}} as UNIT0 ON UNIT0.unit_location_type = " . LOC_FLEET . " AND UNIT0.unit_location_id = FLEET0.fleet_id " .
456
457
      // Без предварительной выборки неизвестно - куда летит этот флот.
458
      // Поэтому надо выбирать флоты, чьи координаты прибытия ИЛИ отбытия совпадают с координатами прибытия ИЛИ отбытия текущего флота.
459
      // Получаем матрицу 2х2 - т.е. 4 подзапроса.
460
      // При блокировке всегда нужно выбирать И лпанету, И луну - поскольку при бое на орбите луны обломки падают на орбиту планеты.
461
      // Поэтому тип планеты не указывается
462
463
      // Lock fleet heading to destination planet. Only if FLEET0.fleet_mess == 0
464
      "LEFT JOIN {{fleets}} AS FLEET1 ON
465
        FLEET1.fleet_mess = 0 AND FLEET0.fleet_mess = 0 AND
466
        FLEET1.fleet_end_galaxy = FLEET0.fleet_end_galaxy AND
467
        FLEET1.fleet_end_system = FLEET0.fleet_end_system AND
468
        FLEET1.fleet_end_planet = FLEET0.fleet_end_planet
469
      " .
470
      // Блокировка всех юнитов, принадлежащих этим флотам
471
      "LEFT JOIN {{unit}} as UNIT1 ON UNIT1.unit_location_type = " . LOC_FLEET . " AND UNIT1.unit_location_id = FLEET1.fleet_id " .
472
      // Lock fleet owner
473
      "LEFT JOIN {{users}} as USER1 on USER1.id = FLEET1.fleet_owner " .
474
475
      "LEFT JOIN {{fleets}} AS FLEET2 ON
476
        FLEET2.fleet_mess = 1   AND FLEET0.fleet_mess = 0 AND
477
        FLEET2.fleet_start_galaxy = FLEET0.fleet_end_galaxy AND
478
        FLEET2.fleet_start_system = FLEET0.fleet_end_system AND
479
        FLEET2.fleet_start_planet = FLEET0.fleet_end_planet
480
      " .
481
      // Блокировка всех юнитов, принадлежащих этим флотам
482
      "LEFT JOIN {{unit}} as UNIT2 ON
483
        UNIT2.unit_location_type = " . LOC_FLEET . " AND
484
        UNIT2.unit_location_id = FLEET2.fleet_id
485
      " .
486
      // Lock fleet owner
487
      "LEFT JOIN {{users}} as USER2 on
488
        USER2.id = FLEET2.fleet_owner
489
      " .
490
491
      // Lock fleet heading to source planet. Only if FLEET0.fleet_mess == 1
492
      "LEFT JOIN {{fleets}} AS FLEET3 ON
493
        FLEET3.fleet_mess = 0 AND FLEET0.fleet_mess = 1 AND
494
        FLEET3.fleet_end_galaxy = FLEET0.fleet_start_galaxy AND
495
        FLEET3.fleet_end_system = FLEET0.fleet_start_system AND
496
        FLEET3.fleet_end_planet = FLEET0.fleet_start_planet
497
      " .
498
      // Блокировка всех юнитов, принадлежащих этим флотам
499
      "LEFT JOIN {{unit}} as UNIT3 ON
500
        UNIT3.unit_location_type = " . LOC_FLEET . " AND
501
        UNIT3.unit_location_id = FLEET3.fleet_id
502
      " .
503
      // Lock fleet owner
504
      "LEFT JOIN {{users}} as USER3 on USER3.id = FLEET3.fleet_owner " .
505
506
      "LEFT JOIN {{fleets}} AS FLEET4 ON
507
        FLEET4.fleet_mess = 1   AND FLEET0.fleet_mess = 1 AND
508
        FLEET4.fleet_start_galaxy = FLEET0.fleet_start_galaxy AND
509
        FLEET4.fleet_start_system = FLEET0.fleet_start_system AND
510
        FLEET4.fleet_start_planet = FLEET0.fleet_start_planet
511
      " .
512
      // Блокировка всех юнитов, принадлежащих этим флотам
513
      "LEFT JOIN {{unit}} as UNIT4 ON
514
        UNIT4.unit_location_type = " . LOC_FLEET . " AND
515
        UNIT4.unit_location_id = FLEET4.fleet_id
516
      " .
517
      // Lock fleet owner
518
      "LEFT JOIN {{users}} as USER4 on
519
        USER4.id = FLEET4.fleet_owner
520
      " .
521
522
523
      // Locking start planet
524
      "LEFT JOIN {{planets}} AS PLANETS5 ON
525
        FLEET0.fleet_mess = 1 AND
526
        PLANETS5.galaxy = FLEET0.fleet_start_galaxy AND
527
        PLANETS5.system = FLEET0.fleet_start_system AND
528
        PLANETS5.planet = FLEET0.fleet_start_planet
529
      " .
530
      // Lock planet owner
531
      "LEFT JOIN {{users}} as USER5 on
532
        USER5.id = PLANETS5.id_owner
533
      " .
534
      // Блокировка всех юнитов, принадлежащих этой планете
535
      "LEFT JOIN {{unit}} as UNIT5 ON
536
        UNIT5.unit_location_type = " . LOC_PLANET . " AND
537
        UNIT5.unit_location_id = PLANETS5.id
538
      " .
539
540
541
      // Locking destination planet
542
      "LEFT JOIN {{planets}} AS PLANETS6 ON
543
        FLEET0.fleet_mess = 0 AND
544
        PLANETS6.galaxy = FLEET0.fleet_end_galaxy AND
545
        PLANETS6.system = FLEET0.fleet_end_system AND
546
        PLANETS6.planet = FLEET0.fleet_end_planet
547
      " .
548
      // Lock planet owner
549
      "LEFT JOIN {{users}} as USER6 on
550
        USER6.id = PLANETS6.id_owner
551
      " .
552
      // Блокировка всех юнитов, принадлежащих этой планете
553
      "LEFT JOIN {{unit}} as UNIT6 ON
554
        UNIT6.unit_location_type = " . LOC_PLANET . " AND
555
        UNIT6.unit_location_id = PLANETS6.id
556
      " .
557
      "WHERE FLEET0.fleet_id = {$dbId} GROUP BY 1 FOR UPDATE"
558
    );
559
  }
560
561
562
  public function dbRowParse($db_row) {
563
    parent::dbRowParse($db_row); // TODO: Change the autogenerated stub
564
    $player = new Player();
565
    $player->dbLoad($db_row['fleet_owner']);
566
    $this->setLocatedAt($player);
567
  }
568
569
  /* FLEET HELPERS =====================================================================================================*/
570
  /**
571
   * Forcibly returns fleet before time outs
572
   */
573
  public function commandReturn() {
574
    $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;
575
576
    $this->markReturned();
577
578
    // Считаем, что флот уже долетел TODO
579
    $this->time_arrive_to_target = SN_TIME_NOW;
580
    // Убираем флот из группы
581
    $this->group_id = 0;
582
    // Отменяем работу в точке назначения
583
    $this->time_mission_job_complete = 0;
584
    // TODO - правильно вычслять время возвращения - по проделанному пути, а не по старому времени возвращения
585
    $this->time_return_to_source = $ReturnFlyingTime;
586
587
    // Записываем изменения в БД
588
    $this->dbSave();
589
590
    if($this->_group_id) {
591
      // TODO: Make here to delete only one AKS - by adding aks_fleet_count to AKS table
592
      db_fleet_aks_purge();
593
    }
594
  }
595
596
597
  /**
598
   * @return array
599
   */
600
  public function target_coordinates_without_type() {
601
    return array(
602
      'galaxy' => $this->_fleet_end_galaxy,
603
      'system' => $this->_fleet_end_system,
604
      'planet' => $this->_fleet_end_planet,
605
    );
606
  }
607
608
  /**
609
   * @return array
610
   */
611
  public function target_coordinates_typed() {
612
    return array(
613
      'galaxy' => $this->_fleet_end_galaxy,
614
      'system' => $this->_fleet_end_system,
615
      'planet' => $this->_fleet_end_planet,
616
      'type'   => $this->_fleet_end_type,
617
    );
618
  }
619
620
  /**
621
   * @return array
622
   */
623
  public function launch_coordinates_typed() {
624
    return array(
625
      'galaxy' => $this->_fleet_start_galaxy,
626
      'system' => $this->_fleet_start_system,
627
      'planet' => $this->_fleet_start_planet,
628
      'type'   => $this->_fleet_start_type,
629
    );
630
  }
631
632
633
  /**
634
   * Sets object fields for fleet return
635
   */
636
  public function markReturned() {
637
    // TODO - Проверка - а не возвращается ли уже флот?
638
    $this->is_returning = 1;
639
  }
640
641
  public function isReturning() {
642
    return 1 == $this->_is_returning;
643
  }
644
645
  public function markReturnedAndSave() {
646
    $this->markReturned();
647
    $this->dbSave();
648
  }
649
650
  /**
651
   * Parses extended unit_array which can include not only ships but resources, captains etc
652
   *
653
   * @param $unit_array
654
   */
655
  // TODO - separate shipList and unitList
656
  public function unitsSetFromArray($unit_array) {
657
    if(empty($unit_array) || !is_array($unit_array)) {
658
      return;
659
    }
660
    foreach($unit_array as $unit_id => $unit_count) {
661
      $unit_count = floatval($unit_count);
662
      if(!$unit_count) {
663
        continue;
664
      }
665
666
      if($this->isShip($unit_id)) {
667
        $this->unitList->unitSetCount($unit_id, $unit_count);
668
      } elseif($this->isResource($unit_id)) {
669
        $this->resource_list[$unit_id] = $unit_count;
670
      } else {
671
        throw new Exception('Trying to pass to fleet non-resource and non-ship ' . var_export($unit_array, true), ERR_ERROR);
672
      }
673
    }
674
  }
675
676
677
  /**
678
   * Sets fleet timers based on flight duration, time on mission (HOLD/EXPLORE) and fleet departure time.
679
   *
680
   * @param int $time_to_travel - flight duration in seconds
681
   * @param int $time_on_mission - time on mission in seconds
682
   * @param int $group_sync_delta_time - delta time to adjust fleet arrival time if fleet is a part of group (i.e. ACS)
683
   * @param int $flight_departure - fleet departure from source planet timestamp. Allows to send fleet in future or in past
684
   */
685
  public function set_times($time_to_travel, $time_on_mission = 0, $group_sync_delta_time = 0, $flight_departure = SN_TIME_NOW) {
686
    $this->_time_launch = $flight_departure;
687
688
    $this->_time_arrive_to_target = $this->_time_launch + $time_to_travel + $group_sync_delta_time;
689
    $this->_time_mission_job_complete = $time_on_mission ? $this->_time_arrive_to_target + $time_on_mission : 0;
690
    $this->_time_return_to_source = ($this->_time_mission_job_complete ? $this->_time_mission_job_complete : $this->_time_arrive_to_target) + $time_to_travel;
691
  }
692
693
694
  public function parse_missile_db_row($missile_db_row) {
695
//    $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...
696
697
    if(empty($missile_db_row) || !is_array($missile_db_row)) {
698
      return;
699
    }
700
701
//      $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...
702
//      $irak_original['fleet_start_name'] = $planet_start['name'];
703
    $this->missile_target = $missile_db_row['primaer'];
704
705
    $this->_dbId = -$missile_db_row['id'];
706
    $this->_playerOwnerId = $missile_db_row['fleet_owner'];
707
    $this->_mission_type = MT_MISSILE;
708
709
    $this->_target_owner_id = $missile_db_row['fleet_target_owner'];
710
711
    $this->_group_id = 0;
712
    $this->_is_returning = 0;
713
714
    $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...
715
    $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...
716
    $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...
717
    $this->_time_return_to_source = $missile_db_row['fleet_end_time'];
718
719
    $this->_fleet_start_planet_id = !empty($missile_db_row['fleet_start_planet_id']) ? $missile_db_row['fleet_start_planet_id'] : null;
720
    $this->_fleet_start_galaxy = $missile_db_row['fleet_start_galaxy'];
721
    $this->_fleet_start_system = $missile_db_row['fleet_start_system'];
722
    $this->_fleet_start_planet = $missile_db_row['fleet_start_planet'];
723
    $this->_fleet_start_type = $missile_db_row['fleet_start_type'];
724
725
    $this->_fleet_end_planet_id = !empty($missile_db_row['fleet_end_planet_id']) ? $missile_db_row['fleet_end_planet_id'] : null;
726
    $this->_fleet_end_galaxy = $missile_db_row['fleet_end_galaxy'];
727
    $this->_fleet_end_system = $missile_db_row['fleet_end_system'];
728
    $this->_fleet_end_planet = $missile_db_row['fleet_end_planet'];
729
    $this->_fleet_end_type = $missile_db_row['fleet_end_type'];
730
731
    $this->unitList->unitSetCount(UNIT_DEF_MISSILE_INTERPLANET, $missile_db_row['fleet_amount']);
732
  }
733
734
735
  /**
736
   * @param $from
737
   */
738
  public function set_start_planet($from) {
739
    $this->fleet_start_planet_id = intval($from['id']) ? $from['id'] : null;
740
    $this->fleet_start_galaxy = $from['galaxy'];
741
    $this->fleet_start_system = $from['system'];
742
    $this->fleet_start_planet = $from['planet'];
743
    $this->fleet_start_type = $from['planet_type'];
744
  }
745
746
  /**
747
   * @param $to
748
   */
749
  public function set_end_planet($to) {
750
    $this->target_owner_id = intval($to['id_owner']) ? $to['id_owner'] : 0;
751
    $this->fleet_end_planet_id = intval($to['id']) ? $to['id'] : null;
752
    $this->fleet_end_galaxy = $to['galaxy'];
753
    $this->fleet_end_system = $to['system'];
754
    $this->fleet_end_planet = $to['planet'];
755
    $this->fleet_end_type = $to['planet_type'];
756
  }
757
758
  /**
759
   * @param Vector $to
760
   */
761
  public function setTargetFromVectorObject($to) {
762
    $this->_fleet_end_galaxy = $to->galaxy;
763
    $this->_fleet_end_system = $to->system;
764
    $this->_fleet_end_planet = $to->planet;
765
    $this->_fleet_end_type = $to->type;
766
  }
767
768
  /**
769
   * @param array $db_row
770
   */
771
  protected function ownerExtract(array &$db_row) {
772
    $player = new Player();
773
    $player->dbLoad($db_row['fleet_owner']);
774
    $this->setLocatedAt($player);
775
  }
776
777
  /**
778
   * @param array $db_row
779
   */
780
  protected function ownerInject(array &$db_row) {
781
    $db_row['fleet_owner'] = $this->getPlayerOwnerId();
782
  }
783
784
785
786
787
  // UnitList/Ships access ***************************************************************************************************
788
789
  // TODO - перекрывать пожже - для миссайл-флотов и дефенс-флотов
790
  protected function isShip($unit_id) {
791
    return UnitShip::is_in_group($unit_id);
792
  }
793
794
  /**
795
   * Set unit count of $unit_id to $unit_count
796
   * If there is no $unit_id - it will be created and saved to DB on dbSave
797
   *
798
   * @param int $unit_id
799
   * @param int $unit_count
800
   */
801
  public function shipSetCount($unit_id, $unit_count = 0) {
802
    $this->shipAdjustCount($unit_id, $unit_count, true);
803
  }
804
805
  /**
806
   * Adjust unit count of $unit_id by $unit_count - or just replace value
807
   * If there is no $unit_id - it will be created and saved to DB on dbSave
808
   *
809
   * @param int  $unit_id
810
   * @param int  $unit_count
811
   * @param bool $replace_value
812
   */
813
  public function shipAdjustCount($unit_id, $unit_count = 0, $replace_value = false) {
814
    $this->unitList->unitAdjustCount($unit_id, $unit_count, $replace_value);
815
  }
816
817
  public function shipGetCount($unit_id) {
818
    return $this->unitList->unitGetCount($unit_id);
819
  }
820
821
  public function shipsCountApplyLossMultiplier($ships_lost_multiplier) {
822
    $this->unitList->unitsCountApplyLossMultiplier($ships_lost_multiplier);
823
  }
824
825
  /**
826
   * Returns ship list in fleet
827
   */
828
  public function shipsGetArray() {
829
    return $this->unitList->unitsGetArray();
830
  }
831
832
  public function shipsGetTotal() {
833
    return $this->unitList->unitsCount();
834
  }
835
836
  public function shipsGetCapacity() {
837
    return $this->unitList->unitsCapacity();
838
  }
839
840
  public function shipsGetHoldFree() {
841
    return max(0, $this->shipsGetCapacity() - $this->resourcesGetTotal());
842
  }
843
844
  public function shipsGetTotalById($ship_id) {
845
    return $this->unitList->unitsCountById($ship_id);
846
  }
847
848
  /**
849
   * Возвращает ёмкость переработчиков во флоте
850
   *
851
   * @param array $recycler_info
852
   *
853
   * @return int
854
   *
855
   * @version 41a6.76
856
   */
857
  public function shipsGetCapacityRecyclers(array $recycler_info) {
858
    $recyclers_incoming_capacity = 0;
859
    $fleet_data = $this->shipsGetArray();
860
    foreach($recycler_info as $recycler_id => $recycler_data) {
861
      $recyclers_incoming_capacity += $fleet_data[$recycler_id] * $recycler_data['capacity'];
862
    }
863
864
    return $recyclers_incoming_capacity;
865
  }
866
867
  /**
868
   * Restores fleet or resources to planet
869
   *
870
   * @param bool $start
871
   * @param int  $result
872
   *
873
   * @return int
874
   */
875
  // TODO - split to functions
876
  public function shipsLand($start = true, &$result = CACHE_NOTHING) {
877
    sn_db_transaction_check(true);
878
879
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
880
    if($this->isEmpty()) {
881
      return $result;
882
    }
883
884
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
885
886
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
887
    // TODO Проверить от многократного срабатывания !!!
888
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
889
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
890
891
    // Узнаем ИД владельца планеты.
892
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
893
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
894
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
895
    // Блокируем пользователя
896
    // TODO - вообще-то нам уже известен пользователь в МЛФ - так что можно просто передать его сюда
897
    $user = db_user_by_id($planet_arrival['id_owner'], true);
898
899
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
900
    // Флот, который возвращается на захваченную планету, пропадает
901
    // Ship landing is possible only to fleet owner's planet
902
    if($this->getPlayerOwnerId() == $planet_arrival['id_owner']) {
903
      $db_changeset = array();
904
905
      $fleet_array = $this->shipsGetArray();
906
      foreach($fleet_array as $ship_id => $ship_count) {
907
        if($ship_count) {
908
          $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
909
        }
910
      }
911
912
      // Adjusting ship amount on planet
913
      if(!empty($db_changeset)) {
914
        db_changeset_apply($db_changeset);
915
      }
916
917
      // Restoring resources to planet
918
      $this->resourcesUnload($start, $result);
919
    }
920
921
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
922
923
    $result = RestoreFleetToPlanet($this, $start, $result);
924
925
    $this->dbDelete();
926
927
    return $result;
928
  }
929
930
931
  // Resources access ***************************************************************************************************
932
933
  /**
934
   * Extracts resources value from db_row
935
   *
936
   * @param array $db_row
937
   *
938
   * @internal param Fleet $that
939
   * @version 41a6.76
940
   */
941
  protected function resourcesExtract(array &$db_row) {
942
    $this->resource_list = array(
943
      RES_METAL     => !empty($db_row['fleet_resource_metal']) ? floor($db_row['fleet_resource_metal']) : 0,
944
      RES_CRYSTAL   => !empty($db_row['fleet_resource_crystal']) ? floor($db_row['fleet_resource_crystal']) : 0,
945
      RES_DEUTERIUM => !empty($db_row['fleet_resource_deuterium']) ? floor($db_row['fleet_resource_deuterium']) : 0,
946
    );
947
  }
948
949
  protected function resourcesInject(array &$db_row) {
950
    $db_row['fleet_resource_metal'] = $this->resource_list[RES_METAL];
951
    $db_row['fleet_resource_crystal'] = $this->resource_list[RES_CRYSTAL];
952
    $db_row['fleet_resource_deuterium'] = $this->resource_list[RES_DEUTERIUM];
953
  }
954
955
  /**
956
   * Set current resource list from array of units
957
   *
958
   * @param array $resource_list
959
   */
960
  public function resourcesSet($resource_list) {
961
    if(!empty($this->propertiesAdjusted['resource_list'])) {
962
      throw new PropertyAccessException('Property "resource_list" already was adjusted so no SET is possible until dbSave in ' . get_called_class() . '::unitSetResourceList', ERR_ERROR);
963
    }
964
    $this->resourcesAdjust($resource_list, true);
965
  }
966
967
  /**
968
   * Updates fleet resource list with deltas
969
   *
970
   * @param $resource_delta_list
971
   */
972
  public function resourcesAdjust($resource_delta_list, $replace_value = false) {
973
    !is_array($resource_delta_list) ? $resource_delta_list = array() : false;
974
975
    foreach($resource_delta_list as $resource_id => $unit_delta) {
976
      if(!UnitResourceLoot::is_in_group($resource_id) || !($unit_delta = floor($unit_delta))) {
977
        // Not a resource or no resources - continuing
978
        continue;
979
      }
980
981
      if($replace_value) {
982
        $this->resource_list[$resource_id] = $unit_delta;
983
      } else {
984
        $this->resource_list[$resource_id] += $unit_delta;
985
        // Preparing changes
986
        $this->resource_delta[$resource_id] += $unit_delta;
987
        $this->propertiesAdjusted['resource_list'] = 1;
988
      }
989
990
      // Check for negative unit value
991
      if($this->resource_list[$resource_id] < 0) {
992
        // TODO
993
        throw new Exception('Resource ' . $resource_id . ' will become negative in ' . get_called_class() . '::unitAdjustResourceList', ERR_ERROR);
994
      }
995
    }
996
  }
997
998
  public function resourcesGetTotal() {
999
    return empty($this->resource_list) || !is_array($this->resource_list) ? 0 : array_sum($this->resource_list);
1000
  }
1001
1002
  /**
1003
   * @param array $rate
1004
   *
1005
   * @return float
1006
   */
1007
  public function resourcesGetTotalInMetal(array $rate) {
1008
    return
1009
      $this->resource_list[RES_METAL] * $rate[RES_METAL]
1010
      + $this->resource_list[RES_CRYSTAL] * $rate[RES_CRYSTAL] / $rate[RES_METAL]
1011
      + $this->resource_list[RES_DEUTERIUM] * $rate[RES_DEUTERIUM] / $rate[RES_METAL];
1012
  }
1013
1014
  /**
1015
   * Returns resource list in fleet
1016
   */
1017
  // TODO
1018
  public function resourcesGetList() {
1019
    return $this->resource_list;
1020
  }
1021
1022
  public function resourcesReset() {
1023
    $this->resourcesSet(array(
1024
      RES_METAL     => 0,
1025
      RES_CRYSTAL   => 0,
1026
      RES_DEUTERIUM => 0,
1027
    ));
1028
  }
1029
1030
  /**
1031
   * Restores fleet or resources to planet
1032
   *
1033
   * @param bool $start
1034
   * @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...
1035
   * @param int  $result
1036
   *
1037
   * @return int
1038
   */
1039
  public function resourcesUnload($start = true, &$result = CACHE_NOTHING) {
1040
    sn_db_transaction_check(true);
1041
1042
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
1043
    if(!$this->resourcesGetTotal()) {
1044
      return $result;
1045
    }
1046
1047
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
1048
1049
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
1050
    // TODO Проверить от многократного срабатывания !!!
1051
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
1052
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
1053
1054
1055
    // Узнаем ИД владельца планеты.
1056
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
1057
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
1058
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
1059
1060
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
1061
1062
    // Restoring resources to planet
1063
    if($this->resourcesGetTotal()) {
1064
      $fleet_resources = $this->resourcesGetList();
1065
      db_planet_set_by_id($planet_arrival['id'],
1066
        "`metal` = `metal` + '{$fleet_resources[RES_METAL]}', `crystal` = `crystal` + '{$fleet_resources[RES_CRYSTAL]}', `deuterium` = `deuterium` + '{$fleet_resources[RES_DEUTERIUM]}'");
1067
    }
1068
1069
    $this->resourcesReset();
1070
    $this->markReturned();
1071
1072
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
1073
1074
    return $result;
1075
  }
1076
1077
1078
  protected function isResource($unit_id) {
1079
    return UnitResourceLoot::is_in_group($unit_id);
1080
  }
1081
1082
1083
  /**
1084
   * @param array  $dbPlayerRow
1085
   * @param array  $dbPlanetRow
1086
   * @param Vector $targetVector
1087
   *
1088
   */
1089
  public function initDefaults($dbPlayerRow, $dbPlanetRow, $targetVector, $mission, $ships, $fleet_group_mr) {
1090
    $objFleet5Player = new Player();
1091
    $objFleet5Player->dbRowParse($dbPlayerRow);
1092
    $this->setLocatedAt($objFleet5Player);
1093
1094
    $this->mission_type = $mission;
1095
1096
    $this->dbOwnerRow = $dbPlayerRow;
1097
1098
    $this->set_start_planet($dbPlanetRow);
1099
    $this->dbSourcePlanetRow = $dbPlanetRow;
1100
1101
    $this->setTargetFromVectorObject($targetVector);
1102
    $this->targetVector = $targetVector;
1103
//pdump($targetVector);pdie();
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...
1104
    $this->populateTargetPlanet();
1105
1106
    $this->unitsSetFromArray($ships);
1107
1108
    $this->_group_id = $fleet_group_mr;
1109
1110
//    $this->restrictTargetTypeByMission();
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...
1111
  }
1112
1113
  protected function populateTargetPlanet() {
1114
    $targetPlanetCoords = $this->targetVector;
1115
    if($this->mission_type != MT_NONE) {
1116
      $this->restrictTargetTypeByMission();
1117
1118
      // TODO - Нельзя тут просто менять тип планеты или координат!
1119
      // If current planet type is not allowed on mission - switch planet type
1120
      if(empty($this->allowed_planet_types[$this->targetVector->type])) {
1121
        $targetPlanetCoords->type = reset($this->allowed_planet_types);
1122
      }
1123
    }
1124
1125
    $this->dbTargetRow = db_planet_by_vector_object($targetPlanetCoords);
1126
  }
1127
1128
  protected function restrictTargetTypeByMission() {
1129
    if($this->_mission_type == MT_MISSILE) {
1130
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1131
    } elseif($this->_mission_type == MT_COLONIZE || $this->_mission_type == MT_EXPLORE) {
1132
      // TODO - PT_NONE
1133
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1134
    } elseif($this->_mission_type == MT_RECYCLE) {
1135
      $this->allowed_planet_types = array(PT_DEBRIS => PT_DEBRIS);
1136
    } elseif($this->_mission_type == MT_DESTROY) {
1137
      $this->allowed_planet_types = array(PT_MOON => PT_MOON);
1138
    } else {
1139
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET, PT_MOON => PT_MOON);
1140
    }
1141
  }
1142
1143
  /**
1144
   */
1145
  public function fleetPage0Prepare() {
1146
    global $template_result;
1147
    $template_result += array(
1148
      'thisgalaxy'      => $this->dbSourcePlanetRow['galaxy'],
1149
      'thissystem'      => $this->dbSourcePlanetRow['system'],
1150
      'thisplanet'      => $this->dbSourcePlanetRow['planet'],
1151
      'thisplanet_type' => $this->dbSourcePlanetRow['planet_type'],
1152
1153
      'galaxy'         => $this->targetVector->galaxy,
1154
      'system'         => $this->targetVector->system,
1155
      'planet'         => $this->targetVector->planet,
1156
      'planet_type'    => $this->targetVector->type,
1157
      'target_mission' => $this->_mission_type,
1158
      'MISSION_NAME'   => $this->_mission_type ? classLocale::$lang['type_mission'][$this->_mission_type] : '',
1159
1160
      'MT_COLONIZE' => MT_COLONIZE,
1161
    );
1162
1163
//    pdump($this->targetVector->type);pdie();
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
1164
  }
1165
1166
  /**
1167
   */
1168
  public function fleetPage0() {
1169
    global $template_result;
1170
1171
    lng_include('overview');
1172
1173
    if(empty($this->dbSourcePlanetRow)) {
1174
      message(classLocale::$lang['fl_noplanetrow'], classLocale::$lang['fl_error']);
1175
    }
1176
1177
    $template = gettemplate('fleet0', true);
1178
1179
    $ship_list = $this->tplRenderAvailableShips($this->dbOwnerRow, $this->dbSourcePlanetRow);
1180
    $this->tplSortShipList($ship_list);
1181
1182
    foreach($ship_list as $ship_data) {
1183
      $template->assign_block_vars('ships', $ship_data);
1184
    }
1185
1186
    foreach(classLocale::$lang['player_option_fleet_ship_sort'] as $sort_id => $sort_text) {
1187
      $template->assign_block_vars('ship_sort_list', array(
1188
        'VALUE' => $sort_id,
1189
        'TEXT'  => $sort_text,
1190
      ));
1191
    }
1192
1193
    /**
1194
     * @var Player $playerOwner
1195
     */
1196
    $playerOwner = $this->getLocatedAt();
1197
1198
    $template->assign_vars(array(
1199
      'FLEET_SHIP_SORT'         => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT],
1200
      'FLEET_SHIP_SORT_INVERSE' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE],
1201
1202
      'FLYING_FLEETS' => $playerOwner->fleetsFlying(),
1203
      'MAX_FLEETS'    => $playerOwner->fleetsMax(),
1204
      'FREE_FLEETS'   => $playerOwner->fleetsMax() - $playerOwner->fleetsFlying(),
1205
1206
      'FLYING_EXPEDITIONS' => $playerOwner->expeditionsFlying(),
1207
      'MAX_EXPEDITIONS'    => $playerOwner->expeditionsMax(),
1208
      'FREE_EXPEDITIONS'   => $playerOwner->expeditionsMax() - $playerOwner->expeditionsFlying(),
1209
1210
      'COLONIES_CURRENT' => $playerOwner->coloniesCurrent(),
1211
      'COLONIES_MAX'     => $playerOwner->coloniesMax(),
1212
1213
      'TYPE_NAME' => classLocale::$lang['fl_planettype'][$this->targetVector->type],
1214
1215
//      'ShipList' => $ShipList,
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...
1216
1217
      'speed_factor' => flt_server_flight_speed_multiplier(),
1218
1219
      'PLANET_RESOURCES' => pretty_number($this->dbSourcePlanetRow['metal'] + $this->dbSourcePlanetRow['crystal'] + $this->dbSourcePlanetRow['deuterium']),
1220
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1221
1222
      'PLAYER_OPTION_FLEET_SHIP_SELECT_OLD'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SELECT_OLD],
1223
      'PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED],
1224
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY'    => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY],
1225
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION],
1226
    ));
1227
1228
    $template->assign_recursive($template_result);
1229
    display($template, classLocale::$lang['fl_title']);
1230
  }
1231
1232
  /**
1233
   * @param $planet_type
1234
   *
1235
   */
1236
  public function fleetPage1($planet_type) {
1237
    global $note_priority_classes, $template_result;
1238
1239
    $template = gettemplate('fleet1', true);
1240
1241
1242
    foreach($this->allowed_planet_types as $possible_planet_type_id) {
1243
      $template->assign_block_vars('possible_planet_type_id', array(
1244
        'ID'         => $possible_planet_type_id,
1245
        'NAME'       => classLocale::$lang['sys_planet_type'][$possible_planet_type_id],
1246
        'NAME_SHORT' => classLocale::$lang['sys_planet_type_sh'][$possible_planet_type_id],
1247
      ));
1248
    }
1249
1250
    $template_route = array(
1251
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$this->dbSourcePlanetRow['planet_type']],
1252
      'START_COORDS'       => uni_render_coordinates($this->dbSourcePlanetRow),
1253
      'START_NAME'         => $this->dbSourcePlanetRow['name'],
1254
    );
1255
    if(!empty($this->dbTargetRow)) {
1256
      $template_route += array(
1257
        'END_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$this->dbTargetRow['planet_type']],
1258
        'END_COORDS'       => uni_render_coordinates($this->dbTargetRow),
1259
        'END_NAME'         => $this->dbTargetRow['name'],
1260
      );
1261
    }
1262
    $template->assign_block_vars('fleets', $template_route);
1263
1264
    $page = '';
1265
    $fleet = array();
1266
    $this->unitList->unitsRender($page, $fleet, $template);
1267
1268
    if(empty($fleet['fleetarray'])) {
1269
      message(classLocale::$lang['fl_err_no_ships'], classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 5);
1270
    }
1271
1272
    // Building list of shortcuts
1273
    $query = db_note_list_select_by_owner_and_planet($this->dbOwnerRow);
1274
    while($shortcut = db_fetch($query)) {
1275
      $template->assign_block_vars('shortcut', array(
1276
        'NAME'           => $shortcut['title'],
1277
        'GALAXY'         => $shortcut['galaxy'],
1278
        'SYSTEM'         => $shortcut['system'],
1279
        'PLANET'         => $shortcut['planet'],
1280
        'PRIORITY'       => $shortcut['priority'],
1281
        'PRIORITY_CLASS' => $note_priority_classes[$shortcut['priority']],
1282
        'TYPE'           => $shortcut['planet_type'],
1283
        'TYPE_PRINT'     => classLocale::$lang['fl_shrtcup'][$shortcut['planet_type']],
1284
      ));
1285
    }
1286
1287
    // Building list of own planets & moons
1288
    $colonies = db_planet_list_sorted($this->dbOwnerRow);
1289
    if(count($colonies) > 1) {
1290 View Code Duplication
      foreach($colonies as $row) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1291
        if($row['id'] == $this->dbSourcePlanetRow['id']) {
1292
          continue;
1293
        }
1294
1295
        $template->assign_block_vars('colonies', array(
1296
          'NAME'       => $row['name'],
1297
          'GALAXY'     => $row['galaxy'],
1298
          'SYSTEM'     => $row['system'],
1299
          'PLANET'     => $row['planet'],
1300
          'TYPE'       => $row['planet_type'],
1301
          'TYPE_PRINT' => classLocale::$lang['fl_shrtcup'][$row['planet_type']],
1302
        ));
1303
      }
1304
    }
1305
1306
    $aks_madnessred = db_acs_get_list();
1307
    while($row = db_fetch($aks_madnessred)) {
1308
      $members = explode(',', $row['eingeladen']);
1309 View Code Duplication
      foreach($members as $a => $b) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1310
        if($b == $this->dbOwnerRow['id']) {
1311
          $template->assign_block_vars('acss', array(
1312
            'ID'         => $row['id'],
1313
            'NAME'       => $row['name'],
1314
            'GALAXY'     => $row['galaxy'],
1315
            'SYSTEM'     => $row['system'],
1316
            'PLANET'     => $row['planet'],
1317
            'TYPE'       => $row['planet_type'],
1318
            'TYPE_PRINT' => classLocale::$lang['fl_shrtcup'][$row['planet_type']],
1319
          ));
1320
        }
1321
      }
1322
    }
1323
1324
    $template->assign_vars(array(
1325
      'usedfleet' => str_rot13(base64_encode(serialize($fleet['fleetarray']))),
1326
1327
      'speed_factor'    => flt_server_flight_speed_multiplier(),
1328
      "t{$planet_type}" => 'SELECTED',
1329
1330
      'ships' => str_rot13(base64_encode(serialize($ships))),
0 ignored issues
show
Bug introduced by
The variable $ships does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1331
1332
      'fleet_speed'    => flt_fleet_speed($this->dbOwnerRow, $fleet['fleetarray']),
1333
      'fleet_capacity' => $fleet['capacity'],
1334
1335
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1336
1337
      'PAGE_HINT' => classLocale::$lang['fl_page1_hint'],
1338
    ));
1339
1340
    $template->assign_recursive($template_result);
1341
    display($template, classLocale::$lang['fl_title']);
1342
  }
1343
1344
  public function restrictToKnownSpace() {
1345
    if(!$this->targetVector->isInKnownSpace()) {
1346
      throw new Exception('FLIGHT_VECTOR_BEYOND_SYSTEM', FLIGHT_VECTOR_BEYOND_SYSTEM);
1347
    }
1348
  }
1349
1350
  public function restrictToPlanet($errorCode) {
1351
    if($this->targetVector->type != PT_PLANET) {
1352
      throw new Exception($errorCode, $errorCode);
1353
    }
1354
  }
1355
1356
  public function restrictToNoMissiles() {
1357
    $missilesAttack = $this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERPLANET);
1358
    $missilesDefense = $this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERCEPTOR);
1359
    if($missilesAttack + $missilesDefense == $this->shipsGetTotal()) {
1360
      throw new Exception('FLIGHT_SHIPS_NO_MISSILES', FLIGHT_SHIPS_NO_MISSILES);
1361
    }
1362
  }
1363
1364
  public function restrictToAttackMissiles($missilesAttack) {
1365
    if($missilesAttack != $this->shipsGetTotal()) {
1366
      throw new Exception('FLIGHT_SHIPS_ONLY_MISSILES', FLIGHT_SHIPS_ONLY_MISSILES);
1367
    }
1368
  }
1369
1370
  public function restrictToSelf() {
1371
    if($this->dbTargetRow['id'] != $this->getPlayerOwnerId()) {
1372
      throw new Exception('FLIGHT_VECTOR_ONLY_OWN', FLIGHT_VECTOR_ONLY_OWN);
1373
    }
1374
  }
1375
1376
  public function restrictToOther() {
1377
    if($this->dbTargetRow['id'] == $this->getPlayerOwnerId()) {
1378
      throw new Exception('FLIGHT_VECTOR_ONLY_OTHER', FLIGHT_VECTOR_ONLY_OTHER);
1379
    }
1380
  }
1381
1382
  public function restrictToNotOnlySpies() {
1383
    if($this->unitList->unitsCountById(SHIP_SPY) == $this->shipsGetTotal()) {
1384
      throw new Exception('FLIGHT_SHIPS_NOT_ONLY_SPIES', FLIGHT_SHIPS_NOT_ONLY_SPIES);
1385
    }
1386
  }
1387
1388
  public function restrictMissionMissile() {
1389
    $missilesAttack = $this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERPLANET);
1390
    $missilesDefense = $this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERCEPTOR);
1391
    if($this->_mission_type == MT_MISSILE) {
1392
      $this->restrictToAttackMissiles($missilesAttack);
1393
      $this->restrictToKnownSpace();
1394
      $this->restrictToOther();
1395
      $this->restrictToPlanet(FLIGHT_MISSION_MISSILE_ONLY_PLANET);
1396
1397
      $this->allowed_missions = array(MT_MISSILE => MT_MISSILE,);
1398
1399
      throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1400
    }
1401
1402
    if($missilesAttack + $missilesDefense > 0) {
1403
      throw new Exception('FLIGHT_SHIPS_NO_MISSILES', FLIGHT_SHIPS_NO_MISSILES);
1404
    }
1405
1406
    unset($this->allowed_missions[MT_MISSILE]);
1407
    // No missile attack beyond this point
1408
  }
1409
1410
  protected function restrictMissionExplore() {
1411
    // Is it exploration - fleet sent beyond of system?
1412
    if(!$this->targetVector->isInKnownSpace()) {
1413
      $this->restrictToNotOnlySpies();
1414
      $this->restrictToNoMissiles();
1415
1416
      $this->allowed_missions = array(MT_EXPLORE => MT_EXPLORE,);
1417
1418
      throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1419
    }
1420
1421
    unset($this->allowed_missions[MT_EXPLORE]);
1422
    // No exploration beyond this point
1423
  }
1424
1425
  protected function restrictToColonizer() {
1426
    // Colonization fleet should have at least one colonizer
1427
    if(!$this->unitList->unitsCountById(SHIP_COLONIZER) <= 0) {
1428
      throw new Exception('FLIGHT_SHIPS_NO_COLONIZER', FLIGHT_SHIPS_NO_COLONIZER);
1429
    }
1430
  }
1431
1432
  protected function restrictMissionColonize() {
1433
    // Is it colonization - fleet sent to empty place?
1434
    if(empty($this->dbTargetRow)) {
1435
      // Only planet can be destination for colonization
1436
      $this->restrictToPlanet(FLIGHT_MISSION_COLONIZE_NOT_EMPTY);
1437
      $this->restrictToColonizer();
1438
1439
      $this->allowed_missions = array(MT_COLONIZE => MT_COLONIZE,);
1440
1441
      throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1442
    }
1443
    unset($this->allowed_missions[MT_COLONIZE]);
1444
    // No colonization beyond this point
1445
  }
1446
1447
  protected function restrictToUniverse() {
1448
    return $this->targetVector->isInUniverse();
1449
  }
1450
1451
  protected function restrictToMovable() {
1452
    if(!$this->unitList->unitsIsAllMovable($this->dbOwnerRow)) {
1453
      throw new Exception('FLIGHT_SHIPS_UNMOVABLE', FLIGHT_SHIPS_UNMOVABLE);
1454
    }
1455
  }
1456
1457
  protected function restrictToFleetUnits() {
1458
    if(!$this->unitList->unitsInGroup(sn_get_groups(array('fleet', 'missile')))) {
1459
      throw new Exception('FLIGHT_SHIPS_UNIT_WRONG', FLIGHT_SHIPS_UNIT_WRONG);
1460
    }
1461
  }
1462
1463
  public function restrictMissionRecycle(){
1464
    if($this->targetVector->type == PT_DEBRIS) {
1465
      $recyclers = 0;
1466
      foreach(sn_get_groups('flt_recyclers') as $recycler_id) {
1467
        $recyclers += $this->unitList->unitsCountById($recycler_id);
1468
      }
1469
1470
      if($recyclers <= 0) {
1471
        throw new Exception('FLIGHT_SHIPS_NO_RECYCLERS', FLIGHT_SHIPS_NO_RECYCLERS);
1472
      }
1473
1474
      $this->allowed_missions = array(MT_RECYCLE => MT_RECYCLE,);
1475
1476
      throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1477
    }
1478
1479
    unset($this->allowed_missions[MT_RECYCLE]);
1480
    // No recycling beyond this point
1481
  }
1482
1483
  public function restrictMission() {
1484
    if($this->targetVector->isEqualToPlanet($this->dbSourcePlanetRow)) {
1485
      throw new Exception('FLIGHT_VECTOR_SAME_SOURCE', FLIGHT_VECTOR_SAME_SOURCE);
1486
    }
1487
1488
    // Only ships and missiles can be sent to mission
1489
    $this->restrictToFleetUnits();
1490
1491
    // Only units with engines can fly - no other units like satellites
1492
    $this->restrictToMovable();
1493
1494
    // No mission could fly beyond Universe - i.e. with wrong Galaxy and/or System coordinates
1495
    $this->restrictToUniverse();
0 ignored issues
show
Unused Code introduced by
The call to the method Fleet::restrictToUniverse() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
1496
1497
    // No missions except MT_MISSILE should have any missiles in fleet
1498
    $this->restrictMissionMissile();
1499
1500
    // No missions except MT_EXPLORE could target coordinates beyond known system
1501
    $this->restrictMissionExplore();
1502
1503
    // Beyond this point all mission address only known space
1504
    $this->restrictToKnownSpace();
1505
1506
    // No missions except MT_COLONIZE could target empty coordinates
1507
    $this->restrictMissionColonize();
1508
1509
    // No missions except MT_RECYCLE could target debris
1510
    $this->restrictMissionRecycle();
1511
1512
    // TODO - later then
1513
1514
    // If no ACS group is shown - then it can't be an ACS attack
1515
    if(empty($this->_group_id)) {
1516
      unset($this->allowed_missions[MT_ACS]);
1517
    }
1518
1519
    // Checking target owner
1520
    if($this->dbTargetRow['id'] != $this->getPlayerOwnerId()) {
1521
      // Relocate can be done only on owner's planet/moon
1522
      unset($this->allowed_missions[MT_RELOCATE]);
1523
    } else {
1524
      // Spying can't be done on owner's planet/moon
1525
      unset($this->allowed_missions[MT_SPY]);
1526
      // Attack can't be done on owner's planet/moon
1527
      unset($this->allowed_missions[MT_ATTACK]);
1528
      // ACS can't be done on owner's planet/moon
1529
      unset($this->allowed_missions[MT_ACS]);
1530
      // Destroy can't be done on owner's moon
1531
      unset($this->allowed_missions[MT_DESTROY]);
1532
    }
1533
1534
    // If no Reapers (i.e. Death Star) in fleet - then mission Moon Destroy is unaccessible
1535
    if($this->targetVector->type == PT_MOON && $this->unitList->unitsCountById(SHIP_HUGE_DEATH_STAR) <= 0) {
1536
      unset($this->allowed_missions[MT_DESTROY]);
1537
    }
1538
  }
1539
1540
  public function fleetPage2($speed_percent) {
1541
    global $template_result;
1542
1543
    try {
1544
      $this->restrictMission();
1545
    } catch(Exception $e) {
1546
      // TODO - MESSAGE BOX
1547
      pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
1548
    }
1549
1550
    // If mission is not set - setting first mission from allowed
1551
    if(!$this->_mission_type && is_array($this->allowed_missions)) {
1552
      $this->_mission_type = reset($this->allowed_missions);
1553
    }
1554
1555
    ksort($this->allowed_missions);
1556
1557
    $travel_data = $this->flt_travel_data($speed_percent);
1558
1559
    $template = gettemplate('fleet2', true);
1560
1561
    foreach($this->allowed_missions as $key => $value) {
1562
      $template->assign_block_vars('missions', array(
1563
        'ID'   => $key,
1564
        'NAME' => classLocale::$lang['type_mission'][$key],
1565
      ));
1566
    };
1567
1568
    $fleetarray = is_array($fleetarray) ? $fleetarray : array();
0 ignored issues
show
Bug introduced by
The variable $fleetarray seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
1569
1570
    $template_route = array(
1571
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$planetrow['planet_type']],
0 ignored issues
show
Bug introduced by
The variable $planetrow does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1572
      'START_COORDS'       => uni_render_coordinates($planetrow),
1573
      'START_NAME'         => $planetrow['name'],
1574
    );
1575
1576
    if(!empty($TargetPlanet)) {
0 ignored issues
show
Bug introduced by
The variable $TargetPlanet 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...
1577
      $template_route += array(
1578
        'END_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$TargetPlanet['planet_type']],
1579
        'END_COORDS'       => uni_render_coordinates($TargetPlanet),
1580
        'END_NAME'         => $TargetPlanet['name'],
1581
      );
1582
    }
1583
1584
    $template->assign_block_vars('fleets', $template_route);
1585
1586
    $sn_groups_fleet = sn_get_groups('fleet');
1587 View Code Duplication
    foreach($fleetarray as $ship_id => $ship_count) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1588
      if(in_array($ship_id, $sn_groups_fleet) && $ship_count) {
1589
//      $ship_base_data = get_ship_data($ship_id, $user);
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...
1590
        $template->assign_block_vars('fleets.ships', array(
1591
          'ID'          => $ship_id,
1592
          'AMOUNT'      => $ship_count,
1593
          'AMOUNT_TEXT' => pretty_number($ship_count),
1594
//        'CONSUMPTION' => $ship_base_data['consumption'],
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...
1595
//        'SPEED'       => $ship_base_data['speed'],
1596
          'NAME'        => classLocale::$lang['tech'][$ship_id],
1597
        ));
1598
      }
1599
    }
1600
1601
    $fleet_capacity = 0;
1602
    foreach($fleetarray as $Ship => $Count) {
1603
      $fleet_capacity += get_unit_param($Ship, P_CAPACITY) * $Count;
1604
    }
1605
1606
    $max_duration = $this->_mission_type == MT_EXPLORE ? get_player_max_expedition_duration($user) :
1607
      (isset($missiontype[MT_HOLD]) ? 12 : 0);
0 ignored issues
show
Bug introduced by
The variable $missiontype seems to never exist, and therefore isset should always return false. 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...
1608
    if($max_duration) {
1609
      $config_game_speed_expedition = ($this->_mission_type == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1);
1610
      for($i = 1; $i <= $max_duration; $i++) {
1611
        $template->assign_block_vars('duration', array(
1612
          'ID'   => $i,
1613
          'TIME' => pretty_time(ceil($i * 3600 / $config_game_speed_expedition)),
1614
        ));
1615
      }
1616
    }
1617
1618
    $sn_group_resources = sn_get_groups('resources');
1619
    for($i = 0; $i < 3; $i++) {
1620
      $amount = $planetrow[$sn_group_resources[$i]] - ($i == 2 ? $travel_data['consumption'] : 0);
1621
      $template->assign_block_vars('resources', array(
1622
        'ID'        => $i,
1623
        'ON_PLANET' => floor($amount),
1624
        'TEXT'      => pretty_number($amount),
1625
        'NAME'      => classLocale::$lang['sys_' . $sn_group_resources[$i]],
1626
      ));
1627
    }
1628
1629
    if(sn_module::$sn_module['unit_captain']->manifest['active'] && ($captain = sn_module::$sn_module['unit_captain']->unit_captain_get($planetrow['id'])) && $captain['unit_location_type'] == LOC_PLANET) {
1630
      $template->assign_vars(array(
1631
        'CAPTAIN_ID'     => $captain['unit_id'],
1632
        'CAPTAIN_LEVEL'  => $captain['captain_level'],
1633
        'CAPTAIN_SHIELD' => $captain['captain_shield'],
1634
        'CAPTAIN_ARMOR'  => $captain['captain_armor'],
1635
        'CAPTAIN_ATTACK' => $captain['captain_attack'],
1636
      ));
1637
    }
1638
1639
    $template->assign_vars(array(
1640
      'planet_metal'     => floor($this->dbTargetRow['metal']),
1641
      'planet_crystal'   => floor($this->dbTargetRow['crystal']),
1642
      'planet_deuterium' => floor($this->dbTargetRow['deuterium'] - $travel_data['consumption']),
1643
1644
      'fleet_capacity' => $fleet_capacity - $travel_data['consumption'],
1645
      'usedfleet'      => $_POST['usedfleet'],
1646
1647
      'speedallsmin' => sys_get_param_float('speedallsmin'),
1648
      'speed'        => sys_get_param_int('speed'),
1649
1650
      'fleet_group'   => sys_get_param_id('fleet_group'),
1651
      'acs_target_mr' => sys_get_param_str('acs_target_mr'),
1652
1653
      'MAX_DURATION' => $max_duration,
1654
1655
      'IS_TRANSPORT_MISSIONS' => $is_transport_missions,
0 ignored issues
show
Bug introduced by
The variable $is_transport_missions does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1656
1657
      'PLAYER_COLONIES_CURRENT' => get_player_current_colonies($user),
1658
      'PLAYER_COLONIES_MAX'     => get_player_max_colonies($user),
1659
    ));
1660
1661
    $template->assign_recursive($template_result);
1662
    display($template, classLocale::$lang['fl_title']);
1663
  }
1664
1665
1666
  /**
1667
   * @param int $speed_percent
1668
   *
1669
   * @return array
1670
   */
1671
  protected function flt_travel_data($speed_percent = 10) {
1672
    $distance = $this->targetVector->distanceFromCoordinates($this->dbSourcePlanetRow);
1673
1674
    return $this->unitList->travelData($speed_percent, $distance, $this->dbOwnerRow);
1675
  }
1676
1677
}
1678