replace ajax downloadurl disallowed on IE (not same domain?) by PHP
[maps-routes-comparison] / index.php
similarity index 71%
rename from index.html
rename to index.php
index 5b16e28efc3d31b84c0707398e101682428da5a9..ca56a5acafe1984f70dd7c4a236a747b3ab0ad24 100644 (file)
+++ b/index.php
@@ -1,3 +1,122 @@
+<?php
+
+ini_set("track_errors", 1);
+ini_set('display_errors', 0);
+
+// Helper function for fatal errors
+function fatal($msg) {
+    echo "<h2>Error</h2>\n";
+    echo "$msg\n";
+    echo "</body></html>";
+    exit;
+
+}
+
+$host = 'api.hostip.info';
+$port = 80;
+$path = '/get_html.php?position=true&ip=' . $_SERVER['REMOTE_ADDR'];
+
+$fp = @fsockopen($host, $port, $errno, $errstr);
+if (!$fp)
+    fatal("<p>Unable to open connection to <tt>$host</tt> ".
+          "(port <tt>$port</tt>):</p><pre>$errstr</pre>");
+
+fwrite($fp, "GET $path HTTP/1.0\r\n");
+fwrite($fp, "Host: $host:$port\r\n");
+fwrite($fp, "\r\n");
+
+$buf = '';
+$length = '';
+while (!feof($fp)) {
+    $buf .= fread($fp, 8192);
+    // Parse the HTTP answer and try to extract response code,
+    // headers and body
+    $answer = parse_answer($buf);
+
+    // We need to discover Content-Length, to know when server
+    // finishes sending data
+    if (!$length) {
+        if ($answer[0] == 200)
+            $length = $answer[1]['content-length'];
+    }
+    
+    // When length is available, we can check if response has
+    // been fully transmitted; this is the case when all what
+    // we received equals the headers plus the full contents.
+    if ($length) {
+        if (strlen_b($buf) == strlen_b($answer[3]) + $length)
+            break;
+    }
+}
+
+fclose($fp);
+$body = $answer[2];
+
+$latitude = $longitude = $zoom = 0;
+if (preg_match('/Latitude: (\S+)/', $body, $matches)) {
+    $latitude = $matches[1];
+    $zoom = 8;
+}
+if (preg_match('/Longitude: (\S+)/', $body, $matches)) {
+    $longitude = $matches[1];
+}
+if (($latitude == 0 || $longitude == 0) && preg_match('/Country: .*?\((\S{2})\)/', $body, $matches)) {
+    $country = $matches[1];
+    include('countries.phpi');
+    $latitude = $countries[$country][0];
+    $longitude = $countries[$country][1];
+    $zoom = 5;
+}
+
+// PHP's strlen should return the length of a string in bytes,
+// except when using multibyte strings, in which case
+// mb_orig_strlen must be used (in case strlen was overloaded
+// with mb_strlen).
+function strlen_b($str) {
+    if (function_exists('mb_orig_strlen')) {
+        return mb_orig_strlen($str);
+    } else {
+        return strlen($str);
+    }
+}
+
+// Parse an HTTP answer to extract response code, headers and body
+// Returns an array containing: response code, headers, body, raw headers
+function parse_answer($answer) {
+
+    // This first pattern matching allows to separate first line
+    // (server response status), headers, and data contents 
+    if (ereg("^(([^\n]+)\r\n(.*)\r\n\r\n)(.*)", $answer, $regs)) {
+        $full_headers   = $regs[1];
+        $response       = $regs[2];
+        $headers_string = $regs[3];
+        $body           = $regs[4];
+        // Parse first line (server response status)
+        if (ereg("^HTTP/[0-9\.]+ ([0-9]+)", $response, $regs)) {
+            $response_code = $regs[1];
+        } else {
+            fatal("<p>Unable to parse response line <tt>$response</tt> ".
+                  "from the server.</p>");
+        }
+        // Parse headers and build a hash with them
+        foreach (split("\r\n", $headers_string) as $line) {
+            if (ereg("^([^:]+): (.*)", $line, $regs)) {
+                $headers[strtolower($regs[1])] = $regs[2];
+            } else {
+                fatal("<p>Unable to parse header line <tt>$line</tt> ".
+                      "from the server. ".
+                      "All headers:</p><pre>$headers_string</pre>");
+            }
+        }
+    } else {
+        // Return -1 as response code if parsing was not possible
+        return array(-1);
+    }
+    return array($response_code, $headers, $body, $full_headers);
+}
+
+?>
+
 <html>
 <head>
     <title>Routes Compare</title>
       function initialize() {
           map = new google.maps.Map(document.getElementById("mapbox"),
                                     { mapTypeId: google.maps.MapTypeId.ROADMAP,
-                                      zoom: 8 });
+                                      zoom: 2 });
 
           mylat = 0;
           mylng = 0;
               }
               startUp();
           } else {
-              document.getElementById('submitshortresult').innerHTML = '<em>Please wait, geolocating you...</em>';
-              downloadUrl("http://api.hostip.info/get_html.php?position=true",
-                          function(data) {
-                              var baseinfomessage = 'This is where I located you,<br/>based on your IP address.<br/>';
-                              if (data.match(/Latitude: (\S+)/)) {
-                                  mylat = RegExp.$1;
-                                  if (data.match(/Longitude: (\S+)/)) {
-                                      mylng = RegExp.$1;
-                                  }
-                              } else if (data.match(/Country: .*?\((\S{2})\)/)) {
-                                  var country = RegExp.$1;
-                                  if (country == 'XX') {
-                                      map.setZoom(2);
-                                      baseinfomessage = 'It was not possible to locate<br/>you, based on your IP address<br/>'
-                                                        + '<a href="http://www.hostip.info/">(submit your location!)</a>.<br/>';
-                                  } else {
-                                      map.setZoom(5);
-                                      mylat = eval("lats." + country);
-                                      mylng = eval("lngs." + country);
-                                  }
-                              }
-                              me = startUp();
-                              document.getElementById('submitshortresult').innerHTML = '';
-                              document.getElementById('submitshortresult').style.color = 'red';
-                              info_window = new google.maps.InfoWindow({ content: baseinfomessage
-                                                                                  + 'You can drag this icon<br/>to move your position.<br/>'
-                                                                                  + '<div class="fakelink" style="float: right" onclick="javascript:info_window.close()">Okay</div>' });
-                              info_window.open(map, me);
-                          });
+              <?php
+                  if ($latitude) {
+               ?>
+              mylat = <?php echo $latitude ?>;
+              mylng = <?php echo $longitude ?>;
+              var baseinfomessage = 'This is where I located you,<br/>based on your IP address.<br/>';
+              <?php
+                  } else {
+               ?>
+              var baseinfomessage = 'It was not possible to locate<br/>you, based on your IP address<br/>'
+                                  + '<a href="http://www.hostip.info/">(submit your location!)</a>.<br/>';
+              <?php
+                  }
+               ?>
+              map.setZoom(<?php echo $zoom ?>);
+              me = startUp();
+              info_window = new google.maps.InfoWindow({ content: baseinfomessage
+                                                                  + 'You can drag this icon<br/>to move your position.<br/>'
+                                                                  + '<div class="fakelink" style="float: right" onclick="javascript:info_window.close()">Okay</div>' });
+              info_window.open(map, me);
               if (!document.cookie || document.cookie.indexOf("not-a-newbie") == -1) {
                   document.getElementById("newbie").style.display = '';
               }
       </div>
 
       <form action="javascript:submit()">
-      Type in an address:
+      Address:
       
       <input type="text" size="32" id="address"/>
       <script type="text/javascript">
         document.getElementById('address').focus();
       </script>
       <input type="submit" value="Show route!"/>
-      <span id="submitshortresult">
+      <span id="submitshortresult" style="color: red">
       </span>
       </form>