Repository navigation
Expand file tree
/
Copy pathmultiplayer.php
More file actions
351 lines (322 loc) · 14.6 KB
/
Copy pathmultiplayer.php
File metadata and controls
351 lines (322 loc) · 14.6 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
<?php
declare(strict_types=1);
/**
* multiplayer.php
*
* DimensioneX Multiplayer Player Gateway.
*
* Serves two types of players:
* 1) Human browser players: Rendered with rich graphical HTML, scene imagery, and UI panels (UIhtml).
* 2) Bot / AI players: API endpoint returning structured JSON room snapshots and command outcomes (UIjson).
*
* Concurrency & World Mutations:
* - Fully encapsulated in Dimx\GameEngine using WorldLock::executeAtomic() (MySQL GET_LOCK).
* - Presentation logic is decoupled into Dimx\UI (UIhtml and UIjson).
*/
if (session_status() === PHP_SESSION_NONE) {
// Support session ID passed explicitly in query, POST, headers, or JSON body (for constrained clients without cookies)
$incomingSessionId = (string)($_GET['session_id'] ?? $_GET['PHPSESSID'] ?? $_POST['session_id'] ?? $_POST['PHPSESSID'] ?? $_SERVER['HTTP_X_SESSION_ID'] ?? '');
if ($incomingSessionId === '') {
$rawInputForSession = file_get_contents('php://input');
if (!empty($rawInputForSession)) {
$parsedJson = json_decode($rawInputForSession, true);
if (is_array($parsedJson) && !empty($parsedJson['session_id'])) {
$incomingSessionId = trim((string)$parsedJson['session_id']);
}
}
}
if ($incomingSessionId !== '' && preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $incomingSessionId)) {
session_id($incomingSessionId);
}
@session_start();
}
require_once __DIR__ . '/autoload.php';
use Dimx\UI;
use Dimx\UIhtml;
use Dimx\UIjson;
use Dimx\UIbot;
use Dimx\GameEngine;
use Dimx\PersistenceManager;
// 1. Bootstrap configuration & persistence
$config = file_exists(__DIR__ . '/config.php') ? require __DIR__ . '/config.php' : [];
$dbConfig = $config['db'] ?? [];
$baseUrl = $config['base_url'] ?? '';
$testBots = (array)($config['testBots'] ?? ['BotAlpha']);
$pm = new PersistenceManager($dbConfig, __DIR__ . '/data');
// Helper to instantiate appropriate Bot UI (UIjson for test bots, UIbot for standard bots)
$createBotUi = function (string $name) use ($testBots): UI {
return in_array($name, $testBots, true) ? new UIjson() : new UIbot();
};
// 2. Parse and sanitize input parameters (POST, GET, and JSON body)
$input = UI::parseInput();
$requestedUser = $input['username'];
$password = $input['password'];
$requestedSkin = $input['skin'] ?? '';
$resetWorld = $input['reset'] || (isset($_GET['reset']) && $_GET['reset'] === '1');
// 3. Determine client type (bot / JSON API vs human / HTML browser)
$clientType = UI::detectClientType();
$sessionUser = (string)($_SESSION['dimx_player'] ?? '');
$activeUsername = !empty($requestedUser) ? $requestedUser : $sessionUser;
$ui = ($clientType === 'json') ? $createBotUi($activeUsername) : new UIhtml();
// 4. Single authoritative world per installation (configured strictly on server, with query/session fallback)
$worldFile = $_SERVER['DIMX_WORLD_FILE'] ?? $_ENV['DIMX_WORLD_FILE'] ?? ($config['world_file'] ?? $config['default_world'] ?? null);
$worldId = trim((string)($_SERVER['DIMX_WORLD_ID'] ?? $_GET['world_id'] ?? $_POST['world_id'] ?? $_SESSION['dimx_world'] ?? ($config['world_id'] ?? 'main')));
// 4b. Invalidate session if world was reset or reset is requested
$activeResetToken = (string)($pm->getSetting($worldId, 'world_reset_token', ''));
if ($resetWorld) {
$pm->resetWorld($worldId);
$activeResetToken = (string)($pm->getSetting($worldId, 'world_reset_token', ''));
unset(
$_SESSION['dimx_player'],
$_SESSION['dimx_authenticated'],
$_SESSION['dimx_numeric_id'],
$_SESSION['dimx_is_bot'],
$_SESSION['dimx_engine_player_id'],
$_SESSION['dimx_skin'],
$_SESSION['dimx_world_obj'],
$_SESSION['dimx_html_tolerant']
);
} elseif ($activeResetToken !== '' && (!isset($_SESSION['dimx_world_reset_token']) || $_SESSION['dimx_world_reset_token'] !== $activeResetToken)) {
unset(
$_SESSION['dimx_player'],
$_SESSION['dimx_authenticated'],
$_SESSION['dimx_numeric_id'],
$_SESSION['dimx_is_bot'],
$_SESSION['dimx_engine_player_id'],
$_SESSION['dimx_skin'],
$_SESSION['dimx_world_obj'],
$_SESSION['dimx_html_tolerant']
);
}
// Instantiate core GameEngine early so UIhtml::renderLogin can list available world SKINS
$engine = new GameEngine($pm, $worldId, $worldFile, $baseUrl, $config);
$ui->setEngine($engine);
// 4c. Special views (e.g. view=players - Section 1.2.16 Who's online)
$view = strtolower(trim((string)($input['view'] ?? $_GET['view'] ?? '')));
if ($view === 'players') {
$world = $engine->loadOrSeedWorld();
$format = trim((string)($input['raw']['format'] ?? $_GET['format'] ?? ''));
$skinName = $requestedSkin !== '' ? $requestedSkin : (string)($_SESSION['dimx_skin'] ?? '');
$skin = $world->getSkin($skinName) ?? $world->defaultSkin ?? new Skin();
$ui->renderPlayers($world, $format, $skin);
exit;
}
if ($view === 'hof') {
$world = $engine->loadOrSeedWorld();
$goals = $pm->getGoals($worldId);
$format = trim((string)($input['raw']['format'] ?? $_GET['format'] ?? ''));
$skinName = $requestedSkin !== '' ? $requestedSkin : (string)($_SESSION['dimx_skin'] ?? '');
$skin = $world->getSkin($skinName) ?? $world->defaultSkin ?? new Skin();
$ui->renderHof($world, $goals, $format, $skin);
exit;
}
// 5. Player Authentication & Account Handling
$sessionUser = (string)($_SESSION['dimx_player'] ?? '');
$isAuthenticated = !empty($_SESSION['dimx_authenticated']);
$numericId = $_SESSION['dimx_numeric_id'] ?? null;
$sessionEngineId = $_SESSION['dimx_engine_player_id'] ?? null;
$isBot = ($clientType === 'json');
$isNewLogin = false;
if ($requestedSkin !== '') {
$_SESSION['dimx_skin'] = $requestedSkin;
}
$activeSkin = $requestedSkin !== '' ? $requestedSkin : (string)($_SESSION['dimx_skin'] ?? '');
// Capture Sounds & Music checkboxes at login form submission or when explicitly passed
$isLoginSubmission = (!empty($requestedUser) && $password !== '');
$explicitSounds = ($isLoginSubmission || !empty($input['has_sounds'])) ? (bool)($input['sounds'] ?? false) : null;
$explicitMusic = ($isLoginSubmission || !empty($input['has_music'])) ? (bool)($input['music'] ?? false) : null;
if ($ui instanceof UI) {
if ($explicitSounds !== null) {
$ui->setSounds($explicitSounds);
}
if ($explicitMusic !== null) {
$ui->setMusic($explicitMusic);
}
}
$activeSounds = $explicitSounds;
$activeMusic = $explicitMusic;
if (!empty($requestedUser)) {
// If client supplied an explicit username:
// Check if session is already authenticated for this exact user
if ($isAuthenticated && $sessionUser === $requestedUser) {
$playerName = $requestedUser;
} elseif ($view === 'msgs' && $password === '') {
$world = $engine->loadOrSeedWorld(false);
$activePlayer = $world->getPlayerByName($requestedUser) ?? $world->getPlayer($requestedUser);
if ($activePlayer !== null) {
$playerName = $activePlayer->name;
$numericId = $activePlayer->numericId;
$sessionEngineId = $activePlayer->id;
$isNewLogin = false;
} else {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Player not found'], JSON_UNESCAPED_UNICODE);
exit;
}
} else {
// Authenticate credentials or auto-create account
if ($password === '') {
$commandStr = ($input['cmd'] ?? 'login') . '(' . ($input['arg0'] ?? '') . ',' . ($input['arg1'] ?? '') . ')';
$dateStr = date('Y-m-d H:i:s');
$engine->log("{$dateStr} USER: {$requestedUser} | COMMAND: {$commandStr} | VIEW: {$view} | ROOM: | STATUS: DISCONNECTED (REFUSAL: password required)");
$engine->executeTick();
if ($ui instanceof UIhtml) {
$ui->renderLogin("Password is required for player '{$requestedUser}'.", $requestedUser, $activeSkin, $ui->hasSounds(), $ui->hasMusic());
} else {
$ui->renderLogin("Password is required for player '{$requestedUser}'.", $requestedUser, $activeSkin);
}
exit;
}
$auth = $pm->authenticateOrCreatePlayer($worldId, $requestedUser, $password, $isBot);
if (!$auth['success']) {
$commandStr = ($input['cmd'] ?? 'login') . '(' . ($input['arg0'] ?? '') . ',' . ($input['arg1'] ?? '') . ')';
$dateStr = date('Y-m-d H:i:s');
$err = $auth['error'] ?? 'Authentication failed';
$engine->log("{$dateStr} USER: {$requestedUser} | COMMAND: {$commandStr} | VIEW: {$view} | ROOM: | STATUS: DISCONNECTED (REFUSAL: {$err})");
$engine->executeTick();
if ($ui instanceof UIhtml) {
$ui->renderLogin($auth['error'] ?? 'Authentication failed.', $requestedUser, $activeSkin, $ui->hasSounds(), $ui->hasMusic());
} else {
$ui->renderLogin($auth['error'] ?? 'Authentication failed.', $requestedUser, $activeSkin);
}
exit;
}
$playerName = (string)($auth['name'] ?? $requestedUser);
$numericId = (int)($auth['numeric_id'] ?? 0);
$isBot = !empty($auth['is_bot']) || $isBot;
$isNewLogin = true;
$sessionEngineId = null;
}
} elseif ($isAuthenticated && $sessionUser !== '') {
// Ongoing authenticated session
$playerName = $sessionUser;
} else {
// No username provided and no authenticated session
$commandStr = ($input['cmd'] ?? 'login') . '(' . ($input['arg0'] ?? '') . ',' . ($input['arg1'] ?? '') . ')';
$dateStr = date('Y-m-d H:i:s');
$engine->log("{$dateStr} USER: anonymous | COMMAND: {$commandStr} | VIEW: {$view} | ROOM: | STATUS: DISCONNECTED (REFUSAL: no session or credentials)");
if ($view === 'msgs') {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Player not specified'], JSON_UNESCAPED_UNICODE);
exit;
}
if ($ui instanceof UIhtml) {
$ui->renderLogin(null, null, $activeSkin, $ui->hasSounds(), $ui->hasMusic());
} else {
$ui->renderLogin(null, null, $activeSkin);
}
exit;
}
// Ensure UI instance matches finalized playerName
if ($clientType === 'json') {
$ui = $createBotUi($playerName);
$ui->setEngine($engine);
}
// Intercept UIbot-specific calls (e.g. toggling HTML tolerance via 'html on' / 'html off')
if ($ui instanceof UIbot && $ui->interceptCall($input, $engine, $playerName, $numericId ? (int)$numericId : null, $sessionEngineId)) {
$_SESSION['dimx_player'] = $playerName;
$_SESSION['dimx_world'] = $worldId;
$_SESSION['dimx_authenticated'] = true;
$_SESSION['dimx_numeric_id'] = $numericId;
$_SESSION['dimx_is_bot'] = $isBot;
$_SESSION['dimx_world_reset_token'] = $activeResetToken;
if ($ui->getPlayer() instanceof Dimx\Player) {
$_SESSION['dimx_engine_player_id'] = $ui->getPlayer()->id;
}
exit;
}
// 8. Process player command inside concurrency critical section
$result = $engine->processCommand(
$playerName,
$input['cmd'],
$input['arg0'],
$input['arg1'],
$ui,
$numericId ? (int)$numericId : null,
(bool)$isBot,
$isNewLogin,
$sessionEngineId,
$activeSkin !== '' ? $activeSkin : null,
$activeSounds,
$activeMusic,
$view !== '' ? $view : ($input['view'] ?? 'scene'),
$input['raw'] ?? []
);
if (!empty($result['login_error'])) {
$dateStr = date('Y-m-d H:i:s');
$engine->log("{$dateStr} USER: {$playerName} | STATUS: DISCONNECTED (REFUSAL: {$result['login_error']})");
unset(
$_SESSION['dimx_player'],
$_SESSION['dimx_authenticated'],
$_SESSION['dimx_numeric_id'],
$_SESSION['dimx_is_bot'],
$_SESSION['dimx_engine_player_id']
);
if ($ui instanceof UIhtml) {
$ui->renderLogin($result['login_error'], $requestedUser, $activeSkin, $ui->hasSounds(), $ui->hasMusic());
} else {
$ui->renderLogin($result['login_error'], $requestedUser, $activeSkin);
}
exit;
}
$result['is_new_login'] = (bool)$isNewLogin;
$_SESSION['dimx_player'] = $playerName;
$_SESSION['dimx_world'] = $worldId;
$_SESSION['dimx_authenticated'] = true;
$_SESSION['dimx_numeric_id'] = $numericId;
$_SESSION['dimx_is_bot'] = $isBot;
$_SESSION['dimx_world_reset_token'] = $activeResetToken;
// Store the active in-memory player ID in session
if (!empty($result['player']) && $result['player'] instanceof Dimx\Player) {
$_SESSION['dimx_engine_player_id'] = $result['player']->id;
}
// 9. If player logged out or world was reset, clear active session
if (!empty($result['logged_out']) || !empty($result['reset'])) {
unset(
$_SESSION['dimx_player'],
$_SESSION['dimx_authenticated'],
$_SESSION['dimx_numeric_id'],
$_SESSION['dimx_is_bot'],
$_SESSION['dimx_engine_player_id'],
$_SESSION['dimx_skin'],
$_SESSION['dimx_html_tolerant']
);
}
// If view is msgs, return JSON payload immediately matching DimensioneX/chat poll format
if ($view === 'msgs') {
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
$response = [
'ok' => true,
'messages' => $result['chat'] ?? [],
];
if (!empty($result['commands'])) {
$response['commands'] = $result['commands'];
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;
}
// 10. Attach UI to player and return outcome via the player's UI
$player = $result['player'] ?? null;
if ($player !== null) {
if (isset($_REQUEST['width']) && (int)$_REQUEST['width'] > 0) {
$_SESSION['dimx_screenwidth'] = (int)$_REQUEST['width'];
}
if (isset($_REQUEST['height']) && (int)$_REQUEST['height'] > 0) {
$_SESSION['dimx_screenheight'] = (int)$_REQUEST['height'];
}
if (isset($_REQUEST['screensize']) && preg_match('/^(\d+)x(\d+)$/i', (string)$_REQUEST['screensize'], $sm)) {
$_SESSION['dimx_screenwidth'] = (int)$sm[1];
$_SESSION['dimx_screenheight'] = (int)$sm[2];
}
if (isset($_SESSION['dimx_screenwidth'])) {
$player->screenWidth = (int)$_SESSION['dimx_screenwidth'];
}
if (isset($_SESSION['dimx_screenheight'])) {
$player->screenHeight = (int)$_SESSION['dimx_screenheight'];
}
$player->isPortrait = ($player->screenWidth > 0 && $player->screenHeight > 0 && $player->screenWidth < $player->screenHeight);
$player->setUI($ui);
$ui->setPlayer($player);
}
$ui->render($result);