forked from exodus4d/pathfinder
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Map.php
1084 lines (939 loc) · 46.5 KB
/
Map.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
/**
* Created by PhpStorm.
* User: exodus4d
* Date: 16.02.15
* Time: 20:23
*/
namespace Exodus4D\Pathfinder\Controller\Api;
use Exodus4D\Pathfinder\Lib\Config;
use Exodus4D\Pathfinder\Controller;
use Exodus4D\Pathfinder\Data\File\FileHandler;
use Exodus4D\Pathfinder\Model\AbstractModel;
use Exodus4D\Pathfinder\Model\Pathfinder;
use Exodus4D\Pathfinder\Model\Universe;
/**
* Map controller
* Class Map
* @package Controller\Api
*/
class Map extends Controller\AccessController {
// cache keys
const CACHE_KEY_INIT = 'CACHED_INIT';
const CACHE_KEY_USER_DATA = 'CACHED.USER_DATA.%s';
const CACHE_KEY_HISTORY = 'CACHED_MAP_HISTORY_%s';
/**
* get user data cache key
* @param int $mapId
* @return string
*/
protected function getUserDataCacheKey(int $mapId): string {
return sprintf(self::CACHE_KEY_USER_DATA, 'MAP_' . $mapId);
}
/**
* get log history data cache key
* @param int $mapId
* @return string
*/
protected function getHistoryDataCacheKey(int $mapId): string {
return sprintf(self::CACHE_KEY_HISTORY, 'MAP_' . $mapId);
}
/**
* Get all required static config data for program initialization
* @param \Base $f3
* @throws \Exception
*/
public function initData(\Base $f3){
$validInitData = true;
$ttl = 60 * 60;
if(!$exists = $f3->exists(self::CACHE_KEY_INIT, $return)){
$return = (object) [];
$return->error = [];
// static program data ------------------------------------------------------------------------------------
$return->timer = Config::getPathfinderData('timer');
// get all available map types ----------------------------------------------------------------------------
$mapType = Pathfinder\AbstractPathfinderModel::getNew('MapTypeModel');
$rows = $mapType->find('active = 1');
// default map type config
$mapsDefaultConfig = Config::getMapsDefaultConfig();
$mapTypeData = [];
foreach((array)$rows as $rowData){
$data = [
'id' => $rowData->id,
'label' => $rowData->label,
'class' => $rowData->class,
'classTab' => $rowData->classTab,
'defaultConfig' => $mapsDefaultConfig[$rowData->name]
];
$mapTypeData[$rowData->name] = $data;
}
$return->mapTypes = $mapTypeData;
$validInitData = $validInitData ? !empty($mapTypeData) : $validInitData;
// get all available map scopes ---------------------------------------------------------------------------
$mapScope = Pathfinder\AbstractPathfinderModel::getNew('MapScopeModel');
$rows = $mapScope->find('active = 1');
$mapScopeData = [];
foreach((array)$rows as $rowData){
$data = [
'id' => $rowData->id,
'label' => $rowData->label
];
$mapScopeData[$rowData->name] = $data;
}
$return->mapScopes = $mapScopeData;
$validInitData = $validInitData ? !empty($mapScopeData) : $validInitData;
// get all available system status ------------------------------------------------------------------------
$systemStatus = Pathfinder\AbstractPathfinderModel::getNew('SystemStatusModel');
$rows = $systemStatus->find('active = 1');
$systemScopeData = [];
foreach((array)$rows as $rowData){
$data = [
'id' => $rowData->id,
'label' => $rowData->label,
'class' => $rowData->class
];
$systemScopeData[$rowData->name] = $data;
}
$return->systemStatus = $systemScopeData;
$validInitData = $validInitData ? !empty($systemScopeData) : $validInitData;
// get all available system types -------------------------------------------------------------------------
$systemType = Pathfinder\AbstractPathfinderModel::getNew('SystemTypeModel');
$rows = $systemType->find('active = 1');
$systemTypeData = [];
foreach((array)$rows as $rowData){
$data = [
'id' => $rowData->id,
'name' => $rowData->name
];
$systemTypeData[$rowData->name] = $data;
}
$return->systemType = $systemTypeData;
$validInitData = $validInitData ? !empty($systemTypeData) : $validInitData;
// get available connection scopes ------------------------------------------------------------------------
$connectionScope = Pathfinder\AbstractPathfinderModel::getNew('ConnectionScopeModel');
$rows = $connectionScope->find('active = 1');
$connectionScopeData = [];
foreach((array)$rows as $rowData){
$data = [
'id' => $rowData->id,
'label' => $rowData->label,
'connectorDefinition' => $rowData->connectorDefinition
];
$connectionScopeData[$rowData->name] = $data;
}
$return->connectionScopes = $connectionScopeData;
$validInitData = $validInitData ? !empty($connectionScopeData) : $validInitData;
// get available character status -------------------------------------------------------------------------
$characterStatus = Pathfinder\AbstractPathfinderModel::getNew('CharacterStatusModel');
$rows = $characterStatus->find('active = 1');
$characterStatusData = [];
foreach((array)$rows as $rowData){
$data = [
'id' => $rowData->id,
'name' => $rowData->name,
'class' => $rowData->class
];
$characterStatusData[$rowData->name] = $data;
}
$return->characterStatus = $characterStatusData;
$validInitData = $validInitData ? !empty($characterStatusData) : $validInitData;
// route search config ------------------------------------------------------------------------------------
$return->routeSearch = [
'defaultCount' => Config::getPathfinderData('route.search_default_count'),
'maxDefaultCount' => Config::getPathfinderData('route.max_default_count'),
'limit' => Config::getPathfinderData('route.limit')
];
// get program routes -------------------------------------------------------------------------------------
$return->routes = [
'ssoLogin' => $this->getF3()->alias('sso', ['action' => 'requestAuthorization'])
];
// get third party APIs -----------------------------------------------------------------------------------
$return->url = [
'ccpImageServer' => Config::getPathfinderData('api.ccp_image_server'),
'zKillboard' => Config::getPathfinderData('api.z_killboard'),
'eveeye' => Config::getPathfinderData('api.eveeye'),
'dotlan' => Config::getPathfinderData('api.dotlan'),
'anoik' => Config::getPathfinderData('api.anoik'),
'eveScout' => Config::getPathfinderData('api.eve_scout')
];
// get Plugin config --------------------------------------------------------------------------------------
$return->plugin = [
'modules' => Config::getPluginConfig('modules')
];
// Character default config -------------------------------------------------------------------------------
$return->character = [
'autoLocationSelect' => (bool)Config::getPathfinderData('character.auto_location_select')
];
// Slack integration status -------------------------------------------------------------------------------
$return->slack = [
'status' => (bool)Config::getPathfinderData('slack.status')
];
// Slack integration status -------------------------------------------------------------------------------
$return->discord = [
'status' => (bool)Config::getPathfinderData('discord.status')
];
// structure status ---------------------------------------------------------------------------------------
$structureStatus = Pathfinder\StructureStatusModel::getAll();
$structureStatusData = [];
foreach($structureStatus as $status){
$structureStatusData[$status->_id] = $status->getData();
}
$return->structureStatus = $structureStatusData;
$validInitData = $validInitData ? !empty($structureStatusData) : $validInitData;
// get available wormhole types ---------------------------------------------------------------------------
/**
* @var $groupUniverseModel Universe\GroupModel
*/
$groupUniverseModel = Universe\AbstractUniverseModel::getNew('GroupModel');
$groupUniverseModel->getById(Config::ESI_GROUP_WORMHOLE_ID);
$wormholesData = [];
/**
* @var $typeModel Universe\TypeModel
*/
foreach($types = $groupUniverseModel->getTypes(false) as $typeModel){
if(
($wormholeData = $typeModel->getWormholeData()) &&
mb_strlen((string)$wormholeData->name) === 4
){
$wormholesData[$wormholeData->name] = $wormholeData;
}
}
ksort($wormholesData);
$return->wormholes = $wormholesData;
$validInitData = $validInitData ? !empty($wormholesData) : $validInitData;
// universe category data ---------------------------------------------------------------------------------
/**
* @var $categoryUniverseModel Universe\CategoryModel
*/
$categoryUniverseModel = Universe\AbstractUniverseModel::getNew('CategoryModel');
$return->universeCategories = [
Config::ESI_CATEGORY_SHIP_ID =>
($categoryUniverseModel->getById(Config::ESI_CATEGORY_SHIP_ID) && $categoryUniverseModel->valid()) ? $categoryUniverseModel->getData(['mass']) : null,
Config::ESI_CATEGORY_STRUCTURE_ID =>
($categoryUniverseModel->getById(Config::ESI_CATEGORY_STRUCTURE_ID) && $categoryUniverseModel->valid()) ? $categoryUniverseModel->getData() : null,
];
$validInitData = $validInitData ? !count(array_filter($return->universeCategories, function($v){
return empty(array_filter((array)$v->groups));
})) : $validInitData;
// response should not be cached if invalid -> e.g. missing static data
if($validInitData){
$f3->set(self::CACHE_KEY_INIT, $return, $ttl);
}
}
// get SSO error messages that should be shown immediately ----------------------------------------------------
// -> e.g. errors while character switch from previous HTTP requests
if($f3->exists(Controller\Ccp\Sso::SESSION_KEY_SSO_ERROR, $text)){
$ssoError = (object) [];
$ssoError->type = 'error';
$ssoError->title = 'Login failed';
$ssoError->text = $text;
$return->error[] = $ssoError;
$f3->clear(Controller\Ccp\Sso::SESSION_KEY_SSO_ERROR);
}elseif($validInitData){
// no errors and valid data -> send Cache header
$f3->expire(Config::ttlLeft($exists, $ttl));
}
echo json_encode($return);
}
/**
* import new map data
* @param \Base $f3
* @throws \Exception
*/
public function import(\Base $f3){
$importData = (array)$f3->get('POST');
$return = (object) [];
$return->error = [];
$return->warning = [];
if(
isset($importData['typeId']) &&
count($importData['mapData']) > 0
){
$activeCharacter = $this->getCharacter();
/**
* @var $map Pathfinder\MapModel
*/
$map = Pathfinder\AbstractPathfinderModel::getNew('MapModel');
/**
* @var $mapType Pathfinder\MapTypeModel
*/
$mapType = Pathfinder\AbstractPathfinderModel::getNew('MapTypeModel');
$mapType->getById((int)$importData['typeId']);
if( !$mapType->dry() ){
$defaultConfig = Config::getMapsDefaultConfig($mapType->name);
foreach($importData['mapData'] as $mapData){
if(
isset($mapData['config']) &&
isset($mapData['data'])
){
$mapDataConfig = (array)$mapData['config'];
$mapDataData = (array)$mapData['data'];
/**
* @var $mapScope Pathfinder\MapScopeModel
*/
$mapScope = Pathfinder\AbstractPathfinderModel::getNew('MapScopeModel');
$mapScope->getById((int)$mapDataConfig['scope']['id']);
if( !$mapScope->dry() ){
if(
isset($mapDataData['systems']) &&
isset($mapDataData['connections'])
){
$mapDataSystems = (array)$mapDataData['systems'];
$mapDataConnections = (array)$mapDataData['connections'];
$systemCount = count($mapDataSystems);
if($systemCount <= $defaultConfig['max_systems']){
$map->copyfrom($mapDataConfig, ['name', 'icon', 'position', 'locked', 'rallyUpdated', 'rallyPoke']);
$map->typeId = $mapType;
$map->scopeId = $mapScope;
$map->save($activeCharacter);
// new system IDs will be generated
// therefore we need to temp store a mapping between IDs
$tempSystemIdMapping = [];
foreach($mapDataSystems as $systemData){
if(
($oldId = (int)$systemData['id']) &&
($systemId = (int)$systemData['systemId'])
){
$system = $map->getNewSystem($systemId);
$system->copyfrom($systemData, ['alias', 'status', 'locked', 'rallyUpdated', 'rallyPoke', 'position']);
$system = $map->saveSystem($system, $activeCharacter, $system->posX, $system->posY);
$tempSystemIdMapping[$oldId] = $system->_id;
}
}
/**
* @var $connection Pathfinder\ConnectionModel
*/
$connection = Pathfinder\AbstractPathfinderModel::getNew('ConnectionModel');
$connection->setActivityLogging(false);
foreach($mapDataConnections as $connectionData){
// check if source and target IDs match with new system ID
if(
($sourceSystemId = $tempSystemIdMapping[(int)$connectionData['source']]) &&
($targetSystemId = $tempSystemIdMapping[(int)$connectionData['target']])
){
$connection->source = $sourceSystemId;
$connection->target = $targetSystemId;
$connection->copyfrom($connectionData, ['scope', 'type']);
$map->saveConnection($connection, $activeCharacter);
$connection->reset();
}
}
// map access info should not automatically imported
if($map->isPrivate()){
$map->setAccess($activeCharacter);
}elseif($map->isCorporation()){
if($corporation = $activeCharacter->getCorporation()){
$map->setAccess($corporation);
}
}elseif($map->isAlliance()){
if($alliance = $activeCharacter->getAlliance()){
$map->setAccess($alliance);
}
}
// broadcast map Access -> and send map Data
$this->broadcastMapAccess($map);
}else{
$maxSystemsError = (object) [];
$maxSystemsError->type = 'error';
$maxSystemsError->text = 'Map has to many systems (' . $systemCount . ').'
.' Max system count is ' . $defaultConfig['max_systems'] . ' for ' . $mapType->name . ' maps.';
$return->error[] = $maxSystemsError;
}
}else{
// systems || connections missing
$missingConfigError = (object) [];
$missingConfigError->type = 'error';
$missingConfigError->text = 'Map data not valid (systems || connections) missing';
$return->error[] = $missingConfigError;
}
}else{
$unknownMapScope= (object) [];
$unknownMapScope->type = 'error';
$unknownMapScope->text = 'Map scope unknown!';
$return->error[] = $unknownMapScope;
}
}else{
// map config || systems/connections missing
$missingConfigError = (object) [];
$missingConfigError->type = 'error';
$missingConfigError->text = 'Map data not valid (config || data) missing';
$return->error[] = $missingConfigError;
}
$map->reset();
}
}else{
$unknownMapType = (object) [];
$unknownMapType->type = 'error';
$unknownMapType->text = 'Map type unknown!';
$return->error[] = $unknownMapType;
}
}else{
// map data missing
$missingDataError = (object) [];
$missingDataError->type = 'error';
$missingDataError->text = 'Map data missing';
$return->error[] = $missingDataError;
}
echo json_encode($return);
}
/**
* broadcast characters with map access rights to WebSocket server
* -> if characters with map access found -> broadcast mapData to them
* @param Pathfinder\MapModel $map
* @throws \Exception
*/
protected function broadcastMapAccess(Pathfinder\MapModel $map){
$mapAccess = [
'id' => $map->_id,
'name' => $map->name,
'characterIds' => array_map(function($data){
return $data->id;
}, $map->getCharactersData())
];
$this->getF3()->webSocket()->write('mapAccess', $mapAccess);
// map has (probably) active connections that should receive map Data
$this->broadcastMap($map, true);
}
/**
* get map access tokens for current character
* -> send access tokens via TCP Socket for WebSocket auth
* @param \Base $f3
* @throws \Exception
*/
public function getAccessData(\Base $f3){
$return = (object) [];
$activeCharacter = $this->getCharacter();
$characterData = $activeCharacter->getData(true);
$maps = $activeCharacter->getMaps();
// some character data is not required (in WebSocket) -> unset() and keep return small
if(isset($characterData->corporation->rights)){
unset($characterData->corporation->rights);
}
// access token
$token = bin2hex(random_bytes(16));
$return->data = [
'id' => $activeCharacter->_id,
'token' => $token, // character access
'characterData' => $characterData,
'mapData' => []
];
if($maps){
foreach($maps as $map){
$return->data['mapData'][] = [
'id' => $map->_id,
'token' => $token, // map access
'name' => $map->name
];
}
}
// send Access Data to WebSocket Server and get response (status)
// if 'OK' -> Socket exists
$status = '';
$f3->webSocket()
->write('mapConnectionAccess', $return->data)
->then(
function($payload) use (&$status) {
$status = (string)$payload['load'];
});
$return->status = $status;
echo json_encode($return);
}
/**
* update maps with $mapsData where $character has access to
* @param Pathfinder\CharacterModel $character
* @param array $mapsData
* @return \stdClass
*/
protected function updateMapsData(Pathfinder\CharacterModel $character, array $mapsData) : \stdClass {
$return = (object) [];
$return->error = [];
$return->mapData = [];
$mapIdsChanged = [];
$maps = $character->getMaps();
if(!empty($mapsData) && !empty($maps)){
// loop all $mapsData that should be saved
// -> currently there will only be ONE map data change submitted -> single loop
foreach($mapsData as $data){
$systems = [];
$connections = [];
// check whether system data and/or connection data is send
// empty arrays are not included in ajax requests
if(isset($data['data']['systems'])){
$systems = (array)$data['data']['systems'];
}
if(isset($data['data']['connections'])){
$connections = (array)$data['data']['connections'];
}
// check if system data or connection data is send
if(
count($systems) > 0 ||
count($connections) > 0
){
// map changes expected ===========================================================================
// loop current user maps and check for changes
foreach($maps as $map){
// update system data -------------------------------------------------------------------------
foreach($systems as $i => $systemData){
// check if current system belongs to the current map
if($system = $map->getSystemById((int)$systemData['id'])){
$system->copyfrom($systemData, ['alias', 'status', 'position', 'locked', 'rallyUpdated', 'rallyPoke']);
if($system->save($character)){
if(!in_array($map->_id, $mapIdsChanged)){
$mapIdsChanged[] = $map->_id;
}
// one system belongs to ONE map -> speed up for multiple maps
unset($systemData[$i]);
}else{
$return->error = array_merge($return->error, $system->getErrors());
}
}
}
// update connection data ---------------------------------------------------------------------
foreach($connections as $i => $connectionData){
// check if the current connection belongs to the current map
if($connection = $map->getConnectionById((int)$connectionData['id'])){
$connection->copyfrom($connectionData, ['scope', 'type', 'endpoints']);
if($connection->save($character)){
if(!in_array($map->_id, $mapIdsChanged)){
$mapIdsChanged[] = $map->_id;
}
// one connection belongs to ONE map -> speed up for multiple maps
unset($connectionData[$i]);
}else{
$return->error = array_merge($return->error, $connection->getErrors());
}
}
}
}
}
}
}
foreach($maps as $map){
// format map Data for return/broadcast
if($mapData = $this->getFormattedMapData($map)){
if(in_array($map->_id, $mapIdsChanged)){
$this->broadcastMapData($mapData);
}
$return->mapData[] = $mapData;
}
}
return $return;
}
/**
* update map data
* -> function is called continuously (trigger) by any active client
* @param \Base $f3
* @throws \Exception
*/
public function updateData(\Base $f3){
$postData = (array)$f3->get('POST');
$mapsData = (array)$postData['mapData'];
$userDataRequired = (bool)$postData['getUserData'];
$activeCharacter = $this->getCharacter();
$return = $this->updateMapsData($activeCharacter, $mapsData);
// if userData is requested -> add it as well
// -> Only first trigger call should request this data!
if($userDataRequired) {
$return->userData = $activeCharacter->getUser()->getData();
}
echo json_encode($return);
}
/**
* onUnload map sync
* @see https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon
* @param \Base $f3
* @throws \Exception
*/
public function updateUnloadData(\Base $f3){
$postData = (array)$f3->get('POST');
if(!empty($mapsData = (string)$postData['mapData'])){
$mapsData = (array)json_decode($mapsData, true);
if(($jsonError = json_last_error()) === JSON_ERROR_NONE){
$activeCharacter = $this->getCharacter();
$this->updateMapsData($activeCharacter, $mapsData);
}
}
}
/**
* update map data api
* -> function is called continuously by any active client
* @param \Base $f3
* @throws \Exception
*/
public function updateUserData(\Base $f3){
$postData = (array)$f3->get('POST');
$mapIds = (array)$postData['mapIds'];
$getMapUserData = (bool)$postData['getMapUserData'];
$mapTracking = (bool)$postData['mapTracking'];
$systemData = (array)$postData['systemData'];
$newSystemPositions = (array)$postData['newSystemPositions'];
$activeCharacter = $this->getCharacter();
$return = (object)[];
// update current location
// -> suppress temporary timeout errors
$activeCharacter = $activeCharacter->updateLog();
if( !empty($mapIds) ){
// IMPORTANT for now -> just update a single map (save performance)
$mapId = (int)reset($mapIds);
// get map and check map access
if( !is_null($map = $activeCharacter->getMap($mapId)) ){
// check character log (current system) and manipulate map (e.g. add new system)
if($mapTracking){
$map = $this->updateMapByCharacter($map, $activeCharacter, $newSystemPositions);
}
// mapUserData ----------------------------------------------------------------------------------------
if($getMapUserData){
$cacheKey = $this->getUserDataCacheKey($mapId);
if( !$f3->exists($cacheKey, $mapUserData) ){
$mapUserData = $map->getUserData();
// cache time (seconds) should be equal or less than request trigger time
// prevent request flooding
$responseTTL = (int)Config::getPathfinderData('timer.update_server_user_data.delay') / 1000;
$f3->set($cacheKey, $mapUserData, $responseTTL);
}
$return->mapUserData[] = $mapUserData;
}
// systemData -----------------------------------------------------------------------------------------
if(
$mapId === (int)$systemData['mapId'] &&
!is_null($system = $map->getSystemById((int)$systemData['id']))
){
// data for currently selected system
$return->system = $system->getData();
$return->system->signatures = $system->getSignaturesData();
$return->system->sigHistory = $system->getSignaturesHistory();
$return->system->structures = $system->getStructuresData();
}
}
}
// get current user data -> this should not be cached because each user has different personal data
// even if they have multiple characters using the same map!
$return->userData = $activeCharacter->getUser()->getData();
// add error (if exists)
$return->error = [];
echo json_encode($return);
}
/**
* update map connections/systems based on $character´s location logs
* @param Pathfinder\MapModel $map
* @param Pathfinder\CharacterModel $character
* @param array $newSystemPositions
* @return Pathfinder\MapModel
* @throws \Exception
*/
protected function updateMapByCharacter(Pathfinder\MapModel $map, Pathfinder\CharacterModel $character, array $newSystemPositions = []) : Pathfinder\MapModel {
// map changed. update cache (system/connection) changed
$mapDataChanged = false;
if(
( $mapScope = $map->getScope() ) &&
( $mapScope->name != 'none' ) && // tracking is disabled for map
( $targetLog = $character->getLog() )
){
// character is currently in a system
$targetSystemId = (int)$targetLog->systemId;
// get 'character log' from source system. If not log found -> assume $sourceLog == $targetLog
$sourceLog = $character->getLogPrevSystem($map->_id, $targetSystemId) ? : $targetLog;
$sourceSystemId = (int)$sourceLog->systemId;
if($sourceSystemId){
$defaultPositions = (array)$newSystemPositions['defaults'];
$currentPosition = (array)$newSystemPositions['location'];
$sourceSystem = null;
$targetSystem = null;
$sourceExists = false;
$targetExists = false;
$sameSystem = false;
// system coordinates for system tha might be added next
$systemOffsetX = 130;
$systemOffsetY = 0;
$systemPosX = ((int)$defaultPositions[0]['x']) ? : 0;
$systemPosY = ((int)$defaultPositions[0]['y']) ? : 30;
// check if previous (solo) system is already on the map ----------------------------------------------
$sourceSystem = $map->getSystemByCCPId($sourceSystemId, [AbstractModel::getFilter('active', true)]);
// if systems don´t already exists on map -> get "blank" system
// -> required for system type check (e.g. wormhole, k-space)
if($sourceSystem){
// system exists
$sourceExists = true;
}else{
// system not exists -> get"blank" system
$sourceSystem = $map->getNewSystem($sourceSystemId);
}
// check if source and target systems are equal -------------------------------------------------------
if($sourceSystemId === $targetSystemId){
$sameSystem = true;
$targetExists = $sourceExists;
$targetSystem = $sourceSystem;
}elseif($targetSystemId){
// check if target system is already on this map
$targetSystem = $map->getSystemByCCPId($targetSystemId, [AbstractModel::getFilter('active', true)]);
if($targetSystem){
$targetExists = true;
if($targetSystemId === (int)$currentPosition['systemId']){
$systemPosX = (int)$currentPosition['position']['x'];
$systemPosY = (int)$currentPosition['position']['y'];
}
}else{
$targetSystem = $map->getNewSystem($targetSystemId);
}
}
// make sure we have system objects to work with
// -> in case SDE does not have system they are null -> we can´t do anything
if(
$sourceSystem &&
$targetSystem
){
$addSourceSystem = false;
$addTargetSystem = false;
$addConnection = false;
$route = [];
switch($mapScope->name){
case 'all':
if($sameSystem){
$addSourceSystem = true;
}else{
$addSourceSystem = true;
$addTargetSystem = true;
$addConnection = true;
}
break;
case 'k-space':
if($sameSystem){
if($sourceSystem->isKspace()){
$addSourceSystem = true;
}
}elseif(
$sourceSystem->isKspace() ||
$targetSystem->isKspace()
){
$addSourceSystem = true;
$addTargetSystem = true;
$addConnection = true;
}
break;
case 'wh':
default:
if($sameSystem){
if($sourceSystem->isWormhole()){
$addSourceSystem = true;
}
}elseif(
$sourceSystem->isWormhole() ||
$targetSystem->isWormhole()
){
$addSourceSystem = true;
$addTargetSystem = true;
$addConnection = true;
}elseif(
!$sourceSystem->isWormhole() &&
!$targetSystem->isWormhole()
){
// check distance between systems (in jumps)
// -> if > 1 it is !very likely! a wormhole
$route = (new Controller\Api\Rest\Route())->searchRoute($sourceSystem->systemId, $targetSystem->systemId, 1);
if(!$route['routePossible']){
$addSourceSystem = true;
$addTargetSystem = true;
$addConnection = true;
}
}
break;
}
// check for "abyss" systems =====================================================================
if(!$map->trackAbyssalJumps){
if(
$sourceSystem->isAbyss() ||
$targetSystem->isAbyss()
){
$addConnection = false;
if($sourceSystem->isAbyss()){
$addSourceSystem = false;
}
if($targetSystem->isAbyss()){
$addTargetSystem = false;
}
}
}
// save source system =============================================================================
if(
$addSourceSystem &&
$sourceSystem &&
!$sourceExists
){
$sourceSystem = $map->saveSystem($sourceSystem, $character, $systemPosX, $systemPosY);
// get updated maps object
if($sourceSystem){
$map = $sourceSystem->mapId;
$sourceExists = true;
$mapDataChanged = true;
if(!empty($defaultPositions[1])){
$systemPosX = (int)$defaultPositions[1]['x'];
$systemPosY = (int)$defaultPositions[1]['y'];
}else{
// increase system position (prevent overlapping)
$systemPosX = $sourceSystem->posX + $systemOffsetX;
$systemPosY = $sourceSystem->posY + $systemOffsetY;
}
}
}
// save target system =============================================================================
if(
$addTargetSystem &&
$targetSystem &&
!$targetExists
){
$targetSystem = $map->saveSystem($targetSystem, $character, $systemPosX, $systemPosY);
// get updated maps object
if($targetSystem){
$map = $targetSystem->mapId;
$mapDataChanged = true;
$targetExists = true;
}
}
if(
!$sameSystem &&
$sourceExists &&
$targetExists &&
$sourceSystem &&
$targetSystem
){
$connection = $map->searchConnection($sourceSystem, $targetSystem);
// save connection ============================================================================
if(
$addConnection &&
!$connection
){
// .. do not add connection if character got "podded" -------------------------------------
if(
$targetLog->shipTypeId == 670 &&
$character->cloneLocationId
){
// .. current character location must be clone location
if(
(
'station' == $character->cloneLocationType &&
$character->cloneLocationId == $targetLog->stationId
) || (
'structure' == $character->cloneLocationType &&
$character->cloneLocationId == $targetLog->structureId
)
){
// .. now we need to check jump distance between systems
// -> if > 1 it is !very likely! podded jump
if(empty($route)){
$route = (new Controller\Api\Rest\Route())->searchRoute($sourceSystem->systemId, $targetSystem->systemId, 1);
}
if(!$route['routePossible']){
$addConnection = false;
}
}
}
if($addConnection){
$connection = $map->getNewConnection($sourceSystem, $targetSystem);
$connection = $map->saveConnection($connection, $character);
// get updated maps object
if($connection){
$map = $connection->mapId;
$mapDataChanged = true;
}
}
}
// log jump mass ==============================================================================
if(
$connection &&
$connection->isWormhole()
){
$connection->logMass($targetLog);
}
}
}
}
}
if($mapDataChanged){
$this->broadcastMap($map);
}
return $map;
}
/**
* get connectionData
* @param \Base $f3
* @throws \Exception
*/
public function getConnectionData(\Base $f3){
$postData = (array)$f3->get('POST');
$addData = (array)$postData['addData'];
$filterData = (array)$postData['filterData'];
$connectionData = [];
if($mapId = (int)$postData['mapId']){
$activeCharacter = $this->getCharacter();
/**