upload_profile.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Profile uploader script.
  4. *
  5. * Exposes an API to save a run to the database.
  6. * Reads post data and calls the upload_profile.py script.
  7. * It also saves the data to a JSON file in the data directory.
  8. * Mandatory POST parameters are:
  9. * - data: Received JSON file.
  10. * - key: User API key.
  11. *
  12. * @category API
  13. */
  14. global $db;
  15. try{
  16. // Check data
  17. $data = filter_input(INPUT_POST, 'response');
  18. if ($data == null || $data == false){
  19. http_response_code(400);
  20. return 400;
  21. }
  22. // Check API key.
  23. $key = filter_input(INPUT_POST, 'key');
  24. if ($key == null || $key == false){
  25. http_response_code(401);
  26. return 401;
  27. }
  28. // Check data format.
  29. $json = json_decode($data);
  30. if ($json === null){
  31. http_response_code(400);
  32. return 400;
  33. }
  34. // Authenticate
  35. $uid = $json->{"wizard_id"};
  36. $uname = $json->{"wizard_info"}->{"wizard_name"};
  37. $s = "SELECT COUNT(uid) AS c FROM player WHERE uid = $uid AND api_key = '$key';";
  38. if (1 != $db->query($s)->fetchArray(SQLITE3_ASSOC)["c"]){
  39. http_response_code(401);
  40. return 401;
  41. }
  42. // Write data file
  43. $dtime = (new DateTime())->format('Y-m-dTH:i:s');
  44. $fname = ($_SERVER["DOCUMENT_ROOT"] . "/../data/profile_" . $uid . "_" . $uname . "_" . $dtime . ".json");
  45. try{
  46. file_put_contents($fname, $data);
  47. }
  48. catch(Exception $e) {
  49. error_log("Unable to write profile data to '$fname': " . $e->getMessage());
  50. http_response_code(500);
  51. return 500;
  52. }
  53. // Run profile parser script
  54. $cmd = __DIR__ . "/bin/upload_profile.py " . $key . " " . $fname;
  55. $out = [];
  56. $ret = 0;
  57. try{
  58. error_log ($cmd);
  59. exec($cmd, $out, $ret);
  60. }
  61. catch(Exception $e) {
  62. error_log("Error running profile script '$cmd': " . $e->getMessage());
  63. http_response_code(500);
  64. return 500;
  65. }
  66. if ($ret != 204){
  67. try{
  68. http_response_code($ret);
  69. return $ret;
  70. }
  71. catch(Exception $e) {
  72. error_log("Profile script '$cmd' returned an unexpected value $ret: " . $e->getMessage());
  73. http_response_code(500);
  74. return 500;
  75. }
  76. }
  77. // At this point, status code should be 200
  78. http_response_code($ret);
  79. return $ret;
  80. }
  81. catch(Exception $e) {
  82. error_log("Unknown error parsing profile: " . $e->getMessage());
  83. http_response_code(500);
  84. return 500;
  85. }
  86. ?>