Improve feedback form to autofill based on referrer
Improve feedback form to autofill based on referrer

--- a/feedback.php
+++ b/feedback.php
@@ -1,11 +1,11 @@
 <?php
-include ('include/common.inc.php');
+include ("include/common.inc.php");
 include_header("Feedback", "feedback");
 function sendEmail($topic, $message)
 {
 	$address = "maxious@lambdacomplex.org";
 	if (file_exists("/tmp/aws.php")) {
-		include_once ('lib/ses.php');
+		include_once ("lib/ses.php");
 		include_once ("/tmp/aws.php");
 		$con = new SimpleEmailService($accessKey, $secretKey);
 		//$con->verifyEmailAddress($address);
@@ -24,16 +24,29 @@
 		mail($address, $topic, $message);
 	}
 }
+
+$stopid = "";
+$stopcode = "";
+$urlparts = explode("?",$_SERVER["HTTP_REFERER"]);
+if (isset($urlparts[1])) {
+    $getparams = explode("&",$urlparts[1]);
+    foreach ($getparams as $param) {
+        $paramparts=explode("=",$param);
+        if ($paramparts[0] == "stopid") $stopid = $paramparts[1];
+        if ($paramparts[0] == "stopcode") $stopcode = $paramparts[1];
+    }
+}
+
 ?>
 <h3>Add/Move/Delete a Bus Stop Location</h3>
-StopID:
-or StopCode:
-<small> if you click on feedback from a stop page, these will get filled in automatically. else describe the location/street of the stop <input type="text" name="stoplocation" /> </small>
+StopID: <input type="text" name="stopid" value="<?php echo $stopid ?>"/><br>
+or StopCode:  <input type="text" name="stopcode" value="<?php echo $stopcode ?>"/><br>
+<small> if you click on feedback from a stop page, these will get filled in automatically. else describe the location/street of the stop in one of these boxes </small><br>
 
-Suggested Stop Location (lat/long or words):
-<small> if your device supports javascript, you can pick a location from the map above</small>
+Suggested Stop Location (lat/long or words):  <input type="text" name="newlocation"/><br>
+<small> if your device supports javascript, you can pick a location from the map above</small><br>
 
-Submit!
+<input type="submit" value="Submit!"/>
 
 <h3>Bug Report/Feedback</h3>
 Please leave feedback about bugs/errors or general suggestions about improvements that could be made to the way the data is presented!
@@ -41,14 +54,15 @@
 </textarea>
 <textarea id="extrainfo">
 <?php
-  echo '  Referrer URL
-    User Agent
-    User host/IP
-    Server host/IP
-    Current date/time
-    Dump of $_SESSION ';
+  echo "Referrer URL: ".$_SERVER["HTTP_REFERER"];
+  echo "\nUser Agent: ".$_SERVER["HTTP_USER_AGENT"];
+  echo "\nUser host/IP: ".$_SERVER["HTTP_X_FORWARDED_FOR"]." ".$_SERVER["REMOTE_ADDR"]; 
+  echo "\nServer host/IP: ".php_uname("n");
+  echo "\nCurrent date/time: ". date("c");
+  echo "\nDump of session: ".print_r($_SESSION,true);
 ?>
 </textarea>
 
-Submit!
+<input type="submit" value="Submit!"/>
 
+

--- a/include/common-template.inc.php
+++ b/include/common-template.inc.php
@@ -36,6 +36,10 @@
 	if ($datepicker) echo '<link rel="stylesheet"  href="css/jquery.ui.datepicker.mobile.css" />';
 	if (isDebugServer()) echo '<link rel="stylesheet"  href="css/jquery-mobile-1.0a3.css" />
          <script type="text/javascript" src="js/jquery-1.5.js"></script>
+	 <script>$(document).bind("mobileinit", function(){
+  $.mobile.ajaxEnabled = false;
+});
+</script>
         <script type="text/javascript" src="js/jquery-mobile-1.0a3.js"></script>';
 	else echo '<link rel="stylesheet"  href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />
         <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
@@ -81,6 +85,10 @@
     .min-width-480px .viaPoints {
         display: block;
     }
+    #extrainfo {
+    visibility: hidden;
+    display: none;
+    }
     // source http://webaim.org/techniques/skipnav/
     #skip a, #skip a:hover, #skip a:visited 
 { 
@@ -111,13 +119,13 @@
 function success(position) {
 $('#geolocate').val(position.coords.latitude+','+position.coords.longitude);
 $.ajax({ url: \"common.inc.php?geolocate=yes&lat=\"+position.coords.latitude+\"&lon=\"+position.coords.longitude });
-$('#here').click(function(event) { $('#geolocate').val(doAJAXrequestForGeolocSessionHere()); return false;});
-$('#here').show();
+location.reload(true);
 }
 function error(msg) {
  console.log(msg);
 }
 
+function geolocate() {
 if (navigator.geolocation) {
 var options = {
       enableHighAccuracy: false,
@@ -126,25 +134,21 @@
 }
   navigator.geolocation.getCurrentPosition(success, error, options);
 }
-
-</script> ";
-	}
-	if (!isDebugServer()) echo '
+}
+$(document).ready(function() {
+        $('#here').click(function(event) { $('#geolocate').val(geolocate()); return false;});
+$('#here').show();
+});
+";
+if (!isset($_SESSION['lat']) || $_SESSION['lat'] == "") echo "geolocate();";
+echo "</script> ";
+	}
+	if (isAnalyticsOn()) echo '
 <script type="text/javascript">'."
 
   var _gaq = _gaq || [];
   _gaq.push(['_setAccount', 'UA-22173039-1']);
   _gaq.push(['_trackPageview']);
-
-  (function() {
-    var ga = document.createElement('script'); ga.type = 
-'text/javascript'; ga.async = true;
-    ga.src = ('https:' == document.location.protocol ? 
-'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
-    var s = document.getElementsByTagName('script')[0]; 
-s.parentNode.insertBefore(ga, s);
-  })();
-
 </script>";
 echo '</head>
 <body>
@@ -169,17 +173,19 @@
 }
 function include_footer()
 {
-	if ($geolocate && isset($_SESSION['lat'])) {
-		echo "<script>
-        $('#here').click(function(event) { $('#geolocate').val(doAJAXrequestForGeolocSessionHere()); return false;});
-$('#here').show();
-</script>";
-	}
 	echo '<div id="footer"><a href="about.php">About/Contact Us</a>&nbsp;<a href="feedback.php">Feedback/Bug Report</a></a>';
 	echo '</div>';
-        if (!isDebugServer()) {
+        if (isAnalyticsOn()) {
+	echo "<script>  (function() {
+    var ga = document.createElement('script'); ga.type = 
+'text/javascript'; ga.async = true;
+    ga.src = ('https:' == document.location.protocol ? 
+'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+    var s = document.getElementsByTagName('script')[0]; 
+s.parentNode.insertBefore(ga, s);
+  })();";
          $googleAnalyticsImageUrl = googleAnalyticsGetImageUrl();
-  echo '<img src="' . $googleAnalyticsImageUrl . '" />';
+  echo '<noscript><img src="' . $googleAnalyticsImageUrl . '" /></noscript>';
     }
 }
 function timePlaceSettings($geolocate = false)
@@ -196,7 +202,7 @@
 	}
 	echo '<div data-role="collapsible" data-collapsed="' . !$geoerror . '">
         <h3>Change Time/Place (' . (isset($_SESSION['time']) ? $_SESSION['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3>
-        <form action="'.basename($_SERVER['PHP_SELF']).'" method="post">
+        <form action="'.basename($_SERVER['PHP_SELF'])."?".$_SERVER['QUERY_STRING'].'" method="post">
         <div class="ui-body"> 
 		<div data-role="fieldcontain">
 	            <label for="geolocate"> Current Location: </label>
@@ -204,7 +210,8 @@
 	        </div>
     		<div data-role="fieldcontain">
 		        <label for="time"> Time: </label>
-		    	<input type="time" name="time" id="time" value="' . (isset($_SESSION['time']) ? $_SESSION['time'] : date("H:i")) . '"/> <a href="#" name="currentTime" id="currentTime">Current Time?</a>
+		    	<input type="time" name="time" id="time" value="' . (isset($_SESSION['time']) ? $_SESSION['time'] : date("H:i")) . '"/>
+			<a href="#" name="currentTime" id="currentTime" onClick="var d = new Date();'. "$('#time').val(d.getHours() +':'+ d.getMinutes());".'">Current Time?</a>
 	        </div>
 		<div data-role="fieldcontain">
 		    <label for="service_period"> Service Period:  </label>
@@ -220,5 +227,10 @@
                 </form>
             </div></div>';
 }
+function trackEvent($category, $action, $label = "", $value = -1) {
+  if (isAnalyticsOn()) {
+    echo "<script> _gaq.push(['_trackEvent', $category, $action".($label != "" ? ", $label" : "").($value != -1 ? ", $value" : "")."]);";
+  }
+}
 ?>
 

--- a/include/common.inc.php
+++ b/include/common.inc.php
@@ -59,11 +59,18 @@
 			}
 		}
 	}
+	if ($_SESSION['lat'] != "" && isAnalyticsOn()) {
+		trackEvent("Geolocation","Updated Location", "Geocoded - ".($geocoded ? "Yes" : "No"));
+	}
 }
 debug(print_r($_SESSION, true) , "session");
 function isDebugServer()
 {
 	return $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1" || !$_SERVER['SERVER_NAME'];
+}
+function isAnalyticsOn()
+{
+	return !isDebugServer();
 }
 function isDebug($debugReason = "other")
 {

file:a/index.php -> file:b/index.php
--- a/index.php
+++ b/index.php
@@ -12,7 +12,7 @@
             <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
                 <li data-role="list-divider">Timetables - Stops</li>
                 <li><a href="stopList.php">Major (Timing Point) Stops</a></li>
-		<li><a href="stopList.php">All Stops</a></li>
+		<li><a href="stopList.php?allstops=yes">All Stops</a></li>
 		<li><a href="stopList.php?suburbs=yes">Stops By Suburb</a></li>
 		<li><a class="nearby" href="stopList.php?nearby=yes">Nearby Stops</a></li>
             </ul>

--- a/routeList.php
+++ b/routeList.php
@@ -36,10 +36,16 @@
 		$suburb = filter_var($_REQUEST['suburb'], FILTER_SANITIZE_STRING);
 		$url = $APIurl . "/json/stopzonesearch?q=" . $suburb;
 		include_header("Routes by Suburb", "routeList");
+		timePlaceSettings(true);
+		trackEvent("Route Lists","Routes By Suburb", $suburb);
+		if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") {
+			include_footer();
+			die();
+		}
 	}
 	if ($_REQUEST['nearby']) {
 		$url = $APIurl . "/json/neareststops?lat={$_SESSION['lat']}&lon={$_SESSION['lon']}&limit=15";
-		include_header("Routes Nearby", "routeList");
+		include_header("Routes Nearby", "routeList", true, true);
 	}
 	$stops = json_decode(getPage($url));
 	$routes = Array();

file:a/stop.php -> file:b/stop.php
--- a/stop.php
+++ b/stop.php
@@ -51,9 +51,12 @@
 echo '<div data-role="content" class="ui-content" role="main">        <a name="maincontent" id="maincontent"></a>';
 echo $stopLinks;
 if (sizeof($stops) > 0) {
+    trackEvent("View Stops","View Combined Stops", $stop[1], $stop[0]);
+
 	echo '<p>' . staticmap($stopPositions) . '</p>';
 }
 else {
+        trackEvent("View Stops","View Single Stop", $stop[1], $stop[0]);
 	echo '<p>' . staticmap(Array(
 		0 => Array(
 			$stop[2],

--- a/stopList.php
+++ b/stopList.php
@@ -48,7 +48,7 @@
 	else if ($_REQUEST['nearby']) {
 		$listType = 'nearby=yes';
 		$url = $APIurl . "/json/neareststops?lat={$_SESSION['lat']}&lon={$_SESSION['lon']}&limit=15";
-		include_header("Nearby Stops", "stopList");
+		include_header("Nearby Stops", "stopList", true, true);
 		navbar();
 		timePlaceSettings(true);
 		if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") {
@@ -62,6 +62,7 @@
 		$url = $APIurl . "/json/stopzonesearch?q=" . $suburb;
 		include_header("Stops in " . ucwords($suburb) , "stopList");
 		navbar();
+	       trackEvent("Stop Lists","Stops By Suburb", $suburb);
 	}
 	else {
 		$url = $APIurl . "/json/timingpoints";

file:a/trip.php -> file:b/trip.php
--- a/trip.php
+++ b/trip.php
@@ -24,6 +24,7 @@
 	$routetrips = json_decode(getPage($url));
 }
 include_header("Stops on " . $trips[1]->route_short_name . ' ' . $trips[1]->route_long_name, "trip");
+trackEvent("Route/Trip View","View Route", $trips[1]->route_short_name . ' ' . $trips[1]->route_long_name, $trips[1]->route_id);
 $url = $APIurl . "/json/tripstoptimes?trip=" . $tripid;
 $json = json_decode(getPage($url));
 $stops = $json[0];

--- a/tripPlanner.php
+++ b/tripPlanner.php
@@ -11,6 +11,7 @@
 }
 function tripPlanForm($errorMessage = "")
 {
+
 	global $date, $time, $from, $to;
 	echo "<font color=red>$errorMessage</font>";
 	echo '<form action="tripPlanner.php" method="post">
@@ -111,8 +112,14 @@
 	$fromPlace = (startsWith($from, "-") ? $from : geocode($from, false));
 	if ($toPlace == "" || $fromPlace == "") {
 		$errorMessage = "";
-		if ($toPlace === "") $errorMessage.= urlencode($to) . " not found.<br>\n";
-		if ($fromPlace === "") $errorMessage.= urlencode($from) . " not found.<br>\n";
+		if ($toPlace === "") {
+                  $errorMessage.= urlencode($to) . " not found.<br>\n";
+                  trackEvent("Trip Planner","Geocoder Failed", $to);
+                }
+		if ($fromPlace === "") {
+                  $errorMessage.= urlencode($from) . " not found.<br>\n";
+                  trackEvent("Trip Planner","Geocoder Failed", $from);
+                }
 		tripPlanForm($errorMessage);
 	}
 	else {
@@ -127,9 +134,11 @@
 		$page = curl_exec($ch);
 		if (curl_errno($ch)) {
 			tripPlanForm("Trip planner temporarily unavailable: " . curl_errno($ch) . " " . curl_error($ch) .(isDebug() ? $url : ""));
-		
+                        trackEvent("Trip Planner","Trip Planner Failed", $url);
                 }
 		else {
+                  	trackEvent("Trip Planner","Plan Trip From", $from);
+                        trackEvent("Trip Planner","Plan Trip To", $to);
 			$tripplan = json_decode($page);
 			debug(print_r($triplan, true));
 			echo "<h1> From: {$tripplan->plan->from->name} To: {$tripplan->plan->to->name} </h1>";