location.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }
  54. //Get location
  55. $q = mysqli_query($con, "SELECT lat, lon, dtime FROM location WHERE action = 'report' AND dtime > NOW() - INTERVAL 30 MINUTE ORDER BY dtime DESC LIMIT 1;");
  56. if (mysqli_num_rows($q) > 0){
  57. $r = mysqli_fetch_array($q);
  58. switch ($format){
  59. case FOR_JSON:
  60. echo("[{\"lat\":\"$r[lat]\",\"lon\":\"$r[lon]\",\"dtime\":\"$r[dtime]\"}]");
  61. break;
  62. default:
  63. http_response_code(400);
  64. $error = $error . ERR_FORMAT . mysqli_real_escape_string($con, $_GET[GET_FORMAT]);
  65. }
  66. }
  67. else{
  68. //No content
  69. http_response_code(204);
  70. }
  71. ?>