-
Notifications
You must be signed in to change notification settings - Fork 15
/
AbstractSmrPlayer.php
3344 lines (2935 loc) · 112 KB
/
AbstractSmrPlayer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php declare(strict_types=1);
require_once('missions.inc.php');
use Smr\BountyType;
use Smr\Database;
use Smr\DatabaseRecord;
use Smr\DisplayNameValidator;
use Smr\Epoch;
use Smr\Exceptions\AccountNotFound;
use Smr\Exceptions\PlayerNotFound;
use Smr\Exceptions\UserError;
use Smr\Messages;
use Smr\Path;
use Smr\Race;
use Smr\ScoutMessageGroupType;
use Smr\TurnsLevel;
abstract class AbstractSmrPlayer {
use Traits\RaceID;
protected const TIME_FOR_FEDERAL_BOUNTY_ON_PR = 10800;
protected const TIME_FOR_ALLIANCE_SWITCH = 0;
protected const SHIP_INSURANCE_FRACTION = 0.25; // ship value regained on death
protected const HOF_CHANGED = 1;
protected const HOF_NEW = 2;
/** @var array<int, array<int, array<int, SmrPlayer>>> */
protected static array $CACHE_SECTOR_PLAYERS = [];
/** @var array<int, array<int, array<int, SmrPlayer>>> */
protected static array $CACHE_PLANET_PLAYERS = [];
/** @var array<int, array<int, array<int, SmrPlayer>>> */
protected static array $CACHE_ALLIANCE_PLAYERS = [];
/** @var array<int, array<int, SmrPlayer>> */
protected static array $CACHE_PLAYERS = [];
protected Database $db;
protected readonly string $SQL;
protected string $playerName;
protected int $playerID;
protected int $sectorID;
protected int $lastSectorID;
protected int $newbieTurns;
protected bool $dead;
protected bool $npc = false; // initialized for legacy combat logs
protected bool $newbieStatus;
protected bool $newbieWarning;
protected bool $landedOnPlanet;
protected int $lastActive;
protected int $credits;
protected int $alignment;
protected int $experience;
protected ?int $level;
protected int $allianceID;
protected int $shipID;
protected int $kills;
protected int $deaths;
protected int $assists;
/** @var array<int, int> */
protected array $personalRelations;
/** @var array<int, int> */
protected array $relations;
protected int $militaryPayment;
/** @var array<int, array<string, mixed>> */
protected array $bounties;
protected int $turns;
protected int $lastCPLAction;
/** @var array<int, array<string, mixed>> */
protected array $missions;
/** @var array<string, array<string, mixed>> */
protected array $tickers;
protected int $lastTurnUpdate;
protected int $lastNewsUpdate;
protected string $attackColour;
protected int $allianceJoinable;
protected int $lastPort;
protected int $bank;
protected int $zoom;
protected bool $displayMissions;
protected bool $displayWeapons;
protected bool $forceDropMessages;
protected ScoutMessageGroupType $scoutMessageGroupType;
protected bool $ignoreGlobals;
protected ?Path $plottedCourse;
protected bool $nameChanged;
protected bool $raceChanged;
protected bool $combatDronesKamikazeOnMines;
protected string|false $customShipName;
/** @var array<array<string, mixed>> */
protected array $storedDestinations;
/** @var array<int, bool> */
protected array $canFed;
protected bool $underAttack;
/** @var array<int> */
protected array $unvisitedSectors;
/** @var array<int, int> */
protected array $allianceRoles = [
0 => 0,
];
protected bool $draftLeader;
protected string|false $gpWriter;
/** @var array<string, float> */
protected array $HOF;
/** @var array<string, string> */
protected static array $HOFVis;
protected bool $hasChanged = false;
/** @var array<string, int> */
protected array $hasHOFChanged = [];
/** @var array<string, int> */
protected static array $hasHOFVisChanged = [];
/** @var array<int, bool> */
protected array $hasBountyChanged = [];
public static function clearCache(): void {
self::$CACHE_PLAYERS = [];
self::$CACHE_SECTOR_PLAYERS = [];
self::$CACHE_PLANET_PLAYERS = [];
self::$CACHE_ALLIANCE_PLAYERS = [];
}
public static function savePlayers(): void {
foreach (self::$CACHE_PLAYERS as $gamePlayers) {
foreach ($gamePlayers as $player) {
$player->save();
}
}
}
/**
* @param array<int> $allianceIDs
* @return array<int, SmrPlayer>
*/
public static function getSectorPlayersByAlliances(int $gameID, int $sectorID, array $allianceIDs, bool $forceUpdate = false): array {
$players = self::getSectorPlayers($gameID, $sectorID, $forceUpdate); // Don't use & as we do an unset
foreach ($players as $accountID => $player) {
if (!in_array($player->getAllianceID(), $allianceIDs)) {
unset($players[$accountID]);
}
}
return $players;
}
/**
* Returns the same players as getSectorPlayers (e.g. not on planets),
* but for an entire galaxy rather than a single sector. This is useful
* for reducing the number of queries in galaxy-wide processing.
*
* @return array<int, array<int, SmrPlayer>>
*/
public static function getGalaxyPlayers(int $gameID, int $galaxyID, bool $forceUpdate = false): array {
$db = Database::getInstance();
$dbResult = $db->read('SELECT player.* FROM player LEFT JOIN sector USING(game_id, sector_id) WHERE game_id = ' . $db->escapeNumber($gameID) . ' AND land_on_planet = ' . $db->escapeBoolean(false) . ' AND (last_cpl_action > ' . $db->escapeNumber(Epoch::time() - TIME_BEFORE_HIDDEN) . ' OR newbie_turns = 0) AND galaxy_id = ' . $db->escapeNumber($galaxyID));
$galaxyPlayers = [];
foreach ($dbResult->records() as $dbRecord) {
$sectorID = $dbRecord->getInt('sector_id');
$accountID = $dbRecord->getInt('account_id');
$player = self::getPlayer($accountID, $gameID, $forceUpdate, $dbRecord);
self::$CACHE_SECTOR_PLAYERS[$gameID][$sectorID][$accountID] = $player;
$galaxyPlayers[$sectorID][$accountID] = $player;
}
return $galaxyPlayers;
}
/**
* @return array<int, SmrPlayer>
*/
public static function getSectorPlayers(int $gameID, int $sectorID, bool $forceUpdate = false): array {
if ($forceUpdate || !isset(self::$CACHE_SECTOR_PLAYERS[$gameID][$sectorID])) {
$db = Database::getInstance();
$dbResult = $db->read('SELECT * FROM player WHERE sector_id = ' . $db->escapeNumber($sectorID) . ' AND game_id=' . $db->escapeNumber($gameID) . ' AND land_on_planet = ' . $db->escapeBoolean(false) . ' AND (last_cpl_action > ' . $db->escapeNumber(Epoch::time() - TIME_BEFORE_HIDDEN) . ' OR newbie_turns = 0) AND account_id NOT IN (' . $db->escapeArray(Globals::getHiddenPlayers()) . ') ORDER BY last_cpl_action DESC');
$players = [];
foreach ($dbResult->records() as $dbRecord) {
$accountID = $dbRecord->getInt('account_id');
$players[$accountID] = self::getPlayer($accountID, $gameID, $forceUpdate, $dbRecord);
}
self::$CACHE_SECTOR_PLAYERS[$gameID][$sectorID] = $players;
}
return self::$CACHE_SECTOR_PLAYERS[$gameID][$sectorID];
}
/**
* @return array<int, SmrPlayer>
*/
public static function getPlanetPlayers(int $gameID, int $sectorID, bool $forceUpdate = false): array {
if ($forceUpdate || !isset(self::$CACHE_PLANET_PLAYERS[$gameID][$sectorID])) {
$db = Database::getInstance();
$dbResult = $db->read('SELECT * FROM player WHERE sector_id = ' . $db->escapeNumber($sectorID) . ' AND game_id=' . $db->escapeNumber($gameID) . ' AND land_on_planet = ' . $db->escapeBoolean(true) . ' AND account_id NOT IN (' . $db->escapeArray(Globals::getHiddenPlayers()) . ') ORDER BY last_cpl_action DESC');
$players = [];
foreach ($dbResult->records() as $dbRecord) {
$accountID = $dbRecord->getInt('account_id');
$players[$accountID] = self::getPlayer($accountID, $gameID, $forceUpdate, $dbRecord);
}
self::$CACHE_PLANET_PLAYERS[$gameID][$sectorID] = $players;
}
return self::$CACHE_PLANET_PLAYERS[$gameID][$sectorID];
}
/**
* @return array<int, SmrPlayer>
*/
public static function getAlliancePlayers(int $gameID, int $allianceID, bool $forceUpdate = false): array {
if ($forceUpdate || !isset(self::$CACHE_ALLIANCE_PLAYERS[$gameID][$allianceID])) {
$db = Database::getInstance();
$dbResult = $db->read('SELECT * FROM player WHERE alliance_id = ' . $db->escapeNumber($allianceID) . ' AND game_id=' . $db->escapeNumber($gameID) . ' ORDER BY experience DESC');
$players = [];
foreach ($dbResult->records() as $dbRecord) {
$accountID = $dbRecord->getInt('account_id');
$players[$accountID] = self::getPlayer($accountID, $gameID, $forceUpdate, $dbRecord);
}
self::$CACHE_ALLIANCE_PLAYERS[$gameID][$allianceID] = $players;
}
return self::$CACHE_ALLIANCE_PLAYERS[$gameID][$allianceID];
}
public static function getPlayer(int $accountID, int $gameID, bool $forceUpdate = false, DatabaseRecord $dbRecord = null): SmrPlayer {
if ($forceUpdate || !isset(self::$CACHE_PLAYERS[$gameID][$accountID])) {
self::$CACHE_PLAYERS[$gameID][$accountID] = new SmrPlayer($gameID, $accountID, $dbRecord);
}
return self::$CACHE_PLAYERS[$gameID][$accountID];
}
public static function getPlayerByPlayerID(int $playerID, int $gameID, bool $forceUpdate = false): SmrPlayer {
$db = Database::getInstance();
$dbResult = $db->read('SELECT * FROM player WHERE game_id = ' . $db->escapeNumber($gameID) . ' AND player_id = ' . $db->escapeNumber($playerID));
if ($dbResult->hasRecord()) {
$dbRecord = $dbResult->record();
return self::getPlayer($dbRecord->getInt('account_id'), $gameID, $forceUpdate, $dbRecord);
}
throw new PlayerNotFound('Player ID not found.');
}
public static function getPlayerByPlayerName(string $playerName, int $gameID, bool $forceUpdate = false): SmrPlayer {
$db = Database::getInstance();
$dbResult = $db->read('SELECT * FROM player WHERE game_id = ' . $db->escapeNumber($gameID) . ' AND player_name = ' . $db->escapeString($playerName));
if ($dbResult->hasRecord()) {
$dbRecord = $dbResult->record();
return self::getPlayer($dbRecord->getInt('account_id'), $gameID, $forceUpdate, $dbRecord);
}
throw new PlayerNotFound('Player Name not found.');
}
protected function __construct(
protected readonly int $gameID,
protected readonly int $accountID,
DatabaseRecord $dbRecord = null
) {
$this->db = Database::getInstance();
$this->SQL = 'account_id = ' . $this->db->escapeNumber($accountID) . ' AND game_id = ' . $this->db->escapeNumber($gameID);
if ($dbRecord === null) {
$dbResult = $this->db->read('SELECT * FROM player WHERE ' . $this->SQL);
if ($dbResult->hasRecord()) {
$dbRecord = $dbResult->record();
}
}
if ($dbRecord === null) {
throw new PlayerNotFound('Invalid accountID: ' . $accountID . ' OR gameID: ' . $gameID);
}
$this->playerName = $dbRecord->getString('player_name');
$this->playerID = $dbRecord->getInt('player_id');
$this->sectorID = $dbRecord->getInt('sector_id');
$this->lastSectorID = $dbRecord->getInt('last_sector_id');
$this->turns = $dbRecord->getInt('turns');
$this->lastTurnUpdate = $dbRecord->getInt('last_turn_update');
$this->newbieTurns = $dbRecord->getInt('newbie_turns');
$this->lastNewsUpdate = $dbRecord->getInt('last_news_update');
$this->attackColour = $dbRecord->getString('attack_warning');
$this->dead = $dbRecord->getBoolean('dead');
$this->npc = $dbRecord->getBoolean('npc');
$this->newbieStatus = $dbRecord->getBoolean('newbie_status');
$this->landedOnPlanet = $dbRecord->getBoolean('land_on_planet');
$this->lastActive = $dbRecord->getInt('last_active');
$this->lastCPLAction = $dbRecord->getInt('last_cpl_action');
$this->raceID = $dbRecord->getInt('race_id');
$this->credits = $dbRecord->getInt('credits');
$this->experience = $dbRecord->getInt('experience');
$this->alignment = $dbRecord->getInt('alignment');
$this->militaryPayment = $dbRecord->getInt('military_payment');
$this->allianceID = $dbRecord->getInt('alliance_id');
$this->allianceJoinable = $dbRecord->getInt('alliance_join');
$this->shipID = $dbRecord->getInt('ship_type_id');
$this->kills = $dbRecord->getInt('kills');
$this->deaths = $dbRecord->getInt('deaths');
$this->assists = $dbRecord->getInt('assists');
$this->lastPort = $dbRecord->getInt('last_port');
$this->bank = $dbRecord->getInt('bank');
$this->zoom = $dbRecord->getInt('zoom');
$this->displayMissions = $dbRecord->getBoolean('display_missions');
$this->displayWeapons = $dbRecord->getBoolean('display_weapons');
$this->forceDropMessages = $dbRecord->getBoolean('force_drop_messages');
$this->scoutMessageGroupType = ScoutMessageGroupType::from($dbRecord->getString('group_scout_messages'));
$this->ignoreGlobals = $dbRecord->getBoolean('ignore_globals');
$this->newbieWarning = $dbRecord->getBoolean('newbie_warning');
$this->nameChanged = $dbRecord->getBoolean('name_changed');
$this->raceChanged = $dbRecord->getBoolean('race_changed');
$this->combatDronesKamikazeOnMines = $dbRecord->getBoolean('combat_drones_kamikaze_on_mines');
$this->underAttack = $dbRecord->getBoolean('under_attack');
}
/**
* Insert a new player into the database. Returns the new player object.
*/
public static function createPlayer(int $accountID, int $gameID, string $playerName, int $raceID, bool $isNewbie, bool $npc = false): self {
$time = Epoch::time();
$db = Database::getInstance();
$db->lockTable('player');
// Player names must be unique within each game
try {
self::getPlayerByPlayerName($playerName, $gameID);
$db->unlock();
throw new UserError('That player name already exists.');
} catch (PlayerNotFound) {
// Player name does not yet exist, we may proceed
}
// Get the next available player ID (start at 1 if no players yet)
$dbResult = $db->read('SELECT IFNULL(MAX(player_id), 0) AS player_id FROM player WHERE game_id = ' . $db->escapeNumber($gameID));
$playerID = $dbResult->record()->getInt('player_id') + 1;
$startSectorID = 0; // Temporarily put player into non-existent sector
$db->insert('player', [
'account_id' => $db->escapeNumber($accountID),
'game_id' => $db->escapeNumber($gameID),
'player_id' => $db->escapeNumber($playerID),
'player_name' => $db->escapeString($playerName),
'race_id' => $db->escapeNumber($raceID),
'sector_id' => $db->escapeNumber($startSectorID),
'last_cpl_action' => $db->escapeNumber($time),
'last_active' => $db->escapeNumber($time),
'npc' => $db->escapeBoolean($npc),
'newbie_status' => $db->escapeBoolean($isNewbie),
]);
$db->unlock();
$player = self::getPlayer($accountID, $gameID);
$player->setSectorID($player->getHome());
return $player;
}
/**
* Get array of players whose info can be accessed by this player.
* Skips players who are not in the same alliance as this player.
*
* @return array<AbstractSmrPlayer>
*/
public function getSharingPlayers(bool $forceUpdate = false): array {
$results = [$this];
// Only return this player if not in an alliance
if (!$this->hasAlliance()) {
return $results;
}
// Get other players who are sharing info for this game.
// NOTE: game_id=0 means that player shares info for all games.
$dbResult = $this->db->read('SELECT from_account_id FROM account_shares_info WHERE to_account_id=' . $this->db->escapeNumber($this->getAccountID()) . ' AND (game_id=0 OR game_id=' . $this->db->escapeNumber($this->getGameID()) . ')');
foreach ($dbResult->records() as $dbRecord) {
try {
$otherPlayer = self::getPlayer($dbRecord->getInt('from_account_id'), $this->getGameID(), $forceUpdate);
} catch (PlayerNotFound) {
// Skip players that have not joined this game
continue;
}
// players must be in the same alliance
if ($this->sameAlliance($otherPlayer)) {
$results[] = $otherPlayer;
}
}
return $results;
}
public function getSQL(): string {
return $this->SQL;
}
public function getZoom(): int {
return $this->zoom;
}
protected function setZoom(int $zoom): void {
// Set the zoom level between [1, 9]
$zoom = max(1, min(9, $zoom));
if ($this->zoom == $zoom) {
return;
}
$this->zoom = $zoom;
$this->hasChanged = true;
}
public function increaseZoom(int $zoom): void {
if ($zoom < 0) {
throw new Exception('Trying to increase negative zoom.');
}
$this->setZoom($this->getZoom() + $zoom);
}
public function decreaseZoom(int $zoom): void {
if ($zoom < 0) {
throw new Exception('Trying to decrease negative zoom.');
}
$this->setZoom($this->getZoom() - $zoom);
}
public function getAttackColour(): string {
return $this->attackColour;
}
public function setAttackColour(string $colour): void {
if ($this->attackColour == $colour) {
return;
}
$this->attackColour = $colour;
$this->hasChanged = true;
}
public function isIgnoreGlobals(): bool {
return $this->ignoreGlobals;
}
public function setIgnoreGlobals(bool $bool): void {
if ($this->ignoreGlobals == $bool) {
return;
}
$this->ignoreGlobals = $bool;
$this->hasChanged = true;
}
public function getAccount(): SmrAccount {
return SmrAccount::getAccount($this->getAccountID());
}
public function getAccountID(): int {
return $this->accountID;
}
public function getGameID(): int {
return $this->gameID;
}
public function getGame(bool $forceUpdate = false): SmrGame {
return SmrGame::getGame($this->gameID, $forceUpdate);
}
public function getNewbieTurns(): int {
return $this->newbieTurns;
}
public function hasNewbieTurns(): bool {
return $this->getNewbieTurns() > 0;
}
public function setNewbieTurns(int $newbieTurns): void {
if ($this->newbieTurns == $newbieTurns) {
return;
}
$this->newbieTurns = $newbieTurns;
$this->hasChanged = true;
}
public function getShip(bool $forceUpdate = false): AbstractSmrShip {
return SmrShip::getShip($this, $forceUpdate);
}
public function getShipTypeID(): int {
return $this->shipID;
}
/**
* Do not call directly. Use SmrShip::setTypeID instead.
*/
public function setShipTypeID(int $shipID): void {
if ($this->shipID == $shipID) {
return;
}
$this->shipID = $shipID;
$this->hasChanged = true;
}
public function hasCustomShipName(): bool {
return $this->getCustomShipName() !== false;
}
public function getCustomShipName(): string|false {
if (!isset($this->customShipName)) {
$dbResult = $this->db->read('SELECT * FROM ship_has_name WHERE ' . $this->SQL);
if ($dbResult->hasRecord()) {
$this->customShipName = $dbResult->record()->getString('ship_name');
} else {
$this->customShipName = false;
}
}
return $this->customShipName;
}
public function setCustomShipName(string $name): void {
$this->db->replace('ship_has_name', [
'game_id' => $this->db->escapeNumber($this->getGameID()),
'account_id' => $this->db->escapeNumber($this->getAccountID()),
'ship_name' => $this->db->escapeString($name),
]);
}
/**
* Get planet owned by this player.
* Returns null if this player does not own a planet.
*/
public function getPlanet(): ?SmrPlanet {
$dbResult = $this->db->read('SELECT * FROM planet WHERE game_id=' . $this->db->escapeNumber($this->getGameID()) . ' AND owner_id=' . $this->db->escapeNumber($this->getAccountID()));
if ($dbResult->hasRecord()) {
$dbRecord = $dbResult->record();
return SmrPlanet::getPlanet($this->getGameID(), $dbRecord->getInt('sector_id'), false, $dbRecord);
}
return null;
}
public function getSectorPlanet(): SmrPlanet {
return SmrPlanet::getPlanet($this->getGameID(), $this->getSectorID());
}
public function getSectorPort(): AbstractSmrPort {
return SmrPort::getPort($this->getGameID(), $this->getSectorID());
}
public function getSectorID(): int {
return $this->sectorID;
}
public function getSector(): SmrSector {
return SmrSector::getSector($this->getGameID(), $this->getSectorID());
}
public function setSectorID(int $sectorID): void {
if ($this->sectorID == $sectorID) {
return;
}
$port = SmrPort::getPort($this->getGameID(), $this->getSectorID());
$port->addCachePort($this->getAccountID()); //Add port of sector we were just in, to make sure it is left totally up to date.
$this->setLastSectorID($this->getSectorID());
$this->actionTaken('LeaveSector', ['SectorID' => $this->getSectorID()]);
$this->sectorID = $sectorID;
$this->actionTaken('EnterSector', ['SectorID' => $this->getSectorID()]);
$this->hasChanged = true;
$port = SmrPort::getPort($this->getGameID(), $this->getSectorID());
$port->addCachePort($this->getAccountID()); //Add the port of sector we are now in.
}
public function getLastSectorID(): int {
return $this->lastSectorID;
}
public function setLastSectorID(int $lastSectorID): void {
if ($this->lastSectorID == $lastSectorID) {
return;
}
$this->lastSectorID = $lastSectorID;
$this->hasChanged = true;
}
public function getHome(): int {
// get his home sector
$hq_id = GOVERNMENT + $this->getRaceID();
$raceHqSectors = SmrSector::getLocationSectors($this->getGameID(), $hq_id);
if (empty($raceHqSectors)) {
// No HQ, default to sector 1
return 1;
}
// If race has multiple HQ's for some reason, use the first one
return key($raceHqSectors);
}
public function isDead(): bool {
return $this->dead;
}
public function isNPC(): bool {
return $this->npc;
}
/**
* Does the player have Newbie status?
*/
public function hasNewbieStatus(): bool {
return $this->newbieStatus;
}
/**
* Update the player's newbie status if it has changed.
* This function queries the account, so use sparingly.
*/
public function updateNewbieStatus(): void {
$accountNewbieStatus = !$this->getAccount()->isVeteran();
if ($this->newbieStatus != $accountNewbieStatus) {
$this->newbieStatus = $accountNewbieStatus;
$this->hasChanged = true;
}
}
/**
* Has this player been designated as the alliance flagship?
*/
public function isFlagship(): bool {
return $this->hasAlliance() && $this->getAlliance()->getFlagshipID() == $this->getAccountID();
}
public function isPresident(): bool {
return Council::getPresidentID($this->getGameID(), $this->getRaceID()) == $this->getAccountID();
}
public function isOnCouncil(): bool {
return Council::isOnCouncil($this->getGameID(), $this->getRaceID(), $this->getAccountID());
}
public function isDraftLeader(): bool {
if (!isset($this->draftLeader)) {
$dbResult = $this->db->read('SELECT 1 FROM draft_leaders WHERE ' . $this->SQL);
$this->draftLeader = $dbResult->hasRecord();
}
return $this->draftLeader;
}
public function getGPWriter(): string|false {
if (!isset($this->gpWriter)) {
$this->gpWriter = false;
$dbResult = $this->db->read('SELECT position FROM galactic_post_writer WHERE ' . $this->SQL);
if ($dbResult->hasRecord()) {
$this->gpWriter = $dbResult->record()->getString('position');
}
}
return $this->gpWriter;
}
public function isGPEditor(): bool {
return $this->getGPWriter() == 'editor';
}
public function isForceDropMessages(): bool {
return $this->forceDropMessages;
}
public function setForceDropMessages(bool $bool): void {
if ($this->forceDropMessages == $bool) {
return;
}
$this->forceDropMessages = $bool;
$this->hasChanged = true;
}
public function getScoutMessageGroupLimit(): int {
return match ($this->scoutMessageGroupType) {
ScoutMessageGroupType::Always => 0,
ScoutMessageGroupType::Auto => MESSAGES_PER_PAGE,
ScoutMessageGroupType::Never => PHP_INT_MAX,
};
}
public function getScoutMessageGroupType(): ScoutMessageGroupType {
return $this->scoutMessageGroupType;
}
public function setScoutMessageGroupType(ScoutMessageGroupType $setting): void {
if ($this->scoutMessageGroupType === $setting) {
return;
}
$this->scoutMessageGroupType = $setting;
$this->hasChanged = true;
}
/**
* @return int Message ID
*/
protected static function doMessageSending(int $senderID, int $receiverID, int $gameID, int $messageTypeID, string $message, int $expires, bool $senderDelete = false, bool $unread = true): int {
$message = trim($message);
$db = Database::getInstance();
// Keep track of the message_id so it can be returned
$insertID = $db->insert('message', [
'account_id' => $db->escapeNumber($receiverID),
'game_id' => $db->escapeNumber($gameID),
'message_type_id' => $db->escapeNumber($messageTypeID),
'message_text' => $db->escapeString($message),
'sender_id' => $db->escapeNumber($senderID),
'send_time' => $db->escapeNumber(Epoch::time()),
'expire_time' => $db->escapeNumber($expires),
'sender_delete' => $db->escapeBoolean($senderDelete),
]);
if ($unread === true) {
// give him the message icon
$db->replace('player_has_unread_messages', [
'game_id' => $db->escapeNumber($gameID),
'account_id' => $db->escapeNumber($receiverID),
'message_type_id' => $db->escapeNumber($messageTypeID),
]);
}
switch ($messageTypeID) {
case MSG_PLAYER:
$receiverAccount = SmrAccount::getAccount($receiverID);
if ($receiverAccount->isValidated() && $receiverAccount->isReceivingMessageNotifications($messageTypeID) && !$receiverAccount->isActive()) {
$sender = Messages::getMessagePlayer($senderID, $gameID, $messageTypeID);
if ($sender instanceof self) {
$sender = $sender->getDisplayName();
}
$mail = setupMailer();
$mail->Subject = 'Message Notification';
$mail->setFrom('notifications@smrealms.de', 'SMR Notifications');
$bbifiedMessage = 'From: ' . $sender . ' Date: ' . date($receiverAccount->getDateTimeFormat(), Epoch::time()) . "<br/>\r\n<br/>\r\n" . bbifyMessage($message, true);
$mail->msgHTML($bbifiedMessage);
$mail->AltBody = strip_tags($bbifiedMessage);
$mail->addAddress($receiverAccount->getEmail(), $receiverAccount->getHofName());
$mail->send();
$receiverAccount->decreaseMessageNotifications($messageTypeID, 1);
$receiverAccount->update();
}
break;
}
return $insertID;
}
public function sendMessageToBox(int $boxTypeID, string $message): void {
// send him the message
SmrAccount::doMessageSendingToBox($this->getAccountID(), $boxTypeID, $message, $this->getGameID());
}
public function sendGlobalMessage(string $message, bool $canBeIgnored = true): void {
if ($canBeIgnored) {
if ($this->getAccount()->isMailBanned()) {
throw new UserError('You are currently banned from sending messages');
}
}
$this->sendMessageToBox(BOX_GLOBALS, $message);
// send to all online player
$db = Database::getInstance();
$dbResult = $db->read('SELECT account_id
FROM active_session
JOIN player USING (game_id, account_id)
WHERE active_session.last_accessed >= ' . $db->escapeNumber(Epoch::time() - TIME_BEFORE_INACTIVE) . '
AND game_id = ' . $db->escapeNumber($this->getGameID()) . '
AND ignore_globals = \'FALSE\'
AND account_id != ' . $db->escapeNumber($this->getAccountID()));
foreach ($dbResult->records() as $dbRecord) {
$this->sendMessage($dbRecord->getInt('account_id'), MSG_GLOBAL, $message, $canBeIgnored);
}
$this->sendMessage($this->getAccountID(), MSG_GLOBAL, $message, $canBeIgnored, false);
}
/**
* @return ($canBeIgnored is true ? int|false : int) Message ID
*/
public function sendMessage(int $receiverID, int $messageTypeID, string $message, bool $canBeIgnored = true, bool $unread = true, int $expires = null, bool $senderDelete = false): int|false {
//get expire time
if ($canBeIgnored) {
if ($this->getAccount()->isMailBanned()) {
throw new UserError('You are currently banned from sending messages');
}
// Don't send messages to players ignoring us
$dbResult = $this->db->read('SELECT 1 FROM message_blacklist WHERE account_id=' . $this->db->escapeNumber($receiverID) . ' AND blacklisted_id=' . $this->db->escapeNumber($this->getAccountID()) . ' LIMIT 1');
if ($dbResult->hasRecord()) {
return false;
}
}
$message = word_filter($message);
// If expires not specified, use default based on message type
if ($expires === null) {
$expires = match ($messageTypeID) {
MSG_GLOBAL => 3600, // 1h
MSG_PLAYER => 86400 * 31, // 1 month
MSG_PLANET => 86400 * 7, // 1 week
MSG_SCOUT => 86400 * 3, // 3 days
MSG_POLITICAL => 86400 * 31, // 1 month
MSG_ALLIANCE => 86400 * 31, // 1 month
MSG_ADMIN => 86400 * 365, // 1 year
MSG_CASINO => 86400 * 31, // 1 month
default => 86400 * 7, // 1 week
};
$expires += Epoch::time();
}
// Do not put scout messages in the sender's sent box
if ($messageTypeID == MSG_SCOUT) {
$senderDelete = true;
}
// send him the message and return the message_id
return self::doMessageSending($this->getAccountID(), $receiverID, $this->getGameID(), $messageTypeID, $message, $expires, $senderDelete, $unread);
}
public function sendMessageFromOpAnnounce(int $receiverID, string $message, int $expires = null): void {
// get expire time if not set
if ($expires === null) {
$expires = Epoch::time() + 86400 * 14;
}
self::doMessageSending(ACCOUNT_ID_OP_ANNOUNCE, $receiverID, $this->getGameID(), MSG_ALLIANCE, $message, $expires);
}
public function sendMessageFromAllianceCommand(int $receiverID, string $message): void {
$expires = Epoch::time() + 86400 * 365;
self::doMessageSending(ACCOUNT_ID_ALLIANCE_COMMAND, $receiverID, $this->getGameID(), MSG_PLAYER, $message, $expires);
}
public static function sendMessageFromPlanet(int $gameID, int $receiverID, string $message): void {
//get expire time
$expires = Epoch::time() + 86400 * 31;
// send him the message
self::doMessageSending(ACCOUNT_ID_PLANET, $receiverID, $gameID, MSG_PLANET, $message, $expires);
}
public static function sendMessageFromPort(int $gameID, int $receiverID, string $message): void {
//get expire time
$expires = Epoch::time() + 86400 * 31;
// send him the message
self::doMessageSending(ACCOUNT_ID_PORT, $receiverID, $gameID, MSG_PLAYER, $message, $expires);
}
public static function sendMessageFromFedClerk(int $gameID, int $receiverID, string $message): void {
$expires = Epoch::time() + 86400 * 365;
self::doMessageSending(ACCOUNT_ID_FED_CLERK, $receiverID, $gameID, MSG_PLAYER, $message, $expires);
}
public static function sendMessageFromAdmin(int $gameID, int $receiverID, string $message, int $expires = null): void {
//get expire time
if ($expires === null) {
$expires = Epoch::time() + 86400 * 365;
}
// send him the message
self::doMessageSending(ACCOUNT_ID_ADMIN, $receiverID, $gameID, MSG_ADMIN, $message, $expires);
}
public static function sendMessageFromAllianceAmbassador(int $gameID, int $receiverID, string $message, int $expires = null): void {
//get expire time
if ($expires === null) {
$expires = Epoch::time() + 86400 * 31;
}
// send him the message
self::doMessageSending(ACCOUNT_ID_ALLIANCE_AMBASSADOR, $receiverID, $gameID, MSG_ALLIANCE, $message, $expires);
}
public static function sendMessageFromCasino(int $gameID, int $receiverID, string $message, int $expires = null): void {
//get expire time
if ($expires === null) {
$expires = Epoch::time() + 86400 * 7;
}
// send him the message
self::doMessageSending(ACCOUNT_ID_CASINO, $receiverID, $gameID, MSG_CASINO, $message, $expires);
}
public static function sendMessageFromRace(int $raceID, int $gameID, int $receiverID, string $message, int $expires = null): void {
//get expire time
if ($expires === null) {
$expires = Epoch::time() + 86400 * 5;
}
// send him the message
self::doMessageSending(ACCOUNT_ID_GROUP_RACES + $raceID, $receiverID, $gameID, MSG_POLITICAL, $message, $expires);
}
public function setMessagesRead(int $messageTypeID): void {
$this->db->write('DELETE FROM player_has_unread_messages
WHERE ' . $this->SQL . ' AND message_type_id = ' . $this->db->escapeNumber($messageTypeID));
$this->db->write('UPDATE message SET msg_read = ' . $this->db->escapeBoolean(true) . '
WHERE message_type_id = ' . $this->db->escapeNumber($messageTypeID) . ' AND ' . $this->SQL);
}
public function getSafeAttackRating(): int {
return max(0, min(8, IFloor($this->getAlignment() / 150) + 4));
}
public function hasFederalProtection(): bool {
$sector = SmrSector::getSector($this->getGameID(), $this->getSectorID());
if (!$sector->offersFederalProtection()) {
return false;
}
$ship = $this->getShip();
if ($ship->hasIllegalGoods()) {
return false;
}
if ($ship->getAttackRating() <= $this->getSafeAttackRating()) {
foreach ($sector->getFedRaceIDs() as $fedRaceID) {
if ($this->canBeProtectedByRace($fedRaceID)) {
return true;
}
}
}
return false;
}
public function canBeProtectedByRace(int $raceID): bool {
if (!isset($this->canFed)) {
$this->canFed = [];
foreach (Race::getAllIDs() as $raceID2) {
$this->canFed[$raceID2] = $this->getRelation($raceID2) >= ALIGN_FED_PROTECTION;
}
$dbResult = $this->db->read('SELECT race_id, allowed FROM player_can_fed
WHERE ' . $this->SQL . ' AND expiry > ' . $this->db->escapeNumber(Epoch::time()));
foreach ($dbResult->records() as $dbRecord) {
$this->canFed[$dbRecord->getInt('race_id')] = $dbRecord->getBoolean('allowed');
}
}
return $this->canFed[$raceID];
}
/**
* Returns a boolean identifying if the player can currently
* participate in battles.
*/
public function canFight(): bool {
return !($this->hasNewbieTurns() ||
$this->isDead() ||
$this->isLandedOnPlanet() ||
$this->hasFederalProtection());
}
public function setDead(bool $bool): void {
if ($this->dead == $bool) {
return;
}
$this->dead = $bool;
$this->hasChanged = true;
}
public function getKills(): int {
return $this->kills;
}
public function increaseKills(int $kills): void {
if ($kills < 0) {
throw new Exception('Trying to increase negative kills.');
}
$this->setKills($this->kills + $kills);
}
public function setKills(int $kills): void {
if ($this->kills == $kills) {
return;
}
$this->kills = $kills;
$this->hasChanged = true;
}
public function getDeaths(): int {
return $this->deaths;
}
public function increaseDeaths(int $deaths): void {
if ($deaths < 0) {
throw new Exception('Trying to increase negative deaths.');
}
$this->setDeaths($this->getDeaths() + $deaths);
}
public function setDeaths(int $deaths): void {
if ($this->deaths == $deaths) {
return;
}
$this->deaths = $deaths;
$this->hasChanged = true;
}
public function getAssists(): int {
return $this->assists;
}
public function increaseAssists(int $assists): void {
if ($assists < 1) {
throw new Exception('Must increase by a positive number.');
}
$this->assists += $assists;
$this->hasChanged = true;
}
public function hasGoodAlignment(): bool {
return $this->alignment >= ALIGNMENT_GOOD;
}
public function hasEvilAlignment(): bool {
return $this->alignment <= ALIGNMENT_EVIL;
}
public function hasNeutralAlignment(): bool {
return !$this->hasGoodAlignment() && !$this->hasEvilAlignment();
}