upload_profile.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. exec($cmd, $out, $ret);
  59. }
  60. catch(Exception $e) {
  61. error_log("Error running profile script '$cmd': " . $e->getMessage());
  62. http_response_code(500);
  63. return 500;
  64. }
  65. if ($ret != 204){
  66. try{
  67. http_response_code($ret);
  68. return $ret;
  69. }
  70. catch(Exception $e) {
  71. error_log("Profile script '$cmd' returned an unexpected value $ret: " . $e->getMessage());
  72. http_response_code(500);
  73. return 500;
  74. }
  75. }
  76. // At this point, status code should be 200
  77. http_response_code($ret);
  78. return $ret;
  79. }
  80. catch(Exception $e) {
  81. error_log("Unknown error parsing profile: " . $e->getMessage());
  82. http_response_code(500);
  83. return 500;
  84. }
  85. ?>