forked from kestasjk/webDiplomacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.php
1678 lines (1509 loc) · 53.7 KB
/
api.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
/*
Copyright (C) 2004-2010 Kestas J. Kuliukas / Timothy Jones
This file is part of webDiplomacy.
webDiplomacy is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
webDiplomacy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with webDiplomacy. If not, see <http://www.gnu.org/licenses/>.
*/
use function PHPSTORM_META\map;
define('IN_CODE', 1);
require_once('config.php');
if( Config::isOnPlayNowDomain() ) define('PLAYNOW',true);
require_once('header.php');
require_once('global/definitions.php');
require_once('locales/layer.php');
require_once('objects/database.php');
require_once('objects/memcached.php');
require_once('board/orders/orderinterface.php');
require_once('api/responses/members_in_cd.php');
require_once('api/responses/unordered_countries.php');
require_once('api/responses/active_games.php');
require_once('api/responses/game_state.php');
require_once('objects/game.php');
require_once('objects/user.php');
require_once('lib/cache.php');
require_once('lib/html.php');
require_once('lib/time.php');
require_once('lib/gamemessage.php');
require_once('lib/variant.php');
require_once('board/orders/jsonBoardData.php');
require_once('variants/install.php');
require_once('gamemaster/gamemaster.php');
$DB = new Database();
/**
* Exception class - missing credentials (API key).
*/
class ClientUnauthorizedException extends Exception {
public function __construct($message) {
parent::__construct($message);
}
}
/**
* Exception class - access denied for request sender.
*/
class ClientForbiddenException extends Exception {
public function __construct($message) {
parent::__construct($message);
}
}
/**
* Exception class - server internal error.
*/
class ServerInternalException extends Exception {
public function __construct($message) {
parent::__construct($message);
}
}
/**
* Exception class - request is not implemented.
*/
class NotImplementedException extends Exception {
public function __construct($message) {
parent::__construct($message);
}
}
/**
* Exception class - bad request.
*/
class RequestException extends Exception {
public function __construct($message) {
parent::__construct($message);
}
}
/**
* Handles an error (user or server) in an API request.
* @param string $message - Error message.
* @param int $errorCode - HTTP error code for this error.
*/
function handleAPIError($message, $errorCode) {
header('Content-Type: text/plain');
http_response_code($errorCode);
print $message;
}
/**
* Get header Authorization
* Reference: https://stackoverflow.com/a/40582472
* */
function getAuthorizationHeader() {
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$rawRequestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array();
foreach ($rawRequestHeaders as $key => $value)
$requestHeaders[ucwords($key)] = $value;
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* Reference: https://stackoverflow.com/a/40582472
* */
function getBearerToken() {
$headers = getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
/**
* Return a proper version of API entry route string.
* */
function cleanRoute($route) {
return strtolower(trim($route, " /\t\n\r\0\x0B"));
}
/**
* Class to manage an API entry.
*/
abstract class ApiEntry {
/**
* API entry name.
* @var string
*/
private $route;
/**
* API entry type: either 'GET', 'POST' or 'JSON'.
* If 'JSON', then entry data should be a JSON-encoded string in raw HTTP body (retrievable from 'php://input').
* @var string
*/
private $type;
/**
* Permission field name to check in database for this API entry.
* @var string
*/
private $databasePermissionField;
/**
* Array of parameters names expected for this API entry.
* @var array
*/
protected $requirements;
/**
* Whether to lock the game record for update; increases chance of deadlocks, but prevents game corruption
* @var bool
*/
protected $gameLocking = false;
/**
* Initialize an ApiEntry.
* @param string $route - API entry name.
* @param string $type - API entry type ('GET' or 'POST').
* @param string $databasePermissionField - name of corresponding permission field in database table `wD_ApiPermissions`.
* @param array $requirements - array of API entry parameters names.
* @throws Exception - if invalid type or if requirements is not an array.
*/
public function __construct($route, $type, $databasePermissionField, $requirements, $gameLocking = false) {
if (!in_array($type, array('GET', 'POST', 'JSON')))
throw new ServerInternalException('Invalid API entry type');
if (!is_array($requirements))
throw new ServerInternalException('API entry field names must be an array.');
$this->route = cleanRoute($route);
$this->type = $type;
$this->databasePermissionField = $databasePermissionField;
$this->requirements = $requirements;
$this->gameLocking = $gameLocking;
}
protected function JSONResponse(string $msg, string $referenceCode, bool $success, array $data = [], $JSON_NUMERIC_CHECK = false){
return json_encode([
'msg' => $msg,
'success' => $success,
'referenceCode' =>$referenceCode,
'data' => $data,
], $JSON_NUMERIC_CHECK ? JSON_NUMERIC_CHECK : 0);
}
/**
* Return API entry name.
* @return string
*/
public function getRoute() {
return $this->route;
}
/**
* Return API entry permission field name.
* @return string
*/
public function getPermissionField() {
return $this->databasePermissionField;
}
/**
* Return an array of actual API parameters values, retrieved from $_GET or $_POST, depending on API entry type.
* @return array
* @throws RequestException
*/
public function getArgs() {
$rawArgs = array();
if ($this->type == 'GET')
$rawArgs = $_GET;
else if ($this->type == 'POST')
$rawArgs = $_POST;
else if ($this->type == 'JSON') {
$rawArgs = json_decode(file_get_contents("php://input"), true);
if (!$rawArgs)
throw new RequestException('Invalid JSON request data.');
}
$selectedArgs = array();
foreach ($this->requirements as $fieldName) {
$selectedArgs[$fieldName] = isset($rawArgs[$fieldName]) ? $rawArgs[$fieldName] : null;
}
return $selectedArgs;
}
/**
* Return true if this API entry requires a parameter called `gameID`.
*/
public function requiresGameID() {
return in_array('gameID', $this->requirements);
}
public function isUserMemberOfGame($userID)
{
global $DB;
list($isMember) = $DB->sql_row("SELECT COUNT(id) FROM wD_Members WHERE userID = " . $userID ." AND gameID = " . $this->getAssociatedGameID());
return ($isMember == 1);
}
public function getAssociatedGameID() {
if (!in_array('gameID', $this->requirements))
throw new RequestException('No game ID available for this request.');
$args = $this->getArgs();
$gameID = $args['gameID'];
if ($gameID == null)
throw new RequestException('Game ID not provided.');
return intval($gameID);
}
private $gameCache = null;
/**
* Return Game object for game associated to this API entry call.
* To get associated game, API entry must expect a parameter named `gameID`.
* @param useCache if true, use the cache, otherwise always re-fetch from DB.
* @return Game
* @throws RequestException - if no gameID field in requirements, or if no valid game ID provided.
*/
public function getAssociatedGame($useCache = true) {
global $DB;
if( $useCache && !is_null($this->gameCache) ) return $this->gameCache;
$gameID = $this->getAssociatedGameID();
// This seems to happen when the client loses the game it was on
if( $gameID == 0 )
throw new RequestException("Game ID = 0, invalid request");
$lockMode = $this->gameLocking ? UPDATE : NOLOCK;
$gameRow = Game::fetchRow($gameID, $lockMode);
if( $gameRow === false )
throw new RequestException("Could not fetch row for give gameID, game may have been cancelled");
$Variant = libVariant::loadFromVariantID($gameRow['variantID']);
libVariant::setGlobals($Variant);
$this->gameCache = $Variant->Game($gameRow, $lockMode);
return $this->gameCache; // Lock game for update, which just ensures the game is always processed sequentially, if the game will be updated
}
/**
* Process API call. To override in derived classes.
* @param int $userID - ID of user who makes API call.
* @param bool $permissionIsExplicit - boolean to indicate if permission flag was set for API caller key.
*/
abstract public function run($userID, $permissionIsExplicit);
}
/**
* API entry players/cd
*/
class ListGamesWithPlayersInCD extends ApiEntry {
public function __construct() {
parent::__construct('players/cd', 'GET', 'listGamesWithPlayersInCD', array(), false);
}
public function run($userID, $permissionIsExplicit) {
$countriesInCivilDisorder = new \webdiplomacy_api\CountriesInCivilDisorder();
return $countriesInCivilDisorder->toJson();
}
}
/**
* API entry players/missing_orders
*/
class ListGamesWithMissingOrders extends ApiEntry {
public function __construct() {
parent::__construct('players/missing_orders', 'GET', '', array(), false);
}
public function run($userID, $permissionIsExplicit) {
$unorderedCountries = new \webdiplomacy_api\UnorderedCountries($userID);
return $unorderedCountries->toJson();
}
}
/**
* API entry players/active_games
*/
class ListActiveGamesForUser extends ApiEntry {
public function __construct() {
parent::__construct('players/active_games', 'GET', '', array(), false);
}
public function run($userID, $permissionIsExplicit) {
$activeGames = new \webdiplomacy_api\ActiveGames($userID);
return $activeGames->toJson();
}
}
/**
* API entry game/togglevote
*/
class ToggleVote extends ApiEntry {
public function __construct() {
parent::__construct('game/togglevote', 'GET', '', array('gameID','countryID','vote'), true);
}
public function run($userID, $permissionIsExplicit) {
global $DB;
$args = $this->getArgs();
$gameID = intval($args['gameID']);
$countryID = intval($args['countryID']);
$vote = $args['vote'];
if (!in_array($vote, ['Draw', 'Pause', 'Cancel', 'Concede']))
throw new RequestException('Invalid vote type; allowed are Draw, Concede, Pause, Cancel');
if (!empty(Config::$apiConfig['restrictToGameIDs']) && !in_array($gameID, Config::$apiConfig['restrictToGameIDs']))
throw new ClientForbiddenException('Game ID is not in list of gameIDs where API usage is permitted.');
$currentVotes = $DB->sql_hash("SELECT votes FROM wD_Members WHERE gameID = ".$gameID." AND countryID = ".$countryID." AND userID = ".$userID);
$currentVotes = $currentVotes['votes'];
// Keep a log that a vote was set in the game messages, so the vote time is recorded
require_once(l_r('lib/gamemessage.php'));
$voteOn = in_array($vote, explode(',',$currentVotes));
libGameMessage::send($countryID, $countryID, ($voteOn?'Un-':'').'Voted for '.$vote, $gameID);
$newVotes = '';
if( strpos($currentVotes, $vote) !== false )
{
// The vote is currently set, so unset it:
$voteArr = explode(',',$currentVotes);
$newVoteArr = array();
for($i=0; $i< count($voteArr); $i++)
if( $voteArr[$i] != $vote )
$newVoteArr[] = $voteArr[$i];
$newVotes = implode(',', $newVoteArr);
}
else
{
if( strpos($currentVotes,',') !== false )
$voteArr = explode(',',$currentVotes);
else
$voteArr = array($currentVotes);
$voteArr[] = $vote;
$newVotes = implode(',', $voteArr);
}
$DB->sql_put("UPDATE wD_Members SET votes = '".$newVotes."' WHERE gameID = ".$gameID." AND userID = ".$userID." AND countryID = ".$countryID);
$DB->sql_put("COMMIT");
require_once('lib/pusher.php');
libPusher::trigger("private-game" . $gameID, 'overview', 'processed');
return $newVotes;
}
}
// FIXME - a bit copypasta with the above API call togglevote.
// togglevote also uses GET rather than POST, but GET is not supposed to be used
// for state-modifying web queries. So probably togglevote should be deprecated.
/**
* API entry game/setvote
*/
class SetVote extends ApiEntry {
public function __construct() {
parent::__construct('game/setvote', 'JSON', '', array('gameID','countryID','vote','voteOn'), false);
}
public function run($userID, $permissionIsExplicit) {
global $DB;
$args = $this->getArgs();
$gameID = intval($args['gameID']);
$countryID = intval($args['countryID']);
$vote = $args['vote'];
$voteOn = filter_var($args['voteOn'], FILTER_VALIDATE_BOOLEAN);
if (!in_array($vote, ['Draw', 'Pause', 'Cancel', 'Concede']))
throw new RequestException('Invalid vote type; allowed are Draw, Concede, Pause, Cancel');
if (!empty(Config::$apiConfig['restrictToGameIDs']) && !in_array($gameID, Config::$apiConfig['restrictToGameIDs']))
throw new ClientForbiddenException('Game ID is not in list of gameIDs where API usage is permitted.');
$currentVotes = $DB->sql_hash("SELECT votes FROM wD_Members WHERE gameID = ".$gameID." AND countryID = ".$countryID." AND userID = ".$userID);
$currentVotes = $currentVotes['votes'];
if( $voteOn === in_array($vote, explode(',',$currentVotes)) )
{
return $currentVotes;
}
// Keep a log that a vote was set in the game messages, so the vote time is recorded
require_once(l_r('lib/gamemessage.php'));
libGameMessage::send($countryID, $countryID, ($voteOn?'Un-':'').'Voted for '.$vote, $gameID);
$newVotes = '';
if( strpos($currentVotes, $vote) !== false )
{
// The vote is currently set, so unset it:
$voteArr = explode(',',$currentVotes);
$newVoteArr = array();
for($i=0; $i< count($voteArr); $i++)
if( $voteArr[$i] != $vote )
$newVoteArr[] = $voteArr[$i];
$newVotes = implode(',', $newVoteArr);
}
else
{
if( strpos($currentVotes,',') !== false )
$voteArr = explode(',',$currentVotes);
else
$voteArr = array($currentVotes);
$voteArr[] = $vote;
$newVotes = implode(',', $voteArr);
}
$DB->sql_put("UPDATE wD_Members SET votes = '".$newVotes."' WHERE gameID = ".$gameID." AND userID = ".$userID." AND countryID = ".$countryID);
$DB->sql_put("COMMIT");
require_once(l_r('gamemaster/game.php'));
$game = $this->getAssociatedGame();
// TODO: this should apply votes only for the current game
libGameMaster::findAndApplyGameVotes();
require_once('lib/pusher.php');
libPusher::trigger("private-game" . $gameID, 'overview', 'set-vote');
return $newVotes;
}
}
/**
* API entry websockets/authentication
* https://pusher.com/docs/channels/library_auth_reference/auth-signatures/
* Every time a user subscribes to a channel, it needs to be authenticated and authorized.
* This function works along with beta-src/src/lib/pusher.ts
*/
class WebSocketsAuthentication extends ApiEntry {
public function __construct() {
parent::__construct('websockets/authentication', 'JSON', 'getStateOfAllGames', array('gameID', 'socket_id', 'channel_name'));
}
public function run($userID, $permissionIsExplicit) {
$args = $this->getArgs();
$socketID = $args['socket_id'];
$channelName = $args['channel_name'];
$channelNameParams = explode("-", $channelName);
$gameID = intval(str_replace("game", "", $channelNameParams[1]));
$countryID = 0;
if (count($channelNameParams) > 2) {
$countryID = intval(str_replace("country", "", $channelNameParams[2]));
}
$Game = $this->getAssociatedGame();
// There are 2 authorization validations because a player can
// subscribe to the game overview channel or to the messages channel
// game overview channel doesn't include the countryID, and anyone can subscribe
if ($countryID != 0) {
if (!(isset($Game->Members->ByUserID[$userID]) && $countryID == $Game->Members->ByUserID[$userID]->countryID)) {
throw new ClientForbiddenException('User does not have explicit permission to make this API call.');
}
}
$appKey = Config::$pusherAppKey;
$appSecret = Config::$pusherAppSecret;
$stringToSign = $socketID.":".$channelName;
$hash = hash_hmac('sha256', $stringToSign, $appSecret);
return $this->JSONResponse(
"User was successfully authenticated for this channel",
'',
true,
[
'auth' => $appKey.':'.$hash
]
);
}
}
/**
* API entry game/messagesseen
*/
class MessagesSeen extends ApiEntry {
public function __construct() {
parent::__construct('game/messagesseen', 'JSON', '', array('gameID','countryID','seenCountryID'), false);
}
public function run($userID, $permissionIsExplicit) {
global $Game, $DB;
$args = $this->getArgs();
$countryID = intval($args['countryID']);
$seenCountryID = intval($args['seenCountryID']);
$Game = $this->getAssociatedGame();
$member = $Game->Members->ByUserID[$userID];
$newMessagesFrom = $member->newMessagesFrom;
foreach($newMessagesFrom as $i => $curCountryID)
{
if ( $curCountryID == $seenCountryID )
{
unset($newMessagesFrom[$i]);
break;
}
}
$DB->sql_put("UPDATE wD_Members
SET newMessagesFrom = '".implode(',',$newMessagesFrom)."'
WHERE id = ".$member->id);
$DB->sql_put("COMMIT");
}
}
/**
* API entry game/markbackfromleft
*/
class MarkBackFromLeft extends ApiEntry {
public function __construct() {
parent::__construct('game/markbackfromleft', 'JSON', '', array('gameID','countryID'), true);
}
public function run($userID, $permissionIsExplicit) {
global $Game, $DB;
$args = $this->getArgs();
$countryID = intval($args['countryID']);
$Game = $this->getAssociatedGame();
$member = $Game->Members->ByUserID[$userID];
$member->markBackFromLeft();
$DB->sql_put("COMMIT");
}
}
/**
* API entry game/status
*/
class GetGamesStates extends ApiEntry {
public function __construct() {
parent::__construct('game/status', 'GET', 'getStateOfAllGames', array('gameID', 'countryID'), false);
}
/**
* @throws RequestException
*/
public function run($userID, $permissionIsExplicit) {
$args = $this->getArgs();
$gameID = $args['gameID'];
$countryID = $args['countryID'] ?? null;
if ($gameID === null || !ctype_digit($gameID))
throw new RequestException('Invalid game ID: '.$gameID);
if (!empty(Config::$apiConfig['restrictToGameIDs']) && !in_array($gameID, Config::$apiConfig['restrictToGameIDs']))
throw new ClientForbiddenException('Game ID is not in list of gameIDs where API usage is permitted.');
$game = $this->getAssociatedGame();
if ($countryID != null && (!isset($game->Members->ByUserID[$userID]) || $countryID != $game->Members->ByUserID[$userID]->countryID))
throw new ClientForbiddenException('A user can only view game state for the country it controls.');
$gameState = new \webdiplomacy_api\GameState(intval($gameID), $countryID ? intval($countryID) : null);
return $gameState->toJson();
}
}
/**
* API entry game/members
* Retrieves member data related to a game.
*/
class GetGameMembers extends ApiEntry {
private $isAnon;
private $showDrawVotes;
public function __construct() {
parent::__construct('game/members', 'GET', 'getStateOfAllGames', array('gameID'), false);
}
private function getMembers( $members ){
return array_map( function( $member ){
return $this->getMemberData($member);
}, $members->ByOrder );
}
private function getMemberData(Member $member, bool $retrievePrivateData = false){
$votes = $member->votes;
if(!$this->showDrawVotes && !$retrievePrivateData){
$drawKey = array_search('Draw', $votes);
if($drawKey !== false){
unset($votes[$drawKey]);
$votes = array_values($votes);
}
}
return [
'bet' => $member->bet,
'country' => $member->country,
'countryID' => $member->countryID,
'excusedMissedTurns' => $member->excusedMissedTurns,
'missedPhases' => $member->missedPhases,
'newMessagesFrom' => $retrievePrivateData ? $member->newMessagesFrom : [],
'online' => $member->online,
'orderStatus' => ($this->isAnon && !$retrievePrivateData ? ['Hidden' => 1] : [
'Ready' => $member->orderStatus->Ready,
'Saved' => $member->orderStatus->Saved,
'Completed' => $member->orderStatus->Completed,
'None' => $member->orderStatus->None,
]),
'pointsWon' => $member->pointsWon,
'status' => $member->status,
'supplyCenterNo' => $member->supplyCenterNo,
'timeLoggedIn' => $member->timeLoggedIn,
'unitNo' => $member->unitNo,
'userID' => $member->userID,
'username' => $this->isAnon && $member->Game->gameOver == 'No' && !$retrievePrivateData ? '' : $member->username,
'votes' => $votes,
];
}
public function getData($userID){
$args = $this->getArgs();
$gameID = $args['gameID'];
if ($gameID === null || !ctype_digit($gameID)){
throw new RequestException(
$this->JSONResponse(
'Invalid game ID.',
'ggm-err-001',
false,
['gameID' => $gameID]
)
);
}
$game = $this->getAssociatedGame();
$this->isAnon = $game->anon === 'Yes' ? true : false;
$this->showDrawVotes = $game->drawType === 'draw-votes-public' ? true : false;
$memberData = [
'members' => $this->getMembers( $game->Members ),
];
if (isset($game->Members->ByUserID[$userID])) {
$memberData['user'] = [
'member' => $this->getMemberData($game->Members->ByUserID[$userID], true),
];
}
return $memberData;
}
/**
* @throws RequestException
*/
public function run($userID, $permissionIsExplicit) {
return $this->JSONResponse('Successfully retrieved game members.', 'ggm-s-001', true, $this->getData($userID));
}
}
/**
* API entry game/overview
*
* This should be cleaned up.
*/
class GetGameOverview extends ApiEntry {
public function __construct() {
parent::__construct('game/overview', 'GET', 'getStateOfAllGames', array('gameID'), false);
}
/**
* @throws RequestException
*/
public function run($userID, $permissionIsExplicit) {
$args = $this->getArgs();
$gameID = $args['gameID'];
if ($gameID === null || !ctype_digit($gameID)){
throw new RequestException(
$this->JSONResponse(
'Invalid game ID.',
'GGO-err-001',
false,
['gameID' => $gameID]
)
);
}
if (!empty(Config::$apiConfig['restrictToGameIDs']) && !in_array($gameID, Config::$apiConfig['restrictToGameIDs'])){
throw new ClientForbiddenException(
$this->JSONResponse(
'Game ID is not in list of gameIDs where API usage is permitted.',
'GGO-err-002',
false,
['gameID' => $gameID]
)
);
}
$game = $this->getAssociatedGame();
$dateTxt = $game->datetxt($game->turn);
$split = explode(',', $dateTxt);
$season = $split[0];
$year = intval($split[1] ?? 1901);
$payload = array_merge([
'alternatives' => strip_tags(implode(', ',$game->getAlternatives())),
'anon' => $game->anon,
'drawType' => $game->drawType,
'season' => $season,
'year' => $year,
'excusedMissedTurns' => $game->excusedMissedTurns,
'gameID' => $gameID,
'gameOver' => $game->gameOver,
'isTempBanned' => $game->Members->isTempBanned(),
'minimumBet' => $game->minimumBet,
'name' => $game->name,
'pauseTimeRemaining' => $game->pauseTimeRemaining,
'phase' => $game->phase,
'phaseMinutes' => $game->phaseMinutes,
'phaseMinutesRB'=> $game->phaseMinutesRB,
'playerTypes' => $game->playerTypes,
'pot' => $game->pot,
'potType' => $game->potType,
'processStatus' => $game->processStatus,
'processTime' => $game->processTime,
'pressType' => $game->pressType,
'startTime' => $game->startTime,
'season' => $season,
'turn' => $game->turn,
'variant' => $game->Variant,
'variantID' => $game->variantID,
'year' => $year,
], (new GetGameMembers)->getData($userID));
return $this->JSONResponse('Successfully retrieved game overview.', 'GGO-s-001', true, $payload, true);
}
}
/**
* API entry game/data
* Retrieves API data needed for order generation code and game functionality.
*/
class GetGameData extends ApiEntry {
private $contextVars;
public function __construct() {
parent::__construct('game/data', 'GET', 'getStateOfAllGames', array('gameID', 'countryID'), true);
}
private function setContextVars( $game, $gameID, $userID, $countryID, $member ){
$this->contextVars = (new OrderInterface(
$gameID,
$game->variantID,
$userID,
$member->id,
$game->turn,
$game->phase,
$countryID,
$member->orderStatus,
null,
false
))->load()->getContextVars();
}
private function getContextVars(){
return [
'context' => json_decode($this->contextVars['context']),
'contextKey' => $this->contextVars['contextKey'],
];
}
private function getCurrentOrders(){
return $this->contextVars['ordersData'];
}
private function getUnits($gameID){
return jsonBoardData::getUnitsData($gameID);
}
private function getTerrStatus($gameID){
return jsonBoardData::getTerrStatusData($gameID);
}
/**
* @throws RequestException
*/
public function run($userID, $permissionIsExplicit) {
global $MC;
$args = $this->getArgs();
$gameID = $args['gameID'];
$countryID = $args['countryID'] ?? null;
if (empty($gameID) || !ctype_digit($gameID)){
throw new RequestException(
$this->JSONResponse(
'Invalid game ID.',
'GGD-err-001',
false,
['gameID' => $gameID]
)
);
}
if (!empty(Config::$apiConfig['restrictToGameIDs']) && !in_array($gameID, Config::$apiConfig['restrictToGameIDs'])){
throw new ClientForbiddenException(
$this->JSONResponse(
'Game ID is not in list of gameIDs where API usage is permitted.',
'GGD-err-003',
false,
['gameID' => $gameID]
)
);
}
$game = $this->getAssociatedGame();
$payload = [];
if (!is_null($countryID)){
if (empty($countryID) || !ctype_digit($countryID)){
throw new RequestException(
$this->JSONResponse(
'Invalid country ID.',
'GGD-err-002',
false,
['countryID' => $countryID]
)
);
}
if (!isset($game->Members->ByUserID[$userID]) || $countryID != $game->Members->ByUserID[$userID]->countryID){
throw new ClientForbiddenException(
$this->JSONResponse(
'A user can only view game state for the country it controls.',
'GGD-err-004',
false,
['gameID' => $gameID]
)
);
}
$member = $game->Members->ByCountryID[$countryID];
$this->setContextVars($game, $gameID, $userID, $countryID, $member);
$payload['contextVars'] = $this->getContextVars();
$payload['currentOrders'] = $this->getCurrentOrders();
}
if($game->variantID && is_numeric($game->variantID)){
$territoriesCacheKey = "territories_$game->variantID";
$cachedTerritories = $MC->get($territoriesCacheKey);
if($cachedTerritories){
$payload['territories'] = $cachedTerritories;
}else{
$territories = InstallCache::terrJSONData($game->variantID);
if(!empty($territories)){
$payload['territories'] = $territories;
$secondsInDay = 86400;
$MC->set($territoriesCacheKey, $territories, $secondsInDay);
}
}
}
$payload = array_merge(
$payload,
[
'units' => $this->getUnits($gameID),
'territoryStatuses' => $this->getTerrStatus($gameID),
'turn' => $game->turn,
'phase' => $game->phase,
],
);
return $this->JSONResponse('Successfully retrieved game data.', 'GGD-s-001', true, $payload);
}
}
/**
* API entry game/orders
*/
class SetOrders extends ApiEntry {
public function __construct() {
parent::__construct(
'game/orders',
'JSON',
'submitOrdersForUserInCD',
array('gameID', 'turn', 'phase', 'countryID', 'orders', 'ready'),
false); // This should only require the member record for the country being updated get locked for update, this is how the ajax.php
// order interface locking works. Locking on this is creating 95+% of deadlocks, which is causing 80+% of errors as of 2022-10-12
// 'ready' is optional.
}
/**
* @throws Exception
* @throws RequestException
* @throws ClientForbiddenException
*/
public function run($userID, $permissionIsExplicit) {
global $DB, $MC;
$args = $this->getArgs();
$gameID = $args['gameID']; // checked in getAssociatedGame()
$turn = $args['turn'];
$phase = $args['phase'];
$countryID = $args['countryID'];
$orders = $args['orders'];
$readyArg = $args['ready'];
if ($turn === null)
throw new RequestException('Turn is required.');
if ($phase === null)
throw new RequestException('Phase is required.');
if ($countryID === null)
throw new RequestException('Country is required.');
if (!is_array($orders))
throw new RequestException('Body field `orders` is not an array.');
if ($readyArg && (!is_string($readyArg) || !in_array($readyArg, array('Yes', 'No'))))
throw new RequestException('Body field `ready` is not either `Yes` or `No`.');
if (!empty(Config::$apiConfig['restrictToGameIDs']) && !in_array($gameID, Config::$apiConfig['restrictToGameIDs']))
throw new ClientForbiddenException('Game ID is not in list of gameIDs where API usage is permitted.');
$turn = intval($turn);
$phase = strval($phase);
$countryID = intval($countryID);
// Getting frequent deadlocks when getting the game and locking members for update, perhaps because the permission check has to query members.
// So commit and begin to release anything locked and start over
$DB->sql_put("COMMIT");
$DB->sql_put("BEGIN");
// Lock the member record for update, as this will be updated but the game will not be
$DB->sql_row("SELECT id FROM wD_Members WHERE gameID = ".$gameID." AND countryID = ".$countryID." FOR UPDATE");
$game = $this->getAssociatedGame();
if (!in_array($game->phase, array('Diplomacy', 'Retreats', 'Builds')))
throw new RequestException('Cannot submit orders in phase `'.$game->phase.'`.');
if ($turn != $game->turn)
throw new RequestException('Invalid turn, expected `'.$game->turn.'`, got `'.$turn.'`.');
if ($phase != $game->phase)
throw new RequestException('Invalid phase, expected `'.$game->phase.'`, got `'.$phase.'`.');
if (!isset($game->Members->ByCountryID[$countryID]))
throw new ClientForbiddenException('Unknown country ID `'.$countryID.'`.');
$member = $game->Members->ByCountryID[$countryID]; /** @var Member $member */
if (isset($game->Members->ByUserID[$userID]) && $countryID == $game->Members->ByUserID[$userID]->countryID) {
// API caller is the game member controlling given country ID.
// Setting the member status as Active
$DB->sql_put("UPDATE wD_Members SET userID = ".$userID.", status='Playing', missedPhases = 0, timeLoggedIn = ".time()." WHERE id = ".$member->id);
unset($game->Members->ByUserID[$member->userID]);
unset($game->Members->ByStatus['Playing'][$member->id]);
$member->status='Playing';
$member->missedPhases=0;
$member->timeLoggedIn=time();
$game->Members->ByUserID[$member->userID] = $member;
$game->Members->ByStatus['Playing'][$member->id] = $member;
} else {
// API caller is not a game member controlling given country ID,
// API caller permission must be explicitly set.
if (!$permissionIsExplicit)
throw new ClientForbiddenException('User does not have explicit permission to make this API call.');
// In this case, the ordered country must be in CD.
if ($member->status != 'Left')
throw new ClientForbiddenException(
'A user not controlling a country can submit orders only for a country in CD.');
// We must have enough time to set orders.
$currentTime = time();
if (($currentTime + 60) < $game->processTime) {
throw new RequestException('Process time is not close enough (current time ' . $currentTime . ', process time ' . $game->processTime . ').');
}
}
$territoryToOrder = array();
$orderToTerritory = array();
$updatedOrders = array();
$sql = 'SELECT wD_Orders.id AS orderID, wD_Units.terrID AS terrID FROM wD_Orders
LEFT JOIN wD_Units ON (wD_Orders.gameID = wD_Units.gameID AND wD_Orders.countryID = wD_Units.countryID AND wD_Orders.unitID = wD_Units.id)