shared_writable_dirs: | |
- /labs/tiles | |
- /lib/staticmaplite/cache | |
php_extensions: [pgsql, pdo, pdo_pgsql, curl] | |
<?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 = ""; | $labsPath = ""; |
if (strstr($_SERVER['PHP_SELF'],"labs")) $labsPath = "../"; | if (strstr($_SERVER['PHP_SELF'],"labs")) $labsPath = "../"; |
function isDebugServer() | function isDebugServer() |
{ | { |
return !isset($_SERVER['SERVER_NAME']) || $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "10.1.0.4" || $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1" ; | return php_sapi_name() == "cli" || isset($_SERVER['SERVER_NAME']) && ( $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "10.1.0.4" || $_SERVER['SERVER_NAME'] == |
"localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1") ; | |
} | } |
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 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 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); |
//echo " prev {$lowestDelta['stop_sequence']} next {$nextTimePoint['stop_sequence']} "; | //echo " prev {$lowestDelta['stop_sequence']} next {$nextTimePoint['stop_sequence']} "; |
$range = ""; | $range = ""; |
if ($prevTimePoint != "") $range .= " AND stop_sequence >= '{$prevTimePoint['stop_sequence']}'"; | if ($prevTimePoint != "") $range .= " AND stop_sequence >= '{$prevTimePoint['stop_sequence']}'"; |
if ($nextTimePoint != "") $range .= " AND stop_sequence <= '{$nextTimePoint['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 getTripEndTime($tripID) | |
{ | |
global $conn; | |
$query = "SELECT trip_id,max(arrival_time) as arrival_time from stop_times | |
WHERE stop_times.arrival_time IS NOT NULL and trip_id = :tripID group by trip_id"; | |
debug($query, "database"); | |
$query = $conn->prepare($query); | |
$query->bindParam(":tripID", $tripID); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
$r = $query->fetch(PDO::FETCH_ASSOC); | |
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 |
include ('../include/common.inc.php'); | include ('../include/common.inc.php'); |
include_header("MyWay Delta Calculate", "mywayDeltaCalc"); | include_header("MyWay Delta Calculate", "mywayDeltaCalc"); |
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 INNER JOIN myway_routes |
ON myway_observations.myway_route=myway_routes.myway_route | 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_code"] == "") { |
echo "error, stop '{$obsv['myway_stop']}' unknown"; | echo "error, stop '{$obsv['myway_stop']}' unknown"; |
continue; | continue; |
} | } |
if ($obsv["route_full_name"] == "") { | if ($obsv["route_full_name"] == "") { |
echo "error, route '{$obsv['myway_route']}' unknown"; | 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 | |
$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"; | |
$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 = getStopsByStopCode($obsv["stop_code"], $obsv["stop_street"]); |
//: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 stopcode {$obsv["stop_code"]} street {$obsv["stop_street"]} unknown"; |
continue; | continue; |
} | } |
//print out stops | //print out stops |
echo "Matched stops: "; | echo "Matched stops: "; |
foreach ($potentialStops as $potentialStop) echo $potentialStop['stop_code'] . " "; | foreach ($potentialStops as $potentialStop) echo $potentialStop['stop_code'] . " "; |
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"]); | $potentialRoute = getRouteByFullName($obsv["route_full_name"]); |
if ($potentialRoute["route_short_name"] == "") { | if ($potentialRoute["route_short_name"] == "") { |
echo "error, route '{$obsv["route_full_name"]}' unknown"; | echo "error, route '{$obsv["route_full_name"]}' unknown"; |
continue; | continue; |
} | } |
echo "Matched route: {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']} {$timing_period}<br>"; | echo "Matched route: {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']} {$timing_period}<br>"; |
$timeDeltas = Array(); | $timeDeltas = Array(); |
foreach ($potentialStops as $potentialStop) { | foreach ($potentialStops as $potentialStop) { |
$stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period); | $stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period); |
$foundRoute = Array(); | $foundRoute = Array(); |
foreach ($stopRoutes as $stopRoute) { | foreach ($stopRoutes as $stopRoute) { |
//Check if this route stops at each stop | //Check if this route stops at each stop |
if ($stopRoute['route_short_name'] . $stopRoute['route_long_name'] == $obsv["route_full_name"]) { | if ($stopRoute['route_short_name'] . $stopRoute['route_long_name'] == $obsv["route_full_name"]) { |
echo "Matching route {$stopRoute['route_id']} found at {$potentialStop['stop_code']}<br>"; | echo "Matching route {$stopRoute['route_id']} found at {$potentialStop['stop_code']}<br>"; |
$foundRoute = $stopRoute; | $foundRoute = $stopRoute; |
//if does get tripstoptimes for this route | //if does get tripstoptimes for this route |
$trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time); | $trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time); |
foreach ($trips as $trip) { | foreach ($trips as $trip) { |
//echo $trip['route_id']." ".$stopRoute['route_id'].";"; | //echo $trip['route_id']." ".$stopRoute['route_id'].";"; |
if ($trip['route_id'] == $stopRoute['route_id']) { | if ($trip['route_id'] == $stopRoute['route_id']) { |
$timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']); | $timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']); |
$actual_time = strtotime($time); | $actual_time = strtotime($time); |
$trip_time = strtotime($timedTrip['arrival_time']); | $trip_time = strtotime($timedTrip['arrival_time']); |
$timeDiff = $actual_time - $trip_time; | $timeDiff = $actual_time - $trip_time; |
//work out time delta, put into array with index of delta | //work out time delta, put into array with index of delta |
$timeDeltas[] = Array( | $timeDeltas[] = Array( |
"timeDiff" => $timeDiff, | "timeDiff" => $timeDiff, |
"stop_code" => $potentialStop['stop_code'], | "stop_code" => $potentialStop['stop_code'], |
"stop_sequence" => $timedTrip['stop_sequence'] | "stop_sequence" => $timedTrip['stop_sequence'] |
); | ); |
echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_code']} (#{$potentialStop['stop_id']}, sequence #{$trip['stop_sequence']})<br>"; | echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_code']} (#{$potentialStop['stop_id']}, sequence #{$trip['stop_sequence']})<br>"; |
echo "Arriving at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes<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) { | if (sizeof($foundRoute) < 1) { |
//print out that stops/does not stop | //print out that stops/does not stop |
echo "No matching routes found at {$potentialStop['stop_code']}<br>"; | echo "No matching routes found at {$potentialStop['stop_code']}<br>"; |
var_dump($stopRoutes); | 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_full_name = $obsv['route_full_name']; |
$stop_code = $timeDeltas[0]["stop_code"]; | $stop_code = $timeDeltas[0]["stop_code"]; |
$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_full_name, stop_code, 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_full_name, :stop_code, :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_full_name', $route_full_name); |
$stmt->bindParam(':stop_code', $stop_code); | $stmt->bindParam(':stop_code', $stop_code); |
$stmt->bindParam(':timing_delta', $lowestDelta); | $stmt->bindParam(':timing_delta', $lowestDelta); |
$stmt->bindParam(':time', $time); | $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(); |
} | } |
<?php | <?php |
include ('../include/common.inc.php'); | include ('../include/common.inc.php'); |
include_header("MyWay Deltas", "mywayDelta"); | include_header("MyWay Deltas", "mywayDelta"); |
?> | ?> |
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../js/flot/excanvas.min.js"></script><![endif]--> | <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../js/flot/excanvas.min.js"></script><![endif]--> |
<script language="javascript" type="text/javascript" src="../js/flot/jquery.flot.js"></script> | <script language="javascript" type="text/javascript" src="../js/flot/jquery.flot.js"></script> |
<form method="get" action=""> | <form method="get" action=""> |
<select id="routeid" name="routeid"> | <select id="routeid" name="routeid"> |
<?php | <?php |
$query = "select distinct route_full_name from myway_routes where myway_route != '' order by route_full_name"; | $query = "select distinct route_full_name from myway_routes where myway_route != '' order by route_full_name"; |
$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 $route) { | foreach ($query->fetchAll() as $route) { |
echo "<option value=\"{$route['route_full_name']}\">{$route['route_full_name']}</option>"; | echo "<option value=\"{$route['route_full_name']}\">{$route['route_full_name']}</option>"; |
}; | }; |
?> </select> | ?> </select> |
<center><div id="placeholder" style="width:900px;height:550px"></div></center> | <center><div id="placeholder" style="width:900px;height:550px"></div></center> |
<script type="text/javascript"> | <script type="text/javascript"> |
$(function () { | $(function () { |
var placeholder = $("#placeholder"); | var placeholder = $("#placeholder"); |
var data = []; | var data = []; |
var options = { | var options = { |
xaxis: { | xaxis: { |
}, | }, |
yaxis: { | yaxis: { |
tickFormatter: yformatter | tickFormatter: yformatter |
}, | }, |
grid: { hoverable: true, clickable: true, labelMargin: 32 }, | grid: { hoverable: true, clickable: true, labelMargin: 32 }, |
series: { | |
lines: { show: false }, | |
points: { show: true } | |
} | |
}; | }; |
var plot = $.plot(placeholder, data, options); | var plot = $.plot(placeholder, data, options); |
// fetch one series, adding to what we got | // fetch one series, adding to what we got |
var alreadyFetched = {}; | var alreadyFetched = {}; |
$("#routeid").change(function () { | $("#routeid").change(function () { |
var select = $(this); | var select = $(this); |
// find the URL in the link right next to us | // find the URL in the link right next to us |
// var dataurl = button.siblings('a').attr('href'); | // var dataurl = button.siblings('a').attr('href'); |
var dataurl = "myway_timeliness_route.json.php?routeid=" + select.val(); | var dataurl = "myway_timeliness_route.json.php?routeid=" + select.val(); |
// then fetch the data with jQuery | // then fetch the data with jQuery |
function onDataReceived(series) { | function onDataReceived(series) { |
// extract the first coordinate pair so you can see that | // extract the first coordinate pair so you can see that |
// data is now an ordinary Javascript object | // data is now an ordinary Javascript object |
var firstcoordinate = '(' + series.data[0][0] + ', ' + series.data[0][1] + ')'; | var firstcoordinate = '(' + series.data[0][0] + ', ' + series.data[0][1] + ')'; |
// let's add it to our current data | // let's add it to our current data |
if (!alreadyFetched[series.label]) { | if (!alreadyFetched[series.label]) { |
alreadyFetched[series.label] = true; | alreadyFetched[series.label] = true; |
data.push(series); | data.push(series); |
} | } |
// and plot all we got | // and plot all we got |
$.plot(placeholder, data, options); | $.plot(placeholder, data, options); |
} | } |
$.ajax({ | $.ajax({ |
url: dataurl, | url: dataurl, |
method: 'GET', | method: 'GET', |
dataType: 'json', | dataType: 'json', |
success: onDataReceived | success: onDataReceived |
}); | }); |
}); | }); |
}); | }); |
function yformatter(v) { | function yformatter(v) { |
if (Math.floor(v/60) < -9) return ""; | if (Math.floor(v/60) < -9) return ""; |
return Math.abs(Math.floor(v/60)) + " min " + (v == 0 ? "" : (v >0 ? "early":"late")) | return Math.abs(Math.floor(v/60)) + " min " + (v == 0 ? "" : (v >0 ? "early":"late")) |
} | } |
function showTooltip(x, y, contents) { | function showTooltip(x, y, contents) { |
$('<div id="tooltip">' + contents + '</div>').css( { | $('<div id="tooltip">' + contents + '</div>').css( { |
position: 'absolute', | position: 'absolute', |
display: 'none', | display: 'none', |
top: y + 5, | top: y + 5, |
left: x + 5, | left: x + 5, |
border: '1px solid #fdd', | border: '1px solid #fdd', |
padding: '2px', | padding: '2px', |
'background-color': '#fee', | 'background-color': '#fee', |
opacity: 0.80 | opacity: 0.80 |
}).appendTo("body").fadeIn(200); | }).appendTo("body").fadeIn(200); |
} | } |
var previousPoint = null; | var previousPoint = null; |
$("#placeholder").bind("plothover", function (event, pos, item) { | $("#placeholder").bind("plothover", function (event, pos, item) { |
$("#x").text(pos.x.toFixed(2)); | $("#x").text(pos.x.toFixed(2)); |
$("#y").text(pos.y.toFixed(2)); | $("#y").text(pos.y.toFixed(2)); |
if (item) { | if (item) { |
if (previousPoint != item.dataIndex) { | if (previousPoint != item.dataIndex) { |
previousPoint = item.dataIndex; | previousPoint = item.dataIndex; |
$("#tooltip").remove(); | $("#tooltip").remove(); |
var x = item.datapoint[0], | var x = item.datapoint[0], |
y = item.datapoint[1].toFixed(2); | y = item.datapoint[1].toFixed(2); |
showTooltip(item.pageX, item.pageY, | showTooltip(item.pageX, item.pageY, |
item.series.label + " at stop_sequence "+ x +" = " + Math.abs(new Number(y/60).toFixed(2))+" minutes "+(y >0 ? "early":"late")); | item.series.label + " at stop_sequence "+ x +" = " + Math.abs(new Number(y/60).toFixed(2))+" minutes "+(y >0 ? "early":"late")); |
} | } |
} | } |
else { | else { |
$("#tooltip").remove(); | $("#tooltip").remove(); |
previousPoint = null; | previousPoint = null; |
} | } |
}); | }); |
</script> | </script> |
<?php | <?php |
include ('../include/common.inc.php'); | include ('../include/common.inc.php'); |
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'); |
?> | ?> |
{ | { |
"label": "<?php echo $_REQUEST['stopid']; ?>", | "label": "<?php echo $_REQUEST['stopid']; ?>", |
"data": <?php | "data": <?php |
$query = "select * from myway_timingdeltas INNER JOIN myway_observations | $query = "select * from myway_timingdeltas INNER JOIN myway_observations |
ON myway_observations.observation_id=myway_timingdeltas.observation_id | ON myway_observations.observation_id=myway_timingdeltas.observation_id |
where myway_stop = :myway_stop | where myway_stop = :myway_stop |
AND abs(timing_delta) < 2*(select stddev(timing_delta) from myway_timingdeltas) | AND abs(timing_delta) < 2*(select stddev(timing_delta) from myway_timingdeltas) |
order by myway_timingdeltas.time;"; | order by myway_timingdeltas.time;"; |
$query = $conn->prepare($query); | $query = $conn->prepare($query); |
$query->bindParam(':myway_stop', $_REQUEST['stopid'],PDO::PARAM_STR, 42); | $query->bindParam(':myway_stop', $_REQUEST['stopid'],PDO::PARAM_STR, 42); |
$query->execute(); | $query->execute(); |
if (!$query) { | if (!$query) { |
databaseError($conn->errorInfo()); | databaseError($conn->errorInfo()); |
return Array(); | return Array(); |
} | } |
foreach ($query->fetchAll() as $delta) { | foreach ($query->fetchAll() as $delta) { |
$points[] = "[".((strtotime("00:00Z") + midnight_seconds(strtotime($delta['time'])))*1000).", {$delta['timing_delta']}]"; | $points[] = "[".((strtotime("00:00Z") + midnight_seconds(strtotime($delta['time'])))*1000).", {$delta['timing_delta']}]"; |
}; | }; |
if (count($points) == 0) { | if (count($points) == 0) { |
echo "[]"; } | echo "[]"; } |
else echo "[".implode(",",$points)."]"; | else echo "[".implode(",",$points)."]"; |
?> | ?> |
} | } |
<?php | <?php |
include ('../include/common.inc.php'); | include ('../include/common.inc.php'); |
include_header("MyWay Deltas", "mywayDelta"); | include_header("MyWay Deltas", "mywayDelta"); |
?> | ?> |
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../js/flot/excanvas.min.js"></script><![endif]--> | <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../js/flot/excanvas.min.js"></script><![endif]--> |
<script language="javascript" type="text/javascript" src="../js/flot/jquery.flot.js"></script> | <script language="javascript" type="text/javascript" src="../js/flot/jquery.flot.js"></script> |
<form method="get" action=""> | <form method="get" action=""> |
<select id="stopid" name="stopid"> | <select id="stopid" name="stopid"> |
<?php | <?php |
$query = "select distinct myway_stop from myway_stops where myway_stop != '' order by myway_stop"; | $query = "select distinct myway_stop from myway_stops where myway_stop != '' order by myway_stop"; |
$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 $stop) { | foreach ($query->fetchAll() as $stop) { |
echo "<option value=\"{$stop['myway_stop']}\">{$stop['myway_stop']}</option>"; | echo "<option value=\"{$stop['myway_stop']}\">{$stop['myway_stop']}</option>"; |
}; | }; |
?> </select> <center><div id="placeholder" style="width:900px;height:550px"></div></center> | ?> </select> <center><div id="placeholder" style="width:900px;height:550px"></div></center> |
<script type="text/javascript"> | <script type="text/javascript"> |
$(function () { | $(function () { |
var d = new Date(); | var d = new Date(); |
d.setUTCMinutes(0); | d.setUTCMinutes(0); |
d.setUTCHours(0); | d.setUTCHours(0); |
var midnight = d.getTime(); | var midnight = d.getTime(); |
var placeholder = $("#placeholder"); | var placeholder = $("#placeholder"); |
var data = []; | var data = []; |
var options = { | var options = { |
xaxis: { | xaxis: { |
mode: "time", | mode: "time", |
min: midnight + (1000*60*60*8), | min: midnight + (1000*60*60*8), |
max: midnight + (1000*60*60*23.5) | max: midnight + (1000*60*60*23.5) |
}, | }, |
yaxis: { | yaxis: { |
tickFormatter: yformatter | tickFormatter: yformatter |
}, | }, |
grid: { hoverable: true, clickable: true, labelMargin: 32 }, | grid: { hoverable: true, clickable: true, labelMargin: 32 }, |
series: { | |
lines: { show: false }, | |
points: { show: true } | |
} | |
}; | }; |
var plot = $.plot(placeholder, data, options); | var plot = $.plot(placeholder, data, options); |
var o; | var o; |
o = plot.pointOffset({ x: midnight+ (9*60*60*1000), y: -1.2}); | o = plot.pointOffset({ x: midnight+ (9*60*60*1000), y: -1.2}); |
placeholder.append('<div style="position:absolute;left:' + (o.left + 4) + 'px;top:' + o.top + 'px;color:#666;font-size:smaller">9am</div>'); | placeholder.append('<div style="position:absolute;left:' + (o.left + 4) + 'px;top:' + o.top + 'px;color:#666;font-size:smaller">9am</div>'); |
o = plot.pointOffset({ x: midnight+ (16*60*60*1000), y: -1.2}); | o = plot.pointOffset({ x: midnight+ (16*60*60*1000), y: -1.2}); |
placeholder.append('<div style="position:absolute;left:' + (o.left + 4) + 'px;top:' + o.top + 'px;color:#666;font-size:smaller">4pm</div>'); | placeholder.append('<div style="position:absolute;left:' + (o.left + 4) + 'px;top:' + o.top + 'px;color:#666;font-size:smaller">4pm</div>'); |
// fetch one series, adding to what we got | // fetch one series, adding to what we got |
var alreadyFetched = {}; | var alreadyFetched = {}; |
$("#stopid").change(function () { | $("#stopid").change(function () { |
var select = $(this); | var select = $(this); |
// find the URL in the link right next to us | // find the URL in the link right next to us |
// var dataurl = button.siblings('a').attr('href'); | // var dataurl = button.siblings('a').attr('href'); |
var dataurl = "myway_timeliness_stop.json.php?stopid=" + select.val(); | var dataurl = "myway_timeliness_stop.json.php?stopid=" + select.val(); |
// then fetch the data with jQuery | // then fetch the data with jQuery |
function onDataReceived(series) { | function onDataReceived(series) { |
// extract the first coordinate pair so you can see that | // extract the first coordinate pair so you can see that |
// data is now an ordinary Javascript object | // data is now an ordinary Javascript object |
var firstcoordinate = '(' + series.data[0][0] + ', ' + series.data[0][1] + ')'; | var firstcoordinate = '(' + series.data[0][0] + ', ' + series.data[0][1] + ')'; |
// let's add it to our current data | // let's add it to our current data |
if (!alreadyFetched[series.label]) { | if (!alreadyFetched[series.label]) { |
alreadyFetched[series.label] = true; | alreadyFetched[series.label] = true; |
data.push(series); | data.push(series); |
} | } |
// and plot all we got | // and plot all we got |
$.plot(placeholder, data, options); | $.plot(placeholder, data, options); |
} | } |
$.ajax({ | $.ajax({ |
url: dataurl, | url: dataurl, |
method: 'GET', | method: 'GET', |
dataType: 'json', | dataType: 'json', |
success: onDataReceived | success: onDataReceived |
}); | }); |
}); | }); |
}); | }); |
function yformatter(v) { | function yformatter(v) { |
if (Math.floor(v/60) < -9) return ""; | if (Math.floor(v/60) < -9) return ""; |
return Math.abs(Math.floor(v/60)) + " min " + (v == 0 ? "" : (v >0 ? "early":"late")) | return Math.abs(Math.floor(v/60)) + " min " + (v == 0 ? "" : (v >0 ? "early":"late")) |
} | } |
function showTooltip(x, y, contents) { | function showTooltip(x, y, contents) { |
$('<div id="tooltip">' + contents + '</div>').css( { | $('<div id="tooltip">' + contents + '</div>').css( { |
position: 'absolute', | position: 'absolute', |
display: 'none', | display: 'none', |
top: y + 5, | top: y + 5, |
left: x + 5, | left: x + 5, |
border: '1px solid #fdd', | border: '1px solid #fdd', |
padding: '2px', | padding: '2px', |
'background-color': '#fee', | 'background-color': '#fee', |
opacity: 0.80 | opacity: 0.80 |
}).appendTo("body").fadeIn(200); | }).appendTo("body").fadeIn(200); |
} | } |
var previousPoint = null; | var previousPoint = null; |
$("#placeholder").bind("plothover", function (event, pos, item) { | $("#placeholder").bind("plothover", function (event, pos, item) { |
$("#x").text(pos.x.toFixed(2)); | $("#x").text(pos.x.toFixed(2)); |
$("#y").text(pos.y.toFixed(2)); | $("#y").text(pos.y.toFixed(2)); |
if (item) { | if (item) { |
if (previousPoint != item.dataIndex) { | if (previousPoint != item.dataIndex) { |
previousPoint = item.dataIndex; | previousPoint = item.dataIndex; |
$("#tooltip").remove(); | $("#tooltip").remove(); |
var x = item.datapoint[0].toFixed(2), | var x = item.datapoint[0].toFixed(2), |
y = item.datapoint[1].toFixed(2); | y = item.datapoint[1].toFixed(2); |
var d = new Date(); | var d = new Date(); |
d.setTime(x); | d.setTime(x); |
var time = d.getUTCHours() +':'+ (d.getUTCMinutes().toString().length == 1 ? '0'+ d.getMinutes(): d.getUTCMinutes()) | var time = d.getUTCHours() +':'+ (d.getUTCMinutes().toString().length == 1 ? '0'+ d.getMinutes(): d.getUTCMinutes()) |
showTooltip(item.pageX, item.pageY, | showTooltip(item.pageX, item.pageY, |
item.series.label + " at "+ time +" = " + Math.abs(new Number(y/60).toFixed(2))+" minutes "+(y >0 ? "early":"late")); | item.series.label + " at "+ time +" = " + Math.abs(new Number(y/60).toFixed(2))+" minutes "+(y >0 ? "early":"late")); |
} | } |
} | } |
else { | else { |
$("#tooltip").remove(); | $("#tooltip").remove(); |
previousPoint = null; | previousPoint = null; |
} | } |
}); | }); |
</script> | </script> |
<?php | |
include ('../include/common.inc.php'); | |
$query = "Select route_short_name,max(route_id) as route_id from routes where route_short_name NOT LIKE '7__' AND route_short_name != '170' AND route_short_name NOT LIKE '9__' group by route_short_name order by route_short_name ;"; | |
debug($query, "database"); | |
$query = $conn->prepare($query); | |
$query->execute(); | |
echo "<table><tr><th>Route Number</th><th>First Trip Start</th><th>First Trip End</th><th>Length</th>"; | |
$total = 0; | |
$count = 0; | |
foreach($query->fetchAll() as $r) { | |
$trips = getRouteTrips($r['route_id']); | |
$startTime = $trips[0]['arrival_time']; | |
$endTime = getTripEndTime($trips[0]['trip_id']); | |
$timeDiff = strtotime($endTime) - strtotime($startTime); | |
$total += $timeDiff; | |
$count ++; | |
echo "<tr><td>{$r['route_short_name']}</td><td>$startTime</td><td>$endTime</td><td>$timeDiff seconds ie. ". ($timeDiff/60). " minutes</td></tr>"; | |
} | |
echo "</table>"; | |
echo "Total time: $total seconds ie. " .($total/60/60). " hours<br>"; | |
echo "$count Routes"; | |
?> |
<?php | <?php |
if ( php_sapi_name() == "cli") { | if ( php_sapi_name() == "cli") { |
include ('include/common.inc.php'); | include ('include/common.inc.php'); |
$conn = pg_connect("dbname=transitdata user=postgres password=snmc host=localhost") or die('connection failed'); | $conn = pg_connect("dbname=transitdata user=postgres password=snmc host=localhost") or die('connection failed'); |
$pdconn = new PDO("pgsql:dbname=transitdata;user=postgres;password=snmc;host=localhost"); | |
// Unzip cbrfeed.zip, import all csv files to database | // Unzip cbrfeed.zip, import all csv files to database |
$unzip = true; | $unzip = true; |
$zip = zip_open(dirname(__FILE__) . "/cbrfeed.zip"); | $zip = zip_open(dirname(__FILE__) . "/cbrfeed.zip"); |
$tmpdir = "/tmp/cbrfeed/"; | $tmpdir = "/tmp/cbrfeed/"; |
mkdir($tmpdir); | mkdir($tmpdir); |
if ($unzip) { | if ($unzip) { |
if (is_resource($zip)) { | if (is_resource($zip)) { |
while ($zip_entry = zip_read($zip)) { | while ($zip_entry = zip_read($zip)) { |
$fp = fopen($tmpdir . zip_entry_name($zip_entry) , "w"); | $fp = fopen($tmpdir . zip_entry_name($zip_entry) , "w"); |
if (zip_entry_open($zip, $zip_entry, "r")) { | if (zip_entry_open($zip, $zip_entry, "r")) { |
echo "Extracting " . zip_entry_name($zip_entry) . "\n"; | echo "Extracting " . zip_entry_name($zip_entry) . "\n"; |
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); | $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); |
fwrite($fp, "$buf"); | fwrite($fp, "$buf"); |
zip_entry_close($zip_entry); | zip_entry_close($zip_entry); |
fclose($fp); | fclose($fp); |
} | } |
} | } |
zip_close($zip); | zip_close($zip); |
} | } |
} | } |
foreach (scandir($tmpdir) as $file) { | foreach (scandir($tmpdir) as $file) { |
if (!strpos($file, ".txt") === false) { | if (!strpos($file, ".txt") === false) { |
$fieldseparator = ","; | $fieldseparator = ","; |
$lineseparator = "\n"; | $lineseparator = "\n"; |
$tablename = str_replace(".txt", "", $file); | $tablename = str_replace(".txt", "", $file); |
echo "Opening $file \n"; | echo "Opening $file \n"; |
$line = 0; | $line = 0; |
$handle = fopen($tmpdir . $file, "r"); | $handle = fopen($tmpdir . $file, "r"); |
if ($tablename =="stop_times") { | |
$stmt = $pdconn->prepare("insert into stop_times (trip_id,stop_id,stop_sequence) values(:trip_id, :stop_id, :stop_sequence);"); | |
$stmt->bindParam(':trip_id',$trip_id); | |
$stmt->bindParam(':stop_id',$stop_id); | |
$stmt->bindParam(':stop_sequence',$stop_sequence); | |
} | |
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { | while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { |
if ($line > 0) { | if ($line == 0) { |
} else { | |
$query = "insert into $tablename values("; | $query = "insert into $tablename values("; |
$valueCount = 0; | $valueCount = 0; |
foreach ($data as $value) { | foreach ($data as $value) { |
$query.=($valueCount >0 ? "','" :"'").pg_escape_string($value); | $query.=($valueCount >0 ? "','" :"'").pg_escape_string($value); |
$valueCount++; | $valueCount++; |
} | } |
if ($tablename == "stops") { | if ($tablename == "stops") { |
$query.= "', ST_GeographyFromText('SRID=4326;POINT({$data[2]} {$data[0]})'));"; | $query.= "', ST_GeographyFromText('SRID=4326;POINT({$data[2]} {$data[0]})'));"; |
} else { | } else { |
$query.= "');"; | $query.= "');"; |
} | } |
if ($tablename =="stop_times" && $data[1] == "") { | if ($tablename =="stop_times" && $data[1] == "") { |
$query = "insert into $tablename (trip_id,stop_id,stop_sequence) values('{$data[0]}','{$data[3]}','{$data[4]}');"; | // $query = "insert into $tablename (trip_id,stop_id,stop_sequence) values('{$data[0]}','{$data[3]}','{$data[4]}');"; |
} | $trip_id=$data[0]; |
$stop_id=$data[3]; | |
$stop_sequence=$data[4]; | |
} | |
} | } |
$result = pg_query($conn, $query); | if ($tablename =="stop_times") { |
$stmt->execute(); | |
} | |
else { | |
$result = pg_query($conn, $query); | |
} | |
$line++; | $line++; |
if ($line % 10000 == 0) echo "$line records... \n"; | if ($line % 10000 == 0) echo "$line records... ".date('c')."\n"; |
} | } |
fclose($handle); | fclose($handle); |
echo "Found a total of $line records in $file.\n"; | echo "Found a total of $line records in $file.\n"; |
} | } |
} | } |
} | } |
?> | ?> |