shared_writable_dirs: | |
- /labs/tiles | |
- /lib/staticmaplite/cache | |
php_extensions: [pgsql, pdo, pdo_pgsql, curl] | |
<?php | <?php |
include ('include/common.inc.php'); | include ('include/common.inc.php'); |
include_header("About", "about") | include_header("About", "about") |
?> | ?> |
<p> | <p> |
Busness Time - An ACT bus timetable webapp<br /> | Busness Time - An ACT bus timetable webapp<br /> |
Based on the maxious-canberra-transit-feed (<a | Based on the maxious-canberra-transit-feed (<a |
href="http://s3-ap-southeast-1.amazonaws.com/busresources/cbrfeed.zip">download</a>, | href="http://s3-ap-southeast-1.amazonaws.com/busresources/cbrfeed.zip">download</a>, |
last updated <?php | last updated <?php |
echo date("F d Y.", @filemtime('cbrfeed.zip')); ?>)<br /> | echo date("F d Y.", @filemtime('cbrfeed.zip')); ?>)<br /> |
Source code for the <a | Source code for the <a |
href="https://github.com/maxious/ACTBus-data">transit | href="https://github.com/maxious/ACTBus-data">transit |
feed</a> and <a href="https://github.com/maxious/ACTBus-ui">this | feed</a> and <a href="https://github.com/maxious/ACTBus-ui">this |
site</a> available from github.<br /> | site</a> available from github.<br /> |
Uses jQuery Mobile, PHP, PostgreSQL, OpenTripPlanner, OpenLayers, OpenStreetMap, Cloudmade Geocoder and Tile Service<br /> | Uses jQuery Mobile, PHP, PostgreSQL, OpenTripPlanner, OpenLayers, OpenStreetMap, Cloudmade Geocoder and Tile Service<br /> |
<br /> | <br /> |
Feedback encouraged; contact maxious@lambdacomplex.org<br /> | Feedback encouraged; contact maxious@lambdacomplex.org<br /> |
<br /> | <br /> |
Some icons by Joseph Wain / glyphish.com<br /> | Some icons by Joseph Wain / glyphish.com<br /> |
Native clients also available for iPhone(<a href="http://itunes.apple.com/au/app/cbrtimetable/id444287349?mt=8">cbrTimetable by Sandor Kolotenko</a> | |
, <a href="http://itunes.apple.com/au/app/act-buses/id376634797?mt=8">ACT Buses by David Sullivan</a>) | |
and Android (<a href="https://market.android.com/details?id=com.action">MyBus 2.0 by Imagine Team</a>) | |
<br /> | |
<br /> | <br /> |
<small>Disclaimer: The content of this website is of a general and informative nature. Please check with printed timetables or those available on http://action.act.gov.au before your trip. | <small>Disclaimer: The content of this website is of a general and informative nature. Please check with printed timetables or those available on http://action.act.gov.au before your trip. |
Whilst every effort has been made to ensure the high quality and accuracy of the Site, the Author makes no warranty, | Whilst every effort has been made to ensure the high quality and accuracy of the Site, the Author makes no warranty, |
express or implied concerning the topicality, correctness, completeness or quality of the information, which is provided | express or implied concerning the topicality, correctness, completeness or quality of the information, which is provided |
"as is". The Author expressly disclaims all warranties, including but not limited to warranties of fitness for a particular purpose and warranties of merchantability. | "as is". The Author expressly disclaims all warranties, including but not limited to warranties of fitness for a particular purpose and warranties of merchantability. |
All offers are not binding and without obligation. The Author expressly reserves the right, in his discretion, to suspend, | All offers are not binding and without obligation. The Author expressly reserves the right, in his discretion, to suspend, |
change, modify, add or remove portions of the Site and to restrict or terminate the use and accessibility of the Site | change, modify, add or remove portions of the Site and to restrict or terminate the use and accessibility of the Site |
without prior notice. </small> | without prior notice. </small> |
<?php | <?php |
include_footer(); | include_footer(); |
?> | ?> |
#!/bin/bash | #!/bin/bash |
#this script should be run from a fresh git checkout from github | #this script should be run from a fresh git checkout from github |
#ami base must have yum install lighttpd-fastcgi, git, tomcat6 | #ami base must have yum install lighttpd-fastcgi, git, tomcat6 |
#php-cli php-gd tomcat6-webapps tomcat6-admin-webapps svn maven2 | #php-cli php-gd tomcat6-webapps tomcat6-admin-webapps svn maven2 |
#postgres postgres-server php-pg | #postgres postgres-server php-pg |
#http://www.how2forge.org/installing-lighttpd-with-php5-and-mysql-support-on-fedora-12 | #http://www.how2forge.org/installing-lighttpd-with-php5-and-mysql-support-on-fedora-12 |
cp /root/aws.php /tmp/ | cp /root/aws.php /tmp/ |
mkdir /var/www/lib/staticmaplite/cache | mkdir /var/www/lib/staticmaplite/cache |
chcon -h system_u:object_r:httpd_sys_content_t /var/www | chcon -h system_u:object_r:httpd_sys_content_t /var/www |
chcon -R -h root:object_r:httpd_sys_content_t /var/www/* | chcon -R -h root:object_r:httpd_sys_content_t /var/www/* |
chcon -R -t httpd_sys_content_rw_t /var/www/lib/staticmaplite/cache | chcon -R -t httpd_sys_content_rw_t /var/www/lib/staticmaplite/cache |
chmod -R 777 /var/www/lib/staticmaplite/cache | chmod -R 777 /var/www/lib/staticmaplite/cache |
chcon -R -t httpd_sys_content_rw_t /var/www/labs/tiles | chcon -R -t httpd_sys_content_rw_t /var/www/labs/tiles |
chmod -R 777 /var/www/labs/tiles | chmod -R 777 /var/www/labs/tiles |
wget http://s3-ap-southeast-1.amazonaws.com/busresources/cbrfeed.zip \ | wget http://s3-ap-southeast-1.amazonaws.com/busresources/cbrfeed.zip \ |
-O /var/www/cbrfeed.zip | -O /var/www/cbrfeed.zip |
createdb transitdata | createdb transitdata |
createlang -d transitdata plpgsql | createlang -d transitdata plpgsql |
psql -d transitdata -f /var/www/lib/postgis.sql | psql -d transitdata -f /var/www/lib/postgis.sql |
# curl https://github.com/maxious/ACTBus-ui/raw/master/transitdata.cbrfeed.sql.gz -o transitdata.cbrfeed.sql.gz | # curl https://github.com/maxious/ACTBus-ui/raw/master/transitdata.cbrfeed.sql.gz -o transitdata.cbrfeed.sql.gz |
#made with pg_dump transitdata | gzip -c > transitdata.cbrfeed.sql.gz | #made with pg_dump transitdata | gzip -c > transitdata.cbrfeed.sql.gz |
gunzip /var/www/transitdata.cbrfeed.sql.gz | gunzip /var/www/transitdata.cbrfeed.sql.gz |
psql -d transitdata -f /var/www/transitdata.cbrfeed.sql | psql -d transitdata -f /var/www/transitdata.cbrfeed.sql |
#createuser transitdata -SDRP | #createuser transitdata -SDRP |
#password transitdata | #password transitdata |
#psql -d transitdata -c \"GRANT SELECT ON TABLE agency,calendar,calendar_dates,routes,stop_times,stops,trips TO transitdata;\" | #psql -d transitdata -c \"GRANT SELECT ON TABLE agency,calendar,calendar_dates,routes,stop_times,stops,trips TO transitdata;\" |
#psql -d transitdata -c "GRANT SELECT,INSERT ON TABLE myway_observations,myway_routes,myway_stops,myway_timingdeltas TO transitdata;" | |
#psql -d transitdata -c "GRANT SELECT,INSERT,UPDATE ON TABLE myway_routes,myway_stops TO transitdata;" | |
##psql -d transitdata -c "GRANT SELECT ON ALL TABLES IN SCHEMA public TO transitdata;" | |
php /var/www/updatedb.php | php /var/www/updatedb.php |
wget http://s3-ap-southeast-1.amazonaws.com/busresources/Graph.obj \ | wget http://s3-ap-southeast-1.amazonaws.com/busresources/Graph.obj \ |
-O /tmp/Graph.obj | -O /tmp/Graph.obj |
rm -rfv /usr/share/tomcat6/webapps/opentripplanner* | rm -rfv /usr/share/tomcat6/webapps/opentripplanner* |
wget http://s3-ap-southeast-1.amazonaws.com/busresources/opentripplanner-webapp.war \ | wget http://s3-ap-southeast-1.amazonaws.com/busresources/opentripplanner-webapp.war \ |
-O /usr/share/tomcat6/webapps/opentripplanner-webapp.war | -O /usr/share/tomcat6/webapps/opentripplanner-webapp.war |
wget http://s3-ap-southeast-1.amazonaws.com/busresources/opentripplanner-api-webapp.war \ | wget http://s3-ap-southeast-1.amazonaws.com/busresources/opentripplanner-api-webapp.war \ |
-O /usr/share/tomcat6/webapps/opentripplanner-api-webapp.war | -O /usr/share/tomcat6/webapps/opentripplanner-api-webapp.war |
/etc/init.d/tomcat6 restart | /etc/init.d/tomcat6 restart |
<?php | <?php |
header('Content-type: text/css'); | header('Content-type: text/css'); |
ob_start("compress"); | ob_start("compress"); |
function compress($buffer) { | function compress($buffer) { |
/* remove comments */ | /* remove comments */ |
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); | $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); |
/* remove tabs, spaces, newlines, etc. */ | /* remove tabs, spaces, newlines, etc. */ |
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); | $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); |
return $buffer; | return $buffer; |
} | } |
echo ' | echo ' |
.ui-li-thumb, .ui-li-icon { position: relative; } | .ui-li-thumb, .ui-li-icon { position: relative; } |
.ui-navbar { | .ui-navbar { |
width: 100%; | width: 100%; |
} | } |
.ui-btn-inner { | .ui-btn-inner { |
white-space: normal !important; | white-space: normal !important; |
} | } |
.ui-li-heading { | .ui-li-heading { |
white-space: normal !important; | white-space: normal !important; |
} | } |
.ui-listview-filter { | .ui-listview-filter { |
margin: 0 !important; | margin: 0 !important; |
} | } |
.ui-icon-navigation { | .ui-icon-navigation { |
background-image: url('.$_REQUEST['labsPath'].'css/images/113-navigation.png); | background-image: url(images/113-navigation.png); |
background-position: 1px 0; | background-position: 1px 0; |
} | } |
.ui-icon-beaker { | .ui-icon-beaker { |
background-image: url('.$_REQUEST['labsPath'].'css/images/91-beaker-2.png); | background-image: url(images/91-beaker-2.png); |
background-position: 1px 0; | background-position: 1px 0; |
} | } |
#footer { | #footer { |
text-size: 0.75em; | text-size: 0.75em; |
text-align: center; | text-align: center; |
} | } |
body { | body { |
background-color: #F0F0F0; | background-color: #F0F0F0; |
} | } |
#jqm-homeheader { | #jqm-homeheader { |
text-align: center; | text-align: center; |
} | } |
.viaPoints { | .viaPoints { |
display: none; | display: none; |
text-size: 0.2em; | text-size: 0.2em; |
} | } |
.min-width-480px .viaPoints { | .min-width-480px .viaPoints { |
display: inline; | display: inline; |
} | } |
#extrainfo { | #extrainfo { |
visibility: hidden; | visibility: hidden; |
display: none; | display: none; |
} | } |
#servicewarning { | #servicewarning { |
padding: 1em; | padding: 1em; |
margin-bottom: 0.5em; | margin-bottom: 0.5em; |
text-size: 0.2em; | text-size: 0.2em; |
background-color: #FF9; | background-color: #FF9; |
-moz-border-radius: 15px; | -moz-border-radius: 15px; |
border-radius: 15px; | border-radius: 15px; |
} | } |
#footer { | #footer { |
clear:both; | clear:both; |
text-align:center; | text-align:center; |
} | } |
// source http://webaim.org/techniques/skipnav/ | // source http://webaim.org/techniques/skipnav/ |
#skip a, #skip a:hover, #skip a:visited | #skip a, #skip a:hover, #skip a:visited |
{ | { |
position:absolute; | position:absolute; |
left:0px; | left:0px; |
top:-500px; | top:-500px; |
width:1px; | width:1px; |
height:1px; | height:1px; |
overflow:hidden; | overflow:hidden; |
} | } |
#skip a:active, #skip a:focus | #skip a:active, #skip a:focus |
{ | { |
position:static; | position:static; |
width:auto; | width:auto; |
height:auto; | height:auto; |
}'; | }'; |
//if (false) | //if (false) |
echo ' | echo ' |
// adaptive layout from jQuery Mobile docs site | // adaptive layout from jQuery Mobile docs site |
.type-interior .content-secondary { | .type-interior .content-secondary { |
border-right: 0; | border-right: 0; |
border-left: 0; | border-left: 0; |
margin: 10px -15px 0; | margin: 10px -15px 0; |
background: #fff; | background: #fff; |
border-top: 1px solid #ccc; | border-top: 1px solid #ccc; |
} | } |
.type-home .ui-content { | .type-home .ui-content { |
margin-top: 5px; | margin-top: 5px; |
} | } |
.type-interior .ui-content { | .type-interior .ui-content { |
padding-bottom: 0; | padding-bottom: 0; |
} | } |
.content-secondary .ui-collapsible-contain { | .content-secondary .ui-collapsible-contain { |
padding: 10px 15px; | padding: 10px 15px; |
} | } |
.content-secondary .ui-collapsible-heading { | .content-secondary .ui-collapsible-heading { |
margin: 0 0 30px; | margin: 0 0 30px; |
} | } |
.content-secondary .ui-collapsible-heading-collapsed, | .content-secondary .ui-collapsible-heading-collapsed, |
.content-secondary .ui-collapsible-content { | .content-secondary .ui-collapsible-content { |
padding:0; | padding:0; |
margin: 0; | margin: 0; |
} | } |
@media all and (min-width: 650px){ | @media all and (min-width: 650px){ |
.content-secondary { | .content-secondary { |
text-align: left; | text-align: left; |
float: left; | float: left; |
width: 45%; | width: 45%; |
background: none; | background: none; |
border-top: 0; | border-top: 0; |
} | } |
.content-secondary, | .content-secondary, |
.type-interior .content-secondary { | .type-interior .content-secondary { |
margin: 30px 0 20px 2%; | margin: 30px 0 20px 2%; |
padding: 20px 4% 0 0; | padding: 20px 4% 0 0; |
background: none; | background: none; |
} | } |
.type-index .content-secondary { | .type-index .content-secondary { |
padding: 0; | padding: 0; |
} | } |
.type-index .content-secondary .ui-listview { | .type-index .content-secondary .ui-listview { |
margin: 0; | margin: 0; |
} | } |
.content-primary { | .content-primary { |
width: 45%; | width: 45%; |
float: right; | float: right; |
margin-top: 30px; | margin-top: 30px; |
margin-right: 1%; | margin-right: 1%; |
padding-right: 1%; | padding-right: 1%; |
} | } |
.content-primary ul:first-child { | .content-primary ul:first-child { |
margin-top: 0; | margin-top: 0; |
} | } |
.type-interior .content-primary { | .type-interior .content-primary { |
padding: 1.5em 6% 3em 0; | padding: 1.5em 6% 3em 0; |
margin: 0; | margin: 0; |
} | } |
/* fix up the collapsibles - expanded on desktop */ | /* fix up the collapsibles - expanded on desktop */ |
.content-secondary .ui-collapsible-heading { | .content-secondary .ui-collapsible-heading { |
display: none; | display: none; |
} | } |
.content-secondary .ui-collapsible-contain { | .content-secondary .ui-collapsible-contain { |
margin:0; | margin:0; |
} | } |
.content-secondary .ui-collapsible-content { | .content-secondary .ui-collapsible-content { |
display: block; | display: block; |
margin: 0; | margin: 0; |
padding: 0; | padding: 0; |
} | } |
.type-interior .content-secondary .ui-li-divider { | .type-interior .content-secondary .ui-li-divider { |
padding-top: 1em; | padding-top: 1em; |
padding-bottom: 1em; | padding-bottom: 1em; |
} | } |
.type-interior .content-secondary { | .type-interior .content-secondary { |
margin: 0; | margin: 0; |
padding: 0; | padding: 0; |
} | } |
} | } |
@media all and (min-width: 750px){ | @media all and (min-width: 750px){ |
.type-home .ui-content, | .type-home .ui-content, |
.type-interior .ui-content { | .type-interior .ui-content { |
background-position: 39%; | background-position: 39%; |
} | } |
.content-secondary { | .content-secondary { |
width: 34%; | width: 34%; |
} | } |
.content-primary { | .content-primary { |
width: 56%; | width: 56%; |
padding-right: 1%; | padding-right: 1%; |
} | } |
.type-interior .ui-content { | .type-interior .ui-content { |
background-position: 34%; | background-position: 34%; |
} | } |
} | } |
@media all and (min-width: 1200px){ | @media all and (min-width: 1200px){ |
.type-home .ui-content{ | .type-home .ui-content{ |
background-position: 38.5%; | background-position: 38.5%; |
} | } |
.type-interior .ui-content { | .type-interior .ui-content { |
background-position: 30%; | background-position: 30%; |
} | } |
.content-secondary { | .content-secondary { |
width: 30%; | width: 30%; |
padding-right:6%; | padding-right:6%; |
margin: 30px 0 20px 5%; | margin: 30px 0 20px 5%; |
} | } |
.type-interior .content-secondary { | .type-interior .content-secondary { |
margin: 0; | margin: 0; |
padding: 0; | padding: 0; |
} | } |
.content-primary { | .content-primary { |
width: 50%; | width: 50%; |
margin-right: 5%; | margin-right: 5%; |
padding-right: 3%; | padding-right: 3%; |
} | } |
.type-interior .content-primary { | .type-interior .content-primary { |
width: 60%; | width: 60%; |
} | } |
}'; | }'; |
ob_end_flush(); | ob_end_flush(); |
?> | ?> |
<?php | <?php |
// Copyright 2009 Google Inc. All Rights Reserved. | // Copyright 2009 Google Inc. All Rights Reserved. |
$GA_ACCOUNT = "MO-22173039-1"; | $GA_ACCOUNT = "MO-22173039-1"; |
$GA_PIXEL = "/lib/ga.php"; | $GA_PIXEL = "/lib/ga.php"; |
function googleAnalyticsGetImageUrl() | function googleAnalyticsGetImageUrl() |
{ | { |
global $GA_ACCOUNT, $GA_PIXEL; | global $GA_ACCOUNT, $GA_PIXEL; |
//if (stristr($_SERVER['HTTP_USER_AGENT'], 'Googlebot') return ""; | //if (stristr($_SERVER['HTTP_USER_AGENT'], 'Googlebot') return ""; |
$url = ""; | $url = ""; |
$url.= $GA_PIXEL . "?"; | $url.= $GA_PIXEL . "?"; |
$url.= "utmac=" . $GA_ACCOUNT; | $url.= "utmac=" . $GA_ACCOUNT; |
$url.= "&utmn=" . rand(0, 0x7fffffff); | $url.= "&utmn=" . rand(0, 0x7fffffff); |
$referer = $_SERVER["HTTP_REFERER"]; | $referer = $_SERVER["HTTP_REFERER"]; |
$query = $_SERVER["QUERY_STRING"]; | $query = $_SERVER["QUERY_STRING"]; |
$path = $_SERVER["REQUEST_URI"]; | $path = $_SERVER["REQUEST_URI"]; |
if (empty($referer)) { | if (empty($referer)) { |
$referer = "-"; | $referer = "-"; |
} | } |
$url.= "&utmr=" . urlencode($referer); | $url.= "&utmr=" . urlencode($referer); |
if (!empty($path)) { | if (!empty($path)) { |
$url.= "&utmp=" . urlencode($path); | $url.= "&utmp=" . urlencode($path); |
} | } |
$url.= "&guid=ON"; | $url.= "&guid=ON"; |
return str_replace("&", "&", $url); | return str_replace("&", "&", $url); |
} | } |
function include_header($pageTitle, $pageType, $opendiv = true, $geolocate = false, $datepicker = false) | function include_header($pageTitle, $pageType, $opendiv = true, $geolocate = false, $datepicker = false) |
{ | { |
global $labsPath; | global $labsPath; |
echo ' | echo ' |
<!DOCTYPE html> | <!DOCTYPE html> |
<html lang="en"> | <html lang="en"> |
<head> | <head> |
<meta charset="UTF-8"> | <meta charset="UTF-8"> |
<meta name="viewport" content="width=device-width, initial-scale=1"> | <meta name="viewport" content="width=device-width, initial-scale=1"> |
<title>' . $pageTitle . '</title> | <title>' . $pageTitle . '</title> |
<meta name="google-site-verification" | <meta name="google-site-verification" content="-53T5Qn4TB_de1NyfR_ZZkEVdUNcNFSaYKSFkWKx-sY" /> |
content="-53T5Qn4TB_de1NyfR_ZZkEVdUNcNFSaYKSFkWKx-sY" /> | <link rel="dns-prefetch" href="//code.jquery.com"> |
<link rel="stylesheet" href="'.$labsPath.'css/jquery-ui-1.8.12.custom.css" />'; | <link rel="dns-prefetch" href="//ajax.googleapis.com"> |
<link rel="stylesheet" href="' . $labsPath . 'css/jquery-ui-1.8.12.custom.css" />'; | |
if (isDebugServer()) { | if (isDebugServer()) { |
echo '<link rel="stylesheet" href="'.$labsPath.'css/jquery.mobile-1.0b1.css" /> | $jqmcss = $labsPath . 'css/jquery.mobile-1.0b1.css'; |
$jqjs = $labsPath . 'js/jquery-1.6.1.min.js'; | |
<script type="text/javascript" src="'.$labsPath.'js/jquery-1.6.1.min.js"></script> | $jqmjs = $labsPath . 'js/jquery.mobile-1.0b1.js'; |
<script>$(document).bind("mobileinit", function(){ | } |
else { | |
$jqmcss = "//code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css"; | |
$jqjs = "//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"; | |
$jqmjs = "//code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"; | |
} | |
echo '<link rel="stylesheet" href="' . $jqmcss . '" /> | |
<script src="'.$jqjs.'"></script> | |
<script>$(document).bind("mobileinit", function(){ | |
$.mobile.ajaxEnabled = false; | $.mobile.ajaxEnabled = false; |
}); | }); |
</script> | </script> |
<script type="text/javascript" src="'.$labsPath.'js/jquery.mobile-1.0b1.js"></script>'; | <script src="'.$jqmjs.'"></script> |
} | |
else { | <script src="' . $labsPath . 'js/jquery.ui.core.min.js"></script> |
echo '<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css" /> | <script src="' . $labsPath . 'js/jquery.ui.position.min.js"></script> |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> | <script src="' . $labsPath . 'js/jquery.ui.widget.min.js"></script> |
<script>$(document).bind("mobileinit", function(){ | <script src="' . $labsPath . 'js/jquery.ui.autocomplete.min.js"></script> |
$.mobile.ajaxEnabled = false; | |
}); | |
</script> | |
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>'; | |
} | |
echo ' | |
<script src="'.$labsPath.'js/jquery.ui.autocomplete.min.js"></script> | |
<script src="'.$labsPath.'js/jquery.ui.core.min.js"></script> | |
<script src="'.$labsPath.'js/jquery.ui.position.min.js"></script> | |
<script src="'.$labsPath.'js/jquery.ui.widget.min.js"></script> | |
<script> | <script> |
$(function() { | $(function() { |
$( "#geolocate" ).autocomplete({ | $( "#geolocate" ).autocomplete({ |
source: "lib/autocomplete.php", | source: "lib/autocomplete.php", |
minLength: 2 | minLength: 2 |
}); | }); |
$( "#from" ).autocomplete({ | $( "#from" ).autocomplete({ |
source: "lib/autocomplete.php", | source: "lib/autocomplete.php", |
minLength: 2 | minLength: 2 |
}); | }); |
$( "#to" ).autocomplete({ | $( "#to" ).autocomplete({ |
source: "lib/autocomplete.php", | source: "lib/autocomplete.php", |
minLength: 2 | minLength: 2 |
}); | }); |
}); | }); |
</script> | </script>'; |
'; | |
echo '<style type="text/css">'; | echo '<style type="text/css">'; |
if (strstr($_SERVER['HTTP_USER_AGENT'], 'Android')) echo '.ui-shadow,.ui-btn-up-a,.ui-btn-hover-a,.ui-btn-down-a,.ui-body-b,.ui-btn-up-b,.ui-btn-hover-b, | |
if (strstr($_SERVER['HTTP_USER_AGENT'], 'Android')) echo '.ui-shadow,.ui-btn-up-a,.ui-btn-hover-a,.ui-btn-down-a,.ui-body-b,.ui-btn-up-b,.ui-btn-hover-b, | |
.ui-btn-down-b,.ui-bar-c,.ui-body-c,.ui-btn-up-c,.ui-btn-hover-c,.ui-btn-down-c,.ui-bar-c,.ui-body-d, | .ui-btn-down-b,.ui-bar-c,.ui-body-c,.ui-btn-up-c,.ui-btn-hover-c,.ui-btn-down-c,.ui-bar-c,.ui-body-d, |
.ui-btn-up-d,.ui-btn-hover-d,.ui-btn-down-d,.ui-bar-d,.ui-body-e,.ui-btn-up-e,.ui-btn-hover-e, | .ui-btn-up-d,.ui-btn-hover-d,.ui-btn-down-d,.ui-bar-d,.ui-body-e,.ui-btn-up-e,.ui-btn-hover-e, |
.ui-btn-down-e,.ui-bar-e,.ui-overlay-shadow,.ui-shadow,.ui-btn-active,.ui-body-a,.ui-bar-a { | .ui-btn-down-e,.ui-bar-e,.ui-overlay-shadow,.ui-shadow,.ui-btn-active,.ui-body-a,.ui-bar-a { |
text-shadow: none; | text-shadow: none; |
box-shadow: none; | box-shadow: none; |
-webkit-box-shadow: none; | -webkit-box-shadow: none; |
}'; | }'; |
echo '</style>'; | echo '</style>'; |
echo '<link rel="stylesheet" href="' . $labsPath . 'css/local.css.php" />'; | |
echo '<link rel="stylesheet" href="'.$labsPath.'css/local.css.php?labsPath='.$labsPath.'" />'; | |
if (strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad')) { | if (strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad')) { |
echo '<meta name="apple-mobile-web-app-capable" content="yes" /> | echo '<meta name="apple-mobile-web-app-capable" content="yes" /> |
<meta name="apple-mobile-web-app-status-bar-style" content="black" /> | <meta name="apple-mobile-web-app-status-bar-style" content="black" /> |
<link rel="apple-touch-startup-image" href="startup.png" /> | <link rel="apple-touch-startup-image" href="startup.png" /> |
<link rel="apple-touch-icon" href="apple-touch-icon.png" />'; | <link rel="apple-touch-icon" href="apple-touch-icon.png" />'; |
} | } |
if ($geolocate) { | if ($geolocate) { |
echo "<script> | echo "<script> |
function success(position) { | function success(position) { |
$('#error').val('Location now detected. Please wait for data to load.'); | $('#error').val('Location now detected. Please wait for data to load.'); |
$('#geolocate').val(position.coords.latitude+','+position.coords.longitude); | $('#geolocate').val(position.coords.latitude+','+position.coords.longitude); |
$.ajax({ url: \"include/common.inc.php?geolocate=yes&lat=\"+position.coords.latitude+\"&lon=\"+position.coords.longitude }); | $.ajax({ url: \"include/common.inc.php?geolocate=yes&lat=\"+position.coords.latitude+\"&lon=\"+position.coords.longitude }); |
location.reload(true); | location.reload(true); |
} | } |
function error(msg) { | function error(msg) { |
$('#error').val('Error: '+msg); | $('#error').val('Error: '+msg); |
} | } |
function geolocate() { | function geolocate() { |
if (navigator.geolocation) { | if (navigator.geolocation) { |
var options = { | var options = { |
enableHighAccuracy: true, | enableHighAccuracy: true, |
timeout: 60000, | timeout: 60000, |
maximumAge: 10000 | maximumAge: 10000 |
} | } |
navigator.geolocation.getCurrentPosition(success, error, options); | navigator.geolocation.getCurrentPosition(success, error, options); |
} | } |
} | } |
$(document).ready(function() { | $(document).ready(function() { |
$('#here').click(function(event) { $('#geolocate').val(geolocate()); return false;}); | $('#here').click(function(event) { $('#geolocate').val(geolocate()); return false;}); |
$('#here').show(); | $('#here').show(); |
}); | }); |
"; | "; |
if (!isset($_SESSION['lat']) || $_SESSION['lat'] == "") echo "geolocate();"; | if (!isset($_SESSION['lat']) || $_SESSION['lat'] == "") echo "geolocate();"; |
echo "</script> "; | echo "</script> "; |
} | } |
if (isAnalyticsOn()) echo ' | if (isAnalyticsOn()) echo ' |
<script type="text/javascript">' . " | <script type="text/javascript">' . " |
var _gaq = _gaq || []; | var _gaq = _gaq || []; |
_gaq.push(['_setAccount', 'UA-22173039-1']); | _gaq.push(['_setAccount', 'UA-22173039-1']); |
_gaq.push(['_trackPageview']); | _gaq.push(['_trackPageview']); |
_gaq.push(['_trackPageLoadTime']); | _gaq.push(['_trackPageLoadTime']); |
</script>"; | </script>"; |
echo '</head> | echo '</head> |
<body> | <body> |
<div id="skip"> | <div id="skip"> |
<a href="#maincontent">Skip to content</a> | <a href="#maincontent">Skip to content</a> |
</div> | </div> |
'; | '; |
if ($opendiv) { | if ($opendiv) { |
echo '<div data-role="page"> | echo '<div data-role="page"> |
<div data-role="header" data-position="inline"> | <div data-role="header" data-position="inline"> |
<a href="' . (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "javascript:history.go(-1)") . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a> | <a href="' . (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "javascript:history.go(-1)") . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a> |
<h1>' . $pageTitle . '</h1> | <h1>' . $pageTitle . '</h1> |
<a href="'.$labsPath.'/index.php" data-icon="home" class="ui-btn-right">Home</a> | <a href="' . $labsPath . '/index.php" data-icon="home" class="ui-btn-right">Home</a> |
</div><!-- /header --> | </div><!-- /header --> |
<a name="maincontent" id="maincontent"></a> | <a name="maincontent" id="maincontent"></a> |
<div data-role="content"> '; | <div data-role="content"> '; |
$overrides = getServiceOverride(); | $overrides = getServiceOverride(); |
if ($overrides['service_id']) { | if ($overrides['service_id']) { |
if ($overrides['service_id'] == "noservice") { | if ($overrides['service_id'] == "noservice") { |
echo '<div id="servicewarning">Buses are <strong>not running today</strong> due to industrial action/public holiday. See <a | echo '<div id="servicewarning">Buses are <strong>not running today</strong> due to industrial action/public holiday. See <a |
href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>'; | href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>'; |
} | } |
else { | else { |
echo '<div id="servicewarning">Buses are running on an altered timetable today due to industrial action/public holiday. See <a href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>'; | echo '<div id="servicewarning">Buses are running on an altered timetable today due to industrial action/public holiday. See <a href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>'; |
} | |
} | } |
} | } |
} | |
} | } |
function include_footer() | function include_footer() |
{ | { |
global $labsPath; | |
global $labsPath; | echo '<div id="footer"><a href="' . $labsPath . 'about.php">About/Contact Us</a> <a href="' . $labsPath . 'feedback.php">Feedback/Bug Report</a> <a href="' . $labsPath . 'privacy.php">Privacy Policy</a>'; |
echo '<div id="footer"><a href="'.$labsPath.'about.php">About/Contact Us</a> <a href="'.$labsPath.'feedback.php">Feedback/Bug Report</a> <a href="'.$labsPath.'privacy.php">Privacy Policy</a>'; | |
echo '</div>'; | echo '</div>'; |
if (isAnalyticsOn()) { | if (isAnalyticsOn()) { |
echo "<script> (function() { | echo "<script> (function() { |
var ga = document.createElement('script'); ga.type = | var ga = document.createElement('script'); ga.type = |
'text/javascript'; ga.async = true; | 'text/javascript'; ga.async = true; |
ga.src = ('https:' == document.location.protocol ? | ga.src = ('https:' == document.location.protocol ? |
'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; | 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; |
var s = document.getElementsByTagName('script')[0]; | var s = document.getElementsByTagName('script')[0]; |
s.parentNode.insertBefore(ga, s); | s.parentNode.insertBefore(ga, s); |
})();</script>"; | })();</script>"; |
$googleAnalyticsImageUrl = googleAnalyticsGetImageUrl(); | $googleAnalyticsImageUrl = googleAnalyticsGetImageUrl(); |
echo '<noscript><img src="' . $googleAnalyticsImageUrl . '" /></noscript>'; | echo '<noscript><img src="' . $googleAnalyticsImageUrl . '" /></noscript>'; |
} | |
} | echo "\n</div></div></body></html>"; |
echo "\n</div></div></body></html>"; | } |
} | function placeSettings() |
function timePlaceSettings($geolocate = false) | |
{ | { |
global $service_periods; | global $service_periods; |
$geoerror = false; | $geoerror = false; |
if ($geolocate == true) { | |
$geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == ""; | $geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == ""; |
} | |
echo '<div id="error">'; | echo '<div id="error">'; |
if ($geoerror) { | if ($geoerror) { |
echo 'Sorry, but your location could not currently be detected. | echo 'Sorry, but your location could not currently be detected. |
Please allow location permission, wait for your location to be detected, | Please allow location permission, wait for your location to be detected, |
or enter an address/co-ordinates in the box below.'; | or enter an address/co-ordinates in the box below.'; |
} | } |
echo '</div>'; | echo '</div>'; |
echo '<div id="settings" data-role="collapsible" data-collapsed="' . !$geoerror . '"> | echo '<div id="settings" data-role="collapsible" data-collapsed="' . !$geoerror . '"> |
<h3>Change Time/Place (' . (isset($_SESSION['time']) ? $_SESSION['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3> | <h3>Change Location...</h3> |
<form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post"> | <form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post"> |
<div class="ui-body"> | <div class="ui-body"> |
<div data-role="fieldcontain"> | <div data-role="fieldcontain"> |
<label for="geolocate"> Current Location: </label> | <label for="geolocate"> Current Location: </label> |
<input type="text" id="geolocate" name="geolocate" value="' . (isset($_SESSION['lat']) && isset($_SESSION['lon']) ? $_SESSION['lat'] . "," . $_SESSION['lon'] : "Enter co-ordinates or address here") . '"/> <a href="#" style="display:none" name="here" id="here">Here?</a> | <input type="text" id="geolocate" name="geolocate" value="' . (isset($_SESSION['lat']) && isset($_SESSION['lon']) ? $_SESSION['lat'] . "," . $_SESSION['lon'] : "Enter co-ordinates or address here") . '"/> <a href="#" style="display:none" name="here" id="here">Here?</a> |
</div> | </div> |
<div data-role="fieldcontain"> | |
<label for="time"> Time: </label> | |
<input type="time" name="time" id="time" value="' . (isset($_SESSION['time']) ? $_SESSION['time'] : date("H:i")) . '"/> | |
<a href="#" name="currentTime" id="currentTime" onClick="var d = new Date();' . "$('#time').val(d.getHours() +':'+ (d.getMinutes().toString().length == 1 ? '0'+ d.getMinutes(): d.getMinutes()));" . '">Current Time?</a> | |
</div> | |
<div data-role="fieldcontain"> | |
<label for="service_period"> Service Period: </label> | |
<select name="service_period" id="service_period">'; | |
foreach ($service_periods as $service_period) { | |
echo "<option value=\"$service_period\"" . (service_period() === $service_period ? " SELECTED" : "") . '>' . ucwords($service_period) . '</option>'; | |
} | |
echo '</select> | |
<a href="#" style="display:none" name="currentPeriod" id="currentPeriod">Current Period?</a> | |
</div> | |
<input type="submit" value="Update"/> | <input type="submit" value="Update"/> |
</div></form> | </div></form> |
</div>'; | </div>'; |
} | } |
function trackEvent($category, $action, $label = "", $value = - 1) | function trackEvent($category, $action, $label = "", $value = - 1) |
{ | { |
if (isAnalyticsOn()) { | if (isAnalyticsOn()) { |
echo "\n<script> _gaq.push(['_trackEvent', '$category', '$action'" . ($label != "" ? ", '$label'" : "") . ($value != - 1 ? ", $value" : "") . "]);</script>"; | echo "\n<script> _gaq.push(['_trackEvent', '$category', '$action'" . ($label != "" ? ", '$label'" : "") . ($value != - 1 ? ", $value" : "") . "]);</script>"; |
} | } |
} | } |
?> | ?> |
<?php | <?php |
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 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("bus.lambdacomplex.org", "index", false) | include_header("bus.lambdacomplex.org", "index", false) |
?> | ?> |
<div data-role="page"> | <div data-role="page"> |
<div data-role="content"> | <div data-role="content"> |
<div id="jqm-homeheader"> | <div id="jqm-homeheader"> |
<h1>busness time</h1><br><small>Canberra Bus Timetables and Trip Planner</small> | <h1>busness time</h1><br><small>Canberra Bus Timetables and Trip Planner</small> |
</div> | </div> |
<a name="maincontent" id="maincontent"></a> | <a name="maincontent" id="maincontent"></a> |
<a href="tripPlanner.php" data-role="button" data-icon="navigation">Launch Trip Planner...</a> | <a href="tripPlanner.php" data-role="button" data-icon="navigation">Launch Trip Planner...</a> |
<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b"> | <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b"> |
<li data-role="list-divider">Timetables - Stops</li> | <li data-role="list-divider">Timetables - Stops</li> |
<li><a href="stopList.php">Major (Timing Point) Stops</a></li> | <li><a href="stopList.php">Major (Timing Point) Stops</a></li> |
<li><a href="stopList.php?allstops=yes">All Stops</a></li> | <li><a href="stopList.php?allstops=yes">All Stops</a></li> |
<li><a href="stopList.php?bysuburbs=yes">Stops By Suburb</a></li> | <li><a href="stopList.php?bysuburbs=yes">Stops By Suburb</a></li> |
<li><a class="nearby" href="stopList.php?nearby=yes">Nearby Stops</a></li> | <li><a class="nearby" href="stopList.php?nearby=yes">Nearby Stops</a></li> |
</ul> | </ul> |
<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b"> | <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b"> |
<li data-role="list-divider">Timetables - Routes</li> | <li data-role="list-divider">Timetables - Routes</li> |
<li><a href="routeList.php">Routes By Final Destination</a></li> | <li><a href="routeList.php">Routes By Final Destination</a></li> |
<li><a href="routeList.php?bynumber=yes">Routes By Number</a></li> | <li><a href="routeList.php?bynumber=yes">Routes By Number</a></li> |
<li><a href="routeList.php?bysuburbs=yes">Routes By Suburb</a></li> | <li><a href="routeList.php?bysuburbs=yes">Routes By Suburb</a></li> |
<li><a class="nearby" href="routeList.php?nearby=yes">Nearby Routes</a></li> | <li><a class="nearby" href="routeList.php?nearby=yes">Nearby Routes</a></li> |
</ul> | </ul> |
<?php | <?php |
echo timePlaceSettings(); | |
echo ' <a href="labs/index.php" data-role="button" data-icon="beaker">Busness R&D</a>'; | echo ' <a href="labs/index.php" data-role="button" data-icon="beaker">Busness R&D</a>'; |
include_footer(true) | include_footer(true) |
?> | ?> |
/*! LAB.js (LABjs :: Loading And Blocking JavaScript) | |
v2.0.1 (c) Kyle Simpson | |
MIT License | |
*/ | |
(function(o){var K=o.$LAB,y="UseLocalXHR",z="AlwaysPreserveOrder",u="AllowDuplicates",A="CacheBust",B="BasePath",C=/^[^?#]*\//.exec(location.href)[0],D=/^\w+\:\/\/\/?[^\/]+/.exec(C)[0],i=document.head||document.getElementsByTagName("head"),L=(o.opera&&Object.prototype.toString.call(o.opera)=="[object Opera]")||("MozAppearance"in document.documentElement.style),q=document.createElement("script"),E=typeof q.preload=="boolean",r=E||(q.readyState&&q.readyState=="uninitialized"),F=!r&&q.async===true,M=!r&&!F&&!L;function G(a){return Object.prototype.toString.call(a)=="[object Function]"}function H(a){return Object.prototype.toString.call(a)=="[object Array]"}function N(a,c){var b=/^\w+\:\/\//;if(/^\/\/\/?/.test(a)){a=location.protocol+a}else if(!b.test(a)&&a.charAt(0)!="/"){a=(c||"")+a}return b.test(a)?a:((a.charAt(0)=="/"?D:C)+a)}function s(a,c){for(var b in a){if(a.hasOwnProperty(b)){c[b]=a[b]}}return c}function O(a){var c=false;for(var b=0;b<a.scripts.length;b++){if(a.scripts[b].ready&&a.scripts[b].exec_trigger){c=true;a.scripts[b].exec_trigger();a.scripts[b].exec_trigger=null}}return c}function t(a,c,b,d){a.onload=a.onreadystatechange=function(){if((a.readyState&&a.readyState!="complete"&&a.readyState!="loaded")||c[b])return;a.onload=a.onreadystatechange=null;d()}}function I(a){a.ready=a.finished=true;for(var c=0;c<a.finished_listeners.length;c++){setTimeout(a.finished_listeners[c],0)}a.ready_listeners=[];a.finished_listeners=[]}function P(d,f,e,g,h){setTimeout(function(){var a,c=f.real_src,b;if("item"in i){if(!i[0]){setTimeout(arguments.callee,25);return}i=i[0]}a=document.createElement("script");if(f.type)a.type=f.type;if(f.charset)a.charset=f.charset;if(h){if(r){e.elem=a;if(E){a.preload=true;a.onpreload=g}else{a.onreadystatechange=function(){if(a.readyState=="loaded")g();a.onreadystatechange=null}}a.src=c}else if(h&&c.indexOf(D)==0&&d[y]){b=new XMLHttpRequest();b.onreadystatechange=function(){if(b.readyState==4){b.onreadystatechange=function(){};e.text=b.responseText+"\n//@ sourceURL="+c;g()}};b.open("GET",c);b.send()}else{a.type="text/cache-script";t(a,e,"ready",function(){i.removeChild(a);g()});a.src=c;i.insertBefore(a,i.firstChild)}}else if(F){a.async=false;t(a,e,"finished",g);a.src=c;i.insertBefore(a,i.firstChild)}else{t(a,e,"finished",g);a.src=c;i.insertBefore(a,i.firstChild)}},0)}function J(){var l={},Q=r||M,n=[],p={},m;l[y]=true;l[z]=false;l[u]=false;l[A]=false;l[B]="";function R(a,c,b){var d;function f(){if(d!=null){I(b);d=null}}if(p[c.src].finished)return;if(!a[u])p[c.src].finished=true;d=b.elem||document.createElement("script");if(c.type)d.type=c.type;if(c.charset)d.charset=c.charset;t(d,b,"finished",f);if(b.elem){b.elem=null}else if(b.text){d.onload=d.onreadystatechange=null;d.text=b.text}else{d.src=c.real_src}i.insertBefore(d,i.firstChild);if(b.text){f()}}function S(c,b,d,f){var e,g,h=function(){b.ready_cb(b,function(){R(c,b,e)})},j=function(){b.finished_cb(b,d)};b.src=N(b.src,c[B]);b.real_src=b.src+(c[A]?((/\?.*$/.test(b.src)?"&_":"?_")+~~(Math.random()*1E9)+"="):"");if(!p[b.src])p[b.src]={items:[],finished:false};g=p[b.src].items;if(c[u]||g.length==0){e=g[g.length]={ready:false,finished:false,ready_listeners:[h],finished_listeners:[j]};P(c,b,e,((f)?function(){e.ready=true;for(var a=0;a<e.ready_listeners.length;a++){setTimeout(e.ready_listeners[a],0)}e.ready_listeners=[]}:function(){I(e)}),f)}else{e=g[0];if(e.finished){setTimeout(j,0)}else{e.finished_listeners.push(j)}}}function v(){var e,g=s(l,{}),h=[],j=0,w=false,k;function T(a,c){a.ready=true;a.exec_trigger=c;x()}function U(a,c){a.ready=a.finished=true;a.exec_trigger=null;for(var b=0;b<c.scripts.length;b++){if(!c.scripts[b].finished)return}c.finished=true;x()}function x(){while(j<h.length){if(G(h[j])){try{h[j]()}catch(err){}}else if(!h[j].finished){if(O(h[j]))continue;break}j++}if(j==h.length){w=false;k=false}}function V(){if(!k||!k.scripts){h.push(k={scripts:[],finished:true})}}e={script:function(){for(var f=0;f<arguments.length;f++){(function(a,c){var b;if(!H(a)){c=[a]}for(var d=0;d<c.length;d++){V();a=c[d];if(G(a))a=a();if(!a)continue;if(H(a)){b=[].slice.call(a);b.push(d,1);c.splice.call(c,b);d--;continue}if(typeof a=="string")a={src:a};a=s(a,{ready:false,ready_cb:T,finished:false,finished_cb:U});k.finished=false;k.scripts.push(a);S(g,a,k,(Q&&w));w=true;if(g[z])e.wait()}})(arguments[f],arguments[f])}return e},wait:function(){if(arguments.length>0){for(var a=0;a<arguments.length;a++){h.push(arguments[a])}k=h[h.length-1]}else k=false;x();return e}};return{script:e.script,wait:e.wait,setOptions:function(a){s(a,g);return e}}}m={setGlobalDefaults:function(a){s(a,l);return m},setOptions:function(){return v().setOptions.apply(null,arguments)},script:function(){return v().script.apply(null,arguments)},wait:function(){return v().wait.apply(null,arguments)},queueScript:function(){n[n.length]={type:"script",args:[].slice.call(arguments)};return m},queueWait:function(){n[n.length]={type:"wait",args:[].slice.call(arguments)};return m},runQueue:function(){var a=m,c=n.length,b=c,d;for(;--b>=0;){d=n.shift();a=a[d.type].apply(null,d.args)}return a},noConflict:function(){o.$LAB=K;return m},sandbox:function(){return J()}};return m}o.$LAB=J();(function(a,c,b){if(document.readyState==null&&document[a]){document.readyState="loading";document[a](c,b=function(){document.removeEventListener(c,b,false);document.readyState="complete"},false)}})("addEventListener","DOMContentLoaded")})(this); |
<?php | <?php |
include ('../include/common.inc.php'); | include ('../include/common.inc.php'); |
include_header("Busness R&D", "index") | include_header("Busness R&D", "index") |
?> | ?> |
<ul data-role="listview" data-theme="e" data-groupingtheme="e"> | <ul data-role="listview" data-theme="e" data-groupingtheme="e"> |
<li data-role="list-divider" > Experimental Features </li> | <li data-role="list-divider" > Experimental Features </li> |
<li><a href="mywaybalance.php"><h3>MyWay Balance for mobile</h3> | <li><a href="mywaybalance.php"><h3>MyWay Balance for mobile</h3> |
<p>Mobile viewer for MyWay balance. Warning! No HTTPS security.</p></a></li> | <p>Mobile viewer for MyWay balance. Warning! No HTTPS security.</p></a></li> |
<li><a href="networkstats.php"><h3>Route Statistics</h3> | |
<p>Analysis of route timing points</p></a></li> | |
<li><a href="busstopdensity.php"><h3>Bus Stop Density Map</h3> | <li><a href="busstopdensity.php"><h3>Bus Stop Density Map</h3> |
<p>Analysis of bus stop coverage</p></a></li> | <p>Analysis of bus stop coverage</p></a></li> |
<li><a href="stopBrowser.php"><h3>Bus Stop Browser Map</h3> | <li><a href="stopBrowser.php"><h3>Bus Stop Browser Map</h3> |
<p>Bus stop location/route browser</p></a></li> | <p>Bus stop location/route browser</p></a></li> |
<li>More coming soon!</li> | </ul> |
<ul data-role="listview" data-theme="e" data-groupingtheme="e"> | |
<li data-role="list-divider" > MyWay Timeliness Graphs </li> | |
<li><a href="myway_timeliness.php"><h3>Timeliness over Day</h3> | |
<p>Displays the deviation from the timetable over the day</p></a></li> | |
<li><a href="myway_timeliness_freqdist.php"><h3>Frequency Distribution of Time Deviation</h3> | |
<p>Displays spread of time deviations</p></a></li> | |
<li><a href="myway_timeliness_route.php"><h3>Timeliness over Route</h3> | |
<p>Displays the deviation from timetable as a specific route progresses</p></a></li> | |
<li><a href="myway_timeliness_stop.php"><h3>Timeliness at Stop</h3> | |
<p>Displays the deviation from the timetable at a specific stop</p></a></li> | |
</ul> | </ul> |
</div> | </div> |
<?php | <?php |
include_footer() | include_footer() |
?> | ?> |
<?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> |
<div id="placeholder" style="width:1000px;height:600px"></div> | <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(); |
<?php | <?php |
$query = "select * from myway_timingdeltas where abs(timing_delta) < 2*(select stddev(timing_delta) from myway_timingdeltas) order by route_full_name;"; | $query = "select * from myway_timingdeltas where abs(timing_delta) < 2*(select stddev(timing_delta) from myway_timingdeltas) 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(); |
} | } |
$i = 0; | $i = 0; |
$labels = Array(); | $labels = Array(); |
$lastRoute = ""; | $lastRoute = ""; |
foreach ($query->fetchAll() as $delta) { | foreach ($query->fetchAll() as $delta) { |
$routeName = $delta['route_full_name']; | $routeName = $delta['route_full_name']; |
if (strstr($routeName," 3")) $routeName = "312-319"; | if (strstr($routeName, " 3")) $routeName = "312-319"; |
else $routeName = preg_replace('/\D/', '', $routeName); | else $routeName = preg_replace('/\D/', '', $routeName); |
if ($routeName != $lastRoute) { | if ($routeName != $lastRoute) { |
$i++; | $i++; |
echo " var d$i = [];"; | echo " var d$i = [];"; |
$lastRoute = $routeName; | $lastRoute = $routeName; |
$labels[$i] = $routeName; | $labels[$i] = $routeName; |
} | } |
echo "d$i.push([ midnight+ (1000*" . midnight_seconds(strtotime($delta['time'])) . "), {$delta['timing_delta']}]); \n"; | echo "d$i.push([ midnight+ (1000*" . midnight_seconds(strtotime($delta['time'])) . "), ".intval($delta['timing_delta'])."]); \n"; |
}; | }; |
?> | ?> |
var placeholder = $("#placeholder"); | var placeholder = $("#placeholder"); |
var plot = $.plot(placeholder, [ | var plot = $.plot(placeholder, [ |
<?php | <?php |
foreach ($labels as $key => $label) { | foreach ($labels as $key => $label) { |
echo " { | echo " { |
data: d$key, | data: d$key, |
points: { show: true }, | points: { show: true }, |
label: '$label' | label: '$label' |
},"; | },"; |
} | } |
?> | ?> |
], | ], |
{ | { |
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 }, | grid: { hoverable: true, clickable: true, labelMargin: 32 }, |
}); | }); |
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>'); |
}); | }); |
function yformatter(v) { | function yformatter(v) { |
return Math.floor(v/60) + " minutes " + (v == 0 ? "" : (v >0 ? "early":"late")) | if (Math.floor(v/60) < -9) return ""; |
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 +" = " + y +" ( "+ y/60+" minutes )"); | 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 | <?php |
include ('../include/common.inc.php'); | include ('../include/common.inc.php'); |
include_header("MyWay Delta Calculate", "mywayDeltaCalc"); | include_header("MyWay Delta Calculate", "mywayDeltaCalc"); |
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 |
$time = date("H:i:s", strtotime($obsv['time'])); | // timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html |
$time = date("H:i:s AESST", strtotime($obsv['time'])); | |
$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'] | |
); | ); |
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); |
} | } |
} | } |
// 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']; |
$myway_route = $obsv['myway_stop']; | |
$stop_code = $timeDeltas[0]["stop_code"]; | $stop_code = $timeDeltas[0]["stop_code"]; |
$stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_full_name, myway_route, stop_code, timing_delta, time, date, timing_period) | $stop_sequence = $timeDeltas[0]["stop_sequence"]; |
values (:observation_id, :route_full_name, :myway_route, :stop_code, :timing_delta, :time, :date, :timing_period)"); | $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)"); | |
$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(':myway_route', $myway_route); | |
$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); |
$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); | |
// 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(); |
} | } |
<?php | |
include ('../include/common.inc.php'); | |
include_header("MyWay Deltas", "mywayDelta"); | |
?> | |
<!--[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> | |
<center><div id="placeholder" style="width:900px;height:550px"></div></center> | |
<script type="text/javascript"> | |
$(function () { | |
var d1 = []; | |
<?php | |
$query = "select td, count(*) from (select (timing_delta - MOD(timing_delta,10)) as td from myway_timingdeltas where abs(timing_delta) < 2*(select stddev(timing_delta) from myway_timingdeltas)) as a group by td order by td"; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $delta) { | |
echo "d1.push([ ".intval($delta['td']).", ".intval($delta['count'])."]); \n"; | |
}; | |
?> | |
var placeholder = $("#placeholder"); | |
var plot = $.plot(placeholder, [ | |
{ | |
data: d1, | |
bars: { show: true } | |
}, | |
], | |
{ | |
grid: { hoverable: true, clickable: true, labelMargin: 17 }, | |
}); | |
}); | |
</script> |
<?php | |
include ('../include/common.inc.php'); | |
include_header("MyWay Deltas", "mywayDelta"); | |
?> | |
<table> | |
<tr><td></td><td>Mean</td><td>Standard<br>Deviation</td><td>Sample Size</td></tr> | |
<th> Overall </th> | |
<?php | |
$query = "select '', avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas "; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $row) { | |
echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>"; | |
}; | |
?> | |
<th> Hour of Day </th> | |
<?php | |
$query = "select extract(hour from time), avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas group by extract(hour from time) order by extract(hour from time)"; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $row) { | |
echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>"; | |
}; | |
?> | |
<th> Day of Week </th> | |
<?php | |
$query = "select to_char(date, 'Day'), avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas group by to_char(date, 'Day') order by to_char(date, 'Day')"; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $row) { | |
echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>"; | |
}; | |
?> | |
<th>Month </th> | |
<?php | |
$query = "select to_char(date, 'Month'), avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas group by to_char(date, 'Month') order by to_char(date, 'Month')"; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $row) { | |
echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>"; | |
}; | |
?> | |
<th>Stop </th> | |
<?php | |
$query = "select myway_stop, avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas INNER JOIN myway_observations | |
ON myway_observations.observation_id=myway_timingdeltas.observation_id group by myway_stop having count(*) > 1 order by myway_stop"; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $row) { | |
echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>"; | |
}; | |
?> | |
<th>Route </th> | |
<?php | |
$query = "select route_full_name, avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas group by route_full_name having count(*) > 1 order by route_full_name"; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $row) { | |
echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>"; | |
}; | |
?> | |
</table> | |
<?php | |
include_footer(); | |
?> | |
<?php | <?php |
include ('../include/common.inc.php'); | include ('../include/common.inc.php'); |
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_full_name = $value; |
$query = "update myway_routes set route_full_name = :route_full_name where myway_route = :myway_route"; | $query = "update myway_routes set route_full_name = :route_full_name 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); | $query->bindParam(":myway_route", $myway_route,PDO::PARAM_STR, 5); |
$query->bindParam(":route_full_name", $route_full_name); | $query->bindParam(":route_full_name", $route_full_name,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_code = $_REQUEST['stop_code']; |
$stop_street = $_REQUEST['stop_street']; | $stop_street = $_REQUEST['stop_street']; |
$query = "update myway_stops set stop_code = :stop_code, stop_street = :stop_street 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); | $query->bindParam(":myway_stop", $myway_stop, PDO::PARAM_STR, 25); |
$query->bindParam(":stop_code", $stop_code); | $query->bindParam(":stop_code", $stop_code, PDO::PARAM_STR, 32); |
$query->bindParam(":stop_street", $stop_street); | $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_code is NULL and stop_street 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]); | $stopNameParts = explode(" ", $myway_stop[0]); |
$markers = array(); | $markers = array(); |
$stopKey = 1; | $stopKey = 1; |
$foundStops = getStops(false, "", $stopNameParts[0] . " " . $stopNameParts[1]); | $foundStops = getStops(false, "", $stopNameParts[0] . " " . $stopNameParts[1]); |
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_code'] . "</td></tr>"; |
} | } |
echo '</table>'; | echo '</table>'; |
echo "" . staticmap($markers, 0, "icong", false) . "<br>\n"; | echo "" . staticmap($markers, 0, "icong", false) . "<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_code">Stop Code</label> |
<input type="text" name="stop_code" id="stop_code" value="' . $foundStops[0]['stop_code'] . '" /> | <input type="text" name="stop_code" id="stop_code" value="' . $foundStops[0]['stop_code'] . '" /> |
</div> | </div> |
<div data-role="fieldcontain"> | <div data-role="fieldcontain"> |
<label for="stop_street">Stop Street </label> | <label for="stop_street">Stop Street </label> |
<input type="text" name="stop_street" id="stop_street" value="' . $foundStops[0]['stop_name'] . '" /> | <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 '<hr>'; |
} | } |
echo '<h2>Routes</h2>'; | echo '<h2>Routes</h2>'; |
/*routes | /*routes |
remove alpha char, search present dropdown*/ | remove alpha char, search present dropdown*/ |
$query = "Select * from myway_routes where route_full_name is NUll;"; | $query = "Select * from myway_routes where route_full_name 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_route) { | foreach ($query->fetchAll() as $myway_route) { |
echo "<h3>{$myway_route[0]}</h3>"; | echo "<h3>{$myway_route[0]}</h3>"; |
$query = "Select * from myway_observations where myway_route = :route order by time"; | $query = "Select * from myway_observations where myway_route = :route order by time"; |
debug($query, "database"); | debug($query, "database"); |
$query = $conn->prepare($query); | $query = $conn->prepare($query); |
$query->bindParam(":route", $myway_route[0]); | $query->bindParam(":route", $myway_route[0]); |
$query->execute(); | $query->execute(); |
if (!$query) { | if (!$query) { |
databaseError($conn->errorInfo()); | databaseError($conn->errorInfo()); |
return Array(); | return Array(); |
} | } |
foreach ($query->fetchAll() as $myway_obvs) { | foreach ($query->fetchAll() as $myway_obvs) { |
echo $myway_obvs['myway_stop'] . $myway_obvs['time'] . "<br>"; | echo $myway_obvs['myway_stop'] . $myway_obvs['time'] . "<br>"; |
} | } |
$searchRouteNo = preg_replace("/[A-Z]/", "", $myway_route[0]); | $searchRouteNo = preg_replace("/[A-Z]/", "", $myway_route[0]); |
echo $searchRouteNo; | echo $searchRouteNo; |
echo '<form id="inputform' . $myway_route[0] . '"> | echo '<form id="inputform' . $myway_route[0] . '"> |
<select name="route' . $myway_route[0] . '" onchange=\'$.post("myway_timeliness_reconcile.php", $("#inputform' . $myway_route[0] . '").serialize())\'> | <select name="route' . $myway_route[0] . '" onchange=\'$.post("myway_timeliness_reconcile.php", $("#inputform' . $myway_route[0] . '").serialize())\'> |
<option>Select a from/to pair...</option>'; | <option>Select a from/to pair...</option>'; |
foreach (getRoutesByNumber($searchRouteNo) as $routeResult) { | 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 "<option value=\"{$routeResult['route_short_name']}{$routeResult['route_long_name']}\"> {$routeResult['route_short_name']}{$routeResult['route_long_name']} </option>\n"; |
} | } |
echo "</select></form>"; | echo "</select></form>"; |
echo '<hr>'; | echo '<hr>'; |
} | } |
include_footer(); | include_footer(); |
?> | ?> |
<?php | |
include ('../include/common.inc.php'); | |
header('Content-Type: text/javascript; charset=utf8'); | |
// header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/'); | |
header('Access-Control-Max-Age: 3628800'); | |
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); | |
?> | |
{ | |
"label": "<?php echo $_REQUEST['routeid']; ?>", | |
"data": <?php | |
$query = "select * from myway_timingdeltas where route_full_name = :route_full_name AND abs(timing_delta) < 2*(select stddev(timing_delta) from myway_timingdeltas) order by stop_sequence;"; | |
$query = $conn->prepare($query); | |
$query->bindParam(':route_full_name', $_REQUEST['routeid'],PDO::PARAM_STR, 42); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $delta) { | |
$points[] = "[{$delta['stop_sequence']}, {$delta['timing_delta']}]"; | |
}; | |
echo "[".implode(",",$points)."]"; | |
?> | |
} |
<?php | |
include ('../include/common.inc.php'); | |
include_header("MyWay Deltas", "mywayDelta"); | |
?> | |
<!--[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> | |
<form method="get" action=""> | |
<select id="routeid" name="routeid"> | |
<?php | |
$query = "select distinct route_full_name from myway_routes where myway_route != '' order by route_full_name"; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $route) { | |
echo "<option value=\"{$route['route_full_name']}\">{$route['route_full_name']}</option>"; | |
}; | |
?> </select> | |
<center><div id="placeholder" style="width:900px;height:550px"></div></center> | |
<script type="text/javascript"> | |
$(function () { | |
var placeholder = $("#placeholder"); | |
var data = []; | |
var options = { | |
xaxis: { | |
}, | |
yaxis: { | |
tickFormatter: yformatter | |
}, | |
grid: { hoverable: true, clickable: true, labelMargin: 32 }, | |
series: { | |
lines: { show: false }, | |
points: { show: true } | |
} | |
}; | |
var plot = $.plot(placeholder, data, options); | |
// fetch one series, adding to what we got | |
var alreadyFetched = {}; | |
$("#routeid").change(function () { | |
var select = $(this); | |
// find the URL in the link right next to us | |
// var dataurl = button.siblings('a').attr('href'); | |
var dataurl = "myway_timeliness_route.json.php?routeid=" + select.val(); | |
// then fetch the data with jQuery | |
function onDataReceived(series) { | |
// extract the first coordinate pair so you can see that | |
// data is now an ordinary Javascript object | |
var firstcoordinate = '(' + series.data[0][0] + ', ' + series.data[0][1] + ')'; | |
// let's add it to our current data | |
if (!alreadyFetched[series.label]) { | |
alreadyFetched[series.label] = true; | |
data.push(series); | |
} | |
// and plot all we got | |
$.plot(placeholder, data, options); | |
} | |
$.ajax({ | |
url: dataurl, | |
method: 'GET', | |
dataType: 'json', | |
success: onDataReceived | |
}); | |
}); | |
}); | |
function yformatter(v) { | |
if (Math.floor(v/60) < -9) return ""; | |
return Math.abs(Math.floor(v/60)) + " min " + (v == 0 ? "" : (v >0 ? "early":"late")) | |
} | |
function showTooltip(x, y, contents) { | |
$('<div id="tooltip">' + contents + '</div>').css( { | |
position: 'absolute', | |
display: 'none', | |
top: y + 5, | |
left: x + 5, | |
border: '1px solid #fdd', | |
padding: '2px', | |
'background-color': '#fee', | |
opacity: 0.80 | |
}).appendTo("body").fadeIn(200); | |
} | |
var previousPoint = null; | |
$("#placeholder").bind("plothover", function (event, pos, item) { | |
$("#x").text(pos.x.toFixed(2)); | |
$("#y").text(pos.y.toFixed(2)); | |
if (item) { | |
if (previousPoint != item.dataIndex) { | |
previousPoint = item.dataIndex; | |
$("#tooltip").remove(); | |
var x = item.datapoint[0], | |
y = item.datapoint[1].toFixed(2); | |
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")); | |
} | |
} | |
else { | |
$("#tooltip").remove(); | |
previousPoint = null; | |
} | |
}); | |
</script> | |
<?php | |
include ('../include/common.inc.php'); | |
header('Content-Type: text/javascript; charset=utf8'); | |
// header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/'); | |
header('Access-Control-Max-Age: 3628800'); | |
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); | |
?> | |
{ | |
"label": "<?php echo $_REQUEST['stopid']; ?>", | |
"data": <?php | |
$query = "select * from myway_timingdeltas INNER JOIN myway_observations | |
ON myway_observations.observation_id=myway_timingdeltas.observation_id | |
where myway_stop = :myway_stop | |
AND abs(timing_delta) < 2*(select stddev(timing_delta) from myway_timingdeltas) | |
order by myway_timingdeltas.time;"; | |
$query = $conn->prepare($query); | |
$query->bindParam(':myway_stop', $_REQUEST['stopid'],PDO::PARAM_STR, 42); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $delta) { | |
$points[] = "[".((strtotime("00:00Z") + midnight_seconds(strtotime($delta['time'])))*1000).", {$delta['timing_delta']}]"; | |
}; | |
if (count($points) == 0) { | |
echo "[]"; } | |
else echo "[".implode(",",$points)."]"; | |
?> | |
} | |
<?php | |
include ('../include/common.inc.php'); | |
include_header("MyWay Deltas", "mywayDelta"); | |
?> | |
<!--[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> | |
<form method="get" action=""> | |
<select id="stopid" name="stopid"> | |
<?php | |
$query = "select distinct myway_stop from myway_stops where myway_stop != '' order by myway_stop"; | |
$query = $conn->prepare($query); | |
$query->execute(); | |
if (!$query) { | |
databaseError($conn->errorInfo()); | |
return Array(); | |
} | |
foreach ($query->fetchAll() as $stop) { | |
echo "<option value=\"{$stop['myway_stop']}\">{$stop['myway_stop']}</option>"; | |
}; | |
?> </select> <center><div id="placeholder" style="width:900px;height:550px"></div></center> | |
<script type="text/javascript"> | |
$(function () { | |
var d = new Date(); | |
d.setUTCMinutes(0); | |
d.setUTCHours(0); | |
var midnight = d.getTime(); | |
var placeholder = $("#placeholder"); | |
var data = []; | |
var options = { | |
xaxis: { | |
mode: "time", | |
min: midnight + (1000*60*60*8), | |
max: midnight + (1000*60*60*23.5) | |
}, | |
yaxis: { | |
tickFormatter: yformatter | |
}, | |
grid: { hoverable: true, clickable: true, labelMargin: 32 }, | |
series: { | |
lines: { show: false }, | |
points: { show: true } | |
} | |
}; | |
var plot = $.plot(placeholder, data, options); | |
var o; | |
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>'); | |
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>'); | |
// fetch one series, adding to what we got | |
var alreadyFetched = {}; | |
$("#stopid").change(function () { | |
var select = $(this); | |
// find the URL in the link right next to us | |
// var dataurl = button.siblings('a').attr('href'); | |
var dataurl = "myway_timeliness_stop.json.php?stopid=" + select.val(); | |
// then fetch the data with jQuery | |
function onDataReceived(series) { | |
// extract the first coordinate pair so you can see that | |
// data is now an ordinary Javascript object | |
var firstcoordinate = '(' + series.data[0][0] + ', ' + series.data[0][1] + ')'; | |
// let's add it to our current data | |
if (!alreadyFetched[series.label]) { | |
alreadyFetched[series.label] = true; | |
data.push(series); | |
} | |
// and plot all we got | |
$.plot(placeholder, data, options); | |
} | |
$.ajax({ | |
url: dataurl, | |
method: 'GET', | |
dataType: 'json', | |
success: onDataReceived | |
}); | |
}); | |
}); | |
function yformatter(v) { | |
if (Math.floor(v/60) < -9) return ""; | |
return Math.abs(Math.floor(v/60)) + " min " + (v == 0 ? "" : (v >0 ? "early":"late")) | |
} | |
function showTooltip(x, y, contents) { | |
$('<div id="tooltip">' + contents + '</div>').css( { | |
position: 'absolute', | |
display: 'none', | |
top: y + 5, | |
left: x + 5, | |
border: '1px solid #fdd', | |
padding: '2px', | |
'background-color': '#fee', | |
opacity: 0.80 | |
}).appendTo("body").fadeIn(200); | |
} | |
var previousPoint = null; | |
$("#placeholder").bind("plothover", function (event, pos, item) { | |
$("#x").text(pos.x.toFixed(2)); | |
$("#y").text(pos.y.toFixed(2)); | |
if (item) { | |
if (previousPoint != item.dataIndex) { | |
previousPoint = item.dataIndex; | |
$("#tooltip").remove(); | |
var x = item.datapoint[0].toFixed(2), | |
y = item.datapoint[1].toFixed(2); | |
var d = new Date(); | |
d.setTime(x); | |
var time = d.getUTCHours() +':'+ (d.getUTCMinutes().toString().length == 1 ? '0'+ d.getMinutes(): d.getUTCMinutes()) | |
showTooltip(item.pageX, item.pageY, | |
item.series.label + " at "+ time +" = " + Math.abs(new Number(y/60).toFixed(2))+" minutes "+(y >0 ? "early":"late")); | |
} | |
} | |
else { | |
$("#tooltip").remove(); | |
previousPoint = null; | |
} | |
}); | |
</script> | |
<?php | <?php |
include ('../include/common.inc.php'); | include ('../include/common.inc.php'); |
include_header("MyWay Balance", "mywayBalance", false, false, true); | include_header("MyWay Balance", "mywayBalance", false, false, true); |
echo '<div data-role="page"> | echo '<div data-role="page"> |
<div data-role="header" data-position="inline"> | <div data-role="header" data-position="inline"> |
<a href="' . $_SERVER["HTTP_REFERER"] . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a> | <a href="' . $_SERVER["HTTP_REFERER"] . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a> |
<h1>MyWay Balance</h1> | <h1>MyWay Balance</h1> |
<a href="mywaybalance.php?logout=yes" data-icon="delete" class="ui-btn-right">Logout</a> | <a href="mywaybalance.php?logout=yes" data-icon="delete" class="ui-btn-right">Logout</a> |
</div><!-- /header --> | </div><!-- /header --> |
<a name="maincontent" id="maincontent"></a> | <a name="maincontent" id="maincontent"></a> |
<div data-role="content"> '; | <div data-role="content"> '; |
$return = Array(); | $return = Array(); |
function logout() | function logout() |
{ | { |
setcookie("card_number", "", time() - 60 * 60 * 24 * 100, "/"); | setcookie("card_number", "", time() - 60 * 60 * 24 * 100, "/"); |
setcookie("date", "", time() - 60 * 60 * 24 * 100, "/"); | setcookie("date", "", time() - 60 * 60 * 24 * 100, "/"); |
setcookie("secret_answer", "", time() - 60 * 60 * 24 * 100, "/"); | setcookie("secret_answer", "", time() - 60 * 60 * 24 * 100, "/"); |
setcookie("contribute_myway", "", time() - 60 * 60 * 24 * 100, "/"); | setcookie("contribute_myway", "", time() - 60 * 60 * 24 * 100, "/"); |
} | } |
function printBalance($mywayResult) | function printBalance($mywayResult) |
{ | { |
if (isset($mywayResult['error'])) { | if (isset($mywayResult['error'])) { |
logout(); | logout(); |
echo '<h3><font color="red">' . $mywayResult['error'][0] . "</font></h3>"; | echo '<h3><font color="red">' . $mywayResult['error'][0] . "</font></h3>"; |
} | } |
else { | else { |
echo "<h2>Balance: " . $mywayResult['myway_carddetails']['Card Balance'] . "</h2>"; | echo "<h2>Balance: " . $mywayResult['myway_carddetails']['Card Balance'] . "</h2>"; |
echo '<ul data-role="listview" data-inset="true"><li data-role="list-divider"> Recent Transactions </li>'; | echo '<ul data-role="listview" data-inset="true"><li data-role="list-divider"> Recent Transactions </li>'; |
$txCount = 0; | $txCount = 0; |
foreach ($mywayResult['myway_transactions'] as $transaction) { | foreach ($mywayResult['myway_transactions'] as $transaction) { |
echo "<li>"; | echo "<li>"; |
if ($transaction["Deduction Type"] == "DEFAULT") echo '<img src="css/images/warning.png" alt="Failed to tap off: " class="ui-li-icon">'; | if ($transaction["Deduction Type"] == "DEFAULT") echo '<img src="css/images/warning.png" alt="Failed to tap off: " class="ui-li-icon">'; |
echo "<b>" . $transaction["Date / Time"] . "</b>"; | echo "<b>" . $transaction["Date / Time"] . "</b>"; |
echo "<br><small>" . $transaction["Route"] . " at " . $transaction["Stop Name"] . "<br>"; | echo "<br><small>" . $transaction["Route"] . " at " . $transaction["Stop Name"] . "<br>"; |
echo $transaction["TX Reference No"] . " " . $transaction["TX Type"] . "</small>"; | echo $transaction["TX Reference No"] . " " . $transaction["TX Type"] . "</small>"; |
echo '<p class="ui-li-aside">' . $transaction["TX Amount"] . '</p>'; | echo '<p class="ui-li-aside">' . $transaction["TX Amount"] . '</p>'; |
echo "</li>"; | echo "</li>"; |
$txCount++; | $txCount++; |
if ($txCount > 10) break; | if ($txCount > 10) break; |
} | } |
echo "</ul>"; | echo "</ul>"; |
} | } |
} | } |
function recordMyWayObservations($mywayResult) | function recordMyWayObservations($mywayResult) |
{ | { |
global $conn; | global $conn; |
if (!isset($mywayResult['error'])) { | if (!isset($mywayResult['error'])) { |
$stmt = $conn->prepare("insert into myway_observations (observation_id, myway_stop, time, myway_route) | $stmt = $conn->prepare("insert into myway_observations (observation_id, myway_stop, time, myway_route) |
values (:observation_id, :myway_stop, :time, :myway_route)"); | values (:observation_id, :myway_stop, :time, :myway_route)"); |
$stmt->bindParam(':observation_id', $observation_hash); | $stmt->bindParam(':observation_id', $observation_hash); |
$stmt->bindParam(':myway_stop', $myway_stop); | $stmt->bindParam(':myway_stop', $myway_stop); |
$stmt->bindParam(':time', $timestamp); | $stmt->bindParam(':time', $timestamp); |
$stmt->bindParam(':myway_route', $myway_route); | $stmt->bindParam(':myway_route', $myway_route); |
// insert a record | // insert a record |
$resultCount = 0; | $resultCount = 0; |
foreach ($mywayResult['myway_transactions'] as $transaction) { | foreach ($mywayResult['myway_transactions'] as $transaction) { |
if ($transaction["Stop Name"] != "" && $transaction["Deduction Type"] != "DEFAULT") { | if ($transaction["Stop Name"] != "" && $transaction["Deduction Type"] != "DEFAULT") { |
$observation_hash = md5($mywayResult['myway_carddetails']['MyWay Number'] . $transaction["TX Reference No"]); | $observation_hash = md5($mywayResult['myway_carddetails']['MyWay Number'] . $transaction["TX Reference No"]); |
$timestamp = date("c", strtotime($transaction["Date / Time"])); | $timestamp = date("c", strtotime($transaction["Date / Time"])); |
$myway_stop = $transaction["Stop Name"]; | $myway_stop = $transaction["Stop Name"]; |
$myway_route = $transaction["Route"]; | $myway_route = $transaction["Route"]; |
if ($stmt->execute()) $resultCount++; | if ($stmt->execute()) $resultCount++; |
} | } |
} | } |
echo "<h3>Thanks for participating in the study! $resultCount transactions were recorded</h3>"; | echo "<h3>Thanks for participating in the study! $resultCount transactions were recorded</h3>"; |
} | } |
} | } |
if (isset($_REQUEST['card_number']) && isset($_REQUEST['date']) && isset($_REQUEST['secret_answer'])) { | if (isset($_REQUEST['card_number']) && isset($_REQUEST['date']) && isset($_REQUEST['secret_answer'])) { |
$cardNumber = $_REQUEST['card_number']; | $cardNumber = $_REQUEST['card_number']; |
$date = explode("/", $_REQUEST['date']); | $date = explode("/", $_REQUEST['date']); |
$pwrd = $_REQUEST['secret_answer']; | $pwrd = $_REQUEST['secret_answer']; |
if ($_REQUEST['remember'] == "on") { | if ($_REQUEST['remember'] == "on") { |
setcookie("card_number", $cardNumber, time() + 60 * 60 * 24 * 100, "/"); | setcookie("card_number", $cardNumber, time() + 60 * 60 * 24 * 100, "/"); |
setcookie("date", $_REQUEST['date'], time() + 60 * 60 * 24 * 100, "/"); | setcookie("date", $_REQUEST['date'], time() + 60 * 60 * 24 * 100, "/"); |
setcookie("contribute_myway", $_REQUEST['contribute_myway'], time() + 60 * 60 * 24 * 100, "/"); | setcookie("contribute_myway", $_REQUEST['contribute_myway'], time() + 60 * 60 * 24 * 100, "/"); |
setcookie("secret_answer", $pwrd, time() + 60 * 60 * 24 * 100, "/"); | setcookie("secret_answer", $pwrd, time() + 60 * 60 * 24 * 100, "/"); |
} | } |
$mywayResult = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd") , true); | $mywayResult = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd") , true); |
if ($_REQUEST['contribute_myway'] == "on") recordMyWayObservations($mywayResult); | if ($_REQUEST['contribute_myway'] == "on") recordMyWayObservations($mywayResult); |
printBalance($mywayResult); | printBalance($mywayResult); |
} | } |
else if (isset($_REQUEST['logout'])) { | else if (isset($_REQUEST['logout'])) { |
echo '<center><h3> Logged out of MyWay balance </h3><a href="/index.php">Back to main menu...</a><center>'; | echo '<center><h3> Logged out of MyWay balance </h3><a href="/index.php">Back to main menu...</a><center>'; |
} | } |
else if (isset($_COOKIE['card_number']) && isset($_COOKIE['date']) && isset($_COOKIE['secret_answer'])) { | else if (isset($_COOKIE['card_number']) && isset($_COOKIE['date']) && isset($_COOKIE['secret_answer'])) { |
$cardNumber = $_COOKIE['card_number']; | $cardNumber = $_COOKIE['card_number']; |
$date = explode("/", $_COOKIE['date']); | $date = explode("/", $_COOKIE['date']); |
$pwrd = $_COOKIE['secret_answer']; | $pwrd = $_COOKIE['secret_answer']; |
$mywayResult = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd") , true); | $mywayResult = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd") , true); |
if ($_COOKIE['contribute_myway'] == "on") recordMyWayObservations($mywayResult); | if ($_COOKIE['contribute_myway'] == "on") recordMyWayObservations($mywayResult); |
printBalance($mywayResult); | printBalance($mywayResult); |
} | } |
else { | else { |
$date = (isset($_REQUEST['date']) ? filter_var($_REQUEST['date'], FILTER_SANITIZE_STRING) : date("m/d/Y")); | $date = (isset($_REQUEST['date']) ? filter_var($_REQUEST['date'], FILTER_SANITIZE_STRING) : date("m/d/Y")); |
echo '<form action="" method="post"> | echo '<form action="" method="post"> |
<div data-role="fieldcontain"> | <div data-role="fieldcontain"> |
<label for="card_number">Card number</label> | <label for="card_number">Card number</label> |
<input type="text" name="card_number" id="card_number" value="' . $card_number . '" /> | <input type="text" name="card_number" id="card_number" value="' . $card_number . '" /> |
</div> | </div> |
<div data-role="fieldcontain"> | <div data-role="fieldcontain"> |
<label for="date"> Date of birth </label> | <label for="date"> Date of birth </label> |
<input type="text" name="date" id="date" value="' . $date . '" /> | <input type="text" name="date" id="date" value="' . $date . '" /> |
</div> | </div> |
<div data-role="fieldcontain"> | <div data-role="fieldcontain"> |
<label for="secret_answer"> Secret question answer </label> | <label for="secret_answer"> Secret question answer </label> |
<input type="text" name="secret_answer" id="secret_answer" value="' . $secret_answer . '" /> | <input type="text" name="secret_answer" id="secret_answer" value="' . $secret_answer . '" /> |
</div> | </div> |
<div data-role="fieldcontain"> | <div data-role="fieldcontain"> |
<label for="remember"> Remember these details? </label> | <label for="remember"> Remember these details? </label> |
<input type="checkbox" name="remember" id="remember" checked="yes" /> | <input type="checkbox" name="remember" id="remember" checked="yes" /> |
</div> | </div> |
<div data-role="fieldcontain"> | <div data-role="fieldcontain"> |
<label for="contribute_myway">Contribute MyWay records to timeliness study? </label> | <label for="contribute_myway">Contribute MyWay records to timeliness study? </label> |
<input type="checkbox" name="contribute_myway" id="contribute_myway" checked="no" /> | <input type="checkbox" name="contribute_myway" id="contribute_myway" defaultChecked="no" /> |
</div> | |
<div data-role="fieldcontain"> | |
<label for="accept_warning">I accept that Transport for Canberra <a href="http://transport.act.gov.au/myway/protect.html">advise against the use of third party MyWay applications</a> </label> | |
<input type="checkbox" name="accept_warning" id="accept_warning" defaultChecked="no" /> | |
</div> | </div> |
<input type="submit" value="Go!"></form>'; | <input type="submit" value="Go!"></form>'; |
} | } |
include_footer(); | include_footer(); |
?> | ?> |
<?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 |
include ('include/common.inc.php'); | include ('include/common.inc.php'); |
function navbar() | function navbar() |
{ | { |
echo ' | echo ' |
<div data-role="navbar"> | <div data-role="navbar"> |
<ul> | <ul> |
<li><a href="routeList.php">By Final Destination...</a></li> | <li><a href="routeList.php">By Final Destination...</a></li> |
<li><a href="routeList.php?bynumber=yes">By Number... </a></li> | <li><a href="routeList.php?bynumber=yes">By Number... </a></li> |
<li><a href="routeList.php?bysuburbs=yes">By Suburb... </a></li> | <li><a href="routeList.php?bysuburbs=yes">By Suburb... </a></li> |
<li><a href="routeList.php?nearby=yes">Nearby... </a></li> | <li><a href="routeList.php?nearby=yes">Nearby... </a></li> |
</ul> | </ul> |
</div> | </div> |
'; | '; |
} | } |
if (isset($bysuburbs)) { | if (isset($bysuburbs)) { |
include_header("Routes by Suburb", "routeList"); | include_header("Routes by Suburb", "routeList"); |
navbar(); | navbar(); |
echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; | echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; |
if (!isset($firstLetter)) { | if (!isset($firstLetter)) { |
foreach (range('A', 'Z') as $letter) { | foreach (range('A', 'Z') as $letter) { |
echo "<li><a href=\"routeList.php?firstLetter=$letter&bysuburbs=yes\">$letter...</a></li>\n"; | echo "<li><a href=\"routeList.php?firstLetter=$letter&bysuburbs=yes\">$letter...</a></li>\n"; |
} | } |
} | } |
else { | else { |
foreach ($suburbs as $suburb) { | foreach ($suburbs as $suburb) { |
if (startsWith($suburb, $firstLetter)) { | if (startsWith($suburb, $firstLetter)) { |
echo '<li><a href="routeList.php?suburb=' . urlencode($suburb) . '">' . $suburb . '</a></li>'; | echo '<li><a href="routeList.php?suburb=' . urlencode($suburb) . '">' . $suburb . '</a></li>'; |
} | } |
} | } |
} | } |
echo '</ul>'; | echo '</ul>'; |
} | } |
else if (isset($nearby) || isset($suburb)) { | else if (isset($nearby) || isset($suburb)) { |
$routes = Array(); | $routes = Array(); |
if ($suburb) { | if ($suburb) { |
include_header($suburb . " - " . ucwords(service_period()) , "routeList"); | include_header($suburb . " - " . ucwords(service_period()) , "routeList"); |
navbar(); | navbar(); |
timePlaceSettings(); | timePlaceSettings(); |
trackEvent("Route Lists", "Routes By Suburb", $suburb); | trackEvent("Route Lists", "Routes By Suburb", $suburb); |
$routes = getRoutesBySuburb($suburb); | $routes = getRoutesBySuburb($suburb); |
} | } |
if (isset($nearby)) { | if (isset($nearby)) { |
include_header("Routes Nearby", "routeList", true, true); | include_header("Routes Nearby", "routeList", true, true); |
trackEvent("Route Lists", "Routes Nearby", $_SESSION['lat'] . "," . $_SESSION['lon']); | trackEvent("Route Lists", "Routes Nearby", $_SESSION['lat'] . "," . $_SESSION['lon']); |
navbar(); | navbar(); |
timePlaceSettings(true); | placeSettings(); |
if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") { | if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") { |
include_footer(); | include_footer(); |
die(); | die(); |
} | } |
$routes = getRoutesNearby($_SESSION['lat'], $_SESSION['lon']); | $routes = getRoutesNearby($_SESSION['lat'], $_SESSION['lon']); |
} | } |
echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; | echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; |
if ($routes) { | if ($routes) { |
foreach ($routes as $route) { | foreach ($routes as $route) { |
echo '<li><a href="trip.php?routeid=' . $route['route_id'] . '"><h3>' . $route['route_short_name'] . "</h3><p>" . $route['route_long_name'] . " (" . ucwords($route['service_id']) . ")</p>"; | echo '<li><a href="trip.php?routeid=' . $route['route_id'] . '"><h3>' . $route['route_short_name'] . "</h3><p>" . $route['route_long_name'] . " (" . ucwords($route['service_id']) . ")</p>"; |
if (isset($nearby)) { | if (isset($nearby)) { |
$time = getTimeInterpolatedRouteAtStop($route['route_id'], $route['stop_id']); | $time = getTimeInterpolatedRouteAtStop($route['route_id'], $route['stop_id']); |
echo '<span class="ui-li-count">' . ($time['arrival_time'] ? $time['arrival_time'] : "No more trips today") . "<br>" . floor($route['distance']) . 'm away</span>'; | echo '<span class="ui-li-count">' . ($time['arrival_time'] ? $time['arrival_time'] : "No more trips today") . "<br>" . floor($route['distance']) . 'm away</span>'; |
} | } |
echo "</a></li>\n"; | echo "</a></li>\n"; |
} | } |
} | } |
else { | else { |
echo "<li style='text-align: center;'> No routes nearby.</li>"; | echo "<li style='text-align: center;'> No routes nearby.</li>"; |
} | } |
} | } |
else if (isset($bynumber) || isset($numberSeries)) { | else if (isset($bynumber) || isset($numberSeries)) { |
include_header("Routes by Number", "routeList"); | include_header("Routes by Number", "routeList"); |
navbar(); | navbar(); |
echo ' <ul data-role="listview" data-inset="true">'; | echo ' <ul data-role="listview" data-inset="true">'; |
if (isset($bynumber)) { | if (isset($bynumber)) { |
$routes = getRoutesByNumber(); | $routes = getRoutesByNumber(); |
$routeSeries = Array(); | $routeSeries = Array(); |
$seriesRange = Array(); | $seriesRange = Array(); |
foreach ($routes as $key => $routeNumber) { | foreach ($routes as $key => $routeNumber) { |
foreach (explode(" ", $routeNumber['route_short_name']) as $routeNumber) { | foreach (explode(" ", $routeNumber['route_short_name']) as $routeNumber) { |
$seriesNum = substr($routeNumber, 0, -1) . "0"; | $seriesNum = substr($routeNumber, 0, -1) . "0"; |
if ($seriesNum == "0") $seriesNum = $routeNumber; | if ($seriesNum == "0") $seriesNum = $routeNumber; |
$finalDigit = substr($routeNumber, sizeof($routeNumber) - 1, 1); | $finalDigit = substr($routeNumber, sizeof($routeNumber) - 1, 1); |
if (isset($seriesRange[$seriesNum])) { | if (isset($seriesRange[$seriesNum])) { |
if ($finalDigit < $seriesRange[$seriesNum]['max']) $seriesRange[$seriesNum]['max'] = $routeNumber; | if ($finalDigit < $seriesRange[$seriesNum]['max']) $seriesRange[$seriesNum]['max'] = $routeNumber; |
if ($finalDigit > $seriesRange[$seriesNum]['min']) $seriesRange[$seriesNum]['min'] = $routeNumber; | if ($finalDigit > $seriesRange[$seriesNum]['min']) $seriesRange[$seriesNum]['min'] = $routeNumber; |
} | } |
else { | else { |
$seriesRange[$seriesNum]['max'] = $routeNumber; | $seriesRange[$seriesNum]['max'] = $routeNumber; |
$seriesRange[$seriesNum]['min'] = $routeNumber; | $seriesRange[$seriesNum]['min'] = $routeNumber; |
} | } |
$routeSeries[$seriesNum][$seriesNum . "-" . $row[1] . "-" . $row[0]] = $row; | $routeSeries[$seriesNum][$seriesNum . "-" . $row[1] . "-" . $row[0]] = $row; |
} | } |
} | } |
ksort($routeSeries); | ksort($routeSeries); |
ksort($seriesRange); | ksort($seriesRange); |
foreach ($routeSeries as $series => $routes) { | foreach ($routeSeries as $series => $routes) { |
echo '<li><a href="' . curPageURL() . '/routeList.php?numberSeries=' . $series . '">'; | echo '<li><a href="' . curPageURL() . '/routeList.php?numberSeries=' . $series . '">'; |
if ($series <= 9) echo $series; | if ($series <= 9) echo $series; |
else echo "{$seriesRange[$series]['min']}-{$seriesRange[$series]['max']}"; | else echo "{$seriesRange[$series]['min']}-{$seriesRange[$series]['max']}"; |
echo "</a></li>\n"; | echo "</a></li>\n"; |
} | } |
} | } |
else if ($numberSeries) { | else if ($numberSeries) { |
$routes = getRoutesByNumberSeries($numberSeries); | $routes = getRoutesByNumberSeries($numberSeries); |
foreach ($routes as $route) { | foreach ($routes as $route) { |
echo '<li> <a href="trip.php?routeid=' . $route['route_id'] . '"><h3>' . $route['route_short_name'] . "</h3><p>" . $route['route_long_name'] . " (" . ucwords($route['service_id']) . ")</p></a></li>\n"; | echo '<li> <a href="trip.php?routeid=' . $route['route_id'] . '"><h3>' . $route['route_short_name'] . "</h3><p>" . $route['route_long_name'] . " (" . ucwords($route['service_id']) . ")</p></a></li>\n"; |
} | } |
} | } |
} | } |
else { | else { |
include_header("Routes by Destination", "routeList"); | include_header("Routes by Destination", "routeList"); |
navbar(); | navbar(); |
echo ' <ul data-role="listview" data-inset="true">'; | echo ' <ul data-role="listview" data-inset="true">'; |
if (isset($routeDestination)) { | if (isset($routeDestination)) { |
foreach (getRoutesByDestination($routeDestination) as $route) { | foreach (getRoutesByDestination($routeDestination) as $route) { |
echo '<li><a href="trip.php?routeid=' . $route["route_id"] . '"><h3>' . $route["route_short_name"] . '</h3><p>' . $route["route_long_name"] . " (" . ucwords($route['service_id']) . ")</p></a></li>\n"; | echo '<li><a href="trip.php?routeid=' . $route["route_id"] . '"><h3>' . $route["route_short_name"] . '</h3><p>' . $route["route_long_name"] . " (" . ucwords($route['service_id']) . ")</p></a></li>\n"; |
} | } |
} | } |
else { | else { |
foreach (getRoutesByDestination() as $destination) { | foreach (getRoutesByDestination() as $destination) { |
echo '<li><a href="' . curPageURL() . '/routeList.php?routeDestination=' . urlencode($destination['route_long_name']) . '">' . $destination['route_long_name'] . "... </a></li>\n"; | echo '<li><a href="' . curPageURL() . '/routeList.php?routeDestination=' . urlencode($destination['route_long_name']) . '">' . $destination['route_long_name'] . "... </a></li>\n"; |
} | } |
} | } |
} | } |
echo "</ul>\n"; | echo "</ul>\n"; |
include_footer(); | include_footer(); |
?> | ?> |
<?php | <?php |
include ('include/common.inc.php'); | include ('include/common.inc.php'); |
/* | /* |
also need last modified epoch of client gtfs | also need last modified epoch of client gtfs |
- add,remove,patch | - add,remove,patch |
- stop | - stop |
- trip | - trip |
- network | - network |
- patterns (WHERE=) | - patterns (WHERE=) |
- route (short_name or route_id) | - route (short_name or route_id) |
- street | - street |
- stop | - stop |
- trip */ | - trip */ |
$return = Array(); | $return = Array(); |
$return['header']['gtrtfs_version'] = "1"; | $return['header']['gtrtfs_version'] = "1"; |
$return['header']['timestamp'] = time(); | $return['header']['timestamp'] = time(); |
$return['entities'] = Array(); | $return['entities'] = Array(); |
foreach(getCurrentAlerts() as $alert) { | foreach(getCurrentAlerts() as $alert) { |
$informedEntities = getInformedAlerts($alert['id'],$_REQUEST['filter_class'],$_REQUEST['filter_id']); | $informedEntities = getInformedAlerts($alert['id'],$_REQUEST['filter_class'],$_REQUEST['filter_id']); |
if (sizeof($informedEntities) >0) { | if (sizeof($informedEntities) >0) { |
$entity = Array(); | $entity = Array(); |
$entity['id'] = $alert['id']; | $entity['id'] = $alert['id']; |
$entity['alert']['active_period']['start'] = $alert['start']; | $entity['alert']['active_period']['start'] = $alert['start']; |
$entity['alert']['active_period']['start'] = $alert['end']; | $entity['alert']['active_period']['start'] = $alert['end']; |
$entity['alert']['url']['translation'] = $alert['url']; | $entity['alert']['url']['translation'] = $alert['url']; |
$entity['alert']['description']['translation'] = $alert['description']; | $entity['alert']['description']['translation'] = $alert['description']; |
foreach ($informedEntities as $informedEntity) { | foreach ($informedEntities as $informedEntity) { |
$informed = Array(); | $informed = Array(); |
$informed[$informedEntity['informed_class']."_id"] = $informedEntity['informed_id']; | $informed[$informedEntity['informed_class']."_id"] = $informedEntity['informed_id']; |
if ($informedEntity['informed_action'] != "") $informed["x-action"] = $informedEntity['informed_action']; | if ($informedEntity['informed_action'] != "") $informed["x-action"] = $informedEntity['informed_action']; |
//$informed[$informedEntity['class']."_type"] = $informedEntity['type']; | //$informed[$informedEntity['class']."_type"] = $informedEntity['type']; |
$entity['informed'][] = $informed; | $entity['informed'][] = $informed; |
} | } |
$return['entities'][] = $entity; | $return['entities'][] = $entity; |
} | } |
} | } |
//header('Content-Type: text/javascript; charset=utf8'); | header('Content-Type: text/javascript; charset=utf8'); |
// header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/'); | // header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/'); |
header('Access-Control-Max-Age: 3628800'); | header('Access-Control-Max-Age: 3628800'); |
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); | header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); |
if (isset($_GET['callback'])) { | if (isset($_GET['callback'])) { |
$json = '(' . json_encode($return) . ');'; //must wrap in parens and end with semicolon | $json = '(' . json_encode($return) . ');'; //must wrap in parens and end with semicolon |
//print_r($_GET['callback'] . $json); //callback is prepended for json-p | //print_r($_GET['callback'] . $json); //callback is prepended for json-p |
} | } |
else echo json_encode($return); | else echo json_encode($return); |
?> | ?> |
<?php | <?php |
include ('include/common.inc.php'); | include ('include/common.inc.php'); |
$last_updated = date('Y-m-d',@filemtime('cbrfeed.zip')); | $last_updated = date('Y-m-d',@filemtime('cbrfeed.zip')); |
header("Content-Type: text/xml"); | header("Content-Type: text/xml"); |
echo "<?xml version='1.0' encoding='UTF-8'?>"; | echo "<?xml version='1.0' encoding='UTF-8'?>"; |
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n"; | echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:geo="http://www.google.com/geo/schemas/sitemap/1.0">' . "\n"; |
echo " <url><loc>".curPageURL()."index.php</loc><priority>1.0</priority></url>\n"; | echo " <url><loc>".curPageURL()."index.php</loc><priority>1.0</priority></url>\n"; |
foreach (scandir("./") as $file) { | foreach (scandir("./") as $file) { |
if (strpos($file,".php") !== false && $file != "index.php" && $file != "sitemap.xml.php") echo " <url><loc>".curPageURL()."$file</loc><priority>0.3</priority></url>\n"; | if (strpos($file,".php") !== false && $file != "index.php" && $file != "sitemap.xml.php") echo " <url><loc>".curPageURL()."$file</loc><priority>0.3</priority></url>\n"; |
} | |
foreach (scandir("./labs") as $file) { | |
if (strpos($file,".php") !== false) echo " <url><loc>".curPageURL()."/labs/$file</loc><priority>0.3</priority></url>\n"; | |
} | } |
foreach (getStops() as $stop) { | foreach (getStops() as $stop) { |
echo " <url><loc>".curPageURL()."stop.php?stopid=".htmlspecialchars ($stop["stop_id"])."</loc>"; | echo " <url><loc>".curPageURL()."stop.php?stopid=".htmlspecialchars ($stop["stop_id"])."</loc>"; |
echo "<lastmod>" . $last_updated . "</lastmod>"; | echo "<lastmod>" . $last_updated . "</lastmod>"; |
echo "<changefreq>monthly</changefreq>"; | echo "<changefreq>monthly</changefreq>"; |
echo "<priority>0.9</priority>"; | echo "<priority>0.9</priority>"; |
echo "</url>\n"; | echo "</url>\n"; |
} | } |
foreach (getRoutes() as $route) { | foreach (getRoutes() as $route) { |
echo " <url><loc>".curPageURL()."trip.php?routeid=".htmlspecialchars ($route["route_id"])."</loc>"; | echo " <url><loc>".curPageURL()."trip.php?routeid=".htmlspecialchars ($route["route_id"])."</loc>"; |
echo "<lastmod>" . $last_updated . "</lastmod>"; | echo "<lastmod>" . $last_updated . "</lastmod>"; |
echo "<changefreq>monthly</changefreq>"; | echo "<changefreq>monthly</changefreq>"; |
echo "<priority>0.9</priority>"; | echo "<priority>0.9</priority>"; |
echo "</url>\n"; | echo "</url>\n"; |
} | } |
// geosite map | // geosite map |
foreach (getRoutes() as $route) { | foreach (getRoutes() as $route) { |
echo " <url><loc>".curPageURL()."geo/route.kml.php?routeid=".htmlspecialchars ($route["route_id"])."</loc>"; | echo " <url><loc>".curPageURL()."geo/route.kml.php?routeid=".htmlspecialchars ($route["route_id"])."</loc>"; |
echo "<lastmod>" . $last_updated . "</lastmod>"; | echo "<lastmod>" . $last_updated . "</lastmod>"; |
echo "<geo:geo> | echo "<geo:geo> |
<geo:format>kml</geo:format> | <geo:format>kml</geo:format> |
</geo:geo>"; | </geo:geo>"; |
echo "</url>\n"; | echo "</url>\n"; |
} | } |
echo '</urlset>'; | echo '</urlset>'; |
?> | ?> |
<?php | <?php |
include ('include/common.inc.php'); | include ('include/common.inc.php'); |
if ($stopid) $stop = getStop($stopid); | if ($stopid) $stop = getStop($stopid); |
/*if ($stopcode != "" && $stop[5] != $stopcode) { | /*if ($stopcode != "" && $stop[5] != $stopcode) { |
$url = $APIurl . "/json/stopcodesearch?q=" . $stopcode; | $url = $APIurl . "/json/stopcodesearch?q=" . $stopcode; |
$stopsearch = json_decode(getPage($url)); | $stopsearch = json_decode(getPage($url)); |
$stopid = $stopsearch[0][0]; | $stopid = $stopsearch[0][0]; |
$url = $APIurl . "/json/stop?stop_id=" . $stopid; | $url = $APIurl . "/json/stop?stop_id=" . $stopid; |
$stop = json_decode(getPage($url)); | $stop = json_decode(getPage($url)); |
} | } |
if (!startsWith($stop[5], "Wj") && strpos($stop[1], "Platform") === false) { | if (!startsWith($stop[5], "Wj") && strpos($stop[1], "Platform") === false) { |
// expand out to all platforms | // expand out to all platforms |
}*/ | }*/ |
$stops = Array(); | $stops = Array(); |
$stopPositions = Array(); | $stopPositions = Array(); |
$stopNames = Array(); | $stopNames = Array(); |
$tripStopNumbers = Array(); | $tripStopNumbers = Array(); |
$allStopsTrips = Array(); | $allStopsTrips = Array(); |
$fetchedTripSequences = Array(); | $fetchedTripSequences = Array(); |
$stopLinks = ""; | $stopLinks = ""; |
if (isset($stopids)) { | if (isset($stopids)) { |
foreach ($stopids as $sub_stopid) { | foreach ($stopids as $sub_stopid) { |
$stops[] = getStop($sub_stopid); | $stops[] = getStop($sub_stopid); |
} | } |
$stop = $stops[0]; | $stop = $stops[0]; |
$stopid = $stops[0]["stop_id"]; | $stopid = $stops[0]["stop_id"]; |
$stopLinks.= "Individual stop pages: "; | $stopLinks.= "Individual stop pages: "; |
foreach ($stops as $key => $sub_stop) { | foreach ($stops as $key => $sub_stop) { |
// $stopNames[$key] = $sub_stop[1] . ' Stop #' . ($key + 1); | // $stopNames[$key] = $sub_stop[1] . ' Stop #' . ($key + 1); |
if (strpos($stop["stop_name"], "Station")) { | if (strpos($stop["stop_name"], "Station")) { |
$stopNames[$key] = 'Platform ' . ($key + 1); | $stopNames[$key] = 'Platform ' . ($key + 1); |
$stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . '</a> '; | $stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . '</a> '; |
} | } |
else { | else { |
$stopNames[$key] = '#' . ($key + 1); | $stopNames[$key] = '#' . ($key + 1); |
$stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . ' Stop #' . ($key + 1) . '</a> '; | $stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . ' Stop #' . ($key + 1) . '</a> '; |
} | } |
$stopPositions[$key] = Array( | $stopPositions[$key] = Array( |
$sub_stop["stop_lat"], | $sub_stop["stop_lat"], |
$sub_stop["stop_lon"] | $sub_stop["stop_lon"] |
); | ); |
$trips = getStopTrips($sub_stop["stop_id"]); | $trips = getStopTrips($sub_stop["stop_id"]); |
$tripSequence = ""; | $tripSequence = ""; |
foreach ($trips as $trip) { | foreach ($trips as $trip) { |
$tripSequence.= "{$trip['trip_id']},"; | $tripSequence.= "{$trip['trip_id']},"; |
$tripStopNumbers[$trip['trip_id']][] = $key; | $tripStopNumbers[$trip['trip_id']][] = $key; |
} | } |
if (!in_array($tripSequence, $fetchedTripSequences)) { | if (!in_array($tripSequence, $fetchedTripSequences)) { |
// only fetch new trip sequences | // only fetch new trip sequences |
$fetchedTripSequences[] = $tripSequence; | $fetchedTripSequences[] = $tripSequence; |
$trips = getStopTripsWithTimes($sub_stop["stop_id"]); | $trips = getStopTripsWithTimes($sub_stop["stop_id"]); |
foreach ($trips as $trip) { | foreach ($trips as $trip) { |
if (!isset($allStopsTrips[$trip["trip_id"]])) $allStopsTrips[$trip["trip_id"]] = $trip; | if (!isset($allStopsTrips[$trip["trip_id"]])) $allStopsTrips[$trip["trip_id"]] = $trip; |
} | } |
} | } |
//else { | //else { |
// echo "skipped sequence $tripSequence"; | // echo "skipped sequence $tripSequence"; |
//} | //} |
} | } |
} | } |
include_header($stop['stop_name'], "stop"); | include_header($stop['stop_name'], "stop"); |
/*$serviceAlerts = json_decode(getPage(curPageURL() . "/servicealerts_api.php?filter_class=stop&filter_id=".$stopid) , true); | /*$serviceAlerts = json_decode(getPage(curPageURL() . "/servicealerts_api.php?filter_class=stop&filter_id=".$stopid) , true); |
foreach($serviceAlerts['entities'] as $serviceAlert) { | foreach($serviceAlerts['entities'] as $serviceAlert) { |
echo '<div id="servicewarning">'.$serviceAlert['alert']['description']['translation'].'</div>'; | echo '<div id="servicewarning">'.$serviceAlert['alert']['description']['translation'].'</div>'; |
}*/ | }*/ |
echo '<span class="content-secondary">'; | echo '<span class="content-secondary">'; |
echo $stopLinks; | echo $stopLinks; |
if (sizeof($stops) > 0) { | if (sizeof($stops) > 0) { |
trackEvent("View Stops", "View Combined Stops", $stop["stop_name"], $stop["stop_id"]); | trackEvent("View Stops", "View Combined Stops", $stop["stop_name"], $stop["stop_id"]); |
echo staticmap($stopPositions); | echo staticmap($stopPositions); |
} | } |
else { | else { |
trackEvent("View Stops", "View Single Stop", $stop["stop_name"], $stop["stop_id"]); | trackEvent("View Stops", "View Single Stop", $stop["stop_name"], $stop["stop_id"]); |
echo staticmap(Array( | echo staticmap(Array( |
0 => Array( | 0 => Array( |
$stop["stop_lat"], | $stop["stop_lat"], |
$stop["stop_lon"] | $stop["stop_lon"] |
) | ) |
)) ; | )) ; |
} | } |
timePlaceSettings(); | |
// time settings | |
echo '<div id="settings" data-role="collapsible" data-collapsed="true"> | |
<h3>Change Time (' . (isset($_SESSION['time']) ? $_SESSION['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3> | |
<form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post"> | |
<div class="ui-body"> | |
<div data-role="fieldcontain"> | |
<label for="time"> Time: </label> | |
<input type="time" name="time" id="time" value="' . (isset($_SESSION['time']) ? $_SESSION['time'] : date("H:i")) . '"/> | |
<a href="#" name="currentTime" id="currentTime" onClick="var d = new Date();' . "$('#time').val(d.getHours() +':'+ (d.getMinutes().toString().length == 1 ? '0'+ d.getMinutes(): d.getMinutes()));" . '">Current Time?</a> | |
</div> | |
<div data-role="fieldcontain"> | |
<label for="service_period"> Service Period: </label> | |
<select name="service_period" id="service_period">'; | |
foreach ($service_periods as $service_period) { | |
echo "<option value=\"$service_period\"" . (service_period() === $service_period ? " SELECTED" : "") . '>' . ucwords($service_period) . '</option>'; | |
} | |
echo '</select> | |
<a href="#" style="display:none" name="currentPeriod" id="currentPeriod">Current Period?</a> | |
</div> | |
<input type="submit" value="Update"/> | |
</div></form> | |
</div>'; | |
echo '</span><span class="content-primary">'; | echo '</span><span class="content-primary">'; |
echo ' <ul data-role="listview" data-inset="true">'; | echo ' <ul data-role="listview" data-inset="true">'; |
if (sizeof($allStopsTrips) > 0) { | if (sizeof($allStopsTrips) > 0) { |
sktimesort($allStopsTrips,"arrival_time", true); | sktimesort($allStopsTrips,"arrival_time", true); |
$trips = $allStopsTrips; | $trips = $allStopsTrips; |
} | } |
else { | else { |
$trips = getStopTripsWithTimes($stopid); | $trips = getStopTripsWithTimes($stopid); |
} | } |
if (sizeof($trips) == 0) { | if (sizeof($trips) == 0) { |
echo "<li style='text-align: center;'>No trips in the near future.</li>"; | echo "<li style='text-align: center;'>No trips in the near future.</li>"; |
} | } |
else { | else { |
foreach ($trips as $trip) { | foreach ($trips as $trip) { |
echo '<li>'; | echo '<li>'; |
echo '<a href="trip.php?stopid=' . $stopid . '&tripid=' . $trip['trip_id'] . '"><h3>' . $trip['route_short_name'] . " " . $trip['route_long_name'] . "</h3><p>"; | echo '<a href="trip.php?stopid=' . $stopid . '&tripid=' . $trip['trip_id'] . '"><h3>' . $trip['route_short_name'] . " " . $trip['route_long_name'] . "</h3><p>"; |
$viaPoints = viaPointNames($trip['trip_id'], $trip['stop_sequence']); | $viaPoints = viaPointNames($trip['trip_id'], $trip['stop_sequence']); |
if ($viaPoints != "") echo '<br><span class="viaPoints">Via: ' . $viaPoints . '</span>'; | if ($viaPoints != "") echo '<br><span class="viaPoints">Via: ' . $viaPoints . '</span>'; |
if (sizeof($tripStopNumbers) > 0) { | if (sizeof($tripStopNumbers) > 0) { |
echo '<br><small>Boarding At: '; | echo '<br><small>Boarding At: '; |
foreach ($tripStopNumbers[$trip['trip_id']] as $key) { | foreach ($tripStopNumbers[$trip['trip_id']] as $key) { |
echo $stopNames[$key] . ' '; | echo $stopNames[$key] . ' '; |
} | } |
echo '</small>'; | echo '</small>'; |
} | } |
echo '</p>'; | echo '</p>'; |
echo '<p class="ui-li-aside"><strong>' . $trip['arrival_time'] . '</strong></p>'; | echo '<p class="ui-li-aside"><strong>' . $trip['arrival_time'] . '</strong></p>'; |
echo '</a></li>'; | echo '</a></li>'; |
flush(); | flush(); |
@ob_flush(); | @ob_flush(); |
} | } |
} | } |
echo '</ul>'; | echo '</ul>'; |
echo '</span>'; | echo '</span>'; |
include_footer(); | include_footer(); |
?> | ?> |
<?php | <?php |
include ('include/common.inc.php'); | include ('include/common.inc.php'); |
$stops = Array(); | $stops = Array(); |
function navbar() | function navbar() |
{ | { |
echo ' | echo ' |
<div data-role="navbar"> | <div data-role="navbar"> |
<ul> | <ul> |
<li><a href="stopList.php">Timing Points</a></li> | <li><a href="stopList.php">Timing Points</a></li> |
<li><a href="stopList.php?bysuburbs=yes">By Suburb</a></li> | <li><a href="stopList.php?bysuburbs=yes">By Suburb</a></li> |
<li><a href="stopList.php?nearby=yes">Nearby Stops</a></li> | <li><a href="stopList.php?nearby=yes">Nearby Stops</a></li> |
<li><a href="stopList.php?allstops=yes">All Stops</a></li> | <li><a href="stopList.php?allstops=yes">All Stops</a></li> |
</ul> | </ul> |
</div> | </div> |
'; | '; |
} | } |
// By suburb | // By suburb |
if (isset($bysuburbs)) { | if (isset($bysuburbs)) { |
include_header("Stops by Suburb", "stopList"); | include_header("Stops by Suburb", "stopList"); |
navbar(); | navbar(); |
echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; | echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; |
if (!isset($firstLetter)) { | if (!isset($firstLetter)) { |
foreach (range('A', 'Z') as $letter) { | foreach (range('A', 'Z') as $letter) { |
echo "<li><a href=\"stopList.php?firstLetter=$letter&bysuburbs=yes\">$letter...</a></li>\n"; | echo "<li><a href=\"stopList.php?firstLetter=$letter&bysuburbs=yes\">$letter...</a></li>\n"; |
} | } |
} | } |
else { | else { |
foreach ($suburbs as $suburb) { | foreach ($suburbs as $suburb) { |
if (startsWith($suburb, $firstLetter)) { | if (startsWith($suburb, $firstLetter)) { |
echo '<li><a href="stopList.php?suburb=' . urlencode($suburb) . '">' . $suburb . '</a></li>'; | echo '<li><a href="stopList.php?suburb=' . urlencode($suburb) . '">' . $suburb . '</a></li>'; |
} | } |
} | } |
} | } |
echo '</ul>'; | echo '</ul>'; |
} | } |
else { | else { |
// Timing Points / All stops | // Timing Points / All stops |
if (isset($allstops)) { | if (isset($allstops)) { |
$listType = 'allstops=yes'; | $listType = 'allstops=yes'; |
$stops = getStops(); | $stops = getStops(); |
include_header("All Stops", "stopList"); | include_header("All Stops", "stopList"); |
navbar(); | navbar(); |
timePlaceSettings(); | |
} | } |
else if (isset($nearby)) { | else if (isset($nearby)) { |
$listType = 'nearby=yes'; | $listType = 'nearby=yes'; |
include_header("Nearby Stops", "stopList", true, true); | include_header("Nearby Stops", "stopList", true, true); |
trackEvent("Stop Lists", "Stops Nearby", $_SESSION['lat'] . "," . $_SESSION['lon']); | trackEvent("Stop Lists", "Stops Nearby", $_SESSION['lat'] . "," . $_SESSION['lon']); |
navbar(); | navbar(); |
if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") { | if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") { |
timePlaceSettings(true); | placeSettings(); |
include_footer(); | include_footer(); |
die(); | die(); |
} | } |
$stops = getNearbyStops($_SESSION['lat'], $_SESSION['lon'], 15); | $stops = getNearbyStops($_SESSION['lat'], $_SESSION['lon'], 15); |
echo '<span class="content-secondary">'; | echo '<span class="content-secondary">'; |
$stopPositions[] = Array( | $stopPositions[] = Array( |
$_SESSION['lat'], | $_SESSION['lat'], |
$_SESSION['lon'] | $_SESSION['lon'] |
); | ); |
foreach ($stops as $sub_stop) { | foreach ($stops as $sub_stop) { |
$stopPositions[] = Array( | $stopPositions[] = Array( |
$sub_stop["stop_lat"], | $sub_stop["stop_lat"], |
$sub_stop["stop_lon"] | $sub_stop["stop_lon"] |
); | ); |
} | } |
echo staticmap($stopPositions, 0, "iconb", true, true); | echo staticmap($stopPositions, 0, "iconb", true, true); |
timePlaceSettings(true); | placeSettings(); |
echo '</span><span class="content-primary">'; | echo '</span><span class="content-primary">'; |
} | } |
else if (isset($suburb)) { | else if (isset($suburb)) { |
$stops = getStopsBySuburb($suburb); | $stops = getStopsBySuburb($suburb); |
include_header("Stops in " . ucwords($suburb) , "stopList"); | include_header("Stops in " . ucwords($suburb) , "stopList"); |
navbar(); | navbar(); |
trackEvent("Stop Lists", "Stops By Suburb", $suburb); | trackEvent("Stop Lists", "Stops By Suburb", $suburb); |
} | } |
else { | else { |
$stops = getStops(true, $firstLetter); | $stops = getStops(true, $firstLetter); |
include_header("Timing Points / Major Stops", "stopList"); | include_header("Timing Points / Major Stops", "stopList"); |
navbar(); | navbar(); |
timePlaceSettings(); | |
} | } |
echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; | echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; |
if (!isset($firstLetter) && !isset($suburb) && !isset($nearby)) { | if (!isset($firstLetter) && !isset($suburb) && !isset($nearby)) { |
foreach (range('A', 'Z') as $letter) { | foreach (range('A', 'Z') as $letter) { |
echo "<li><a href=\"stopList.php?firstLetter=$letter&$listType\">$letter...</a></li>\n"; | echo "<li><a href=\"stopList.php?firstLetter=$letter&$listType\">$letter...</a></li>\n"; |
} | } |
} | } |
else { | else { |
//var_dump($stops); | //var_dump($stops); |
$stopsGrouped = Array(); | $stopsGrouped = Array(); |
foreach ($stops as $key => $stop) { | foreach ($stops as $key => $stop) { |
if ((trim(preg_replace("/\(Platform.*/", "", $stops[$key]["stop_name"])) != trim(preg_replace("/\(Platform.*/", "", $stops[$key + 1]["stop_name"]))) || $key + 1 >= sizeof($stops)) { | if ((trim(preg_replace("/\(Platform.*/", "", $stops[$key]["stop_name"])) != trim(preg_replace("/\(Platform.*/", "", $stops[$key + 1]["stop_name"]))) || $key + 1 >= sizeof($stops)) { |
if (sizeof($stopsGrouped) > 0) { | if (sizeof($stopsGrouped) > 0) { |
// print and empty grouped stops | // print and empty grouped stops |
// subsequent duplicates | // subsequent duplicates |
$stopsGrouped["stop_ids"][] = $stop['stop_id']; | $stopsGrouped["stop_ids"][] = $stop['stop_id']; |
echo '<li>'; | echo '<li>'; |
if (!startsWith($stopsGrouped['stop_codes'][0], "Wj")) echo '<img src="css/images/time.png" alt="Timing Point: " class="ui-li-icon">'; | if (!startsWith($stopsGrouped['stop_codes'][0], "Wj")) echo '<img src="css/images/time.png" alt="Timing Point: " class="ui-li-icon">'; |
echo '<a href="stop.php?stopids=' . implode(",", $stopsGrouped['stop_ids']) . '">'; | echo '<a href="stop.php?stopids=' . implode(",", $stopsGrouped['stop_ids']) . '">'; |
if (isset($_SESSION['lat']) && isset($_SESSION['lon'])) { | if (isset($_SESSION['lat']) && isset($_SESSION['lon'])) { |
echo '<span class="ui-li-count">' . distance($stop['stop_lat'], $stop['stop_lon'], $_SESSION['lat'], $_SESSION['lon'], true) . 'm away</span>'; | echo '<span class="ui-li-count">' . distance($stop['stop_lat'], $stop['stop_lon'], $_SESSION['lat'], $_SESSION['lon'], true) . 'm away</span>'; |
} | } |
echo bracketsMeanNewLine(trim(preg_replace("/\(Platform.*/", "", $stop['stop_name'])) . '(' . sizeof($stopsGrouped["stop_ids"]) . ' stops)'); | echo bracketsMeanNewLine(trim(preg_replace("/\(Platform.*/", "", $stop['stop_name'])) . '(' . sizeof($stopsGrouped["stop_ids"]) . ' stops)'); |
echo "</a></li>\n"; | echo "</a></li>\n"; |
flush(); | flush(); |
@ob_flush(); | @ob_flush(); |
$stopsGrouped = Array(); | $stopsGrouped = Array(); |
} | } |
else { | else { |
// just a normal stop | // just a normal stop |
echo '<li>'; | echo '<li>'; |
if (!startsWith($stop['stop_code'], "Wj")) echo '<img src="css/images/time.png" alt="Timing Point" class="ui-li-icon">'; | if (!startsWith($stop['stop_code'], "Wj")) echo '<img src="css/images/time.png" alt="Timing Point" class="ui-li-icon">'; |
echo '<a href="stop.php?stopid=' . $stop['stop_id'] . (startsWith($stop['stop_code'], "Wj") ? '&stopcode=' . $stop['stop_code'] : "") . '">'; | echo '<a href="stop.php?stopid=' . $stop['stop_id'] . (startsWith($stop['stop_code'], "Wj") ? '&stopcode=' . $stop['stop_code'] : "") . '">'; |
if (isset($_SESSION['lat']) && isset($_SESSION['lon'])) { | if (isset($_SESSION['lat']) && isset($_SESSION['lon'])) { |
echo '<span class="ui-li-count">' . distance($stop['stop_lat'], $stop['stop_lon'], $_SESSION['lat'], $_SESSION['lon'], true) . 'm away</span>'; | echo '<span class="ui-li-count">' . distance($stop['stop_lat'], $stop['stop_lon'], $_SESSION['lat'], $_SESSION['lon'], true) . 'm away</span>'; |
} | } |
echo bracketsMeanNewLine($stop['stop_name']); | echo bracketsMeanNewLine($stop['stop_name']); |
echo "</a></li>\n"; | echo "</a></li>\n"; |
flush(); | flush(); |
@ob_flush(); | @ob_flush(); |
} | } |
} | } |
else { | else { |
// this is a duplicated line item | // this is a duplicated line item |
if ($key - 1 <= 0 || (trim(preg_replace("/\(Platform.*/", "", $stops[$key]['stop_name'])) != trim(preg_replace("/\(Platform.*/", "", $stops[$key - 1]['stop_name'])))) { | if ($key - 1 <= 0 || (trim(preg_replace("/\(Platform.*/", "", $stops[$key]['stop_name'])) != trim(preg_replace("/\(Platform.*/", "", $stops[$key - 1]['stop_name'])))) { |
// first duplicate | // first duplicate |
$stopsGrouped = Array( | $stopsGrouped = Array( |
"name" => trim(preg_replace("/\(Platform.*/", "", $stop['stop_name'])) , | "name" => trim(preg_replace("/\(Platform.*/", "", $stop['stop_name'])) , |
"stop_ids" => Array( | "stop_ids" => Array( |
$stop['stop_id'] | $stop['stop_id'] |
) , | ) , |
"stop_codes" => Array( | "stop_codes" => Array( |
$stop['stop_code'] | $stop['stop_code'] |
) | ) |
); | ); |
} | } |
else { | else { |
// subsequent duplicates | // subsequent duplicates |
$stopsGrouped["stop_ids"][] = $stop['stop_id'];; | $stopsGrouped["stop_ids"][] = $stop['stop_id'];; |
} | } |
} | } |
} | } |
} | } |
echo '</ul>'; | echo '</ul>'; |
if (isset($nearby)) echo '</span>'; | if (isset($nearby)) echo '</span>'; |
} | } |
include_footer(); | include_footer(); |
?> | ?> |
<?php | <?php |
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'); |
// 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"); |
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { | while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { |
if ($line > 0) { | if ($line > 0) { |
$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]}');"; |
} | } |
} | } |
$result = pg_query($conn, $query); | $result = pg_query($conn, $query); |
$line++; | $line++; |
if ($line % 10000 == 0) echo "$line records... \n"; | if ($line % 10000 == 0) echo "$line records... \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"; |
} | } |
} | } |
} | |
?> | ?> |