-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathxtense.php
More file actions
executable file
·1867 lines (1594 loc) · 87.3 KB
/
xtense.php
File metadata and controls
executable file
·1867 lines (1594 loc) · 87.3 KB
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
global $db, $database, $server_config, $databaseSpyId, $log;
/**
* @package Xtense 2
* @author Unibozu
* @licence GNU
*/
const IN_SPYOGAME = true;
const IN_XTENSE = true;
date_default_timezone_set(@date_default_timezone_get());
$currentFolder = getcwd();
if (str_contains(getcwd(), 'mod')) {
chdir('../../');
}
$_SERVER['SCRIPT_FILENAME'] = str_replace(basename(__FILE__), 'index.php', preg_replace('#/mod/(.*)/#', '/', $_SERVER['SCRIPT_FILENAME']));
include_once("common.php");
list($root, $active) = $db->sql_fetch_row($db->sql_query("SELECT `root`, `active` FROM " . TABLE_MOD . " WHERE `action` = 'xtense'"));
// Récupérer l'origine et vérifier qu'elle existe
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
// Si c'est localhost, s'assurer qu'il a le bon format (http ou https)
if ($origin === 'localhost' || $origin === '') {
$scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$origin = $scheme . 'localhost';
// Si un port est spécifié dans la requête, l'ajouter
if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] !== '80' && $_SERVER['SERVER_PORT'] !== '443') {
$origin .= ':' . $_SERVER['SERVER_PORT'];
}
}
header('Access-Control-Max-Age: 86400'); // cache for 1 day
header("Access-Control-Allow-Origin: {$origin}");
header('Access-Control-Request-Headers: Content-Type');
header("Access-Control-Allow-Methods: POST");
header('X-Content-Type-Options: nosniff');
require_once("mod/$root/includes/config.php");
require_once("mod/$root/includes/functions.php");
require_once("mod/$root/includes/CallbackHandler.php");
require_once("mod/$root/includes/Callback.php");
require_once("mod/$root/includes/Io.php");
require_once("mod/$root/includes/Check.php");
require_once("mod/$root/includes/auth.php");
$start_time = microtime(true);
$io = new Io();
$time = time() - 60 * 4;
if ($time > mktime(0, 0, 0) && $time < mktime(8, 0, 0)) {
$timestamp = mktime(0, 0, 0);
}
if ($time > mktime(8, 0, 0) && $time < mktime(16, 0, 0)) {
$timestamp = mktime(8, 0, 0);
}
if ($time > mktime(16, 0, 0) && $time < (mktime(0, 0, 0) + 60 * 60 * 24)) {
$timestamp = mktime(16, 0, 0);
}
$json = file_get_contents('php://input');
$received_content = json_decode($json, true);
//print_r($received_content);
$args = array(
'type' => FILTER_SANITIZE_SPECIAL_CHARS,
'toolbar_version' => FILTER_SANITIZE_SPECIAL_CHARS,
'toolbar_type' => FILTER_SANITIZE_SPECIAL_CHARS,
'mod_min_version' => FILTER_SANITIZE_SPECIAL_CHARS,
'univers' => FILTER_VALIDATE_URL,
'password' => FILTER_DEFAULT,
'data' => FILTER_DEFAULT
);
$received_game_data = filter_var_array($received_content, $args);
//print_r($received_game_data);
if (!isset($received_game_data['type'])) {
throw new UnexpectedValueException("Xtense data not provided");
}
xtense_check_before_auth($received_game_data['toolbar_version'], $received_game_data['mod_min_version'], $active, $received_game_data['univers']);
$xtense_user_data = xtense_check_auth($received_game_data['password']);
$xtense_user_data = xtense_check_user_rights($xtense_user_data);
$call = new CallbackHandler();
// Xtense : Ajout de la version et du type de barre utilisée par l'utilisateur
$current_user_id = $xtense_user_data['id'];
$db->sql_query("UPDATE " . TABLE_USER . " SET `xtense_version` = '" . $received_game_data['toolbar_version'] . "', `xtense_type` = '" . $received_game_data['toolbar_type'] . "' WHERE `id` = $current_user_id");
$toolbar_info = $received_game_data['toolbar_type'] . " V" . $received_game_data['toolbar_version'];
// Récupération des données de jeu
$data = json_decode($received_game_data['data'], true);
// Meilleur Endroit pour voir ce que l'on récupère de l'extension :-)
//print_r($data);
switch ($received_game_data['type']) {
case 'overview':
{ //PAGE OVERVIEW
if (!$xtense_user_data['grant']['empire']) {
$io->set(array(
'type' => 'plugin grant',
'access' => 'empire'
));
$io->status(0);
} else {
$player_details = filter_var_array($data['playerdetails'], [
'player_name' => FILTER_DEFAULT,
'player_id' => FILTER_DEFAULT,
'playerclass_explorer' => FILTER_DEFAULT,
'playerclass_miner' => FILTER_DEFAULT,
'playerclass_warrior' => FILTER_VALIDATE_INT,
'player_officer_commander' => FILTER_VALIDATE_INT,
'player_officer_amiral' => FILTER_VALIDATE_INT,
'player_officer_engineer' => FILTER_VALIDATE_INT,
'player_officer_geologist' => FILTER_VALIDATE_INT,
'player_officer_technocrate' => FILTER_VALIDATE_INT
]);
$uni_details = filter_var_array(
$data['unidetails'],
[
'uni_version' => FILTER_DEFAULT,
'uni_url' => FILTER_DEFAULT,
'uni_lang' => FILTER_DEFAULT,
'uni_name' => FILTER_DEFAULT,
'uni_time' => FILTER_VALIDATE_INT,
'uni_speed' => FILTER_VALIDATE_INT, // speed_uni
'uni_speed_fleet_peaceful' => FILTER_VALIDATE_INT,
'uni_speed_fleet_war' => FILTER_VALIDATE_INT,
'uni_speed_fleet_holding' => FILTER_VALIDATE_INT,
'uni_donut_g' => FILTER_VALIDATE_INT,
'uni_donut_s' => FILTER_VALIDATE_INT
]
);
$planet_name = filter_var($data['planet']['name'], FILTER_DEFAULT);
$planet_id = filter_var($data['planet']['id'], FILTER_VALIDATE_INT);
$ressources = filter_var_array($data['ressources'], FILTER_VALIDATE_INT);
$temperature_min = filter_var($data['temperature_min'], FILTER_VALIDATE_INT);
$temperature_max = filter_var($data['temperature_max'], FILTER_VALIDATE_INT);
$fields = filter_var($data['fields'], FILTER_VALIDATE_INT);
$coords = Check::coords($data['planet']['coords']);
$planet_type = ((int)$data['planet']['type'] == 0 ? TYPE_PLANET : TYPE_MOON);
$ogame_timestamp = $uni_details['uni_time'];
$userclass = 'none';
if ($player_details['playerclass_miner'] == 1) {
$userclass = 'COL';
} elseif ($player_details['playerclass_warrior'] == 1) {
$userclass = 'GEN';
} elseif ($player_details['playerclass_explorer'] == 1) {
$userclass = 'EXP';
}
// Met à jour les informations du joueur dans la table ogspy_game_player (TABLE_GAME_PLAYER)
// et lie l'ID du joueur de jeu à l'utilisateur OGSpy dans la table ogspy_user (TABLE_USER)
$gamePlayerId = (int)$player_details['player_id'];
if ($gamePlayerId > 0) { // S'assurer que player_id est valide
$gamePlayerName = $db->sql_escape_string($player_details['player_name']);
$officerCommander = (int)$player_details['player_officer_commander'];
$officerAmiral = (int)$player_details['player_officer_amiral'];
$officerEngineer = (int)$player_details['player_officer_engineer'];
$officerGeologist = (int)$player_details['player_officer_geologist'];
$officerTechnocrate = (int)$player_details['player_officer_technocrate'];
$ogameTimestamp = (int)$uni_details['uni_time'];
$currentOgspyUserId = (int)$xtense_user_data['id']; // ID de l'utilisateur OGSpy
$queryGamePlayer = "
INSERT INTO " . TABLE_GAME_PLAYER . " (
`id`, `name`, `class`,
`off_commandant`, `off_amiral`, `off_ingenieur`, `off_geologue`, `off_technocrate`,
`datadate`,
`status`, `ally_id`
) VALUES (
{$gamePlayerId},
'{$gamePlayerName}',
'{$userclass}',
{$officerCommander},
{$officerAmiral},
{$officerEngineer},
{$officerGeologist},
{$officerTechnocrate},
{$ogameTimestamp},
'',
-1
)
ON DUPLICATE KEY UPDATE
`name` = VALUES(`name`),
`class` = VALUES(`class`),
`off_commandant` = VALUES(`off_commandant`),
`off_amiral` = VALUES(`off_amiral`),
`off_ingenieur` = VALUES(`off_ingenieur`),
`off_geologue` = VALUES(`off_geologue`),
`off_technocrate` = VALUES(`off_technocrate`),
`datadate` = VALUES(`datadate`)";
$db->sql_query($queryGamePlayer);
}
// Met à jour TABLE_USER pour stocker le player_id (ID du joueur dans le jeu)
$db->sql_query("UPDATE " . TABLE_USER . " SET `player_id` = {$gamePlayerId} WHERE `id` = {$currentOgspyUserId}");
//Uni Speed
$db->sql_query("INSERT INTO " . TABLE_CONFIG . " (name, value) VALUES ('speed_uni', '{$uni_details['uni_speed']}') ON DUPLICATE KEY UPDATE value = VALUES(value)");
//Uni Speed Peaceful
$db->sql_query("INSERT INTO " . TABLE_CONFIG . " (name, value) VALUES ('speed_fleet_peaceful', '{$uni_details['uni_speed_fleet_peaceful']}') ON DUPLICATE KEY UPDATE value = VALUES(value)");
//Uni Speed War
$db->sql_query("INSERT INTO " . TABLE_CONFIG . " (name, value) VALUES ('speed_fleet_war', '{$uni_details['uni_speed_fleet_war']}') ON DUPLICATE KEY UPDATE value = VALUES(value)");
//Uni Speed holding
$db->sql_query("INSERT INTO " . TABLE_CONFIG . " (name, value) VALUES ('speed_fleet_holding', '{$uni_details['uni_speed_fleet_holding']}') ON DUPLICATE KEY UPDATE value = VALUES(value)");
//Update Config Cache
generate_config_cache();
//boosters
if (isset($data['boosters'])) {
$boosters = update_boosters($data['boosters'], $ogame_timestamp); /*Merge des différents boosters*/
$boosters = booster_encode($boosters); /*Conversion de l'array boosters en string*/
} else {
$boosters = booster_encodev(0, 0, 0, 0, 0, 0, 0, 0); /* si aucun booster détecté*/
}
//Empire
list($g, $s, $r) = explode(':', $coords);
$db->sql_query("INSERT INTO " . TABLE_USER_BUILDING . "
(`player_id`, `id`, `type`, `galaxy`, `system`, `row`, `name`, `fields`, `boosters`, `temperature_min`, `temperature_max`)
VALUES
({$gamePlayerId}, {$planet_id}, '{$planet_type}' , {$g}, {$s}, {$r},'{$planet_name}', {$fields}, '{$boosters}', {$temperature_min}, {$temperature_max})
ON DUPLICATE KEY UPDATE
type = VALUES(type),
name = VALUES(name),
player_id = VALUES(player_id),
fields = VALUES(fields),
boosters = VALUES(boosters),
temperature_min = VALUES(temperature_min),
temperature_max = VALUES(temperature_max),
galaxy = VALUES(galaxy),
system = VALUES(system),
row = VALUES(row)");
$io->set(array(
'type' => 'home updated',
'page' => 'overview',
'planet' => $coords
));
}
// Appel fonction de callback
$call->add('overview', array(
'coords' => explode(':', $coords),
'planet_type' => $planet_type,
'planet_name' => $planet_name,
'fields' => $fields,
'temperature_min' => $temperature_min,
'temperature_max' => $temperature_max,
'ressources' => $ressources
));
add_log('overview', array('coords' => $coords, 'planet_name' => $planet_name, 'toolbar' => $toolbar_info));
}
break;
case 'buildings': //PAGE BATIMENTS
if (!$xtense_user_data['grant']['empire']) {
$io->set(array(
'type' => 'plugin grant',
'access' => 'empire'
));
$io->status(0);
} else {
$coords = filter_var($data['planet']['coords']);
$planet_name = filter_var($data['planet']['name']);
$planet_type = filter_var($data['planet']['type']);
$planet_id = filter_var($data['planet']['id'], FILTER_VALIDATE_INT);
if (!isset($coords, $planet_name, $planet_type)) {
throw new UnexpectedValueException("Buildings- Missing data");
}
$buildings = $data['buildings'];
$coords = Check::coords($coords);
list($g, $s, $r) = explode(':', $coords); // ADDED: Parse coordinates
$planet_type = ((int)$planet_type == TYPE_PLANET ? TYPE_PLANET : TYPE_MOON);
// Construction d'une requête UPSERT pour les bâtiments de la planète
$buildingColumns = [];
$buildingValues = [];
// Préparation des colonnes de base
$buildingColumns[] = 'id'; // ADDED
$buildingValues[] = $planet_id; // ADDED
$buildingColumns[] = 'galaxy'; // ADDED
$buildingValues[] = $g; // ADDED
$buildingColumns[] = 'system'; // ADDED
$buildingValues[] = $s; // ADDED
$buildingColumns[] = 'row'; // ADDED
$buildingValues[] = $r; // ADDED
$buildingColumns[] = 'name'; // RENAMED from 'planet_name'
$buildingValues[] = $planet_name;
// Ajout des bâtiments
foreach ($database['buildings'] as $code) {
if (isset($buildings[$code])) {
$buildingColumns[] = $code;
$buildingValues[] = (int)$buildings[$code];
}
}
// Préparation des champs pour la clause ON DUPLICATE KEY UPDATE
$updatePairs = [];
$updatePairs[] = "name = VALUES(name)"; // CHANGED and RENAMED
$updatePairs[] = "galaxy = VALUES(galaxy)"; // ADDED
$updatePairs[] = "system = VALUES(system)"; // ADDED
$updatePairs[] = "row = VALUES(row)"; // ADDED
foreach ($database['buildings'] as $code) {
if (isset($buildings[$code])) {
$updatePairs[] = "`$code` = VALUES(`$code`)"; // CHANGED to use VALUES()
}
}
// Construction de la requête complète
$query = "INSERT INTO " . TABLE_USER_BUILDING . " (`" . implode('`, `', $buildingColumns) . "`)
VALUES (" . implode(', ', array_map(function ($val) {
return is_numeric($val) ? $val : "'$val'";
}, $buildingValues)) . ")
ON DUPLICATE KEY UPDATE " . implode(', ', $updatePairs);
$db->sql_query($query);
$io->set(array(
'type' => 'home updated',
'page' => 'buildings',
'planet' => $coords
));
}
$call->add('buildings', array(
'coords' => explode(':', $coords),
'planet_type' => $planet_type,
'planet_name' => $planet_name,
'buildings' => $buildings
));
add_log('buildings', array('coords' => $coords, 'planet_name' => $planet_name, 'toolbar' => $toolbar_info));
break;
case 'resourceSettings':
if (!$xtense_user_data['grant']['empire']) {
$io->set(array(
'type' => 'plugin grant',
'access' => 'empire'
));
$io->status(0);
} else {
$coords_str = filter_var($data['planet']['coords']);
$planet_name = filter_var($data['planet']['name']);
$planet_type_int = filter_var($data['planet']['type'], FILTER_VALIDATE_INT);
$planet_id = filter_var($data['planet']['id'], FILTER_VALIDATE_INT);
$resourceSettings_data = isset($data['resourceSettings']) && is_array($data['resourceSettings']) ? $data['resourceSettings'] : null;
if (!isset($coords_str, $planet_name, $planet_type_int) ||
$planet_id === false || $planet_type_int === false || $resourceSettings_data === null
) {
throw new UnexpectedValueException("ResourceSettings: Missing or invalid planet details or resourceSettings data");
}
$coords = Check::coords($coords_str);
list($g, $s, $r) = explode(':', $coords);
// Constante pour le callback (ex: TYPE_PLANET, TYPE_MOON)
$planet_type_const = ($planet_type_int == TYPE_PLANET ? TYPE_PLANET : TYPE_MOON);
// Chaîne pour la base de données ('planet', 'moon')
$astro_object_type_str = ($planet_type_int == TYPE_PLANET ? 'planet' : 'moon');
$columns = [];
$values = [];
// Colonnes de base pour TABLE_USER_BUILDING (ogspy_game_astro_object)
$columns[] = 'id';
$values[] = $planet_id;
$columns[] = 'galaxy';
$values[] = (int)$g;
$columns[] = 'system';
$values[] = (int)$s;
$columns[] = 'row';
$values[] = (int)$r;
$columns[] = 'name';
$values[] = $db->sql_escape_string($planet_name);
$columns[] = 'type';
$values[] = $db->sql_escape_string($astro_object_type_str);
// Colonnes pour les pourcentages de ressources
// Clé JSON => Colonne DB
$resource_settings_map = [
'M_percentage' => 'M_percentage',
'C_Percentage' => 'C_Percentage',
'D_percentage' => 'D_percentage',
'CES_percentage' => 'CES_percentage',
'CEF_percentage' => 'CEF_percentage',
'SAT_percentage' => 'Sat_percentage', // Correction de casse pour la DB
'FOR_percentage' => 'FOR_percentage'
];
foreach ($resource_settings_map as $json_key => $db_col_name) {
$columns[] = $db_col_name;
// Si la clé n'est pas dans les données JSON, mettre 0 (comme pour 'buildings')
$values[] = isset($resourceSettings_data[$json_key]) ? (int)$resourceSettings_data[$json_key] : 100;
}
// Préparation des champs pour la clause ON DUPLICATE KEY UPDATE
$updatePairs = [];
$updatePairs[] = "name = VALUES(name)";
$updatePairs[] = "galaxy = VALUES(galaxy)";
$updatePairs[] = "system = VALUES(system)";
$updatePairs[] = "row = VALUES(row)";
$updatePairs[] = "type = VALUES(type)";
foreach ($resource_settings_map as $json_key => $db_col_name) {
$updatePairs[] = "`$db_col_name` = VALUES(`$db_col_name`)";
}
// Construction de la requête complète
$query = "INSERT INTO " . TABLE_USER_BUILDING . " (`" . implode('`, `', $columns) . "`)
VALUES (" . implode(', ', array_map(function ($val) {
// Les valeurs numériques sont directes, les chaînes (déjà échappées) sont entourées d'apostrophes
return is_numeric($val) ? $val : "'" . $val . "'";
}, $values)) . ")
ON DUPLICATE KEY UPDATE " . implode(', ', $updatePairs);
$db->sql_query($query);
$io->set(array(
'type' => 'home updated',
'page' => 'buildings', // Conformément au code existant pour resourceSettings et à la demande de reproduire 'buildings'
'planet' => $coords
));
// Appel fonction de callback
$call->add('resourceSettings', array( // Nom de callback spécifique
'coords' => explode(':', $coords),
'planet_type' => $planet_type_const, // Utiliser la constante (ex: TYPE_PLANET)
'planet_name' => $planet_name,
'resourceSettings' => $resourceSettings_data // Renvoyer les données JSON originales
));
add_log('resourceSettings', array('coords' => $coords, 'planet_name' => $planet_name, 'toolbar' => $toolbar_info));
}
break;
case 'defense': //PAGE DEFENSE
if (!$xtense_user_data['grant']['empire']) {
$io->set(array(
'type' => 'plugin grant',
'access' => 'empire'
));
$io->status(0);
} else {
$coords = filter_var($data['planet']['coords']);
$planet_name = filter_var($data['planet']['name']);
$planet_id = filter_var($data['planet']['id'], FILTER_VALIDATE_INT);
$planet_type = filter_var($data['planet']['type']);
$defense = $data['defense'];
//Stop si donnée manquante
if (!isset($coords, $planet_name, $planet_type)) {
throw new UnexpectedValueException("Defense: Missing Planet Details");
}
$coords = Check::coords($coords);
list($g, $s, $r) = explode(':', $coords); // Extraire les coordonnées
$planet_type = ((int)$planet_type == TYPE_PLANET ? TYPE_PLANET : TYPE_MOON);
$planet_type_str = ((int)$planet_type == TYPE_PLANET ? 'planet' : 'moon');
$db->sql_query("INSERT INTO " . TABLE_USER_BUILDING . "
(id, type, galaxy, system, row, name, player_id)
VALUES
({$planet_id}, '{$planet_type_str}', {$g}, {$s}, {$r}, '{$planet_name}', {$xtense_user_data['player_id']})
ON DUPLICATE KEY UPDATE
name = '{$planet_name}'");
// Préparer les champs pour la requête d'insertion/mise à jour des défenses
$defense_fields = [];
$defense_values = [];
$update_pairs = [];
foreach ($database['defense'] as $code) {
if (isset($defense[$code])) {
$defense_fields[] = "`$code`";
$defense_values[] = (int)$defense[$code];
$update_pairs[] = "`$code` = " . (int)$defense[$code];
}
}
// Construction de la requête UPSERT pour les défenses
if (!empty($defense_fields)) {
$fields_str = implode(', ', $defense_fields);
$values_str = implode(', ', $defense_values);
$db->sql_query("INSERT INTO " . TABLE_GAME_PLAYER_DEFENSE . "
(astro_object_id, {$fields_str})
VALUES
({$planet_id}, {$values_str})
ON DUPLICATE KEY UPDATE
" . implode(", ", $update_pairs));
}
$io->set(array(
'type' => 'home updated',
'page' => 'defense',
'planet' => $coords
));
// Préparer les données pour le callback
$defenses = array();
foreach ($database['defense'] as $code) {
if (isset($defense[$code])) {
$defenses[$code] = (int)$defense[$code];
}
}
$call->add('defense', [
'coords' => explode(':', $coords),
'planet_type' => $planet_type,
'planet_name' => $planet_name,
'defense' => $defenses
]);
add_log('defense', array('coords' => $coords, 'planet_name' => $planet_name, 'toolbar' => $toolbar_info));
}
break;
case 'researchs': //PAGE RECHERCHE
if (!$xtense_user_data['grant']['empire']) {
$io->set(['type' => 'plugin grant', 'access' => 'empire']);
$io->status(0);
} else {
$coords = filter_var($data['planet']['coords']);
$planet_name = filter_var($data['planet']['name']);
$planet_type = filter_var($data['planet']['type']);
$researchs = $data['researchs'];
if (!isset($coords, $planet_name, $planet_type)) {
throw new UnexpectedValueException("Researchs: Missing Planet Details");
}
$coords = Check::coords($coords);
$planet_type = ((int)$planet_type == TYPE_PLANET ? TYPE_PLANET : TYPE_MOON);
// Vérifier que l'ID du joueur est disponible
if (!isset($xtense_user_data['player_id']) || $xtense_user_data['player_id'] <= 0) {
throw new UnexpectedValueException("Researchs: Player ID not available");
}
$player_id = (int)$xtense_user_data['player_id'];
// Préparer les champs pour la requête d'insertion/mise à jour des technologies
$fields = [];
$values = [];
$update_parts = [];
foreach ($database['labo'] as $code) {
if (isset($researchs[$code])) {
$fields[] = "`$code`";
$values[] = (int)$researchs[$code];
$update_parts[] = "`$code` = " . (int)$researchs[$code];
}
}
// Construction de la requête UPSERT pour les technologies
if (!empty($fields)) {
$fields_str = implode(', ', $fields);
$values_str = implode(', ', $values);
$db->sql_query("INSERT INTO " . TABLE_USER_TECHNOLOGY . "
(`player_id`, {$fields_str})
VALUES
({$player_id}, {$values_str})
ON DUPLICATE KEY UPDATE
" . implode(", ", $update_parts));
}
$io->set(array(
'type' => 'home updated',
'page' => 'labo',
'planet' => $coords
));
$call->add('research', array(
'research' => $researchs
));
add_log('research', array('toolbar' => $toolbar_info));
}
break;
case 'fleet': //PAGE FLOTTE
if (!$xtense_user_data['grant']['empire']) {
$io->set(array(
'type' => 'plugin grant',
'access' => 'empire'
));
$io->status(0);
} else {
$coords = filter_var($data['planet']['coords']);
$planet_name = filter_var($data['planet']['name']);
$planet_type = filter_var($data['planet']['type']);
$planet_id = filter_var($data['planet']['id'], FILTER_VALIDATE_INT);
$fleet = $data['fleet'];
if (!isset($coords, $planet_name, $planet_type)) {
throw new UnexpectedValueException("Fleet: Missing Planet Details");
}
$coords = Check::coords($coords);
list($g, $s, $r) = explode(':', $coords); // Extraire les coordonnées
$planet_type = ((int)$planet_type == TYPE_PLANET ? TYPE_PLANET : TYPE_MOON);
$planet_type_str = ((int)$planet_type == TYPE_PLANET ? 'planet' : 'moon');
$query = "INSERT INTO " . TABLE_USER_BUILDING . " (id, type, galaxy, system, row, name, player_id)
VALUES ({$planet_id}, '{$planet_type_str}', {$g}, {$s}, {$r}, '{$planet_name}', {$xtense_user_data['player_id']})
ON DUPLICATE KEY
UPDATE name = '{$planet_name}'";
$db->sql_query($query);
// Préparer les champs pour la requête d'insertion/mise à jour de la flotte
$fleet_fields = [];
$fleet_values = [];
$update_pairs = [];
foreach ($database['fleet'] as $code) {
if (isset($fleet[$code])) {
$fleet_fields[] = "`$code`";
$fleet_values[] = (int)$fleet[$code];
$update_pairs[] = "`$code` = " . (int)$fleet[$code];
}
}
// Construction de la requête UPSERT pour la flotte
if (!empty($fleet_fields)) {
$fields_str = implode(', ', $fleet_fields);
$values_str = implode(', ', $fleet_values);
$db->sql_query("INSERT INTO " . TABLE_GAME_PLAYER_FLEET . " (astro_object_id, {$fields_str})
VALUES
({$planet_id}, {$values_str})
ON DUPLICATE KEY UPDATE
" . implode(", ", $update_pairs));
}
// Mettre à jour les informations de la flotte de production
foreach ($database['fleet_production'] as $code) {
if (isset($fleet[$code])) {
$fleet_production_fields[] = "`$code`";
$fleet_production_values[] = (int)$fleet[$code];
$update_prod_pairs[] = "`$code` = " . (int)$fleet[$code];
}
}
// Construction de la requête UPSERT pour la flotte
if (!empty($fleet_production_fields)) {
$fields_str = implode(', ', $fleet_production_fields);
$values_str = implode(', ', $fleet_production_values);
$db->sql_query("INSERT INTO " . TABLE_USER_BUILDING . "
(id, {$fields_str})
VALUES
({$planet_id}, {$values_str})
ON DUPLICATE KEY UPDATE
" . implode(", ", $update_prod_pairs));
}
$io->set(array(
'type' => 'home updated',
'page' => 'fleet',
'planet' => $coords
));
$call->add('fleet', array(
'coords' => explode(':', $coords),
'planet_type' => $planet_type,
'planet_name' => $planet_name,
'fleet' => $fleet
));
add_log('fleet', array('coords' => $coords, 'planet_name' => $planet_name, 'toolbar' => $toolbar_info));
}
break;
case 'system': //PAGE SYSTEME SOLAIRE
if (!$xtense_user_data['grant']['system']) {
$io->set(array(
'type' => 'plugin grant',
'access' => 'system'
));
$io->status(0);
} else {
$galaxy = filter_var($data['galaxy'], FILTER_SANITIZE_NUMBER_INT);
$system = filter_var($data['system'], FILTER_SANITIZE_NUMBER_INT);
if (!isset($galaxy, $system)) {
throw new UnexpectedValueException("Galaxy: Missing Planet position");
}
if ($galaxy > $server_config['num_of_galaxies'] || $system > $server_config['num_of_systems']) {
$io->set(array(
'type' => 'plugin univers',
'access' => 'system'
));
$io->status(0);
}
$delete = [];
$update = [];
$query = "SELECT `row` FROM " . TABLE_USER_BUILDING . " WHERE `galaxy` = {$galaxy} AND `system` = {$system}";
$check = $db->sql_query($query);
while ($value = $db->sql_fetch_assoc($check)) {
$update[$value['row']] = true;
}
$rows = $data['rows'];
// Recupération des données
for ($i = 1; $i < 16; $i++) {
if (isset($rows[$i])) {
$line = $rows[$i];
$line['player_name'] = filter_var($line['player_name']);
$line['planet_name'] = filter_var($line['planet_name']);
$line['planet_id'] = filter_var($line['planet_id'], FILTER_VALIDATE_INT);
$line['ally_tag'] = filter_var($line['ally_tag']);
if (isset($line['debris'])) {
$line['debris'] = filter_var_array($line['debris'], [
'metal' => FILTER_SANITIZE_NUMBER_INT,
'crystal' => FILTER_SANITIZE_NUMBER_INT,
'deuterium' => FILTER_SANITIZE_NUMBER_INT,
]);
}
if (isset($line['status'])) {
$line['status'] = filter_var($line['status']);
}
$system_data[$i] = $line;
} else {
$delete[] = $i;
$system_data[$i] = array(
'planet_id' => '',
'planet_name' => '',
'player_name' => '',
'status' => '',
'ally_tag' => '',
'debris' => array('metal' => 0, 'cristal' => 0, 'deuterium' => 0),
'moon' => 0,
'activity' => ''
);
}
}
foreach ($system_data as $row => $v) {
$statusTemp = (Check::player_status_forbidden($v['status']) ? "" : $v['status']); //On supprime les status qui sont subjectifs
//default player_id/ally_id à -1 (cf shemas SQL)
$v['player_id'] = (isset($v['player_id']) ? (int)$v['player_id'] : -1);
$v['planet_id'] = (isset($v['planet_id']) ? (int)$v['planet_id'] : -1);
$v['moon'] = (isset($v['moon']) ? (int)$v['moon'] : -1);
$v['moon_id'] = (isset($v['moon_id']) ? (int)$v['moon_id'] : -1);
$v['ally_id'] = (isset($v['ally_id']) ? (int)$v['ally_id'] : -1);
$v['ally_tag'] = $v['ally_tag'] ?? '';
$db->sql_query("INSERT INTO " . TABLE_USER_BUILDING . "
(`id`, `galaxy`, `system`, `row`, `name`, `player_id`, `last_update`, `last_update_user_id`)
VALUES
({$v['planet_id']},{$galaxy}, {$system}, {$row}, '{$v['planet_name']}', {$v['player_id']}, " . time() . ", {$xtense_user_data['id']} )
ON DUPLICATE KEY UPDATE
`name` = '{$v['planet_name']}',
`player_id` = {$v['player_id']},
`last_update` = " . time() . ",
`last_update_user_id` = {$xtense_user_data['id']}");
// Création des lignes pour les lunes
if (isset($v['moon_id']) && $v['moon'] == 1) {
$db->sql_query("INSERT INTO " . TABLE_USER_BUILDING . "
(`id`, `type`, `galaxy`, `system`, `row`, `name`, `player_id`, `last_update_moon`, `last_update_user_id`)
VALUES
({$v['moon_id']}, 'moon',{$galaxy}, {$system}, {$row}, '{$v['planet_name']} - Moon', {$v['player_id']}, " . time() . ", {$xtense_user_data['id']} )
ON DUPLICATE KEY UPDATE
`name` = '{$v['planet_name']} - Moon',
`player_id` = {$v['player_id']},
`last_update_moon` = " . time() . ",
`last_update_user_id` = {$xtense_user_data['id']}");
}
// UPSERT pour la table game_player pour mettre à jour le statut
if ($v['player_id'] != -1) {
$currentTime = time();
$playerId = (int)$v['player_id'];
$playerName = $db->sql_escape_string($v['player_name']);
$status = $db->sql_escape_string($statusTemp);
$allyId = (int)$v['ally_id'];
$db->sql_query("INSERT INTO " . TABLE_GAME_PLAYER . "
(`id`, `name`, `status`, `ally_id`, `datadate`)
VALUES
($playerId, '$playerName', '$status', $allyId, $currentTime)
ON DUPLICATE KEY UPDATE
`name` = '$playerName',
`status` = '$status',
`ally_id` = $allyId,
`datadate` = $currentTime");
}
//La table game ally ne peut se mettre à jour, champs ally non alimenté (toutes les infos sont dans page rank)
// UPSERT pour la table game_player pour mettre à jour le statut
if ($v['ally_id'] > 0) {
$currentTime = time();
$allytag = $v['ally_tag'];
$allyId = $v['ally_id'];
$db->sql_query("INSERT INTO " . TABLE_GAME_ALLY . "
(`id`, `tag`, `datadate`)
VALUES
($allyId, '$allytag', $currentTime)
ON DUPLICATE KEY UPDATE
`tag` = '$allytag',
`datadate` = $currentTime");
}
}
if (!empty($delete)) {
$toDelete = array();
foreach ($delete as $n) {
$toDelete[] = $galaxy . ':' . $system . ':' . $n;
}
}
$db->sql_query("UPDATE " . TABLE_USER . " SET `planet_imports` = `planet_imports` + 15 WHERE `id` = " . $xtense_user_data['id']);
$call->add('system', array(
'data' => $data['rows'],
'galaxy' => $galaxy,
'system' => $system
));
$io->set(array(
'type' => 'system',
'galaxy' => $galaxy,
'system' => $system
));
update_statistic('planetimports', 15);
add_log('system', array('coords' => $galaxy . ':' . $system, 'toolbar' => $toolbar_info));
}
break;
case 'ranking': //PAGE STATS
$type1 = filter_var($data['type1']);
$type2 = filter_var($data['type2']);
$type3 = filter_var($data['type3']) ?? 0;
$offset = filter_var($data['offset'], FILTER_SANITIZE_NUMBER_INT);
$date = filter_var($data['time']);
if (!isset($type1, $type2, $offset, $data['n'], $date)) {
throw new UnexpectedValueException("Rankings: Incomplete Ranking");
}
if (!$xtense_user_data['grant']['ranking']) {
$io->set(array(
'type' => 'plugin grant',
'access' => 'ranking'
));
$io->status(0);
} else {
if ($type1 != ('player' || 'ally')) {
throw new UnexpectedValueException("Ranking: Unexpected Ranking type for type1");
}
}
//Vérification Offset
if ((($offset - 1) % 100) != 0) {
throw new UnexpectedValueException("Ranking: Offset not found");
}
$n = $data['n'];
$total = 0;
$count = count($n);
if ($type1 == 'player') {
$table = match ($type2) {
'points' => TABLE_RANK_PLAYER_POINTS,
'economy' => TABLE_RANK_PLAYER_ECO,
'research' => TABLE_RANK_PLAYER_TECHNOLOGY,
'fleet' => match ($type3) {
'5' => TABLE_RANK_PLAYER_MILITARY_BUILT,
'6' => TABLE_RANK_PLAYER_MILITARY_DESTRUCT,
'4' => TABLE_RANK_PLAYER_MILITARY_LOOSE,
'7' => TABLE_RANK_PLAYER_HONOR,
default => throw new OutOfRangeException("Ranking Player: Unexpected Ranking type for type3: " . $type3),
},
default => throw new UnexpectedValueException("Ranking Player: Unexpected Ranking type for type2: " . $type2),
};
} else {
$table = match ($type2) {
'points' => TABLE_RANK_ALLY_POINTS,
'economy' => TABLE_RANK_ALLY_ECO,
'research' => TABLE_RANK_ALLY_TECHNOLOGY,
'fleet' => match ($type3) {
'5' => TABLE_RANK_ALLY_MILITARY_BUILT,
'6' => TABLE_RANK_ALLY_MILITARY_DESTRUCT,
'4' => TABLE_RANK_ALLY_MILITARY_LOOSE,
'7' => TABLE_RANK_ALLY_HONOR,
default => throw new OutOfRangeException("Ranking Ally: Unexpected Ranking type for type3: " . $type3),
},
default => throw new UnexpectedValueException("Ranking Ally: Unexpected Ranking type for type2: " . $type2),
};
}
$query = array();
if ($type1 == 'player') {
foreach ($n as $data) {
// Vérification des données essentielles
$data['player_name'] = filter_var($data['player_name']);
$data['ally_tag'] = filter_var($data['ally_tag']);
if (!empty($data['points'])) {
$data['points'] = (int)$data['points'];
}
$data['ally_id'] = !empty($data['ally_id']) ? (int)$data['ally_id'] : -1;
$data['player_id'] = !empty($data['player_id']) ? (int)$data['player_id'] : -1;
//Compléter table GAME PLAYER pour les joueurs qui n'ont pas de compte
if ($data['player_id'] > 0 && !empty($data['player_name'])) {
$db->sql_query("INSERT INTO " . TABLE_GAME_PLAYER . "
(id, name, ally_id, datadate)
VALUES
({$data['player_id']}, '{$data['player_name']}', {$data['ally_id']}, " . time() . ")
ON DUPLICATE KEY UPDATE
name = VALUES(name),
ally_id = VALUES(ally_id),
datadate = VALUES(datadate)");
}
//Compléter table GAME ALLY pour les alliances qui n'ont pas de compte
// Insert or update alliance data in the GAME ALLY table
if ($data['ally_id'] > 0 && !empty($data['ally_tag'])) {
$db->sql_query("INSERT INTO " . TABLE_GAME_ALLY . "
(id, tag, datadate)
VALUES
({$data['ally_id']}, '{$data['ally_tag']}', " . time() . ")
ON DUPLICATE KEY UPDATE
tag = VALUES(tag),
datadate = VALUES(datadate)");
}
if ($table == TABLE_RANK_PLAYER_MILITARY) {
$query[] = "({$timestamp}, {$data['rank']}, '{$data['player_name']}' , {$data['player_id']}, '{$data['ally_tag']}', {$data['ally_id']}, {$data['points']}, {$xtense_user_data['id']}, {$data['nb_spacecraft']} )";
} else {
$query[] = "({$timestamp}, {$data['rank']}, '{$data['player_name']}' , {$data['player_id']}, '{$data['ally_tag']}', {$data['ally_id']}, {$data['points']}, {$xtense_user_data['id']} )";
}
$total++;
$datas[] = $data;
if (!empty($query)) {
if ($table == TABLE_RANK_PLAYER_MILITARY) {
$db->sql_query("REPLACE INTO " . $table . " (`datadate`, `rank`, `player`, `player_id`, `ally`, `ally_id`, `points`, `sender_id`, `nb_spacecraft`) VALUES " . implode(',', $query));
} else {
$db->sql_query("REPLACE INTO " . $table . " (`datadate`, `rank`, `player`, `player_id`, `ally`, `ally_id`, `points`, `sender_id`) VALUES " . implode(',', $query));
}
}
}
} else {
$fields = 'datadate, rank, ally, ally_id, points, sender_id, number_member, points_per_member';
foreach ($n as $data) {
$data['ally_tag'] = filter_var($data['ally_tag']);
$data['ally_name'] = filter_var($data['ally']);
$data['ally_id'] = filter_var($data['ally_id'] ?? throw new UnexpectedValueException("Ranking Ally: Alliance Id not found"), FILTER_SANITIZE_NUMBER_INT);
$data['points'] = filter_var($data['points'] ?? throw new UnexpectedValueException("Ranking Ally: No points sent"), FILTER_SANITIZE_NUMBER_INT);
$data['mean'] = filter_var($data['mean'] ?? throw new UnexpectedValueException("Ranking Ally: No mean found"), FILTER_SANITIZE_NUMBER_INT);
$data['members'] = filter_var($data['members'] ?? throw new UnexpectedValueException("Ranking Ally: Nb players not found"), FILTER_SANITIZE_NUMBER_INT);