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

Fleet::renderFleet1TargetSelect()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

Loading history...
1310
    if($this->unitList->unitsCountById(SHIP_SPY) != $this->shipsGetTotal()) {
1311
//      throw new Exception('FLIGHT_SHIPS_ONLY_SPIES', FLIGHT_SHIPS_ONLY_SPIES);
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...
1312
      unset($this->allowed_missions[MT_SPY]);
1313
1314
      $this->restrictToNotOnlySpies();
1315
1316
      return;
1317
    }
1318
1319
    $this->allowed_missions = array(MT_SPY => MT_SPY,);
1320
    throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1321
  }
1322
1323
  protected function restrictMissionDestroy() {
1324
    // If target vector is not Moon - then it can't be Destroy mission
1325
    // If no Reapers (i.e. Death Star) in fleet - then mission Moon Destroy is unaccessible
1326
    if($this->targetVector->type != PT_MOON || $this->unitList->unitsCountById(SHIP_HUGE_DEATH_STAR) <= 0) {
1327
      unset($this->allowed_missions[MT_DESTROY]);
1328
    }
1329
  }
1330
1331
  protected function restrictMissionACS() {
1332
    // If no ACS group is shown - then it can't be an ACS attack
1333
    if(empty($this->_group_id)) {
1334
      unset($this->allowed_missions[MT_ACS]);
1335
    }
1336
  }
1337
1338
  /** @throws Exception */
1339
  protected function restrictFriendOrFoe() {
1340
    // Checking target owner
1341
    if($this->dbTargetRow['id'] == $this->getPlayerOwnerId()) {
1342
      // Spying can't be done on owner's planet/moon
1343
      unset($this->allowed_missions[MT_SPY]);
1344
      // Attack can't be done on owner's planet/moon
1345
      unset($this->allowed_missions[MT_ATTACK]);
1346
      // ACS can't be done on owner's planet/moon
1347
      unset($this->allowed_missions[MT_ACS]);
1348
      // Destroy can't be done on owner's moon
1349
      unset($this->allowed_missions[MT_DESTROY]);
1350
1351
      $this->restrictToNoMissiles();
1352
1353
      // MT_RELOCATE
1354
      // No checks
1355
      // TODO - check captain
1356
1357
      // MT_HOLD
1358
      // TODO - Check for Allies Deposit for HOLD
1359
1360
      // MT_TRANSPORT
1361
1362
    } else {
1363
      // Relocate can be done only on owner's planet/moon
1364
      unset($this->allowed_missions[MT_RELOCATE]);
1365
1366
      // TODO - check for moratorium
1367
1368
      // MT_HOLD
1369
      // TODO - Check for Allies Deposit for HOLD
1370
      // TODO - Noob protection for HOLD depends on server settings
1371
1372
      // MT_SPY
1373
      $this->restrictToNotOnlySpiesOrMissionSpy();
1374
1375
      // TODO - check noob protection
1376
1377
      // TODO - check bashing
1378
1379
      // No missions except MT_MISSILE should have any missiles in fleet
1380
      $this->restrictMissionMissile();
1381
      $this->restrictToNoMissiles();
1382
      // Beyond this point no mission can have a missile in fleet
1383
1384
      // MT_DESTROY
1385
      $this->restrictMissionDestroy();
1386
1387
      // MT_ACS
1388
      $this->restrictMissionACS();
1389
1390
      // MT_ATTACK - no checks
1391
1392
      // MT_TRANSPORT - no checks
1393
    }
1394
  }
1395
1396
  /**
1397
   * Restricts mission availability internally w/o DB access
1398
   *
1399
   * @throws Exception
1400
   */
1401
  public function restrictMission() {
1402
    if($this->targetVector->isEqualToPlanet($this->dbSourcePlanetRow)) {
1403
      throw new Exception('FLIGHT_VECTOR_SAME_SOURCE', FLIGHT_VECTOR_SAME_SOURCE);
1404
    }
1405
1406
    // Only ships and missiles can be sent to mission
1407
    $this->restrictToFleetUnits();
1408
    // Only units with main engines (speed >=0) can fly - no other units like satellites
1409
    $this->restrictToMovable();
1410
    // No mission could fly beyond Universe - i.e. with wrong Galaxy and/or System coordinates
1411
    $this->restrictToUniverse();
0 ignored issues
show
Unused Code introduced by
The call to the method Fleet::restrictToUniverse() seems un-needed as the method has no side-effects.

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

Let’s take a look at an example:

class User
{
    private $email;

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

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

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

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

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

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
1412
1413
    // TODO - check vacation
1414
1415
    // No missions except MT_EXPLORE could target coordinates beyond known system
1416
    $this->restrictKnownSpaceOrMissionExplore();
1417
    // Beyond this point all mission address only known space
1418
1419
    // No missions except MT_COLONIZE could target empty coordinates
1420
    $this->restrictTargetExistsOrMissionColonize();
1421
    // Beyond this point all mission address only existing planets/moons
1422
1423
    // No missions except MT_RECYCLE could target debris
1424
    $this->restrictNotDebrisOrMissionRecycle();
1425
    // Beyond this point targets can be only PT_PLANET or PT_MOON
1426
1427
    // TODO - later then
1428
    $this->restrictFriendOrFoe();
1429
  }
1430
1431
1432
  protected function printErrorIfNoShips() {
1433
    if($this->unitList->unitsCount() <= 0) {
1434
      message(classLocale::$lang['fl_err_no_ships'], classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 5);
1435
    }
1436
  }
1437
1438
  /**
1439
   * @param array $template_result
1440
   *
1441
   * @throws Exception
1442
   */
1443
  protected function renderFleet(&$template_result) {
1444
    $this->printErrorIfNoShips();
1445
1446
    $tplShips = $this->unitList->unitsRender();
1447
    $template_result['.']['fleets'][] = array(
1448
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$this->dbSourcePlanetRow['planet_type']],
1449
      'START_COORDS'       => uni_render_coordinates($this->dbSourcePlanetRow),
1450
      'START_NAME'         => $this->dbSourcePlanetRow['name'],
1451
      'END_TYPE_TEXT_SH'   =>
1452
        !empty($this->targetVector->type)
1453
          ? classLocale::$lang['sys_planet_type_sh'][$this->targetVector->type]
1454
          : '',
1455
      'END_COORDS'         => uniRenderVector($this->targetVector),
1456
      'END_NAME'           => !empty($this->dbTargetRow['name']) ? $this->dbTargetRow['name'] : '',
1457
      '.'                  => array(
1458
        'ships' => $tplShips,
1459
      ),
1460
    );
1461
  }
1462
1463
  /**
1464
   */
1465
  public function fleetPage0() {
1466
    global $template_result;
1467
1468
    lng_include('overview');
1469
1470
    if(empty($this->dbSourcePlanetRow)) {
1471
      message(classLocale::$lang['fl_noplanetrow'], classLocale::$lang['fl_error']);
1472
    }
1473
1474
    // TODO - redo to unitlist render/unit render
1475
    $this->renderAvailableShips($template_result, $this->dbOwnerRow, $this->dbSourcePlanetRow);
1476
1477
    $this->renderShipSortOptions($template_result);
1478
1479
    /**
1480
     * @var Player $playerOwner
1481
     */
1482
    $playerOwner = $this->getLocatedAt();
1483
1484
    $template_result += array(
1485
      'FLYING_FLEETS'      => $playerOwner->fleetsFlying(),
1486
      'MAX_FLEETS'         => $playerOwner->fleetsMax(),
1487
      'FREE_FLEETS'        => $playerOwner->fleetsMax() - $playerOwner->fleetsFlying(),
1488
      'FLYING_EXPEDITIONS' => $playerOwner->expeditionsFlying(),
1489
      'MAX_EXPEDITIONS'    => $playerOwner->expeditionsMax(),
1490
      'FREE_EXPEDITIONS'   => $playerOwner->expeditionsMax() - $playerOwner->expeditionsFlying(),
1491
      'COLONIES_CURRENT'   => $playerOwner->coloniesCurrent(),
1492
      'COLONIES_MAX'       => $playerOwner->coloniesMax(),
1493
1494
      'TYPE_NAME' => classLocale::$lang['fl_planettype'][$this->targetVector->type],
1495
1496
      'speed_factor' => flt_server_flight_speed_multiplier(),
1497
1498
      'PLANET_RESOURCES' => pretty_number($this->dbSourcePlanetRow['metal'] + $this->dbSourcePlanetRow['crystal'] + $this->dbSourcePlanetRow['deuterium']),
1499
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1500
1501
      'PLAYER_OPTION_FLEET_SHIP_SELECT_OLD'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SELECT_OLD],
1502
      'PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED],
1503
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY'    => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY],
1504
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION],
1505
    );
1506
1507
    $template = gettemplate('fleet0', true);
1508
    $template->assign_recursive($template_result);
1509
    display($template, classLocale::$lang['fl_title']);
1510
  }
1511
1512
  public function fleetPage1() {
1513
    global $template_result;
1514
1515
    $this->renderFleet($template_result);
1516
1517
    $this->renderAllowedPlanetTypes($template_result);
1518
1519
    $this->renderOwnPlanets($template_result);
1520
1521
    $this->renderFleetShortcuts($template_result);
1522
1523
    $this->renderACSList($template_result);
1524
1525
    $template_result += array(
1526
      'speed_factor' => flt_server_flight_speed_multiplier(),
1527
1528
      'fleet_speed'    => flt_fleet_speed($this->dbOwnerRow, $this->shipsGetArray()),
1529
      'fleet_capacity' => $this->shipsGetCapacity(),
1530
1531
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1532
1533
      'PAGE_HINT' => classLocale::$lang['fl_page1_hint'],
1534
    );
1535
1536
    $template = gettemplate('fleet1', true);
1537
    $template->assign_recursive($template_result);
1538
    display($template, classLocale::$lang['fl_title']);
1539
  }
1540
1541
  public function fleetPage2() {
1542
    global $template_result;
1543
1544
    try {
1545
      $this->restrictMission();
1546
    } catch(Exception $e) {
1547
      // TODO - MESSAGE BOX
1548
      if($e->getCode() != FLIGHT_ALLOWED) {
1549
        pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
1550
      } else {
1551
        pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1552
      }
1553
    }
1554
1555
    $this->renderAllowedMissions($template_result);
1556
    $this->renderFleet($template_result);
1557
1558
    $max_duration = $this->_mission_type == MT_EXPLORE ? get_player_max_expedition_duration($this->dbOwnerRow) :
1559
      (isset($this->allowed_missions[MT_HOLD]) ? 12 : 0);
1560
    $this->renderDuration($template_result, $max_duration);
1561
1562
    $travel_data = $this->flt_travel_data($this->oldSpeedInTens);
1563
1564
    $sn_group_resources = sn_get_groups('resources_loot');
1565
    $planetResources = array();
1566
    foreach($sn_group_resources as $resource_id) {
1567
      $planetResources[$resource_id] = floor(mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, $resource_id) - ($resource_id == RES_DEUTERIUM ? $travel_data['consumption'] : 0));
1568
    }
1569
    $this->renderPlanetResources($planetResources, $template_result);
1570
1571
    if(sn_module::$sn_module['unit_captain']->manifest['active'] && ($captain = sn_module::$sn_module['unit_captain']->unit_captain_get($this->dbSourcePlanetRow['id'])) && $captain['unit_location_type'] == LOC_PLANET) {
1572
      $template_result += array(
1573
        'CAPTAIN_ID'     => $captain['unit_id'],
1574
        'CAPTAIN_LEVEL'  => $captain['captain_level'],
1575
        'CAPTAIN_SHIELD' => $captain['captain_shield'],
1576
        'CAPTAIN_ARMOR'  => $captain['captain_armor'],
1577
        'CAPTAIN_ATTACK' => $captain['captain_attack'],
1578
      );
1579
    }
1580
1581
    $template_result += array(
1582
      'planet_metal'     => $planetResources[RES_METAL],
1583
      'planet_crystal'   => $planetResources[RES_CRYSTAL],
1584
      'planet_deuterium' => $planetResources[RES_DEUTERIUM],
1585
1586
      'fleet_capacity' => $this->shipsGetCapacity() - $travel_data['consumption'],
1587
      'speed'          => $this->oldSpeedInTens,
1588
      'fleet_group'    => $this->_group_id,
1589
1590
      'MAX_DURATION'          => $max_duration,
1591
1592
      // TODO - remove
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
1593
//      'IS_TRANSPORT_MISSIONS' => !empty($this->allowed_missions[$this->_mission_type]['transport']),
1594
      'IS_TRANSPORT_MISSIONS' => true,
1595
1596
      'PLAYER_COLONIES_CURRENT' => get_player_current_colonies($this->dbOwnerRow),
1597
      'PLAYER_COLONIES_MAX'     => get_player_max_colonies($this->dbOwnerRow),
1598
    );
1599
1600
    $template = gettemplate('fleet2', true);
1601
    $template->assign_recursive($template_result);
1602
    display($template, classLocale::$lang['fl_title']);
1603
  }
1604
1605
  /**
1606
   * @param array $template_result
1607
   *
1608
   * @return array
1609
   */
1610
  protected function renderAllowedMissions(&$template_result) {
1611
    ksort($this->allowed_missions);
1612
    // If mission is not set - setting first mission from allowed
1613
    if(empty($this->_mission_type) && is_array($this->allowed_missions)) {
1614
      $this->_mission_type = reset($this->allowed_missions);
1615
    }
1616
    foreach($this->allowed_missions as $key => $value) {
1617
      $template_result['.']['missions'][] = array(
1618
        'ID'   => $key,
1619
        'NAME' => classLocale::$lang['type_mission'][$key],
1620
      );
1621
    };
1622
  }
1623
1624
  /**
1625
   * @param $template_result
1626
   */
1627
  protected function renderDuration(&$template_result, $max_duration) {
1628
    if($max_duration) {
1629
      $config_game_speed_expedition = ($this->_mission_type == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1);
1630
      for($i = 1; $i <= $max_duration; $i++) {
1631
        $template_result['.']['duration'][] = array(
1632
          'ID'   => $i,
1633
          'TIME' => pretty_time(ceil($i * 3600 / $config_game_speed_expedition)),
1634
        );
1635
      }
1636
    }
1637
  }
1638
1639
  /**
1640
   * @param array $planetResources
1641
   * @param array &$template_result
1642
   */
1643
  protected function renderPlanetResources(&$planetResources, &$template_result) {
1644
    // TODO - REDO to resource_id
1645
    $i = 0;
1646
    foreach($planetResources as $resource_id => $resource_amount) {
1647
      $template_result['.']['resources'][] = array(
1648
        'ID'        => $i++, // $resource_id,
1649
        'ON_PLANET' => $resource_amount,
1650
        'TEXT'      => pretty_number($resource_amount),
1651
        'NAME'      => classLocale::$lang['tech'][$resource_id],
1652
      );
1653
    }
1654
  }
1655
1656
  /**
1657
   * @param $template_result
1658
   */
1659
  protected function renderAllowedPlanetTypes(&$template_result) {
1660
    foreach($this->allowed_planet_types as $possible_planet_type_id) {
1661
      $template_result['.']['possible_planet_type_id'][] = array(
1662
        'ID'         => $possible_planet_type_id,
1663
        'NAME'       => classLocale::$lang['sys_planet_type'][$possible_planet_type_id],
1664
        'NAME_SHORT' => classLocale::$lang['sys_planet_type_sh'][$possible_planet_type_id],
1665
      );
1666
    }
1667
  }
1668
1669
  protected function renderFleet1TargetSelect(&$shortcut) {
1670
    global $note_priority_classes;
1671
1672
    $name = !empty($shortcut['title']) ? $shortcut['title'] : $shortcut['name'];
1673
1674
    $result = array(
1675
      'NAME'       => $name,
1676
      'GALAXY'     => $shortcut['galaxy'],
1677
      'SYSTEM'     => $shortcut['system'],
1678
      'PLANET'     => $shortcut['planet'],
1679
      'TYPE'       => $shortcut['planet_type'],
1680
      'TYPE_PRINT' => classLocale::$lang['fl_shrtcup'][$shortcut['planet_type']],
1681
    );
1682
1683
    if(isset($shortcut['priority'])) {
1684
      $result += array(
1685
        'PRIORITY'       => $shortcut['priority'],
1686
        'PRIORITY_CLASS' => $note_priority_classes[$shortcut['priority']],
1687
      );
1688
    }
1689
1690
    if(isset($shortcut['id'])) {
1691
      $result += array(
1692
        'ID' => $shortcut['id'],
1693
      );
1694
    }
1695
1696
    return $result;
1697
  }
1698
1699
  /**
1700
   * @param $template_result
1701
   */
1702
  protected function renderFleetShortcuts(&$template_result) {
1703
    // Building list of shortcuts
1704
    $query = db_note_list_select_by_owner_and_planet($this->dbOwnerRow);
1705
    while($row = db_fetch($query)) {
1706
      $template_result['.']['shortcut'][] = $this->renderFleet1TargetSelect($row);
1707
    }
1708
  }
1709
1710
  /**
1711
   * Building list of own planets & moons
1712
   *
1713
   * @param $template_result
1714
   */
1715
  protected function renderOwnPlanets(&$template_result) {
1716
    $colonies = db_planet_list_sorted($this->dbOwnerRow);
1717
    if(count($colonies) <= 1) {
1718
      return;
1719
    }
1720
1721
    foreach($colonies as $row) {
1722
      if($row['id'] == $this->dbSourcePlanetRow['id']) {
1723
        continue;
1724
      }
1725
1726
      $template_result['.']['colonies'][] = $this->renderFleet1TargetSelect($row);
1727
    }
1728
  }
1729
1730
  /**
1731
   * @param $template_result
1732
   */
1733
  protected function renderACSList(&$template_result) {
1734
    $query = db_acs_get_list();
1735
    while($row = db_fetch($query)) {
1736
      $members = explode(',', $row['eingeladen']);
1737
      foreach($members as $a => $b) {
1738
        if($b == $this->dbOwnerRow['id']) {
1739
          $template_result['.']['acss'][] = $this->renderFleet1TargetSelect($row);
1740
        }
1741
      }
1742
    }
1743
  }
1744
1745
  /**
1746
   * @param $template_result
1747
   */
1748
  protected function renderShipSortOptions(&$template_result) {
1749
    foreach(classLocale::$lang['player_option_fleet_ship_sort'] as $sort_id => $sort_text) {
1750
      $template_result['.']['ship_sort_list'][] = array(
1751
        'VALUE' => $sort_id,
1752
        'TEXT'  => $sort_text,
1753
      );
1754
    }
1755
    $template_result += array(
1756
      'FLEET_SHIP_SORT'         => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT],
1757
      'FLEET_SHIP_SORT_INVERSE' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE],
1758
    );
1759
  }
1760
1761
}
1762