Completed
Branch work-fleets (4d76fa)
by SuperNova.WS
05:23
created

Fleet::restrict2MissionExploreAvailable()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 17
rs 9.2
cc 4
eloc 10
nc 4
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
  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
   * Fleet constructor.
308
   */
309
  public function __construct() {
310
    parent::__construct();
311
    $this->exists_missions = sn_get_groups('missions');
312
    $this->allowed_missions = $this->exists_missions;
313
  }
314
315
  /**
316
   * @param array $template_result
317
   * @param array $playerRow
318
   * @param array $planetRow
319
   */
320
  // TODO - redo to unit/unitlist renderer
321
  public function renderAvailableShips(&$template_result, $playerRow, $planetRow) {
322
    $record_index = 0;
323
    $ship_list = array();
324
    foreach (sn_get_groups('fleet') as $n => $unit_id) {
325
      $unit_level = mrc_get_level($playerRow, $planetRow, $unit_id, false, true);
326
      if ($unit_level <= 0) {
327
        continue;
328
      }
329
      $ship_data = get_ship_data($unit_id, $playerRow);
330
      $ship_list[$unit_id] = array(
331
        '__INDEX'          => $record_index++,
332
        'ID'               => $unit_id,
333
        'NAME'             => classLocale::$lang['tech'][$unit_id],
334
        'AMOUNT'           => $unit_level,
335
        'AMOUNT_TEXT'      => pretty_number($unit_level),
336
        'CONSUMPTION'      => $ship_data['consumption'],
337
        'CONSUMPTION_TEXT' => pretty_number($ship_data['consumption']),
338
        'SPEED'            => $ship_data['speed'],
339
        'SPEED_TEXT'       => pretty_number($ship_data['speed']),
340
        'CAPACITY'         => $ship_data['capacity'],
341
        'CAPACITY_TEXT'    => pretty_number($ship_data['capacity']),
342
      );
343
    }
344
345
    sortUnitRenderedList($ship_list, classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT], classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE]);
346
347
    foreach ($ship_list as $ship_data) {
348
      $template_result['.']['ships'][] = $ship_data;
349
    }
350
  }
351
352
  public function isEmpty() {
353
    return !$this->resourcesGetTotal() && !$this->shipsGetTotal();
354
  }
355
356
//  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...
357
//    return $this->playerOwnerId;
358
//  }
359
360
  /**
361
   * Initializes Fleet from user params and posts it to DB
362
   */
363
  public function dbInsert() {
364
    // WARNING! MISSION TIMES MUST BE SET WITH set_times() method!
365
    // TODO - more checks!
366
    if (empty($this->_time_launch)) {
367
      die('Fleet time not set!');
368
    }
369
370
    parent::dbInsert();
371
  }
372
373
374
  /* FLEET DB ACCESS =================================================================================================*/
375
376
  /**
377
   * LOCK - Lock all records which can be used with mission
378
   *
379
   * @param $mission_data
380
   *
381
   * @return array|bool|mysqli_result|null
382
   */
383
  public function dbLockFlying(&$mission_data) {
384
    // Тупо лочим всех юзеров, чьи флоты летят или улетают с координат отбытия/прибытия $fleet_row
385
    // Что бы делать это умно - надо учитывать fleet__mess во $fleet_row и в таблице fleets
386
387
    $fleet_id_safe = idval($this->_dbId);
388
389
    return doquery(
390
    // Блокировка самого флота
391
      "SELECT 1 FROM {{fleets}} AS f " .
392
393
      // Блокировка всех юнитов, принадлежащих этому флоту
394
      "LEFT JOIN {{unit}} as unit ON unit.unit_location_type = " . static::$locationType . " AND unit.unit_location_id = f.fleet_id " .
395
396
      // Блокировка всех прилетающих и улетающих флотов, если нужно
397
      // TODO - lock fleets by COORDINATES
398
      ($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 " : '') .
399
      // Блокировка всех юнитов, принадлежащих прилетающим и улетающим флотам - ufd = unit_fleet_destination
400
      ($mission_data['dst_fleets'] ? "LEFT JOIN {{unit}} AS ufd ON ufd.unit_location_type = " . static::$locationType . " AND ufd.unit_location_id = fd.fleet_id " : '') .
401
402
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{users}} AS ud ON ud.id = f.fleet_target_owner " : '') .
403
      // Блокировка всех юнитов, принадлежащих владельцу планеты-цели
404
      ($mission_data['dst_user'] || $mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS unit_player_dest ON unit_player_dest.unit_player_id = ud.id " : '') .
405
      // Блокировка планеты-цели
406
      ($mission_data['dst_planet'] ? "LEFT JOIN {{planets}} AS pd ON pd.id = f.fleet_end_planet_id " : '') .
407
      // Блокировка всех юнитов, принадлежащих планете-цели - НЕ НУЖНО. Уже залочили ранее, как принадлежащие игроку-цели
408
//      ($mission_data['dst_planet'] ? "LEFT JOIN {{unit}} AS upd ON upd.unit_location_type = " . LOC_PLANET . " AND upd.unit_location_id = pd.id " : '') .
409
410
411
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{users}} AS us ON us.id = f.fleet_owner " : '') .
412
      // Блокировка всех юнитов, принадлежащих владельцу флота
413
      ($mission_data['src_user'] || $mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS unit_player_src ON unit_player_src.unit_player_id = us.id " : '') .
414
      // Блокировка планеты отправления
415
      ($mission_data['src_planet'] ? "LEFT JOIN {{planets}} AS ps ON ps.id = f.fleet_start_planet_id " : '') .
416
      // Блокировка всех юнитов, принадлежащих планете с которой юниты были отправлены - НЕ НУЖНО. Уже залочили ранее, как принадлежащие владельцу флота
417
//      ($mission_data['src_planet'] ? "LEFT JOIN {{unit}} AS ups ON ups.unit_location_type = " . LOC_PLANET . " AND ups.unit_location_id = ps.id " : '') .
418
419
      "WHERE f.fleet_id = {$fleet_id_safe} GROUP BY 1 FOR UPDATE"
420
    );
421
  }
422
423
  /**
424
   * Lock all fields that belongs to operation
425
   *
426
   * @param $dbId
427
   */
428
  // TODO = make static
429
  public function dbGetLockById($dbId) {
430
    doquery(
431
    // Блокировка самого флота
432
      "SELECT 1 FROM {{fleets}} AS FLEET0 " .
433
      // Lock fleet owner
434
      "LEFT JOIN {{users}} as USER0 on USER0.id = FLEET0.fleet_owner " .
435
      // Блокировка всех юнитов, принадлежащих этому флоту
436
      "LEFT JOIN {{unit}} as UNIT0 ON UNIT0.unit_location_type = " . LOC_FLEET . " AND UNIT0.unit_location_id = FLEET0.fleet_id " .
437
438
      // Без предварительной выборки неизвестно - куда летит этот флот.
439
      // Поэтому надо выбирать флоты, чьи координаты прибытия ИЛИ отбытия совпадают с координатами прибытия ИЛИ отбытия текущего флота.
440
      // Получаем матрицу 2х2 - т.е. 4 подзапроса.
441
      // При блокировке всегда нужно выбирать И лпанету, И луну - поскольку при бое на орбите луны обломки падают на орбиту планеты.
442
      // Поэтому тип планеты не указывается
443
444
      // Lock fleet heading to destination planet. Only if FLEET0.fleet_mess == 0
445
      "LEFT JOIN {{fleets}} AS FLEET1 ON
446
        FLEET1.fleet_mess = 0 AND FLEET0.fleet_mess = 0 AND
447
        FLEET1.fleet_end_galaxy = FLEET0.fleet_end_galaxy AND
448
        FLEET1.fleet_end_system = FLEET0.fleet_end_system AND
449
        FLEET1.fleet_end_planet = FLEET0.fleet_end_planet
450
      " .
451
      // Блокировка всех юнитов, принадлежащих этим флотам
452
      "LEFT JOIN {{unit}} as UNIT1 ON UNIT1.unit_location_type = " . LOC_FLEET . " AND UNIT1.unit_location_id = FLEET1.fleet_id " .
453
      // Lock fleet owner
454
      "LEFT JOIN {{users}} as USER1 on USER1.id = FLEET1.fleet_owner " .
455
456
      "LEFT JOIN {{fleets}} AS FLEET2 ON
457
        FLEET2.fleet_mess = 1   AND FLEET0.fleet_mess = 0 AND
458
        FLEET2.fleet_start_galaxy = FLEET0.fleet_end_galaxy AND
459
        FLEET2.fleet_start_system = FLEET0.fleet_end_system AND
460
        FLEET2.fleet_start_planet = FLEET0.fleet_end_planet
461
      " .
462
      // Блокировка всех юнитов, принадлежащих этим флотам
463
      "LEFT JOIN {{unit}} as UNIT2 ON
464
        UNIT2.unit_location_type = " . LOC_FLEET . " AND
465
        UNIT2.unit_location_id = FLEET2.fleet_id
466
      " .
467
      // Lock fleet owner
468
      "LEFT JOIN {{users}} as USER2 on
469
        USER2.id = FLEET2.fleet_owner
470
      " .
471
472
      // Lock fleet heading to source planet. Only if FLEET0.fleet_mess == 1
473
      "LEFT JOIN {{fleets}} AS FLEET3 ON
474
        FLEET3.fleet_mess = 0 AND FLEET0.fleet_mess = 1 AND
475
        FLEET3.fleet_end_galaxy = FLEET0.fleet_start_galaxy AND
476
        FLEET3.fleet_end_system = FLEET0.fleet_start_system AND
477
        FLEET3.fleet_end_planet = FLEET0.fleet_start_planet
478
      " .
479
      // Блокировка всех юнитов, принадлежащих этим флотам
480
      "LEFT JOIN {{unit}} as UNIT3 ON
481
        UNIT3.unit_location_type = " . LOC_FLEET . " AND
482
        UNIT3.unit_location_id = FLEET3.fleet_id
483
      " .
484
      // Lock fleet owner
485
      "LEFT JOIN {{users}} as USER3 on USER3.id = FLEET3.fleet_owner " .
486
487
      "LEFT JOIN {{fleets}} AS FLEET4 ON
488
        FLEET4.fleet_mess = 1   AND FLEET0.fleet_mess = 1 AND
489
        FLEET4.fleet_start_galaxy = FLEET0.fleet_start_galaxy AND
490
        FLEET4.fleet_start_system = FLEET0.fleet_start_system AND
491
        FLEET4.fleet_start_planet = FLEET0.fleet_start_planet
492
      " .
493
      // Блокировка всех юнитов, принадлежащих этим флотам
494
      "LEFT JOIN {{unit}} as UNIT4 ON
495
        UNIT4.unit_location_type = " . LOC_FLEET . " AND
496
        UNIT4.unit_location_id = FLEET4.fleet_id
497
      " .
498
      // Lock fleet owner
499
      "LEFT JOIN {{users}} as USER4 on
500
        USER4.id = FLEET4.fleet_owner
501
      " .
502
503
504
      // Locking start planet
505
      "LEFT JOIN {{planets}} AS PLANETS5 ON
506
        FLEET0.fleet_mess = 1 AND
507
        PLANETS5.galaxy = FLEET0.fleet_start_galaxy AND
508
        PLANETS5.system = FLEET0.fleet_start_system AND
509
        PLANETS5.planet = FLEET0.fleet_start_planet
510
      " .
511
      // Lock planet owner
512
      "LEFT JOIN {{users}} as USER5 on
513
        USER5.id = PLANETS5.id_owner
514
      " .
515
      // Блокировка всех юнитов, принадлежащих этой планете
516
      "LEFT JOIN {{unit}} as UNIT5 ON
517
        UNIT5.unit_location_type = " . LOC_PLANET . " AND
518
        UNIT5.unit_location_id = PLANETS5.id
519
      " .
520
521
522
      // Locking destination planet
523
      "LEFT JOIN {{planets}} AS PLANETS6 ON
524
        FLEET0.fleet_mess = 0 AND
525
        PLANETS6.galaxy = FLEET0.fleet_end_galaxy AND
526
        PLANETS6.system = FLEET0.fleet_end_system AND
527
        PLANETS6.planet = FLEET0.fleet_end_planet
528
      " .
529
      // Lock planet owner
530
      "LEFT JOIN {{users}} as USER6 on
531
        USER6.id = PLANETS6.id_owner
532
      " .
533
      // Блокировка всех юнитов, принадлежащих этой планете
534
      "LEFT JOIN {{unit}} as UNIT6 ON
535
        UNIT6.unit_location_type = " . LOC_PLANET . " AND
536
        UNIT6.unit_location_id = PLANETS6.id
537
      " .
538
      "WHERE FLEET0.fleet_id = {$dbId} GROUP BY 1 FOR UPDATE"
539
    );
540
  }
541
542
543
  public function dbRowParse($db_row) {
544
    parent::dbRowParse($db_row); // TODO: Change the autogenerated stub
545
    $player = new Player();
546
    $player->dbLoad($db_row['fleet_owner']);
547
    $this->setLocatedAt($player);
548
  }
549
550
  /* FLEET HELPERS =====================================================================================================*/
551
  /**
552
   * Forcibly returns fleet before time outs
553
   */
554
  public function commandReturn() {
555
    $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;
556
557
    $this->markReturned();
558
559
    // Считаем, что флот уже долетел TODO
560
    $this->time_arrive_to_target = SN_TIME_NOW;
561
    // Убираем флот из группы
562
    $this->group_id = 0;
563
    // Отменяем работу в точке назначения
564
    $this->time_mission_job_complete = 0;
565
    // TODO - правильно вычслять время возвращения - по проделанному пути, а не по старому времени возвращения
566
    $this->time_return_to_source = $ReturnFlyingTime;
567
568
    // Записываем изменения в БД
569
    $this->dbSave();
570
571
    if ($this->_group_id) {
572
      // TODO: Make here to delete only one AKS - by adding aks_fleet_count to AKS table
573
      db_fleet_aks_purge();
574
    }
575
  }
576
577
578
  /**
579
   * @return array
580
   */
581
  public function target_coordinates_without_type() {
582
    return array(
583
      'galaxy' => $this->_fleet_end_galaxy,
584
      'system' => $this->_fleet_end_system,
585
      'planet' => $this->_fleet_end_planet,
586
    );
587
  }
588
589
  /**
590
   * @return array
591
   */
592
  public function target_coordinates_typed() {
593
    return array(
594
      'galaxy' => $this->_fleet_end_galaxy,
595
      'system' => $this->_fleet_end_system,
596
      'planet' => $this->_fleet_end_planet,
597
      'type'   => $this->_fleet_end_type,
598
    );
599
  }
600
601
  /**
602
   * @return array
603
   */
604
  public function launch_coordinates_typed() {
605
    return array(
606
      'galaxy' => $this->_fleet_start_galaxy,
607
      'system' => $this->_fleet_start_system,
608
      'planet' => $this->_fleet_start_planet,
609
      'type'   => $this->_fleet_start_type,
610
    );
611
  }
612
613
614
  /**
615
   * Sets object fields for fleet return
616
   */
617
  public function markReturned() {
618
    // TODO - Проверка - а не возвращается ли уже флот?
619
    $this->is_returning = 1;
620
  }
621
622
  public function isReturning() {
623
    return 1 == $this->_is_returning;
624
  }
625
626
  public function markReturnedAndSave() {
627
    $this->markReturned();
628
    $this->dbSave();
629
  }
630
631
  /**
632
   * Parses extended unit_array which can include not only ships but resources, captains etc
633
   *
634
   * @param $unit_array
635
   *
636
   * @throws Exception
637
   */
638
  // TODO - separate shipList and unitList
639
  public function unitsSetFromArray($unit_array) {
640
    if (empty($unit_array) || !is_array($unit_array)) {
641
      return;
642
    }
643
    foreach ($unit_array as $unit_id => $unit_count) {
644
      $unit_count = floatval($unit_count);
645
      if (!$unit_count) {
646
        continue;
647
      }
648
649
      if ($this->isShip($unit_id)) {
650
        $this->unitList->unitSetCount($unit_id, $unit_count);
651
      } elseif ($this->isResource($unit_id)) {
652
        $this->resource_list[$unit_id] = $unit_count;
653
      } else {
654
        throw new Exception('Trying to pass to fleet non-resource and non-ship ' . var_export($unit_array, true), ERR_ERROR);
655
      }
656
    }
657
  }
658
659
660
  /**
661
   * Sets fleet timers based on flight duration, time on mission (HOLD/EXPLORE) and fleet departure time.
662
   *
663
   * @param int $time_to_travel - flight duration in seconds
664
   * @param int $time_on_mission - time on mission in seconds
665
   * @param int $flight_departure - fleet departure from source planet timestamp. Allows to send fleet in future or in past
666
   */
667
  public function set_times($time_to_travel, $time_on_mission = 0, $flight_departure = SN_TIME_NOW) {
668
    $this->_time_launch = $flight_departure;
669
670
    $this->_time_arrive_to_target = $this->_time_launch + $time_to_travel;
671
    $this->_time_mission_job_complete = $time_on_mission ? $this->_time_arrive_to_target + $time_on_mission : 0;
672
    $this->_time_return_to_source = ($this->_time_mission_job_complete ? $this->_time_mission_job_complete : $this->_time_arrive_to_target) + $time_to_travel;
673
  }
674
675
676
  public function parse_missile_db_row($missile_db_row) {
677
//    $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...
678
679
    if (empty($missile_db_row) || !is_array($missile_db_row)) {
680
      return;
681
    }
682
683
//      $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...
684
//      $irak_original['fleet_start_name'] = $planet_start['name'];
685
    $this->missile_target = $missile_db_row['primaer'];
686
687
    $this->_dbId = -$missile_db_row['id'];
688
    $this->_playerOwnerId = $missile_db_row['fleet_owner'];
689
    $this->_mission_type = MT_MISSILE;
690
691
    $this->_target_owner_id = $missile_db_row['fleet_target_owner'];
692
693
    $this->_group_id = 0;
694
    $this->_is_returning = 0;
695
696
    $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...
697
    $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...
698
    $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...
699
    $this->_time_return_to_source = $missile_db_row['fleet_end_time'];
700
701
    $this->_fleet_start_planet_id = !empty($missile_db_row['fleet_start_planet_id']) ? $missile_db_row['fleet_start_planet_id'] : null;
702
    $this->_fleet_start_galaxy = $missile_db_row['fleet_start_galaxy'];
703
    $this->_fleet_start_system = $missile_db_row['fleet_start_system'];
704
    $this->_fleet_start_planet = $missile_db_row['fleet_start_planet'];
705
    $this->_fleet_start_type = $missile_db_row['fleet_start_type'];
706
707
    $this->_fleet_end_planet_id = !empty($missile_db_row['fleet_end_planet_id']) ? $missile_db_row['fleet_end_planet_id'] : null;
708
    $this->_fleet_end_galaxy = $missile_db_row['fleet_end_galaxy'];
709
    $this->_fleet_end_system = $missile_db_row['fleet_end_system'];
710
    $this->_fleet_end_planet = $missile_db_row['fleet_end_planet'];
711
    $this->_fleet_end_type = $missile_db_row['fleet_end_type'];
712
713
    $this->unitList->unitSetCount(UNIT_DEF_MISSILE_INTERPLANET, $missile_db_row['fleet_amount']);
714
  }
715
716
717
  /**
718
   * @param $from
719
   */
720
  public function set_start_planet($from) {
721
    $this->fleet_start_planet_id = intval($from['id']) ? $from['id'] : null;
722
    $this->fleet_start_galaxy = $from['galaxy'];
723
    $this->fleet_start_system = $from['system'];
724
    $this->fleet_start_planet = $from['planet'];
725
    $this->fleet_start_type = $from['planet_type'];
726
  }
727
728
  /**
729
   * @param $to
730
   */
731
  public function set_end_planet($to) {
732
    $this->target_owner_id = intval($to['id_owner']) ? $to['id_owner'] : 0;
733
    $this->fleet_end_planet_id = intval($to['id']) ? $to['id'] : null;
734
    $this->fleet_end_galaxy = $to['galaxy'];
735
    $this->fleet_end_system = $to['system'];
736
    $this->fleet_end_planet = $to['planet'];
737
    $this->fleet_end_type = $to['planet_type'];
738
  }
739
740
  /**
741
   * @param Vector $to
742
   */
743
  public function setTargetFromVectorObject($to) {
744
    $this->_fleet_end_galaxy = $to->galaxy;
745
    $this->_fleet_end_system = $to->system;
746
    $this->_fleet_end_planet = $to->planet;
747
    $this->_fleet_end_type = $to->type;
748
  }
749
750
  /**
751
   * @param array $db_row
752
   */
753
  protected function ownerExtract(array &$db_row) {
754
    $player = new Player();
755
    $player->dbLoad($db_row['fleet_owner']);
756
    $this->setLocatedAt($player);
757
  }
758
759
  /**
760
   * @param array $db_row
761
   */
762
  protected function ownerInject(array &$db_row) {
763
    $db_row['fleet_owner'] = $this->getPlayerOwnerId();
764
  }
765
766
767
768
769
  // UnitList/Ships access ***************************************************************************************************
770
771
  // TODO - перекрывать пожже - для миссайл-флотов и дефенс-флотов
772
  protected function isShip($unit_id) {
773
    return UnitShip::is_in_group($unit_id);
774
  }
775
776
  /**
777
   * Set unit count of $unit_id to $unit_count
778
   * If there is no $unit_id - it will be created and saved to DB on dbSave
779
   *
780
   * @param int $unit_id
781
   * @param int $unit_count
782
   */
783
  public function shipSetCount($unit_id, $unit_count = 0) {
784
    $this->shipAdjustCount($unit_id, $unit_count, true);
785
  }
786
787
  /**
788
   * Adjust unit count of $unit_id by $unit_count - or just replace value
789
   * If there is no $unit_id - it will be created and saved to DB on dbSave
790
   *
791
   * @param int  $unit_id
792
   * @param int  $unit_count
793
   * @param bool $replace_value
794
   */
795
  public function shipAdjustCount($unit_id, $unit_count = 0, $replace_value = false) {
796
    $this->unitList->unitAdjustCount($unit_id, $unit_count, $replace_value);
797
  }
798
799
  public function shipGetCount($unit_id) {
800
    return $this->unitList->unitGetCount($unit_id);
801
  }
802
803
  public function shipsCountApplyLossMultiplier($ships_lost_multiplier) {
804
    $this->unitList->unitsCountApplyLossMultiplier($ships_lost_multiplier);
805
  }
806
807
  /**
808
   * Returns ship list in fleet
809
   */
810
  public function shipsGetArray() {
811
    return $this->unitList->unitsGetArray();
812
  }
813
814
  public function shipsGetTotal() {
815
    return $this->unitList->unitsCount();
816
  }
817
818
  public function shipsGetCapacity() {
819
    return $this->unitList->shipsCapacity();
820
  }
821
822
  public function shipsGetHoldFree() {
823
    return max(0, $this->shipsGetCapacity() - $this->resourcesGetTotal());
824
  }
825
826
  /**
827
   * Get count of ships with $ship_id
828
   *
829
   * @param int $ship_id
830
   *
831
   * @return int
832
   */
833
  public function shipsGetTotalById($ship_id) {
834
    return $this->unitList->unitsCountById($ship_id);
835
  }
836
837
  /**
838
   * Возвращает ёмкость переработчиков во флоте
839
   *
840
   * @param array $recycler_info
841
   *
842
   * @return int
843
   *
844
   * @version 41a6.87
845
   */
846
  public function shipsGetCapacityRecyclers(array $recycler_info) {
847
    $recyclers_incoming_capacity = 0;
848
    $fleet_data = $this->shipsGetArray();
849
    foreach ($recycler_info as $recycler_id => $recycler_data) {
850
      $recyclers_incoming_capacity += $fleet_data[$recycler_id] * $recycler_data['capacity'];
851
    }
852
853
    return $recyclers_incoming_capacity;
854
  }
855
856
  /**
857
   * @return bool
858
   */
859
  public function shipsIsEnoughOnPlanet() {
860
    return $this->unitList->shipsIsEnoughOnPlanet($this->fleet->dbSourcePlanetRow);
861
  }
862
863
  /**
864
   * @return bool
865
   */
866
  public function shipsAllPositive() {
867
    return $this->unitList->unitsPositive();
868
  }
869
870
  /**
871
   * @return bool
872
   */
873
  public function shipsAllFlying() {
874
    return $this->unitList->unitsInGroup(sn_get_groups(array('fleet', 'missile')));
875
  }
876
877
  /**
878
   * @return bool
879
   */
880
  public function shipsAllMovable() {
881
    return $this->unitList->unitsIsAllMovable($this->fleet->dbOwnerRow);
882
  }
883
884
  /**
885
   * Restores fleet or resources to planet
886
   *
887
   * @param bool $start
888
   * @param int  $result
889
   *
890
   * @return int
891
   */
892
  // TODO - split to functions
893
  public function shipsLand($start = true, &$result = CACHE_NOTHING) {
894
    sn_db_transaction_check(true);
895
896
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
897
    if ($this->isEmpty()) {
898
      return $result;
899
    }
900
901
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
902
903
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
904
    // TODO Проверить от многократного срабатывания !!!
905
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
906
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
907
908
    // Узнаем ИД владельца планеты.
909
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
910
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
911
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
912
    // Блокируем пользователя
913
    // TODO - вообще-то нам уже известен пользователь в МЛФ - так что можно просто передать его сюда
914
    $user = db_user_by_id($planet_arrival['id_owner'], true);
915
916
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
917
    // Флот, который возвращается на захваченную планету, пропадает
918
    // Ship landing is possible only to fleet owner's planet
919
    if ($this->getPlayerOwnerId() == $planet_arrival['id_owner']) {
920
      $db_changeset = array();
921
922
      $fleet_array = $this->shipsGetArray();
923
      foreach ($fleet_array as $ship_id => $ship_count) {
924
        if ($ship_count) {
925
          $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
926
        }
927
      }
928
929
      // Adjusting ship amount on planet
930
      if (!empty($db_changeset)) {
931
        db_changeset_apply($db_changeset);
932
      }
933
934
      // Restoring resources to planet
935
      $this->resourcesUnload($start, $result);
936
    }
937
938
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
939
940
    $result = RestoreFleetToPlanet($this, $start, $result);
941
942
    $this->dbDelete();
943
944
    return $result;
945
  }
946
947
948
  // Resources access ***************************************************************************************************
949
950
  /**
951
   * Extracts resources value from db_row
952
   *
953
   * @param array $db_row
954
   *
955
   * @internal param Fleet $that
956
   * @version 41a6.87
957
   */
958
  protected function resourcesExtract(array &$db_row) {
959
    $this->resource_list = array(
960
      RES_METAL     => !empty($db_row['fleet_resource_metal']) ? floor($db_row['fleet_resource_metal']) : 0,
961
      RES_CRYSTAL   => !empty($db_row['fleet_resource_crystal']) ? floor($db_row['fleet_resource_crystal']) : 0,
962
      RES_DEUTERIUM => !empty($db_row['fleet_resource_deuterium']) ? floor($db_row['fleet_resource_deuterium']) : 0,
963
    );
964
  }
965
966
  protected function resourcesInject(array &$db_row) {
967
    $db_row['fleet_resource_metal'] = $this->resource_list[RES_METAL];
968
    $db_row['fleet_resource_crystal'] = $this->resource_list[RES_CRYSTAL];
969
    $db_row['fleet_resource_deuterium'] = $this->resource_list[RES_DEUTERIUM];
970
  }
971
972
  /**
973
   * Set current resource list from array of units
974
   *
975
   * @param array $resource_list
976
   */
977
  public function resourcesSet($resource_list) {
978
    if (!empty($this->propertiesAdjusted['resource_list'])) {
979
      throw new PropertyAccessException('Property "resource_list" already was adjusted so no SET is possible until dbSave in ' . get_called_class() . '::unitSetResourceList', ERR_ERROR);
980
    }
981
    $this->resourcesAdjust($resource_list, true);
982
  }
983
984
  /**
985
   * Updates fleet resource list with deltas
986
   *
987
   * @param array $resource_delta_list
988
   * @param bool  $replace_value
989
   *
990
   * @throws Exception
991
   */
992
  public function resourcesAdjust($resource_delta_list, $replace_value = false) {
993
    !is_array($resource_delta_list) ? $resource_delta_list = array() : false;
994
995
    foreach ($resource_delta_list as $resource_id => $unit_delta) {
996
      if (!UnitResourceLoot::is_in_group($resource_id) || !($unit_delta = floor($unit_delta))) {
997
        // Not a resource or no resources - continuing
998
        continue;
999
      }
1000
1001
      if ($replace_value) {
1002
        $this->resource_list[$resource_id] = $unit_delta;
1003
      } else {
1004
        $this->resource_list[$resource_id] += $unit_delta;
1005
        // Preparing changes
1006
        $this->resource_delta[$resource_id] += $unit_delta;
1007
        $this->propertiesAdjusted['resource_list'] = 1;
1008
      }
1009
1010
      // Check for negative unit value
1011
      if ($this->resource_list[$resource_id] < 0) {
1012
        // TODO
1013
        throw new Exception('Resource ' . $resource_id . ' will become negative in ' . get_called_class() . '::unitAdjustResourceList', ERR_ERROR);
1014
      }
1015
    }
1016
  }
1017
1018
  public function resourcesGetTotal() {
1019
    return empty($this->resource_list) || !is_array($this->resource_list) ? 0 : array_sum($this->resource_list);
1020
  }
1021
1022
  /**
1023
   * @param array $rate
1024
   *
1025
   * @return float
1026
   */
1027
  public function resourcesGetTotalInMetal(array $rate) {
1028
    return
1029
      $this->resource_list[RES_METAL] * $rate[RES_METAL]
1030
      + $this->resource_list[RES_CRYSTAL] * $rate[RES_CRYSTAL] / $rate[RES_METAL]
1031
      + $this->resource_list[RES_DEUTERIUM] * $rate[RES_DEUTERIUM] / $rate[RES_METAL];
1032
  }
1033
1034
  /**
1035
   * Returns resource list in fleet
1036
   */
1037
  // TODO
1038
  public function resourcesGetList() {
1039
    return $this->resource_list;
1040
  }
1041
1042
  public function resourcesReset() {
1043
    $this->resourcesSet(array(
1044
      RES_METAL     => 0,
1045
      RES_CRYSTAL   => 0,
1046
      RES_DEUTERIUM => 0,
1047
    ));
1048
  }
1049
1050
  /**
1051
   * Restores fleet or resources to planet
1052
   *
1053
   * @param bool $start
1054
   * @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...
1055
   * @param int  $result
1056
   *
1057
   * @return int
1058
   */
1059
  public function resourcesUnload($start = true, &$result = CACHE_NOTHING) {
1060
    sn_db_transaction_check(true);
1061
1062
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
1063
    if (!$this->resourcesGetTotal()) {
1064
      return $result;
1065
    }
1066
1067
    $coordinates = $start ? $this->launch_coordinates_typed() : $this->target_coordinates_typed();
1068
1069
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
1070
    // TODO Проверить от многократного срабатывания !!!
1071
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
1072
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
1073
1074
1075
    // Узнаем ИД владельца планеты.
1076
    // С блокировкой, поскольку эта функция может быть вызвана только из менеджера летящих флотов.
1077
    // А там уже всё заблокировано как надо и повторная блокировка не вызовет дедлок.
1078
    $planet_arrival = db_planet_by_vector($coordinates, '', true);
1079
1080
    // TODO - Проверка, что планета всё еще существует на указанных координатах, а не телепортировалась, не удалена хозяином, не уничтожена врагом
1081
1082
    // Restoring resources to planet
1083
    if ($this->resourcesGetTotal()) {
1084
      $fleet_resources = $this->resourcesGetList();
1085
      db_planet_set_by_id($planet_arrival['id'],
1086
        "`metal` = `metal` + '{$fleet_resources[RES_METAL]}', `crystal` = `crystal` + '{$fleet_resources[RES_CRYSTAL]}', `deuterium` = `deuterium` + '{$fleet_resources[RES_DEUTERIUM]}'");
1087
    }
1088
1089
    $this->resourcesReset();
1090
    $this->markReturned();
1091
1092
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
1093
1094
    return $result;
1095
  }
1096
1097
1098
  protected function isResource($unit_id) {
1099
    return UnitResourceLoot::is_in_group($unit_id);
1100
  }
1101
1102
  /**
1103
   * @param int $speed_percent
1104
   *
1105
   * @return array
1106
   */
1107
  protected function flt_travel_data($speed_percent = 10) {
1108
    $distance = $this->targetVector->distanceFromCoordinates($this->dbSourcePlanetRow);
1109
1110
    return $this->unitList->travelData($speed_percent, $distance, $this->dbOwnerRow);
1111
  }
1112
1113
1114
  /**
1115
   * @param array  $dbPlayerRow
1116
   * @param array  $dbPlanetRow
1117
   * @param Vector $targetVector
1118
   *
1119
   */
1120
  public function initDefaults($dbPlayerRow, $dbPlanetRow, $targetVector, $mission, $ships, $fleet_group_mr, $oldSpeedInTens = 10, $targetedUnitId = 0) {
1121
    $objFleet5Player = new Player();
1122
    $objFleet5Player->dbRowParse($dbPlayerRow);
1123
    $this->setLocatedAt($objFleet5Player);
1124
1125
    $this->mission_type = $mission;
1126
1127
    $this->dbOwnerRow = $dbPlayerRow;
1128
1129
    $this->set_start_planet($dbPlanetRow);
1130
    $this->dbSourcePlanetRow = $dbPlanetRow;
1131
1132
    $this->setTargetFromVectorObject($targetVector);
1133
    $this->targetVector = $targetVector;
1134
1135
    $this->populateTargetPlanet();
1136
1137
    $this->unitsSetFromArray($ships);
1138
1139
    $this->_group_id = $fleet_group_mr;
1140
1141
    $this->oldSpeedInTens = $oldSpeedInTens;
1142
1143
    $this->targetedUnitId = $targetedUnitId;
1144
1145
    $this->renderParamCoordinates();
1146
1147
  }
1148
1149
  protected function restrictTargetTypeByMission() {
1150
    if ($this->_mission_type == MT_MISSILE) {
1151
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1152
    } elseif ($this->_mission_type == MT_COLONIZE || $this->_mission_type == MT_EXPLORE) {
1153
      // TODO - PT_NONE
1154
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET);
1155
    } elseif ($this->_mission_type == MT_RECYCLE) {
1156
      $this->allowed_planet_types = array(PT_DEBRIS => PT_DEBRIS);
1157
    } elseif ($this->_mission_type == MT_DESTROY) {
1158
      $this->allowed_planet_types = array(PT_MOON => PT_MOON);
1159
    } else {
1160
      $this->allowed_planet_types = array(PT_PLANET => PT_PLANET, PT_MOON => PT_MOON);
1161
    }
1162
  }
1163
1164
  protected function populateTargetPlanet() {
1165
    $targetPlanetCoords = $this->targetVector;
1166
    if ($this->mission_type != MT_NONE) {
1167
      $this->restrictTargetTypeByMission();
1168
1169
      // TODO - Нельзя тут просто менять тип планеты или координат!
1170
      // If current planet type is not allowed on mission - switch planet type
1171
      if (empty($this->allowed_planet_types[$this->targetVector->type])) {
1172
        $targetPlanetCoords->type = reset($this->allowed_planet_types);
1173
      }
1174
    }
1175
1176
    $this->dbTargetRow = db_planet_by_vector_object($targetPlanetCoords);
1177
  }
1178
1179
1180
  protected function printErrorIfNoShips() {
1181
    if ($this->unitList->unitsCount() <= 0) {
1182
      message(classLocale::$lang['fl_err_no_ships'], classLocale::$lang['fl_error'], 'fleet' . DOT_PHP_EX, 5);
1183
    }
1184
  }
1185
1186
  /**
1187
   */
1188
  public function renderParamCoordinates() {
1189
    global $template_result;
1190
    $template_result += array(
1191
      'thisgalaxy'      => $this->dbSourcePlanetRow['galaxy'],
1192
      'thissystem'      => $this->dbSourcePlanetRow['system'],
1193
      'thisplanet'      => $this->dbSourcePlanetRow['planet'],
1194
      'thisplanet_type' => $this->dbSourcePlanetRow['planet_type'],
1195
1196
      'galaxy'         => $this->targetVector->galaxy,
1197
      'system'         => $this->targetVector->system,
1198
      'planet'         => $this->targetVector->planet,
1199
      'planet_type'    => $this->targetVector->type,
1200
      'target_mission' => $this->_mission_type,
1201
      'MISSION_NAME'   => $this->_mission_type ? classLocale::$lang['type_mission'][$this->_mission_type] : '',
1202
1203
      'MT_COLONIZE' => MT_COLONIZE,
1204
    );
1205
  }
1206
1207
1208
  protected function renderFleetCoordinates($missionStartTimeStamp = SN_TIME_NOW, $timeMissionJob = 0) {
1209
    $timeToReturn = $this->travelData['duration'] * 2 + $timeMissionJob;
1210
1211
    return array(
1212
      'ID'                 => 1,
1213
      'START_TYPE_TEXT_SH' => classLocale::$lang['sys_planet_type_sh'][$this->dbSourcePlanetRow['planet_type']],
1214
      'START_COORDS'       => uni_render_coordinates($this->dbSourcePlanetRow),
1215
      'START_NAME'         => $this->dbSourcePlanetRow['name'],
1216
      'START_TIME_TEXT'    => date(FMT_DATE_TIME, $missionStartTimeStamp + $timeToReturn + SN_CLIENT_TIME_DIFF),
1217
      'START_LEFT'         => floor($this->travelData['duration'] * 2 + $timeMissionJob),
1218
      'END_TYPE_TEXT_SH'   =>
1219
        !empty($this->targetVector->type)
1220
          ? classLocale::$lang['sys_planet_type_sh'][$this->targetVector->type]
1221
          : '',
1222
      'END_COORDS'         => uniRenderVector($this->targetVector),
1223
      'END_NAME'           => !empty($this->dbTargetRow['name']) ? $this->dbTargetRow['name'] : '',
1224
      'END_TIME_TEXT'      => date(FMT_DATE_TIME, $missionStartTimeStamp + $this->travelData['duration'] + SN_CLIENT_TIME_DIFF),
1225
      'END_LEFT'           => floor($this->travelData['duration']),
1226
    );
1227
  }
1228
1229
  /**
1230
   * @param int $missionStartTimeStamp
1231
   * @param int $timeMissionJob
1232
   *
1233
   * @return array
1234
   *
1235
   * @throws Exception
1236
   */
1237
  protected function renderFleet($missionStartTimeStamp = SN_TIME_NOW, $timeMissionJob = 0) {
1238
    $this->printErrorIfNoShips();
1239
1240
    $result = $this->renderFleetCoordinates($missionStartTimeStamp, $timeMissionJob);
1241
    $result['.']['ships'] = $this->unitList->unitsRender();
1242
1243
    return $result;
1244
  }
1245
1246
  /**
1247
   * @return array
1248
   */
1249
  protected function renderAllowedMissions() {
1250
    $result = array();
1251
1252
    ksort($this->allowed_missions);
1253
    // If mission is not set - setting first mission from allowed
1254
    if (empty($this->_mission_type) && is_array($this->allowed_missions)) {
1255
      reset($this->allowed_missions);
1256
      $this->_mission_type = key($this->allowed_missions);
1257
    }
1258
    foreach ($this->allowed_missions as $key => $value) {
1259
      $result[] = array(
1260
        'ID'   => $key,
1261
        'NAME' => classLocale::$lang['type_mission'][$key],
1262
      );
1263
    };
1264
1265
    return $result;
1266
  }
1267
1268
  /**
1269
   * @param $max_duration
1270
   *
1271
   * @return array
1272
   */
1273
  protected function renderDuration($max_duration) {
1274
    $result = array();
1275
1276
    if (!$max_duration) {
1277
      return $result;
1278
    }
1279
1280
    $config_game_speed_expedition = ($this->_mission_type == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1);
1281
    for ($i = 1; $i <= $max_duration; $i++) {
1282
      $result[] = array(
1283
        'ID'   => $i,
1284
        'TIME' => pretty_time(ceil($i * 3600 / $config_game_speed_expedition)),
1285
      );
1286
    }
1287
1288
    return $result;
1289
  }
1290
1291
  /**
1292
   * @param array $planetResources
1293
   *
1294
   * @return array
1295
   */
1296
  // TODO - REDO to resource_id
1297
  protected function renderPlanetResources(&$planetResources) {
1298
    $result = array();
1299
1300
    $i = 0;
1301
    foreach ($planetResources as $resource_id => $resource_amount) {
1302
      $result[] = array(
1303
        'ID'        => $i++, // $resource_id,
1304
        'ON_PLANET' => $resource_amount,
1305
        'TEXT'      => pretty_number($resource_amount),
1306
        'NAME'      => classLocale::$lang['tech'][$resource_id],
1307
      );
1308
    }
1309
1310
    return $result;
1311
  }
1312
1313
  /**
1314
   * @return array
1315
   */
1316
  protected function renderAllowedPlanetTypes() {
1317
    $result = array();
1318
1319
    foreach ($this->allowed_planet_types as $possible_planet_type_id) {
1320
      $result[] = array(
1321
        'ID'         => $possible_planet_type_id,
1322
        'NAME'       => classLocale::$lang['sys_planet_type'][$possible_planet_type_id],
1323
        'NAME_SHORT' => classLocale::$lang['sys_planet_type_sh'][$possible_planet_type_id],
1324
      );
1325
    }
1326
1327
    return $result;
1328
  }
1329
1330
1331
  protected function renderFleet1TargetSelect(&$shortcut) {
1332
    global $note_priority_classes;
1333
1334
    $name = !empty($shortcut['title']) ? $shortcut['title'] : $shortcut['name'];
1335
1336
    $result = array(
1337
      'NAME'       => $name,
1338
      'GALAXY'     => $shortcut['galaxy'],
1339
      'SYSTEM'     => $shortcut['system'],
1340
      'PLANET'     => $shortcut['planet'],
1341
      'TYPE'       => $shortcut['planet_type'],
1342
      'TYPE_PRINT' => classLocale::$lang['fl_shrtcup'][$shortcut['planet_type']],
1343
    );
1344
1345
    if (isset($shortcut['priority'])) {
1346
      $result += array(
1347
        'PRIORITY'       => $shortcut['priority'],
1348
        'PRIORITY_CLASS' => $note_priority_classes[$shortcut['priority']],
1349
      );
1350
    }
1351
1352
    if (isset($shortcut['id'])) {
1353
      $result += array(
1354
        'ID' => $shortcut['id'],
1355
      );
1356
    }
1357
1358
    return $result;
1359
  }
1360
1361
  /**
1362
   * @return array
1363
   */
1364
  protected function renderFleetShortcuts() {
1365
    $result = array();
1366
1367
    // Building list of shortcuts
1368
    $query = db_note_list_select_by_owner_and_planet($this->dbOwnerRow);
1369
    while ($row = db_fetch($query)) {
1370
      $result[] = $this->renderFleet1TargetSelect($row);
1371
    }
1372
1373
    return $result;
1374
  }
1375
1376
  /**
1377
   * Building list of own planets & moons
1378
   *
1379
   * @return array
1380
   */
1381
  protected function renderOwnPlanets() {
1382
    $result = array();
1383
1384
    $colonies = db_planet_list_sorted($this->dbOwnerRow);
1385
    if (count($colonies) <= 1) {
1386
      return $result;
1387
    }
1388
1389
    foreach ($colonies as $row) {
1390
      if ($row['id'] == $this->dbSourcePlanetRow['id']) {
1391
        continue;
1392
      }
1393
1394
      $result[] = $this->renderFleet1TargetSelect($row);
1395
    }
1396
1397
    return $result;
1398
  }
1399
1400
  /**
1401
   * @return array
1402
   */
1403
  protected function renderACSList() {
1404
    $result = array();
1405
1406
    $query = db_acs_get_list();
1407
    while ($row = db_fetch($query)) {
1408
      $members = explode(',', $row['eingeladen']);
1409
      foreach ($members as $a => $b) {
1410
        if ($b == $this->dbOwnerRow['id']) {
1411
          $result[] = $this->renderFleet1TargetSelect($row);
1412
        }
1413
      }
1414
    }
1415
1416
    return $result;
1417
  }
1418
1419
1420
  /**
1421
   * @param $template_result
1422
   */
1423
  protected function renderShipSortOptions(&$template_result) {
1424
    foreach (classLocale::$lang['player_option_fleet_ship_sort'] as $sort_id => $sort_text) {
1425
      $template_result['.']['ship_sort_list'][] = array(
1426
        'VALUE' => $sort_id,
1427
        'TEXT'  => $sort_text,
1428
      );
1429
    }
1430
    $template_result += array(
1431
      'FLEET_SHIP_SORT'         => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT],
1432
      'FLEET_SHIP_SORT_INVERSE' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SORT_INVERSE],
1433
    );
1434
  }
1435
1436
1437
  /**
1438
   *
1439
   */
1440
  public function fleetPage0() {
1441
    global $template_result;
1442
1443
    lng_include('overview');
1444
1445
    if (empty($this->dbSourcePlanetRow)) {
1446
      message(classLocale::$lang['fl_noplanetrow'], classLocale::$lang['fl_error']);
1447
    }
1448
1449
    // TODO - redo to unitlist render/unit render
1450
    $this->renderAvailableShips($template_result, $this->dbOwnerRow, $this->dbSourcePlanetRow);
1451
1452
    $this->renderShipSortOptions($template_result);
1453
1454
    /**
1455
     * @var Player $playerOwner
1456
     */
1457
    $playerOwner = $this->getLocatedAt();
1458
1459
    $template_result += array(
1460
      'FLYING_FLEETS'      => $playerOwner->fleetsFlying(),
1461
      'MAX_FLEETS'         => $playerOwner->fleetsMax(),
1462
      'FREE_FLEETS'        => $playerOwner->fleetsMax() - $playerOwner->fleetsFlying(),
1463
      'FLYING_EXPEDITIONS' => $playerOwner->expeditionsFlying(),
1464
      'MAX_EXPEDITIONS'    => $playerOwner->expeditionsMax(),
1465
      'FREE_EXPEDITIONS'   => $playerOwner->expeditionsMax() - $playerOwner->expeditionsFlying(),
1466
      'COLONIES_CURRENT'   => $playerOwner->coloniesCurrent(),
1467
      'COLONIES_MAX'       => $playerOwner->coloniesMax(),
1468
1469
      'TYPE_NAME' => classLocale::$lang['fl_planettype'][$this->targetVector->type],
1470
1471
      'speed_factor' => flt_server_flight_speed_multiplier(),
1472
1473
      'PLANET_RESOURCES' => pretty_number($this->dbSourcePlanetRow['metal'] + $this->dbSourcePlanetRow['crystal'] + $this->dbSourcePlanetRow['deuterium']),
1474
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1475
1476
      'PLAYER_OPTION_FLEET_SHIP_SELECT_OLD'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_SELECT_OLD],
1477
      'PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED'       => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_SPEED],
1478
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY'    => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CAPACITY],
1479
      'PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION' => classSupernova::$user_options[PLAYER_OPTION_FLEET_SHIP_HIDE_CONSUMPTION],
1480
    );
1481
1482
    $template = gettemplate('fleet0', true);
1483
    $template->assign_recursive($template_result);
1484
    display($template, classLocale::$lang['fl_title']);
1485
  }
1486
1487
  /**
1488
   *
1489
   */
1490
  public function fleetPage1() {
1491
    global $template_result;
1492
1493
    $template_result['.']['fleets'][] = $this->renderFleet(SN_TIME_NOW);
1494
    $template_result['.']['possible_planet_type_id'] = $this->renderAllowedPlanetTypes();
1495
    $template_result['.']['colonies'] = $this->renderOwnPlanets();
1496
    $template_result['.']['shortcut'] = $this->renderFleetShortcuts();
1497
    $template_result['.']['acss'] = $this->renderACSList();
1498
1499
    $template_result += array(
1500
      'speed_factor' => flt_server_flight_speed_multiplier(),
1501
1502
      'fleet_speed'    => flt_fleet_speed($this->dbOwnerRow, $this->shipsGetArray()),
1503
      'fleet_capacity' => $this->shipsGetCapacity(),
1504
1505
      'PLANET_DEUTERIUM' => pretty_number($this->dbSourcePlanetRow['deuterium']),
1506
1507
      'PAGE_HINT' => classLocale::$lang['fl_page1_hint'],
1508
    );
1509
1510
    $template = gettemplate('fleet1', true);
1511
    $template->assign_recursive($template_result);
1512
    display($template, classLocale::$lang['fl_title']);
1513
  }
1514
1515
  /**
1516
   *
1517
   */
1518
  public function fleetPage2() {
1519
    global $template_result;
1520
1521
    $this->travelData = $this->flt_travel_data($this->oldSpeedInTens);
1522
    try {
1523
      $validator = new FleetValidator($this);
1524
      $validator->validate();
1525
    } catch (Exception $e) {
1526
      // TODO - MESSAGE BOX
1527
      sn_db_transaction_rollback();
1528
      pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
1529
    }
1530
1531
    // Flight allowed here
1532
    pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1533
1534
    $template_result['.']['missions'] = $this->renderAllowedMissions();
1535
1536
    $template_result['.']['fleets'][] = $this->renderFleet(SN_TIME_NOW);
1537
1538
    $max_duration =
1539
      $this->_mission_type == MT_EXPLORE
1540
        ? get_player_max_expedition_duration($this->dbOwnerRow)
1541
        : (isset($this->allowed_missions[MT_HOLD]) ? 12 : 0);
1542
    $template_result['.']['duration'] = $this->renderDuration($max_duration);
1543
1544
    $template_result += $this->renderCaptain();
1545
1546
    $planetResources = $this->resourcesGetOnPlanet();
1547
    $template_result['.']['resources'] = $this->renderPlanetResources($planetResources);
1548
1549
    $template_result += array(
1550
      'planet_metal'     => $planetResources[RES_METAL],
1551
      'planet_crystal'   => $planetResources[RES_CRYSTAL],
1552
      'planet_deuterium' => $planetResources[RES_DEUTERIUM],
1553
1554
      'fleet_capacity' => $this->shipsGetCapacity() - $this->travelData['consumption'],
1555
      'speed'          => $this->oldSpeedInTens,
1556
      'fleet_group'    => $this->_group_id,
1557
1558
      'MAX_DURATION'          => $max_duration,
1559
1560
      // 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...
1561
//      'IS_TRANSPORT_MISSIONS' => !empty($this->allowed_missions[$this->_mission_type]['transport']),
1562
      'IS_TRANSPORT_MISSIONS' => true,
1563
1564
      'PLAYER_COLONIES_CURRENT' => get_player_current_colonies($this->dbOwnerRow),
1565
      'PLAYER_COLONIES_MAX'     => get_player_max_colonies($this->dbOwnerRow),
1566
    );
1567
1568
    $template = gettemplate('fleet2', true);
1569
    $template->assign_recursive($template_result);
1570
    display($template, classLocale::$lang['fl_title']);
1571
  }
1572
1573
  /**
1574
   *
1575
   */
1576
  public function fleetPage3() {
1577
    global $template_result;
1578
1579
    $errorlist = ''; // TODO - DEPRECATED
1580
1581
    $this->isRealFlight = true;
1582
1583
    sn_db_transaction_start();
1584
1585
    db_user_lock_with_target_owner($this->dbOwnerRow, $this->dbTargetRow);
1586
1587
    $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...
1588
    $this->dbSourcePlanetRow = db_planet_by_id($this->dbSourcePlanetRow['id'], true);
1589
    if (!empty($this->dbTargetRow['id'])) {
1590
      $this->dbTargetRow = db_planet_by_id($this->dbTargetRow['id'], true);
1591
    }
1592
    if (!empty($this->dbTargetRow['id_owner'])) {
1593
      $this->dbTargetOwnerRow = db_planet_by_id($this->dbTargetRow['id_owner'], true);
1594
    }
1595
1596
    $this->resource_list = array(
1597
      RES_METAL     => max(0, floor(sys_get_param_float('resource0'))),
1598
      RES_CRYSTAL   => max(0, floor(sys_get_param_float('resource1'))),
1599
      RES_DEUTERIUM => max(0, floor(sys_get_param_float('resource2'))),
1600
    );
1601
1602
1603
    // TODO
1604
    $captain = array();
1605
    if ($captain_id = sys_get_param_id('captain_id')) {
0 ignored issues
show
Unused Code introduced by
$captain_id is not used, you could remove the assignment.

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

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

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

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

Loading history...
1606
      $captain = $this->captainGet();
1607
      if (empty($captain)) {
1608
        $errorlist .= classLocale::$lang['module_unit_captain_error_no_captain'];
1609
      } elseif ($captain['unit_location_type'] == LOC_PLANET) {
1610
        if ($this->_mission_type == MT_RELOCATE && ($arriving_captain = mrc_get_level($this->dbOwnerRow, $this->dbTargetRow, UNIT_CAPTAIN, true))) {
0 ignored issues
show
Security Bug introduced by
It seems like $this->dbOwnerRow can also be of type false; however, mrc_get_level() does only seem to accept array, did you maybe forget to handle an error condition?
Loading history...
1611
          $errorlist .= classLocale::$lang['module_unit_captain_error_captain_already_bound'];
1612
        }
1613
      } else {
1614
        $errorlist .= classLocale::$lang['module_unit_captain_error_captain_flying'];
1615
      }
1616
    }
1617
1618
    $this->travelData = $this->flt_travel_data($this->oldSpeedInTens);
1619
1620
    try {
1621
      $validator = new FleetValidator($this);
1622
      $validator->validate();
1623
    } catch (Exception $e) {
1624
      // TODO - MESSAGE BOX
1625
      sn_db_transaction_rollback();
1626
      pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
1627
    }
1628
1629
    // Flight allowed here
1630
    pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
1631
1632
1633
    // TODO check for empty mission AKA mission allowed
1634
1635
    if (array_sum($this->resource_list) < 1 && $this->_mission_type == MT_TRANSPORT) {
1636
      $errorlist .= classLocale::$lang['fl_noenoughtgoods'];
1637
    }
1638
1639
    if ($errorlist) {
1640
      sn_db_transaction_rollback();
1641
      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...
1642
    }
1643
1644
    //Normally... unless its acs...
1645
    $aks = 0;
1646
    //But is it acs??
1647
    //Well all acs fleets must have a fleet code.
1648
    //The co-ords must be the same as where the acs fleet is going.
1649
    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}") {
1650
      //ACS attack must exist (if acs fleet has arrived this will also return false (2 checks in 1!!!)
1651
      $aks = db_acs_get_by_group_id($this->_group_id);
1652
      if (!$aks) {
1653
        $this->_group_id = 0;
1654
      } else {
1655
        //Also it must be mission type 2
1656
        $this->_mission_type = MT_ACS;
1657
1658
1659
        $this->targetVector->galaxy = $aks['galaxy'];
1660
        $this->targetVector->system = $aks['system'];
1661
        $this->targetVector->planet = $aks['planet'];
1662
        $this->targetVector->type = $aks['planet_type'];
1663
      }
1664
    } elseif ($this->_mission_type == MT_ACS) {
1665
      //Check that a failed acs attack isn't being sent, if it is, make it an attack fleet.
1666
      $this->_mission_type = MT_ATTACK;
1667
    }
1668
1669
    $timeMissionJob = 0;
1670
    if ($this->_mission_type == MT_ACS && $aks) {
1671
      $acsTimeToArrive = $aks['ankunft'] - SN_TIME_NOW;
1672
      if ($acsTimeToArrive < $this->travelData['duration']) {
1673
        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']);
1674
      }
1675
      // Set time to travel to ACS' TTT
1676
      $this->travelData['duration'] = $acsTimeToArrive;
1677
    } else {
1678
      if ($this->_mission_type == MT_EXPLORE || $this->_mission_type == MT_HOLD) {
1679
        $max_duration = $this->_mission_type == MT_EXPLORE ? get_player_max_expedition_duration($this->dbOwnerRow) : ($this->_mission_type == MT_HOLD ? 12 : 0);
1680
        if ($max_duration) {
1681
          $mission_time_in_hours = sys_get_param_id('missiontime');
1682
          if ($mission_time_in_hours > $max_duration || $mission_time_in_hours < 1) {
1683
            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...
1684
            die();
1685
          }
1686
          $timeMissionJob = ceil($mission_time_in_hours * 3600 / ($this->_mission_type == MT_EXPLORE && classSupernova::$config->game_speed_expedition ? classSupernova::$config->game_speed_expedition : 1));
1687
        }
1688
      }
1689
    }
1690
1691
    //
1692
    //
1693
    //
1694
    //
1695
    //
1696
    //
1697
    //
1698
    //
1699
    // ---------------- END OF CHECKS ------------------------------------------------------
1700
1701
    $this->set_times($this->travelData['duration'], $timeMissionJob);
1702
    $this->dbInsert();
1703
1704
    db_planet_set_by_id($this->dbSourcePlanetRow['id'],
1705
      "`metal` = `metal` - {$this->resource_list[RES_METAL]},
1706
      `crystal` = `crystal` - {$this->resource_list[RES_CRYSTAL]},
1707
      `deuterium` = `deuterium` - {$this->resource_list[RES_DEUTERIUM]} - {$this->travelData['consumption']}"
1708
    );
1709
1710
    $db_changeset = $this->unitList->db_prepare_old_changeset_for_planet($this->dbOwnerRow, $this->dbSourcePlanetRow['id']);
1711
    db_changeset_apply($db_changeset);
1712
1713
1714
    if (!empty($captain['unit_id'])) {
1715
      db_unit_set_by_id($captain['unit_id'], "`unit_location_type` = " . LOC_FLEET . ", `unit_location_id` = {$this->_dbId}");
1716
    }
1717
1718
1719
    $template_result['.']['fleets'][] = $this->renderFleet(SN_TIME_NOW, $timeMissionJob);
1720
1721
    $template_result += array(
1722
      'mission'         => classLocale::$lang['type_mission'][$this->_mission_type] . ($this->_mission_type == MT_EXPLORE || $this->_mission_type == MT_HOLD ? ' ' . pretty_time($timeMissionJob) : ''),
1723
      'dist'            => pretty_number($this->travelData['distance']),
1724
      'speed'           => pretty_number($this->travelData['fleet_speed']),
1725
      'deute_need'      => pretty_number($this->travelData['consumption']),
1726
      'from'            => "{$this->dbSourcePlanetRow['galaxy']}:{$this->dbSourcePlanetRow['system']}:{$this->dbSourcePlanetRow['planet']}",
1727
      'time_go'         => date(FMT_DATE_TIME, $this->_time_arrive_to_target),
1728
      'time_go_local'   => date(FMT_DATE_TIME, $this->_time_arrive_to_target + SN_CLIENT_TIME_DIFF),
1729
      'time_back'       => date(FMT_DATE_TIME, $this->_time_return_to_source),
1730
      'time_back_local' => date(FMT_DATE_TIME, $this->_time_return_to_source + SN_CLIENT_TIME_DIFF),
1731
    );
1732
1733
    $this->dbSourcePlanetRow = db_planet_by_id($this->dbSourcePlanetRow['id']);
1734
1735
    pdie('Stop for debug');
1736
1737
    sn_db_transaction_commit();
1738
1739
    $template = gettemplate('fleet3', true);
1740
    $template->assign_recursive($template_result);
1741
    display($template, classLocale::$lang['fl_title']);
1742
  }
1743
1744
1745
  /**
1746
   * @return array
1747
   */
1748
  protected function resourcesGetOnPlanet() {
1749
    $planetResources = array();
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
  protected function captainGet() {
1759
    $result = array();
1760
1761
    /**
1762
     * @var unit_captain $moduleCaptain
1763
     */
1764
    $moduleCaptain = !empty(sn_module::$sn_module['unit_captain']) ? sn_module::$sn_module['unit_captain'] : null;
1765
1766
    if (
1767
      !empty($moduleCaptain)
1768
      &&
1769
      $moduleCaptain->manifest['active']
1770
    ) {
1771
      $result = $moduleCaptain->unit_captain_get($this->dbSourcePlanetRow['id']);
1772
    }
1773
1774
    return $result;
1775
  }
1776
1777
  /**
1778
   * @return array
1779
   */
1780
  protected function renderCaptain() {
1781
    $result = array();
1782
1783
    $captain = $this->captainGet();
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