Completed
Push — work-fleets ( 4d76fa...c97fe0 )
by SuperNova.WS
05:17
created

Fleet::renderAvailableShips()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 30
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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...
Bug introduced by
Are you sure the assignment to $this->captain is correct as $this->captainGet() (which targets Fleet::captainGet()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1616
1617
    $this->travelData = $this->flt_travel_data($this->oldSpeedInTens);
1618
1619
    try {
1620
      $validator = new FleetValidator($this);
1621
      $validator->validate();
1622
    } catch (Exception $e) {
1623
      // TODO - MESSAGE BOX
1624
      sn_db_transaction_rollback();
1625
      pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
1626
    }
1627
1628
    // Flight allowed here
1629
    pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1630
1631
1632
    // TODO check for empty mission AKA mission allowed
1633
1634
    if (array_sum($this->resource_list) < 1 && $this->_mission_type == MT_TRANSPORT) {
1635
      $errorlist .= classLocale::$lang['fl_noenoughtgoods'];
1636
    }
1637
1638
    if ($errorlist) {
1639
      sn_db_transaction_rollback();
1640
      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...
1641
    }
1642
1643
    //Normally... unless its acs...
1644
    $aks = 0;
1645
    //But is it acs??
1646
    //Well all acs fleets must have a fleet code.
1647
    //The co-ords must be the same as where the acs fleet is going.
1648
    if ($this->_group_id && sys_get_param_str('acs_target_mr') == "g{$this->targetVector->galaxy}s{$this->targetVector->system}p{$this->targetVector->planet}t{$this->targetVector->type}") {
1649
      //ACS attack must exist (if acs fleet has arrived this will also return false (2 checks in 1!!!)
1650
      $aks = db_acs_get_by_group_id($this->_group_id);
1651
      if (!$aks) {
1652
        $this->_group_id = 0;
1653
      } else {
1654
        //Also it must be mission type 2
1655
        $this->_mission_type = MT_ACS;
1656
1657
1658
        $this->targetVector->galaxy = $aks['galaxy'];
1659
        $this->targetVector->system = $aks['system'];
1660
        $this->targetVector->planet = $aks['planet'];
1661
        $this->targetVector->type = $aks['planet_type'];
1662
      }
1663
    } elseif ($this->_mission_type == MT_ACS) {
1664
      //Check that a failed acs attack isn't being sent, if it is, make it an attack fleet.
1665
      $this->_mission_type = MT_ATTACK;
1666
    }
1667
1668
    $timeMissionJob = 0;
1669
    if ($this->_mission_type == MT_ACS && $aks) {
1670
      $acsTimeToArrive = $aks['ankunft'] - SN_TIME_NOW;
1671
      if ($acsTimeToArrive < $this->travelData['duration']) {
1672
        message(classLocale::$lang['fl_aks_too_slow'] . 'Fleet arrival: ' . date(FMT_DATE_TIME, SN_TIME_NOW + $this->travelData['duration']) . " AKS arrival: " . date(FMT_DATE_TIME, $aks['ankunft']), classLocale::$lang['fl_error']);
1673
      }
1674
      // Set time to travel to ACS' TTT
1675
      $this->travelData['duration'] = $acsTimeToArrive;
1676
    } else {
1677
      if ($this->_mission_type == MT_EXPLORE || $this->_mission_type == MT_HOLD) {
1678
        $max_duration = $this->_mission_type == MT_EXPLORE ? get_player_max_expedition_duration($this->dbOwnerRow) : ($this->_mission_type == MT_HOLD ? 12 : 0);
1679
        if ($max_duration) {
1680
          $mission_time_in_hours = sys_get_param_id('missiontime');
1681
          if ($mission_time_in_hours > $max_duration || $mission_time_in_hours < 1) {
1682
            classSupernova::$debug->warning('Supplying wrong mission time', 'Hack attempt', 302, array('base_dump' => true));
0 ignored issues
show
Documentation introduced by
array('base_dump' => true) is of type array<string,boolean,{"base_dump":"boolean"}>, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1683
            die();
1684
          }
1685
          $timeMissionJob = ceil($mission_time_in_hours * 3600 / ($this->_mission_type == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1));
1686
        }
1687
      }
1688
    }
1689
1690
    //
1691
    //
1692
    //
1693
    //
1694
    //
1695
    //
1696
    //
1697
    //
1698
    // ---------------- END OF CHECKS ------------------------------------------------------
1699
1700
    $this->set_times($this->travelData['duration'], $timeMissionJob);
1701
    $this->dbInsert();
1702
1703
    db_planet_set_by_id($this->dbSourcePlanetRow['id'],
1704
      "`metal` = `metal` - {$this->resource_list[RES_METAL]},
1705
      `crystal` = `crystal` - {$this->resource_list[RES_CRYSTAL]},
1706
      `deuterium` = `deuterium` - {$this->resource_list[RES_DEUTERIUM]} - {$this->travelData['consumption']}"
1707
    );
1708
1709
    $db_changeset = $this->unitList->db_prepare_old_changeset_for_planet($this->dbOwnerRow, $this->dbSourcePlanetRow['id']);
1710
    db_changeset_apply($db_changeset);
1711
1712
1713
    if (!empty($captain['unit_id'])) {
0 ignored issues
show
Bug introduced by
The variable $captain seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

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

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

Loading history...
1714
      db_unit_set_by_id($captain['unit_id'], "`unit_location_type` = " . LOC_FLEET . ", `unit_location_id` = {$this->_dbId}");
1715
    }
1716
1717
1718
    $template_result['.']['fleets'][] = $this->renderFleet(SN_TIME_NOW, $timeMissionJob);
1719
1720
    $template_result += array(
1721
      'mission'         => classLocale::$lang['type_mission'][$this->_mission_type] . ($this->_mission_type == MT_EXPLORE || $this->_mission_type == MT_HOLD ? ' ' . pretty_time($timeMissionJob) : ''),
1722
      'dist'            => pretty_number($this->travelData['distance']),
1723
      'speed'           => pretty_number($this->travelData['fleet_speed']),
1724
      'deute_need'      => pretty_number($this->travelData['consumption']),
1725
      'from'            => "{$this->dbSourcePlanetRow['galaxy']}:{$this->dbSourcePlanetRow['system']}:{$this->dbSourcePlanetRow['planet']}",
1726
      'time_go'         => date(FMT_DATE_TIME, $this->_time_arrive_to_target),
1727
      'time_go_local'   => date(FMT_DATE_TIME, $this->_time_arrive_to_target + SN_CLIENT_TIME_DIFF),
1728
      'time_back'       => date(FMT_DATE_TIME, $this->_time_return_to_source),
1729
      'time_back_local' => date(FMT_DATE_TIME, $this->_time_return_to_source + SN_CLIENT_TIME_DIFF),
1730
    );
1731
1732
    $this->dbSourcePlanetRow = db_planet_by_id($this->dbSourcePlanetRow['id']);
1733
1734
    pdie('Stop for debug');
1735
1736
    sn_db_transaction_commit();
1737
1738
    $template = gettemplate('fleet3', true);
1739
    $template->assign_recursive($template_result);
1740
    display($template, classLocale::$lang['fl_title']);
1741
  }
1742
1743
1744
  /**
1745
   * @return array
1746
   */
1747
  protected function resourcesGetOnPlanet() {
1748
    $planetResources = array();
1749
1750
    $sn_group_resources = sn_get_groups('resources_loot');
1751
    foreach ($sn_group_resources as $resource_id) {
1752
      $planetResources[$resource_id] = floor(mrc_get_level($this->dbOwnerRow, $this->dbSourcePlanetRow, $resource_id) - ($resource_id == RES_DEUTERIUM ? $this->travelData['consumption'] : 0));
1753
    }
1754
1755
    return $planetResources;
1756
  }
1757
1758
  /**
1759
   */
1760
  public function captainGet() {
1761
    $this->captain = array();
1762
1763
    /**
1764
     * @var unit_captain $moduleCaptain
1765
     */
1766
    $moduleCaptain = !empty(sn_module::$sn_module['unit_captain']) ? sn_module::$sn_module['unit_captain'] : null;
1767
1768
    if (
1769
      !empty($moduleCaptain)
1770
      &&
1771
      $moduleCaptain->manifest['active']
1772
    ) {
1773
      $this->captain = $moduleCaptain->unit_captain_get($this->dbSourcePlanetRow['id']);
1774
    }
1775
  }
1776
1777
  /**
1778
   * @return array
1779
   */
1780
  protected function renderCaptain() {
1781
    $result = array();
1782
1783
    $captain = $this->captainGet();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $captain is correct as $this->captainGet() (which targets Fleet::captainGet()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1784
1785
    if (!empty($captain['unit_id']) && $captain['unit_location_type'] == LOC_PLANET) {
1786
      $result = array(
1787
        'CAPTAIN_ID'     => $captain['unit_id'],
1788
        'CAPTAIN_LEVEL'  => $captain['captain_level'],
1789
        'CAPTAIN_SHIELD' => $captain['captain_shield'],
1790
        'CAPTAIN_ARMOR'  => $captain['captain_armor'],
1791
        'CAPTAIN_ATTACK' => $captain['captain_attack'],
1792
      );
1793
    }
1794
1795
    return $result;
1796
  }
1797
1798
}
1799