Completed
Push — work-fleets ( ab257a...4117d7 )
by SuperNova.WS
05:11
created

Fleet::checkTargetNotSource()   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 0
1
<?php
2
3
/**
4
 * Class Fleet
5
 *
6
 * @property int dbId
7
 * @property int playerOwnerId
8
 * @property int group_id
9
 * @property int mission_type
10
 * @property int target_owner_id
11
 * @property int is_returning
12
 *
13
 * @property int time_launch
14
 * @property int time_arrive_to_target
15
 * @property int time_mission_job_complete
16
 * @property int time_return_to_source
17
 *
18
 * @property int fleet_start_planet_id
19
 * @property int fleet_start_galaxy
20
 * @property int fleet_start_system
21
 * @property int fleet_start_planet
22
 * @property int fleet_start_type
23
 *
24
 * @property int fleet_end_planet_id
25
 * @property int fleet_end_galaxy
26
 * @property int fleet_end_system
27
 * @property int fleet_end_planet
28
 * @property int fleet_end_type
29
 *
30
 */
31
class Fleet extends UnitContainer {
32
33
  // DBRow inheritance *************************************************************************************************
34
35
  /**
36
   * Table name in DB
37
   *
38
   * @var string
39
   */
40
  protected static $_table = 'fleets';
41
  /**
42
   * Name of ID field in DB
43
   *
44
   * @var string
45
   */
46
  protected static $_dbIdFieldName = 'fleet_id';
47
  /**
48
   * DB_ROW to Class translation scheme
49
   *
50
   * @var array
51
   */
52
  protected static $_properties = array(
53
    'dbId'          => array(
54
      P_DB_FIELD => 'fleet_id',
55
    ),
56
    'playerOwnerId' => array(
57
      P_METHOD_EXTRACT => 'ownerExtract',
58
      P_METHOD_INJECT  => 'ownerInject',
59
//      P_DB_FIELD => 'fleet_owner',
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
60
    ),
61
    'mission_type'  => array(
62
      P_DB_FIELD   => 'fleet_mission',
63
      P_FUNC_INPUT => 'intval',
64
    ),
65
66
    'target_owner_id' => array(
67
      P_DB_FIELD => 'fleet_target_owner',
68
    ),
69
    'group_id'        => array(
70
      P_DB_FIELD => 'fleet_group',
71
    ),
72
    'is_returning'    => array(
73
      P_DB_FIELD   => 'fleet_mess',
74
      P_FUNC_INPUT => 'intval',
75
    ),
76
77
    'shipCount' => array(
78
      P_DB_FIELD  => 'fleet_amount',
79
// TODO - CHECK !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
80
//      P_FUNC_OUTPUT => 'get_ship_count',
81
//      P_DB_FIELDS_LINKED => array(
82
//        'fleet_amount',
83
//      ),
84
      P_READ_ONLY => true,
85
    ),
86
87
    'time_launch' => array(
88
      P_DB_FIELD => 'start_time',
89
    ),
90
91
    'time_arrive_to_target'     => array(
92
      P_DB_FIELD => 'fleet_start_time',
93
    ),
94
    'time_mission_job_complete' => array(
95
      P_DB_FIELD => 'fleet_end_stay',
96
    ),
97
    'time_return_to_source'     => array(
98
      P_DB_FIELD => 'fleet_end_time',
99
    ),
100
101
    'fleet_start_planet_id' => array(
102
      P_DB_FIELD   => 'fleet_start_planet_id',
103
      P_FUNC_INPUT => 'nullIfEmpty',
104
    ),
105
106
    'fleet_start_galaxy' => array(
107
      P_DB_FIELD => 'fleet_start_galaxy',
108
    ),
109
    'fleet_start_system' => array(
110
      P_DB_FIELD => 'fleet_start_system',
111
    ),
112
    'fleet_start_planet' => array(
113
      P_DB_FIELD => 'fleet_start_planet',
114
    ),
115
    'fleet_start_type'   => array(
116
      P_DB_FIELD => 'fleet_start_type',
117
    ),
118
119
    'fleet_end_planet_id' => array(
120
      P_DB_FIELD   => 'fleet_end_planet_id',
121
      P_FUNC_INPUT => 'nullIfEmpty',
122
    ),
123
    'fleet_end_galaxy'    => array(
124
      P_DB_FIELD => 'fleet_end_galaxy',
125
    ),
126
    'fleet_end_system'    => array(
127
      P_DB_FIELD => 'fleet_end_system',
128
    ),
129
    'fleet_end_planet'    => array(
130
      P_DB_FIELD => 'fleet_end_planet',
131
    ),
132
    'fleet_end_type'      => array(
133
      P_DB_FIELD => 'fleet_end_type',
134
    ),
135
136
    'resource_list' => array(
137
      P_METHOD_EXTRACT   => 'resourcesExtract',
138
      P_METHOD_INJECT    => 'resourcesInject',
139
      P_DB_FIELDS_LINKED => array(
140
        'fleet_resource_metal',
141
        'fleet_resource_crystal',
142
        'fleet_resource_deuterium',
143
      ),
144
    ),
145
  );
146
147
148
  // UnitContainer inheritance *****************************************************************************************
149
  /**
150
   * Type of this location
151
   *
152
   * @var int $locationType
153
   */
154
  protected static $locationType = LOC_FLEET;
155
156
157
  // New properties ****************************************************************************************************
158
  /**
159
   * `fleet_owner`
160
   *
161
   * @var int
162
   */
163
  protected $_playerOwnerId = 0;
164
  /**
165
   * `fleet_group`
166
   *
167
   * @var int
168
   */
169
  protected $_group_id = 0;
170
171
  /**
172
   * `fleet_mission`
173
   *
174
   * @var int
175
   */
176
  protected $_mission_type = 0;
177
178
  /**
179
   * `fleet_target_owner`
180
   *
181
   * @var int
182
   */
183
  protected $_target_owner_id = null;
184
185
  /**
186
   * @var array
187
   */
188
  protected $resource_list = array(
189
    RES_METAL     => 0,
190
    RES_CRYSTAL   => 0,
191
    RES_DEUTERIUM => 0,
192
  );
193
194
195
  /**
196
   * `fleet__mess` - Флаг возвращающегося флота
197
   *
198
   * @var int
199
   */
200
  protected $_is_returning = 0;
201
  /**
202
   * `start_time` - Время отправления - таймштамп взлёта флота из точки отправления
203
   *
204
   * @var int $_time_launch
205
   */
206
  protected $_time_launch = 0; // `start_time` = SN_TIME_NOW
207
  /**
208
   * `fleet_start_time` - Время прибытия в точку миссии/время начала выполнения миссии
209
   *
210
   * @var int $_time_arrive_to_target
211
   */
212
  protected $_time_arrive_to_target = 0; // `fleet_start_time` = SN_TIME_NOW + $time_travel
213
  /**
214
   * `fleet_end_stay` - Время окончания миссии в точке назначения
215
   *
216
   * @var int $_time_mission_job_complete
217
   */
218
  protected $_time_mission_job_complete = 0; // `fleet_end_stay`
219
  /**
220
   * `fleet_end_time` - Время возвращения флота после окончания миссии
221
   *
222
   * @var int $_time_return_to_source
223
   */
224
  protected $_time_return_to_source = 0; // `fleet_end_time`
225
226
227
  protected $_fleet_start_planet_id = null;
228
  protected $_fleet_start_galaxy = 0;
229
  protected $_fleet_start_system = 0;
230
  protected $_fleet_start_planet = 0;
231
  protected $_fleet_start_type = PT_ALL;
232
233
  protected $_fleet_end_planet_id = null;
234
  protected $_fleet_end_galaxy = 0;
235
  protected $_fleet_end_system = 0;
236
  protected $_fleet_end_planet = 0;
237
  protected $_fleet_end_type = PT_ALL;
238
239
  // Missile properties
240
  public $missile_target = 0;
241
242
  // Fleet event properties
243
  public $fleet_start_name = '';
244
  public $fleet_end_name = '';
245
  public $ov_label = '';
246
  public $ov_this_planet = '';
247
  public $event_time = 0;
248
249
  protected $resource_delta = array();
250
  protected $resource_replace = array();
251
252
253
//
254
255
256
  protected $allowed_missions = array();
257
  protected $allowed_planet_types = array(
258
    // PT_NONE => PT_NONE,
259
    PT_PLANET => PT_PLANET,
260
    PT_MOON   => PT_MOON,
261
    PT_DEBRIS => PT_DEBRIS
262
  );
263
264
  // TODO - Move to Player
265
  public $dbOwnerRow = array();
266
  public $dbSourcePlanetRow = array();
267
268
  /**
269
   * GSPT coordinates of target
270
   *
271
   * @var Vector
272
   */
273
  public $targetVector = array();
274
  /**
275
   * Target planet row
276
   *
277
   * @var array
278
   */
279
  public $dbTargetRow = array();
280
  public $dbTargetOwnerRow = array();
281
282
  /**
283
   * Fleet speed - old in 1/10 of 100%
284
   *
285
   * @var int
286
   */
287
  public $oldSpeedInTens = 0;
288
289
  public $tempPlayerMaxFleets = 0;
290
  public $travelData = array();
291
292
  /**
293
   * Fleet constructor.
294
   */
295
  public function __construct() {
296
    parent::__construct();
297
    $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...
298
  }
299
300
  /**
301
   * @param array $template_result
302
   * @param array $playerRow
303
   * @param array $planetRow
304
   */
305
  // TODO - redo to unit/unitlist renderer
306
  public function renderAvailableShips(&$template_result, $playerRow, $planetRow) {
307
    $record_index = 0;
308
    $ship_list = array();
309
    foreach(sn_get_groups('fleet') as $n => $unit_id) {
310
      $unit_level = mrc_get_level($playerRow, $planetRow, $unit_id, false, true);
311
      if($unit_level <= 0) {
312
        continue;
313
      }
314
      $ship_data = get_ship_data($unit_id, $playerRow);
315
      $ship_list[$unit_id] = array(
316
        '__INDEX'          => $record_index++,
317
        'ID'               => $unit_id,
318
        'NAME'             => classLocale::$lang['tech'][$unit_id],
319
        'AMOUNT'           => $unit_level,
320
        'AMOUNT_TEXT'      => pretty_number($unit_level),
321
        'CONSUMPTION'      => $ship_data['consumption'],
322
        'CONSUMPTION_TEXT' => pretty_number($ship_data['consumption']),
323
        'SPEED'            => $ship_data['speed'],
324
        'SPEED_TEXT'       => pretty_number($ship_data['speed']),
325
        'CAPACITY'         => $ship_data['capacity'],
326
        'CAPACITY_TEXT'    => pretty_number($ship_data['capacity']),
327
      );
328
    }
329
330
    sortUnitRenderedList($ship_list, classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT], classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE]);
331
332
    foreach($ship_list as $ship_data) {
333
      $template_result['.']['ships'][] = $ship_data;
334
    }
335
  }
336
337
  public function isEmpty() {
338
    return !$this->resourcesGetTotal() && !$this->shipsGetTotal();
339
  }
340
341
//  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...
342
//    return $this->playerOwnerId;
343
//  }
344
345
  /**
346
   * Initializes Fleet from user params and posts it to DB
347
   */
348
  public function dbInsert() {
349
    // WARNING! MISSION TIMES MUST BE SET WITH set_times() method!
350
    // TODO - more checks!
351
    if(empty($this->_time_launch)) {
352
      die('Fleet time not set!');
353
    }
354
355
    parent::dbInsert();
356
  }
357
358
359
  /* FLEET DB ACCESS =================================================================================================*/
360
361
  /**
362
   * LOCK - Lock all records which can be used with mission
363
   *
364
   * @param $mission_data
365
   * @param $fleet_id
366
   *
367
   * @return array|bool|mysqli_result|null
368
   */
369
  public function dbLockFlying(&$mission_data) {
370
    // Тупо лочим всех юзеров, чьи флоты летят или улетают с координат отбытия/прибытия $fleet_row
371
    // Что бы делать это умно - надо учитывать fleet__mess во $fleet_row и в таблице fleets
372
373
    $fleet_id_safe = idval($this->_dbId);
374
375
    return doquery(
376
    // Блокировка самого флота
377
      "SELECT 1 FROM {{fleets}} AS f " .
378
379
      // Блокировка всех юнитов, принадлежащих этому флоту
380
      "LEFT JOIN {{unit}} as unit ON unit.unit_location_type = " . static::$locationType . " AND unit.unit_location_id = f.fleet_id " .
381
382
      // Блокировка всех прилетающих и улетающих флотов, если нужно
383
      // TODO - lock fleets by COORDINATES
384
      ($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 " : '') .
385
      // Блокировка всех юнитов, принадлежащих прилетающим и улетающим флотам - ufd = unit_fleet_destination
386
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{unit}} AS ufd ON ufd.unit_location_type = " . static::$locationType . " AND ufd.unit_location_id = fd.fleet_id " : '') .
387
388
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{users}} AS ud ON ud.id = f.fleet_target_owner " : '') .
389
      // Блокировка всех юнитов, принадлежащих владельцу планеты-цели
390
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS unit_player_dest ON unit_player_dest.unit_player_id = ud.id " : '') .
391
      // Блокировка планеты-цели
392
      ($mission_data['dst_planet'] ? "LEFT JOIN {{planets}} AS pd ON pd.id = f.fleet_end_planet_id " : '') .
393
      // Блокировка всех юнитов, принадлежащих планете-цели - НЕ НУЖНО. Уже залочили ранее, как принадлежащие игроку-цели
394
//      ($mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS upd ON upd.unit_location_type = " . LOC_PLANET . " AND upd.unit_location_id = pd.id " : '') .
395
396
397
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{users}} AS us ON us.id = f.fleet_owner " : '') .
398
      // Блокировка всех юнитов, принадлежащих владельцу флота
399
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS unit_player_src ON unit_player_src.unit_player_id = us.id " : '') .
400
      // Блокировка планеты отправления
401
      ($mission_data['src_planet'] ? "LEFT JOIN {{planets}} AS ps ON ps.id = f.fleet_start_planet_id " : '') .
402
      // Блокировка всех юнитов, принадлежащих планете с которой юниты были отправлены - НЕ НУЖНО. Уже залочили ранее, как принадлежащие владельцу флота
403
//      ($mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS ups ON ups.unit_location_type = " . LOC_PLANET . " AND ups.unit_location_id = ps.id " : '') .
404
405
      "WHERE f.fleet_id = {$fleet_id_safe} GROUP BY 1 FOR UPDATE"
406
    );
407
  }
408
409
  /**
410
   * Lock all fields that belongs to operation
411
   *
412
   * @param $dbId
413
   *
414
   * @internal param DBLock $dbRow - Object that accumulates locks
415
   *
416
   */
417
  // TODO = make static
418
  public function dbGetLockById($dbId) {
419
    doquery(
420
    // Блокировка самого флота
421
      "SELECT 1 FROM {{fleets}} AS FLEET0 " .
422
      // Lock fleet owner
423
      "LEFT JOIN {{users}} as USER0 on USER0.id = FLEET0.fleet_owner " .
424
      // Блокировка всех юнитов, принадлежащих этому флоту
425
      "LEFT JOIN {{unit}} as UNIT0 ON UNIT0.unit_location_type = " . LOC_FLEET . " AND UNIT0.unit_location_id = FLEET0.fleet_id " .
426
427
      // Без предварительной выборки неизвестно - куда летит этот флот.
428
      // Поэтому надо выбирать флоты, чьи координаты прибытия ИЛИ отбытия совпадают с координатами прибытия ИЛИ отбытия текущего флота.
429
      // Получаем матрицу 2х2 - т.е. 4 подзапроса.
430
      // При блокировке всегда нужно выбирать И лпанету, И луну - поскольку при бое на орбите луны обломки падают на орбиту планеты.
431
      // Поэтому тип планеты не указывается
432
433
      // Lock fleet heading to destination planet. Only if FLEET0.fleet_mess == 0
434
      "LEFT JOIN {{fleets}} AS FLEET1 ON
435
        FLEET1.fleet_mess = 0 AND FLEET0.fleet_mess = 0 AND
436
        FLEET1.fleet_end_galaxy = FLEET0.fleet_end_galaxy AND
437
        FLEET1.fleet_end_system = FLEET0.fleet_end_system AND
438
        FLEET1.fleet_end_planet = FLEET0.fleet_end_planet
439
      " .
440
      // Блокировка всех юнитов, принадлежащих этим флотам
441
      "LEFT JOIN {{unit}} as UNIT1 ON UNIT1.unit_location_type = " . LOC_FLEET . " AND UNIT1.unit_location_id = FLEET1.fleet_id " .
442
      // Lock fleet owner
443
      "LEFT JOIN {{users}} as USER1 on USER1.id = FLEET1.fleet_owner " .
444
445
      "LEFT JOIN {{fleets}} AS FLEET2 ON
446
        FLEET2.fleet_mess = 1   AND FLEET0.fleet_mess = 0 AND
447
        FLEET2.fleet_start_galaxy = FLEET0.fleet_end_galaxy AND
448
        FLEET2.fleet_start_system = FLEET0.fleet_end_system AND
449
        FLEET2.fleet_start_planet = FLEET0.fleet_end_planet
450
      " .
451
      // Блокировка всех юнитов, принадлежащих этим флотам
452
      "LEFT JOIN {{unit}} as UNIT2 ON
453
        UNIT2.unit_location_type = " . LOC_FLEET . " AND
454
        UNIT2.unit_location_id = FLEET2.fleet_id
455
      " .
456
      // Lock fleet owner
457
      "LEFT JOIN {{users}} as USER2 on
458
        USER2.id = FLEET2.fleet_owner
459
      " .
460
461
      // Lock fleet heading to source planet. Only if FLEET0.fleet_mess == 1
462
      "LEFT JOIN {{fleets}} AS FLEET3 ON
463
        FLEET3.fleet_mess = 0 AND FLEET0.fleet_mess = 1 AND
464
        FLEET3.fleet_end_galaxy = FLEET0.fleet_start_galaxy AND
465
        FLEET3.fleet_end_system = FLEET0.fleet_start_system AND
466
        FLEET3.fleet_end_planet = FLEET0.fleet_start_planet
467
      " .
468
      // Блокировка всех юнитов, принадлежащих этим флотам
469
      "LEFT JOIN {{unit}} as UNIT3 ON
470
        UNIT3.unit_location_type = " . LOC_FLEET . " AND
471
        UNIT3.unit_location_id = FLEET3.fleet_id
472
      " .
473
      // Lock fleet owner
474
      "LEFT JOIN {{users}} as USER3 on USER3.id = FLEET3.fleet_owner " .
475
476
      "LEFT JOIN {{fleets}} AS FLEET4 ON
477
        FLEET4.fleet_mess = 1   AND FLEET0.fleet_mess = 1 AND
478
        FLEET4.fleet_start_galaxy = FLEET0.fleet_start_galaxy AND
479
        FLEET4.fleet_start_system = FLEET0.fleet_start_system AND
480
        FLEET4.fleet_start_planet = FLEET0.fleet_start_planet
481
      " .
482
      // Блокировка всех юнитов, принадлежащих этим флотам
483
      "LEFT JOIN {{unit}} as UNIT4 ON
484
        UNIT4.unit_location_type = " . LOC_FLEET . " AND
485
        UNIT4.unit_location_id = FLEET4.fleet_id
486
      " .
487
      // Lock fleet owner
488
      "LEFT JOIN {{users}} as USER4 on
489
        USER4.id = FLEET4.fleet_owner
490
      " .
491
492
493
      // Locking start planet
494
      "LEFT JOIN {{planets}} AS PLANETS5 ON
495
        FLEET0.fleet_mess = 1 AND
496
        PLANETS5.galaxy = FLEET0.fleet_start_galaxy AND
497
        PLANETS5.system = FLEET0.fleet_start_system AND
498
        PLANETS5.planet = FLEET0.fleet_start_planet
499
      " .
500
      // Lock planet owner
501
      "LEFT JOIN {{users}} as USER5 on
502
        USER5.id = PLANETS5.id_owner
503
      " .
504
      // Блокировка всех юнитов, принадлежащих этой планете
505
      "LEFT JOIN {{unit}} as UNIT5 ON
506
        UNIT5.unit_location_type = " . LOC_PLANET . " AND
507
        UNIT5.unit_location_id = PLANETS5.id
508
      " .
509
510
511
      // Locking destination planet
512
      "LEFT JOIN {{planets}} AS PLANETS6 ON
513
        FLEET0.fleet_mess = 0 AND
514
        PLANETS6.galaxy = FLEET0.fleet_end_galaxy AND
515
        PLANETS6.system = FLEET0.fleet_end_system AND
516
        PLANETS6.planet = FLEET0.fleet_end_planet
517
      " .
518
      // Lock planet owner
519
      "LEFT JOIN {{users}} as USER6 on
520
        USER6.id = PLANETS6.id_owner
521
      " .
522
      // Блокировка всех юнитов, принадлежащих этой планете
523
      "LEFT JOIN {{unit}} as UNIT6 ON
524
        UNIT6.unit_location_type = " . LOC_PLANET . " AND
525
        UNIT6.unit_location_id = PLANETS6.id
526
      " .
527
      "WHERE FLEET0.fleet_id = {$dbId} GROUP BY 1 FOR UPDATE"
528
    );
529
  }
530
531
532
  public function dbRowParse($db_row) {
533
    parent::dbRowParse($db_row); // TODO: Change the autogenerated stub
534
    $player = new Player();
535
    $player->dbLoad($db_row['fleet_owner']);
536
    $this->setLocatedAt($player);
537
  }
538
539
  /* FLEET HELPERS =====================================================================================================*/
540
  /**
541
   * Forcibly returns fleet before time outs
542
   */
543
  public function commandReturn() {
544
    $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;
545
546
    $this->markReturned();
547
548
    // Считаем, что флот уже долетел TODO
549
    $this->time_arrive_to_target = SN_TIME_NOW;
550
    // Убираем флот из группы
551
    $this->group_id = 0;
552
    // Отменяем работу в точке назначения
553
    $this->time_mission_job_complete = 0;
554
    // TODO - правильно вычслять время возвращения - по проделанному пути, а не по старому времени возвращения
555
    $this->time_return_to_source = $ReturnFlyingTime;
556
557
    // Записываем изменения в БД
558
    $this->dbSave();
559
560
    if($this->_group_id) {
561
      // TODO: Make here to delete only one AKS - by adding aks_fleet_count to AKS table
562
      db_fleet_aks_purge();
563
    }
564
  }
565
566
567
  /**
568
   * @return array
569
   */
570
  public function target_coordinates_without_type() {
571
    return array(
572
      'galaxy' => $this->_fleet_end_galaxy,
573
      'system' => $this->_fleet_end_system,
574
      'planet' => $this->_fleet_end_planet,
575
    );
576
  }
577
578
  /**
579
   * @return array
580
   */
581
  public function target_coordinates_typed() {
582
    return array(
583
      'galaxy' => $this->_fleet_end_galaxy,
584
      'system' => $this->_fleet_end_system,
585
      'planet' => $this->_fleet_end_planet,
586
      'type'   => $this->_fleet_end_type,
587
    );
588
  }
589
590
  /**
591
   * @return array
592
   */
593
  public function launch_coordinates_typed() {
594
    return array(
595
      'galaxy' => $this->_fleet_start_galaxy,
596
      'system' => $this->_fleet_start_system,
597
      'planet' => $this->_fleet_start_planet,
598
      'type'   => $this->_fleet_start_type,
599
    );
600
  }
601
602
603
  /**
604
   * Sets object fields for fleet return
605
   */
606
  public function markReturned() {
607
    // TODO - Проверка - а не возвращается ли уже флот?
608
    $this->is_returning = 1;
609
  }
610
611
  public function isReturning() {
612
    return 1 == $this->_is_returning;
613
  }
614
615
  public function markReturnedAndSave() {
616
    $this->markReturned();
617
    $this->dbSave();
618
  }
619
620
  /**
621
   * Parses extended unit_array which can include not only ships but resources, captains etc
622
   *
623
   * @param $unit_array
624
   */
625
  // TODO - separate shipList and unitList
626
  public function unitsSetFromArray($unit_array) {
627
    if(empty($unit_array) || !is_array($unit_array)) {
628
      return;
629
    }
630
    foreach($unit_array as $unit_id => $unit_count) {
631
      $unit_count = floatval($unit_count);
632
      if(!$unit_count) {
633
        continue;
634
      }
635
636
      if($this->isShip($unit_id)) {
637
        $this->unitList->unitSetCount($unit_id, $unit_count);
638
      } elseif($this->isResource($unit_id)) {
639
        $this->resource_list[$unit_id] = $unit_count;
640
      } else {
641
        throw new Exception('Trying to pass to fleet non-resource and non-ship ' . var_export($unit_array, true), ERR_ERROR);
642
      }
643
    }
644
  }
645
646
647
  /**
648
   * Sets fleet timers based on flight duration, time on mission (HOLD/EXPLORE) and fleet departure time.
649
   *
650
   * @param int $time_to_travel - flight duration in seconds
651
   * @param int $time_on_mission - time on mission in seconds
652
   * @param int $group_sync_delta_time - delta time to adjust fleet arrival time if fleet is a part of group (i.e. ACS)
653
   * @param int $flight_departure - fleet departure from source planet timestamp. Allows to send fleet in future or in past
654
   */
655
  public function set_times($time_to_travel, $time_on_mission = 0, $group_sync_delta_time = 0, $flight_departure = SN_TIME_NOW) {
656
    $this->_time_launch = $flight_departure;
657
658
    $this->_time_arrive_to_target = $this->_time_launch + $time_to_travel + $group_sync_delta_time;
659
    $this->_time_mission_job_complete = $time_on_mission ? $this->_time_arrive_to_target + $time_on_mission : 0;
660
    $this->_time_return_to_source = ($this->_time_mission_job_complete ? $this->_time_mission_job_complete : $this->_time_arrive_to_target) + $time_to_travel;
661
  }
662
663
664
  public function parse_missile_db_row($missile_db_row) {
665
//    $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...
666
667
    if(empty($missile_db_row) || !is_array($missile_db_row)) {
668
      return;
669
    }
670
671
//      $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...
672
//      $irak_original['fleet_start_name'] = $planet_start['name'];
673
    $this->missile_target = $missile_db_row['primaer'];
674
675
    $this->_dbId = -$missile_db_row['id'];
676
    $this->_playerOwnerId = $missile_db_row['fleet_owner'];
677
    $this->_mission_type = MT_MISSILE;
678
679
    $this->_target_owner_id = $missile_db_row['fleet_target_owner'];
680
681
    $this->_group_id = 0;
682
    $this->_is_returning = 0;
683
684
    $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...
685
    $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...
686
    $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...
687
    $this->_time_return_to_source = $missile_db_row['fleet_end_time'];
688
689
    $this->_fleet_start_planet_id = !empty($missile_db_row['fleet_start_planet_id']) ? $missile_db_row['fleet_start_planet_id'] : null;
690
    $this->_fleet_start_galaxy = $missile_db_row['fleet_start_galaxy'];
691
    $this->_fleet_start_system = $missile_db_row['fleet_start_system'];
692
    $this->_fleet_start_planet = $missile_db_row['fleet_start_planet'];
693
    $this->_fleet_start_type = $missile_db_row['fleet_start_type'];
694
695
    $this->_fleet_end_planet_id = !empty($missile_db_row['fleet_end_planet_id']) ? $missile_db_row['fleet_end_planet_id'] : null;
696
    $this->_fleet_end_galaxy = $missile_db_row['fleet_end_galaxy'];
697
    $this->_fleet_end_system = $missile_db_row['fleet_end_system'];
698
    $this->_fleet_end_planet = $missile_db_row['fleet_end_planet'];
699
    $this->_fleet_end_type = $missile_db_row['fleet_end_type'];
700
701
    $this->unitList->unitSetCount(UNIT_DEF_MISSILE_INTERPLANET, $missile_db_row['fleet_amount']);
702
  }
703
704
705
  /**
706
   * @param $from
707
   */
708
  public function set_start_planet($from) {
709
    $this->fleet_start_planet_id = intval($from['id']) ? $from['id'] : null;
710
    $this->fleet_start_galaxy = $from['galaxy'];
711
    $this->fleet_start_system = $from['system'];
712
    $this->fleet_start_planet = $from['planet'];
713
    $this->fleet_start_type = $from['planet_type'];
714
  }
715
716
  /**
717
   * @param $to
718
   */
719
  public function set_end_planet($to) {
720
    $this->target_owner_id = intval($to['id_owner']) ? $to['id_owner'] : 0;
721
    $this->fleet_end_planet_id = intval($to['id']) ? $to['id'] : null;
722
    $this->fleet_end_galaxy = $to['galaxy'];
723
    $this->fleet_end_system = $to['system'];
724
    $this->fleet_end_planet = $to['planet'];
725
    $this->fleet_end_type = $to['planet_type'];
726
  }
727
728
  /**
729
   * @param Vector $to
730
   */
731
  public function setTargetFromVectorObject($to) {
732
    $this->_fleet_end_galaxy = $to->galaxy;
733
    $this->_fleet_end_system = $to->system;
734
    $this->_fleet_end_planet = $to->planet;
735
    $this->_fleet_end_type = $to->type;
736
  }
737
738
  /**
739
   * @param array $db_row
740
   */
741
  protected function ownerExtract(array &$db_row) {
742
    $player = new Player();
743
    $player->dbLoad($db_row['fleet_owner']);
744
    $this->setLocatedAt($player);
745
  }
746
747
  /**
748
   * @param array $db_row
749
   */
750
  protected function ownerInject(array &$db_row) {
751
    $db_row['fleet_owner'] = $this->getPlayerOwnerId();
752
  }
753
754
755
756
757
  // UnitList/Ships access ***************************************************************************************************
758
759
  // TODO - перекрывать пожже - для миссайл-флотов и дефенс-флотов
760
  protected function isShip($unit_id) {
761
    return UnitShip::is_in_group($unit_id);
762
  }
763
764
  /**
765
   * Set unit count of $unit_id to $unit_count
766
   * If there is no $unit_id - it will be created and saved to DB on dbSave
767
   *
768
   * @param int $unit_id
769
   * @param int $unit_count
770
   */
771
  public function shipSetCount($unit_id, $unit_count = 0) {
772
    $this->shipAdjustCount($unit_id, $unit_count, true);
773
  }
774
775
  /**
776
   * Adjust unit count of $unit_id by $unit_count - or just replace value
777
   * If there is no $unit_id - it will be created and saved to DB on dbSave
778
   *
779
   * @param int  $unit_id
780
   * @param int  $unit_count
781
   * @param bool $replace_value
782
   */
783
  public function shipAdjustCount($unit_id, $unit_count = 0, $replace_value = false) {
784
    $this->unitList->unitAdjustCount($unit_id, $unit_count, $replace_value);
785
  }
786
787
  public function shipGetCount($unit_id) {
788
    return $this->unitList->unitGetCount($unit_id);
789
  }
790
791
  public function shipsCountApplyLossMultiplier($ships_lost_multiplier) {
792
    $this->unitList->unitsCountApplyLossMultiplier($ships_lost_multiplier);
793
  }
794
795
  /**
796
   * Returns ship list in fleet
797
   */
798
  public function shipsGetArray() {
799
    return $this->unitList->unitsGetArray();
800
  }
801
802
  public function shipsGetTotal() {
803
    return $this->unitList->unitsCount();
804
  }
805
806
  public function shipsGetCapacity() {
807
    return $this->unitList->shipsCapacity();
808
  }
809
810
  public function shipsGetHoldFree() {
811
    return max(0, $this->shipsGetCapacity() - $this->resourcesGetTotal());
812
  }
813
814
  public function shipsGetTotalById($ship_id) {
815
    return $this->unitList->unitsCountById($ship_id);
816
  }
817
818
  /**
819
   * Возвращает ёмкость переработчиков во флоте
820
   *
821
   * @param array $recycler_info
822
   *
823
   * @return int
824
   *
825
   * @version 41a6.81
826
   */
827
  public function shipsGetCapacityRecyclers(array $recycler_info) {
828
    $recyclers_incoming_capacity = 0;
829
    $fleet_data = $this->shipsGetArray();
830
    foreach($recycler_info as $recycler_id => $recycler_data) {
831
      $recyclers_incoming_capacity += $fleet_data[$recycler_id] * $recycler_data['capacity'];
832
    }
833
834
    return $recyclers_incoming_capacity;
835
  }
836
837
  /**
838
   * Restores fleet or resources to planet
839
   *
840
   * @param bool $start
841
   * @param int  $result
842
   *
843
   * @return int
844
   */
845
  // TODO - split to functions
846
  public function shipsLand($start = true, &$result = CACHE_NOTHING) {
847
    sn_db_transaction_check(true);
848
849
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
850
    if($this->isEmpty()) {
851
      return $result;
852
    }
853
854
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
855
856
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
857
    // TODO Проверить от многократного срабатывания !!!
858
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
859
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
860
861
    // Узнаем ИД владельца планеты.
862
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
863
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
864
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
865
    // Блокируем пользователя
866
    // TODO - вообще-то нам уже известен пользователь в МЛФ - так что можно просто передать его сюда
867
    $user = db_user_by_id($planet_arrival['id_owner'], true);
868
869
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
870
    // Флот, который возвращается на захваченную планету, пропадает
871
    // Ship landing is possible only to fleet owner's planet
872
    if($this->getPlayerOwnerId() == $planet_arrival['id_owner']) {
873
      $db_changeset = array();
874
875
      $fleet_array = $this->shipsGetArray();
876
      foreach($fleet_array as $ship_id => $ship_count) {
877
        if($ship_count) {
878
          $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
879
        }
880
      }
881
882
      // Adjusting ship amount on planet
883
      if(!empty($db_changeset)) {
884
        db_changeset_apply($db_changeset);
885
      }
886
887
      // Restoring resources to planet
888
      $this->resourcesUnload($start, $result);
889
    }
890
891
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
892
893
    $result = RestoreFleetToPlanet($this, $start, $result);
894
895
    $this->dbDelete();
896
897
    return $result;
898
  }
899
900
901
  // Resources access ***************************************************************************************************
902
903
  /**
904
   * Extracts resources value from db_row
905
   *
906
   * @param array $db_row
907
   *
908
   * @internal param Fleet $that
909
   * @version 41a6.81
910
   */
911
  protected function resourcesExtract(array &$db_row) {
912
    $this->resource_list = array(
913
      RES_METAL     => !empty($db_row['fleet_resource_metal']) ? floor($db_row['fleet_resource_metal']) : 0,
914
      RES_CRYSTAL   => !empty($db_row['fleet_resource_crystal']) ? floor($db_row['fleet_resource_crystal']) : 0,
915
      RES_DEUTERIUM => !empty($db_row['fleet_resource_deuterium']) ? floor($db_row['fleet_resource_deuterium']) : 0,
916
    );
917
  }
918
919
  protected function resourcesInject(array &$db_row) {
920
    $db_row['fleet_resource_metal'] = $this->resource_list[RES_METAL];
921
    $db_row['fleet_resource_crystal'] = $this->resource_list[RES_CRYSTAL];
922
    $db_row['fleet_resource_deuterium'] = $this->resource_list[RES_DEUTERIUM];
923
  }
924
925
  /**
926
   * Set current resource list from array of units
927
   *
928
   * @param array $resource_list
929
   */
930
  public function resourcesSet($resource_list) {
931
    if(!empty($this->propertiesAdjusted['resource_list'])) {
932
      throw new PropertyAccessException('Property "resource_list" already was adjusted so no SET is possible until dbSave in ' . get_called_class() . '::unitSetResourceList', ERR_ERROR);
933
    }
934
    $this->resourcesAdjust($resource_list, true);
935
  }
936
937
  /**
938
   * Updates fleet resource list with deltas
939
   *
940
   * @param $resource_delta_list
941
   */
942
  public function resourcesAdjust($resource_delta_list, $replace_value = false) {
943
    !is_array($resource_delta_list) ? $resource_delta_list = array() : false;
944
945
    foreach($resource_delta_list as $resource_id => $unit_delta) {
946
      if(!UnitResourceLoot::is_in_group($resource_id) || !($unit_delta = floor($unit_delta))) {
947
        // Not a resource or no resources - continuing
948
        continue;
949
      }
950
951
      if($replace_value) {
952
        $this->resource_list[$resource_id] = $unit_delta;
953
      } else {
954
        $this->resource_list[$resource_id] += $unit_delta;
955
        // Preparing changes
956
        $this->resource_delta[$resource_id] += $unit_delta;
957
        $this->propertiesAdjusted['resource_list'] = 1;
958
      }
959
960
      // Check for negative unit value
961
      if($this->resource_list[$resource_id] < 0) {
962
        // TODO
963
        throw new Exception('Resource ' . $resource_id . ' will become negative in ' . get_called_class() . '::unitAdjustResourceList', ERR_ERROR);
964
      }
965
    }
966
  }
967
968
  public function resourcesGetTotal() {
969
    return empty($this->resource_list) || !is_array($this->resource_list) ? 0 : array_sum($this->resource_list);
970
  }
971
972
  /**
973
   * @param array $rate
974
   *
975
   * @return float
976
   */
977
  public function resourcesGetTotalInMetal(array $rate) {
978
    return
979
      $this->resource_list[RES_METAL] * $rate[RES_METAL]
980
      + $this->resource_list[RES_CRYSTAL] * $rate[RES_CRYSTAL] / $rate[RES_METAL]
981
      + $this->resource_list[RES_DEUTERIUM] * $rate[RES_DEUTERIUM] / $rate[RES_METAL];
982
  }
983
984
  /**
985
   * Returns resource list in fleet
986
   */
987
  // TODO
988
  public function resourcesGetList() {
989
    return $this->resource_list;
990
  }
991
992
  public function resourcesReset() {
993
    $this->resourcesSet(array(
994
      RES_METAL     => 0,
995
      RES_CRYSTAL   => 0,
996
      RES_DEUTERIUM => 0,
997
    ));
998
  }
999
1000
  /**
1001
   * Restores fleet or resources to planet
1002
   *
1003
   * @param bool $start
1004
   * @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...
1005
   * @param int  $result
1006
   *
1007
   * @return int
1008
   */
1009
  public function resourcesUnload($start = true, &$result = CACHE_NOTHING) {
1010
    sn_db_transaction_check(true);
1011
1012
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
1013
    if(!$this->resourcesGetTotal()) {
1014
      return $result;
1015
    }
1016
1017
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
1018
1019
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
1020
    // TODO Проверить от многократного срабатывания !!!
1021
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
1022
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
1023
1024
1025
    // Узнаем ИД владельца планеты.
1026
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
1027
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
1028
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
1029
1030
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
1031
1032
    // Restoring resources to planet
1033
    if($this->resourcesGetTotal()) {
1034
      $fleet_resources = $this->resourcesGetList();
1035
      db_planet_set_by_id($planet_arrival['id'],
1036
        "`metal` = `metal` + '{$fleet_resources[RES_METAL]}', `crystal` = `crystal` + '{$fleet_resources[RES_CRYSTAL]}', `deuterium` = `deuterium` + '{$fleet_resources[RES_DEUTERIUM]}'");
1037
    }
1038
1039
    $this->resourcesReset();
1040
    $this->markReturned();
1041
1042
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
1043
1044
    return $result;
1045
  }
1046
1047
1048
  protected function isResource($unit_id) {
1049
    return UnitResourceLoot::is_in_group($unit_id);
1050
  }
1051
1052
  /**
1053
   * @param int $speed_percent
1054
   *
1055
   * @return array
1056
   */
1057
  protected function flt_travel_data($speed_percent = 10) {
1058
    $distance = $this->targetVector->distanceFromCoordinates($this->dbSourcePlanetRow);
1059
1060
    return $this->unitList->travelData($speed_percent, $distance, $this->dbOwnerRow);
1061
  }
1062
1063
1064
  /**
1065
   * @param array  $dbPlayerRow
1066
   * @param array  $dbPlanetRow
1067
   * @param Vector $targetVector
1068
   *
1069
   */
1070
  public function initDefaults($dbPlayerRow, $dbPlanetRow, $targetVector, $mission, $ships, $fleet_group_mr, $oldSpeedInTens) {
1071
    $objFleet5Player = new Player();
1072
    $objFleet5Player->dbRowParse($dbPlayerRow);
1073
    $this->setLocatedAt($objFleet5Player);
1074
1075
    $this->mission_type = $mission;
1076
1077
    $this->dbOwnerRow = $dbPlayerRow;
1078
1079
    $this->set_start_planet($dbPlanetRow);
1080
    $this->dbSourcePlanetRow = $dbPlanetRow;
1081
1082
    $this->setTargetFromVectorObject($targetVector);
1083
    $this->targetVector = $targetVector;
1084
1085
    $this->populateTargetPlanet();
1086
1087
    $this->unitsSetFromArray($ships);
1088
1089
    $this->_group_id = $fleet_group_mr;
1090
1091
    $this->oldSpeedInTens = $oldSpeedInTens;
1092
1093
    $this->fleetPage0Prepare();
1094
1095
  }
1096
1097
  protected function populateTargetPlanet() {
1098
    $targetPlanetCoords = $this->targetVector;
1099
    if($this->mission_type != MT_NONE) {
1100
      $this->restrictTargetTypeByMission();
1101
1102
      // TODO - Нельзя тут просто менять тип планеты или координат!
1103
      // If current planet type is not allowed on mission - switch planet type
1104
      if(empty($this->allowed_planet_types[$this->targetVector->type])) {
1105
        $targetPlanetCoords->type = reset($this->allowed_planet_types);
1106
      }
1107
    }
1108
1109
    $this->dbTargetRow = db_planet_by_vector_object($targetPlanetCoords);
1110
  }
1111
1112
  protected function restrictTargetTypeByMission() {
1113
    if($this->_mission_type == MT_MISSILE) {
1114
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1115
    } elseif($this->_mission_type == MT_COLONIZE || $this->_mission_type == MT_EXPLORE) {
1116
      // TODO - PT_NONE
1117
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1118
    } elseif($this->_mission_type == MT_RECYCLE) {
1119
      $this->allowed_planet_types = array(PT_DEBRIS => PT_DEBRIS);
1120
    } elseif($this->_mission_type == MT_DESTROY) {
1121
      $this->allowed_planet_types = array(PT_MOON => PT_MOON);
1122
    } else {
1123
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET, PT_MOON => PT_MOON);
1124
    }
1125
  }
1126
1127
  /**
1128
   */
1129
  public function fleetPage0Prepare() {
1130
    global $template_result;
1131
    $template_result += array(
1132
      'thisgalaxy'      => $this->dbSourcePlanetRow['galaxy'],
1133
      'thissystem'      => $this->dbSourcePlanetRow['system'],
1134
      'thisplanet'      => $this->dbSourcePlanetRow['planet'],
1135
      'thisplanet_type' => $this->dbSourcePlanetRow['planet_type'],
1136
1137
      'galaxy'         => $this->targetVector->galaxy,
1138
      'system'         => $this->targetVector->system,
1139
      'planet'         => $this->targetVector->planet,
1140
      'planet_type'    => $this->targetVector->type,
1141
      'target_mission' => $this->_mission_type,
1142
      'MISSION_NAME'   => $this->_mission_type ? classLocale::$lang['type_mission'][$this->_mission_type] : '',
1143
1144
      'MT_COLONIZE' => MT_COLONIZE,
1145
    );
1146
1147
//    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...
1148
  }
1149
1150
1151
  public function restrictToKnownSpace() {
1152
    if(!$this->targetVector->isInKnownSpace()) {
1153
      throw new Exception('FLIGHT_VECTOR_BEYOND_SYSTEM', FLIGHT_VECTOR_BEYOND_SYSTEM);
1154
    }
1155
  }
1156
1157
  public function restrictToTypePlanet($errorCode) {
1158
    if($this->targetVector->type != PT_PLANET) {
1159
      throw new Exception($errorCode, $errorCode);
1160
    }
1161
  }
1162
1163
  public function restrictToNoMissiles() {
1164
    $missilesAttack = $this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERPLANET);
1165
    $missilesDefense = $this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERCEPTOR);
1166
    if($missilesAttack > 0 || $missilesDefense > 0) {
1167
      throw new Exception('FLIGHT_SHIPS_NO_MISSILES', FLIGHT_SHIPS_NO_MISSILES);
1168
    }
1169
  }
1170
1171
  public function restrictToTargetOwn() {
1172
    if($this->dbTargetRow['id'] != $this->getPlayerOwnerId()) {
1173
      throw new Exception('FLIGHT_VECTOR_ONLY_OWN', FLIGHT_VECTOR_ONLY_OWN);
1174
    }
1175
  }
1176
1177
  public function restrictToTargetOther() {
1178
    if($this->dbTargetRow['id'] == $this->getPlayerOwnerId()) {
1179
      throw new Exception('FLIGHT_VECTOR_ONLY_OTHER', FLIGHT_VECTOR_ONLY_OTHER);
1180
    }
1181
  }
1182
1183
  public function restrictToNotOnlySpies() {
1184
    if($this->unitList->unitsCountById(SHIP_SPY) == $this->shipsGetTotal()) {
1185
      throw new Exception('FLIGHT_SHIPS_NOT_ONLY_SPIES', FLIGHT_SHIPS_NOT_ONLY_SPIES);
1186
    }
1187
  }
1188
1189
  protected function restrictToUniverse() {
1190
    if(!$this->targetVector->isInUniverse()) {
1191
      throw new Exception('FLIGHT_VECTOR_BEYOND_UNIVERSE', FLIGHT_VECTOR_BEYOND_UNIVERSE);
1192
    }
1193
  }
1194
1195
  protected function restrictToMovable() {
1196
    if(!$this->unitList->unitsIsAllMovable($this->dbOwnerRow)) {
1197
      throw new Exception('FLIGHT_SHIPS_UNMOVABLE', FLIGHT_SHIPS_UNMOVABLE);
1198
    }
1199
  }
1200
1201
  protected function restrictToFleetUnits() {
1202
    if(!$this->unitList->unitsInGroup(sn_get_groups(array('fleet', 'missile')))) {
1203
      throw new Exception('FLIGHT_SHIPS_UNIT_WRONG', FLIGHT_SHIPS_UNIT_WRONG);
1204
    }
1205
  }
1206
1207
  protected function restrictToColonizer() {
1208
    // Colonization fleet should have at least one colonizer
1209
    if(!$this->unitList->unitsCountById(SHIP_COLONIZER) <= 0) {
1210
      throw new Exception('FLIGHT_SHIPS_NO_COLONIZER', FLIGHT_SHIPS_NO_COLONIZER);
1211
    }
1212
  }
1213
1214
  protected function restrictToTargetExists() {
1215
    if(empty($this->dbTargetRow) || empty($this->dbTargetRow['id'])) {
1216
      throw new Exception('FLIGHT_VECTOR_NO_TARGET', FLIGHT_VECTOR_NO_TARGET);
1217
    }
1218
  }
1219
1220
1221 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...
1222
    // Is it exploration - fleet sent beyond of system?
1223
    if($this->targetVector->isInKnownSpace()) {
1224
      // No exploration beyond this point
1225
      unset($this->allowed_missions[MT_EXPLORE]);
1226
1227
      $this->restrictToKnownSpace();
1228
1229
      return;
1230
    }
1231
    $this->restrictToNotOnlySpies();
1232
    $this->restrictToNoMissiles();
1233
1234
    $this->allowed_missions = array(MT_EXPLORE => MT_EXPLORE,);
1235
1236
    throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1237
  }
1238
1239 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...
1240
    // Is it colonization - fleet sent to empty place?
1241
    if(!empty($this->dbTargetRow)) {
1242
      // No colonization beyond this point
1243
      unset($this->allowed_missions[MT_COLONIZE]);
1244
1245
      $this->restrictToTargetExists();
1246
1247
      return;
1248
    }
1249
    // Only planet can be destination for colonization
1250
    $this->restrictToTypePlanet(FLIGHT_MISSION_COLONIZE_NOT_PLANET);
1251
    $this->restrictToColonizer();
1252
    $this->restrictToNoMissiles();
1253
1254
    $this->allowed_missions = array(MT_COLONIZE => MT_COLONIZE,);
1255
1256
    throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1257
  }
1258
1259
  protected function restrictNotDebrisOrMissionRecycle() {
1260
    if($this->targetVector->type != PT_DEBRIS) {
1261
      // No recycling beyond this point
1262
      unset($this->allowed_missions[MT_RECYCLE]);
1263
1264
      return;
1265
    }
1266
1267
    $this->restrictToNoMissiles();
1268
1269
    // restrict to recyclers
1270
    $recyclers = 0;
1271
    foreach(sn_get_groups('flt_recyclers') as $recycler_id) {
1272
      $recyclers += $this->unitList->unitsCountById($recycler_id);
1273
    }
1274
1275
    if($recyclers <= 0) {
1276
      throw new Exception('FLIGHT_SHIPS_NO_RECYCLERS', FLIGHT_SHIPS_NO_RECYCLERS);
1277
    }
1278
1279
    $this->allowed_missions = array(MT_RECYCLE => MT_RECYCLE,);
1280
1281
    throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1282
  }
1283
1284
  protected function restrictMissionMissile() {
1285
    $missilesAttack = $this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERPLANET);
1286
    if($missilesAttack <= 0) {
1287
      // No missile attack beyond this point
1288
      unset($this->allowed_missions[MT_MISSILE]);
1289
1290
      return;
1291
    }
1292
1293
    if($missilesAttack != $this->shipsGetTotal()) {
1294
      throw new Exception('FLIGHT_SHIPS_ONLY_MISSILES', FLIGHT_SHIPS_ONLY_MISSILES);
1295
    }
1296
1297
    $this->restrictToTypePlanet(FLIGHT_MISSION_MISSILE_ONLY_PLANET);
1298
    $this->restrictToTargetOther();
1299
1300
    $this->allowed_missions = array(MT_MISSILE => MT_MISSILE,);
1301
    throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1302
  }
1303
1304 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...
1305
    if($this->unitList->unitsCountById(SHIP_SPY) != $this->shipsGetTotal()) {
1306
//      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...
1307
      unset($this->allowed_missions[MT_SPY]);
1308
1309
      $this->restrictToNotOnlySpies();
1310
1311
      return;
1312
    }
1313
1314
    $this->allowed_missions = array(MT_SPY => MT_SPY,);
1315
    throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1316
  }
1317
1318
  protected function restrictMissionDestroy() {
1319
    // If target vector is not Moon - then it can't be Destroy mission
1320
    // If no Reapers (i.e. Death Star) in fleet - then mission Moon Destroy is unaccessible
1321
    if($this->targetVector->type != PT_MOON || $this->unitList->unitsCountById(SHIP_HUGE_DEATH_STAR) <= 0) {
1322
      unset($this->allowed_missions[MT_DESTROY]);
1323
    }
1324
  }
1325
1326
  protected function restrictMissionACS() {
1327
    // If no ACS group is shown - then it can't be an ACS attack
1328
    if(empty($this->_group_id)) {
1329
      unset($this->allowed_missions[MT_ACS]);
1330
    }
1331
  }
1332
1333
  /** @throws Exception */
1334
  protected function restrictFriendOrFoe() {
1335
    // Checking target owner
1336 View Code Duplication
    if($this->dbTargetRow['id'] == $this->getPlayerOwnerId()) {
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...
1337
      // Spying can't be done on owner's planet/moon
1338
      unset($this->allowed_missions[MT_SPY]);
1339
      // Attack can't be done on owner's planet/moon
1340
      unset($this->allowed_missions[MT_ATTACK]);
1341
      // ACS can't be done on owner's planet/moon
1342
      unset($this->allowed_missions[MT_ACS]);
1343
      // Destroy can't be done on owner's moon
1344
      unset($this->allowed_missions[MT_DESTROY]);
1345
1346
      $this->restrictToNoMissiles();
1347
1348
      // MT_RELOCATE
1349
      // No checks
1350
      // TODO - check captain
1351
1352
      // MT_HOLD
1353
      // TODO - Check for Allies Deposit for HOLD
1354
1355
      // MT_TRANSPORT
1356
1357
    } else {
1358
      // Relocate can be done only on owner's planet/moon
1359
      unset($this->allowed_missions[MT_RELOCATE]);
1360
1361
      // TODO - check for moratorium
1362
1363
      // MT_HOLD
1364
      // TODO - Check for Allies Deposit for HOLD
1365
      // TODO - Noob protection for HOLD depends on server settings
1366
1367
      // MT_SPY
1368
      $this->restrictToNotOnlySpiesOrMissionSpy();
1369
1370
      // TODO - check noob protection
1371
1372
      // TODO - check bashing
1373
1374
      // No missions except MT_MISSILE should have any missiles in fleet
1375
      $this->restrictMissionMissile();
1376
      $this->restrictToNoMissiles();
1377
      // Beyond this point no mission can have a missile in fleet
1378
1379
      // MT_DESTROY
1380
      $this->restrictMissionDestroy();
1381
1382
      // MT_ACS
1383
      $this->restrictMissionACS();
1384
1385
      // MT_ATTACK - no checks
1386
1387
      // MT_TRANSPORT - no checks
1388
    }
1389
  }
1390
1391
  protected function restrictToNotSource() {
1392
    if($this->targetVector->isEqualToPlanet($this->dbSourcePlanetRow)) {
1393
      throw new Exception('FLIGHT_VECTOR_SAME_SOURCE', FLIGHT_VECTOR_SAME_SOURCE);
1394
    }
1395
  }
1396
1397
  protected function restrictToNonVacationSender() {
1398
    if(!empty($this->dbOwnerRow['vacation']) && $this->dbOwnerRow['vacation'] >= SN_TIME_NOW) {
1399
      throw new Exception('FLIGHT_PLAYER_VACATION_OWN', FLIGHT_PLAYER_VACATION_OWN);
1400
    }
1401
  }
1402
1403
  protected function restrictToValidSpeedPercentOld() {
1404
    $speed_possible = array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
1405
    if(!in_array($this->oldSpeedInTens, $speed_possible)) {
1406
      throw new Exception('FLIGHT_FLEET_SPEED_WRONG', FLIGHT_FLEET_SPEED_WRONG);
1407
    }
1408
1409
  }
1410
1411
  protected function restrict2ToAllowedMissions() {
1412
    if(empty($this->allowed_missions[$this->_mission_type])) {
1413
      throw new Exception('FLIGHT_MISSION_IMPOSSIBLE', FLIGHT_MISSION_IMPOSSIBLE);
1414
    }
1415
  }
1416
1417
  protected function restrict2ToAllowedPlanetTypes() {
1418
    if(empty($this->allowed_planet_types[$this->targetVector->type])) {
1419
      throw new Exception('FLIGHT_MISSION_IMPOSSIBLE', FLIGHT_MISSION_IMPOSSIBLE);
1420
    }
1421
  }
1422
1423
  protected function restrict2ToMaxFleets() {
1424
    if(FleetList::fleet_count_flying($this->getPlayerOwnerId()) >= GetMaxFleets($this->dbOwnerRow)) {
1425
      throw new Exception('FLIGHT_FLEET_NO_SLOTS', FLIGHT_FLEET_NO_SLOTS);
1426
    }
1427
  }
1428
1429
  protected function restrict2ToEnoughShips() {
1430
    if(!$this->unitList->shipsIsEnoughOnPlanet($this->dbSourcePlanetRow)) {
1431
      throw new Exception('FLIGHT_SHIPS_NOT_ENOUGH', FLIGHT_SHIPS_NOT_ENOUGH);
1432
    }
1433
  }
1434
1435
  protected function restrict2ToEnoughCapacity($fleetCapacity, $fleetConsumption) {
1436
    if(floor($fleetCapacity) < ceil(array_sum($this->resource_list) + $fleetConsumption)) {
1437
      throw new Exception('FLIGHT_FLEET_OVERLOAD', FLIGHT_FLEET_OVERLOAD);
1438
    }
1439
  }
1440
1441
  protected function restrict2ByResources($fleetConsumption) {
1442
    $fleetResources = $this->resource_list;
1443
    $fleetResources[RES_DEUTERIUM] = ceil($fleetResources[RES_DEUTERIUM] + $fleetConsumption);
1444
    foreach($fleetResources as $resourceId => $resourceAmount) {
1445
      if($fleetResources[$resourceId] < 0) {
1446
        throw new Exception('FLIGHT_RESOURCES_NEGATIVE', FLIGHT_RESOURCES_NEGATIVE);
1447
      }
1448
1449
      if(mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, $resourceId) < ceil($fleetResources[$resourceId])) {
1450
        if($resourceId == RES_DEUTERIUM) {
1451
          throw new Exception('FLIGHT_RESOURCES_FUEL_NOT_ENOUGH', FLIGHT_RESOURCES_FUEL_NOT_ENOUGH);
1452
        } else {
1453
          throw new Exception('FLIGHT_RESOURCES_NOT_ENOUGH', FLIGHT_RESOURCES_NOT_ENOUGH);
1454
        }
1455
      }
1456
    }
1457
  }
1458
1459
  /**
1460
   * Restricts mission availability internally w/o DB access
1461
   *
1462
   * @throws Exception
1463
   */
1464
  public function restrictMission() {
1465
    // Only "cheap" checks that didn't require to query DB
1466
1467
1468
    // Check for valid percent speed value
1469
    $this->restrictToValidSpeedPercentOld();
1470
1471
    // Player in Vacation can't send fleets
1472
    $this->restrictToNonVacationSender();
1473
1474
    // Fleet source and destination can't be the same
1475
    $this->restrictToNotSource();
1476
1477
    // No mission could fly beyond Universe - i.e. with wrong Galaxy and/or System coordinates
1478
    $this->restrictToUniverse();
1479
1480
    // Only ships and missiles can be sent to mission
1481
    $this->restrictToFleetUnits();
1482
    // Only units with main engines (speed >=0) can fly - no other units like satellites
1483
    $this->restrictToMovable();
1484
1485
    // No missions except MT_EXPLORE could target coordinates beyond known system
1486
    $this->restrictKnownSpaceOrMissionExplore();
1487
    // Beyond this point all mission address only known space
1488
1489
    // No missions except MT_COLONIZE could target empty coordinates
1490
    $this->restrictTargetExistsOrMissionColonize();
1491
    // Beyond this point all mission address only existing planets/moons
1492
1493
    // No missions except MT_RECYCLE could target debris
1494
    $this->restrictNotDebrisOrMissionRecycle();
1495
    // Beyond this point targets can be only PT_PLANET or PT_MOON
1496
1497
    // TODO - later then
1498
    $this->restrictFriendOrFoe();
1499
  }
1500
1501
1502
  protected function printErrorIfNoShips() {
1503
    if($this->unitList->unitsCount() <= 0) {
1504
      message(classLocale::$lang['fl_err_no_ships'], classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 5);
1505
    }
1506
  }
1507
1508
  /**
1509
   * @param array $template_result
1510
   *
1511
   * @throws Exception
1512
   */
1513
  protected function renderFleet(&$template_result) {
1514
    $this->printErrorIfNoShips();
1515
1516
    $tplShips = $this->unitList->unitsRender();
1517
    $template_result['.']['fleets'][] = array(
1518
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$this->dbSourcePlanetRow['planet_type']],
1519
      'START_COORDS'       => uni_render_coordinates($this->dbSourcePlanetRow),
1520
      'START_NAME'         => $this->dbSourcePlanetRow['name'],
1521
      'END_TYPE_TEXT_SH'   =>
1522
        !empty($this->targetVector->type)
1523
          ? classLocale::$lang['sys_planet_type_sh'][$this->targetVector->type]
1524
          : '',
1525
      'END_COORDS'         => uniRenderVector($this->targetVector),
1526
      'END_NAME'           => !empty($this->dbTargetRow['name']) ? $this->dbTargetRow['name'] : '',
1527
      '.'                  => array(
1528
        'ships' => $tplShips,
1529
      ),
1530
    );
1531
  }
1532
1533
  /**
1534
   * @param array $template_result
1535
   *
1536
   * @return array
1537
   */
1538
  protected function renderAllowedMissions(&$template_result) {
1539
    ksort($this->allowed_missions);
1540
    // If mission is not set - setting first mission from allowed
1541
    if(empty($this->_mission_type) && is_array($this->allowed_missions)) {
1542
      $this->_mission_type = reset($this->allowed_missions);
1543
    }
1544
    foreach($this->allowed_missions as $key => $value) {
1545
      $template_result['.']['missions'][] = array(
1546
        'ID'   => $key,
1547
        'NAME' => classLocale::$lang['type_mission'][$key],
1548
      );
1549
    };
1550
  }
1551
1552
  /**
1553
   * @param $template_result
1554
   */
1555
  protected function renderDuration(&$template_result, $max_duration) {
1556
    if($max_duration) {
1557
      $config_game_speed_expedition = ($this->_mission_type == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1);
1558
      for($i = 1; $i <= $max_duration; $i++) {
1559
        $template_result['.']['duration'][] = array(
1560
          'ID'   => $i,
1561
          'TIME' => pretty_time(ceil($i * 3600 / $config_game_speed_expedition)),
1562
        );
1563
      }
1564
    }
1565
  }
1566
1567
  /**
1568
   * @param array $planetResources
1569
   * @param array &$template_result
1570
   */
1571
  protected function renderPlanetResources(&$planetResources, &$template_result) {
1572
    // TODO - REDO to resource_id
1573
    $i = 0;
1574
    foreach($planetResources as $resource_id => $resource_amount) {
1575
      $template_result['.']['resources'][] = array(
1576
        'ID'        => $i++, // $resource_id,
1577
        'ON_PLANET' => $resource_amount,
1578
        'TEXT'      => pretty_number($resource_amount),
1579
        'NAME'      => classLocale::$lang['tech'][$resource_id],
1580
      );
1581
    }
1582
  }
1583
1584
  /**
1585
   * @param $template_result
1586
   */
1587
  protected function renderAllowedPlanetTypes(&$template_result) {
1588
    foreach($this->allowed_planet_types as $possible_planet_type_id) {
1589
      $template_result['.']['possible_planet_type_id'][] = array(
1590
        'ID'         => $possible_planet_type_id,
1591
        'NAME'       => classLocale::$lang['sys_planet_type'][$possible_planet_type_id],
1592
        'NAME_SHORT' => classLocale::$lang['sys_planet_type_sh'][$possible_planet_type_id],
1593
      );
1594
    }
1595
  }
1596
1597
  protected function renderFleet1TargetSelect(&$shortcut) {
1598
    global $note_priority_classes;
1599
1600
    $name = !empty($shortcut['title']) ? $shortcut['title'] : $shortcut['name'];
1601
1602
    $result = array(
1603
      'NAME'       => $name,
1604
      'GALAXY'     => $shortcut['galaxy'],
1605
      'SYSTEM'     => $shortcut['system'],
1606
      'PLANET'     => $shortcut['planet'],
1607
      'TYPE'       => $shortcut['planet_type'],
1608
      'TYPE_PRINT' => classLocale::$lang['fl_shrtcup'][$shortcut['planet_type']],
1609
    );
1610
1611
    if(isset($shortcut['priority'])) {
1612
      $result += array(
1613
        'PRIORITY'       => $shortcut['priority'],
1614
        'PRIORITY_CLASS' => $note_priority_classes[$shortcut['priority']],
1615
      );
1616
    }
1617
1618
    if(isset($shortcut['id'])) {
1619
      $result += array(
1620
        'ID' => $shortcut['id'],
1621
      );
1622
    }
1623
1624
    return $result;
1625
  }
1626
1627
  /**
1628
   * @param $template_result
1629
   */
1630
  protected function renderFleetShortcuts(&$template_result) {
1631
    // Building list of shortcuts
1632
    $query = db_note_list_select_by_owner_and_planet($this->dbOwnerRow);
1633
    while($row = db_fetch($query)) {
1634
      $template_result['.']['shortcut'][] = $this->renderFleet1TargetSelect($row);
1635
    }
1636
  }
1637
1638
  /**
1639
   * Building list of own planets & moons
1640
   *
1641
   * @param $template_result
1642
   */
1643
  protected function renderOwnPlanets(&$template_result) {
1644
    $colonies = db_planet_list_sorted($this->dbOwnerRow);
1645
    if(count($colonies) <= 1) {
1646
      return;
1647
    }
1648
1649
    foreach($colonies as $row) {
1650
      if($row['id'] == $this->dbSourcePlanetRow['id']) {
1651
        continue;
1652
      }
1653
1654
      $template_result['.']['colonies'][] = $this->renderFleet1TargetSelect($row);
1655
    }
1656
  }
1657
1658
  /**
1659
   * @param $template_result
1660
   */
1661
  protected function renderACSList(&$template_result) {
1662
    $query = db_acs_get_list();
1663
    while($row = db_fetch($query)) {
1664
      $members = explode(',', $row['eingeladen']);
1665
      foreach($members as $a => $b) {
1666
        if($b == $this->dbOwnerRow['id']) {
1667
          $template_result['.']['acss'][] = $this->renderFleet1TargetSelect($row);
1668
        }
1669
      }
1670
    }
1671
  }
1672
1673
  /**
1674
   * @param $template_result
1675
   */
1676
  protected function renderShipSortOptions(&$template_result) {
1677
    foreach(classLocale::$lang['player_option_fleet_ship_sort'] as $sort_id => $sort_text) {
1678
      $template_result['.']['ship_sort_list'][] = array(
1679
        'VALUE' => $sort_id,
1680
        'TEXT'  => $sort_text,
1681
      );
1682
    }
1683
    $template_result += array(
1684
      'FLEET_SHIP_SORT'         => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT],
1685
      'FLEET_SHIP_SORT_INVERSE' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE],
1686
    );
1687
  }
1688
1689
  /**
1690
   */
1691
  public function fleetPage0() {
1692
    global $template_result;
1693
1694
    lng_include('overview');
1695
1696
    if(empty($this->dbSourcePlanetRow)) {
1697
      message(classLocale::$lang['fl_noplanetrow'], classLocale::$lang['fl_error']);
1698
    }
1699
1700
    // TODO - redo to unitlist render/unit render
1701
    $this->renderAvailableShips($template_result, $this->dbOwnerRow, $this->dbSourcePlanetRow);
1702
1703
    $this->renderShipSortOptions($template_result);
1704
1705
    /**
1706
     * @var Player $playerOwner
1707
     */
1708
    $playerOwner = $this->getLocatedAt();
1709
1710
    $template_result += array(
1711
      'FLYING_FLEETS'      => $playerOwner->fleetsFlying(),
1712
      'MAX_FLEETS'         => $playerOwner->fleetsMax(),
1713
      'FREE_FLEETS'        => $playerOwner->fleetsMax() - $playerOwner->fleetsFlying(),
1714
      'FLYING_EXPEDITIONS' => $playerOwner->expeditionsFlying(),
1715
      'MAX_EXPEDITIONS'    => $playerOwner->expeditionsMax(),
1716
      'FREE_EXPEDITIONS'   => $playerOwner->expeditionsMax() - $playerOwner->expeditionsFlying(),
1717
      'COLONIES_CURRENT'   => $playerOwner->coloniesCurrent(),
1718
      'COLONIES_MAX'       => $playerOwner->coloniesMax(),
1719
1720
      'TYPE_NAME' => classLocale::$lang['fl_planettype'][$this->targetVector->type],
1721
1722
      'speed_factor' => flt_server_flight_speed_multiplier(),
1723
1724
      'PLANET_RESOURCES' => pretty_number($this->dbSourcePlanetRow['metal'] + $this->dbSourcePlanetRow['crystal'] + $this->dbSourcePlanetRow['deuterium']),
1725
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1726
1727
      'PLAYER_OPTION_FLEET_SHIP_SELECT_OLD'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SELECT_OLD],
1728
      'PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED],
1729
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY'    => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY],
1730
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION],
1731
    );
1732
1733
    $template = gettemplate('fleet0', true);
1734
    $template->assign_recursive($template_result);
1735
    display($template, classLocale::$lang['fl_title']);
1736
  }
1737
1738
  public function fleetPage1() {
1739
    global $template_result;
1740
1741
    $this->renderFleet($template_result);
1742
1743
    $this->renderAllowedPlanetTypes($template_result);
1744
1745
    $this->renderOwnPlanets($template_result);
1746
1747
    $this->renderFleetShortcuts($template_result);
1748
1749
    $this->renderACSList($template_result);
1750
1751
    $template_result += array(
1752
      'speed_factor' => flt_server_flight_speed_multiplier(),
1753
1754
      'fleet_speed'    => flt_fleet_speed($this->dbOwnerRow, $this->shipsGetArray()),
1755
      'fleet_capacity' => $this->shipsGetCapacity(),
1756
1757
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1758
1759
      'PAGE_HINT' => classLocale::$lang['fl_page1_hint'],
1760
    );
1761
1762
    $template = gettemplate('fleet1', true);
1763
    $template->assign_recursive($template_result);
1764
    display($template, classLocale::$lang['fl_title']);
1765
  }
1766
1767
  public function fleetPage2() {
1768
    global $template_result;
1769
1770
    try {
1771
      $this->restrictMission();
1772
    } catch(Exception $e) {
1773
      // TODO - MESSAGE BOX
1774 View Code Duplication
      if($e->getCode() != FLIGHT_ALLOWED) {
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...
1775
        pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
1776
      } else {
1777
        pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1778
      }
1779
    }
1780
1781
    $this->renderAllowedMissions($template_result);
1782
    $this->renderFleet($template_result);
1783
1784
    $max_duration = $this->_mission_type == MT_EXPLORE ? get_player_max_expedition_duration($this->dbOwnerRow) :
1785
      (isset($this->allowed_missions[MT_HOLD]) ? 12 : 0);
1786
    $this->renderDuration($template_result, $max_duration);
1787
1788
    $travel_data = $this->flt_travel_data($this->oldSpeedInTens);
1789
1790
    $sn_group_resources = sn_get_groups('resources_loot');
1791
    $planetResources = array();
1792
    foreach($sn_group_resources as $resource_id) {
1793
      $planetResources[$resource_id] = floor(mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, $resource_id) - ($resource_id == RES_DEUTERIUM ? $travel_data['consumption'] : 0));
1794
    }
1795
    $this->renderPlanetResources($planetResources, $template_result);
1796
1797
    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) {
1798
      $template_result += array(
1799
        'CAPTAIN_ID'     => $captain['unit_id'],
1800
        'CAPTAIN_LEVEL'  => $captain['captain_level'],
1801
        'CAPTAIN_SHIELD' => $captain['captain_shield'],
1802
        'CAPTAIN_ARMOR'  => $captain['captain_armor'],
1803
        'CAPTAIN_ATTACK' => $captain['captain_attack'],
1804
      );
1805
    }
1806
1807
    $template_result += array(
1808
      'planet_metal'     => $planetResources[RES_METAL],
1809
      'planet_crystal'   => $planetResources[RES_CRYSTAL],
1810
      'planet_deuterium' => $planetResources[RES_DEUTERIUM],
1811
1812
      'fleet_capacity' => $this->shipsGetCapacity() - $travel_data['consumption'],
1813
      'speed'          => $this->oldSpeedInTens,
1814
      'fleet_group'    => $this->_group_id,
1815
1816
      'MAX_DURATION'          => $max_duration,
1817
1818
      // 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...
1819
//      'IS_TRANSPORT_MISSIONS' => !empty($this->allowed_missions[$this->_mission_type]['transport']),
1820
      'IS_TRANSPORT_MISSIONS' => true,
1821
1822
      'PLAYER_COLONIES_CURRENT' => get_player_current_colonies($this->dbOwnerRow),
1823
      'PLAYER_COLONIES_MAX'     => get_player_max_colonies($this->dbOwnerRow),
1824
    );
1825
1826
    $template = gettemplate('fleet2', true);
1827
    $template->assign_recursive($template_result);
1828
    display($template, classLocale::$lang['fl_title']);
1829
  }
1830
1831
1832
  public function restrict2MissionTransportWithResources($fleetResources) {
1833
    if($this->_mission_type != MT_TRANSPORT) {
1834
      return;
1835
    }
1836
1837
    if(array_sum($fleetResources) <= 0) {
1838
      throw new Exception('FLIGHT_RESOURCES_EMPTY', FLIGHT_RESOURCES_EMPTY);
1839
    }
1840
  }
1841
1842
  protected function restrict2MissionExploreAvailable() {
1843
    if($this->_mission_type != MT_EXPLORE) {
1844
      return;
1845
    }
1846
1847
    if(($expeditionsMax = get_player_max_expeditons($this->dbOwnerRow)) <= 0) {
1848
      throw new Exception('FLIGHT_MISSION_EXPLORE_NO_ASTROTECH', FLIGHT_MISSION_EXPLORE_NO_ASTROTECH);
1849
    }
1850
    if(FleetList::fleet_count_flying($this->getPlayerOwnerId(), MT_EXPLORE) >= $expeditionsMax) {
1851
      throw new Exception('FLIGHT_MISSION_EXPLORE_NO_SLOTS', FLIGHT_MISSION_EXPLORE_NO_SLOTS);
1852
    }
1853
1854
    $this->restrictToNotOnlySpies();
1855
    $this->restrictToNoMissiles();
1856
1857
    throw new Exception('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1858
  }
1859
1860
1861
  public function fleetPage3($time_to_travel) {
1862
    global $target_mission, $fleetarray, $planetrow;
1863
    global $galaxy, $system, $planet, $TargetPlanet, $consumption, $template_result;
1864
    global $errorlist, $planet_type, $MaxExpeditions, $FlyingExpeditions;
1865
    global $speed_percent, $distance, $fleet_speed, $user, $debug;
1866
1867
    $classLocale = classLocale::$lang;
1868
1869
    sn_db_transaction_start();
1870
1871
    db_user_lock_with_target_owner($this->dbOwnerRow, $this->dbTargetRow);
1872
1873
    $this->dbOwnerRow = db_user_by_id($this->dbOwnerRow['id'], true);
0 ignored issues
show
Documentation Bug introduced by
It seems like db_user_by_id($this->dbOwnerRow['id'], true) can also be of type false. However, the property $dbOwnerRow is declared as type array. Maybe add an additional type check?

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1874
    $this->dbSourcePlanetRow = db_planet_by_id($this->dbSourcePlanetRow['id'], true);
1875
    if(!empty($this->dbTargetRow['id'])) {
1876
      $this->dbTargetRow = db_planet_by_id($this->dbTargetRow['id'], true);
1877
    }
1878
    if(!empty($this->dbTargetRow['id_owner'])) {
1879
      $this->dbTargetOwnerRow = db_planet_by_id($this->dbTargetRow['id_owner'], true);
1880
    }
1881
1882
    $this->resource_list = array(
1883
      RES_METAL     => max(0, floor(sys_get_param_float('resource0'))),
1884
      RES_CRYSTAL   => max(0, floor(sys_get_param_float('resource1'))),
1885
      RES_DEUTERIUM => max(0, floor(sys_get_param_float('resource2'))),
1886
    );
1887
1888
    $checklist = sn_get_groups('mission_checks');
1889
1890
    $this->travelData = $this->flt_travel_data($this->oldSpeedInTens);
1891
1892
    try {
1893
1894
      $this->checkMissionRestrictions($checklist);
1895
1896
1897
      // Do the restrictMission checks
1898
1899
      // TODO - Кое-какие проверки дают FLIGHT_ALLOWED - ЧТО НЕПРАВДА В ДАННОМ СЛУЧАЕ!!!
1900
      // На странице 1 некоторые проверки ДОЛЖНЫ БЫТЬ опущены - иначе будет некрасиво
1901
      // А вот здесь надо проверять много дополнительной хуйни
1902
      try {
1903
        $this->restrictToNonVacationSender();
1904
1905
        $this->restrictToNotSource();
1906
1907
        // No mission could fly beyond Universe - i.e. with wrong Galaxy and/or System coordinates
1908
        $this->restrictToUniverse();
1909
1910
        // Only ships and missiles can be sent to mission
1911
        $this->restrictToFleetUnits();
1912
        // Only units with main engines (speed >=0) can fly - no other units like satellites
1913
        $this->restrictToMovable();
1914
1915
        // No missions except MT_EXPLORE could target coordinates beyond known system
1916
        $this->restrictKnownSpaceOrMissionExplore();
1917
        // Beyond this point all mission address only known space
1918
1919
        // No missions except MT_COLONIZE could target empty coordinates
1920
        $this->restrictTargetExistsOrMissionColonize();
1921
        // Beyond this point all mission address only existing planets/moons
1922
1923
        // No missions except MT_RECYCLE could target debris
1924
        $this->restrictNotDebrisOrMissionRecycle();
1925
        // Beyond this point targets can be only PT_PLANET or PT_MOON
1926
1927
1928
        // TODO  - ALL OF THE ABOVE!
1929
        $this->restrictMission();
1930
      } catch(Exception $e) {
1931
        // If mission is restricted - rethrow exception
1932
        if($e->getCode() != FLIGHT_ALLOWED) {
1933
          throw new Exception($e->getMessage(), $e->getCode());
1934
        }
1935
      }
1936
1937
      // TODO - later then
1938
1939
      // 2nd level restrictions
1940
      // Still cheap
1941
      $this->restrict2ToAllowedMissions();
1942
      $this->restrict2ToAllowedPlanetTypes();
1943
1944
      // More expensive checks
1945
      $this->restrict2ToMaxFleets();
1946
      $this->restrict2ToEnoughShips();
1947
1948
1949
      $travelData = $this->flt_travel_data($this->oldSpeedInTens);
1950
      $fleetCapacity = $travelData['capacity'];
1951
      $fleetConsumption = $travelData['consumption'];
1952
      /*
1953
        fleet_speed
1954
        distance
1955
        duration
1956
        consumption
1957
        capacity
1958
        hold                   = capacity - consumption,
1959
        transport_effectivness = consumption ? capacity / consumption : 0,
1960
       */
1961
      $this->restrict2ToEnoughCapacity($fleetCapacity, $fleetConsumption);
1962
      $this->restrict2ByResources($fleetConsumption);
1963
1964
1965
      // TODO - REWRITE TO LEVEL 2
1966
      $this->restrict2MissionExploreAvailable();
1967
      $this->restrictTargetExistsOrMissionColonize();
1968
      $this->restrictNotDebrisOrMissionRecycle();
1969
      // TODO - START $this->restrictFriendOrFoe();
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
1970 View Code Duplication
      if($this->dbTargetRow['id'] == $this->getPlayerOwnerId()) {
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...
1971
        // Spying can't be done on owner's planet/moon
1972
        unset($this->allowed_missions[MT_SPY]);
1973
        // Attack can't be done on owner's planet/moon
1974
        unset($this->allowed_missions[MT_ATTACK]);
1975
        // ACS can't be done on owner's planet/moon
1976
        unset($this->allowed_missions[MT_ACS]);
1977
        // Destroy can't be done on owner's moon
1978
        unset($this->allowed_missions[MT_DESTROY]);
1979
1980
        $this->restrictToNoMissiles();
1981
1982
        // MT_RELOCATE
1983
        // No checks
1984
        // TODO - check captain
1985
1986
        // MT_HOLD
1987
        // TODO - Check for Allies Deposit for HOLD
1988
1989
        // MT_TRANSPORT
1990
1991
      } else {
1992
        // Relocate can be done only on owner's planet/moon
1993
        unset($this->allowed_missions[MT_RELOCATE]);
1994
1995
        // TODO - check for moratorium
1996
1997
        // MT_HOLD
1998
        // TODO - Check for Allies Deposit for HOLD
1999
        // TODO - Noob protection for HOLD depends on server settings
2000
2001
        // MT_SPY
2002
        $this->restrictToNotOnlySpiesOrMissionSpy();
2003
2004
        // TODO - check noob protection
2005
2006
        // TODO - check bashing
2007
2008
        // No missions except MT_MISSILE should have any missiles in fleet
2009
        $this->restrictMissionMissile();
2010
        $this->restrictToNoMissiles();
2011
        // Beyond this point no mission can have a missile in fleet
2012
2013
        // MT_DESTROY
2014
        $this->restrictMissionDestroy();
2015
2016
        // MT_ACS
2017
        $this->restrictMissionACS();
2018
2019
        // MT_ATTACK - no checks
2020
2021
        // MT_TRANSPORT - no checks
2022
      }
2023
      // TODO - END $this->restrictFriendOrFoe();
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
2024
2025
2026
      //
2027
      //
2028
      //
2029
      //
2030
      //
2031
      //
2032
      //
2033
      //
2034
      //
2035
      //
2036
      //
2037
      //
2038
      //
2039
      //
2040
      //
2041
      //
2042
      //
2043
      //
2044
2045
2046
//      $this->restrict2MissionTransportWithResources($fleetResources);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
2047
    } catch(Exception $e) {
2048
      // TODO - MESSAGE BOX
2049 View Code Duplication
      if($e->getCode() != FLIGHT_ALLOWED) {
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...
2050
        sn_db_transaction_rollback();
2051
        pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
2052
      } else {
2053
        pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
2054
      }
2055
    }
2056
2057
2058
    // TODO check for empty mission AKA mission allowed
2059
2060
    $errorlist = '';
2061
2062
    $errorlist .= !is_array($fleetarray) ? classLocale::$lang['fl_no_fleetarray'] : '';
2063
2064
    $TransMetal = max(0, floor(sys_get_param_float('resource0')));
2065
    $TransCrystal = max(0, floor(sys_get_param_float('resource1')));
2066
    $TransDeuterium = max(0, floor(sys_get_param_float('resource2')));
2067
    $StorageNeeded = $TransMetal + $TransCrystal + $TransDeuterium;
2068
2069
    if(!$StorageNeeded && $target_mission == MT_TRANSPORT) {
2070
      $errorlist .= classLocale::$lang['fl_noenoughtgoods'];
2071
    }
2072
2073
2074
    if($target_mission == MT_EXPLORE) {
2075
      if($MaxExpeditions == 0) {
2076
        $errorlist .= classLocale::$lang['fl_expe_notech'];
2077
      } elseif($FlyingExpeditions >= $MaxExpeditions) {
2078
        $errorlist .= classLocale::$lang['fl_expe_max'];
2079
      }
2080
    } else {
2081
      if($TargetPlanet['id_owner']) {
2082
        if($target_mission == MT_COLONIZE) {
2083
          $errorlist .= classLocale::$lang['fl_colonized'];
2084
        }
2085
2086
        if($TargetPlanet['id_owner'] == $planetrow['id_owner']) {
2087
          if($target_mission == MT_ATTACK) {
2088
            $errorlist .= classLocale::$lang['fl_no_self_attack'];
2089
          }
2090
2091
          if($target_mission == MT_SPY) {
2092
            $errorlist .= classLocale::$lang['fl_no_self_spy'];
2093
          }
2094
        } else {
2095
          if($target_mission == MT_RELOCATE) {
2096
            $errorlist .= classLocale::$lang['fl_only_stay_at_home'];
2097
          }
2098
        }
2099
      } else {
2100
        if($target_mission < MT_COLONIZE) {
2101
          $errorlist .= classLocale::$lang['fl_unknow_target'];
2102
        } else {
2103
//          if($target_mission == MT_DESTROY) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% 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...
2104
//            $errorlist .= classLocale::$lang['fl_nomoon'];
2105
//          }
2106
2107
          if($target_mission == MT_RECYCLE) {
2108
            if($TargetPlanet['debris_metal'] + $TargetPlanet['debris_crystal'] == 0) {
2109
              $errorlist .= classLocale::$lang['fl_nodebris'];
2110
            }
2111
          }
2112
        }
2113
      }
2114
    }
2115
2116
2117
    if(sn_module::$sn_module['unit_captain']->manifest['active'] && $captain_id = sys_get_param_id('captain_id')) {
2118
      $captain = sn_module::$sn_module['unit_captain']->unit_captain_get($planetrow['id']);
2119
      if(!$captain) {
2120
        $errorlist .= classLocale::$lang['module_unit_captain_error_no_captain'];
2121
      } elseif($captain['unit_location_type'] == LOC_PLANET) {
2122
        if($target_mission == MT_RELOCATE && ($arriving_captain = mrc_get_level($user, $TargetPlanet, UNIT_CAPTAIN, true))) {
2123
          $errorlist .= classLocale::$lang['module_unit_captain_error_captain_already_bound'];
2124
        }
2125
      } else {
2126
        $errorlist .= classLocale::$lang['module_unit_captain_error_captain_flying'];
2127
      }
2128
    }
2129
2130
    if($errorlist) {
2131
      sn_db_transaction_rollback();
2132
      message("<span class='error'><ul>{$errorlist}</ul></span>", classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2133
    }
2134
2135
    //Normally... unless its acs...
2136
    $aks = 0;
2137
    $fleet_group = sys_get_param_int('fleet_group');
2138
    //But is it acs??
2139
    //Well all acs fleets must have a fleet code.
2140
    //The co-ords must be the same as where the acs fleet is going.
2141
    if($fleet_group && sys_get_param_str('acs_target_mr') == "g{$galaxy}s{$system}p{$planet}t{$planet_type}") {
2142
      //ACS attack must exist (if acs fleet has arrived this will also return false (2 checks in 1!!!)
2143
      $aks = db_acs_get_by_group_id($fleet_group);
2144
      if(!$aks) {
2145
        $fleet_group = 0;
2146
      } else {
2147
        //Also it must be mission type 2
2148
        $target_mission = MT_ACS;
2149
2150
        $galaxy = $aks['galaxy'];
2151
        $system = $aks['system'];
2152
        $planet = $aks['planet'];
2153
        $planet_type = $aks['planet_type'];
2154
      }
2155
    } elseif($target_mission == MT_ACS) {
2156
      //Check that a failed acs attack isn't being sent, if it is, make it an attack fleet.
2157
      $target_mission = MT_ATTACK;
2158
    }
2159
2160
    if($target_mission == MT_COLONIZE || $target_mission == MT_EXPLORE) {
2161
      $TargetPlanet = array('galaxy' => $galaxy, 'system' => $system, 'planet' => $planet, 'id_owner' => 0);
2162
    }
2163
    $options = array('fleet_speed_percent' => $speed_percent, 'fleet_group' => $fleet_group, 'resources' => $StorageNeeded);
2164
    $cant_attack = flt_can_attack($planetrow, $TargetPlanet, $fleetarray, $target_mission, $options);
0 ignored issues
show
Documentation introduced by
$options is of type array<string,integer|dou...,"resources":"double"}>, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2165
2166
    if($cant_attack !== FLIGHT_ALLOWED) {
2167
      message("<span class='error'><b>{$classLocale['fl_attack_error'][$cant_attack]}</b></span>", classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 99);
2168
    }
2169
2170
    $mission_time_in_seconds = 0;
2171
    $arrival_time = SN_TIME_NOW + $time_to_travel;
2172
    if($target_mission == MT_ACS && $aks) {
2173
//    if($fleet_start_time > $aks['ankunft']) {
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...
2174
      if($arrival_time > $aks['ankunft']) {
2175
        message(classLocale::$lang['fl_aks_too_slow'] . 'Fleet arrival: ' . date(FMT_DATE_TIME, $arrival_time) . " AKS arrival: " . date(FMT_DATE_TIME, $aks['ankunft']), classLocale::$lang['fl_error']);
2176
      }
2177
      $group_sync_delta_time = $aks['ankunft'] - $arrival_time;
2178
      // Set arrival time to ACS arrival time
2179
      $arrival_time = $aks['ankunft'];
2180
      // Set return time to ACS return time + fleet's time to travel
2181
      $return_time = $aks['ankunft'] + $time_to_travel;
2182
    } else {
2183
      if($target_mission == MT_EXPLORE || $target_mission == MT_HOLD) {
2184
        $max_duration = $target_mission == MT_EXPLORE ? get_player_max_expedition_duration($user) : ($target_mission == MT_HOLD ? 12 : 0);
2185
        if($max_duration) {
2186
          $mission_time_in_hours = sys_get_param_id('missiontime');
2187
          if($mission_time_in_hours > $max_duration || $mission_time_in_hours < 1) {
2188
            $debug->warning('Supplying wrong mission time', 'Hack attempt', 302, array('base_dump' => true));
2189
            die();
2190
          }
2191
          $mission_time_in_seconds = ceil($mission_time_in_hours * 3600 / ($target_mission == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1));
2192
        }
2193
      }
2194
      $return_time = $arrival_time + $mission_time_in_seconds + $time_to_travel;
2195
      $group_sync_delta_time = 0;
2196
    }
2197
2198
//    $FleetStorage = 0;
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...
2199
2200
    $db_changeset = array();
2201
    foreach($fleetarray as $Ship => $Count) {
2202
//      $FleetStorage += get_unit_param($Ship, P_CAPACITY) * $Count;
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
2203
      $db_changeset['unit'][] = sn_db_unit_changeset_prepare($Ship, -$Count, $user, $planetrow['id']);
2204
    }
2205
//    $FleetStorage -= $consumption;
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...
2206
2207
//    if($StorageNeeded > $FleetStorage) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% 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...
2208
//      message("<span class='error'><b>" . classLocale::$lang['fl_nostoragespa'] . pretty_number($StorageNeeded - $FleetStorage) . "</b></span>", classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 2);
2209
//    }
2210
//    if($planetrow['deuterium'] < $TransDeuterium + $consumption) {
2211
//      message("<font color=\"red\"><b>" . classLocale::$lang['fl_no_deuterium'] . pretty_number($TransDeuterium + $consumption - $planetrow['deuterium']) . "</b></font>", classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 2);
2212
//    }
2213
//    if(($planetrow['metal'] < $TransMetal) || ($planetrow['crystal'] < $TransCrystal)) {
2214
//      message("<font color=\"red\"><b>" . classLocale::$lang['fl_no_resources'] . "</b></font>", classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 2);
2215
//    }
2216
2217
2218
    //
2219
    //
2220
    //
2221
    //
2222
    //
2223
    //
2224
    //
2225
    //
2226
    // ---------------- END OF CHECKS ------------------------------------------------------
2227
2228
    $fleetarray[RES_METAL] = $TransMetal;
2229
    $fleetarray[RES_CRYSTAL] = $TransCrystal;
2230
    $fleetarray[RES_DEUTERIUM] = $TransDeuterium;
2231
2232
    $objFleet = new Fleet();
2233
    $objFleet->set_times($time_to_travel, $mission_time_in_seconds, $group_sync_delta_time);
2234
    $objFleet->unitsSetFromArray($fleetarray);
2235
    $objFleet->mission_type = $target_mission;
2236
    $objFleet->set_start_planet($planetrow);
2237
    $objFleet->set_end_planet(array(
2238
      'id'          => !empty($TargetPlanet['id']) ? $TargetPlanet['id'] : null,
2239
      'galaxy'      => !empty($galaxy) ? $galaxy : 0,
2240
      'system'      => !empty($system) ? $system : 0,
2241
      'planet'      => !empty($planet) ? $planet : 0,
2242
      'planet_type' => !empty($planet_type) ? $planet_type : 0,
2243
      'id_owner'    => $TargetPlanet['id_owner'],
2244
    ));
2245
    $objFleet->playerOwnerId = $user['id'];
2246
    $objFleet->group_id = $fleet_group;
2247
    $objFleet->dbInsert();
2248
2249
    db_planet_set_by_id($planetrow['id'], "`metal` = `metal` - {$TransMetal}, `crystal` = `crystal` - {$TransCrystal}, `deuterium` = `deuterium` - {$TransDeuterium} - {$consumption}");
2250
    db_changeset_apply($db_changeset);
2251
2252
    $template = gettemplate('fleet3', true);
2253
2254
    if(is_array($captain)) {
2255
      db_unit_set_by_id($captain['unit_id'], "`unit_location_type` = " . LOC_FLEET . ", `unit_location_id` = {$objFleet->dbId}");
0 ignored issues
show
Bug introduced by
The variable $captain does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
2256
    }
2257
2258
    $template_route = array(
2259
      'ID'                 => 1,
2260
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$planetrow['planet_type']],
2261
      'START_COORDS'       => uni_render_coordinates($planetrow),
2262
      'START_NAME'         => $planetrow['name'],
2263
      'START_TIME_TEXT'    => date(FMT_DATE_TIME, $return_time + SN_CLIENT_TIME_DIFF),
2264
      'START_LEFT'         => floor($return_time + 1 - SN_TIME_NOW),
2265
    );
2266
    if(!empty($TargetPlanet)) {
2267
      $template_route += array(
2268
        'END_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$TargetPlanet['planet_type']],
2269
        'END_COORDS'       => uni_render_coordinates($TargetPlanet),
2270
        'END_NAME'         => $TargetPlanet['name'],
2271
        'END_TIME_TEXT'    => date(FMT_DATE_TIME, $arrival_time + SN_CLIENT_TIME_DIFF),
2272
        'END_LEFT'         => floor($arrival_time + 1 - SN_TIME_NOW),
2273
      );
2274
    }
2275
2276
    $template->assign_block_vars('fleets', $template_route);
2277
2278
    $sn_groups_fleet = sn_get_groups('fleet');
2279
    foreach($fleetarray as $ship_id => $ship_count) {
2280
      if(in_array($ship_id, $sn_groups_fleet) && $ship_count) {
2281
//      $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...
2282
        $template->assign_block_vars('fleets.ships', array(
2283
          'ID'          => $ship_id,
2284
          'AMOUNT'      => $ship_count,
2285
          'AMOUNT_TEXT' => pretty_number($ship_count),
2286
//        '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...
2287
//        'SPEED'       => $ship_base_data['speed'],
2288
          'NAME'        => classLocale::$lang['tech'][$ship_id],
2289
        ));
2290
      }
2291
    }
2292
2293
    $template->assign_vars(array(
2294
      'mission'         => classLocale::$lang['type_mission'][$target_mission] . ($target_mission == MT_EXPLORE || $target_mission == MT_HOLD ? ' ' . pretty_time($mission_time_in_seconds) : ''),
2295
      'dist'            => pretty_number($distance),
2296
      'speed'           => pretty_number($fleet_speed),
2297
      'deute_need'      => pretty_number($consumption),
2298
      'from'            => "{$planetrow['galaxy']}:{$planetrow['system']}:{$planetrow['planet']}",
2299
      'time_go'         => date(FMT_DATE_TIME, $arrival_time),
2300
      'time_go_local'   => date(FMT_DATE_TIME, $arrival_time + SN_CLIENT_TIME_DIFF),
2301
      'time_back'       => date(FMT_DATE_TIME, $return_time),
2302
      'time_back_local' => date(FMT_DATE_TIME, $return_time + SN_CLIENT_TIME_DIFF),
2303
    ));
2304
2305
    pdie('Stop for debug');
2306
2307
    sn_db_transaction_commit();
2308
    $planetrow = db_planet_by_id($planetrow['id']);
2309
    $template->assign_recursive($template_result);
2310
    display($template, classLocale::$lang['fl_title']);
2311
  }
2312
2313
2314
  /**
2315
   * @param array $checklist
2316
   *
2317
   * @throws Exception
2318
   */
2319
  public function checkMissionRestrictions($checklist) {
2320
    foreach($checklist as $condition => $action) {
2321
      $checkResult = call_user_func(array($this, $condition));
2322
2323
      if(is_array($action) && !empty($action[$checkResult])) {
2324
        $action = $action[$checkResult];
2325
      }
2326
2327
      if(is_array($action)) {
2328
        $this->checkMissionRestrictions($action);
2329
      } elseif(!$checkResult) {
2330
        throw new Exception($action, $action);
2331
      }
2332
    }
2333
  }
2334
2335
  protected function checkSpeedPercentOld() {
2336
    return in_array($this->oldSpeedInTens, array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1));
2337
  }
2338
2339
  protected function checkSenderNoVacation() {
2340
    return empty($this->dbOwnerRow['vacation']) || $this->dbOwnerRow['vacation'] >= SN_TIME_NOW;
2341
  }
2342
2343
  protected function checkTargetNotSource() {
2344
    return !$this->targetVector->isEqualToPlanet($this->dbSourcePlanetRow);
2345
  }
2346
2347
  protected function checkTargetInUniverse() {
2348
    return $this->targetVector->isInUniverse();
2349
  }
2350
2351
  protected function checkUnitsPositive() {
2352
    return $this->unitList->unitsPositive();
2353
  }
2354
2355
  protected function checkOnlyFleetUnits() {
2356
    return $this->unitList->unitsInGroup(sn_get_groups(array('fleet', 'missile')));
2357
  }
2358
2359
  protected function checkOnlyFlyingUnits() {
2360
    return $this->unitList->unitsIsAllMovable($this->dbOwnerRow);
2361
  }
2362
2363
  protected function checkEnoughFleetSlots() {
2364
    return FleetList::fleet_count_flying($this->getPlayerOwnerId()) < GetMaxFleets($this->dbOwnerRow);
2365
  }
2366
2367
  protected function checkSourceEnoughShips() {
2368
    return $this->unitList->shipsIsEnoughOnPlanet($this->dbSourcePlanetRow);
2369
  }
2370
2371
  protected function checkEnoughCapacity() {
2372
    return
2373
      !empty($this->travelData) &&
2374
      is_array($this->travelData) &&
2375
      floor($this->travelData['capacity']) >= ceil(array_sum($this->resource_list) + $this->travelData['consumption']);
2376
  }
2377
2378
  protected function checkResourcesPositive() {
2379
    foreach($this->resource_list as $resourceId => $resourceAmount) {
2380
      if($resourceAmount < 0) {
2381
        return false;
2382
      }
2383
    }
2384
2385
    return true;
2386
  }
2387
2388
  protected function checkSourceEnoughFuel() {
2389
    $deuteriumOnPlanet = mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, RES_DEUTERIUM);
2390
2391
    return $deuteriumOnPlanet < ceil($this->travelData['consumption']);
2392
  }
2393
2394
2395
  protected function checkSourceEnoughResources() {
2396
    $fleetResources = $this->resource_list;
2397
    $fleetResources[RES_DEUTERIUM] = ceil($fleetResources[RES_DEUTERIUM] + $this->travelData['consumption']);
2398
    foreach($fleetResources as $resourceId => $resourceAmount) {
2399
      if(mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, $resourceId) < ceil($fleetResources[$resourceId])) {
2400
        return false;
2401
      }
2402
    }
2403
2404
    return true;
2405
  }
2406
2407
  protected function checkKnownSpace() {
2408
    return $this->targetVector->isInKnownSpace();
2409
  }
2410
2411
  protected function checkNotOnlySpies() {
2412
    return $this->unitList->unitsCountById(SHIP_SPY) < $this->shipsGetTotal();
2413
  }
2414
2415
  public function checkNoMissiles() {
2416
    $missilesAttack = mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, UNIT_DEF_MISSILE_INTERPLANET); // this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERPLANET);
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
2417
    $missilesDefense = mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, UNIT_DEF_MISSILE_INTERCEPTOR); // this->unitList->unitsCountById(UNIT_DEF_MISSILE_INTERCEPTOR);
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
2418
    return $missilesAttack == 0 && $missilesDefense == 0;
2419
  }
2420
2421
2422
  protected function forceMissionExplore() {
2423
    $this->allowed_missions = array(
2424
      MT_EXPLORE => MT_EXPLORE,
2425
    );
2426
2427
    return false;
2428
  }
2429
2430
  protected function checkTargetExists() {
2431
    return !empty($this->dbTargetRow['id']);
2432
  }
2433
2434
  protected function checkHaveColonizer() {
2435
    // Colonization fleet should have at least one colonizer
2436
    return $this->unitList->unitsCountById(SHIP_COLONIZER) >= 1;
2437
  }
2438
2439
  protected function checkTargetIsPlanet() {
2440
    return $this->targetVector->type == PT_PLANET;
2441
  }
2442
2443
  protected function forceMissionColonize() {
2444
    $this->allowed_missions = array(
2445
      MT_COLONIZE => MT_COLONIZE,
2446
    );
2447
2448
    return false;
2449
  }
2450
2451
  protected function checkTargetIsDebris() {
2452
    return $this->targetVector->type == PT_DEBRIS;
2453
  }
2454
2455
  protected function checkHaveRecyclers() {
2456
    $recyclers = 0;
2457
    foreach(sn_get_groups('flt_recyclers') as $recycler_id) {
2458
      $recyclers += $this->unitList->unitsCountById($recycler_id);
2459
    }
2460
2461
    return $recyclers >= 1;
2462
  }
2463
2464
  protected function forceMissionRecycle() {
2465
    $this->allowed_missions = array(
2466
      MT_RECYCLE => MT_RECYCLE,
2467
    );
2468
2469
    return false;
2470
  }
2471
2472
2473
  // TODO
2474
  protected function checkTargetOwn() {
2475
    $result = $this->dbTargetRow['id_owner'] == $this->dbSourcePlanetRow['id_owner'];
2476
2477
    if($result) {
2478
      // Spying can't be done on owner's planet/moon
2479
      unset($this->allowed_missions[MT_SPY]);
2480
      // Attack can't be done on owner's planet/moon
2481
      unset($this->allowed_missions[MT_ATTACK]);
2482
      // ACS can't be done on owner's planet/moon
2483
      unset($this->allowed_missions[MT_ACS]);
2484
      // Destroy can't be done on owner's moon
2485
      unset($this->allowed_missions[MT_DESTROY]);
2486
      unset($this->allowed_missions[MT_MISSILE]);
2487
2488
      // MT_RELOCATE
2489
      // No checks
2490
      // TODO - check captain
2491
2492
      // MT_HOLD
2493
      // TODO - Check for Allies Deposit for HOLD
2494
2495
      // MT_TRANSPORT
2496
2497
    } else {
2498
      // Relocate can be done only on owner's planet/moon
2499
      unset($this->allowed_missions[MT_RELOCATE]);
2500
2501
    }
2502
2503
    return $result; // this->getPlayerOwnerId();
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...
2504
  }
2505
2506
2507
  protected function alwaysFalse() {
2508
    return false;
2509
  }
2510
2511
2512
  // TODO - is MT_HOLD is aggressive??
2513
  protected function checkMissionPeaceful() {
2514
    return !$this->_mission_type || in_array($this->_mission_type, array(
2515
      MT_EXPLORE => MT_EXPLORE,
2516
      MT_COLONIZE => MT_COLONIZE,
2517
      MT_RECYCLE => MT_RECYCLE,
2518
      MT_RELOCATE => MT_RELOCATE,
2519
      MT_TRANSPORT => MT_TRANSPORT,
2520
    ));
2521
  }
2522
2523
  protected function checkSpiesOnly() {
2524
    return $this->unitList->unitsCountById(SHIP_SPY) == $this->shipsGetTotal();
2525
  }
2526
2527 View Code Duplication
  protected function checkMissionSpy() {
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...
2528
    $result = !$this->_mission_type || $this->_mission_type == MT_SPY;
2529
    if($result) {
2530
      $this->allowed_missions = array(
2531
        MT_SPY => MT_SPY,
2532
      );
2533
    } else {
2534
      unset($this->allowed_missions[MT_SPY]);
2535
    }
2536
2537
    return $result;
2538
  }
2539
2540
2541 View Code Duplication
  protected function checkMissionRelocate() {
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...
2542
    $result = !$this->_mission_type || $this->_mission_type == MT_RELOCATE;
2543
    if($result) {
2544
      $this->allowed_missions = array(
2545
        MT_RELOCATE => MT_RELOCATE,
2546
      );
2547
    } else {
2548
      unset($this->allowed_missions[MT_RELOCATE]);
2549
    }
2550
2551
    return $result;
2552
  }
2553
2554
}
2555