upload_run_scenario.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Scenario run logger script.
  4. *
  5. * Exposes an API to save a run to the database.
  6. * Reads post data and calls the upload_scenario_run.py script.
  7. * Mandatory POST parameters are:
  8. * - data: Received JSON file after a run.
  9. * - key: User API key.
  10. *
  11. * @category API
  12. */
  13. global $db;
  14. try{
  15. // Check data
  16. $data = filter_input(INPUT_POST, 'data');
  17. if ($data == null || $data == false){
  18. http_response_code(400);
  19. return 400;
  20. }
  21. // Check API key.
  22. $key = filter_input(INPUT_POST, 'key');
  23. if ($key == null || $key == false){
  24. http_response_code(401);
  25. return 401;
  26. }
  27. // Check data format.
  28. $json = json_decode($data);
  29. if ($json === null){
  30. http_response_code(400);
  31. return 400;
  32. }
  33. // Authenticate
  34. $uid = $json->{"wizard_id"};
  35. $s = "SELECT COUNT(uid) AS c FROM player WHERE uid = $uid AND api_key = '$key';";
  36. if (1 != $db->query($s)->fetchArray(SQLITE3_ASSOC)["c"]){
  37. http_response_code(401);
  38. return 401;
  39. }
  40. // Run scenario run parser script
  41. $cmd = __DIR__ . "/bin/upload_run_scenario.py " . $key . " " . escapeshellarg($data);;
  42. $out = [];
  43. $ret = 0;
  44. try{
  45. exec($cmd, $out, $ret);
  46. }
  47. catch(Exception $e) {
  48. error_log("Error running scenario run script '$cmd': " . $e->getMessage());
  49. http_response_code(500);
  50. return 500;
  51. }
  52. if ($ret != 200){
  53. try{
  54. http_response_code($ret);
  55. return $ret;
  56. }
  57. catch(Exception $e) {
  58. error_log("Dungeon run script '$cmd' returned an unexpected value $ret: " . $e->getMessage());
  59. http_response_code(500);
  60. return 500;
  61. }
  62. }
  63. // At this point, status code should be 200
  64. http_response_code($ret);
  65. return $ret;
  66. }
  67. catch(Exception $e) {
  68. error_log("Unknown error parsing scenario run: " . $e->getMessage());
  69. http_response_code(500);
  70. return 500;
  71. }
  72. ?>