location.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. // Gasteizko Margolariak API v1 //
  3. //List of available data formatting
  4. define('FOR_JSON', 'json');
  5. //Default info format
  6. define('DEF_FORMAT', FOR_JSON);
  7. //Errors
  8. define('ERR_FORMAT', '-FORMAT:');
  9. /****************************************************
  10. * This function is called from almost everywhere at *
  11. * the beggining of the page. It initializes the *
  12. * session variables, connect to the db, enabling *
  13. * the variable $con for futher use everywhere in *
  14. * the php code, and populates the arrays $user *
  15. * and $permission, with info about the user. *
  16. * *
  17. * @return: (db connection): The connection handler. *
  18. ****************************************************/
  19. function startdb(){
  20. //Include the db configuration file. It's somehow like this
  21. /*
  22. <?php
  23. $host = 'XXXX';
  24. $db_name = 'XXXX';
  25. $username_ro = 'XXXX';
  26. $username_rw = 'XXXX';
  27. $pass_ro = 'XXXX';
  28. $pass_rw = 'XXXX';
  29. ?>
  30. */
  31. include('../../.htpasswd');
  32. //Connect to to database
  33. $con = mysqli_connect($host, $username_rw, $pass_rw, $db_name);
  34. //Set encoding options
  35. mysqli_set_charset($con, 'utf-8');
  36. header('Content-Type: text/html; charset=utf8');
  37. mysqli_query($con, 'SET NAMES utf8;');
  38. //Return the db connection
  39. return $con;
  40. }
  41. //Connect to the database
  42. $con = startdb('rw');
  43. //Get data from the url
  44. $format = strtolower(mysqli_real_escape_string($con, $_GET[GET_FORMAT]));
  45. //Validate input
  46. if (strlen($format) < 1){
  47. $format = DEF_FORMAT;
  48. }
  49. if ($format != FOR_JSON){
  50. //Bad request
  51. http_response_code(400);
  52. $error = $error . ERR_FORMAT . mysqli_real_escape_string($con, $_GET[GET_FORMAT]);
  53. error_log($error);
  54. exit(-1);
  55. }
  56. //Get location
  57. $q = mysqli_query($con, "SELECT lat, lon, dtime FROM location WHERE action <> 'F' AND lat IS NOT null AND lon IS NOT null AND dtime > NOW() - INTERVAL 30 MINUTE ORDER BY dtime DESC LIMIT 1;");
  58. if (mysqli_num_rows($q) > 0){
  59. $r = mysqli_fetch_array($q);
  60. switch ($format){
  61. case FOR_JSON:
  62. echo("[{\"lat\":\"$r[lat]\",\"lon\":\"$r[lon]\",\"dtime\":\"$r[dtime]\"}]");
  63. break;
  64. default:
  65. http_response_code(400);
  66. $error = $error . ERR_FORMAT . mysqli_real_escape_string($con, $_GET[GET_FORMAT]);
  67. error_log($error);
  68. exit(-2);
  69. }
  70. }
  71. else{
  72. //No content
  73. http_response_code(204);
  74. exit(0);
  75. }
  76. ?>