GET.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Profile getter script.
  4. *
  5. * Exposes an API to rerieve a user profile.
  6. *
  7. * A lst of profiles can't be retrieved.
  8. *
  9. * Mandatory query parameters are:
  10. * - id: Player ID.
  11. *
  12. * Optional GET parameters are.
  13. * - key: User API key to retrieve a private profile.
  14. *
  15. * @author Iñigo Valentin <i@inigovalentin.com>
  16. * @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License V3
  17. * @package SWDB
  18. * @category API
  19. */
  20. try{
  21. header("Content-type: application/json; charset=utf-8");
  22. // Get profile ID
  23. /** @var mixed $query Request parameters, from API_CONTROLLER*/
  24. if (count($query) > 1){
  25. $id = $query[0];
  26. }
  27. else{
  28. // Id is mandatory, a list can be retrieved
  29. header("HTTP/1.1 403 A list of profiles cant be retrieved. Please specify a profile ID or player name.");
  30. syslog(LOG_INFO, "[APIv1] HTTP/1.1 403 A list of profiles cant be retrieved. Please specify a profile ID or player name.");
  31. return 403;
  32. }
  33. $db = get_context()->get_db();
  34. // Get player
  35. $statement = $db->prepare("
  36. SELECT
  37. user.api_key AS api_key,
  38. player.id AS id,
  39. player.public AS public
  40. FROM
  41. user,
  42. player
  43. WHERE
  44. user.id = player.user AND
  45. player.id = :id AND
  46. user.api_key = :api_key;
  47. ");
  48. $statement->bindValue(":id", $id, SQLITE3_INTEGER);
  49. $r = $statement->execute()->fetchArray(SQLITE3_ASSOC);
  50. if ($r == null){
  51. // No player found
  52. header("HTTP/1.1 404 Player not found.");
  53. syslog(LOG_INFO, "[APIv1] HTTP/1.1 404 Player not found.");
  54. return 403;
  55. }
  56. if ($r["public"] != 1 && $r["key"] != filter_input(INPUT_GET, "key")){
  57. header("HTTP/1.1 403 The profile is not public.");
  58. syslog(LOG_INFO, "[APIv1] HTTP/1.1 403 The profile is not public.");
  59. return 403;
  60. }
  61. // Permission granted, get player data.
  62. $player_id = $r["player_id"];
  63. $player = new Player($player_id);
  64. // Build array
  65. // TODO: Add way more data
  66. $player = [
  67. "username" => $player->get_name(),
  68. "level" => $player->get_level(),
  69. "public" => $player->is_public()
  70. ];
  71. echo(json_encode($player));
  72. header("HTTP/1.1 200 Success.");
  73. syslog(LOG_INFO, "[APIv1] HTTP/1.1 200 Success.");
  74. return 200;
  75. }
  76. catch(Exception $e) {
  77. header("HTTP/1.1 500 Unexpeced error: " . $e->getMessage());
  78. syslog(LOG_ERR, "[APIv1] HTTP/1.1 500 Unexpected error: " . $e->getMessage());
  79. return 500;
  80. }