| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- <?php
- /**
- * Unit api.
- *
- * Exposes an API to get a list of units of a player, or a unit details.
- * Used POST parameters are:
- * - key: User API key. If not, only public user's unit can be seen.
- *
- * @category API
- * @magic $params URL parameters:
- * 1: User ID
- * 2: Unit ID (optional)
- */
- global $db;
- try{
- if (count($params) <= 1){
- http_response_code(400);
- return 400;
- }
- $uid = $params[1];
- $id = null;
- if (count($params) > 2){
- $id = $params[2];
- }
- // Check API key or public profile.
- if (isset($_POST['key'])){
- $key = filter_input(INPUT_POST, 'key');
- }
- else{
- $key = "";
- }
- $s = "SELECT COUNT(uid) AS c FROM player WHERE uid = $uid AND (public = 1 OR api_key = '$key');";
- if (1 != $db->query($s)->fetchArray(SQLITE3_ASSOC)["c"]){
- http_response_code(401);
- return 401;
- }
- // No unit ID specified, show a list.
- if ($id == null){
- $units = [];
- $s = "SELECT id, '" . URL::BASE . "API/v2/units/$uid/' || id AS uri FROM unit WHERE uid = '$uid'";
- $q = $db->query($s);
- $content = false;
- while ($r = $q->fetchArray(SQLITE3_ASSOC)){
- array_push($units, $r);
- $content = true;
- }
- if ($content == true){
- header('Content-Type: application/json');
- echo json_encode($units);
- http_response_code(200);
- return 200;
- }
- else{
- http_response_code(204);
- return 204;
- }
- }
- // Specific unit, show details.
- else{
- $s = "SELECT * FROM unit WHERE uid = '$uid' AND id = '$id'";
- $q = $db->query($s);
- if($r = $q->fetchArray(SQLITE3_ASSOC)){
- $unit = $r;
- // Runes
- $unit["runes"] = [];
- $s = "SELECT * FROM rune WHERE assigned_to = '" . $unit["id"] . "' ORDER BY slot;";
- $q = $db->query($s);
- while ($r = $q->fetchArray(SQLITE3_ASSOC)){
- $rune = $r;
- unset($rune["uid"]); # Not needed
- unset($rune["assigned_to"]); # Not needed
- array_push($unit["runes"], $rune);
- }
- // Skills
- $unit["skills"] = [];
- $s = "SELECT skill, level FROM unit_skill WHERE unit = '" . $unit["id"] . "';";
- $q = $db->query($s);
- while ($r = $q->fetchArray(SQLITE3_ASSOC)){
- array_push($unit["skills"], $r);
- }
- header('Content-Type: application/json');
- echo json_encode($unit);
- http_response_code(200);
- return 200;
- }
- else{
- http_response_code(404);
- return 404;
- }
- }
- }
- catch(Exception $e) {
- error_log("Unknown error fetching units: " . $e->getMessage());
- http_response_code(500);
- return 500;
- }
- ?>
|