Completed
Push — work-fleets ( 451000...e7900f )
by SuperNova.WS
06:16
created

Fleet::shipsGetTotalById()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
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.75
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.75
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
      // If current planet type is not allowed on mission - switch planet type
1119
      if(empty($this->allowed_planet_types[$this->targetVector->type])) {
1120
        $targetPlanetCoords->type = reset($this->allowed_planet_types);
1121
      }
1122
    }
1123
1124
    $this->dbTargetRow = db_planet_by_vector_object($targetPlanetCoords);
1125
  }
1126
1127
  protected function restrictTargetTypeByMission() {
1128
    if($this->_mission_type == MT_MISSILE) {
1129
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1130
    } elseif($this->_mission_type == MT_COLONIZE || $this->_mission_type == MT_EXPLORE) {
1131
      // TODO - PT_NONE
1132
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1133
    } elseif($this->_mission_type == MT_RECYCLE) {
1134
      $this->allowed_planet_types = array(PT_DEBRIS => PT_DEBRIS);
1135
    } elseif($this->_mission_type == MT_DESTROY) {
1136
      $this->allowed_planet_types = array(PT_MOON => PT_MOON);
1137
    } else {
1138
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET, PT_MOON => PT_MOON);
1139
    }
1140
  }
1141
1142
  /**
1143
   */
1144
  public function fleetPage0Prepare() {
1145
    global $template_result;
1146
    $template_result += array(
1147
      'thisgalaxy'      => $this->dbSourcePlanetRow['galaxy'],
1148
      'thissystem'      => $this->dbSourcePlanetRow['system'],
1149
      'thisplanet'      => $this->dbSourcePlanetRow['planet'],
1150
      'thisplanet_type' => $this->dbSourcePlanetRow['planet_type'],
1151
1152
      'galaxy'         => $this->targetVector->galaxy,
1153
      'system'         => $this->targetVector->system,
1154
      'planet'         => $this->targetVector->planet,
1155
      'planet_type'    => $this->targetVector->type,
1156
      'target_mission' => $this->_mission_type,
1157
      'MISSION_NAME'   => $this->_mission_type ? classLocale::$lang['type_mission'][$this->_mission_type] : '',
1158
1159
      'MT_COLONIZE' => MT_COLONIZE,
1160
    );
1161
1162
//    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...
1163
  }
1164
1165
  /**
1166
   */
1167
  public function fleetPage0() {
1168
    global $template_result;
1169
1170
    lng_include('overview');
1171
1172
    if(empty($this->dbSourcePlanetRow)) {
1173
      message(classLocale::$lang['fl_noplanetrow'], classLocale::$lang['fl_error']);
1174
    }
1175
1176
    $template = gettemplate('fleet0', true);
1177
1178
    $ship_list = $this->tplRenderAvailableShips($this->dbOwnerRow, $this->dbSourcePlanetRow);
1179
    $this->tplSortShipList($ship_list);
1180
1181
    foreach($ship_list as $ship_data) {
1182
      $template->assign_block_vars('ships', $ship_data);
1183
    }
1184
1185
    foreach(classLocale::$lang['player_option_fleet_ship_sort'] as $sort_id => $sort_text) {
1186
      $template->assign_block_vars('ship_sort_list', array(
1187
        'VALUE' => $sort_id,
1188
        'TEXT'  => $sort_text,
1189
      ));
1190
    }
1191
1192
    /**
1193
     * @var Player $playerOwner
1194
     */
1195
    $playerOwner = $this->getLocatedAt();
1196
1197
    $template->assign_vars(array(
1198
      'FLEET_SHIP_SORT'         => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT],
1199
      'FLEET_SHIP_SORT_INVERSE' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE],
1200
1201
      'FLYING_FLEETS' => $playerOwner->fleetsFlying(),
1202
      'MAX_FLEETS'    => $playerOwner->fleetsMax(),
1203
      'FREE_FLEETS'   => $playerOwner->fleetsMax() - $playerOwner->fleetsFlying(),
1204
1205
      'FLYING_EXPEDITIONS' => $playerOwner->expeditionsFlying(),
1206
      'MAX_EXPEDITIONS'    => $playerOwner->expeditionsMax(),
1207
      'FREE_EXPEDITIONS'   => $playerOwner->expeditionsMax() - $playerOwner->expeditionsFlying(),
1208
1209
      'COLONIES_CURRENT' => $playerOwner->coloniesCurrent(),
1210
      'COLONIES_MAX'     => $playerOwner->coloniesMax(),
1211
1212
      'TYPE_NAME' => classLocale::$lang['fl_planettype'][$this->targetVector->type],
1213
1214
//      '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...
1215
1216
      'speed_factor' => flt_server_flight_speed_multiplier(),
1217
1218
      'PLANET_RESOURCES' => pretty_number($this->dbSourcePlanetRow['metal'] + $this->dbSourcePlanetRow['crystal'] + $this->dbSourcePlanetRow['deuterium']),
1219
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1220
1221
      'PLAYER_OPTION_FLEET_SHIP_SELECT_OLD'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SELECT_OLD],
1222
      'PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED],
1223
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY'    => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY],
1224
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION],
1225
    ));
1226
1227
    $template->assign_recursive($template_result);
1228
    display($template, classLocale::$lang['fl_title']);
1229
  }
1230
1231
  /**
1232
   * @param $planet_type
1233
   *
1234
   */
1235
  public function fleetPage1($planet_type) {
1236
    global $note_priority_classes, $template_result;
1237
1238
    $template = gettemplate('fleet1', true);
1239
1240
1241
    foreach($this->allowed_planet_types as $possible_planet_type_id) {
1242
      $template->assign_block_vars('possible_planet_type_id', array(
1243
        'ID'         => $possible_planet_type_id,
1244
        'NAME'       => classLocale::$lang['sys_planet_type'][$possible_planet_type_id],
1245
        'NAME_SHORT' => classLocale::$lang['sys_planet_type_sh'][$possible_planet_type_id],
1246
      ));
1247
    }
1248
1249
    $template_route = array(
1250
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$this->dbSourcePlanetRow['planet_type']],
1251
      'START_COORDS'       => uni_render_coordinates($this->dbSourcePlanetRow),
1252
      'START_NAME'         => $this->dbSourcePlanetRow['name'],
1253
    );
1254
    if(!empty($this->dbTargetRow)) {
1255
      $template_route += array(
1256
        'END_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$this->dbTargetRow['planet_type']],
1257
        'END_COORDS'       => uni_render_coordinates($this->dbTargetRow),
1258
        'END_NAME'         => $this->dbTargetRow['name'],
1259
      );
1260
    }
1261
    $template->assign_block_vars('fleets', $template_route);
1262
1263
    $page = '';
1264
    $fleet = array();
1265
    $this->unitList->unitsRender($page, $fleet, $template);
1266
1267
    if(empty($fleet['fleetarray'])) {
1268
      message(classLocale::$lang['fl_err_no_ships'], classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 5);
1269
    }
1270
1271
    // Building list of shortcuts
1272
    $query = db_note_list_select_by_owner_and_planet($this->dbOwnerRow);
1273
    while($shortcut = db_fetch($query)) {
1274
      $template->assign_block_vars('shortcut', array(
1275
        'NAME'           => $shortcut['title'],
1276
        'GALAXY'         => $shortcut['galaxy'],
1277
        'SYSTEM'         => $shortcut['system'],
1278
        'PLANET'         => $shortcut['planet'],
1279
        'PRIORITY'       => $shortcut['priority'],
1280
        'PRIORITY_CLASS' => $note_priority_classes[$shortcut['priority']],
1281
        'TYPE'           => $shortcut['planet_type'],
1282
        'TYPE_PRINT'     => classLocale::$lang['fl_shrtcup'][$shortcut['planet_type']],
1283
      ));
1284
    }
1285
1286
    // Building list of own planets & moons
1287
    $colonies = db_planet_list_sorted($this->dbOwnerRow);
1288
    if(count($colonies) > 1) {
1289 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...
1290
        if($row['id'] == $this->dbSourcePlanetRow['id']) {
1291
          continue;
1292
        }
1293
1294
        $template->assign_block_vars('colonies', array(
1295
          'NAME'       => $row['name'],
1296
          'GALAXY'     => $row['galaxy'],
1297
          'SYSTEM'     => $row['system'],
1298
          'PLANET'     => $row['planet'],
1299
          'TYPE'       => $row['planet_type'],
1300
          'TYPE_PRINT' => classLocale::$lang['fl_shrtcup'][$row['planet_type']],
1301
        ));
1302
      }
1303
    }
1304
1305
    $aks_madnessred = db_acs_get_list();
1306
    while($row = db_fetch($aks_madnessred)) {
1307
      $members = explode(',', $row['eingeladen']);
1308 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...
1309
        if($b == $this->dbOwnerRow['id']) {
1310
          $template->assign_block_vars('acss', array(
1311
            'ID'         => $row['id'],
1312
            'NAME'       => $row['name'],
1313
            'GALAXY'     => $row['galaxy'],
1314
            'SYSTEM'     => $row['system'],
1315
            'PLANET'     => $row['planet'],
1316
            'TYPE'       => $row['planet_type'],
1317
            'TYPE_PRINT' => classLocale::$lang['fl_shrtcup'][$row['planet_type']],
1318
          ));
1319
        }
1320
      }
1321
    }
1322
1323
    $template->assign_vars(array(
1324
      'usedfleet' => str_rot13(base64_encode(serialize($fleet['fleetarray']))),
1325
1326
      'speed_factor'    => flt_server_flight_speed_multiplier(),
1327
      "t{$planet_type}" => 'SELECTED',
1328
1329
      '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...
1330
1331
      'fleet_speed'    => flt_fleet_speed($this->dbOwnerRow, $fleet['fleetarray']),
1332
      'fleet_capacity' => $fleet['capacity'],
1333
1334
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1335
1336
      'PAGE_HINT' => classLocale::$lang['fl_page1_hint'],
1337
    ));
1338
1339
    $template->assign_recursive($template_result);
1340
    display($template, classLocale::$lang['fl_title']);
1341
  }
1342
1343
  protected function restrictMission() {
1344
1345
1346
    // Is it exploration - fleet sent beyond of system?
1347
    if($this->targetVector->planet > classSupernova::$config->game_maxPlanet) {
1348
      $this->allowed_missions = array(MT_EXPLORE => MT_EXPLORE,);
1349
1350
      // TODO - check for only spies in fleet
1351
1352
      return;
1353
    }
1354
    unset($this->allowed_missions[MT_EXPLORE]);
1355
    // No exploration beyond this point
1356
1357
    if(!uni_vector_valid($this->targetVector)) {
1358
      throw new Exception('LANG_INVALID_COORDINATES');
1359
    }
1360
1361
    // Is it colonization - fleet sent to empty place?
1362
    if(empty($this->dbTargetRow)) {
1363
      // Only planet can be destination for colonization
1364
      if(!$this->targetVector->type == PT_PLANET) {
1365
        throw new Exception('LANG_INVALID_COLONIZATION_TYPE_ONLY_PLANET_CAN_BE_COLONIZED');
1366
      }
1367
      // Colonization fleet should have at least one colonizer
1368
      if(!$this->unitList->unitsCountById(SHIP_COLONIZER) <= 0) {
1369
        throw new Exception('LANG_INVALID_COLONIZATION_TYPE_ONLY_PLANET_CAN_BE_COLONIZED', ATTACK_NO_COLONIZER);
1370
      }
1371
1372
      $this->allowed_missions = array(MT_COLONIZE => MT_COLONIZE,);
1373
1374
      return;
1375
    }
1376
    unset($this->allowed_missions[MT_COLONIZE]);
1377
    // No colonization beyond this point
1378
1379
1380
    $UsedPlanet = false;
1381
    $YourPlanet = false;
1382
    $missiontype = array();
1383
1384
    $check_type = $planet_type == PT_MOON ? PT_MOON : PT_PLANET;
0 ignored issues
show
Bug introduced by
The variable $planet_type 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...
1385
1386
    $TargetPlanet = db_planet_by_gspt($galaxy, $system, $planet, $check_type);
0 ignored issues
show
Bug introduced by
The variable $galaxy 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...
Bug introduced by
The variable $system 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...
Bug introduced by
The variable $planet does not exist. Did you mean $UsedPlanet?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1387
1388 View Code Duplication
    if($TargetPlanet['id_owner']) {
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...
1389
      $UsedPlanet = true;
1390
      if($TargetPlanet['id_owner'] == $user['id']) {
0 ignored issues
show
Bug introduced by
The variable $user 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...
1391
        $YourPlanet = true;
1392
      }
1393
    }
1394
1395 View Code Duplication
    if(!$UsedPlanet) {
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...
1396
      if($fleetarray[SHIP_COLONIZER]) {
0 ignored issues
show
Bug introduced by
The variable $fleetarray 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...
1397
        $missiontype[MT_COLONIZE] = classLocale::$lang['type_mission'][MT_COLONIZE];
1398
        $target_mission = MT_COLONIZE;
0 ignored issues
show
Unused Code introduced by
$target_mission is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1399
        $planet_type = PT_PLANET;
0 ignored issues
show
Unused Code introduced by
$planet_type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1400
      } else {
1401
        message("<font color=\"red\"><b>" . classLocale::$lang['fl_no_planet_type'] . "</b></font>", classLocale::$lang['fl_error']);
1402
      }
1403
    } else {
1404
      $recyclers = 0;
1405
      foreach(sn_get_groups('flt_recyclers') as $recycler_id) {
1406
        $recyclers += $fleetarray[$recycler_id];
1407
      }
1408
      if($recyclers > 0 && $planet_type == PT_DEBRIS) {
0 ignored issues
show
Bug introduced by
The variable $planet_type 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...
1409
        $target_mission = MT_RECYCLE;
0 ignored issues
show
Unused Code introduced by
$target_mission is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1410
        $missiontype[MT_RECYCLE] = classLocale::$lang['type_mission'][MT_RECYCLE];
1411
      } elseif($planet_type == PT_PLANET || $planet_type == PT_MOON) {
0 ignored issues
show
Bug introduced by
The variable $planet_type 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...
1412
        if($YourPlanet) {
1413
          $missiontype[MT_RELOCATE] = classLocale::$lang['type_mission'][MT_RELOCATE];
1414
          $missiontype[MT_TRANSPORT] = classLocale::$lang['type_mission'][MT_TRANSPORT];
1415
        } else {
1416
          // Not Your Planet
1417
          if($fleetarray[SHIP_SPY]) {
1418
            // Only spy missions if any spy
1419
            $missiontype[MT_SPY] = classLocale::$lang['type_mission'][MT_SPY];
1420
          } else {
1421
            // If no spies...
1422
            if($fleet_group_mr) {
0 ignored issues
show
Bug introduced by
The variable $fleet_group_mr 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...
1423
              $missiontype[MT_AKS] = classLocale::$lang['type_mission'][MT_AKS];
1424
            } else {
1425
              $missiontype[MT_ATTACK] = classLocale::$lang['type_mission'][MT_ATTACK];
1426
              $missiontype[MT_TRANSPORT] = classLocale::$lang['type_mission'][MT_TRANSPORT];
1427
1428
              $missiontype[MT_HOLD] = classLocale::$lang['type_mission'][MT_HOLD];
1429
1430
              if($planet_type == PT_MOON && $fleetarray[SHIP_HUGE_DEATH_STAR]) {
0 ignored issues
show
Bug introduced by
The variable $planet_type 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...
1431
                $missiontype[MT_DESTROY] = classLocale::$lang['type_mission'][MT_DESTROY];
1432
              }
1433
            }
1434
          }
1435
        }
1436
      }
1437
    }
1438
1439
  }
1440
1441
  /**
1442
   * @param $ship_amount
1443
   * @param $debug
1444
   * @param $planet
1445
   * @param $galaxy
1446
   * @param $system
1447
   * @param $planet_type
1448
   * @param $user
1449
   * @param $planetrow
1450
   *
1451
   * @return array
1452
   */
1453
  public function fleetPage2Prepare($ship_amount, $planet, $galaxy, $system, $planet_type, $user, $planetrow) {
0 ignored issues
show
Unused Code introduced by
The parameter $ship_amount 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...
Unused Code introduced by
The parameter $planetrow 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...
1454
//    $fleet_group_mr = sys_get_param_id('fleet_group');
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
1455
//    $fleetarray = unserialize(base64_decode(str_rot13(sys_get_param('usedfleet'))));
1456
//    $fleetarray = is_array($fleetarray) ? $fleetarray : array();
1457
//
1458
//    foreach($fleetarray as $ship_id => &$ship_amount) {
1459
//      if(!in_array($ship_id, sn_get_groups('fleet')) || (string)floatval($ship_amount) != $ship_amount || $ship_amount < 1) {
1460
//        $debug->warning('Supplying wrong ship in ship list on fleet page', 'Hack attempt', 302, array('base_dump' => true));
1461
//        die();
1462
//      }
1463
//      $ship_amount = floatval($ship_amount);
1464
//    }
1465
1466
    $UsedPlanet = false;
1467
    $YourPlanet = false;
1468
    $missiontype = array();
1469
    if($planet > classSupernova::$config->game_maxPlanet) {
1470
      $target_mission = MT_EXPLORE;
0 ignored issues
show
Unused Code introduced by
$target_mission is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1471
      $missiontype[MT_EXPLORE] = classLocale::$lang['type_mission'][MT_EXPLORE];
1472
    } elseif($galaxy && $system && $planet) {
1473
      $check_type = $planet_type == PT_MOON ? PT_MOON : PT_PLANET;
1474
1475
      $TargetPlanet = db_planet_by_gspt($galaxy, $system, $planet, $check_type);
1476
1477 View Code Duplication
      if($TargetPlanet['id_owner']) {
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...
1478
        $UsedPlanet = true;
1479
        if($TargetPlanet['id_owner'] == $user['id']) {
1480
          $YourPlanet = true;
1481
        }
1482
      }
1483
1484 View Code Duplication
      if(!$UsedPlanet) {
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...
1485
        if($fleetarray[SHIP_COLONIZER]) {
0 ignored issues
show
Bug introduced by
The variable $fleetarray 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...
1486
          $missiontype[MT_COLONIZE] = classLocale::$lang['type_mission'][MT_COLONIZE];
1487
          $target_mission = MT_COLONIZE;
0 ignored issues
show
Unused Code introduced by
$target_mission is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1488
          $planet_type = PT_PLANET;
0 ignored issues
show
Unused Code introduced by
$planet_type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1489
        } else {
1490
          message("<font color=\"red\"><b>" . classLocale::$lang['fl_no_planet_type'] . "</b></font>", classLocale::$lang['fl_error']);
1491
        }
1492
      } else {
1493
        $recyclers = 0;
1494
        foreach(sn_get_groups('flt_recyclers') as $recycler_id) {
1495
          $recyclers += $fleetarray[$recycler_id];
1496
        }
1497
        if($recyclers > 0 && $planet_type == PT_DEBRIS) {
1498
          $target_mission = MT_RECYCLE;
0 ignored issues
show
Unused Code introduced by
$target_mission is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1499
          $missiontype[MT_RECYCLE] = classLocale::$lang['type_mission'][MT_RECYCLE];
1500
        } elseif($planet_type == PT_PLANET || $planet_type == PT_MOON) {
1501
          if($YourPlanet) {
1502
            $missiontype[MT_RELOCATE] = classLocale::$lang['type_mission'][MT_RELOCATE];
1503
            $missiontype[MT_TRANSPORT] = classLocale::$lang['type_mission'][MT_TRANSPORT];
1504
          } else {
1505
            // Not Your Planet
1506
            if($fleetarray[SHIP_SPY]) {
1507
              // Only spy missions if any spy
1508
              $missiontype[MT_SPY] = classLocale::$lang['type_mission'][MT_SPY];
1509
            } else {
1510
              // If no spies...
1511
              if($fleet_group_mr) {
0 ignored issues
show
Bug introduced by
The variable $fleet_group_mr 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...
1512
                $missiontype[MT_AKS] = classLocale::$lang['type_mission'][MT_AKS];
1513
              } else {
1514
                $missiontype[MT_ATTACK] = classLocale::$lang['type_mission'][MT_ATTACK];
1515
                $missiontype[MT_TRANSPORT] = classLocale::$lang['type_mission'][MT_TRANSPORT];
1516
1517
                $missiontype[MT_HOLD] = classLocale::$lang['type_mission'][MT_HOLD];
1518
1519
                if($planet_type == PT_MOON && $fleetarray[SHIP_HUGE_DEATH_STAR]) {
1520
                  $missiontype[MT_DESTROY] = classLocale::$lang['type_mission'][MT_DESTROY];
1521
                }
1522
              }
1523
            }
1524
          }
1525
        }
1526
      }
1527
    }
1528
  }
1529
1530
  public function fleetPage2() {
1531
    global $missiontype, $target_mission, $fleetarray, $planetrow;
1532
    global $TargetPlanet, $consumption, $template_result;
1533
    global $user, $is_transport_missions;
1534
1535
    try {
1536
      $this->restrictMission();
1537
      if(!$target_mission && is_array($missiontype)) {
1538
        $target_mission = MT_ATTACK;
1539
      }
1540
1541
      ksort($missiontype);
1542
1543
      $speed_percent = sys_get_param_int('speed', 10);
1544
      $travel_data = flt_travel_data($user, $planetrow, array('galaxy' => $galaxy, 'system' => $system, 'planet' => $planet), $fleetarray, $speed_percent);
0 ignored issues
show
Bug introduced by
The variable $galaxy 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...
Bug introduced by
The variable $system 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...
Bug introduced by
The variable $planet does not exist. Did you mean $planetrow?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1545
1546
      $fleet_speed = $travel_data['fleet_speed'];
0 ignored issues
show
Unused Code introduced by
$fleet_speed is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1547
      $distance = $travel_data['distance'];
0 ignored issues
show
Unused Code introduced by
$distance is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1548
      $duration = $travel_data['duration'];
1549
      $consumption = $travel_data['consumption'];
1550
1551
      return array($ship_amount, $planet_type, $duration);
0 ignored issues
show
Bug introduced by
The variable $ship_amount 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...
Bug introduced by
The variable $planet_type 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...
1552
    } catch(Exception $e) {
1553
      die($e->getMessage());
1554
    }
1555
1556
    $template = gettemplate('fleet2', true);
0 ignored issues
show
Unused Code introduced by
$template = gettemplate('fleet2', true); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1557
1558
    foreach($missiontype as $key => $value) {
1559
      $template->assign_block_vars('missions', array(
1560
        'ID'      => $key,
1561
        'NAME'    => $value,
1562
        'CHECKED' => $target_mission == $key,
1563
      ));
1564
    };
1565
1566
    $fleetarray = is_array($fleetarray) ? $fleetarray : array();
1567
1568
    $template_route = array(
1569
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$planetrow['planet_type']],
1570
      'START_COORDS'       => uni_render_coordinates($planetrow),
1571
      'START_NAME'         => $planetrow['name'],
1572
    );
1573
1574
    if(!empty($TargetPlanet)) {
0 ignored issues
show
Bug introduced by
The variable $TargetPlanet seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
1575
      $template_route += array(
1576
        'END_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$TargetPlanet['planet_type']],
1577
        'END_COORDS'       => uni_render_coordinates($TargetPlanet),
1578
        'END_NAME'         => $TargetPlanet['name'],
1579
      );
1580
    }
1581
1582
    $template->assign_block_vars('fleets', $template_route);
1583
1584
    $sn_groups_fleet = sn_get_groups('fleet');
1585 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...
1586
      if(in_array($ship_id, $sn_groups_fleet) && $ship_count) {
0 ignored issues
show
Bug introduced by
The variable $sn_groups_fleet 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...
1587
//      $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...
1588
        $template->assign_block_vars('fleets.ships', array(
1589
          'ID'          => $ship_id,
1590
          'AMOUNT'      => $ship_count,
1591
          'AMOUNT_TEXT' => pretty_number($ship_count),
1592
//        '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...
1593
//        'SPEED'       => $ship_base_data['speed'],
1594
          'NAME'        => classLocale::$lang['tech'][$ship_id],
1595
        ));
1596
      }
1597
    }
1598
1599
    $fleet_capacity = 0;
1600
    foreach($fleetarray as $Ship => $Count) {
1601
      $fleet_capacity += get_unit_param($Ship, P_CAPACITY) * $Count;
1602
    }
1603
1604
    $max_duration = $target_mission == MT_EXPLORE ? get_player_max_expedition_duration($user) :
1605
      (isset($missiontype[MT_HOLD]) ? 12 : 0);
1606
    if($max_duration) {
0 ignored issues
show
Bug introduced by
The variable $max_duration 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...
1607
      $config_game_speed_expedition = ($target_mission == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1);
1608
      for($i = 1; $i <= $max_duration; $i++) {
0 ignored issues
show
Bug introduced by
The variable $i 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...
Bug introduced by
The variable $max_duration 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...
1609
        $template->assign_block_vars('duration', array(
1610
          'ID'   => $i,
1611
          'TIME' => pretty_time(ceil($i * 3600 / $config_game_speed_expedition)),
1612
        ));
1613
      }
1614
    }
1615
1616
    $sn_group_resources = sn_get_groups('resources');
1617
    for($i = 0; $i < 3; $i++) {
0 ignored issues
show
Bug introduced by
The variable $i 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...
1618
      $amount = $planetrow[$sn_group_resources[$i]] - ($i == 2 ? $consumption : 0);
1619
      $template->assign_block_vars('resources', array(
1620
        'ID'        => $i,
1621
        'ON_PLANET' => floor($amount),
1622
        'TEXT'      => pretty_number($amount),
1623
        'NAME'      => classLocale::$lang['sys_' . $sn_group_resources[$i]],
1624
      ));
1625
    }
1626
1627
    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) {
0 ignored issues
show
Bug introduced by
The variable $planetrow 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...
1628
      $template->assign_vars(array(
1629
        'CAPTAIN_ID'     => $captain['unit_id'],
1630
        'CAPTAIN_LEVEL'  => $captain['captain_level'],
1631
        'CAPTAIN_SHIELD' => $captain['captain_shield'],
1632
        'CAPTAIN_ARMOR'  => $captain['captain_armor'],
1633
        'CAPTAIN_ATTACK' => $captain['captain_attack'],
1634
      ));
1635
    }
1636
1637
    $template->assign_vars(array(
1638
      'planet_metal'     => floor($planetrow['metal']),
1639
      'planet_crystal'   => floor($planetrow['crystal']),
1640
      'planet_deuterium' => floor($planetrow['deuterium'] - $consumption),
1641
1642
      'fleet_capacity' => $fleet_capacity - $consumption,
1643
      'usedfleet'      => $_POST['usedfleet'],
1644
1645
      // 'TableTitle' => $TableTitle,
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...
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,
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