Completed
Push — work-fleets ( 33857b...22a48f )
by SuperNova.WS
05:55
created

FleetValidator::checkMissionRestrictions()   D

Complexity

Conditions 9
Paths 11

Size

Total Lines 38
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 9
eloc 18
c 4
b 0
f 0
nc 11
nop 2
dl 0
loc 38
rs 4.909
ccs 0
cts 18
cp 0
crap 90
1
<?php
2
3
/**
4
 * Class FleetValidator
5
 */
6
class FleetValidator {
7
  /**
8
   * @var Fleet $fleet
9
   */
10
  protected $fleet;
11
12
  protected static $conditionsGlobal = array(
13
    // Cheap checks - class Fleet already have all this info internally
14
    'checkSpeedPercentOld'       => FLIGHT_FLEET_SPEED_WRONG,
15
    'checkTargetInUniverse'      => FLIGHT_VECTOR_BEYOND_UNIVERSE,
16
    'checkTargetNotSource'       => FLIGHT_VECTOR_SAME_SOURCE,
17
    'checkSenderNoVacation'      => FLIGHT_PLAYER_VACATION_OWN,  // tODO
18
    'checkTargetNoVacation'      => FLIGHT_PLAYER_VACATION,
19
    'checkFleetNotEmpty'         => FLIGHT_SHIPS_NO_SHIPS,
20
    // 'checkUnitsPositive'         => FLIGHT_SHIPS_NEGATIVE, // Unused - 'cause it's not allowed to put negative units into Unit class
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
21
    // 'checkOnlyFleetUnits'        => FLIGHT_SHIPS_UNIT_WRONG, // Unused - 'cause it's only possible to pass to fleet SHIP or RESOURCE
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
22
    'checkOnlyFlyingUnits'       => FLIGHT_SHIPS_UNMOVABLE,
23
    'checkResourcesPositive'     => FLIGHT_RESOURCES_NEGATIVE,
24
    'checkNotTooFar'             => FLIGHT_FLEET_TOO_FAR,
25
    'checkEnoughCapacity'        => FLIGHT_FLEET_OVERLOAD,
26
27
    // checkMissionAllowed
28
    // consumptionIsNegative ??????
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
29
30
    // Medium checks - currently requires access to DB but potentially doesn't
31
    'checkSourceEnoughShips'     => FLIGHT_SHIPS_NOT_ENOUGH,
32
    'checkSourceEnoughFuel'      => FLIGHT_RESOURCES_FUEL_NOT_ENOUGH,
33
    'checkSourceEnoughResources' => FLIGHT_RESOURCES_NOT_ENOUGH,
34
35
    'checkMultiAccountNot'            => FLIGHT_PLAYER_SAME_IP,
36
37
    // Heavy checks - will absolutely require DB access
38
    'checkEnoughFleetSlots'           => FLIGHT_FLEET_NO_SLOTS,
39
40
    // TODO - THIS CHECKS SHOULD BE ADDED IN UNIT_CAPTAIN MODULE!
41
    'checkCaptainSent'                => array(
42
      true => array(
43
        'checkCaptainExists'         => FLIGHT_CAPTAIN_NOT_HIRED,
44
        'checkCaptainOnPlanetType'   => FLIGHT_CAPTAIN_ALREADY_FLYING,
45
        'checkCaptainOnPlanetSource' => FLIGHT_CAPTAIN_ON_OTHER_PLANET,
46
        'checkCaptainNotRelocating'  => FLIGHT_CAPTAIN_RELOCATE_LOCK,
47
      ),
48
    ),
49
  );
50
51
52
  /**
53
   * FleetValidator constructor.
54
   *
55
   * @param Fleet $fleet
56
   */
57
  public function __construct($fleet) {
58
    $this->fleet = $fleet;
59
  }
60
61
  /**
62
   *
63
   */
64
  public function validateGlobals() {
65
//    print('Validate globals<br/>');
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...
66
    $this->checkMissionRestrictions(self::$conditionsGlobal);
67
//    print('Globals validated<br/>');
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...
68
69
//    try {
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% 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...
70
//      // TODO - Do the restrictMission checks
71
//
72
//      // TODO - Кое-какие проверки дают FLIGHT_ALLOWED - ЧТО НЕПРАВДА В ДАННОМ СЛУЧАЕ!!!
73
//      // На странице 1 некоторые проверки ДОЛЖНЫ БЫТЬ опущены - иначе будет некрасиво
74
//      // А вот здесь надо проверять много дополнительной хуйни
75
//      $this->checkMissionRestrictions($checklist);
76
////pdump('passed');
77
//
78
//      // 2nd level restrictions
79
//      // Still cheap
80
////      $this->restrict2ToAllowedMissions();
81
////      $this->restrict2ToAllowedPlanetTypes();
82
//    } catch (ExceptionFleetInvalid $e) {
83
////pdump($e->getCode(), '$e->getCode()');
84
////pdump($e->getMessage(), '$e->getMessage()');
85
//      if ($e->getCode() != FLIGHT_ALLOWED) {
86
//        pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
87
//      } else {
88
//        pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
89
//      }
90
//    }
91
  }
92
93
  /**
94
   *
95
   */
96
  public function validate() {
97
    $checklist = sn_get_groups('mission_checks');
98
99
    $this->checkMissionRestrictions($checklist);
100
101
//    try {
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% 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...
102
//      // TODO - Do the restrictMission checks
103
//
104
//      // TODO - Кое-какие проверки дают FLIGHT_ALLOWED - ЧТО НЕПРАВДА В ДАННОМ СЛУЧАЕ!!!
105
//      // На странице 1 некоторые проверки ДОЛЖНЫ БЫТЬ опущены - иначе будет некрасиво
106
//      // А вот здесь надо проверять много дополнительной хуйни
107
//      $this->checkMissionRestrictions($checklist);
108
////pdump('passed');
109
//
110
//      // 2nd level restrictions
111
//      // Still cheap
112
////      $this->restrict2ToAllowedMissions();
113
////      $this->restrict2ToAllowedPlanetTypes();
114
//    } catch (ExceptionFleetInvalid $e) {
115
////pdump($e->getCode(), '$e->getCode()');
116
////pdump($e->getMessage(), '$e->getMessage()');
117
//      if ($e->getCode() != FLIGHT_ALLOWED) {
118
//        pdie(classLocale::$lang['fl_attack_error'][$e->getCode()]);
119
//      } else {
120
//        pdump('FLIGHT_ALLOWED', FLIGHT_ALLOWED);
121
//      }
122
//    }
123
    pdump('// TODO - Сделать flletvalidator DI - внутре контейнер для методов, а методы - анонимные функции, вызывающие другие методы же', FLIGHT_ALLOWED);
124
  }
125
126
  /**
127
   * @param array $checklist
128
   *
129
   * @throws Exception
130
   */
131
  public function checkMissionRestrictions($checklist, $exception = true) {
132
    foreach ($checklist as $condition => $action) {
133
134
      $checkResult = call_user_func(array($this, $condition));
135
      defined('DEBUG_FLEET_MISSION_VALIDATE_DUMP_STEPS')
136
        ? pdump($action, $condition . ' ' . ($checkResult ? 'TRUE' : 'FALSE')) : false;
137
138
      // If check failed and there no alternative actions - throw exception
139
      // Shortcut ACTION => FAIL_STATUS instead of ACTION => array(false => FAIL_STATUS)
140
      if (!$checkResult && !is_array($action)) {
141
        throw new ExceptionFleetInvalid($action, $action);
142
      }
143
144
      // If no actions on current result - just skipping to next condition
145
      if (!isset($action[$checkResult])) {
146
        // If not - just continuing
147
        continue;
148
      }
149
150
      // Otherwise - we got some action for current result
151
      $action = $action[$checkResult];
152
153
      // Is it a list of conditions?
154
      if (is_array($action)) {
155
        // Yes - performing condition check
156
        $this->checkMissionRestrictions($action);
157
      } else {
158
        // No - then just performing action
159
        if($exception) {
160
          throw new ExceptionFleetInvalid($action, $action);
161
        } else {
162
          return $action;
163
        }
164
      }
165
    }
166
167
    return FLIGHT_ALLOWED;
168
  }
169
170
171
  /**
172
   * @throws Exception
173
   */
174
  protected function restrict2ToAllowedMissions() {
175
    if (empty($this->fleet->allowed_missions[$this->fleet->mission_type])) {
176
      throw new Exception('FLIGHT_MISSION_IMPOSSIBLE', FLIGHT_MISSION_IMPOSSIBLE);
177
    }
178
  }
179
180
  /**
181
   * @throws Exception
182
   */
183
  protected function restrict2ToAllowedPlanetTypes() {
184
    if (empty($this->fleet->allowed_planet_types[$this->fleet->targetVector->type])) {
185
      throw new Exception('FLIGHT_MISSION_IMPOSSIBLE', FLIGHT_MISSION_IMPOSSIBLE);
186
    }
187
  }
188
189
190
  /**
191
   * @return bool
192
   */
193
  protected function checkSpeedPercentOld() {
194
    return in_array($this->fleet->oldSpeedInTens, array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1));
195
  }
196
197
  /**
198
   * @return bool
199
   */
200
  protected function checkSenderNoVacation() {
201
    return empty($this->fleet->dbOwnerRow['vacation']) || $this->fleet->dbOwnerRow['vacation'] <= SN_TIME_NOW;
202
  }
203
204
  /**
205
   * @return bool
206
   */
207
  protected function checkTargetNoVacation() {
208
    return empty($this->fleet->dbTargetOwnerRow['vacation']) || $this->fleet->dbTargetOwnerRow['vacation'] >= SN_TIME_NOW;
209
  }
210
211
  /**
212
   * @return bool
213
   */
214
  protected function checkMultiAccountNot() {
215
    return !sys_is_multiaccount($this->fleet->dbOwnerRow, $this->fleet->dbTargetOwnerRow);
216
  }
217
218
  /**
219
   * @return bool
220
   */
221
  protected function checkTargetNotSource() {
222
    return !$this->fleet->targetVector->isSameLocation($this->fleet->dbSourcePlanetRow);
223
  }
224
225
  /**
226
   * @return bool
227
   */
228
  protected function checkTargetInUniverse() {
229
    return $this->fleet->targetVector->isInUniverse();
230
  }
231
232
  /**
233
   * @return bool
234
   */
235
  protected function checkUnitsPositive() {
236
    return $this->fleet->shipsAllPositive();
237
  }
238
239
  /**
240
   * @return bool
241
   */
242
  protected function checkOnlyFleetUnits() {
243
    return $this->fleet->shipsAllFlying();
244
  }
245
246
  /**
247
   * @return bool
248
   */
249
  protected function checkOnlyFlyingUnits() {
250
    return $this->fleet->shipsAllMovable();
251
  }
252
253
  /**
254
   * @return bool
255
   */
256
  protected function checkEnoughFleetSlots() {
257
    return FleetList::fleet_count_flying($this->fleet->getPlayerOwnerId()) < GetMaxFleets($this->fleet->dbOwnerRow);
258
  }
259
260
261
  /**
262
   * @return bool
263
   */
264
  protected function checkEnoughCapacity($includeResources = true) {
265
    $checkVia = $this->fleet->travelData['consumption'];
266
    $checkVia = ceil(($includeResources ? array_sum($this->fleet->resource_list) : 0) + $checkVia);
267
268
    return
269
      !empty($this->fleet->travelData) &&
270
      is_array($this->fleet->travelData) &&
271
      floor($this->fleet->travelData['capacity']) >= $checkVia;
272
  }
273
274
  /**
275
   * @return bool
276
   */
277
  protected function checkNotTooFar() {
278
    return $this->checkEnoughCapacity(false);
279
  }
280
281
  /**
282
   * @return bool
283
   */
284
  protected function checkDebrisExists() {
285
    return is_array($this->fleet->dbTargetRow) && ($this->fleet->dbTargetRow['debris_metal'] + $this->fleet->dbTargetRow['debris_crystal'] > 0);
286
  }
287
288
289
290
291
292
293
294
295
296
297
298
299
  // Resources checks
300
301
  /**
302
   * @return bool
303
   */
304
  protected function checkResourcesPositive() {
305
    foreach ($this->fleet->resource_list as $resourceId => $resourceAmount) {
306
      if ($resourceAmount < 0) {
307
        return false;
308
      }
309
    }
310
311
    return true;
312
  }
313
314
  /**
315
   * @return bool
316
   */
317
  protected function checkCargo() {
318
    return array_sum($this->fleet->resource_list) >= 1;
319
  }
320
321
  /**
322
   * @return bool
323
   */
324
  protected function checkSourceEnoughFuel() {
325
    $deuteriumOnPlanet = mrc_get_level($this->fleet->dbOwnerRow, $this->fleet->dbSourcePlanetRow, RES_DEUTERIUM);
326
327
    return $deuteriumOnPlanet > ceil($this->fleet->travelData['consumption']);
328
  }
329
330
  /**
331
   * @return bool
332
   */
333
  protected function checkSourceEnoughResources() {
334
    $fleetResources = $this->fleet->resource_list;
335
    $fleetResources[RES_DEUTERIUM] = ceil($fleetResources[RES_DEUTERIUM] + $this->fleet->travelData['consumption']);
336
    foreach ($fleetResources as $resourceId => $resourceAmount) {
337
      if (mrc_get_level($this->fleet->dbOwnerRow, $this->fleet->dbSourcePlanetRow, $resourceId) < ceil($fleetResources[$resourceId])) {
338
        return false;
339
      }
340
    }
341
342
    return true;
343
  }
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
  // Target vector checks (????????)
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
370
371
  /**
372
   * @return bool
373
   */
374
  protected function checkKnownSpace() {
375
    return $this->fleet->targetVector->isInKnownSpace();
376
  }
377
378
  /**
379
   * @return bool
380
   */
381
  protected function checkUnKnownSpace() {
382
    return !$this->checkKnownSpace();
383
  }
384
385
  /**
386
   * @return bool
387
   */
388
  protected function checkTargetExists() {
389
    return !empty($this->fleet->dbTargetRow['id']);
390
  }
391
392
  /**
393
   * @return bool
394
   */
395
  protected function checkTargetNotExists() {
396
    return !$this->checkTargetExists();
397
  }
398
399
  /**
400
   * @return bool
401
   */
402
  protected function checkTargetIsPlanet() {
403
    return $this->fleet->targetVector->type == PT_PLANET;
404
  }
405
406
  /**
407
   * @return bool
408
   */
409
  protected function checkTargetIsDebris() {
410
    return $this->fleet->targetVector->type == PT_DEBRIS;
411
  }
412
413
  /**
414
   * @return bool
415
   */
416
  protected function checkTargetIsMoon() {
417
    return $this->fleet->targetVector->type == PT_MOON;
418
  }
419
420
421
422
423
424
425
  // Ships checks
426
427
  /**
428
   * @return bool
429
   */
430
  protected function checkFleetNotEmpty() {
431
    return $this->fleet->shipsGetTotal() >= 1;
432
  }
433
434
435
  /**
436
   * @return bool
437
   */
438
  protected function checkSourceEnoughShips() {
439
    return $this->fleet->shipsIsEnoughOnPlanet();
440
  }
441
442
443
  /**
444
   * @return bool
445
   */
446
  protected function checkHaveColonizer() {
447
    // Colonization fleet should have at least one colonizer
448
    return $this->fleet->shipsGetTotalById(SHIP_COLONIZER) >= 1;
449
  }
450
451
  /**
452
   * @return bool
453
   */
454
  protected function checkHaveRecyclers() {
455
    $recyclers = 0;
456
    foreach (Fleet::$snGroupRecyclers as $recycler_id) {
457
      $recyclers += $this->fleet->shipsGetTotalById($recycler_id);
458
    }
459
460
    return $recyclers >= 1;
461
  }
462
463
  /**
464
   * @return bool
465
   */
466
  // TODO - used only as callable. Redo inversion
467
  protected function checkSpiesOnly() {
468
    return $this->fleet->shipsGetTotalById(SHIP_SPY) == $this->fleet->shipsGetTotal();
469
  }
470
471
  /**
472
   * @return bool
473
   */
474
  protected function checkNotOnlySpies() {
475
    return !$this->checkSpiesOnly();
476
  }
477
478
  /**
479
   * @return bool
480
   */
481
  protected function checkNoMissiles() {
482
    return
483
      $this->fleet->shipsGetTotalById(UNIT_DEF_MISSILE_INTERPLANET) == 0
484
      &&
485
      $this->fleet->shipsGetTotalById(UNIT_DEF_MISSILE_INTERCEPTOR) == 0;
486
  }
487
488
489
  /**
490
   * @return bool
491
   */
492
  protected function checkTargetOwn() {
493
    return $this->fleet->dbTargetRow['id_owner'] == $this->fleet->dbSourcePlanetRow['id_owner'];
494
  }
495
496
  /**
497
   * @return bool
498
   */
499
  protected function forceTargetOwn() {
500
    if ($result = $this->checkTargetOwn()) {
501
      unset($this->fleet->allowed_missions[MT_EXPLORE]);
502
      unset($this->fleet->allowed_missions[MT_COLONIZE]);
503
      unset($this->fleet->allowed_missions[MT_RECYCLE]);
504
      unset($this->fleet->allowed_missions[MT_MISSILE]);
505
506
      unset($this->fleet->allowed_missions[MT_SPY]);
507
508
      unset($this->fleet->allowed_missions[MT_ATTACK]);
509
      unset($this->fleet->allowed_missions[MT_ACS]);
510
      unset($this->fleet->allowed_missions[MT_DESTROY]);
511
    } else {
512
      unset($this->fleet->allowed_missions[MT_RELOCATE]);
513
    }
514
515
    return $result;
516
  }
517
518
  protected function checkMissionPeaceful() {
519
    return
520
      !$this->fleet->mission_type
521
      ||
522
      in_array($this->fleet->mission_type, array(
523
        MT_HOLD,
524
        MT_RELOCATE,
525
        MT_TRANSPORT,
526
      ));
527
  }
528
529
  /**
530
   * @return bool
531
   */
532
  protected function checkTargetOther() {
533
    return !$this->checkTargetOwn();
534
  }
535
536
537
  /**
538
   * @return bool
539
   */
540
  protected function alwaysFalse() {
541
    return false;
542
  }
543
544
545
  /**
546
   * @return bool
547
   */
548
  protected function checkTargetAllyDeposit() {
549
    $result = mrc_get_level($this->fleet->dbTargetOwnerRow, $this->fleet->dbTargetRow, STRUC_ALLY_DEPOSIT) >= 1;
550
    if (!$result) {
551
      unset($this->fleet->allowed_missions[MT_HOLD]);
552
    }
553
554
    return $result;
555
  }
556
557
  /**
558
   * @param int  $missionType
559
   * @param bool $exact
560
   *
561
   * @return bool
562
   */
563
  protected function checkMission($missionType, $exact = false) {
564
    return $this->fleet->mission_type == $missionType || (!$exact && $this->fleet->mission_type == MT_NONE);
565
  }
566
567
568
  /**
569
   * Check mission type OR no mission - and limits available missions to this type if positive
570
   *
571
   * @param int $missionType
572
   *
573
   * @return bool
574
   */
575
  protected function forceMission($missionType, $exact = false) {
576
    return $this->unsetMission($missionType, $this->checkMission($missionType, $exact), true);
577
  }
578
579
  protected function unsetMission($missionType, $result, $forceMission = false) {
580
    if (!$result) {
581
      unset($this->fleet->allowed_missions[$missionType]);
582
    } elseif ($forceMission) {
583
      $this->fleet->allowed_missions = array(
584
        $missionType => $this->fleet->exists_missions[$missionType],
585
      );
586
    }
587
588
    return $result;
589
  }
590
591
  /**
592
   * @param string $name
593
   * @param string $prefix
594
   *
595
   * @return int|false
596
   * @throws Exception
597
   */
598
  protected function checkMissionPrefix($name, $prefix) {
599
    $result = false;
600
    if (strpos($name, $prefix) === 0) {
601
      $mission = 'MT_' . strtoupper(substr($name, strlen($prefix)));
602
      if (!defined($mission)) {
603
        // TODO - Ну, как-то получше это обделать
604
        throw new Exception('Mission type "' . $mission . '" is not defined', FLIGHT_MISSION_UNKNOWN);
605
      }
606
607
      $result = constant($mission);
608
    }
609
610
    return $result;
611
  }
612
613
  public function __call($name, $arguments) {
614
    $result = null;
615
    if (($missionType = $this->checkMissionPrefix($name, 'unsetMission')) !== false) {
616
      $result = $this->unsetMission($missionType, false);
617
    } elseif (($missionType = $this->checkMissionPrefix($name, 'forceMissionExact')) !== false) {
618
      $result = $this->forceMission($missionType, true);
619
    } elseif (($missionType = $this->checkMissionPrefix($name, 'forceMission')) !== false) {
620
      $result = $this->forceMission($missionType, false);
621
    } elseif (($missionType = $this->checkMissionPrefix($name, 'checkMissionExact')) !== false) {
622
      $result = $this->checkMission($missionType, true);
623
    } elseif (($missionType = $this->checkMissionPrefix($name, 'checkMission')) !== false) {
624
      $result = $this->checkMission($missionType, false);
625
    }
626
627
    return $result;
628
  }
629
630
  /**
631
   * Just checks mission type
632
   *
633
   * @param int $missionType
634
   *
635
   * @return bool
636
   */
637
  // TODO - obsolete ??
638
  protected function checkMissionExact($missionType) {
639
    return $this->checkMission($missionType, true);
640
  }
641
642
643
  /**
644
   * @return bool
645
   */
646
  protected function checkNotEmptyMission() {
647
    return !empty($this->fleet->mission_type);
648
  }
649
650
  /**
651
   * @return bool
652
   */
653
  protected function checkRealFlight() {
654
    return $this->fleet->isRealFlight;
655
  }
656
657
658
  /**
659
   * @return bool
660
   */
661
  protected function unsetMissionSpyComplex() {
662
    unset($this->fleet->allowed_missions[MT_SPY]);
663
    if ($this->fleet->mission_type == MT_SPY) {
664
      if ($this->checkRealFlight()) {
665
        return false;
666
      }
667
      $this->fleet->mission_type = MT_NONE;
668
    }
669
670
    return true;
671
  }
672
673
674
  /**
675
   * @return bool
676
   */
677
  protected function checkMissionExists() {
678
    return !empty($this->fleet->exists_missions[$this->fleet->mission_type]);
679
  }
680
681
  /**
682
   * @return bool
683
   */
684
  protected function checkMissionAllowed() {
685
    return !empty($this->fleet->allowed_missions[$this->fleet->mission_type]);
686
  }
687
688
  /**
689
   * @return bool
690
   */
691
  protected function checkPlayerInactiveOrNotNoob() {
692
    return
693
      $this->checkTargetNotActive()
694
      ||
695
      $this->checkTargetNotNoob();
696
  }
697
698
  /**
699
   * @return bool
700
   */
701
  protected function checkTargetActive() {
702
    return
703
      empty($this->fleet->dbTargetOwnerRow['onlinetime'])
704
      ||
705
      SN_TIME_NOW - $this->fleet->dbTargetOwnerRow['onlinetime'] >= PLAYER_TIME_ACTIVE_SECONDS;
706
  }
707
708
  /**
709
   * @return bool
710
   */
711
  // TODO - REDO MAIN FUNCTION
712
  protected function checkTargetNotActive() {
713
    return !$this->checkTargetActive();
714
  }
715
716
717
  /**
718
   * @return bool
719
   */
720
  protected function checkSameAlly() {
721
    return !empty($this->fleet->dbTargetOwnerRow['ally_id']) && $this->fleet->dbTargetOwnerRow['ally_id'] == $this->fleet->dbOwnerRow['ally_id'];
722
  }
723
724
  /**
725
   * @return bool
726
   */
727
  protected function checkTargetNoob() {
728
    $user_points = $this->fleet->dbTargetOwnerRow['total_points'];
729
    $enemy_points = $this->fleet->dbTargetOwnerRow['total_points'];
730
731
    return
732
      // Target is under Noob Protection but Fleet owner is not
733
      (
734
        classSupernova::$config->game_noob_points
735
        &&
736
        $enemy_points <= classSupernova::$config->game_noob_points
737
        &&
738
        $user_points > classSupernova::$config->game_noob_points
739
      ) || (
740
        classSupernova::$config->game_noob_factor
741
        &&
742
        $user_points > $enemy_points * classSupernova::$config->game_noob_factor
743
      );
744
  }
745
746
  /**
747
   * @return bool
748
   */
749
  // TODO - REDO MAIN FUNCTION
750
  protected function checkTargetNotNoob() {
751
    return !$this->checkTargetNoob();
752
  }
753
754
755
  /**
756
   * @return bool
757
   */
758
  protected function checkMissionHoldReal() {
759
    return
760
      $this->checkRealFlight()
761
      &&
762
      $this->checkMissionExact(MT_HOLD);
763
  }
764
765
  /**
766
   * @return bool
767
   */
768
  protected function checkMissionHoldOnNotNoob() {
769
    return
770
      $this->checkTargetNotActive()
771
      ||
772
      ($this->checkSameAlly() && classSupernova::$config->ally_help_weak)
773
      ||
774
      $this->checkTargetNotNoob();
775
  }
776
777
778
  // Missiles
779
780
  /**
781
   * @return bool
782
   */
783
  protected function checkOnlyAttackMissiles() {
784
    $missilesAttack = $this->fleet->shipsGetTotalById(UNIT_DEF_MISSILE_INTERPLANET);
785
786
    return $missilesAttack != 0 && $missilesAttack == $this->fleet->shipsGetTotal();
787
  }
788
789
  /**
790
   * @return bool
791
   */
792
  protected function checkSiloLevel() {
793
    $sn_data_mip = get_unit_param(UNIT_DEF_MISSILE_INTERPLANET);
794
795
    return mrc_get_level($this->fleet->dbOwnerRow, $this->fleet->dbSourcePlanetRow, STRUC_SILO) >= $sn_data_mip[P_REQUIRE][STRUC_SILO];
796
  }
797
798
  /**
799
   * @return bool
800
   */
801
  protected function checkSameGalaxy() {
802
    return $this->fleet->targetVector->galaxy == $this->fleet->dbSourcePlanetRow['galaxy'];
803
  }
804
805
  /**
806
   * @return bool
807
   */
808
  protected function checkMissileDistance() {
809
    return abs($this->fleet->dbSourcePlanetRow['system'] - $this->fleet->targetVector->system) <= flt_get_missile_range($this->fleet->dbOwnerRow);
810
  }
811
812
  /**
813
   * @return bool
814
   */
815
  protected function checkMissileTarget() {
816
    return empty($this->fleet->targetedUnitId) || in_array($this->fleet->targetedUnitId, sn_get_groups('defense_active'));
817
  }
818
819
820
  /**
821
   * @return int
822
   */
823
  protected function checkExpeditionsMax() {
824
    return get_player_max_expeditons($this->fleet->dbOwnerRow) > 0;
825
  }
826
827
  /**
828
   * @return bool
829
   */
830
  protected function checkExpeditionsFree() {
831
    return get_player_max_expeditons($this->fleet->dbOwnerRow) > FleetList::fleet_count_flying($this->fleet->dbOwnerRow['id'], MT_EXPLORE);
832
  }
833
834
  /**
835
   * @return bool
836
   */
837
  protected function checkCaptainSent() {
838
    return $this->fleet->captainId >= 1;
839
  }
840
841
  /**
842
   * @return bool
843
   */
844
  protected function checkCaptainExists() {
845
    return !empty($this->fleet->captain) && is_array($this->fleet->captain);
846
  }
847
848
  /**
849
   * @return bool
850
   */
851
  protected function checkCaptainOnPlanetType() {
852
    return $this->fleet->captain['unit_location_type'] == $this->fleet->dbSourcePlanetRow['planet_type'];
853
  }
854
855
  /**
856
   * @return bool
857
   */
858
  protected function checkCaptainOnPlanetSource() {
859
    return $this->checkCaptainOnPlanetType() && $this->fleet->captain['unit_location_id'] == $this->fleet->dbSourcePlanetRow['id'];
860
  }
861
862
  /**
863
   * @return bool
864
   */
865
  protected function checkCaptainNotRelocating() {
866
    if ($this->fleet->mission_type == MT_RELOCATE) {
867
      $arriving_captain = mrc_get_level($this->fleet->dbOwnerRow, $this->fleet->dbTargetRow, UNIT_CAPTAIN, true);
868
    } else {
869
      $arriving_captain = false;
870
    }
871
872
    return empty($arriving_captain) || !is_array($arriving_captain);
873
  }
874
875
876
  /**
877
   * @return bool
878
   */
879
  protected function checkMissionDestroyReal() {
880
    return
881
      $this->checkRealFlight()
882
      &&
883
      $this->checkMissionExact(MT_DESTROY);
884
  }
885
886
  /**
887
   * @return bool
888
   */
889
  protected function checkHaveReapers() {
890
    $unitsTyped = 0;
891
    foreach (sn_get_groups('flt_reapers') as $unit_id) {
892
      $unitsTyped += $this->fleet->shipsGetTotalById($unit_id);
893
    }
894
895
    return $unitsTyped >= 1;
896
  }
897
898
899
  /**
900
   * @return bool
901
   */
902
  protected function checkMissionACSReal() {
903
    return
904
      $this->checkRealFlight()
905
      &&
906
      $this->checkMissionExact(MT_ACS);
907
  }
908
909
  protected function checkACSInTime() {
910
    return $this->fleet->acs['ankunft'] - $this->fleet->time_launch >= $this->fleet->travelData['duration'];
911
  }
912
913
914
  protected function checkMissionRealAndSelected($missionType) {
915
    return
916
      $this->checkRealFlight()
917
      &&
918
      $this->checkMissionExact($missionType);
919
  }
920
921
  protected function checkMissionResultAndUnset($missionType, $result, $forceMission = false) {
922
    $this->unsetMission($missionType, $result, $forceMission);
923
924
    return $result && $this->checkMissionRealAndSelected($missionType);
925
  }
926
927
928
  /**
929
   * @return bool
930
   */
931
  protected function checkMissionSpyPossibleAndReal() {
932
    return $this->checkMissionResultAndUnset(
933
      MT_SPY,
934
      $this->checkSpiesOnly() && $this->checkTargetOther(),
935
      true
936
    );
937
  }
938
939
  /**
940
   * @return bool
941
   */
942
  protected function checkMissionDestroyAndReal() {
943
    return $this->checkMissionResultAndUnset(
944
      MT_DESTROY,
945
      $this->checkTargetIsMoon() && $this->checkHaveReapers()
946
    );
947
  }
948
949
  /**
950
   * @return bool
951
   */
952
  protected function checkMissionHoldPossibleAndReal() {
953
    return $this->checkMissionResultAndUnset(
954
      MT_HOLD,
955
      $this->checkTargetAllyDeposit() && $this->checkMissionHoldOnNotNoob() && $this->checkNotOnlySpies()
956
    );
957
  }
958
959
  /**
960
   * @return bool
961
   */
962
  protected function checkSpiesOnlyFriendlyRestrictsToRelocate() {
963
    if ($result = $this->checkSpiesOnly()) {
964
      $this->fleet->allowed_missions = array(
965
        MT_RELOCATE => $this->fleet->exists_missions[MT_RELOCATE],
966
      );
967
    }
968
969
    return $result;
970
  }
971
972
973
  protected function checkFleetGroupACS() {
974
    $result = !empty($this->fleet->group_id) && !empty($this->fleet->acs);
975
    $this->unsetMission(MT_ACS, $result, true);
976
    if ($result) {
977
      $this->fleet->mission_type = MT_ACS;
978
    } else {
979
      $this->fleet->group_id = 0;
980
    }
981
982
    return $result;
983
  }
984
985
  protected function checkACSNotEmpty() {
986
    return !empty($this->fleet->acs);
987
  }
988
989
  /**
990
   * @return bool
991
   */
992
  protected function checkACSInvited() {
993
    $playersInvited = !empty($this->fleet->acs['eingeladen']) ? explode(',', $this->fleet->acs['eingeladen']) : array();
994
    foreach ($playersInvited as $playerId) {
995
      if (intval($playerId) == $this->fleet->dbOwnerRow['id']) {
996
        return true;
997
      }
998
    }
999
1000
    return false;
1001
  }
1002
1003
  /**
1004
   * @return bool
1005
   */
1006
  protected function checkMissionACSPossibleAndReal() {
1007
    return $this->checkMissionResultAndUnset(
1008
      MT_ACS,
1009
      $this->checkACSNotEmpty() && $this->checkACSInvited() && $this->checkACSInTime(),
1010
      true
1011
    );
1012
  }
1013
1014
  /**
1015
   * @return bool
1016
   */
1017
  protected function checkMissionTransportPossibleAndReal() {
1018
    return $this->checkMissionResultAndUnset(
1019
      MT_TRANSPORT,
1020
      $this->checkCargo() && $this->checkPlayerInactiveOrNotNoob() && $this->checkNotOnlySpies()
1021
    );
1022
  }
1023
1024
  /**
1025
   * @return bool
1026
   */
1027
  protected function checkMissionTransportReal() {
1028
    return
1029
      $this->checkMissionExact(MT_TRANSPORT)
1030
      &&
1031
      $this->checkRealFlight();
1032
  }
1033
1034
1035
  protected function checkBashingNotRestricted() {
1036
    return classSupernova::$config->fleet_bashing_attacks <= 0;
1037
  }
1038
1039
  protected function checkBashingBothAllies() {
1040
    return $this->fleet->dbOwnerRow['ally_id'] && $this->fleet->dbTargetOwnerRow['ally_id'];
1041
  }
1042
1043
  protected function checkBashingAlliesHaveRelationWar() {
1044
    return ali_relation($this->fleet->dbOwnerRow['ally_id'], $this->fleet->dbTargetOwnerRow['ally_id']) == ALLY_DIPLOMACY_WAR;
1045
  }
1046
1047
  protected function checkBashingBothAlliesAndRelationWar() {
1048
    return $this->checkBashingBothAllies() && $this->checkBashingAlliesHaveRelationWar();
1049
  }
1050
1051
  protected function checkBashingAlliesWarNoDelay() {
1052
    $user = $this->fleet->dbOwnerRow;
1053
    $enemy = $this->fleet->dbTargetOwnerRow;
1054
1055
    $relations = ali_relations($user['ally_id'], $enemy['ally_id']);
1056
1057
    return SN_TIME_NOW - $relations[$enemy['ally_id']]['alliance_diplomacy_time'] > classSupernova::$config->fleet_bashing_war_delay;
1058
  }
1059
1060
1061
  protected function checkBashingNone() {
1062
    $user = $this->fleet->dbOwnerRow;
1063
1064
    $time_limit = SN_TIME_NOW + $this->fleet->travelData['duration'] - classSupernova::$config->fleet_bashing_scope;
1065
    $bashing_list = array(SN_TIME_NOW);
1066
1067
    // Retrieving flying fleets
1068
    $objFleetsBashing = FleetList::dbGetFleetListBashing($user['id'], $this->fleet->dbTargetRow);
1069 View Code Duplication
    foreach ($objFleetsBashing->_container as $fleetBashing) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1070
      // Checking for ACS - each ACS count only once
1071
      if ($fleetBashing->group_id) {
1072
        $bashing_list["{$user['id']}_{$fleetBashing->group_id}"] = $fleetBashing->time_arrive_to_target;
1073
      } else {
1074
        $bashing_list[] = $fleetBashing->time_arrive_to_target;
1075
      }
1076
    }
1077
1078
    // Check for joining to ACS - if there are already fleets in ACS no checks should be done
1079
    if ($this->fleet->mission_type == MT_ACS && $bashing_list["{$user['id']}_{$this->fleet->group_id}"]) {
1080
      return true;
1081
    }
1082
1083
    $query = DBStaticFleetBashing::db_bashing_list_get($user, $this->fleet->dbTargetRow, $time_limit);
1084
    while ($bashing_row = db_fetch($query)) {
1085
      $bashing_list[] = $bashing_row['bashing_time'];
1086
    }
1087
1088
    sort($bashing_list);
1089
1090
    $last_attack = 0;
1091
    $wave = 0;
1092
    $attack = 1;
1093
    foreach ($bashing_list as &$bash_time) {
1094
      $attack++;
1095
      if (
1096
        $bash_time - $last_attack > classSupernova::$config->fleet_bashing_interval
1097
        ||
1098
        $attack > classSupernova::$config->fleet_bashing_attacks
1099
      ) {
1100
        $wave++;
1101
        $attack = 1;
1102
      }
1103
1104
      $last_attack = $bash_time;
1105
    }
1106
1107
    return $wave <= classSupernova::$config->fleet_bashing_waves;
1108
  }
1109
1110
}
1111