MyWay timeliness study data collection
MyWay timeliness study data collection

<?php <?php
if (php_uname('n') == "actbus-www") { if (php_uname('n') == "actbus-www") {
$conn = new PDO("pgsql:dbname=transitdata;user=transitdata;password=transitdata;host=bus-main.lambdacomplex.org"); $conn = new PDO("pgsql:dbname=transitdata;user=transitdata;password=transitdata;host=bus-main.lambdacomplex.org");
} }
else if (isDebugServer()) { else if (isDebugServer()) {
$conn = new PDO("pgsql:dbname=transitdata;user=postgres;password=snmc;host=localhost"); $conn = new PDO("pgsql:dbname=transitdata;user=postgres;password=snmc;host=localhost");
} }
else { else {
$conn = new PDO("pgsql:dbname=transitdata;user=transitdata;password=transitdata;host=localhost"); $conn = new PDO("pgsql:dbname=transitdata;user=transitdata;password=transitdata;host=localhost");
} }
if (!$conn) { if (!$conn) {
die("A database error occurred.\n"); die("A database error occurred.\n");
} }
  if (isDebug()) {
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
function databaseError($errMsg) function databaseError($errMsg)
{ {
die($errMsg); die($errMsg);
} }
include ('db/route-dao.inc.php'); include ('db/route-dao.inc.php');
include ('db/trip-dao.inc.php'); include ('db/trip-dao.inc.php');
include ('db/stop-dao.inc.php'); include ('db/stop-dao.inc.php');
include ('db/servicealert-dao.inc.php'); include ('db/servicealert-dao.inc.php');
?> ?>
   
<?php <?php
// SELECT array_to_string(array(SELECT REPLACE(name_2006, ',', '\,') as name FROM suburbs order by name), ',') // 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"); $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");
function staticmap($mapPoints, $zoom = 0, $markerImage = "iconb", $collapsible = true) function staticmap($mapPoints, $zoom = 0, $markerImage = "iconb", $collapsible = true)
{ {
  global $labsPath;
$width = 300; $width = 300;
$height = 300; $height = 300;
$metersperpixel[9] = 305.492 * $width; $metersperpixel[9] = 305.492 * $width;
$metersperpixel[10] = 152.746 * $width; $metersperpixel[10] = 152.746 * $width;
$metersperpixel[11] = 76.373 * $width; $metersperpixel[11] = 76.373 * $width;
$metersperpixel[12] = 38.187 * $width; $metersperpixel[12] = 38.187 * $width;
$metersperpixel[13] = 19.093 * $width; $metersperpixel[13] = 19.093 * $width;
$metersperpixel[14] = 9.547 * $width; $metersperpixel[14] = 9.547 * $width;
$metersperpixel[15] = 4.773 * $width; $metersperpixel[15] = 4.773 * $width;
$metersperpixel[16] = 2.387 * $width; $metersperpixel[16] = 2.387 * $width;
// $metersperpixel[17]=1.193*$width; // $metersperpixel[17]=1.193*$width;
$center = ""; $center = "";
$markers = ""; $markers = "";
$minlat = 999; $minlat = 999;
$minlon = 999; $minlon = 999;
$maxlat = 0; $maxlat = 0;
$maxlon = 0; $maxlon = 0;
if (sizeof($mapPoints) < 1) return "map error"; if (sizeof($mapPoints) < 1) return "map error";
if (sizeof($mapPoints) === 1) { if (sizeof($mapPoints) === 1) {
if ($zoom == 0) $zoom = 14; if ($zoom == 0) $zoom = 14;
$markers.= "{$mapPoints[0][0]},{$mapPoints[0][1]},$markerimage"; $markers.= "{$mapPoints[0][0]},{$mapPoints[0][1]},$markerimage";
$center = "{$mapPoints[0][0]},{$mapPoints[0][1]}"; $center = "{$mapPoints[0][0]},{$mapPoints[0][1]}";
} }
else { else {
foreach ($mapPoints as $index => $mapPoint) { foreach ($mapPoints as $index => $mapPoint) {
$markers.= $mapPoint[0] . "," . $mapPoint[1] . "," . $markerImage . ($index + 1); $markers.= $mapPoint[0] . "," . $mapPoint[1] . "," . $markerImage . ($index + 1);
if ($index + 1 != sizeof($mapPoints)) $markers.= "|"; if ($index + 1 != sizeof($mapPoints)) $markers.= "|";
if ($mapPoint[0] < $minlat) $minlat = $mapPoint[0]; if ($mapPoint[0] < $minlat) $minlat = $mapPoint[0];
if ($mapPoint[0] > $maxlat) $maxlat = $mapPoint[0]; if ($mapPoint[0] > $maxlat) $maxlat = $mapPoint[0];
if ($mapPoint[1] < $minlon) $minlon = $mapPoint[1]; if ($mapPoint[1] < $minlon) $minlon = $mapPoint[1];
if ($mapPoint[1] > $maxlon) $maxlon = $mapPoint[1]; if ($mapPoint[1] > $maxlon) $maxlon = $mapPoint[1];
$totalLat+= $mapPoint[0]; $totalLat+= $mapPoint[0];
$totalLon+= $mapPoint[1]; $totalLon+= $mapPoint[1];
} }
if ($zoom == 0) { if ($zoom == 0) {
$mapwidthinmeters = distance($minlat, $minlon, $minlat, $maxlon); $mapwidthinmeters = distance($minlat, $minlon, $minlat, $maxlon);
foreach (array_reverse($metersperpixel, true) as $zoomLevel => $maxdistance) { foreach (array_reverse($metersperpixel, true) as $zoomLevel => $maxdistance) {
if ($zoom == 0 && $mapwidthinmeters < ($maxdistance + 50)) $zoom = $zoomLevel; if ($zoom == 0 && $mapwidthinmeters < ($maxdistance + 50)) $zoom = $zoomLevel;
} }
} }
$center = $totalLat / sizeof($mapPoints) . "," . $totalLon / sizeof($mapPoints); $center = $totalLat / sizeof($mapPoints) . "," . $totalLon / sizeof($mapPoints);
} }
$output = ""; $output = "";
if ($collapsible) $output.= '<div class="map" data-role="collapsible" data-collapsed="true"><h3>Open Map...</h3>'; if ($collapsible) $output.= '<div class="map" data-role="collapsible" data-collapsed="true"><h3>Open Map...</h3>';
$output.= '<img class="map" src="' . curPageURL() . '/lib/staticmaplite/staticmap.php?center=' . $center . '&amp;zoom=' . $zoom . '&amp;size=' . $width . 'x' . $height . '&amp;markers=' . $output.= '<img class="map" src="' . curPageURL() . '/'. $labsPath. '/lib/staticmaplite/staticmap.php?center=' . $center . '&amp;zoom=' . $zoom . '&amp;size=' . $width . 'x' . $height . '&amp;markers=' .
$markers . '" width=' . $width . ' height=' . $height . '>'; $markers . '" width=' . $width . ' height=' . $height . '>';
if ($collapsible) $output.= '</div>'; if ($collapsible) $output.= '</div>';
return $output; return $output;
} }
function distance($lat1, $lng1, $lat2, $lng2, $roundLargeValues = false) function distance($lat1, $lng1, $lat2, $lng2, $roundLargeValues = false)
{ {
$pi80 = M_PI / 180; $pi80 = M_PI / 180;
$lat1*= $pi80; $lat1*= $pi80;
$lng1*= $pi80; $lng1*= $pi80;
$lat2*= $pi80; $lat2*= $pi80;
$lng2*= $pi80; $lng2*= $pi80;
$r = 6372.797; // mean radius of Earth in km $r = 6372.797; // mean radius of Earth in km
$dlat = $lat2 - $lat1; $dlat = $lat2 - $lat1;
$dlng = $lng2 - $lng1; $dlng = $lng2 - $lng1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2); $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
$c = 2 * atan2(sqrt($a) , sqrt(1 - $a)); $c = 2 * atan2(sqrt($a) , sqrt(1 - $a));
$km = $r * $c; $km = $r * $c;
if ($roundLargeValues) { if ($roundLargeValues) {
if ($km < 1) return floor($km * 1000); if ($km < 1) return floor($km * 1000);
else return round($km,2)."k"; else return round($km,2)."k";
} else return floor($km * 1000); } else return floor($km * 1000);
} }
   
function decodePolylineToArray($encoded) function decodePolylineToArray($encoded)
{ {
// source: http://latlongeeks.com/forum/viewtopic.php?f=4&t=5 // source: http://latlongeeks.com/forum/viewtopic.php?f=4&t=5
$length = strlen($encoded); $length = strlen($encoded);
$index = 0; $index = 0;
$points = array(); $points = array();
$lat = 0; $lat = 0;
$lng = 0; $lng = 0;
while ($index < $length) { while ($index < $length) {
// Temporary variable to hold each ASCII byte. // Temporary variable to hold each ASCII byte.
$b = 0; $b = 0;
// The encoded polyline consists of a latitude value followed by a // The encoded polyline consists of a latitude value followed by a
// longitude value. They should always come in pairs. Read the // longitude value. They should always come in pairs. Read the
// latitude value first. // latitude value first.
$shift = 0; $shift = 0;
$result = 0; $result = 0;
do { do {
// The `ord(substr($encoded, $index++))` statement returns the ASCII // The `ord(substr($encoded, $index++))` statement returns the ASCII
// code for the character at $index. Subtract 63 to get the original // code for the character at $index. Subtract 63 to get the original
// value. (63 was added to ensure proper ASCII characters are displayed // value. (63 was added to ensure proper ASCII characters are displayed
// in the encoded polyline string, which is `human` readable) // in the encoded polyline string, which is `human` readable)
$b = ord(substr($encoded, $index++)) - 63; $b = ord(substr($encoded, $index++)) - 63;
// AND the bits of the byte with 0x1f to get the original 5-bit `chunk. // AND the bits of the byte with 0x1f to get the original 5-bit `chunk.
// Then left shift the bits by the required amount, which increases // Then left shift the bits by the required amount, which increases
// by 5 bits each time. // by 5 bits each time.
// OR the value into $results, which sums up the individual 5-bit chunks // OR the value into $results, which sums up the individual 5-bit chunks
// into the original value. Since the 5-bit chunks were reversed in // into the original value. Since the 5-bit chunks were reversed in
// order during encoding, reading them in this way ensures proper // order during encoding, reading them in this way ensures proper
// summation. // summation.
$result|= ($b & 0x1f) << $shift; $result|= ($b & 0x1f) << $shift;
$shift+= 5; $shift+= 5;
} }
// Continue while the read byte is >= 0x20 since the last `chunk` // Continue while the read byte is >= 0x20 since the last `chunk`
// was not OR'd with 0x20 during the conversion process. (Signals the end) // was not OR'd with 0x20 during the conversion process. (Signals the end)
while ($b >= 0x20); while ($b >= 0x20);
// Check if negative, and convert. (All negative values have the last bit // Check if negative, and convert. (All negative values have the last bit
// set) // set)
$dlat = (($result & 1) ? ~($result >> 1) : ($result >> 1)); $dlat = (($result & 1) ? ~($result >> 1) : ($result >> 1));
// Compute actual latitude since value is offset from previous value. // Compute actual latitude since value is offset from previous value.
$lat+= $dlat; $lat+= $dlat;
// The next values will correspond to the longitude for this point. // The next values will correspond to the longitude for this point.
$shift = 0; $shift = 0;
$result = 0; $result = 0;
do { do {
$b = ord(substr($encoded, $index++)) - 63; $b = ord(substr($encoded, $index++)) - 63;
$result|= ($b & 0x1f) << $shift; $result|= ($b & 0x1f) << $shift;
$shift+= 5; $shift+= 5;
} while ($b >= 0x20); } while ($b >= 0x20);
$dlng = (($result & 1) ? ~($result >> 1) : ($result >> 1)); $dlng = (($result & 1) ? ~($result >> 1) : ($result >> 1));
$lng+= $dlng; $lng+= $dlng;
// The actual latitude and longitude values were multiplied by // The actual latitude and longitude values were multiplied by
// 1e5 before encoding so that they could be converted to a 32-bit // 1e5 before encoding so that they could be converted to a 32-bit
// integer representation. (With a decimal accuracy of 5 places) // integer representation. (With a decimal accuracy of 5 places)
// Convert back to original values. // Convert back to original values.
$points[] = array( $points[] = array(
$lat * 1e-5, $lat * 1e-5,
$lng * 1e-5 $lng * 1e-5
); );
} }
return $points; return $points;
} }
function geocode($query, $giveOptions) function geocode($query, $giveOptions)
{ {
global $cloudmadeAPIkey; global $cloudmadeAPIkey;
$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"; $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)); $contents = json_decode(getPage($url));
if ($giveOptions) return $contents->features; if ($giveOptions) return $contents->features;
elseif (isset($contents->features[0]->centroid)) return $contents->features[0]->centroid->coordinates[0] . "," . $contents->features[0]->centroid->coordinates[1]; elseif (isset($contents->features[0]->centroid)) return $contents->features[0]->centroid->coordinates[0] . "," . $contents->features[0]->centroid->coordinates[1];
else return ""; else return "";
} }
function reverseGeocode($lat, $lng) function reverseGeocode($lat, $lng)
{ {
global $cloudmadeAPIkey; global $cloudmadeAPIkey;
$url = "http://geocoding.cloudmade.com/$cloudmadeAPIkey/geocoding/v2/find.js?around=" . $lat . "," . $lng . "&distance=closest&object_type=road"; $url = "http://geocoding.cloudmade.com/$cloudmadeAPIkey/geocoding/v2/find.js?around=" . $lat . "," . $lng . "&distance=closest&object_type=road";
$contents = json_decode(getPage($url)); $contents = json_decode(getPage($url));
return $contents->features[0]->properties->name; return $contents->features[0]->properties->name;
} }
?> ?>
   
<?php <?php
// Copyright 2009 Google Inc. All Rights Reserved. // Copyright 2009 Google Inc. All Rights Reserved.
$GA_ACCOUNT = "MO-22173039-1"; $GA_ACCOUNT = "MO-22173039-1";
$GA_PIXEL = "/lib/ga.php"; $GA_PIXEL = "/lib/ga.php";
function googleAnalyticsGetImageUrl() function googleAnalyticsGetImageUrl()
{ {
global $GA_ACCOUNT, $GA_PIXEL; global $GA_ACCOUNT, $GA_PIXEL;
//if (stristr($_SERVER['HTTP_USER_AGENT'], 'Googlebot') return ""; //if (stristr($_SERVER['HTTP_USER_AGENT'], 'Googlebot') return "";
$url = ""; $url = "";
$url.= $GA_PIXEL . "?"; $url.= $GA_PIXEL . "?";
$url.= "utmac=" . $GA_ACCOUNT; $url.= "utmac=" . $GA_ACCOUNT;
$url.= "&utmn=" . rand(0, 0x7fffffff); $url.= "&utmn=" . rand(0, 0x7fffffff);
$referer = $_SERVER["HTTP_REFERER"]; $referer = $_SERVER["HTTP_REFERER"];
$query = $_SERVER["QUERY_STRING"]; $query = $_SERVER["QUERY_STRING"];
$path = $_SERVER["REQUEST_URI"]; $path = $_SERVER["REQUEST_URI"];
if (empty($referer)) { if (empty($referer)) {
$referer = "-"; $referer = "-";
} }
$url.= "&utmr=" . urlencode($referer); $url.= "&utmr=" . urlencode($referer);
if (!empty($path)) { if (!empty($path)) {
$url.= "&utmp=" . urlencode($path); $url.= "&utmp=" . urlencode($path);
} }
$url.= "&guid=ON"; $url.= "&guid=ON";
return str_replace("&", "&amp;", $url); return str_replace("&", "&amp;", $url);
} }
   
$labsPath = "";  
if (strstr($_SERVER['PHP_SELF'],"labs")) $labsPath = "../";  
   
function include_header($pageTitle, $pageType, $opendiv = true, $geolocate = false, $datepicker = false) function include_header($pageTitle, $pageType, $opendiv = true, $geolocate = false, $datepicker = false)
{ {
global $labsPath; global $labsPath;
echo ' echo '
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>' . $pageTitle . '</title> <title>' . $pageTitle . '</title>
<meta name="google-site-verification" <meta name="google-site-verification"
content="-53T5Qn4TB_de1NyfR_ZZkEVdUNcNFSaYKSFkWKx-sY" /> content="-53T5Qn4TB_de1NyfR_ZZkEVdUNcNFSaYKSFkWKx-sY" />
<link rel="stylesheet" href="'.$labsPath.'css/jquery-ui-1.8.12.custom.css" />'; <link rel="stylesheet" href="'.$labsPath.'css/jquery-ui-1.8.12.custom.css" />';
if (isDebugServer()) { if (isDebugServer()) {
echo '<link rel="stylesheet" href="'.$labsPath.'css/jquery.mobile-1.0b1.css" /> echo '<link rel="stylesheet" href="'.$labsPath.'css/jquery.mobile-1.0b1.css" />
<script type="text/javascript" src="'.$labsPath.'js/jquery-1.6.1.min.js"></script> <script type="text/javascript" src="'.$labsPath.'js/jquery-1.6.1.min.js"></script>
<script>$(document).bind("mobileinit", function(){ <script>$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false; $.mobile.ajaxEnabled = false;
}); });
</script> </script>
<script type="text/javascript" src="'.$labsPath.'js/jquery.mobile-1.0b1.js"></script>'; <script type="text/javascript" src="'.$labsPath.'js/jquery.mobile-1.0b1.js"></script>';
} }
else { else {
echo '<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css" /> echo '<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>$(document).bind("mobileinit", function(){ <script>$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false; $.mobile.ajaxEnabled = false;
}); });
</script> </script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>'; <script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>';
} }
echo ' echo '
<script src="'.$labsPath.'js/jquery.ui.autocomplete.min.js"></script> <script src="'.$labsPath.'js/jquery.ui.autocomplete.min.js"></script>
<script src="'.$labsPath.'js/jquery.ui.core.min.js"></script> <script src="'.$labsPath.'js/jquery.ui.core.min.js"></script>
<script src="'.$labsPath.'js/jquery.ui.position.min.js"></script> <script src="'.$labsPath.'js/jquery.ui.position.min.js"></script>
<script src="'.$labsPath.'js/jquery.ui.widget.min.js"></script> <script src="'.$labsPath.'js/jquery.ui.widget.min.js"></script>
<script> <script>
$(function() { $(function() {
$( "#geolocate" ).autocomplete({ $( "#geolocate" ).autocomplete({
source: "lib/autocomplete.php", source: "lib/autocomplete.php",
minLength: 2 minLength: 2
}); });
$( "#from" ).autocomplete({ $( "#from" ).autocomplete({
source: "lib/autocomplete.php", source: "lib/autocomplete.php",
minLength: 2 minLength: 2
}); });
$( "#to" ).autocomplete({ $( "#to" ).autocomplete({
source: "lib/autocomplete.php", source: "lib/autocomplete.php",
minLength: 2 minLength: 2
}); });
}); });
</script> </script>
'; ';
echo '<style type="text/css"> echo '<style type="text/css">
.ui-li-thumb, .ui-li-icon { position: relative; }'; .ui-li-thumb, .ui-li-icon { position: relative; }';
   
if (strstr($_SERVER['HTTP_USER_AGENT'], 'Android')) echo '.ui-shadow,.ui-btn-up-a,.ui-btn-hover-a,.ui-btn-down-a,.ui-body-b,.ui-btn-up-b,.ui-btn-hover-b, if (strstr($_SERVER['HTTP_USER_AGENT'], 'Android')) echo '.ui-shadow,.ui-btn-up-a,.ui-btn-hover-a,.ui-btn-down-a,.ui-body-b,.ui-btn-up-b,.ui-btn-hover-b,
.ui-btn-down-b,.ui-bar-c,.ui-body-c,.ui-btn-up-c,.ui-btn-hover-c,.ui-btn-down-c,.ui-bar-c,.ui-body-d, .ui-btn-down-b,.ui-bar-c,.ui-body-c,.ui-btn-up-c,.ui-btn-hover-c,.ui-btn-down-c,.ui-bar-c,.ui-body-d,
.ui-btn-up-d,.ui-btn-hover-d,.ui-btn-down-d,.ui-bar-d,.ui-body-e,.ui-btn-up-e,.ui-btn-hover-e, .ui-btn-up-d,.ui-btn-hover-d,.ui-btn-down-d,.ui-bar-d,.ui-body-e,.ui-btn-up-e,.ui-btn-hover-e,
.ui-btn-down-e,.ui-bar-e,.ui-overlay-shadow,.ui-shadow,.ui-btn-active,.ui-body-a,.ui-bar-a { .ui-btn-down-e,.ui-bar-e,.ui-overlay-shadow,.ui-shadow,.ui-btn-active,.ui-body-a,.ui-bar-a {
text-shadow: none; text-shadow: none;
box-shadow: none; box-shadow: none;
-webkit-box-shadow: none; -webkit-box-shadow: none;
}'; }';
echo ' echo '
.ui-navbar { .ui-navbar {
width: 100%; width: 100%;
} }
.ui-btn-inner { .ui-btn-inner {
white-space: normal !important; white-space: normal !important;
} }
.ui-li-heading { .ui-li-heading {
white-space: normal !important; white-space: normal !important;
} }
.ui-listview-filter { .ui-listview-filter {
margin: 0 !important; margin: 0 !important;
} }
.ui-icon-navigation { .ui-icon-navigation {
background-image: url('.$labsPath.'css/images/113-navigation.png); background-image: url('.$labsPath.'css/images/113-navigation.png);
background-position: 1px 0; background-position: 1px 0;
} }
.ui-icon-beaker { .ui-icon-beaker {
background-image: url('.$labsPath.'css/images/91-beaker-2.png); background-image: url('.$labsPath.'css/images/91-beaker-2.png);
background-position: 1px 0; background-position: 1px 0;
} }
#footer { #footer {
text-size: 0.75em; text-size: 0.75em;
text-align: center; text-align: center;
} }
body { body {
background-color: #F0F0F0; background-color: #F0F0F0;
} }
#jqm-homeheader { #jqm-homeheader {
text-align: center; text-align: center;
} }
.viaPoints { .viaPoints {
display: none; display: none;
text-size: 0.2em; text-size: 0.2em;
} }
.min-width-480px .viaPoints { .min-width-480px .viaPoints {
display: inline; display: inline;
} }
#extrainfo { #extrainfo {
visibility: hidden; visibility: hidden;
display: none; display: none;
} }
#servicewarning { #servicewarning {
padding: 1em; padding: 1em;
margin-bottom: 0.5em; margin-bottom: 0.5em;
text-size: 0.2em; text-size: 0.2em;
background-color: #FF9; background-color: #FF9;
-moz-border-radius: 15px; -moz-border-radius: 15px;
border-radius: 15px; border-radius: 15px;
} }
/*#leftcolumn { /*#leftcolumn {
float: none; float: none;
} }
.min-width-768px #leftcolumn { .min-width-768px #leftcolumn {
float: left; float: left;
width: 30%; width: 30%;
} }
#rightcolumn { #rightcolumn {
float: none; float: none;
} }
.min-width-768px #rightcolumn { .min-width-768px #rightcolumn {
float: right; float: right;
width: 68%; width: 68%;
}*/ }*/
   
#footer { #footer {
clear:both; clear:both;
text-align:center; text-align:center;
} }
// source http://webaim.org/techniques/skipnav/ // source http://webaim.org/techniques/skipnav/
#skip a, #skip a:hover, #skip a:visited #skip a, #skip a:hover, #skip a:visited
{ {
position:absolute; position:absolute;
left:0px; left:0px;
top:-500px; top:-500px;
width:1px; width:1px;
height:1px; height:1px;
overflow:hidden; overflow:hidden;
} }
   
#skip a:active, #skip a:focus #skip a:active, #skip a:focus
{ {
position:static; position:static;
width:auto; width:auto;
height:auto; height:auto;
} }
</style>'; </style>';
if (strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad')) { if (strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
echo '<meta name="apple-mobile-web-app-capable" content="yes" /> echo '<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-startup-image" href="startup.png" /> <link rel="apple-touch-startup-image" href="startup.png" />
<link rel="apple-touch-icon" href="apple-touch-icon.png" />'; <link rel="apple-touch-icon" href="apple-touch-icon.png" />';
} }
if ($geolocate) { if ($geolocate) {
echo "<script> echo "<script>
   
function success(position) { function success(position) {
$('#error').val('Location now detected. Please wait for data to load.'); $('#error').val('Location now detected. Please wait for data to load.');
$('#geolocate').val(position.coords.latitude+','+position.coords.longitude); $('#geolocate').val(position.coords.latitude+','+position.coords.longitude);
$.ajax({ url: \"include/common.inc.php?geolocate=yes&lat=\"+position.coords.latitude+\"&lon=\"+position.coords.longitude }); $.ajax({ url: \"include/common.inc.php?geolocate=yes&lat=\"+position.coords.latitude+\"&lon=\"+position.coords.longitude });
location.reload(true); location.reload(true);
} }
function error(msg) { function error(msg) {
$('#error').val('Error: '+msg); $('#error').val('Error: '+msg);
} }
   
function geolocate() { function geolocate() {
if (navigator.geolocation) { if (navigator.geolocation) {
var options = { var options = {
enableHighAccuracy: true, enableHighAccuracy: true,
timeout: 60000, timeout: 60000,
maximumAge: 10000 maximumAge: 10000
} }
navigator.geolocation.getCurrentPosition(success, error, options); navigator.geolocation.getCurrentPosition(success, error, options);
} }
} }
$(document).ready(function() { $(document).ready(function() {
$('#here').click(function(event) { $('#geolocate').val(geolocate()); return false;}); $('#here').click(function(event) { $('#geolocate').val(geolocate()); return false;});
$('#here').show(); $('#here').show();
/*if ($.mobile.media('screen and (min-width: 768px)')) { /*if ($.mobile.media('screen and (min-width: 768px)')) {
$('map a:first').click(); $('map a:first').click();
$('#settings a:first').click(); $('#settings a:first').click();
}*/ }*/
}); });
"; ";
if (!isset($_SESSION['lat']) || $_SESSION['lat'] == "") echo "geolocate();"; if (!isset($_SESSION['lat']) || $_SESSION['lat'] == "") echo "geolocate();";
echo "</script> "; echo "</script> ";
} }
if (isAnalyticsOn()) echo ' if (isAnalyticsOn()) echo '
<script type="text/javascript">' . " <script type="text/javascript">' . "
   
var _gaq = _gaq || []; var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-22173039-1']); _gaq.push(['_setAccount', 'UA-22173039-1']);
_gaq.push(['_trackPageview']); _gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']); _gaq.push(['_trackPageLoadTime']);
</script>"; </script>";
echo '</head> echo '</head>
<body> <body>
<div id="skip"> <div id="skip">
<a href="#maincontent">Skip to content</a> <a href="#maincontent">Skip to content</a>
</div> </div>
'; ';
if ($opendiv) { if ($opendiv) {
echo '<div data-role="page"> echo '<div data-role="page">
<div data-role="header" data-position="inline"> <div data-role="header" data-position="inline">
<a href="' . (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "javascript:history.go(-1)") . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a> <a href="' . (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "javascript:history.go(-1)") . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a>
<h1>' . $pageTitle . '</h1> <h1>' . $pageTitle . '</h1>
<a href="'.$labsPath.'/index.php" data-icon="home" class="ui-btn-right">Home</a> <a href="'.$labsPath.'/index.php" data-icon="home" class="ui-btn-right">Home</a>
</div><!-- /header --> </div><!-- /header -->
<a name="maincontent" id="maincontent"></a> <a name="maincontent" id="maincontent"></a>
<div data-role="content"> '; <div data-role="content"> ';
$overrides = getServiceOverride(); $overrides = getServiceOverride();
if ($overrides['service_id']) { if ($overrides['service_id']) {
if ($overrides['service_id'] == "noservice") { if ($overrides['service_id'] == "noservice") {
echo '<div id="servicewarning">Buses are <strong>not running today</strong> due to industrial action/public holiday. See <a echo '<div id="servicewarning">Buses are <strong>not running today</strong> due to industrial action/public holiday. See <a
href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>'; href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>';
} }
else { else {
echo '<div id="servicewarning">Buses are running on an altered timetable today due to industrial action/public holiday. See <a href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>'; echo '<div id="servicewarning">Buses are running on an altered timetable today due to industrial action/public holiday. See <a href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>';
} }
} }
} }
   
} }
function include_footer() function include_footer()
{ {
   
global $labsPath; global $labsPath;
echo '<div id="footer"><a href="'.$labsPath.'about.php">About/Contact Us</a>&nbsp;<a href="'.$labsPath.'feedback.php">Feedback/Bug Report</a>&nbsp;<a href="'.$labsPath.'privacy.php">Privacy Policy</a>'; echo '<div id="footer"><a href="'.$labsPath.'about.php">About/Contact Us</a>&nbsp;<a href="'.$labsPath.'feedback.php">Feedback/Bug Report</a>&nbsp;<a href="'.$labsPath.'privacy.php">Privacy Policy</a>';
echo '</div>'; echo '</div>';
if (isAnalyticsOn()) { if (isAnalyticsOn()) {
echo "<script> (function() { echo "<script> (function() {
var ga = document.createElement('script'); ga.type = var ga = document.createElement('script'); ga.type =
'text/javascript'; ga.async = true; 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? ga.src = ('https:' == document.location.protocol ?
'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s); s.parentNode.insertBefore(ga, s);
})();</script>"; })();</script>";
$googleAnalyticsImageUrl = googleAnalyticsGetImageUrl(); $googleAnalyticsImageUrl = googleAnalyticsGetImageUrl();
echo '<noscript><img src="' . $googleAnalyticsImageUrl . '" /></noscript>'; echo '<noscript><img src="' . $googleAnalyticsImageUrl . '" /></noscript>';
   
} }
echo "\n</div></div></body></html>"; echo "\n</div></div></body></html>";
} }
function timePlaceSettings($geolocate = false) function timePlaceSettings($geolocate = false)
{ {
global $service_periods; global $service_periods;
$geoerror = false; $geoerror = false;
if ($geolocate == true) { if ($geolocate == true) {
$geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == ""; $geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "";
} }
echo '<div id="error">'; echo '<div id="error">';
if ($geoerror) { if ($geoerror) {
echo 'Sorry, but your location could not currently be detected. echo 'Sorry, but your location could not currently be detected.
Please allow location permission, wait for your location to be detected, Please allow location permission, wait for your location to be detected,
or enter an address/co-ordinates in the box below.'; or enter an address/co-ordinates in the box below.';
} }
echo '</div>'; echo '</div>';
echo '<div id="settings" data-role="collapsible" data-collapsed="' . !$geoerror . '"> echo '<div id="settings" data-role="collapsible" data-collapsed="' . !$geoerror . '">
<h3>Change Time/Place (' . (isset($_SESSION['time']) ? $_SESSION['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3> <h3>Change Time/Place (' . (isset($_SESSION['time']) ? $_SESSION['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3>
<form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post"> <form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post">
<div class="ui-body"> <div class="ui-body">
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="geolocate"> Current Location: </label> <label for="geolocate"> Current Location: </label>
<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> <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>
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="time"> Time: </label> <label for="time"> Time: </label>
<input type="time" name="time" id="time" value="' . (isset($_SESSION['time']) ? $_SESSION['time'] : date("H:i")) . '"/> <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().toString().length == 1 ? '0'+ d.getMinutes(): d.getMinutes()));" . '">Current Time?</a> <a href="#" name="currentTime" id="currentTime" onClick="var d = new Date();' . "$('#time').val(d.getHours() +':'+ (d.getMinutes().toString().length == 1 ? '0'+ d.getMinutes(): d.getMinutes()));" . '">Current Time?</a>
</div> </div>
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="service_period"> Service Period: </label> <label for="service_period"> Service Period: </label>
<select name="service_period" id="service_period">'; <select name="service_period" id="service_period">';
foreach ($service_periods as $service_period) { foreach ($service_periods as $service_period) {
echo "<option value=\"$service_period\"" . (service_period() === $service_period ? " SELECTED" : "") . '>' . ucwords($service_period) . '</option>'; echo "<option value=\"$service_period\"" . (service_period() === $service_period ? " SELECTED" : "") . '>' . ucwords($service_period) . '</option>';
} }
echo '</select> echo '</select>
<a href="#" style="display:none" name="currentPeriod" id="currentPeriod">Current Period?</a> <a href="#" style="display:none" name="currentPeriod" id="currentPeriod">Current Period?</a>
</div> </div>
<input type="submit" value="Update"/> <input type="submit" value="Update"/>
</div></form> </div></form>
</div>'; </div>';
} }
function trackEvent($category, $action, $label = "", $value = - 1) function trackEvent($category, $action, $label = "", $value = - 1)
{ {
if (isAnalyticsOn()) { if (isAnalyticsOn()) {
echo "\n<script> _gaq.push(['_trackEvent', '$category', '$action'" . ($label != "" ? ", '$label'" : "") . ($value != - 1 ? ", $value" : "") . "]);</script>"; echo "\n<script> _gaq.push(['_trackEvent', '$category', '$action'" . ($label != "" ? ", '$label'" : "") . ($value != - 1 ? ", $value" : "") . "]);</script>";
} }
} }
?> ?>
   
<?php <?php
$service_periods = Array( $service_periods = Array(
'sunday', 'sunday',
'saturday', 'saturday',
'weekday' 'weekday'
); );
   
function service_period() function service_period($date = "")
{ {
if (isset($_SESSION['service_period'])) return $_SESSION['service_period']; if (isset($_SESSION['service_period'])) return $_SESSION['service_period'];
$override = getServiceOverride(); $override = getServiceOverride($date);
if ($override['service_id']){ if ($override['service_id']){
return $override['service_id']; return $override['service_id'];
} }
   
switch (date('w')) { switch (date('w',($date != "" ? $date : time()))) {
case 0: case 0:
return 'sunday'; return 'sunday';
case 6: case 6:
return 'saturday'; return 'saturday';
default: default:
return 'weekday'; return 'weekday';
} }
} }
function midnight_seconds() function midnight_seconds()
{ {
// from http://www.perturb.org/display/Perlfunc__Seconds_Since_Midnight.html // from http://www.perturb.org/display/Perlfunc__Seconds_Since_Midnight.html
if (isset($_SESSION['time'])) { if (isset($_SESSION['time'])) {
$time = strtotime($_SESSION['time']); $time = strtotime($_SESSION['time']);
return (date("G", $time) * 3600) + (date("i", $time) * 60) + date("s", $time); return (date("G", $time) * 3600) + (date("i", $time) * 60) + date("s", $time);
} }
return (date("G") * 3600) + (date("i") * 60) + date("s"); return (date("G") * 3600) + (date("i") * 60) + date("s");
} }
function midnight_seconds_to_time($seconds) function midnight_seconds_to_time($seconds)
{ {
if ($seconds > 0) { if ($seconds > 0) {
$midnight = mktime(0, 0, 0, date("n") , date("j") , date("Y")); $midnight = mktime(0, 0, 0, date("n") , date("j") , date("Y"));
return date("h:ia", $midnight + $seconds); return date("h:ia", $midnight + $seconds);
} }
else { else {
return ""; return "";
} }
} }
?> ?>
   
<?php <?php
date_default_timezone_set('Australia/ACT'); date_default_timezone_set('Australia/ACT');
$debugOkay = Array( $debugOkay = Array(
"session", "session",
"json", "json",
"phperror", "phperror",
"awsotp", "awsotp",
//"squallotp", //"squallotp",
"vanilleotp", "vanilleotp",
"database", "database",
"other" "other"
); );
$cloudmadeAPIkey = "daa03470bb8740298d4b10e3f03d63e6"; $cloudmadeAPIkey = "daa03470bb8740298d4b10e3f03d63e6";
$googleMapsAPIkey = "ABQIAAAA95XYXN0cki3Yj_Sb71CFvBTPaLd08ONybQDjcH_VdYtHHLgZvRTw2INzI_m17_IoOUqH3RNNmlTk1Q"; $googleMapsAPIkey = "ABQIAAAA95XYXN0cki3Yj_Sb71CFvBTPaLd08ONybQDjcH_VdYtHHLgZvRTw2INzI_m17_IoOUqH3RNNmlTk1Q";
$otpAPIurl = 'http://localhost:8080/opentripplanner-api-webapp/'; $otpAPIurl = 'http://localhost:8080/opentripplanner-api-webapp/';
if (isDebug("awsotp") || php_uname('n') == "maxious.xen.prgmr.com") { if (isDebug("awsotp") || php_uname('n') == "maxious.xen.prgmr.com") {
$otpAPIurl = 'http://bus-main.lambdacomplex.org:8080/opentripplanner-api-webapp/'; $otpAPIurl = 'http://bus-main.lambdacomplex.org:8080/opentripplanner-api-webapp/';
} }
if (isDebug("dotcloudotp") || php_uname('n') == "actbus-www") { if (isDebug("dotcloudotp") || php_uname('n') == "actbus-www") {
$otpAPIurl = 'http://otp.actbus.dotcloud.com/opentripplanner-api-webapp/'; $otpAPIurl = 'http://otp.actbus.dotcloud.com/opentripplanner-api-webapp/';
} }
if (isDebug("squallotp")) { if (isDebug("squallotp")) {
$otpAPIurl = 'http://10.0.1.108:5080/opentripplanner-api-webapp/'; $otpAPIurl = 'http://10.0.1.108:5080/opentripplanner-api-webapp/';
} }
if (isDebug("vanilleotp")) { if (isDebug("vanilleotp")) {
$otpAPIurl = 'http://10.0.1.135:8080/opentripplanner-api-webapp/'; $otpAPIurl = 'http://10.0.1.135:8080/opentripplanner-api-webapp/';
} }
if (isDebug("phperror")) error_reporting(E_ALL ^ E_NOTICE); if (isDebug("phperror")) error_reporting(E_ALL ^ E_NOTICE);
  $labsPath = "";
  if (strstr($_SERVER['PHP_SELF'],"labs")) $labsPath = "../";
   
include_once ("common-geo.inc.php"); include_once ("common-geo.inc.php");
include_once ("common-net.inc.php"); include_once ("common-net.inc.php");
include_once ("common-transit.inc.php"); include_once ("common-transit.inc.php");
include_once ("common-db.inc.php"); include_once ("common-db.inc.php");
   
include_once ("common-request.inc.php"); include_once ("common-request.inc.php");
include_once ("common-session.inc.php"); include_once ("common-session.inc.php");
include_once ("common-template.inc.php"); include_once ("common-template.inc.php");
   
function isDebugServer() function isDebugServer()
{ {
return $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1" || !$_SERVER['SERVER_NAME']; return $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1" || !$_SERVER['SERVER_NAME'];
} }
function isAnalyticsOn() function isAnalyticsOn()
{ {
return !isDebugServer(); return !isDebugServer();
} }
function isDebug($debugReason = "other") function isDebug($debugReason = "other")
{ {
global $debugOkay; global $debugOkay;
return in_array($debugReason, $debugOkay, false) && isDebugServer(); return in_array($debugReason, $debugOkay, false) && isDebugServer();
} }
function debug($msg, $debugReason = "other") function debug($msg, $debugReason = "other")
{ {
if (isDebug($debugReason)) echo "\n<!-- " . date(DATE_RFC822) . "\n $msg -->\n"; if (isDebug($debugReason)) echo "\n<!-- " . date(DATE_RFC822) . "\n $msg -->\n";
} }
function isJQueryMobileDevice() function isJQueryMobileDevice()
{ {
// http://forum.jquery.com/topic/what-is-the-best-way-to-detect-all-useragents-which-can-handle-jquery-mobile#14737000002087897 // http://forum.jquery.com/topic/what-is-the-best-way-to-detect-all-useragents-which-can-handle-jquery-mobile#14737000002087897
$user_agent = $_SERVER['HTTP_USER_AGENT']; $user_agent = $_SERVER['HTTP_USER_AGENT'];
return preg_match('/iphone/i', $user_agent) || preg_match('/android/i', $user_agent) || preg_match('/webos/i', $user_agent) || preg_match('/ios/i', $user_agent) || preg_match('/bada/i', $user_agent) || preg_match('/maemo/i', $user_agent) || preg_match('/meego/i', $user_agent) || preg_match('/fennec/i', $user_agent) || (preg_match('/symbian/i', $user_agent) && preg_match('/s60/i', $user_agent) && $browser['majorver'] >= 5) || (preg_match('/symbian/i', $user_agent) && preg_match('/platform/i', $user_agent) && $browser['majorver'] >= 3) || (preg_match('/blackberry/i', $user_agent) && $browser['majorver'] >= 5) || (preg_match('/opera mobile/i', $user_agent) && $browser['majorver'] >= 10) || (preg_match('/opera mini/i', $user_agent) && $browser['majorver'] >= 5); return preg_match('/iphone/i', $user_agent) || preg_match('/android/i', $user_agent) || preg_match('/webos/i', $user_agent) || preg_match('/ios/i', $user_agent) || preg_match('/bada/i', $user_agent) || preg_match('/maemo/i', $user_agent) || preg_match('/meego/i', $user_agent) || preg_match('/fennec/i', $user_agent) || (preg_match('/symbian/i', $user_agent) && preg_match('/s60/i', $user_agent) && $browser['majorver'] >= 5) || (preg_match('/symbian/i', $user_agent) && preg_match('/platform/i', $user_agent) && $browser['majorver'] >= 3) || (preg_match('/blackberry/i', $user_agent) && $browser['majorver'] >= 5) || (preg_match('/opera mobile/i', $user_agent) && $browser['majorver'] >= 10) || (preg_match('/opera mini/i', $user_agent) && $browser['majorver'] >= 5);
} }
function isFastDevice() function isFastDevice()
{ {
$ua = $_SERVER['HTTP_USER_AGENT']; $ua = $_SERVER['HTTP_USER_AGENT'];
$fastDevices = Array( $fastDevices = Array(
"Mozilla/5.0 (X11;", "Mozilla/5.0 (X11;",
"Mozilla/5.0 (Windows;", "Mozilla/5.0 (Windows;",
"Mozilla/5.0 (iP", "Mozilla/5.0 (iP",
"Mozilla/5.0 (Linux; U; Android", "Mozilla/5.0 (Linux; U; Android",
"Mozilla/4.0 (compatible; MSIE" "Mozilla/4.0 (compatible; MSIE"
); );
$slowDevices = Array( $slowDevices = Array(
"J2ME", "J2ME",
"MIDP", "MIDP",
"Opera/", "Opera/",
"Mozilla/2.0 (compatible;", "Mozilla/2.0 (compatible;",
"Mozilla/3.0 (compatible;" "Mozilla/3.0 (compatible;"
); );
return true; return true;
} }
function array_flatten($a, $f = array()) function array_flatten($a, $f = array())
{ {
if (!$a || !is_array($a)) return ''; if (!$a || !is_array($a)) return '';
foreach ($a as $k => $v) { foreach ($a as $k => $v) {
if (is_array($v)) $f = array_flatten($v, $f); if (is_array($v)) $f = array_flatten($v, $f);
else $f[$k] = $v; else $f[$k] = $v;
} }
return $f; return $f;
} }
function remove_spaces($string) function remove_spaces($string)
{ {
return str_replace(' ', '', $string); return str_replace(' ', '', $string);
} }
function object2array($object) function object2array($object)
{ {
if (is_object($object)) { if (is_object($object)) {
foreach ($object as $key => $value) { foreach ($object as $key => $value) {
$array[$key] = $value; $array[$key] = $value;
} }
} }
else { else {
$array = $object; $array = $object;
} }
return $array; return $array;
} }
function startsWith($haystack, $needle, $case = true) function startsWith($haystack, $needle, $case = true)
{ {
if ($case) { if ($case) {
return (strcmp(substr($haystack, 0, strlen($needle)) , $needle) === 0); return (strcmp(substr($haystack, 0, strlen($needle)) , $needle) === 0);
} }
return (strcasecmp(substr($haystack, 0, strlen($needle)) , $needle) === 0); return (strcasecmp(substr($haystack, 0, strlen($needle)) , $needle) === 0);
} }
   
function endsWith($haystack, $needle, $case = true) function endsWith($haystack, $needle, $case = true)
{ {
if ($case) { if ($case) {
return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)) , $needle) === 0); return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)) , $needle) === 0);
} }
return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)) , $needle) === 0); return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)) , $needle) === 0);
} }
function bracketsMeanNewLine($input) function bracketsMeanNewLine($input)
{ {
return str_replace(")", "</small>", str_replace("(", "<br><small>", $input)); return str_replace(")", "</small>", str_replace("(", "<br><small>", $input));
} }
function sksort(&$array, $subkey = "id", $sort_ascending = false) function sksort(&$array, $subkey = "id", $sort_ascending = false)
{ {
if (count($array)) $temp_array[key($array) ] = array_shift($array); if (count($array)) $temp_array[key($array) ] = array_shift($array);
foreach ($array as $key => $val) { foreach ($array as $key => $val) {
$offset = 0; $offset = 0;
$found = false; $found = false;
foreach ($temp_array as $tmp_key => $tmp_val) { foreach ($temp_array as $tmp_key => $tmp_val) {
if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])) { if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])) {
$temp_array = array_merge((array)array_slice($temp_array, 0, $offset) , array( $temp_array = array_merge((array)array_slice($temp_array, 0, $offset) , array(
$key => $val $key => $val
) , array_slice($temp_array, $offset)); ) , array_slice($temp_array, $offset));
$found = true; $found = true;
} }
$offset++; $offset++;
} }
if (!$found) $temp_array = array_merge($temp_array, array( if (!$found) $temp_array = array_merge($temp_array, array(
$key => $val $key => $val
)); ));
} }
if ($sort_ascending) $array = array_reverse($temp_array); if ($sort_ascending) $array = array_reverse($temp_array);
else $array = $temp_array; else $array = $temp_array;
} }
function sktimesort(&$array, $subkey = "id", $sort_ascending = false) function sktimesort(&$array, $subkey = "id", $sort_ascending = false)
{ {
if (count($array)) $temp_array[key($array) ] = array_shift($array); if (count($array)) $temp_array[key($array) ] = array_shift($array);
foreach ($array as $key => $val) { foreach ($array as $key => $val) {
$offset = 0; $offset = 0;
$found = false; $found = false;
foreach ($temp_array as $tmp_key => $tmp_val) { foreach ($temp_array as $tmp_key => $tmp_val) {
if (!$found and strtotime($val[$subkey]) > strtotime($tmp_val[$subkey])) { if (!$found and strtotime($val[$subkey]) > strtotime($tmp_val[$subkey])) {
$temp_array = array_merge((array)array_slice($temp_array, 0, $offset) , array( $temp_array = array_merge((array)array_slice($temp_array, 0, $offset) , array(
$key => $val $key => $val
) , array_slice($temp_array, $offset)); ) , array_slice($temp_array, $offset));
$found = true; $found = true;
} }
$offset++; $offset++;
} }
if (!$found) $temp_array = array_merge($temp_array, array( if (!$found) $temp_array = array_merge($temp_array, array(
$key => $val $key => $val
)); ));
} }
if ($sort_ascending && isset($temp_array)) $array = array_reverse($temp_array); if ($sort_ascending && isset($temp_array)) $array = array_reverse($temp_array);
else $array = $temp_array; else $array = $temp_array;
} }
function r_implode( $glue, $pieces ) function r_implode( $glue, $pieces )
{ {
foreach( $pieces as $r_pieces ) foreach( $pieces as $r_pieces )
{ {
if( is_array( $r_pieces ) ) if( is_array( $r_pieces ) )
{ {
$retVal[] = r_implode( $glue, $r_pieces ); $retVal[] = r_implode( $glue, $r_pieces );
} }
else else
{ {
$retVal[] = $r_pieces; $retVal[] = $r_pieces;
} }
} }
return implode( $glue, $retVal ); return implode( $glue, $retVal );
} }
?> ?>
   
<?php <?php
function getRoute($routeID) function getRoute($routeID)
{ {
global $conn; global $conn;
$query = "Select * from routes where route_id = :routeID LIMIT 1"; $query = "Select * from routes where route_id = :routeID LIMIT 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeID", $routeID); $query->bindParam(":routeID", $routeID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO::FETCH_ASSOC); return $query->fetch(PDO::FETCH_ASSOC);
} }
   
  function getRouteByFullName($routeFullName)
  {
  global $conn;
  $query = "Select * from routes where route_short_name||route_long_name = :routeFullName LIMIT 1";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":routeFullName", $routeFullName);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  return $query->fetch(PDO::FETCH_ASSOC);
  }
   
function getRoutes() function getRoutes()
{ {
global $conn; global $conn;
$query = "Select * from routes order by route_short_name;"; $query = "Select * from routes order by route_short_name;";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getRoutesByNumber($routeNumber = "") function getRoutesByNumber($routeNumber = "")
{ {
global $conn; global $conn;
if ($routeNumber != "") { if ($routeNumber != "") {
$query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id = $query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id =
routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where route_short_name = :routeNumber order by route_short_name;"; routes.route_id join stop_times on stop_times.trip_id = trips.trip_id
  where route_short_name = :routeNumber OR route_short_name LIKE :routeNumber2 order by route_short_name;";
} }
else { else {
$query = "SELECT DISTINCT route_short_name from routes order by route_short_name"; $query = "SELECT DISTINCT route_short_name from routes order by route_short_name";
} }
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
if ($routeNumber != "") { if ($routeNumber != "") {
$query->bindParam(":routeNumber", $routeNumber); $query->bindParam(":routeNumber", $routeNumber);
  $routeNumber2 = "% ".$routeNumber;
  $query->bindParam(":routeNumber2", $routeNumber2);
} }
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getRoutesByNumberSeries($routeNumberSeries = "") function getRoutesByNumberSeries($routeNumberSeries = "")
{ {
global $conn; global $conn;
if (strlen($routeNumberSeries) == 1) { if (strlen($routeNumberSeries) == 1) {
return getRoutesByNumber($routeNumberSeries); return getRoutesByNumber($routeNumberSeries);
} }
$seriesMin = substr($routeNumberSeries, 0, -1) . "0"; $seriesMin = substr($routeNumberSeries, 0, -1) . "0";
$seriesMax = substr($routeNumberSeries, 0, -1) . "9"; $seriesMax = substr($routeNumberSeries, 0, -1) . "9";
$query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id = $query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id =
routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where to_number(route_short_name, 'FM999') between :seriesMin and :seriesMax OR route_short_name LIKE :routeNumberSeries order by route_short_name;"; routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where to_number(route_short_name, 'FM999') between :seriesMin and :seriesMax OR route_short_name LIKE :routeNumberSeries order by route_short_name;";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":seriesMin", $seriesMin); $query->bindParam(":seriesMin", $seriesMin);
$query->bindParam(":seriesMax", $seriesMax); $query->bindParam(":seriesMax", $seriesMax);
$routeNumberSeries = "% ".substr($routeNumberSeries, 0, -1)."%"; $routeNumberSeries = "% ".substr($routeNumberSeries, 0, -1)."%";
$query->bindParam(":routeNumberSeries", $routeNumberSeries); $query->bindParam(":routeNumberSeries", $routeNumberSeries);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getRouteNextTrip($routeID) function getRouteNextTrip($routeID)
{ {
global $conn; global $conn;
$query = "select * from routes join trips on trips.route_id = routes.route_id $query = "select * from routes join trips on trips.route_id = routes.route_id
join stop_times on stop_times.trip_id = trips.trip_id where join stop_times on stop_times.trip_id = trips.trip_id where
arrival_time > :currentTime and routes.route_id = :routeID order by arrival_time > :currentTime and routes.route_id = :routeID order by
arrival_time limit 1"; arrival_time limit 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":currentTime", current_time()); $query->bindParam(":currentTime", current_time());
$query->bindParam(":routeID", $routeID); $query->bindParam(":routeID", $routeID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$r = $query->fetch(PDO::FETCH_ASSOC); $r = $query->fetch(PDO::FETCH_ASSOC);
   
// past last trip of the day special case // past last trip of the day special case
if (sizeof($r) < 16) { if (sizeof($r) < 16) {
$query = "select * from routes join trips on trips.route_id = routes.route_id $query = "select * from routes join trips on trips.route_id = routes.route_id
join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID order by join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID order by
arrival_time DESC limit 1"; arrival_time DESC limit 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeID", $routeID); $query->bindParam(":routeID", $routeID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$r = $query->fetch(PDO::FETCH_ASSOC); $r = $query->fetch(PDO::FETCH_ASSOC);
} }
return $r; return $r;
} }
function getTimeInterpolatedRouteAtStop($routeID, $stop_id) function getTimeInterpolatedRouteAtStop($routeID, $stop_id)
{ {
$nextTrip = getRouteNextTrip($routeID); $nextTrip = getRouteNextTrip($routeID);
if ($nextTrip['trip_id']) { if ($nextTrip['trip_id']) {
foreach (getTimeInterpolatedTrip($nextTrip['trip_id']) as $tripStop) { foreach (getTimeInterpolatedTrip($nextTrip['trip_id']) as $tripStop) {
if ($tripStop['stop_id'] == $stop_id) return $tripStop; if ($tripStop['stop_id'] == $stop_id) return $tripStop;
} }
} }
return Array(); return Array();
} }
function getRouteTrips($routeID) function getRouteTrips($routeID)
{ {
global $conn; global $conn;
$query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id $query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id
join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID and stop_sequence = '1' order by join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID and stop_sequence = '1' order by
arrival_time "; arrival_time ";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeID", $routeID); $query->bindParam(":routeID", $routeID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getRoutesByDestination($destination = "", $service_period = "") function getRoutesByDestination($destination = "", $service_period = "")
{ {
global $conn; global $conn;
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
if ($destination != "") { if ($destination != "") {
$query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id $query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id
FROM stop_times join trips on trips.trip_id = FROM stop_times join trips on trips.trip_id =
stop_times.trip_id join routes on trips.route_id = routes.route_id stop_times.trip_id join routes on trips.route_id = routes.route_id
WHERE route_long_name = :destination AND service_id=:service_period order by route_short_name"; WHERE route_long_name = :destination AND service_id=:service_period order by route_short_name";
} }
else { else {
$query = "SELECT DISTINCT route_long_name $query = "SELECT DISTINCT route_long_name
FROM stop_times join trips on trips.trip_id = FROM stop_times join trips on trips.trip_id =
stop_times.trip_id join routes on trips.route_id = routes.route_id stop_times.trip_id join routes on trips.route_id = routes.route_id
WHERE service_id= :service_period order by route_long_name"; WHERE service_id= :service_period order by route_long_name";
} }
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_period", $service_period); $query->bindParam(":service_period", $service_period);
if ($destination != "") $query->bindParam(":destination", $destination); if ($destination != "") $query->bindParam(":destination", $destination);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getRoutesBySuburb($suburb, $service_period = "") function getRoutesBySuburb($suburb, $service_period = "")
{ {
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
global $conn; global $conn;
$query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name $query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name
FROM stop_times join trips on trips.trip_id = stop_times.trip_id FROM stop_times join trips on trips.trip_id = stop_times.trip_id
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE zone_id LIKE ':suburb AND service_id=:service_period ORDER BY route_short_name"; WHERE zone_id LIKE ':suburb AND service_id=:service_period ORDER BY route_short_name";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_period", $service_period); $query->bindParam(":service_period", $service_period);
$suburb = "%" . $suburb . ";%"; $suburb = "%" . $suburb . ";%";
$query->bindParam(":suburb", $suburb); $query->bindParam(":suburb", $suburb);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getRoutesNearby($lat, $lng, $limit = "", $distance = 500) function getRoutesNearby($lat, $lng, $limit = "", $distance = 500)
{ {
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
if ($limit != "") $limitSQL = " LIMIT :limit "; if ($limit != "") $limitSQL = " LIMIT :limit ";
global $conn; global $conn;
$query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id, $query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id,
min(ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE)) as distance min(ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE)) as distance
FROM stop_times FROM stop_times
join trips on trips.trip_id = stop_times.trip_id join trips on trips.trip_id = stop_times.trip_id
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE service_id=:service_period WHERE service_id=:service_period
AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), :distance, FALSE) AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), :distance, FALSE)
group by service_id,trips.route_id,route_short_name,route_long_name group by service_id,trips.route_id,route_short_name,route_long_name
order by distance $limitSQL"; order by distance $limitSQL";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_period", $service_period); $query->bindParam(":service_period", $service_period);
$query->bindParam(":distance", $distance); $query->bindParam(":distance", $distance);
if ($limit != "") $query->bindParam(":limit", $limit); if ($limit != "") $query->bindParam(":limit", $limit);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
?> ?>
<?php <?php
function getServiceOverride() { function getServiceOverride($date="") {
global $conn; global $conn;
$query = "Select * from calendar_dates where date = :date and exception_type = '1' LIMIT 1"; $query = "Select * from calendar_dates where date = :date and exception_type = '1' LIMIT 1";
debug($query,"database"); debug($query,"database");
$query = $conn->prepare($query); // Create a prepared statement $query = $conn->prepare($query); // Create a prepared statement
$query->bindParam(":date", date("Ymd")); $query->bindParam(":date", date("Ymd",($date != "" ? $date : time())));
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO::FETCH_ASSOC); return $query->fetch(PDO::FETCH_ASSOC);
} }
?> ?>
<?php <?php
function getStop($stopID) function getStop($stopID)
{ {
global $conn; global $conn;
$query = "Select * from stops where stop_id = :stopID LIMIT 1"; $query = "Select * from stops where stop_id = :stopID LIMIT 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":stopID", $stopID); $query->bindParam(":stopID", $stopID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO::FETCH_ASSOC); return $query->fetch(PDO::FETCH_ASSOC);
} }
function getStops($timingPointsOnly = false, $firstLetter = "") function getStops($timingPointsOnly = false, $firstLetter = "", $startsWith = "")
{ {
global $conn; global $conn;
$conditions = Array(); $conditions = Array();
if ($timingPointsOnly) $conditions[] = "substr(stop_code,1,2) != 'Wj'"; if ($timingPointsOnly) $conditions[] = "substr(stop_code,1,2) != 'Wj'";
if ($firstLetter != "") $conditions[] = "substr(stop_name,1,1) = :firstLetter"; if ($firstLetter != "") $conditions[] = "substr(stop_name,1,1) = :firstLetter";
  if ($startsWith != "") $conditions[] = "stop_name like :startsWith";
$query = "Select * from stops"; $query = "Select * from stops";
if (sizeof($conditions) > 0) { if (sizeof($conditions) > 0) {
if (sizeof($conditions) > 1) { if (sizeof($conditions) > 1) {
$query.= " Where " . implode(" AND ", $conditions) . " "; $query.= " Where " . implode(" AND ", $conditions) . " ";
} }
else { else {
$query.= " Where " . $conditions[0] . " "; $query.= " Where " . $conditions[0] . " ";
} }
} }
$query.= " order by stop_name;"; $query.= " order by stop_name;";
$query = $conn->prepare($query); $query = $conn->prepare($query);
if ($firstLetter != "") $query->bindParam(":firstLetter", $firstLetter); if ($firstLetter != "") $query->bindParam(":firstLetter", $firstLetter);
   
  if ($startsWith != "") {
  $startsWith = $startsWith."%";
  $query->bindParam(":startsWith", $startsWith);
  }
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getNearbyStops($lat, $lng, $limit = "", $distance = 1000) function getNearbyStops($lat, $lng, $limit = "", $distance = 1000)
{ {
if ($lat == null || $lng == null) return Array(); if ($lat == null || $lng == null) return Array();
if ($limit != "") $limitSQL = " LIMIT :limit "; if ($limit != "") $limitSQL = " LIMIT :limit ";
global $conn; global $conn;
$query = "Select *, ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE) as distance $query = "Select *, ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE) as distance
from stops WHERE ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), :distance, FALSE) from stops WHERE ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), :distance, FALSE)
order by distance $limitSQL;"; order by distance $limitSQL;";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":distance", $distance); $query->bindParam(":distance", $distance);
$query->bindParam(":limit", $limit); $query->bindParam(":limit", $limit);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getStopsBySuburb($suburb) function getStopsBySuburb($suburb)
{ {
global $conn; global $conn;
$query = "Select * from stops where zone_id LIKE :suburb order by stop_name;"; $query = "Select * from stops where zone_id LIKE :suburb order by stop_name;";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$suburb = "%" . $suburb . ";%"; $suburb = "%" . $suburb . ";%";
$query->bindParam(":suburb", $suburb); $query->bindParam(":suburb", $suburb);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
  function getStopsByStopCode($stop_code,$startsWith = "")
  {
  global $conn;
  $query = "Select * from stops where stop_code = :stop_code OR stop_code LIKE :stop_code2";
  if ($startsWith != "") $query .= " AND stop_name like :startsWith";
   
  debug($query, "database");
  $query = $conn->prepare($query);
   
  $query->bindParam(":stop_code", $stop_code);
  $stop_code2 = $stop_code . "%";
  $query->bindParam(":stop_code2", $stop_code2);
  if ($startsWith != "") {
  $startsWith = $startsWith."%";
  $query->bindParam(":startsWith", $startsWith);
  }
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  return $query->fetchAll();
  }
function getStopRoutes($stopID, $service_period) function getStopRoutes($stopID, $service_period)
{ {
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
global $conn; global $conn;
$query = "SELECT service_id,trips.route_id,route_short_name,route_long_name $query = "SELECT service_id,trips.route_id,route_short_name,route_long_name
FROM stop_times join trips on trips.trip_id = FROM stop_times join trips on trips.trip_id =
stop_times.trip_id join routes on trips.route_id = routes.route_id WHERE stop_id = :stopID AND service_id=:service_period"; stop_times.trip_id join routes on trips.route_id = routes.route_id WHERE stop_id = :stopID AND service_id=:service_period";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_period", $service_period); $query->bindParam(":service_period", $service_period);
$query->bindParam(":stopID", $stopID); $query->bindParam(":stopID", $stopID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getStopTrips($stopID, $service_period = "", $afterTime = "") function getStopTrips($stopID, $service_period = "", $afterTime = "", $limit = "")
{ {
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
  if ($limit != "") $limitSQL = " LIMIT :limit ";
global $conn; global $conn;
if ($afterTime != "") { if ($afterTime != "") {
$query = " SELECT stop_times.trip_id,stop_times.arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name, end_times.arrival_time as end_time $query = " SELECT stop_times.trip_id,stop_times.arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name, end_times.arrival_time as end_time
FROM stop_times FROM stop_times
join trips on trips.trip_id = join trips on trips.trip_id =
stop_times.trip_id stop_times.trip_id
join routes on trips.route_id = routes.route_id , (SELECT trip_id,max(arrival_time) as arrival_time from stop_times join routes on trips.route_id = routes.route_id , (SELECT trip_id,max(arrival_time) as arrival_time from stop_times
WHERE stop_times.arrival_time IS NOT NULL group by trip_id) as end_times WHERE stop_times.arrival_time IS NOT NULL group by trip_id) as end_times
WHERE stop_times.stop_id = :stopID WHERE stop_times.stop_id = :stopID
AND stop_times.trip_id = end_times.trip_id AND stop_times.trip_id = end_times.trip_id
AND service_id=:service_period AND service_id=:service_period
AND end_times.arrival_time > :afterTime AND end_times.arrival_time > :afterTime
ORDER BY end_time"; ORDER BY end_time $limitSQL";
} }
else { else {
$query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name $query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name
FROM stop_times FROM stop_times
join trips on trips.trip_id = join trips on trips.trip_id =
stop_times.trip_id stop_times.trip_id
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
WHERE stop_times.stop_id = :stopID WHERE stop_times.stop_id = :stopID
AND service_id=:service_period AND service_id=:service_period
ORDER BY arrival_time"; ORDER BY arrival_time $limitSQL";
} }
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_period", $service_period); $query->bindParam(":service_period", $service_period);
$query->bindParam(":stopID", $stopID); $query->bindParam(":stopID", $stopID);
  if ($limit != "") $query->bindParam(":limit", $limit);
if ($afterTime != "") $query->bindParam(":afterTime", $afterTime); if ($afterTime != "") $query->bindParam(":afterTime", $afterTime);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function getStopTripsWithTimes($stopID, $time = "", $service_period = "", $time_range = "", $limit = "") function getStopTripsWithTimes($stopID, $time = "", $service_period = "", $time_range = "", $limit = "")
{ {
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
if ($time_range == "") $time_range = (24 * 60 * 60); if ($time_range == "") $time_range = (24 * 60 * 60);
if ($time == "") $time = current_time(); if ($time == "") $time = current_time();
if ($limit == "") $limit = 10; if ($limit == "") $limit = 10;
$trips = getStopTrips($stopID, $service_period, $time); $trips = getStopTrips($stopID, $service_period, $time);
$timedTrips = Array(); $timedTrips = Array();
if ($trips && sizeof($trips) > 0) { if ($trips && sizeof($trips) > 0) {
foreach ($trips as $trip) { foreach ($trips as $trip) {
if ($trip['arrival_time'] != "") { if ($trip['arrival_time'] != "") {
if (strtotime($trip['arrival_time']) > strtotime($time) and strtotime($trip['arrival_time']) < (strtotime($time) + $time_range)) { if (strtotime($trip['arrival_time']) > strtotime($time) and strtotime($trip['arrival_time']) < (strtotime($time) + $time_range)) {
$timedTrips[] = $trip; $timedTrips[] = $trip;
} }
} }
else { else {
$timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']); $timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']);
if ($timedTrip['arrival_time'] > $time and strtotime($timedTrip['arrival_time']) < (strtotime($time) + $time_range)) { if ($timedTrip['arrival_time'] > $time and strtotime($timedTrip['arrival_time']) < (strtotime($time) + $time_range)) {
$timedTrips[] = $timedTrip; $timedTrips[] = $timedTrip;
} }
} }
if (sizeof($timedTrips) > $limit) break; if (sizeof($timedTrips) > $limit) break;
} }
sktimesort($timedTrips, "arrival_time", true); sktimesort($timedTrips, "arrival_time", true);
} }
return $timedTrips; return $timedTrips;
} }
?> ?>
<?php <?php
function getTrip($tripID) function getTrip($tripID)
{ {
global $conn; global $conn;
$query = "Select * from trips $query = "Select * from trips
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
where trip_id = :tripID where trip_id = :tripID
LIMIT 1"; LIMIT 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO::FETCH_ASSOC); return $query->fetch(PDO::FETCH_ASSOC);
} }
function getTripShape($tripID) function getTripShape($tripID)
{ {
global $conn; global $conn;
$query = "SELECT ST_AsKML(ST_MakeLine(geometry(a.position))) as the_route $query = "SELECT ST_AsKML(ST_MakeLine(geometry(a.position))) as the_route
FROM (SELECT position, FROM (SELECT position,
stop_sequence, trips.trip_id stop_sequence, trips.trip_id
FROM stop_times FROM stop_times
join trips on trips.trip_id = stop_times.trip_id join trips on trips.trip_id = stop_times.trip_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE trips.trip_id = :tripID ORDER BY stop_sequence) as a group by a.trip_id"; WHERE trips.trip_id = :tripID ORDER BY stop_sequence) as a group by a.trip_id";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchColumn(0); return $query->fetchColumn(0);
} }
function getTimeInterpolatedTrip($tripID, $range = "") function getTimeInterpolatedTrip($tripID, $range = "")
{ {
global $conn; global $conn;
$query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_lat,stop_lon,stop_name,stop_code, $query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_lat,stop_lon,stop_name,stop_code,
stop_sequence,service_id,trips.route_id,route_short_name,route_long_name stop_sequence,service_id,trips.route_id,route_short_name,route_long_name
FROM stop_times FROM stop_times
join trips on trips.trip_id = stop_times.trip_id join trips on trips.trip_id = stop_times.trip_id
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE trips.trip_id = :tripID $range ORDER BY stop_sequence"; WHERE trips.trip_id = :tripID $range ORDER BY stop_sequence";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$stopTimes = $query->fetchAll(); $stopTimes = $query->fetchAll();
$cur_timepoint = Array(); $cur_timepoint = Array();
$next_timepoint = Array(); $next_timepoint = Array();
$distance_between_timepoints = 0.0; $distance_between_timepoints = 0.0;
$distance_traveled_between_timepoints = 0.0; $distance_traveled_between_timepoints = 0.0;
$rv = Array(); $rv = Array();
foreach ($stopTimes as $i => $stopTime) { foreach ($stopTimes as $i => $stopTime) {
if ($stopTime['arrival_time'] != "") { if ($stopTime['arrival_time'] != "") {
// is timepoint // is timepoint
$cur_timepoint = $stopTime; $cur_timepoint = $stopTime;
$distance_between_timepoints = 0.0; $distance_between_timepoints = 0.0;
$distance_traveled_between_timepoints = 0.0; $distance_traveled_between_timepoints = 0.0;
if ($i + 1 < sizeof($stopTimes)) { if ($i + 1 < sizeof($stopTimes)) {
$k = $i + 1; $k = $i + 1;
$distance_between_timepoints+= distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]); $distance_between_timepoints+= distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) { while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) {
$k+= 1; $k+= 1;
//echo "k".$k; //echo "k".$k;
$distance_between_timepoints+= distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]); $distance_between_timepoints+= distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
} }
$next_timepoint = $stopTimes[$k]; $next_timepoint = $stopTimes[$k];
$rv[] = $stopTime; $rv[] = $stopTime;
} }
} }
else { else {
// is untimed point // is untimed point
//echo "i".$i; //echo "i".$i;
$distance_traveled_between_timepoints+= distance($stopTimes[$i - 1]["stop_lat"], $stopTimes[$i - 1]["stop_lon"], $stopTimes[$i]["stop_lat"], $stopTimes[$i]["stop_lon"]); $distance_traveled_between_timepoints+= distance($stopTimes[$i - 1]["stop_lat"], $stopTimes[$i - 1]["stop_lon"], $stopTimes[$i]["stop_lat"], $stopTimes[$i]["stop_lon"]);
//echo "$distance_traveled_between_timepoints / $distance_between_timepoints<br>"; //echo "$distance_traveled_between_timepoints / $distance_between_timepoints<br>";
$distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints; $distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints;
if ($next_timepoint["arrival_time"] != "") { if ($next_timepoint["arrival_time"] != "") {
$total_time = strtotime($next_timepoint["arrival_time"]) - strtotime($cur_timepoint["arrival_time"]); $total_time = strtotime($next_timepoint["arrival_time"]) - strtotime($cur_timepoint["arrival_time"]);
//echo strtotime($next_timepoint["arrival_time"])." - ".strtotime($cur_timepoint["arrival_time"])."<br>"; //echo strtotime($next_timepoint["arrival_time"])." - ".strtotime($cur_timepoint["arrival_time"])."<br>";
$time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]); $time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]);
$stopTime["arrival_time"] = date("H:i:s", $time_estimate); $stopTime["arrival_time"] = date("H:i:s", $time_estimate);
} }
else { else {
$stopTime["arrival_time"] = $cur_timepoint["arrival_time"]; $stopTime["arrival_time"] = $cur_timepoint["arrival_time"];
} }
$rv[] = $stopTime; $rv[] = $stopTime;
//var_dump($rv); //var_dump($rv);
} }
} }
return $rv; return $rv;
} }
function getTripPreviousTimePoint($tripID, $stop_sequence) function getTripPreviousTimePoint($tripID, $stop_sequence)
{ {
global $conn; global $conn;
$query = " SELECT trip_id,stop_id, $query = " SELECT trip_id,stop_id,
stop_sequence stop_sequence
FROM stop_times FROM stop_times
WHERE trip_id = :tripID and stop_sequence < :stop_sequence WHERE trip_id = :tripID and stop_sequence < :stop_sequence
and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence DESC LIMIT 1"; and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence DESC LIMIT 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->bindParam(":stop_sequence", $stop_sequence); $query->bindParam(":stop_sequence", $stop_sequence);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO::FETCH_ASSOC); return $query->fetch(PDO::FETCH_ASSOC);
} }
function getTripNextTimePoint($tripID, $stop_sequence) function getTripNextTimePoint($tripID, $stop_sequence)
{ {
global $conn; global $conn;
$query = " SELECT trip_id,stop_id, $query = " SELECT trip_id,stop_id,
stop_sequence stop_sequence
FROM stop_times FROM stop_times
WHERE trip_id = :tripID and stop_sequence > :stop_sequence WHERE trip_id = :tripID and stop_sequence > :stop_sequence
and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence LIMIT 1"; and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence LIMIT 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->bindParam(":stop_sequence", $stop_sequence); $query->bindParam(":stop_sequence", $stop_sequence);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO::FETCH_ASSOC); return $query->fetch(PDO::FETCH_ASSOC);
} }
function getTimeInterpolatedTripAtStop($tripID, $stop_sequence) function getTimeInterpolatedTripAtStop($tripID, $stop_sequence)
{ {
global $conn; global $conn;
// limit interpolation to between nearest actual points. // limit interpolation to between nearest actual points.
$prevTimePoint = getTripPreviousTimePoint($tripID, $stop_sequence); $prevTimePoint = getTripPreviousTimePoint($tripID, $stop_sequence);
$nextTimePoint = getTripNextTimePoint($tripID, $stop_sequence); $nextTimePoint = getTripNextTimePoint($tripID, $stop_sequence);
$range = "AND stop_sequence >= '{$prevTimePoint['stop_sequence']}' AND stop_sequence <= '{$nextTimePoint['stop_sequence']}'"; //echo " prev {$lowestDelta['stop_sequence']} next {$nextTimePoint['stop_sequence']} ";
  $range = "";
  if ($prevTimePoint != "") $range .= " AND stop_sequence >= '{$prevTimePoint['stop_sequence']}'";
  if ($nextTimePoint != "") $range .= " AND stop_sequence <= '{$nextTimePoint['stop_sequence']}'";
foreach (getTimeInterpolatedTrip($tripID, $range) as $tripStop) { foreach (getTimeInterpolatedTrip($tripID, $range) as $tripStop) {
if ($tripStop['stop_sequence'] == $stop_sequence) return $tripStop; if ($tripStop['stop_sequence'] == $stop_sequence) return $tripStop;
} }
return Array(); return Array();
} }
function getTripStartTime($tripID) function getTripStartTime($tripID)
{ {
global $conn; global $conn;
$query = "Select * from stop_times $query = "Select * from stop_times
where trip_id = :tripID where trip_id = :tripID
AND arrival_time IS NOT NULL AND arrival_time IS NOT NULL
AND stop_sequence = '1'"; AND stop_sequence = '1'";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$r = $query->fetch(PDO::FETCH_ASSOC); $r = $query->fetch(PDO::FETCH_ASSOC);
return $r['arrival_time']; return $r['arrival_time'];
} }
function getActiveTrips($time) function getActiveTrips($time)
{ {
global $conn; global $conn;
if ($time == "") $time = current_time(); if ($time == "") $time = current_time();
$query = "Select distinct stop_times.trip_id, start_times.arrival_time as start_time, end_times.arrival_time as end_time from stop_times, (SELECT trip_id,arrival_time from stop_times WHERE stop_times.arrival_time IS NOT NULL $query = "Select distinct stop_times.trip_id, start_times.arrival_time as start_time, end_times.arrival_time as end_time from stop_times, (SELECT trip_id,arrival_time from stop_times WHERE stop_times.arrival_time IS NOT NULL
AND stop_sequence = '1') as start_times, (SELECT trip_id,max(arrival_time) as arrival_time from stop_times WHERE stop_times.arrival_time IS NOT NULL group by trip_id) as end_times AND stop_sequence = '1') as start_times, (SELECT trip_id,max(arrival_time) as arrival_time from stop_times WHERE stop_times.arrival_time IS NOT NULL group by trip_id) as end_times
WHERE start_times.trip_id = end_times.trip_id AND stop_times.trip_id = end_times.trip_id AND :time > start_times.arrival_time AND :time < end_times.arrival_time"; WHERE start_times.trip_id = end_times.trip_id AND stop_times.trip_id = end_times.trip_id AND :time > start_times.arrival_time AND :time < end_times.arrival_time";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":time", $time); $query->bindParam(":time", $time);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function viaPoints($tripID, $stop_sequence = "") function viaPoints($tripID, $stop_sequence = "")
{ {
global $conn; global $conn;
$query = "SELECT stops.stop_id, stop_name, arrival_time $query = "SELECT stops.stop_id, stop_name, arrival_time
FROM stop_times join stops on stops.stop_id = stop_times.stop_id FROM stop_times join stops on stops.stop_id = stop_times.stop_id
WHERE stop_times.trip_id = :tripID WHERE stop_times.trip_id = :tripID
" . ($stop_sequence != "" ? " AND stop_sequence > :stop_sequence " : "") . "AND substr(stop_code,1,2) != 'Wj' ORDER BY stop_sequence"; " . ($stop_sequence != "" ? " AND stop_sequence > :stop_sequence " : "") . "AND substr(stop_code,1,2) != 'Wj' ORDER BY stop_sequence";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
if ($stop_sequence != "") $query->bindParam(":stop_sequence", $stop_sequence); if ($stop_sequence != "") $query->bindParam(":stop_sequence", $stop_sequence);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
function viaPointNames($tripid, $stop_sequence = "") function viaPointNames($tripid, $stop_sequence = "")
{ {
$viaPointNames = Array(); $viaPointNames = Array();
foreach (viaPoints($tripid, $stop_sequence) as $point) { foreach (viaPoints($tripid, $stop_sequence) as $point) {
$viaPointNames[] = $point['stop_name']; $viaPointNames[] = $point['stop_name'];
} }
if (sizeof($viaPointNames) > 0) { if (sizeof($viaPointNames) > 0) {
return r_implode(", ", $viaPointNames); return r_implode(", ", $viaPointNames);
} }
else { else {
return ""; return "";
} }
} }
?> ?>
<?php <?php
function cleanString($subject) function cleanString($subject)
{ {
$subject = str_replace("&nbsp;", " ", $subject); $subject = str_replace("&nbsp;", " ", $subject);
$subject = str_replace("&", "&amp;", $subject); $subject = str_replace("&", "&amp;", $subject);
$subject = preg_replace('/[^\r\n\t\x20-\x7E\xA0-\xFF]/', '', $subject); $subject = preg_replace('/[^\r\n\t\x20-\x7E\xA0-\xFF]/', '', $subject);
$subject = str_replace(" ", " ", $subject); $subject = str_replace(" ", " ", $subject);
return trim($subject); return trim($subject);
} }
$return = Array(); $return = Array();
/*if (file_exists("mywayresponse.txt")) { /*if (file_exists("mywayresponse.txt")) {
@$fh = fopen("mywayresponse.txt", 'r'); @$fh = fopen("mywayresponse.txt", 'r');
if ($fh) { if ($fh) {
$pageHTML = fread($fh, filesize("mywayresponse.txt")); $pageHTML = fread($fh, filesize("mywayresponse.txt"));
fclose($fh); fclose($fh);
} }
}*/ }*/
//set POST variables //set POST variables
$url = 'https://www.action.act.gov.au/ARTS/use_Funcs.asp'; $url = 'https://www.action.act.gov.au/ARTS/use_Funcs.asp';
  //$url = 'http://localhost/myway.htm';
$field_mapping = Array( $field_mapping = Array(
"card_number" => "SRNO", "card_number" => "SRNO",
"DOBmonth" => "month", "DOBmonth" => "month",
"DOBday" => "day", "DOBday" => "day",
"DOByear" => "year", "DOByear" => "year",
"secret_answer" => "pwrd", "secret_answer" => "pwrd",
"button" => "Submit" "button" => "Submit"
); );
foreach (Array( foreach (Array(
"card_number", "card_number",
"DOBday", "DOBday",
"DOBmonth", "DOBmonth",
"DOByear" "DOByear"
) as $field_name) { ) as $field_name) {
if (isset($_REQUEST[$field_name])) { if (isset($_REQUEST[$field_name])) {
$fields[$field_name] = filter_var($_REQUEST[$field_name], FILTER_SANITIZE_NUMBER_INT); $fields[$field_name] = filter_var($_REQUEST[$field_name], FILTER_SANITIZE_NUMBER_INT);
} }
else { else {
$return["error"][] = $field_name. " parameter invalid or unspecified"; $return["error"][] = $field_name. " parameter invalid or unspecified";
} }
} }
if (isset($_REQUEST['secret_answer'])) { if (isset($_REQUEST['secret_answer'])) {
$fields['secret_answer'] = filter_var($_REQUEST['secret_answer'], FILTER_SANITIZE_STRING, Array( $fields['secret_answer'] = filter_var($_REQUEST['secret_answer'], FILTER_SANITIZE_STRING, Array(
FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_NO_ENCODE_QUOTES,
FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_HIGH,
FILTER_FLAG_STRIP_LOW FILTER_FLAG_STRIP_LOW
)); ));
} }
else { else {
$return["error"][] = "secret_answer parameter invalid or unspecified"; $return["error"][] = "secret_answer parameter invalid or unspecified";
} }
$fields['button'] = 'Submit'; $fields['button'] = 'Submit';
$fields_string = ""; $fields_string = "";
//url-ify the data for the POST //url-ify the data for the POST
foreach ($fields as $key => $value) { foreach ($fields as $key => $value) {
if (sizeof($value) === 0) $return['error'][] = $key . " parameter invalid or unspecified"; if (sizeof($value) === 0) $return['error'][] = $key . " parameter invalid or unspecified";
$fields_string.= $field_mapping[$key] . '=' . $value . '&'; $fields_string.= $field_mapping[$key] . '=' . $value . '&';
} }
$fields_string = rtrim($fields_string, '&'); $fields_string = rtrim($fields_string, '&');
if (!isset($return['error'])) { if (!isset($return['error'])) {
//open connection //open connection
$ch = curl_init(); $ch = curl_init();
//set the url, number of POST vars, POST data //set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "https://www.action.act.gov.au/ARTS/getbalance.asp"); curl_setopt($ch, CURLOPT_REFERER, "https://www.action.act.gov.au/ARTS/getbalance.asp");
curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//execute post //execute post
$pageHTML = curl_exec($ch); $pageHTML = curl_exec($ch);
if (curl_errno($ch)) $return["error"][] = "Network error " . curl_errno($ch) . " " . curl_error($ch) . " " . $url . $fields_string; if (curl_errno($ch)) $return["error"][] = "Network error " . curl_errno($ch) . " " . curl_error($ch) . " " . $url . $fields_string;
//close connection //close connection
curl_close($ch); curl_close($ch);
} }
   
if (!isset($return['error'])) { if (!isset($return['error'])) {
include_once ('lib/simple_html_dom.php'); include_once ('../lib/simple_html_dom.php');
//print_r($pageHTML); //print_r($pageHTML);
$page = str_get_html($pageHTML); $page = str_get_html($pageHTML);
$pageAlerts = $page->find(".smartCardAlert"); $pageAlerts = $page->find(".smartCardAlert");
if (sizeof($pageAlerts) > 0) { if (sizeof($pageAlerts) > 0) {
$return['error'][] = $pageAlerts[0]->plaintext; $return['error'][] = $pageAlerts[0]->plaintext;
} }
if (!isset($return['error'])) { if (!isset($return['error'])) {
$tableNum = 0; $tableNum = 0;
$tableName = Array( $tableName = Array(
1 => "myway_carddetails", 1 => "myway_carddetails",
2 => "myway_transactions" 2 => "myway_transactions"
); );
foreach ($page->find("table") as $table) { foreach ($page->find("table") as $table) {
$tableNum++; $tableNum++;
$tableColumns = Array(); $tableColumns = Array();
$tableColumnNum = 0; $tableColumnNum = 0;
foreach ($table->find("th") as $th) { foreach ($table->find("th") as $th) {
$tableColumns[$tableColumnNum] = cleanString($th->plaintext); $tableColumns[$tableColumnNum] = cleanString($th->plaintext);
$tableColumnNum++; $tableColumnNum++;
} }
//print_r($tableColumns); //print_r($tableColumns);
$tableRowNum = 0; $tableRowNum = 0;
foreach ($table->find("tr") as $tr) { foreach ($table->find("tr") as $tr) {
$tableColumnNum = 0; $tableColumnNum = 0;
foreach ($tr->find("td") as $td) { foreach ($tr->find("td") as $td) {
if ($tableNum == 1) $return[$tableName[$tableNum]][$tableColumns[$tableColumnNum]] = cleanString($td->plaintext); if ($tableNum == 1) {
else $return[$tableName[$tableNum]][$tableRowNum][$tableColumns[$tableColumnNum]] = cleanString($td->plaintext); // first table has card/cardholder details
  $return[$tableName[$tableNum]][$tableColumns[$tableColumnNum]] = cleanString($td->plaintext);
  } else {
  // second table has transactions
   
  if ($tableColumns[$tableColumnNum] == "TX Reference No / Type") {
  $return[$tableName[$tableNum]][$tableRowNum]["TX Reference No"] = substr(cleanString($td->plaintext), 0,6);
  $return[$tableName[$tableNum]][$tableRowNum]["TX Type"] = substr(cleanString($td->plaintext), 7);
  } else {
  $return[$tableName[$tableNum]][$tableRowNum][$tableColumns[$tableColumnNum]] = cleanString($td->plaintext);
  }
  }
//print_r($return); //print_r($return);
$tableColumnNum++; $tableColumnNum++;
} }
$tableRowNum++; $tableRowNum++;
} }
} }
} }
} }
if (sizeof($return) == 0) { if (sizeof($return) == 0) {
$return['error'][] = "No data extracted from MyWay website - API may be out of date"; $return['error'][] = "No data extracted from MyWay website - API may be out of date";
} }
   
header('Content-Type: text/javascript; charset=utf8'); header('Content-Type: text/javascript; charset=utf8');
// header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/'); // header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/');
header('Access-Control-Max-Age: 3628800'); header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
if (isset($_GET['callback'])) { if (isset($_GET['callback'])) {
$json = '(' . json_encode($return) . ');'; //must wrap in parens and end with semicolon $json = '(' . json_encode($return) . ');'; //must wrap in parens and end with semicolon
print_r($_GET['callback'] . $json); //callback is prepended for json-p print_r($_GET['callback'] . $json); //callback is prepended for json-p
} }
else echo json_encode($return); else echo json_encode($return);
?> ?>
   
  <?php
  include ('../include/common.inc.php');
  include_header("MyWay Delta Calculate", "mywayDeltaCalc");
  function abssort($a, $b)
  {
  if ($a['timeDiff'] == $b['timeDiff']) {
  return 0;
  }
  return (abs($a['timeDiff']) < abs($b['timeDiff'])) ? -1 : 1;
  }
  //collect all observation not in delta
  $query = "select * from myway_observations INNER JOIN myway_stops
  ON myway_observations.myway_stop=myway_stops.myway_stop INNER JOIN myway_routes
  ON myway_observations.myway_route=myway_routes.myway_route
  WHERE observation_id NOT IN
  (
  SELECT observation_id
  FROM myway_timingdeltas
  )";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  $uncalcdObservations = $query->fetchAll();
  //Display count
  echo "<h3>" . sizeof($uncalcdObservations) . " observations not yet processed</h2>";
  //foreach observation not in delta
  foreach ($uncalcdObservations as $obsv) {
  //var_dump($obsv);
  echo "<h3>Observation {$obsv['observation_id']}:</h1>
  <small>{$obsv['myway_stop']} @ {$obsv['time']} on {$obsv['myway_route']}</small><br>";
  if ($obsv["stop_code"] == "") {
  echo "error, stop '{$obsv['myway_stop']}' unknown";
  continue;
  }
  if ($obsv["route_full_name"] == "") {
  echo "error, route '{$obsv['myway_route']}' unknown";
  continue;
  }
  // :convert timestamp into time of day and date
  $time = date("H:i:s", strtotime($obsv['time']));
  $date = date("c", strtotime($obsv['time']));
  $timing_period = service_period(strtotime($date));
  $potentialStops = getStopsByStopCode($obsv["stop_code"], $obsv["stop_street"]);
  //:get myway_stops records
  //:search by starts with stopcode and starts with street if street is not null
  //no result, skip and display error
  if (sizeof($potentialStops) < 1) {
  echo "error, potential stops for stopcode {$obsv["stop_code"]} street {$obsv["stop_street"]} unknown";
  continue;
  }
  //print out stops
  echo "Matched stops: ";
  foreach ($potentialStops as $potentialStop) echo $potentialStop['stop_code'] . " ";
  echo "<br>";
  //:get myway_route record
  //no result, skip and display error
  //print out route
  $potentialRoute = getRouteByFullName($obsv["route_full_name"]);
  if ($potentialRoute["route_short_name"] == "") {
  echo "error, route '{$obsv["route_full_name"]}' unknown";
  continue;
  }
  echo "Matched route: {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']}<br>";
  $timeDeltas = Array();
  foreach ($potentialStops as $potentialStop) {
  $stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period);
  $foundRoute = Array();
  foreach ($stopRoutes as $stopRoute) {
  //Check if this route stops at each stop
  if ($stopRoute['route_short_name'] . $stopRoute['route_long_name'] == $obsv["route_full_name"]) {
  echo "Matching route found at {$potentialStop['stop_code']}<br>";
  $foundRoute = $stopRoute;
  //if does get tripstoptimes for this route
  $trips = getStopTrips($potentialStop['stop_id'], $timing_period, $time);
  foreach ($trips as $trip) {
  //echo $trip['route_id']." ".$stopRoute['route_id'].";";
  if ($trip['route_id'] == $stopRoute['route_id']) {
  $timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']);
  $actual_time = strtotime($time);
  $trip_time = strtotime($timedTrip['arrival_time']);
  $timeDiff = $actual_time - $trip_time;
  //work out time delta, put into array with index of delta
  $timeDeltas[] = Array(
  "timeDiff" => $timeDiff,
  "stop_code" => $potentialStop['stop_code']
  );
  echo "Found trip at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes<br>";
  }
  }
  break; // because have found route
 
  }
  }
  if (sizeof($foundRoute) < 1) {
  //print out that stops/does not stop
  echo "No matching routes found at {$potentialStop['stop_code']}<br>";
  }
  }
  // lowest delta is recorded delta
  usort($timeDeltas, "abssort");
  $lowestDelta = $timeDeltas[0]["timeDiff"];
  if (sizeof($timeDeltas) != 0) {
  echo "Lowest difference of " . round($lowestDelta / 60, 2) . " minutes will be recorded for this observation<br>";
  $observation_id = $obsv['observation_id'];
  $route_full_name = $obsv['route_full_name'];
  $myway_route = $obsv['myway_stop'];
  $stop_code = $timeDeltas[0]["stop_code"];
  $stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_full_name, myway_route, stop_code, timing_delta, time, date, timing_period)
  values (:observation_id, :route_full_name, :myway_route, :stop_code, :timing_delta, :time, :date, :timing_period)");
  $stmt->bindParam(':observation_id', $observation_id);
  $stmt->bindParam(':route_full_name', $route_full_name);
  $stmt->bindParam(':myway_route', $myway_route);
  $stmt->bindParam(':stop_code', $stop_code);
  $stmt->bindParam(':timing_delta', $lowestDelta);
  $stmt->bindParam(':time', $time);
  $stmt->bindParam(':date', $date);
  $stmt->bindParam(':timing_period', $timing_period);
  // insert a record
  $stmt->execute();
  if ($stmt->rowCount() > 0) {
  echo "Recorded.<br>";
  }
  var_dump($conn->errorInfo());
  }
  flush();
  }
 
  <?php
  include ('../include/common.inc.php');
  foreach ($_REQUEST as $key => $value) {
  if (strstr($key, "route") && !strstr($value, "Select")) {
  $myway_route = str_replace("route", "", $key);
  $route_full_name = $value;
  $query = "update myway_routes set route_full_name = :route_full_name where myway_route = :myway_route";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":myway_route", $myway_route);
  $query->bindParam(":route_full_name", $route_full_name);
  $query->execute();
  die(print_r($conn->errorInfo() , true));
  }
  if (strstr($key, "myway_stop")) {
  $myway_stop = $value;
  $stop_code = $_REQUEST['stop_code'];
  $stop_street = $_REQUEST['stop_street'];
  $query = "update myway_stops set stop_code = :stop_code, stop_street = :stop_street where myway_stop = :myway_stop";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":myway_stop", $myway_stop);
  $query->bindParam(":stop_code", $stop_code);
  $query->bindParam(":stop_street", $stop_street);
  $query->execute();
  die(print_r($conn->errorInfo() , true));
  }
  }
  include_header("MyWay Data Reconcile", "mywayTimeRec");
  // initialise
  $count = $conn->exec("insert into myway_stops
  select distinct myway_stop from myway_observations
  WHERE myway_stop NOT IN
  (
  SELECT myway_stop
  FROM myway_stops
  )");
  echo "$count new stops.<br>";
  if (!$count) {
  print_r($conn->errorInfo());
  }
  $count = $conn->exec("insert into myway_routes select distinct myway_route from myway_observations
  WHERE myway_route NOT IN
  (
  SELECT myway_route
  FROM myway_routes
  )");
  echo "$count new routes.<br>";
  if (!$count) {
  print_r($conn->errorInfo());
  }
  echo "<h2>Stops</h2>";
  /*stops
  search start of name, display map and table nuimbered, two text boxes */
  $query = "Select * from myway_stops where stop_code is NULL and stop_street is NUll;";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  foreach ($query->fetchAll() as $myway_stop) {
  echo "<h3>{$myway_stop[0]}</h3>";
  $stopNameParts = explode(" ", $myway_stop[0]);
  $markers = array();
  $stopKey = 1;
  $foundStops = getStops(false, "", $stopNameParts[0] . " " . $stopNameParts[1]);
  if (sizeof($foundStops) > 0) {
  echo "<table>";
  foreach ($foundStops as $stopResult) {
  $markers[] = array(
  $stopResult['stop_lat'],
  $stopResult['stop_lon']
  );
  echo "<tr><td>" . $stopKey++ . "</td><td>" . $stopResult['stop_name'] . "</td><td>" . $stopResult['stop_code'] . "</td></tr>";
  }
  echo '</table>';
  echo "" . staticmap($markers, 0, "icong", false) . "<br>\n";
  }
  echo '<form id="inputform' .md5($myway_stop[0]).'">
  <input type="hidden" name="myway_stop" value="' .$myway_stop[0].'">
  <div data-role="fieldcontain">
  <label for="stop_code">Stop Code</label>
  <input type="text" name="stop_code" id="stop_code" value="' . $foundStops[0]['stop_code'] . '" />
  </div>
  <div data-role="fieldcontain">
  <label for="stop_street">Stop Street </label>
  <input type="text" name="stop_street" id="stop_street" value="' . $foundStops[0]['stop_name'] . '" />
  </div> <input type="button" onclick="$.post(\'myway_timeliness_reconcile.php\', $(\'#inputform' .md5($myway_stop[0]) . '\').serialize())" value="Go!"></form>
  ';
  echo '<hr>';
  }
  echo '<h2>Routes</h2>';
  /*routes
  remove alpha char, search present dropdown*/
  $query = "Select * from myway_routes where route_full_name is NUll;";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  foreach ($query->fetchAll() as $myway_route) {
  echo "<h3>{$myway_route[0]}</h3>";
  $query = "Select * from myway_observations where myway_route = :route order by time";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":route", $myway_route[0]);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  foreach ($query->fetchAll() as $myway_obvs) {
  echo $myway_obvs['myway_stop'] . $myway_obvs['time'] . "<br>";
  }
  $searchRouteNo = preg_replace("/[A-Z]/", "", $myway_route[0]);
  echo $searchRouteNo;
  echo '<form id="inputform' . $myway_route[0] . '">
  <select name="route' . $myway_route[0] . '" onchange=\'$.post("myway_timeliness_reconcile.php", $("#inputform' . $myway_route[0] . '").serialize())\'>
  <option>Select a from/to pair...</option>';
  foreach (getRoutesByNumber($searchRouteNo) as $routeResult) {
  echo "<option value=\"{$routeResult['route_short_name']}{$routeResult['route_long_name']}\"> {$routeResult['route_short_name']}{$routeResult['route_long_name']} </option>\n";
  }
  echo "</select></form>";
  echo '<hr>';
  }
  include_footer();
  ?>
 
<?php <?php
include ('../include/common.inc.php'); include ('../include/common.inc.php');
include_header("MyWay Balance", "mywayBalance", false, false, true); include_header("MyWay Balance", "mywayBalance", false, false, true);
echo '<div data-role="page"> echo '<div data-role="page">
<div data-role="header" data-position="inline"> <div data-role="header" data-position="inline">
<a href="' . $_SERVER["HTTP_REFERER"] . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a> <a href="' . $_SERVER["HTTP_REFERER"] . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a>
<h1>MyWay Balance</h1> <h1>MyWay Balance</h1>
<a href="mywaybalance.php?logout=yes" data-icon="delete" class="ui-btn-right">Logout</a> <a href="mywaybalance.php?logout=yes" data-icon="delete" class="ui-btn-right">Logout</a>
</div><!-- /header --> </div><!-- /header -->
<a name="maincontent" id="maincontent"></a> <a name="maincontent" id="maincontent"></a>
<div data-role="content"> '; <div data-role="content"> ';
   
$return = Array(); $return = Array();
function logout() { function logout()
  {
setcookie("card_number", "", time() - 60 * 60 * 24 * 100, "/"); setcookie("card_number", "", time() - 60 * 60 * 24 * 100, "/");
setcookie("date", "", time() - 60 * 60 * 24 * 100, "/"); setcookie("date", "", time() - 60 * 60 * 24 * 100, "/");
setcookie("secret_answer", "", time() - 60 * 60 * 24 * 100, "/"); setcookie("secret_answer", "", time() - 60 * 60 * 24 * 100, "/");
  setcookie("contribute_myway", "", time() - 60 * 60 * 24 * 100, "/");
} }
function printBalance($cardNumber, $date, $pwrd) function printBalance($mywayResult)
{ {
global $return; if (isset($mywayResult['error'])) {
$return = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd") , true);  
if (isset($return['error'])) {  
logout(); logout();
echo '<h3><font color="red">' . $return['error'][0] . "</font></h3>"; echo '<h3><font color="red">' . $mywayResult['error'][0] . "</font></h3>";
} }
else { else {
echo "<h2>Balance: " . $return['myway_carddetails']['Card Balance'] . "</h2>"; echo "<h2>Balance: " . $mywayResult['myway_carddetails']['Card Balance'] . "</h2>";
echo '<ul data-role="listview" data-inset="true"><li data-role="list-divider"> Recent Transactions </li>'; echo '<ul data-role="listview" data-inset="true"><li data-role="list-divider"> Recent Transactions </li>';
$txCount=0; $txCount = 0;
foreach ($return['myway_transactions'] as $transaction) { foreach ($mywayResult['myway_transactions'] as $transaction) {
echo "<li>"; echo "<li>";
if ($transaction["Deduction Type"] == "DEFAULT") echo '<img src="css/images/warning.png" alt="Failed to tap off: " class="ui-li-icon">'; if ($transaction["Deduction Type"] == "DEFAULT") echo '<img src="css/images/warning.png" alt="Failed to tap off: " class="ui-li-icon">';
echo"<b>" . $transaction["Date / Time"] . "</b>"; echo "<b>" . $transaction["Date / Time"] . "</b>";
echo "<br><small>" .$transaction["Route"] ." at " . $transaction["Stop Name"]. "<br>". $transaction["TX Reference No / Type"] . "</small>"; echo "<br><small>" . $transaction["Route"] . " at " . $transaction["Stop Name"] . "<br>";
  echo $transaction["TX Reference No"] . " " . $transaction["TX Type"] . "</small>";
echo '<p class="ui-li-aside">' . $transaction["TX Amount"] . '</p>'; echo '<p class="ui-li-aside">' . $transaction["TX Amount"] . '</p>';
echo "</li>"; echo "</li>";
$txCount++; $txCount++;
if ($txCount > 10) break; if ($txCount > 10) break;
} }
echo "</ul>"; echo "</ul>";
  }
  }
  function recordMyWayObservations($mywayResult)
  {
  global $conn;
  if (!isset($mywayResult['error'])) {
  $stmt = $conn->prepare("insert into myway_observations (observation_id, myway_stop, time, myway_route)
  values (:observation_id, :myway_stop, :time, :myway_route)");
  $stmt->bindParam(':observation_id', $observation_hash);
  $stmt->bindParam(':myway_stop', $myway_stop);
  $stmt->bindParam(':time', $timestamp);
  $stmt->bindParam(':myway_route', $myway_route);
  // insert a record
  $resultCount = 0;
  foreach ($mywayResult['myway_transactions'] as $transaction) {
  if ($transaction["Stop Name"] != "" && $transaction["Deduction Type"] != "DEFAULT") {
  $observation_hash = md5($mywayResult['myway_carddetails']['MyWay Number'] . $transaction["TX Reference No"]);
  $timestamp = date("c", strtotime($transaction["Date / Time"]));
  $myway_stop = $transaction["Stop Name"];
  $myway_route = $transaction["Route"];
  if ($stmt->execute()) $resultCount++;
  }
  }
  echo "<h3>Thanks for participating in the study! $resultCount transactions were recorded</h3>";
} }
} }
if (isset($_REQUEST['card_number']) && isset($_REQUEST['date']) && isset($_REQUEST['secret_answer'])) { if (isset($_REQUEST['card_number']) && isset($_REQUEST['date']) && isset($_REQUEST['secret_answer'])) {
$cardNumber = $_REQUEST['card_number']; $cardNumber = $_REQUEST['card_number'];
$date = explode("/", $_REQUEST['date']); $date = explode("/", $_REQUEST['date']);
$pwrd = $_REQUEST['secret_answer']; $pwrd = $_REQUEST['secret_answer'];
if ($_REQUEST['remember'] == "on") { if ($_REQUEST['remember'] == "on") {
setcookie("card_number", $cardNumber, time() + 60 * 60 * 24 * 100, "/"); setcookie("card_number", $cardNumber, time() + 60 * 60 * 24 * 100, "/");
setcookie("date", $_REQUEST['date'], time() + 60 * 60 * 24 * 100, "/"); setcookie("date", $_REQUEST['date'], time() + 60 * 60 * 24 * 100, "/");
  setcookie("contribute_myway", $_REQUEST['contribute_myway'], time() + 60 * 60 * 24 * 100, "/");
setcookie("secret_answer", $pwrd, time() + 60 * 60 * 24 * 100, "/"); setcookie("secret_answer", $pwrd, time() + 60 * 60 * 24 * 100, "/");
} }
printBalance($cardNumber, $date, $pwrd); $mywayResult = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd") , true);
  if ($_REQUEST['contribute_myway'] == "on") recordMyWayObservations($mywayResult);
  printBalance($mywayResult);
} }
else if (isset($_REQUEST['logout'])) { else if (isset($_REQUEST['logout'])) {
echo '<center><h3> Logged out of MyWay balance </h3><a href="/index.php">Back to main menu...</a><center>'; echo '<center><h3> Logged out of MyWay balance </h3><a href="/index.php">Back to main menu...</a><center>';
} }
else if (isset($_COOKIE['card_number']) && isset($_COOKIE['date']) && isset($_COOKIE['secret_answer'])) { else if (isset($_COOKIE['card_number']) && isset($_COOKIE['date']) && isset($_COOKIE['secret_answer'])) {
$cardNumber = $_COOKIE['card_number']; $cardNumber = $_COOKIE['card_number'];
$date = explode("/", $_COOKIE['date']); $date = explode("/", $_COOKIE['date']);
$pwrd = $_COOKIE['secret_answer']; $pwrd = $_COOKIE['secret_answer'];
printBalance($cardNumber, $date, $pwrd); $mywayResult = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd") , true);
  if ($_COOKIE['contribute_myway'] == "on") recordMyWayObservations($mywayResult);
  printBalance($mywayResult);
} }
else { else {
$date = (isset($_REQUEST['date']) ? filter_var($_REQUEST['date'], FILTER_SANITIZE_STRING) : date("m/d/Y")); $date = (isset($_REQUEST['date']) ? filter_var($_REQUEST['date'], FILTER_SANITIZE_STRING) : date("m/d/Y"));
echo '<form action="" method="post"> echo '<form action="" method="post">
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="card_number">Card number</label> <label for="card_number">Card number</label>
<input type="text" name="card_number" id="card_number" value="' . $card_number . '" /> <input type="text" name="card_number" id="card_number" value="' . $card_number . '" />
</div> </div>
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="date"> Date of birth </label> <label for="date"> Date of birth </label>
<input type="text" name="date" id="date" value="' . $date . '" /> <input type="text" name="date" id="date" value="' . $date . '" />
</div> </div>
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="secret_answer"> Secret question answer </label> <label for="secret_answer"> Secret question answer </label>
<input type="text" name="secret_answer" id="secret_answer" value="' . $secret_answer . '" /> <input type="text" name="secret_answer" id="secret_answer" value="' . $secret_answer . '" />
</div> </div>
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="remember"> Remember these details? </label> <label for="remember"> Remember these details? </label>
<input type="checkbox" name="remember" id="remember" checked="yes" /> <input type="checkbox" name="remember" id="remember" checked="yes" />
</div> </div>
  <div data-role="fieldcontain">
  <label for="contribute_myway">Contribute MyWay records to timeliness study? </label>
  <input type="checkbox" name="contribute_myway" id="contribute_myway" checked="no" />
  </div>
<input type="submit" value="Go!"></form>'; <input type="submit" value="Go!"></form>';
} }
include_footer(); include_footer();
?> ?>