location-ws.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /* GNU FM -- a free network service for sharing your music listening habits
  3. Copyright (C) 2009 Free Software Foundation, Inc
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU Affero General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Affero General Public License for more details.
  12. You should have received a copy of the GNU Affero General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. # This file should probably be moved out of the web root. /js/edit_profile.js will
  16. # need updating if you do.
  17. // The place being searched for.
  18. $query = $_GET['q'];
  19. if (!$query) {
  20. header('Content-Type: text/plain');
  21. die("Must supply a query argument.\r\n");
  22. }
  23. // The number of results requested
  24. $num = $_GET['n'];
  25. if (!$num) {
  26. $num = 10;
  27. }
  28. // When translated versions become available, should be able to calculate
  29. // the language code from the subdomain.
  30. $lang = 'en';
  31. $uri = sprintf('http://ws.geonames.org/searchJSON?q=%s&maxRows=%d&lang=%s&style=full',
  32. rawurlencode($query),
  33. $num,
  34. rawurlencode($lang));
  35. if (function_exists('curl_init')) {
  36. # We'll try to use cURL if the extension is installed on this server.
  37. header('Content-Type: application/json');
  38. $ch = curl_init($uri);
  39. curl_setopt($ch, CURLOPT_HEADER, 0);
  40. curl_setopt($ch, CURLOPT_USERAGENT, 'libre.fm');
  41. curl_exec($ch);
  42. curl_close($ch);
  43. } else if (function_exists('parse_url')) {
  44. # Otherwise, we'll fall back to direct socket calls. Ugly.
  45. $_uri = parse_url($uri);
  46. if (!$_uri['port']) {
  47. $_uri['port'] = 80;
  48. }
  49. if (!($nh = fsockopen($_uri['host'], $_uri['port'], $errno, $errstr, 20))) {
  50. header('Content-Type: text/plain');
  51. die("Could not open network connection! ($errno - $errstr)\r\n");
  52. }
  53. fwrite($nh, "GET {$_uri[path]}?{$_uri[query]} HTTP/1.0\r\n"
  54. . "Host: {$_uri['host']}\r\n"
  55. . "User-Agent: libre.fm\r\n"
  56. . "Connection: close\r\n\r\n"
  57. );
  58. header('Content-Type: application/json');
  59. while (!feof($nh)) {
  60. $output .= fgets($nh, 128);
  61. }
  62. fclose($nh);
  63. // Remove HTTP header.
  64. echo substr(strstr($output, "\r\n\r\n"), 4);
  65. }