Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed bugs and added API #572

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions .htaccess
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

# redirect requests for API to api.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/([^/]+)/?$ %{ENV:BASE}api.php?endpoint=$1 [L,QSA]

# redirect requests to public folder
RewriteCond %{THE_REQUEST} /public/([^\s?]*) [NC]
RewriteRule ^ %1 [L,NE,R=302]

RewriteRule ^((?!public/).*)$ %{ENV:BASE}/public/$1 [L,NC]
</IfModule>
RewriteRule ^((?!public/).*)$ %{ENV:BASE}public/$1 [L,NC]
</IfModule>
8 changes: 8 additions & 0 deletions app/Http/Controllers/Install/InstallationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,14 @@ private function writeConfigFile()
$data .= "defined('DB_NAME') ? null : define('DB_NAME', '" . $this->db_name . "');\n";
$data .= "defined('DB_PREFIX') ? null : define('DB_PREFIX', '" . $this->db_prefix . "');\n";
$data .= "defined('SECRETWORD') ? null : define('SECRETWORD', 'xgp-" . StringsHelper::randomString(16) . "');\n";
$data .= "\n//This is added to allow API pull from database\n";
$data .= '$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;' . "\n";
$data .= '$options = [' . "\n";
$data .= " PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n";
$data .= " PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n";
$data .= " PDO::ATTR_EMULATE_PREPARES => false,\n";
$data .= "];\n";
$data .= '$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);' . "\n";
$data .= '?>';

// create the new file
Expand Down
1 change: 1 addition & 0 deletions app/Libraries/BattleEngine/CombatObject/PhysicShot.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class PhysicShot
private $bouncedDamage = 0;
private $hullDamage = 0;
private $cellDestroyed = 0;
private $fighters;

/**
* PhysicShot::__construct()
Expand Down
4 changes: 2 additions & 2 deletions app/Libraries/BattleEngine/Core/BattleReport.php
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ public function getAttackerDebris()
$metal += $lost[0];
$crystal += $lost[1];
}
$factor = constant(strtoupper($role) . '_DEBRIS_FACTOR');
$factor = constant(strtoupper($role) . 'SHIPS_DEBRIS_FACTOR');
$sendMetal += $metal * $factor;
$sendCrystal += $crystal * $factor;
}
Expand All @@ -278,7 +278,7 @@ public function getDefenderDebris()
$metal += $lost[0];
$crystal += $lost[1];
}
$factor = constant(strtoupper($role) . '_DEBRIS_FACTOR');
$factor = constant(strtoupper($role) . 'DEFENSE_DEBRIS_FACTOR');
$sendMetal += $metal * $factor;
$sendCrystal += $crystal * $factor;
}
Expand Down
19 changes: 19 additions & 0 deletions public/api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

$endpoint = $_GET['endpoint'] ?? null;
$acceptsHtml = strpos($_SERVER['HTTP_ACCEPT'], 'text/html') !== false;
define('XGP_ROOT', realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR);

switch ($endpoint) {
case 'players':
$data = include XGP_ROOT . '/public/api/PlayerData.php';
break;
case 'universe':
$data = include XGP_ROOT . '/public/api/ServerData.php';
break;
//Add other endpoints as needed
default:
header("HTTP/1.0 404 Not Found");
$data = ['error' => 'Endpoint not found'];
break;
}
129 changes: 129 additions & 0 deletions public/api/PlayerData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php
require (dirname( __FILE__, 3 ) .'/config/config.php'); // Assuming your config file is in the default XGP location

// Fetch data from {$db_prefix}_users table
$stmt = $pdo->prepare("SELECT user_id, user_name, user_authlevel, user_ally_id FROM " . DB_PREFIX . "users");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

$final_json_colored = "";

// Process and transform user data
$playerData = [];
foreach ($users as $user) {
$playerType = '';
switch ($user['user_authlevel']) {
case 0:
$playerType = 'Player';
break;
case 1:
$playerType = 'GO';
break;
case 2:
$playerType = 'SGO';
break;
case 3:
$playerType = 'Admin';
break;
}

// Fetching planet data for the user
$planetStmt = $pdo->prepare("SELECT planet_id, planet_galaxy, planet_system, planet_planet, planet_type FROM ge1_planets WHERE planet_user_id = ? ORDER BY planet_galaxy, planet_system, planet_planet");
$planetStmt->execute([$user['user_id']]);
$planets = $planetStmt->fetchAll(PDO::FETCH_ASSOC);

$planetData = [];
$previousCoordinates = "";
foreach ($planets as $planet) {
$coordinates = $planet['planet_galaxy'] . ':' . $planet['planet_system'] . ':' . $planet['planet_planet'];

if ($planet['planet_type'] == 3 && $coordinates === $previousCoordinates) {
end($planetData); // Move internal pointer to the end of the array
$planetData[key($planetData)]['Coordinates'] .= " (m)";
} else {
$planetID = $planet['planet_type'] == 1 ? 'Planet ID' : 'Moon ID';
$planetData[] = [
$planetID => $planet['planet_id'],
'Coordinates' => $coordinates
];
$previousCoordinates = $coordinates;
}
}

// Fetching player statistics data
$statsStmt = $pdo->prepare("SELECT user_statistic_buildings_points, user_statistic_defenses_points, user_statistic_ships_points, user_statistic_technology_points FROM ge1_users_statistics WHERE user_statistic_user_id = ?");
$statsStmt->execute([$user['user_id']]);
$statistics = $statsStmt->fetch(PDO::FETCH_ASSOC);

// Preparing the player data array
$playerInfo = [
'Player Name' => $user['user_name'],
'Player Type' => $playerType
];

// Include the Ally ID only if it's set and not null
if (isset($user['user_ally_id']) && $user['user_ally_id'] != 0) {
$playerInfo['Ally ID'] = $user['user_ally_id'];
}

$playerInfo['Planets'] = $planetData;
$playerInfo['Economy Points'] = number_format(intval($statistics['user_statistic_buildings_points']));
$playerInfo['Defense Points'] = number_format(intval($statistics['user_statistic_defenses_points']));
$playerInfo['Fleet Points'] = number_format(intval($statistics['user_statistic_ships_points']));
$playerInfo['Research Points'] = number_format(intval($statistics['user_statistic_technology_points']));


// Add "PlayerID_" title to the user_id key
$key = 'PlayerID_' . $user['user_id'];
$playerData[$key] = $playerInfo;

// Output Pretty JSON
$playerJson = json_encode([$key => $playerInfo], JSON_PRETTY_PRINT);

$json_colored = preg_replace_callback('/("(\\\\u[a-zA-Z0-9]{4}|\\\\.|[^"\\\\])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/', function ($match) use ($playerType) {
$cls = 'number';
if (preg_match('/^"/', $match[0])) {
if (preg_match('/:$/', $match[0])) {
$cls = 'key ' . $playerType;
} else {
$cls = 'string ' . $playerType;
}
} elseif (preg_match('/(true|false|null)\b/', $match[0])) {
$cls = 'bool';
}
return "<span class=\"$cls\">$match[0]</span>";
}, $playerJson);

$final_json_colored .= $json_colored . ",\n";
}

$final_json_colored = rtrim($final_json_colored, ",\n");
$json_no_brackets = preg_replace('/[{}\[\]]/', '', $final_json_colored);

// Output the styled JSON without curly braces and square brackets
echo <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Players API Results</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
pre { background-color: #f5f5f5; padding: 10px; border: 1px solid #ddd; }
code { color: #333; }
.key { color: blue; }
.string { color: green; }
.number { color: green; }
.bool { color: #955; }
.string.Admin { color: red; }
.string.GO, .string.SGO { color: orange; }
</style>
</head>
<body>
<pre><code>$json_no_brackets</code></pre>
</body>
</html>
HTML;

?>
64 changes: 64 additions & 0 deletions public/api/ServerData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php
require (dirname( __FILE__, 3 ) .'/config/config.php'); // Assuming your config file is in the default XGP location

// Fetching relevant game settings based on Option_id values
$option_ids = [1, 4, 5, 15, 16, 22];
$placeholders = implode(',', array_fill(0, count($option_ids), '?'));
$stmt = $pdo->prepare("SELECT Option_id, Option_name, Option_value FROM ge1_options WHERE Option_id IN ($placeholders)");
$stmt->execute($option_ids);
$options = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Transforming the fetched data
$serverdata = [];
foreach ($options as $option) {
switch ($option['Option_id']) {
case 1:
$serverdata['Universe'] = $option['Option_value'];
break;
case 4:
$serverdata['Uni Speed'] = $option['Option_value'] / 2500;
break;
case 5:
$serverdata['Fleet Speed'] = $option['Option_value'] / 2500;
break;
case 15:
$serverdata['Fleet to debris'] = $option['Option_value'] / 100;
break;
case 16:
$serverdata['Def to debris'] = $option['Option_value'] / 100;
break;
case 22:
$serverdata['Initial Planet Fields'] = $option['Option_value'];
break;
}
}

$json = json_encode($serverdata, JSON_PRETTY_PRINT);

// Remove curly braces and square brackets from the JSON
$json_no_brackets = preg_replace('/[{}\[\]]/', '', $json);

// Output the styled JSON in HTML
echo <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Universe Settings API Result</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
pre { background-color: #f5f5f5; padding: 10px; border: 1px solid #ddd; }
code { color: #333; }
.key { color: blue; }
.string { color: green; }
.number { color: red; }
.bool { color: #955; }
</style>
</head>
<body>
<pre><code>$json_no_brackets</code></pre>
</body>
</html>
HTML;
?>