Convert myway timeliness calculation to new GTFS feed format
Convert myway timeliness calculation to new GTFS feed format

<?php <?php
   
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
   
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"
); );
$GTFSREnabled = true; $GTFSREnabled = true;
$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")) if (isDebug("phperror"))
error_reporting(E_ALL ^ E_NOTICE); error_reporting(E_ALL ^ E_NOTICE);
$basePath = ""; $basePath = "";
if (strstr($_SERVER['PHP_SELF'], "labs/") if (strstr($_SERVER['PHP_SELF'], "labs/")
|| strstr($_SERVER['PHP_SELF'], "myway/") || strstr($_SERVER['PHP_SELF'], "myway/")
|| strstr($_SERVER['PHP_SELF'], "lib/") || strstr($_SERVER['PHP_SELF'], "lib/")
|| strstr($_SERVER['PHP_SELF'], "geo/") || strstr($_SERVER['PHP_SELF'], "geo/")
|| strstr($_SERVER['PHP_SELF'], "include/") || strstr($_SERVER['PHP_SELF'], "include/")
|| strstr($_SERVER['PHP_SELF'], "servicealerts/")) || strstr($_SERVER['PHP_SELF'], "servicealerts/"))
$basePath = "../"; $basePath = "../";
   
function isDebugServer() { function isDebugServer() {
return php_sapi_name() == "cli" || isset($_SERVER['SERVER_NAME']) && ( $_SERVER['SERVER_NAME'] == "azusa" || $_SERVER['SERVER_NAME'] == "vanille" return php_sapi_name() == "cli" || isset($_SERVER['SERVER_NAME']) && ( $_SERVER['SERVER_NAME'] == "azusa" || $_SERVER['SERVER_NAME'] == "vanille"
|| $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1"); || $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "192.168.1.8");
} }
   
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-auth.inc.php"); include_once ("common-auth.inc.php");
include_once ("common-template.inc.php"); include_once ("common-template.inc.php");
   
function isAnalyticsOn() { function isAnalyticsOn() {
$user_agent = $_SERVER['HTTP_USER_AGENT']; $user_agent = $_SERVER['HTTP_USER_AGENT'];
return !isDebugServer() && !preg_match('/cloudkick/i', $user_agent) && !preg_match('/googlebot/i', $user_agent) && return !isDebugServer() && !preg_match('/cloudkick/i', $user_agent) && !preg_match('/googlebot/i', $user_agent) &&
!preg_match('/baidu/i', $user_agent); !preg_match('/baidu/i', $user_agent);
} }
   
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)) if (isDebug($debugReason))
echo "\n<!-- " . date(DATE_RFC822) . "\n $msg -->\n"; echo "\n<!-- " . date(DATE_RFC822) . "\n $msg -->\n";
} }
function isIOSDevice() { function isIOSDevice() {
return strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad'); return strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad');
} }
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 array_flatten($a, $f = array()) { function array_flatten($a, $f = array()) {
if (!$a || !is_array($a)) if (!$a || !is_array($a))
return ''; return '';
foreach ($a as $k => $v) { foreach ($a as $k => $v) {
if (is_array($v)) if (is_array($v))
$f = array_flatten($v, $f); $f = array_flatten($v, $f);
else else
$f[$k] = $v; $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 sksort(&$array, $subkey = "id", $sort_ascending = false) { function sksort(&$array, $subkey = "id", $sort_ascending = false) {
if (count($array)) if (count($array))
$temp_array[key($array)] = array_shift($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) if (!$found)
$temp_array = array_merge($temp_array, array( $temp_array = array_merge($temp_array, array(
$key => $val $key => $val
)); ));
} }
if ($sort_ascending) if ($sort_ascending)
$array = array_reverse($temp_array); $array = array_reverse($temp_array);
else else
$array = $temp_array; $array = $temp_array;
} }
   
function sktimesort(&$array, $subkey = "id", $sort_ascending = false) { function sktimesort(&$array, $subkey = "id", $sort_ascending = false) {
if (count($array)) if (count($array))
$temp_array[key($array)] = array_shift($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) if (!$found)
$temp_array = array_merge($temp_array, array( $temp_array = array_merge($temp_array, array(
$key => $val $key => $val
)); ));
} }
if ($sort_ascending && isset($temp_array)) if ($sort_ascending && isset($temp_array))
$array = array_reverse($temp_array); $array = array_reverse($temp_array);
else else
$array = $temp_array; $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
   
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
   
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 getRoutesByShortName($routeShortName) {
  global $conn;
  $query = "Select * from routes where route_short_name = :routeShortName";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":routeShortName", $routeShortName);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  return $query->fetchAll();
  }
function getRouteByFullName($routeFullName) { function getRouteByFullName($routeFullName) {
global $conn; global $conn;
$query = "Select * from routes where route_short_name||route_long_name = :routeFullName LIMIT 1"; $query = "Select * from routes where route_short_name||route_long_name = :routeFullName LIMIT 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeFullName", $routeFullName); $query->bindParam(":routeFullName", $routeFullName);
$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 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 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;"; 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; $routeNumber2 = "% " . $routeNumber;
$query->bindParam(":routeNumber2", $routeNumber2); $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 getRouteAtStop($routeID, $stop_id) { function getRouteAtStop($routeID, $stop_id) {
$nextTrip = getRouteNextTrip($routeID); $nextTrip = getRouteNextTrip($routeID);
if ($nextTrip['trip_id']) { if ($nextTrip['trip_id']) {
foreach (getTripStopTimes($nextTrip['trip_id']) as $tripStop) { foreach (getTripStopTimes($nextTrip['trip_id']) as $tripStop) {
if ($tripStop['stop_id'] == $stop_id) if ($tripStop['stop_id'] == $stop_id)
return $tripStop; 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 == "") if ($service_period == "")
$service_period = 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 != "") if ($destination != "")
$query->bindParam(":destination", $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 == "") if ($service_period == "")
$service_period = 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 == "") if ($service_period == "")
$service_period = service_period(); $service_period = service_period();
$service_ids = service_ids($service_period); $service_ids = service_ids($service_period);
$sidA = $service_ids[0]; $sidA = $service_ids[0];
$sidB = $service_ids[1]; $sidB = $service_ids[1];
if ($limit != "") if ($limit != "")
$limitSQL = " LIMIT :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_periodA OR service_id=:service_periodB) WHERE (service_id=:service_periodA OR service_id=:service_periodB)
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_periodA", $sidA); $query->bindParam(":service_periodA", $sidA);
$query->bindParam(":service_periodB", $sidB); $query->bindParam(":service_periodB", $sidB);
$query->bindParam(":distance", $distance); $query->bindParam(":distance", $distance);
if ($limit != "") if ($limit != "")
$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();
} }
   
?> ?>
<?php <?php
   
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
   
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($firstLetter = "", $startsWith = "") { function getStops($firstLetter = "", $startsWith = "") {
global $conn; global $conn;
$conditions = Array(); $conditions = Array();
if ($firstLetter != "") if ($firstLetter != "")
$conditions[] = "substr(stop_name,1,1) = :firstLetter"; $conditions[] = "substr(stop_name,1,1) = :firstLetter";
if ($startsWith != "") if ($startsWith != "")
$conditions[] = "stop_name like :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;";
debug($query,"database"); debug($query,"database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
if ($firstLetter != "") if ($firstLetter != "")
$query->bindParam(":firstLetter", $firstLetter); $query->bindParam(":firstLetter", $firstLetter);
   
if ($startsWith != "") { if ($startsWith != "") {
$startsWith = $startsWith . "%"; $startsWith = $startsWith . "%";
$query->bindParam(":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) if ($lat == null || $lng == null)
return Array(); return Array();
if ($limit != "") if ($limit != "")
$limitSQL = " LIMIT :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 getStopsByName($name) { function getStopsByName($name) {
global $conn; global $conn;
$query = "Select * from stops where stop_name LIKE :name;"; $query = "Select * from stops where stop_name LIKE :name;";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$name = "%" . $name . ";%"; $name = "%" . $name . ";%";
$query->bindParam(":name", $name); $query->bindParam(":name", $name);
$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 = "") { function getStopsByStopCode($stop_code, $startsWith = "") {
global $conn; global $conn;
$query = "Select * from stops where (stop_code = :stop_code OR stop_code LIKE :stop_code2)"; $query = "Select * from stops where (stop_code = :stop_code OR stop_code LIKE :stop_code2)";
if ($startsWith != "") if ($startsWith != "")
$query .= " AND stop_name like :startsWith"; $query .= " AND stop_name like :startsWith";
   
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
   
$query->bindParam(":stop_code", $stop_code); $query->bindParam(":stop_code", $stop_code);
$stop_code2 = $stop_code . "%"; $stop_code2 = $stop_code . "%";
$query->bindParam(":stop_code2", $stop_code2); $query->bindParam(":stop_code2", $stop_code2);
if ($startsWith != "") { if ($startsWith != "") {
$startsWith = $startsWith . "%"; $startsWith = $startsWith . "%";
$query->bindParam(":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 getStopRoutes($stopID, $service_period) { function getStopRoutes($stopID, $service_period) {
if ($service_period == "") if ($service_period == "") {
$service_period = service_period(); $service_period = service_period();
  }
$service_ids = service_ids($service_period); $service_ids = service_ids($service_period);
$sidA = $service_ids[0]; $sidA = $service_ids[0];
$sidB = $service_ids[1]; $sidB = $service_ids[1];
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 = 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 stop_times.trip_id join routes on trips.route_id = routes.route_id WHERE stop_id = :stopID
AND (service_id=:service_periodA OR service_id=:service_periodB)"; AND (service_id=:service_periodA OR service_id=:service_periodB)";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_periodA", $sidA); $query->bindParam(":service_periodA", $sidA);
$query->bindParam(":service_periodB", $sidB); $query->bindParam(":service_periodB", $sidB);
$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 = "", $limit = "") { function getStopTrips($stopID, $service_period = "", $afterTime = "", $limit = "") {
if ($service_period == "") if ($service_period == "") {
$service_period = service_period(); $service_period = service_period();
  }
$service_ids = service_ids($service_period); $service_ids = service_ids($service_period);
   
$sidA = $service_ids[0]; $sidA = $service_ids[0];
$sidB = $service_ids[1]; $sidB = $service_ids[1];
if ($limit != "") if ($limit != "")
$limitSQL = " LIMIT :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_periodA OR service_id=:service_periodB) AND (service_id=:service_periodA OR service_id=:service_periodB)
AND end_times.arrival_time > :afterTime AND end_times.arrival_time > :afterTime
ORDER BY end_time $limitSQL"; 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_periodA OR service_id=:service_periodB) AND (service_id=:service_periodA OR service_id=:service_periodB)
ORDER BY arrival_time $limitSQL"; ORDER BY arrival_time $limitSQL";
} }
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_periodA", $sidA); $query->bindParam(":service_periodA", $sidA);
$query->bindParam(":service_periodB", $sidB); $query->bindParam(":service_periodB", $sidB);
$query->bindParam(":stopID", $stopID); $query->bindParam(":stopID", $stopID);
if ($limit != "") if ($limit != "")
$query->bindParam(":limit", $limit); $query->bindParam(":limit", $limit);
if ($afterTime != "") if ($afterTime != "")
$query->bindParam(":afterTime", $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 == "") if ($service_period == "")
$service_period = service_period(); $service_period = service_period();
if ($time_range == "") if ($time_range == "")
$time_range = (24 * 60 * 60); $time_range = (24 * 60 * 60);
if ($time == "") if ($time == "")
$time = current_time(); $time = current_time();
if ($limit == "") if ($limit == "")
$limit = 10; $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 = getTripAtStop($trip['trip_id'], $trip['stop_sequence']); $timedTrip = getTripAtStop($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) if (sizeof($timedTrips) > $limit)
break; break;
} }
sktimesort($timedTrips, "arrival_time", true); sktimesort($timedTrips, "arrival_time", true);
} }
return $timedTrips; return $timedTrips;
} }
   
?> ?>
<?php <?php
   
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
include ('../include/common.inc.php'); include ('../include/common.inc.php');
include_header("MyWay Delta Calculate", "mywayDeltaCalc"); include_header("MyWay Delta Calculate", "mywayDeltaCalc");
flush(); flush();
ob_flush(); ob_flush();
   
function abssort($a, $b) { function abssort($a, $b) {
if ($a['timeDiff'] == $b['timeDiff']) { if ($a['timeDiff'] == $b['timeDiff']) {
return 0; return 0;
} }
return (abs($a['timeDiff']) < abs($b['timeDiff'])) ? -1 : 1; return (abs($a['timeDiff']) < abs($b['timeDiff'])) ? -1 : 1;
} }
   
//collect all observation not in delta //collect all observation not in delta
$query = "select * from myway_observations INNER JOIN myway_stops $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_stop=myway_stops.myway_stop
ON myway_observations.myway_route=myway_routes.myway_route  
WHERE observation_id NOT IN WHERE observation_id NOT IN
( (
SELECT observation_id SELECT observation_id
FROM myway_timingdeltas FROM myway_timingdeltas
)"; )";
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();
} }
$uncalcdObservations = $query->fetchAll(); $uncalcdObservations = $query->fetchAll();
//Display count //Display count
echo "<h3>" . sizeof($uncalcdObservations) . " observations not yet processed</h2>"; echo "<h3>" . sizeof($uncalcdObservations) . " observations not yet processed</h2>";
//foreach observation not in delta //foreach observation not in delta
foreach ($uncalcdObservations as $obsv) { foreach ($uncalcdObservations as $obsv) {
//var_dump($obsv); //var_dump($obsv);
echo "<h3>Observation {$obsv['observation_id']}:</h1> echo "<h3>Observation {$obsv['observation_id']}:</h1>
<small>{$obsv['myway_stop']} @ {$obsv['time']} on {$obsv['myway_route']}</small><br>"; <small>{$obsv['myway_stop']} @ {$obsv['time']} on {$obsv['myway_route']}</small><br>";
if ($obsv["stop_code"] == "") { if ($obsv["stop_id"] == "") {
echo "error, stop '{$obsv['myway_stop']}' unknown"; echo "error, stop '{$obsv['myway_stop']}' unknown";
continue;  
}  
if ($obsv["route_full_name"] == "") {  
echo "error, route '{$obsv['myway_route']}' unknown";  
continue; continue;
} }
// convert timestamp into time of day and date // convert timestamp into time of day and date
// timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html // timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html
$time = date("H:i:s", strtotime($obsv['time'])); $time = date("H:i:s", strtotime($obsv['time']));
$time_tz = date("H:i:s", strtotime($obsv['time'])) . " AESST"; $time_tz = date("H:i:s", strtotime($obsv['time'])) . " AESST";
$search_time = date("H:i:s", strtotime($obsv['time']) - (30 * 60)); // 30 minutes margin $search_time = date("H:i:s", strtotime($obsv['time']) - (30 * 60)); // 30 minutes margin
$date = date("c", strtotime($obsv['time'])); $date = date("c", strtotime($obsv['time']));
$timing_period = service_period(strtotime($date)); $timing_period = service_period(strtotime($date));
$potentialStops = getStopsByStopCode($obsv["stop_code"], $obsv["stop_street"]); $potentialStops = Array(getStop($obsv["stop_id"]));
//:get myway_stops records //:get myway_stops records
//:search by starts with stopcode and starts with street if street is not null //:search by starts with stopcode and starts with street if street is not null
//no result, skip and display error //no result, skip and display error
if (sizeof($potentialStops) < 1) { if (sizeof($potentialStops) < 1) {
echo "error, potential stops for stopcode {$obsv["stop_code"]} street {$obsv["stop_street"]} unknown"; echo "error, potential stops for stopid {$obsv["stop_id"]} unknown";
continue; continue;
} }
//print out stops //print out stops
echo "Matched stops: "; echo "Matched stops: ";
foreach ($potentialStops as $potentialStop) foreach ($potentialStops as $potentialStop) {
echo $potentialStop['stop_code'] . " "; echo $potentialStop['stop_id'] . " " . $potentialStop['stop_name'] . " ";
  }
echo "<br>"; echo "<br>";
//:get myway_route record //:get myway_route record
//no result, skip and display error //no result, skip and display error
//print out route //print out route
$potentialRoute = getRouteByFullName($obsv["route_full_name"]); $potentialRoutes = getRoutesByShortName(preg_replace("/[A-Z]/", "", $obsv["myway_route"]));
if ($potentialRoute["route_short_name"] == "") { if (sizeof($potentialRoutes) < 1) {
echo "error, route '{$obsv["route_full_name"]}' unknown"; echo "error, route '{$obsv["myway_route"]}' unknown";
continue; continue;
} }
echo "Matched route: {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']} {$timing_period}<br>";  
$timeDeltas = Array(); $timeDeltas = Array();
foreach ($potentialStops as $potentialStop) { foreach ($potentialRoutes as $potentialRoute) {
$stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period); echo "Matched route: {$potentialRoute['route_id']} {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']} {$timing_period}<br>";
$foundRoute = Array(); foreach ($potentialStops as $potentialStop) {
foreach ($stopRoutes as $stopRoute) { $stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period);
//Check if this route stops at each stop $foundRoute = Array();
if ($stopRoute['route_short_name'] . $stopRoute['route_long_name'] == $obsv["route_full_name"]) { foreach ($stopRoutes as $stopRoute) {
echo "Matching route {$stopRoute['route_id']} found at {$potentialStop['stop_code']}<br>"; //Check if this route stops at each stop
$foundRoute = $stopRoute; if ($stopRoute['route_id'] == $potentialRoute['route_id']) {
//if does get tripstoptimes for this route echo "Matching route {$stopRoute['route_id']} found at stop #{$potentialStop['stop_id']}<br>";
$trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time); $foundRoute = $stopRoute;
foreach ($trips as $trip) { //if does get tripstoptimes for this route
//echo $trip['route_id']." ".$stopRoute['route_id'].";"; $trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time);
if ($trip['route_id'] == $stopRoute['route_id']) { foreach ($trips as $trip) {
$timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']); //echo $trip['route_id']." ".$stopRoute['route_id'].";";
$actual_time = strtotime($time); if ($trip['route_id'] == $stopRoute['route_id']) {
$trip_time = strtotime($timedTrip['arrival_time']); $timedTrip = getTripAtStop($trip['trip_id'], $trip['stop_sequence']);
$timeDiff = $actual_time - $trip_time; $actual_time = strtotime($time);
//work out time delta, put into array with index of delta $trip_time = strtotime($timedTrip['arrival_time']);
$timeDeltas[] = Array( $timeDiff = $actual_time - $trip_time;
"timeDiff" => $timeDiff, //work out time delta, put into array with index of delta
"stop_code" => $potentialStop['stop_code'], $timeDeltas[] = Array(
"stop_sequence" => $timedTrip['stop_sequence'] "timeDiff" => $timeDiff,
); "stop_id" => $potentialStop['stop_id'],
echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_code']} (#{$potentialStop['stop_id']}, sequence #{$trip['stop_sequence']})<br>"; "stop_sequence" => $trip['stop_sequence'],
echo "Arriving at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes<br>"; "route_id" => $trip['route_id']
  );
  echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_id']} (#{$potentialStop['stop_name']}, sequence #{$trip['stop_sequence']})<br>";
  echo "Arriving at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes<br>";
  }
} }
  break; // because have found route
} }
break; // because have found route }
  if (sizeof($foundRoute) < 1) {
  //print out that stops/does not stop
  echo "No matching routes found at {$potentialStop['stop_id']}<br>";
  //var_dump($stopRoutes);
  flush();
} }
} }
if (sizeof($foundRoute) < 1) {  
//print out that stops/does not stop  
echo "No matching routes found at {$potentialStop['stop_code']}<br>";  
var_dump($stopRoutes);  
flush();  
}  
} }
   
// lowest delta is recorded delta // lowest delta is recorded delta
usort($timeDeltas, "abssort"); usort($timeDeltas, "abssort");
$lowestDelta = $timeDeltas[0]["timeDiff"]; $lowestDelta = $timeDeltas[0]["timeDiff"];
if (sizeof($timeDeltas) != 0) { if (sizeof($timeDeltas) != 0) {
echo "Lowest difference of " . round($lowestDelta / 60, 2) . " minutes will be recorded for this observation<br>"; echo "Lowest difference of " . round($lowestDelta / 60, 2) . " minutes will be recorded for this observation<br>";
   
$observation_id = $obsv['observation_id']; $observation_id = $obsv['observation_id'];
$route_full_name = $obsv['route_full_name']; $route_id = $timeDeltas[0]["route_id"];
$stop_code = $timeDeltas[0]["stop_code"]; $stop_id = $timeDeltas[0]["stop_id"];
$stop_sequence = $timeDeltas[0]["stop_sequence"]; $stop_sequence = $timeDeltas[0]["stop_sequence"];
$stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_full_name, stop_code, timing_delta, time, date, timing_period, stop_sequence) $stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_id, stop_id, timing_delta, time, date, timing_period, stop_sequence)
values (:observation_id, :route_full_name, :stop_code, :timing_delta, :time, :date, :timing_period, :stop_sequence)"); values (:observation_id, :route_id, :stop_id, :timing_delta, :time, :date, :timing_period, :stop_sequence)");
$stmt->bindParam(':observation_id', $observation_id); $stmt->bindParam(':observation_id', $observation_id);
$stmt->bindParam(':route_full_name', $route_full_name); $stmt->bindParam(':route_id', $route_id);
$stmt->bindParam(':stop_code', $stop_code); $stmt->bindParam(':stop_id', $stop_id);
$stmt->bindParam(':timing_delta', $lowestDelta); $stmt->bindParam(':timing_delta', $lowestDelta);
$stmt->bindParam(':time', $time_tz); $stmt->bindParam(':time', $time_tz);
$stmt->bindParam(':date', $date); $stmt->bindParam(':date', $date);
$stmt->bindParam(':timing_period', $timing_period); $stmt->bindParam(':timing_period', $timing_period);
$stmt->bindParam(':stop_sequence', $stop_sequence); $stmt->bindParam(':stop_sequence', $stop_sequence);
// insert a record // insert a record
$stmt->execute(); $stmt->execute();
if ($stmt->rowCount() > 0) { if ($stmt->rowCount() > 0) {
echo "Recorded.<br>"; echo "Recorded.<br>";
} }
var_dump($conn->errorInfo()); var_dump($conn->errorInfo());
flush(); flush();
} }
flush(); flush();
} }
   
<?php <?php
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
include ('../include/common.inc.php'); include ('../include/common.inc.php');
auth(); auth();
foreach ($_REQUEST as $key => $value) { foreach ($_REQUEST as $key => $value) {
if (strstr($key, "route") && !strstr($value, "Select")) { if (strstr($key, "route") && !strstr($value, "Select")) {
$myway_route = str_replace("route", "", $key); $myway_route = str_replace("route", "", $key);
$route_full_name = $value; $route_id = $value;
$query = "update myway_routes set route_full_name = :route_full_name where myway_route = :myway_route"; $query = "update myway_routes set route_id = :route_id where myway_route = :myway_route";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":myway_route", $myway_route, PDO::PARAM_STR, 5); $query->bindParam(":myway_route", $myway_route, PDO::PARAM_STR, 5);
$query->bindParam(":route_full_name", $route_full_name, PDO::PARAM_STR, 42); $query->bindParam(":route_id", $route_id, PDO::PARAM_STR, 42);
$query->execute(); $query->execute();
die(print_r($conn->errorInfo(), true)); die(print_r($conn->errorInfo(), true));
} }
if (strstr($key, "myway_stop")) { if (strstr($key, "myway_stop")) {
$myway_stop = $value; $myway_stop = $value;
$stop_code = $_REQUEST['stop_code']; $stop_id = $_REQUEST['stop_id'];
$stop_street = $_REQUEST['stop_street']; $query = "update myway_stops set stop_id = :stop_id where myway_stop = :myway_stop";
$query = "update myway_stops set stop_code = :stop_code, stop_street = :stop_street where myway_stop = :myway_stop";  
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":myway_stop", $myway_stop, PDO::PARAM_STR, 25); $query->bindParam(":myway_stop", $myway_stop, PDO::PARAM_STR, 25);
$query->bindParam(":stop_code", $stop_code, PDO::PARAM_STR, 32); $query->bindParam(":stop_id", $stop_id, PDO::PARAM_STR, 32);
$query->bindParam(":stop_street", $stop_street);  
$query->execute(); $query->execute();
die(print_r($conn->errorInfo(), true)); die(print_r($conn->errorInfo(), true));
} }
} }
include_header("MyWay Data Reconcile", "mywayTimeRec"); include_header("MyWay Data Reconcile", "mywayTimeRec");
// initialise // initialise
$count = $conn->exec("insert into myway_stops $count = $conn->exec("insert into myway_stops
select distinct myway_stop from myway_observations select distinct myway_stop from myway_observations
WHERE myway_stop NOT IN WHERE myway_stop NOT IN
( (
SELECT myway_stop SELECT myway_stop
FROM myway_stops FROM myway_stops
)"); )");
echo "$count new stops.<br>"; echo "$count new stops.<br>";
if (!$count) { if (!$count) {
print_r($conn->errorInfo()); print_r($conn->errorInfo());
} }
$count = $conn->exec("insert into myway_routes select distinct myway_route from myway_observations $count = $conn->exec("insert into myway_routes select distinct myway_route from myway_observations
WHERE myway_route NOT IN WHERE myway_route NOT IN
( (
SELECT myway_route SELECT myway_route
FROM myway_routes FROM myway_routes
)"); )");
echo "$count new routes.<br>"; echo "$count new routes.<br>";
if (!$count) { if (!$count) {
print_r($conn->errorInfo()); print_r($conn->errorInfo());
} }
echo "<h2>Stops</h2>"; echo "<h2>Stops</h2>";
/* stops /* stops
search start of name, display map and table nuimbered, two text boxes */ 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;"; $query = "Select * from myway_stops where stop_id is NUll;";
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();
} }
foreach ($query->fetchAll() as $myway_stop) { foreach ($query->fetchAll() as $myway_stop) {
echo "<h3>{$myway_stop[0]}</h3>"; echo "<h3>{$myway_stop[0]}</h3>";
$stopNameParts = explode(" ", $myway_stop[0]);  
$markers = array(); $markers = array();
$stopKey = 0; $stopKey = 0;
$foundStops = getStops(false, "", $stopNameParts[0] . " " . $stopNameParts[1]); $foundStops = getStops("",$myway_stop[0]);
if (sizeof($foundStops) > 0) { if (sizeof($foundStops) > 0) {
echo "<table>"; echo "<table>";
foreach ($foundStops as $stopResult) { foreach ($foundStops as $stopResult) {
$markers[] = array( $markers[] = array(
$stopResult['stop_lat'], $stopResult['stop_lat'],
$stopResult['stop_lon'] $stopResult['stop_lon']
); );
echo "<tr><td>" . $stopKey++ . "</td><td>" . $stopResult['stop_name'] . "</td><td>" . $stopResult['stop_code'] . "</td></tr>"; echo "<tr><td>" . $stopKey++ . "</td><td>" . $stopResult['stop_name'] . "</td><td>" . $stopResult['stop_id'] . "</td></tr>";
} }
echo '</table>'; echo '</table>';
echo "" . staticmap($markers,false,false,false,true) . "<br>\n"; echo "" . staticmap($markers,false,false,false,true) . "<br>\n";
} }
echo '<form id="inputform' . md5($myway_stop[0]) . '"> echo '<form id="inputform' . md5($myway_stop[0]) . '">
<input type="hidden" name="myway_stop" value="' . $myway_stop[0] . '"> <input type="hidden" name="myway_stop" value="' . $myway_stop[0] . '">
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="stop_code">Stop Code</label> <label for="stop_id">Stop ID</label>
<input type="text" name="stop_code" id="stop_code" value="' . $foundStops[0]['stop_code'] . '" /> <input type="text" name="stop_id" id="stop_id" value="' . $foundStops[0]['stop_id'] . '" />
</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> </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>'; echo '<hr>';
} }
include_footer(); include_footer();
?> ?>