units.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. * Unit api.
  4. *
  5. * Exposes an API to get a list of units of a player, or a unit details.
  6. * Used POST parameters are:
  7. * - key: User API key. If not, only public user's unit can be seen.
  8. *
  9. * @category API
  10. * @var mixed[] $params URL parameters.
  11. */
  12. global $db;
  13. try{
  14. if (count($params) <= 1){
  15. http_response_code(400);
  16. return 400;
  17. }
  18. $uid = $params[1];
  19. $id = null;
  20. if (count($params) > 2){
  21. $id = $params[2];
  22. }
  23. // Check API key or public profile.
  24. if (isset($_POST['key'])){
  25. $key = filter_input(INPUT_POST, 'key');
  26. }
  27. else{
  28. $key = "";
  29. }
  30. $s = "SELECT COUNT(uid) AS c FROM player WHERE uid = $uid AND (public = 1 OR api_key = '$key');";
  31. if (1 != $db->query($s)->fetchArray(SQLITE3_ASSOC)["c"]){
  32. http_response_code(401);
  33. return 401;
  34. }
  35. // No unit ID specified, show a list.
  36. if ($id == null){
  37. $units = [];
  38. $s = "SELECT id, '" . URL::BASE . "API/v2/units/$uid/' || id AS uri FROM unit WHERE uid = '$uid'";
  39. $q = $db->query($s);
  40. $content = false;
  41. while ($r = $q->fetchArray(SQLITE3_ASSOC)){
  42. array_push($units, $r);
  43. $content = true;
  44. }
  45. if ($content == true){
  46. header('Content-Type: application/json');
  47. echo json_encode($units);
  48. http_response_code(200);
  49. return 200;
  50. }
  51. else{
  52. http_response_code(204);
  53. return 204;
  54. }
  55. }
  56. // Specific unit, show details.
  57. else{
  58. $s = "SELECT * FROM unit WHERE uid = '$uid' AND id = '$id'";
  59. $q = $db->query($s);
  60. if($r = $q->fetchArray(SQLITE3_ASSOC)){
  61. $unit = $r;
  62. // Runes
  63. $unit["runes"] = [];
  64. $s = "SELECT * FROM rune WHERE assigned_to = '" . $unit["id"] . "' ORDER BY slot;";
  65. $q = $db->query($s);
  66. while ($r = $q->fetchArray(SQLITE3_ASSOC)){
  67. $rune = $r;
  68. unset($rune["uid"]); # Not needed
  69. unset($rune["assigned_to"]); # Not needed
  70. array_push($unit["runes"], $rune);
  71. }
  72. // Skills
  73. $unit["skills"] = [];
  74. $s = "SELECT skill, level FROM unit_skill WHERE unit = '" . $unit["id"] . "';";
  75. $q = $db->query($s);
  76. while ($r = $q->fetchArray(SQLITE3_ASSOC)){
  77. array_push($unit["skills"], $r);
  78. }
  79. header('Content-Type: application/json');
  80. echo json_encode($unit);
  81. http_response_code(200);
  82. return 200;
  83. }
  84. else{
  85. http_response_code(404);
  86. return 404;
  87. }
  88. }
  89. }
  90. catch(Exception $e) {
  91. error_log("Unknown error fetching units: " . $e->getMessage());
  92. http_response_code(500);
  93. return 500;
  94. }
  95. ?>