AWS fixes
[busui.git] / common.inc.php
blob:a/common.inc.php -> blob:b/common.inc.php
--- a/common.inc.php
+++ b/common.inc.php
@@ -4,42 +4,75 @@
 $cloudmadeAPIkey="daa03470bb8740298d4b10e3f03d63e6";
 $googleMapsAPIkey="ABQIAAAA95XYXN0cki3Yj_Sb71CFvBTPaLd08ONybQDjcH_VdYtHHLgZvRTw2INzI_m17_IoOUqH3RNNmlTk1Q";
 $otpAPIurl = 'http://localhost:8080/opentripplanner-api-webapp/';
-if (isDebug()) error_reporting(E_ALL ^ E_NOTICE);
+$owaSiteID = 'fe5b819fa8c424a99ff0764d955d23f3';
+//$debugOkay = Array("session","json","phperror","other");
+$debugOkay = Array("session","json","phperror");
+if (isDebug("phperror")) error_reporting(E_ALL ^ E_NOTICE);
 
 // SELECT array_to_string(array(SELECT REPLACE(name_2006, ',', '\,') as name FROM suburbs order by name), ',')
 $suburbs = explode(",","Acton,Ainslie,Amaroo,Aranda,Banks,Barton,Belconnen,Bonner,Bonython,Braddon,Bruce,Calwell,Campbell,Chapman,Charnwood,Chifley,Chisholm,City,Conder,Cook,Curtin,Deakin,Dickson,Downer,Duffy,Dunlop,Evatt,Fadden,Farrer,Fisher,Florey,Flynn,Forrest,Franklin,Fraser,Fyshwick,Garran,Gilmore,Giralang,Gordon,Gowrie,Greenway,Griffith,Gungahlin,Hackett,Hall,Harrison,Hawker,Higgins,Holder,Holt,Hughes,Hume,Isaacs,Isabella Plains,Kaleen,Kambah,Kingston,Latham,Lawson,Lyneham,Lyons,Macarthur,Macgregor,Macquarie,Mawson,McKellar,Melba,Mitchell,Monash,Narrabundah,Ngunnawal,Nicholls,Oaks Estate,O'Connor,O'Malley,Oxley,Page,Palmerston,Parkes,Pearce,Phillip,Pialligo,Red Hill,Reid,Richardson,Rivett,Russell,Scullin,Spence,Stirling,Symonston,Tharwa,Theodore,Torrens,Turner,Wanniassa,Waramanga,Watson,Weetangera,Weston,Yarralumla");
 
  // you have to open the session to be able to modify or remove it 
 session_start();
- if (isset($_REQUEST['service_period'])) $_SESSION['service_period'] = filter_var($_REQUEST['service_period'],FILTER_SANITIZE_STRING);
- if (isset($_REQUEST['time'])) $_SESSION['time'] = filter_var($_REQUEST['time'],FILTER_SANITIZE_STRING);
+ if (isset($_REQUEST['service_period'])) {
+   $_SESSION['service_period'] = filter_var($_REQUEST['service_period'],FILTER_SANITIZE_STRING);
+ }
+ if (isset($_REQUEST['time'])) {
+   $_SESSION['time'] = filter_var($_REQUEST['time'],FILTER_SANITIZE_STRING);
+ }
  if (isset($_REQUEST['geolocate'])) {
-    $contents = geocode(var_filter($_REQUEST['geolocate'],FILTER_SANITIZE_URL),true);
+   $geocoded = false;
+   if (isset($_REQUEST['lat']) && isset($_REQUEST['lon'])) {
+      $_SESSION['lat'] = filter_var($_REQUEST['lat'],FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
+        $_SESSION['lon'] = filter_var($_REQUEST['lon'],FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
+   } else {
+    $contents = geocode(filter_var($_REQUEST['geolocate'],FILTER_SANITIZE_URL),true);
     if (isset($contents[0]->centroid)) {
-        $session['lat'] = $contents[0]->centroid->coordinates[0];
-        $session['lon'] = $contents[0]->centroid->coordinates[1];
-    }
-    else {
-        $session['lat'] = "";
-        $session['lon'] = "";
+      $geocoded = true;
+        $_SESSION['lat'] = $contents[0]->centroid->coordinates[0];
+        $_SESSION['lon'] = $contents[0]->centroid->coordinates[1];
+      }
+      else {
+        $_SESSION['lat'] = "";
+        $_SESSION['lon'] = "";
+    }
+   }
+   if ($_SESSION['lat'] != "" && isMetricsOn()) {
+// Create a new Instance of the tracker
+$owa = new owa_php($config);
+// Set the ID of the site being tracked
+$owa->setSiteId($owaSiteID);
+// Create a new event object
+$event = $owa->makeEvent();
+// Set the Event Type, in this case a "video_play"
+$event->setEventType('geolocate');
+// Set a property
+$event->set('lat',$_SESSION['lat']);
+$event->set('lon',$_SESSION['lon']);
+$event->set('geocoded',$geocoded);
+// Track the event
+$owa->trackEvent($event);
     }
  }
-//print_r ($_SESSION);
-function isDebug()
-{
-    return $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1" || !$_SERVER['SERVER_NAME'];
+debug(print_r($_SESSION,true));
+function isDebug($debugReason = "other")
+{
+    global $debugOkay;
+    return in_array($debugReason,$debugOkay,false) && $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1" || !$_SERVER['SERVER_NAME'];
 }
 
 function isMetricsOn()
 {
-    return true;
-}
-
-function debug($msg) {
-    if (isDebug()) echo "<!-- $msg -->";
+    return !isDebug();
+}
+
+function debug($msg, $debugReason = "other") {
+    if (isDebug($debugReason)) echo "\n<!-- ".date(DATE_RFC822)."\n $msg -->\n";
 }
 function isFastDevice() {
+   $ua = $_SERVER['HTTP_USER_AGENT']; 
     $fastDevices = Array("Mozilla/5.0 (X11;", "Mozilla/5.0 (Windows;", "Mozilla/5.0 (iP", "Mozilla/5.0 (Linux; U; Android", "Mozilla/4.0 (compatible; MSIE");
+   
     $slowDevices = Array("J2ME","MIDP","Opera/","Mozilla/2.0 (compatible;","Mozilla/3.0 (compatible;");
     return true;
 }
@@ -96,7 +129,7 @@
 
 function success(position) {
 $('#geolocate').val(position.coords.latitude+','+position.coords.longitude);
-// setCookie('geolocate',position.coords.latitude+','+position.coords.longitude,1);
+$.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();
 }
@@ -117,7 +150,8 @@
     require_once('owa/owa_env.php');
     require_once(OWA_DIR.'owa_php.php');
     $owa = new owa_php();
-    $owa->setSiteId('bus.lambdacomplex.org');
+    global $owaSiteID;
+    $owa->setSiteId($owaSiteID);
     $owa->setPageTitle($pageTitle);
     $owa->setPageType($pageType);
     $owa->trackPageView();
@@ -199,7 +233,7 @@
 curl_setopt( $ch, CURLOPT_HEADER, 0 );
           curl_setopt($ch,CURLOPT_TIMEOUT,30); 
 $page = curl_exec($ch);
- if(curl_errno($ch)) echo "<font color=red> Database temporarily unavailable: ".curl_errno($ch)." ".curl_error($ch)."</font>";
+ if(curl_errno($ch)) echo "<font color=red> Database temporarily unavailable: ".curl_errno($ch)." ".curl_error($ch)."</font><br>";
 curl_close($ch);
 return $page;
 }
@@ -212,7 +246,15 @@
   return $f;
 }
 
-function staticmap($mapPoints, $zoom = 0, $markerImage = "iconb")
+function curPageURL() {
+$isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
+$port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
+$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
+$url = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.dirname($_SERVER['PHP_SELF'])."/";
+return $url;
+}
+
+function staticmap($mapPoints, $zoom = 0, $markerImage = "iconb", $collapsible = true)
 {
 $width = 300;
 $height = 300;
@@ -236,7 +278,7 @@
     if (sizeof($mapPoints) === 1) {
          if ($zoom == 0) $zoom = 14;
             $markers .= "{$mapPoints[0][0]},{$mapPoints[0][1]},$markerimage";
-            $center = "{$mapPoints[0][0]},{$mapPoints[0][1]}";        
+            $center = "{$mapPoints[0][0]},{$mapPoints[0][1]}";
     } else {
         foreach ($mapPoints as $index => $mapPoint) {
             $markers .= $mapPoint[0].",".$mapPoint[1].",".$markerImage.($index+1);
@@ -258,9 +300,9 @@
        $center = $totalLat/sizeof($mapPoints).",".$totalLon/sizeof($mapPoints);
     }
     $output = "";
-   if(basename($_SERVER['PHP_SELF']) != "tripPlanner.php") $output .= '<div data-role="collapsible" data-collapsed="true"><h3>Open Map...</h3>';
-    $output .= '<center><img src="staticmaplite/staticmap.php?center='.$center.'&zoom='.$zoom.'&size='.$width.'x'.$height.'&maptype=mapnik&markers='.$markers.'" width='.$width.' height='.$height.'></center>';
-   if(basename($_SERVER['PHP_SELF']) != "tripPlanner.php") $output .= '</div>';
+   if ($collapsible) $output .= '<div data-role="collapsible" data-collapsed="true"><h3>Open Map...</h3>';
+    $output .= '<center><img src="'.curPageURL().'staticmaplite/staticmap.php?center='.$center.'&zoom='.$zoom.'&size='.$width.'x'.$height.'&maptype=mapnik&markers='.$markers.'" width='.$width.' height='.$height.'></center>';
+   if ($collapsible) $output .= '</div>';
     return $output;
 }
 
@@ -368,7 +410,7 @@
 
 function geocode($query, $giveOptions) {
     global $cloudmadeAPIkey;
-       $url = "http://geocoding.cloudmade.com/$cloudmadeAPIkey/geocoding/v2/find.js?query=".$query."&bbox=-35.5,149.00,-35.15,149.1930&return_location=true&bbox_only=true";
+       $url = "http://geocoding.cloudmade.com/$cloudmadeAPIkey/geocoding/v2/find.js?query=".urlencode($query)."&bbox=-35.5,149.00,-35.15,149.1930&return_location=true&bbox_only=true";
       $contents = json_decode(getPage($url));
       if ($giveOptions) return $contents->features;
       elseif (isset($contents->features[0]->centroid)) return $contents->features[0]->centroid->coordinates[0].",".$contents->features[0]->centroid->coordinates[1];
@@ -445,11 +487,11 @@
         <div class="ui-body"> 
 		<div data-role="fieldcontain">
 	            <label for="geolocate"> Current Location: </label>
-			<input type="text" id="geolocate" name="geolocate" value="Enter co-ordinates or address here"/> <a href="#" style="display:none" name="here" id="here"/>Here?</a>
+			<input type="text" id="geolocate" name="geolocate" value="'. (isset($_SESSION['lat']) && isset($_SESSION['lon']) ? $_SESSION['lat'] .",". $_SESSION['lon'] :"Enter co-ordinates or address here"). '"/> <a href="#" style="display:none" name="here" id="here"/>Here?</a>
 	        </div>
     		<div data-role="fieldcontain">
 		        <label for="time"> Time: </label>
-		    	<input type="time" name="time" id="time" value="'. ($_SESSION['time'] ? $_SESSION['time'] : date("H:m")).'"/> <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"/>Current Time?</a>
 	        </div>
 		<div data-role="fieldcontain">
 		    <label for="service_period"> Service Period:  </label>
@@ -466,5 +508,7 @@
                 </form>
             </div></div>';
 }
+
+
 ?>