From: Alexander Sadleir Date: Sun, 11 Sep 2011 06:51:37 +0000 Subject: Labs Tidy up, depreciate old trip planner tester, promote myway balance/service alerts to main site X-Git-Url: http://maxious.lambdacomplex.org/git/?p=busui.git&a=commitdiff&h=7782f02a084d3e83b767baac665abc2fc9c3b0ce --- Labs Tidy up, depreciate old trip planner tester, promote myway balance/service alerts to main site --- --- /dev/null +++ b/.gitignore @@ -1,1 +1,8 @@ +/labs/tiles/12 +/labs/tiles/13 +/labs/tiles/14 +/labs/tiles/15 +/labs/tiles/16 +/labs/tiles/17 +/labs/tiles/19 --- a/about.php +++ b/about.php @@ -21,6 +21,10 @@ , ACT Buses by David Sullivan) and Android (MyBus 2.0 by Imagine Team)
+GTFS-realtime API; +Alerts and Trip Updates (but only Cancelled or Stop Skipped) +Default format binary but can get JSON by adding ?ascii=yes +

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, --- a/aws/awsStartup.sh +++ b/aws/awsStartup.sh @@ -5,38 +5,9 @@ #postgres postgres-server php-pg #http://www.how2forge.org/installing-lighttpd-with-php5-and-mysql-support-on-fedora-12 -cp /root/aws.php /tmp/ -mkdir /var/www/lib/staticmaplite/cache -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 -t httpd_sys_content_rw_t /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 -chmod -R 777 /var/www/labs/tiles -wget http://s3-ap-southeast-1.amazonaws.com/busresources/cbrfeed.zip \ --O /var/www/cbrfeed.zip +sh busuiphp.sh +sh busuidb.sh +sh busuiotp.sh -createdb transitdata -createlang -d transitdata plpgsql -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 -#made with pg_dump transitdata | gzip -c > transitdata.cbrfeed.sql.gz -gunzip /var/www/transitdata.cbrfeed.sql.gz -psql -d transitdata -f /var/www/transitdata.cbrfeed.sql -#createuser transitdata -SDRP -#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,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 -wget http://s3-ap-southeast-1.amazonaws.com/busresources/Graph.obj \ --O /tmp/Graph.obj -rm -rfv /usr/share/tomcat6/webapps/opentripplanner* -wget http://s3-ap-southeast-1.amazonaws.com/busresources/opentripplanner-webapp.war \ --O /usr/share/tomcat6/webapps/opentripplanner-webapp.war -wget http://s3-ap-southeast-1.amazonaws.com/busresources/opentripplanner-api-webapp.war \ --O /usr/share/tomcat6/webapps/opentripplanner-api-webapp.war -/etc/init.d/tomcat6 restart --- /dev/null +++ b/aws/busuidb.sh @@ -1,1 +1,14 @@ - +createdb transitdata +createlang -d transitdata plpgsql +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 +#made with pg_dump transitdata | gzip -c > transitdata.cbrfeed.sql.gz +gunzip /var/www/transitdata.cbrfeed.sql.gz +psql -d transitdata -f /var/www/transitdata.cbrfeed.sql +#createuser transitdata -SDRP +#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,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 --- /dev/null +++ b/aws/busuiotp.sh @@ -1,1 +1,10 @@ +wget http://s3-ap-southeast-1.amazonaws.com/busresources/Graph.obj \ +-O /tmp/Graph.obj +/etc/init.d/tomcat6 stop +rm -rfv /usr/share/tomcat6/webapps/opentripplanner* +wget http://s3-ap-southeast-1.amazonaws.com/busresources/opentripplanner-webapp.war \ +-O /usr/share/tomcat6/webapps/opentripplanner-webapp.war +wget http://s3-ap-southeast-1.amazonaws.com/busresources/opentripplanner-api-webapp.war \ +-O /usr/share/tomcat6/webapps/opentripplanner-api-webapp.war +/etc/init.d/tomcat6 restart --- /dev/null +++ b/aws/busuiotp.testing.sh @@ -1,1 +1,10 @@ +wget http://s3-ap-southeast-1.amazonaws.com/busresources/testing/Graph.obj \ +-O /tmp/Graph.obj +/etc/init.d/tomcat6 stop +rm -rfv /usr/share/tomcat6/webapps/opentripplanner* +wget http://s3-ap-southeast-1.amazonaws.com/busresources/testing/opentripplanner-webapp.war \ +-O /usr/share/tomcat6/webapps/opentripplanner-webapp.war +wget http://s3-ap-southeast-1.amazonaws.com/busresources/testing/opentripplanner-api-webapp.war \ +-O /usr/share/tomcat6/webapps/opentripplanner-api-webapp.war +/etc/init.d/tomcat6 restart --- /dev/null +++ b/aws/busuiphp.sh @@ -1,1 +1,16 @@ +cp /root/aws.php /tmp/ +mkdir /var/www/lib/staticmaplite/cache +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 -t httpd_sys_content_rw_t /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 +chmod -R 777 /var/www/labs/tiles + +chcon -R -t httpd_sys_content_rw_t /var/www/lib/openid-php/oid_store +chmod -R 777 /var/www/lib/openid-php/oid_store + +wget http://s3-ap-southeast-1.amazonaws.com/busresources/cbrfeed.zip \ +-O /var/www/cbrfeed.zip --- /dev/null +++ b/aws/data-sources.xml @@ -1,1 +1,13 @@ + + + + + + + + + + + --- /dev/null +++ b/include/common-auth.inc.php @@ -1,1 +1,83 @@ +begin($oid_identifier); + + // Create attribute request object + // See http://code.google.com/apis/accounts/docs/OpenID.html#Parameters for parameters + // Usage: make($type_uri, $count=1, $required=false, $alias=null) + $attribute[] = Auth_OpenID_AX_AttrInfo :: make('http://axschema.org/contact/email', 2, 1, 'email'); + $attribute[] = Auth_OpenID_AX_AttrInfo :: make('http://axschema.org/namePerson/first', 1, 1, 'firstname'); + $attribute[] = Auth_OpenID_AX_AttrInfo :: make('http://axschema.org/namePerson/last', 1, 1, 'lastname'); + + // Create AX fetch request + $ax = new Auth_OpenID_AX_FetchRequest; + + // Add attributes to AX fetch request + foreach ($attribute as $attr) { + $ax->add($attr); + } + + // Add AX fetch request to authentication request + $auth->addExtension($ax); + $_SESSION['returnURL'] = curPageURL(); + // Redirect to OpenID provider for authentication + $url = $auth->redirectURL(getTrustRoot(), $_SESSION['returnURL']); + header('Location: ' . $url); +} + +function auth() { + if ($_SESSION['authed'] == true) + return true; + + // Create file storage area for OpenID data + $store = new Auth_OpenID_FileStore('lib/openid-php/oid_store'); + // Create OpenID consumer + $consumer = new Auth_OpenID_Consumer($store); + // Create an authentication request to the OpenID provider + $response = $consumer->complete($_SESSION['returnURL']); + + if ($response->status == Auth_OpenID_SUCCESS) { + // Get registration informations + $ax = new Auth_OpenID_AX_FetchResponse(); + $obj = $ax->fromSuccessResponse($response); + $email = $obj->data['http://axschema.org/contact/email'][0]; + var_dump($email); + if ($email != "maxious@gmail.com") { + die("Access Denied"); + } else { + $_SESSION['authed'] = true; + } + } else { + login(); + } +} + +if ($_REQUEST['janrain_nonce']) + auth(); +?> --- a/include/common-geo.inc.php +++ b/include/common-geo.inc.php @@ -1,153 +1,166 @@ $mapPoint) { - if ($twotone && $index == 0) { - $markers.= $mapPoint[0] . "," . $mapPoint[1] . "," . "iconr" . ($index + 1); - $center = "{$mapPoints[0][0]},{$mapPoints[0][1]}"; - } - else { - $markers.= $mapPoint[0] . "," . $mapPoint[1] . "," . $markerImage . ($index + 1); - } - if ($index + 1 != sizeof($mapPoints)) $markers.= "|"; - $dist = distance($mapPoints[0][0], $mapPoint[0][1], $mapPoint[0], $mapPoint[1]); - $mapwidthinmeters = ($dist > $mapwidthinmeters ? $dist : $mapwidthinmeters); - $totalLat+= $mapPoint[0]; - $totalLon+= $mapPoint[1]; - } - if ($zoom == 0) { - $mapwidthinmeters = distance($minlat, $minlon, $minlat, $maxlon); - foreach (array_reverse($metersperpixel, true) as $zoomLevel => $maxdistance) { - if ($zoom == 0 && $mapwidthinmeters * 1.5 < ($maxdistance)) $zoom = $zoomLevel; - } - } - $center = $totalLat / sizeof($mapPoints) . "," . $totalLon / sizeof($mapPoints); - } - $output = ""; - if ($collapsible) $output.= '

Open Map...

'; - $output.= ''; - if ($collapsible) $output.= '
'; - return $output; + +function staticmap($mapPoints, $zoom = 0, $markerImage = "iconb", $collapsible = true, $twotone = false) { + global $basePath; + $width = 300; + $height = 300; + $metersperpixel[9] = 305.492 * $width; + $metersperpixel[10] = 152.746 * $width; + $metersperpixel[11] = 76.373 * $width; + $metersperpixel[12] = 38.187 * $width; + $metersperpixel[13] = 19.093 * $width; + $metersperpixel[14] = 9.547 * $width; + $metersperpixel[15] = 4.773 * $width; + //$metersperpixel[16] = 2.387 * $width; + // $metersperpixel[17]=1.193*$width; + $center = ""; + $markers = ""; + $mapwidthinmeters = 50; + if (sizeof($mapPoints) < 1) + return "map error"; + if (sizeof($mapPoints) === 1) { + if ($zoom == 0) + $zoom = 14; + $markers.= "{$mapPoints[0][0]},{$mapPoints[0][1]},$markerimage"; + $center = "{$mapPoints[0][0]},{$mapPoints[0][1]}"; + } + else { + foreach ($mapPoints as $index => $mapPoint) { + if ($twotone && $index == 0) { + $markers.= $mapPoint[0] . "," . $mapPoint[1] . "," . "iconr" . ($index + 1); + $center = "{$mapPoints[0][0]},{$mapPoints[0][1]}"; + } else { + $markers.= $mapPoint[0] . "," . $mapPoint[1] . "," . $markerImage . ($index + 1); + } + if ($index + 1 != sizeof($mapPoints)) + $markers.= "|"; + $dist = distance($mapPoints[0][0], $mapPoint[0][1], $mapPoint[0], $mapPoint[1]); + $mapwidthinmeters = ($dist > $mapwidthinmeters ? $dist : $mapwidthinmeters); + $totalLat+= $mapPoint[0]; + $totalLon+= $mapPoint[1]; + } + if ($zoom == 0) { + $mapwidthinmeters = distance($minlat, $minlon, $minlat, $maxlon); + foreach (array_reverse($metersperpixel, true) as $zoomLevel => $maxdistance) { + if ($zoom == 0 && $mapwidthinmeters * 1.5 < ($maxdistance)) + $zoom = $zoomLevel; + } + } + $center = $totalLat / sizeof($mapPoints) . "," . $totalLon / sizeof($mapPoints); + } + $output = ""; + if ($collapsible) + $output.= '

Open Map...

'; + $output.= ''; + if ($collapsible) + $output.= '
'; + return $output; } -function distance($lat1, $lng1, $lat2, $lng2, $roundLargeValues = false) -{ - $pi80 = M_PI / 180; - $lat1*= $pi80; - $lng1*= $pi80; - $lat2*= $pi80; - $lng2*= $pi80; - $r = 6372.797; // mean radius of Earth in km - $dlat = $lat2 - $lat1; - $dlng = $lng2 - $lng1; - $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2); - $c = 2 * atan2(sqrt($a) , sqrt(1 - $a)); - $km = $r * $c; - if ($roundLargeValues) { - if ($km < 1) return floor($km * 1000); - else return round($km, 2) . "k"; - } - else return floor($km * 1000); + +function distance($lat1, $lng1, $lat2, $lng2, $roundLargeValues = false) { + $pi80 = M_PI / 180; + $lat1*= $pi80; + $lng1*= $pi80; + $lat2*= $pi80; + $lng2*= $pi80; + $r = 6372.797; // mean radius of Earth in km + $dlat = $lat2 - $lat1; + $dlng = $lng2 - $lng1; + $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2); + $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); + $km = $r * $c; + if ($roundLargeValues) { + if ($km < 1) + return floor($km * 1000); + else + return round($km, 2) . "k"; + } + else + return floor($km * 1000); } -function decodePolylineToArray($encoded) -{ - // source: http://latlongeeks.com/forum/viewtopic.php?f=4&t=5 - $length = strlen($encoded); - $index = 0; - $points = array(); - $lat = 0; - $lng = 0; - while ($index < $length) { - // Temporary variable to hold each ASCII byte. - $b = 0; - // The encoded polyline consists of a latitude value followed by a - // longitude value. They should always come in pairs. Read the - // latitude value first. - $shift = 0; - $result = 0; - do { - // The `ord(substr($encoded, $index++))` statement returns the ASCII - // code for the character at $index. Subtract 63 to get the original - // value. (63 was added to ensure proper ASCII characters are displayed - // in the encoded polyline string, which is `human` readable) - $b = ord(substr($encoded, $index++)) - 63; - // AND the bits of the byte with 0x1f to get the original 5-bit `chunk. - // Then left shift the bits by the required amount, which increases - // by 5 bits each time. - // OR the value into $results, which sums up the individual 5-bit chunks - // into the original value. Since the 5-bit chunks were reversed in - // order during encoding, reading them in this way ensures proper - // summation. - $result|= ($b & 0x1f) << $shift; - $shift+= 5; - } - // Continue while the read byte is >= 0x20 since the last `chunk` - // was not OR'd with 0x20 during the conversion process. (Signals the end) - while ($b >= 0x20); - // Check if negative, and convert. (All negative values have the last bit - // set) - $dlat = (($result & 1) ? ~($result >> 1) : ($result >> 1)); - // Compute actual latitude since value is offset from previous value. - $lat+= $dlat; - // The next values will correspond to the longitude for this point. - $shift = 0; - $result = 0; - do { - $b = ord(substr($encoded, $index++)) - 63; - $result|= ($b & 0x1f) << $shift; - $shift+= 5; - } while ($b >= 0x20); - $dlng = (($result & 1) ? ~($result >> 1) : ($result >> 1)); - $lng+= $dlng; - // The actual latitude and longitude values were multiplied by - // 1e5 before encoding so that they could be converted to a 32-bit - // integer representation. (With a decimal accuracy of 5 places) - // Convert back to original values. - $points[] = array( - $lat * 1e-5, - $lng * 1e-5 - ); - } - return $points; + +function decodePolylineToArray($encoded) { + // source: http://latlongeeks.com/forum/viewtopic.php?f=4&t=5 + $length = strlen($encoded); + $index = 0; + $points = array(); + $lat = 0; + $lng = 0; + while ($index < $length) { + // Temporary variable to hold each ASCII byte. + $b = 0; + // The encoded polyline consists of a latitude value followed by a + // longitude value. They should always come in pairs. Read the + // latitude value first. + $shift = 0; + $result = 0; + do { + // The `ord(substr($encoded, $index++))` statement returns the ASCII + // code for the character at $index. Subtract 63 to get the original + // value. (63 was added to ensure proper ASCII characters are displayed + // in the encoded polyline string, which is `human` readable) + $b = ord(substr($encoded, $index++)) - 63; + // AND the bits of the byte with 0x1f to get the original 5-bit `chunk. + // Then left shift the bits by the required amount, which increases + // by 5 bits each time. + // OR the value into $results, which sums up the individual 5-bit chunks + // into the original value. Since the 5-bit chunks were reversed in + // order during encoding, reading them in this way ensures proper + // summation. + $result|= ($b & 0x1f) << $shift; + $shift+= 5; + } + // Continue while the read byte is >= 0x20 since the last `chunk` + // was not OR'd with 0x20 during the conversion process. (Signals the end) + while ($b >= 0x20); + // Check if negative, and convert. (All negative values have the last bit + // set) + $dlat = (($result & 1) ? ~($result >> 1) : ($result >> 1)); + // Compute actual latitude since value is offset from previous value. + $lat+= $dlat; + // The next values will correspond to the longitude for this point. + $shift = 0; + $result = 0; + do { + $b = ord(substr($encoded, $index++)) - 63; + $result|= ($b & 0x1f) << $shift; + $shift+= 5; + } while ($b >= 0x20); + $dlng = (($result & 1) ? ~($result >> 1) : ($result >> 1)); + $lng+= $dlng; + // The actual latitude and longitude values were multiplied by + // 1e5 before encoding so that they could be converted to a 32-bit + // integer representation. (With a decimal accuracy of 5 places) + // Convert back to original values. + $points[] = array( + $lat * 1e-5, + $lng * 1e-5 + ); + } + return $points; } -function geocode($query, $giveOptions) -{ - global $cloudmadeAPIkey; - $url = "http://geocoding.cloudmade.com/$cloudmadeAPIkey/geocoding/v2/find.js?query=" . urlencode($query) . "&bbox=-35.5,149.00,-35.15,149.1930&return_location=true&bbox_only=true"; - $contents = json_decode(getPage($url)); - if ($giveOptions) return $contents->features; - elseif (isset($contents->features[0]->centroid)) return $contents->features[0]->centroid->coordinates[0] . "," . $contents->features[0]->centroid->coordinates[1]; - else return ""; + +function geocode($query, $giveOptions) { + global $cloudmadeAPIkey; + $url = "http://geocoding.cloudmade.com/$cloudmadeAPIkey/geocoding/v2/find.js?query=" . urlencode($query) . "&bbox=-35.5,149.00,-35.15,149.1930&return_location=true&bbox_only=true"; + $contents = json_decode(getPage($url)); + if ($giveOptions) + return $contents->features; + elseif (isset($contents->features[0]->centroid)) + return $contents->features[0]->centroid->coordinates[0] . "," . $contents->features[0]->centroid->coordinates[1]; + else + return ""; } -function reverseGeocode($lat, $lng) -{ - global $cloudmadeAPIkey; - $url = "http://geocoding.cloudmade.com/$cloudmadeAPIkey/geocoding/v2/find.js?around=" . $lat . "," . $lng . "&distance=closest&object_type=road"; - $contents = json_decode(getPage($url)); - return $contents->features[0]->properties->name; + +function reverseGeocode($lat, $lng) { + global $cloudmadeAPIkey; + $url = "http://geocoding.cloudmade.com/$cloudmadeAPIkey/geocoding/v2/find.js?around=" . $lat . "," . $lng . "&distance=closest&object_type=road"; + $contents = json_decode(getPage($url)); + return $contents->features[0]->properties->name; } + ?> --- a/include/common-template.inc.php +++ b/include/common-template.inc.php @@ -1,64 +1,64 @@ -' . $pageTitle . ' +' . $pageTitle . ' - Canberra Bus Timetable - '; - if (isDebugServer()) { - $jqmcss = $labsPath . 'css/jquery.mobile-1.0b2.css'; - $jqjs = $labsPath . 'js/jquery-1.6.2.min.js'; - $jqmjs = $labsPath . 'js/jquery.mobile-1.0b2.js'; - } - else { - $jqmcss = "//code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css"; - $jqjs = "//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"; - $jqmjs = "//code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"; - } - echo ' - + '; + if (isDebugServer()) { + $jqmcss = $basePath . 'css/jquery.mobile-1.0b2.css'; + $jqjs = $basePath . 'js/jquery-1.6.2.min.js'; + $jqmjs = $basePath . 'js/jquery.mobile-1.0b2.js'; + } else { + $jqmcss = "//code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css"; + $jqjs = "//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"; + $jqmjs = "//code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"; + } + echo ' + - - - - - - + + + + + + '; - echo ''; - echo ''; - if (strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad')) { - echo ' + echo ''; + echo ''; + if (strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad')) { + echo ' '; - } - if ($geolocate) { - echo " "; - } - if (isAnalyticsOn()) echo ' + if (!isset($_SESSION['lat']) || $_SESSION['lat'] == "") + echo "geolocate();"; + echo " "; + } + if (isAnalyticsOn()) + echo ' "; - echo ' + echo ' '; - if ($opendiv) { - echo '
+ if ($opendiv) { + echo '
Back

' . $pageTitle . '

- Home + Home
'; - $overrides = getServiceOverride(); - if ($overrides['service_id']) { - if ($overrides['service_id'] == "noservice") { - echo '
Buses are not running today due to industrial action/public holiday. See Buses are not running today due to industrial action/public holiday. See http://www.action.act.gov.au for details.
'; - } - else { - echo '
Buses are running on an altered timetable today due to industrial action/public holiday. See http://www.action.act.gov.au for details.
'; - } - } - } -} -function include_footer() -{ - global $labsPath; - echo ''; - if (isAnalyticsOn()) { - echo ""; - $googleAnalyticsImageUrl = googleAnalyticsGetImageUrl(); - echo ''; - } - echo "\n
"; -} -function placeSettings() -{ - global $service_periods; - $geoerror = false; - $geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == ""; - - echo '
'; - if ($geoerror) { - echo 'Sorry, but your location could not currently be detected. + $googleAnalyticsImageUrl = googleAnalyticsGetImageUrl(); + echo ''; + } + echo "\n
"; +} + +function placeSettings() { + global $service_periods; + $geoerror = false; + $geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == ""; + + echo '
'; + if ($geoerror) { + echo 'Sorry, but your location could not currently be detected. Please allow location permission, wait for your location to be detected, or enter an address/co-ordinates in the box below.'; - } - echo '
'; - echo '
+ } + echo '
'; + echo '

Change Location...

@@ -203,11 +215,12 @@
'; } -function trackEvent($category, $action, $label = "", $value = - 1) -{ - if (isAnalyticsOn()) { - echo "\n"; - } -} + +function trackEvent($category, $action, $label = "", $value = - 1) { + if (isAnalyticsOn()) { + echo "\n"; + } +} + ?> --- a/include/common-transit.inc.php +++ b/include/common-transit.inc.php @@ -45,5 +45,216 @@ return ""; } } +if ($GTFSREnabled) { +$serviceAlertCause = Array( +"UNKNOWN_CAUSE" => "Unknown cause", +"OTHER_CAUSE" => "Other cause", +"TECHNICAL_PROBLEM" => "Technical problem", +"STRIKE" => "Strike", +"DEMONSTRATION" => "Demonstration", +"ACCIDENT" => "Accident", +"HOLIDAY" => "Holiday", +"WEATHER" => "Weather", +"MAINTENANCE" => "Maintenance", +"CONSTRUCTION" => "Construction", +"POLICE_ACTIVITY" => "Police activity", +"MEDICAL_EMERGENCY" => "Medical emergency" +); +$serviceAlertEffect = Array( +"NO_SERVICE" => "No service", +"REDUCED_SERVICE" => "Reduced service", +"SIGNIFICANT_DELAYS" => "Significant delays", +"DETOUR" => "Detour", +"ADDITIONAL_SERVICE" => "Additional service", +"MODIFIED_SERVICE" => "Modified service", +"OTHER_EFFECT" => "Other effect", +"UNKNOWN_EFFECT" => "Unknown effect", +"STOP_MOVED" => "Stop moved"); + +set_include_path(get_include_path() . PATH_SEPARATOR . $labsPath."lib/Protobuf-PHP/library/DrSlump/"); + +include_once("Protobuf.php"); +include_once("Protobuf/Message.php"); +include_once("Protobuf/Registry.php"); +include_once("Protobuf/Descriptor.php"); +include_once("Protobuf/Field.php"); + +include_once($labsPath."lib/Protobuf-PHP/gtfs-realtime.php"); +include_once("Protobuf/CodecInterface.php"); +include_once("Protobuf/Codec/PhpArray.php"); +include_once("Protobuf/Codec/Binary.php"); +include_once("Protobuf/Codec/Binary/Writer.php"); +include_once("Protobuf/Codec/Json.php"); + +function getServiceAlerts($filter_class = "", $filter_id = "") { +/* + + also need last modified epoch of client gtfs + + - add,remove,patch,inform (null) + - stop + - trip + - network + - classes (WHERE=) + - route (short_name or route_id) + - street + - stop + - trip + Currently support: + network inform + trip patch: stop remove + street inform: route inform, trip inform, stop inform + route patch: trip remove + */ + $fm = new transit_realtime\FeedMessage(); +$fh = new transit_realtime\FeedHeader(); +$fh->setGtfsRealtimeVersion(1); +$fh->setTimestamp(time()); +$fm->setHeader($fh); +foreach(getCurrentAlerts() as $alert) { +$fe = new transit_realtime\FeedEntity(); + $fe->setId($alert['id']); + $fe->setIsDeleted(false); + $alert = new transit_realtime\Alert(); + $tr = new transit_realtime\TimeRange(); + $tr->setStart($alert['start']); + $tr->setEnd($alert['end']); + $alert-> addActivePeriod($tr); + $informedEntities = getInformedAlerts($alert['id'],$_REQUEST['filter_class'],$_REQUEST['filter_id']); + if (sizeof($informedEntities) >0) { + $informed = Array(); + $es = new transit_realtime\EntitySelector(); + if ($informedEntity['informed_class'] == "agency") { + $es->setAgencyId($informedEntity['informed_id']); + } + if ($informedEntity['informed_class'] == "stop") { + $es->setStopId($informedEntity['informed_id']); + } + if ($informedEntity['informed_class'] == "route") { + $es->setRouteId($informedEntity['informed_id']); + } + if ($informedEntity['informed_class'] == "trip") { + $td = new transit_realtime\TripDescriptor(); + $td->setTripId($informedEntity['informed_id']); + $es->setTrip($td); + } + $alert-> addInformedEntity($es); + } + $alert->setCause(constant("transit_realtime\Alert\Cause::".$alert['cause'])); + $alert->setEffect(constant("transit_realtime\Alert\Effect::".$alert['effect'])); + $tsUrl = new transit_realtime\TranslatedString(); + $tUrl = new transit_realtime\TranslatedString\Translation(); + $tUrl->setText($alert['url']); + $tUrl->setLanguage("en"); + $tsUrl->addTranslation($tUrl); + $alert->setUrl($tsUrl); + $tsHeaderText= new transit_realtime\TranslatedString(); + $tHeaderText = new transit_realtime\TranslatedString\Translation(); + $tHeaderText->setText($alert['header']); + $tHeaderText->setLanguage("en"); + $tsHeaderText->addTranslation($tHeaderText); + $alert->setHeaderText($tsHeaderText); + $tsDescriptionText= new transit_realtime\TranslatedString(); + $tDescriptionText = new transit_realtime\TranslatedString\Translation(); + $tDescriptionText->setText($alert['description']); + $tDescriptionText->setLanguage("en"); + $tsDescriptionText->addTranslation($tDescriptionText); + $alert->setDescriptionText($tsDescriptionText); + $fe->setAlert($alert); +$fm->addEntity($fe); +} +return $fm; +} +function getServiceAlertsAsArray($filter_class = "", $filter_id = "") { + $codec = new DrSlump\Protobuf\Codec\PhpArray(); + return $codec->encode(getServiceAlerts($filter_class, $filter_id)); +} + +function getServiceAlertsAsBinary($filter_class = "", $filter_id = "") { + $codec = new DrSlump\Protobuf\Codec\Binary(); + return $codec->encode(getServiceAlerts($filter_class, $filter_id)); +} + +function getServiceAlertsAsJSON($filter_class = "", $filter_id = "") { + $codec = new DrSlump\Protobuf\Codec\Json(); + return $codec->encode(getServiceAlerts($filter_class, $filter_id)); +} +function getServiceAlertsByClass() { + $return = Array(); + $alerts = getServiceAlertsAsArray("",""); + foreach ($alerts['entities'] as $entity) { + foreach ($entity['informed'] as $informed) { + foreach($informed as $key => $value){ + if (strpos("_id",$key) > 0) { + $parts = explode($key); + $class = $parts[0]; + $id = $value; + } + } + $return[$class][$id][] = $entity; + } + } +} + +function getTripUpdates($filter_class = "", $filter_id = "") { + $fm = new transit_realtime\FeedMessage(); +$fh = new transit_realtime\FeedHeader(); +$fh->setGtfsRealtimeVersion(1); +$fh->setTimestamp(time()); +$fm->setHeader($fh); +foreach(getCurrentAlerts() as $alert) { + $informedEntities = getInformedAlerts($alert['id'],$_REQUEST['filter_class'],$_REQUEST['filter_id']); + $stops = Array(); + $routestrips = Array(); + if (sizeof($informedEntities) >0) { + if ($informedEntity['informed_class'] == "stop" && $informed["x-action"] == "remove") { + $stops[] = $informedEntity['informed_id']; + } + if (($informedEntity['informed_class'] == "route" || $informedEntity['informed_class'] == "trip") && $informed["x-action"] == "patch" ) { + $routestrips[] = Array( "id" => $informedEntity['informed_id'], + "type"=>$informedEntity['informed_class']); + } + } +foreach ($routestrips as $routetrip) { +$fe = new transit_realtime\FeedEntity(); + $fe->setId($alert['id'].$routetrip['id']); + $fe->setIsDeleted(false); + $tu = new transit_realtime\TripUpdate(); + $td = new transit_realtime\TripDescriptor(); + if ($routetrip['type'] == "route") { + $td->setRouteId($routetrip['id']); + } else if ($routetrip['type'] == "trip") { + $td->setTripId($routetrip['id']); + } + $tu->setTrip($td); + foreach ($stops as $stop) { + $stu = new transit_realtime\TripUpdate\StopTimeUpdate(); + $stu->setStopId($stop); + $stu->setScheduleRelationship(transit_realtime\TripUpdate\StopTimeUpdate\ScheduleRelationship::SKIPPED); + $tu->addStopTimeUpdate($stu); + } + $fe->setTripUpdate($tu); +$fm->addEntity($fe); +} + +} +return $fm; + +} +function getTripUpdatesAsArray($filter_class = "", $filter_id = "") { + $codec = new DrSlump\Protobuf\Codec\PhpArray(); + return $codec->encode(getTripUpdates($filter_class, $filter_id)); +} + +function getTripUpdatesAsBinary($filter_class = "", $filter_id = "") { + $codec = new DrSlump\Protobuf\Codec\Binary(); + return $codec->encode(getTripUpdates($filter_class, $filter_id)); +} + +function getTripUpdatesAsJSON($filter_class = "", $filter_id = "") { + $codec = new DrSlump\Protobuf\Codec\Json(); + return $codec->encode(getTripUpdates($filter_class, $filter_id)); +} +} ?> --- a/include/common.inc.php +++ b/include/common.inc.php @@ -1,38 +1,43 @@ \n"; -} -function isJQueryMobileDevice() -{ - // 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']; - 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() -{ - $ua = $_SERVER['HTTP_USER_AGENT']; - $fastDevices = Array( - "Mozilla/5.0 (X11;", - "Mozilla/5.0 (Windows;", - "Mozilla/5.0 (iP", - "Mozilla/5.0 (Linux; U; Android", - "Mozilla/4.0 (compatible; MSIE" - ); - $slowDevices = Array( - "J2ME", - "MIDP", - "Opera/", - "Mozilla/2.0 (compatible;", - "Mozilla/3.0 (compatible;" - ); - return true; -} -function array_flatten($a, $f = array()) -{ - if (!$a || !is_array($a)) return ''; - foreach ($a as $k => $v) { - if (is_array($v)) $f = array_flatten($v, $f); - else $f[$k] = $v; - } - return $f; -} -function remove_spaces($string) -{ - return str_replace(' ', '', $string); -} -function object2array($object) -{ - if (is_object($object)) { - foreach ($object as $key => $value) { - $array[$key] = $value; - } - } - else { - $array = $object; - } - return $array; -} -function startsWith($haystack, $needle, $case = true) -{ - if ($case) { - return (strcmp(substr($haystack, 0, strlen($needle)) , $needle) === 0); - } - return (strcasecmp(substr($haystack, 0, strlen($needle)) , $needle) === 0); -} - -function endsWith($haystack, $needle, $case = true) -{ - if ($case) { - return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)) , $needle) === 0); - } - return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)) , $needle) === 0); -} -function bracketsMeanNewLine($input) -{ - return str_replace(")", "
", str_replace("(", "
", $input)); -} -function sksort(&$array, $subkey = "id", $sort_ascending = false) -{ - if (count($array)) $temp_array[key($array) ] = array_shift($array); - foreach ($array as $key => $val) { - $offset = 0; - $found = false; - foreach ($temp_array as $tmp_key => $tmp_val) { - if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])) { - $temp_array = array_merge((array)array_slice($temp_array, 0, $offset) , array( - $key => $val - ) , array_slice($temp_array, $offset)); - $found = true; - } - $offset++; - } - if (!$found) $temp_array = array_merge($temp_array, array( - $key => $val - )); - } - if ($sort_ascending) $array = array_reverse($temp_array); - else $array = $temp_array; -} -function sktimesort(&$array, $subkey = "id", $sort_ascending = false) -{ - if (count($array)) $temp_array[key($array) ] = array_shift($array); - foreach ($array as $key => $val) { - $offset = 0; - $found = false; - foreach ($temp_array as $tmp_key => $tmp_val) { - if (!$found and strtotime($val[$subkey]) > strtotime($tmp_val[$subkey])) { - $temp_array = array_merge((array)array_slice($temp_array, 0, $offset) , array( - $key => $val - ) , array_slice($temp_array, $offset)); - $found = true; - } - $offset++; - } - if (!$found) $temp_array = array_merge($temp_array, array( - $key => $val - )); - } - if ($sort_ascending && isset($temp_array)) $array = array_reverse($temp_array); - else $array = $temp_array; -} -function r_implode( $glue, $pieces ) -{ - foreach( $pieces as $r_pieces ) - { - if( is_array( $r_pieces ) ) - { - $retVal[] = r_implode( $glue, $r_pieces ); - } - else - { - $retVal[] = $r_pieces; - } - } - return implode( $glue, $retVal ); -} +function isAnalyticsOn() { + $user_agent = $_SERVER['HTTP_USER_AGENT']; + return!isDebugServer() && !preg_match('/cloudkick/i', $user_agent) && !preg_match('/googlebot/i', $user_agent) && + !preg_match('/baidu/i', $user_agent); +} + +function isDebug($debugReason = "other") { + global $debugOkay; + return in_array($debugReason, $debugOkay, false) && isDebugServer(); +} + +function debug($msg, $debugReason = "other") { + if (isDebug($debugReason)) + echo "\n\n"; +} + +function isJQueryMobileDevice() { + // 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']; + 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() { + $ua = $_SERVER['HTTP_USER_AGENT']; + $fastDevices = Array( + "Mozilla/5.0 (X11;", + "Mozilla/5.0 (Windows;", + "Mozilla/5.0 (iP", + "Mozilla/5.0 (Linux; U; Android", + "Mozilla/4.0 (compatible; MSIE" + ); + $slowDevices = Array( + "J2ME", + "MIDP", + "Opera/", + "Mozilla/2.0 (compatible;", + "Mozilla/3.0 (compatible;" + ); + return true; +} + +function array_flatten($a, $f = array()) { + if (!$a || !is_array($a)) + return ''; + foreach ($a as $k => $v) { + if (is_array($v)) + $f = array_flatten($v, $f); + else + $f[$k] = $v; + } + return $f; +} + +function remove_spaces($string) { + return str_replace(' ', '', $string); +} + +function object2array($object) { + if (is_object($object)) { + foreach ($object as $key => $value) { + $array[$key] = $value; + } + } else { + $array = $object; + } + return $array; +} + +function startsWith($haystack, $needle, $case = true) { + if ($case) { + return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0); + } + return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0); +} + +function endsWith($haystack, $needle, $case = true) { + if ($case) { + return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0); + } + return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0); +} + +function bracketsMeanNewLine($input) { + return str_replace(")", "", str_replace("(", "
", $input)); +} + +function sksort(&$array, $subkey = "id", $sort_ascending = false) { + if (count($array)) + $temp_array[key($array)] = array_shift($array); + foreach ($array as $key => $val) { + $offset = 0; + $found = false; + foreach ($temp_array as $tmp_key => $tmp_val) { + if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])) { + $temp_array = array_merge((array) array_slice($temp_array, 0, $offset), array( + $key => $val + ), array_slice($temp_array, $offset)); + $found = true; + } + $offset++; + } + if (!$found) + $temp_array = array_merge($temp_array, array( + $key => $val + )); + } + if ($sort_ascending) + $array = array_reverse($temp_array); + else + $array = $temp_array; +} + +function sktimesort(&$array, $subkey = "id", $sort_ascending = false) { + if (count($array)) + $temp_array[key($array)] = array_shift($array); + foreach ($array as $key => $val) { + $offset = 0; + $found = false; + foreach ($temp_array as $tmp_key => $tmp_val) { + if (!$found and strtotime($val[$subkey]) > strtotime($tmp_val[$subkey])) { + $temp_array = array_merge((array) array_slice($temp_array, 0, $offset), array( + $key => $val + ), array_slice($temp_array, $offset)); + $found = true; + } + $offset++; + } + if (!$found) + $temp_array = array_merge($temp_array, array( + $key => $val + )); + } + if ($sort_ascending && isset($temp_array)) + $array = array_reverse($temp_array); + else + $array = $temp_array; +} + +function r_implode($glue, $pieces) { + foreach ($pieces as $r_pieces) { + if (is_array($r_pieces)) { + $retVal[] = r_implode($glue, $r_pieces); + } else { + $retVal[] = $r_pieces; + } + } + return implode($glue, $retVal); +} + ?> --- a/include/db/route-dao.inc.php +++ b/include/db/route-dao.inc.php @@ -1,211 +1,222 @@ prepare($query); - $query->bindParam(":routeID", $routeID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetch(PDO::FETCH_ASSOC); -} + +{ + global $conn; + $query = "Select * from routes where route_id = :routeID LIMIT 1"; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":routeID", $routeID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } function getRouteByFullName($routeFullName) -{ - global $conn; - $query = "Select * from routes where route_short_name||route_long_name = :routeFullName LIMIT 1"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":routeFullName", $routeFullName); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetch(PDO::FETCH_ASSOC); -} + +{ + global $conn; + $query = "Select * from routes where route_short_name||route_long_name = :routeFullName LIMIT 1"; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":routeFullName", $routeFullName); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } function getRoutes() -{ - global $conn; - $query = "Select * from routes order by route_short_name;"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + +{ + global $conn; + $query = "Select * from routes order by route_short_name;"; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getRoutesByNumber($routeNumber = "") -{ - global $conn; - if ($routeNumber != "") { - $query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id = + +{ + global $conn; + if ($routeNumber != "") { + $query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id = routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where route_short_name = :routeNumber OR route_short_name LIKE :routeNumber2 order by route_short_name;"; - } - else { - $query = "SELECT DISTINCT route_short_name from routes order by route_short_name"; - } - debug($query, "database"); - $query = $conn->prepare($query); - if ($routeNumber != "") { - $query->bindParam(":routeNumber", $routeNumber); - $routeNumber2 = "% ".$routeNumber; - $query->bindParam(":routeNumber2", $routeNumber2); - } - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + } + else { + $query = "SELECT DISTINCT route_short_name from routes order by route_short_name"; + } + debug($query, "database"); + $query = $conn -> prepare($query); + if ($routeNumber != "") { + $query -> bindParam(":routeNumber", $routeNumber); + $routeNumber2 = "% " . $routeNumber; + $query -> bindParam(":routeNumber2", $routeNumber2); + } + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getRoutesByNumberSeries($routeNumberSeries = "") -{ - global $conn; - if (strlen($routeNumberSeries) == 1) { - return getRoutesByNumber($routeNumberSeries); - } - $seriesMin = substr($routeNumberSeries, 0, -1) . "0"; - $seriesMax = substr($routeNumberSeries, 0, -1) . "9"; - $query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id = + +{ + global $conn; + if (strlen($routeNumberSeries) == 1) { + return getRoutesByNumber($routeNumberSeries); + } + $seriesMin = substr($routeNumberSeries, 0, -1) . "0"; + $seriesMax = substr($routeNumberSeries, 0, -1) . "9"; + $query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id = routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where to_number(route_short_name, 'FM999') between :seriesMin and :seriesMax OR route_short_name LIKE :routeNumberSeries order by route_short_name;"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":seriesMin", $seriesMin); - $query->bindParam(":seriesMax", $seriesMax); - $routeNumberSeries = "% ".substr($routeNumberSeries, 0, -1)."%"; - $query->bindParam(":routeNumberSeries", $routeNumberSeries); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":seriesMin", $seriesMin); + $query -> bindParam(":seriesMax", $seriesMax); + $routeNumberSeries = "% " . substr($routeNumberSeries, 0, -1) . "%"; + $query -> bindParam(":routeNumberSeries", $routeNumberSeries); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getRouteNextTrip($routeID) -{ - global $conn; - $query = "select * from routes join trips on trips.route_id = routes.route_id + +{ + global $conn; + $query = "select * from routes join trips on trips.route_id = routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where arrival_time > :currentTime and routes.route_id = :routeID order by arrival_time limit 1"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":currentTime", current_time()); - $query->bindParam(":routeID", $routeID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - $r = $query->fetch(PDO::FETCH_ASSOC); - - // past last trip of the day special case - if (sizeof($r) < 16) { - $query = "select * from routes join trips on trips.route_id = routes.route_id + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":currentTime", current_time()); + $query -> bindParam(":routeID", $routeID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + $r = $query -> fetch(PDO :: FETCH_ASSOC); + + // past last trip of the day special case + if (sizeof($r) < 16) { + $query = "select * from routes join trips on trips.route_id = routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID order by arrival_time DESC limit 1"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":routeID", $routeID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - - $r = $query->fetch(PDO::FETCH_ASSOC); - } - return $r; -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":routeID", $routeID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + + $r = $query -> fetch(PDO :: FETCH_ASSOC); + } + return $r; + } function getTimeInterpolatedRouteAtStop($routeID, $stop_id) -{ - $nextTrip = getRouteNextTrip($routeID); - if ($nextTrip['trip_id']) { - foreach (getTimeInterpolatedTrip($nextTrip['trip_id']) as $tripStop) { - if ($tripStop['stop_id'] == $stop_id) return $tripStop; - } - } - return Array(); -} + +{ + $nextTrip = getRouteNextTrip($routeID); + if ($nextTrip['trip_id']) { + foreach (getTimeInterpolatedTrip($nextTrip['trip_id']) as $tripStop) { + if ($tripStop['stop_id'] == $stop_id) return $tripStop; + } + } + return Array(); + } function getRouteTrips($routeID) -{ - global $conn; - $query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id + +{ + global $conn; + $query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID and stop_sequence = '1' order by arrival_time "; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":routeID", $routeID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":routeID", $routeID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getRoutesByDestination($destination = "", $service_period = "") -{ - global $conn; - if ($service_period == "") $service_period = service_period(); - if ($destination != "") { - $query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id + +{ + global $conn; + if ($service_period == "") $service_period = service_period(); + if ($destination != "") { + $query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id FROM stop_times join trips on trips.trip_id = stop_times.trip_id join routes on trips.route_id = routes.route_id WHERE route_long_name = :destination AND service_id=:service_period order by route_short_name"; - } - else { - $query = "SELECT DISTINCT route_long_name + } + else { + $query = "SELECT DISTINCT route_long_name FROM stop_times join trips on trips.trip_id = stop_times.trip_id join routes on trips.route_id = routes.route_id WHERE service_id= :service_period order by route_long_name"; - } - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":service_period", $service_period); - if ($destination != "") $query->bindParam(":destination", $destination); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + } + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":service_period", $service_period); + if ($destination != "") $query -> bindParam(":destination", $destination); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getRoutesBySuburb($suburb, $service_period = "") -{ - if ($service_period == "") $service_period = service_period(); - global $conn; - $query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name + +{ + if ($service_period == "") $service_period = service_period(); + global $conn; + $query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name FROM stop_times join trips on trips.trip_id = stop_times.trip_id join routes on trips.route_id = routes.route_id join stops on stops.stop_id = stop_times.stop_id WHERE zone_id LIKE ':suburb AND service_id=:service_period ORDER BY route_short_name"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":service_period", $service_period); - $suburb = "%" . $suburb . ";%"; - $query->bindParam(":suburb", $suburb); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":service_period", $service_period); + $suburb = "%" . $suburb . ";%"; + $query -> bindParam(":suburb", $suburb); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getRoutesNearby($lat, $lng, $limit = "", $distance = 500) -{ - if ($service_period == "") $service_period = service_period(); - if ($limit != "") $limitSQL = " LIMIT :limit "; - global $conn; - $query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id, + +{ + if ($service_period == "") $service_period = service_period(); + if ($limit != "") $limitSQL = " LIMIT :limit "; + global $conn; + $query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id, min(ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE)) as distance FROM stop_times join trips on trips.trip_id = stop_times.trip_id @@ -215,16 +226,16 @@ AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), :distance, FALSE) group by service_id,trips.route_id,route_short_name,route_long_name order by distance $limitSQL"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":service_period", $service_period); - $query->bindParam(":distance", $distance); - if ($limit != "") $query->bindParam(":limit", $limit); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":service_period", $service_period); + $query -> bindParam(":distance", $distance); + if ($limit != "") $query -> bindParam(":limit", $limit); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } ?> --- a/include/db/servicealert-dao.inc.php +++ b/include/db/servicealert-dao.inc.php @@ -1,53 +1,169 @@ prepare($query); // Create a prepared statement - $query->bindParam(":date", date("Ymd",($date != "" ? $date : time()))); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetch(PDO::FETCH_ASSOC); -} +function getServiceOverride($date = "") +{ + global $conn; + $query = "Select * from calendar_dates where date = :date and exception_type = '1' LIMIT 1"; + // debug($query,"database"); + $query = $conn -> prepare($query); // Create a prepared statement + $query -> bindParam(":date", date("Ymd", ($date != "" ? $date : time()))); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } -function getCurrentAlerts() { - global $conn; - $query = "SELECT * from servicealerts_alerts"; - //debug($query, "database"); - $query = $conn->prepare($query); - //if ($stop_sequence != "") $query->bindParam(":stop_sequence", $stop_sequence); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} -function getInformedAlerts($id,$filter_class,$filter_id) { - - global $conn; - $query = "SELECT * from servicealerts_informed where servicealert_id = :servicealert_id"; - - if ($filter_class != "" && $filter_id != "") { - $query .= " AND (informed_class = :informed_class OR informed_class = 'network') AND informed_id = :informed_id"; - - } - //debug($query, "database"); - $query = $conn->prepare($query); - if ($filter_class != "" && $filter_id != "") { - $query->bindParam(":informed_class", $filter_class); - $query->bindParam(":informed_id", $filter_id); - } - $query->bindParam(":servicealert_id", $id); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} +function getServiceAlert($alertID) +{ + global $conn; + $query = "SELECT id,extract('epoch', start) as start, extract('epoch', end) as end,cause,effect,header,description,url from servicealerts_alerts where id = :servicealert_id"; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":servicealert_id", $alertID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } + +function updateServiceAlert($alertID, $start, $end, $header, $description, $url) +{ + global $conn; + $query = 'update servicealerts_alerts set start=:start, "end"=:end, header=:header, description=:description, url=:url where id = :servicealert_id'; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":servicealert_id", $alertID); + $query -> bindParam(":start", $start); + $query -> bindParam(":end", $end); + $query -> bindParam(":header", $header); + $query -> bindParam(":description", $description); + $query -> bindParam(":url", $url); + $query -> execute(); + + print_r($conn -> errorInfo()); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } + + function addServiceAlert($start, $end, $header, $description, $url) +{ + global $conn; + $query = 'INSERT INTO servicealerts_alerts (start, "end", header, description, url) VALUES (:start, :end, :header, :description, :url) '; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":start", $start); + $query -> bindParam(":end", $end); + $query -> bindParam(":header", $header); + $query -> bindParam(":description", $description); + $query -> bindParam(":url", $url); + $query -> execute(); + + print_r($conn -> errorInfo()); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } + +function getCurrentAlerts() +{ + global $conn; + $query = "SELECT id,extract('epoch', start) as start, extract('epoch', end) as end,cause,effect,header,description,url from servicealerts_alerts where NOW() > start and NOW() < \"end\""; + // debug($query, "database"); + $query = $conn -> prepare($query); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } + +function getFutureAlerts() +{ + global $conn; + $query = "SELECT id,extract('epoch', start) as start, extract('epoch', end) as end,cause,effect,header,description,url from servicealerts_alerts where NOW() > start or NOW() < \"end\""; + // debug($query, "database"); + $query = $conn -> prepare($query); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } +function getInformedAlerts($id, $filter_class, $filter_id) +{ + + global $conn; + $query = "SELECT * from servicealerts_informed where servicealert_id = :servicealert_id"; + + if ($filter_class != "") { + $query .= " AND informed_class = :informed_class "; + + } + if ($filter_id != "") { + $query .= " AND informed_id = :informed_id "; + + } + // debug($query, "database"); + $query = $conn -> prepare($query); + if ($filter_class != "") { + $query -> bindParam(":informed_class", $filter_class); + } + if ($filter_id != "") { + $query -> bindParam(":informed_id", $filter_id); + } + $query -> bindParam(":servicealert_id", $id); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } +function deleteInformedAlert($serviceAlertID, $class, $id) +{ + global $conn; + $query = 'DELETE from servicealerts_informed where servicealert_id = :servicealert_id and informed_class = :informed_class AND informed_id = :informed_id'; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":servicealert_id", $serviceAlertID); + $query -> bindParam(":informed_class", $class); + $query -> bindParam(":informed_id", $id); + $query -> execute(); + print_r($conn -> errorInfo()); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return null; + } +function addInformedAlert($serviceAlertID, $class, $id, $action) +{ + global $conn; + $query = 'INSERT INTO servicealerts_informed (servicealert_id , informed_class , informed_id) VALUES(:servicealert_id ,:informed_class, :informed_id)'; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":servicealert_id", $serviceAlertID); + $query -> bindParam(":informed_class", $class); + $query -> bindParam(":informed_id", $id); + $query -> execute(); + + print_r($conn -> errorInfo()); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return null; + + } ?> --- a/include/db/stop-dao.inc.php +++ b/include/db/stop-dao.inc.php @@ -1,131 +1,154 @@ prepare($query); - $query->bindParam(":stopID", $stopID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetch(PDO::FETCH_ASSOC); -} + +{ + global $conn; + $query = "Select * from stops where stop_id = :stopID LIMIT 1"; + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":stopID", $stopID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } function getStops($timingPointsOnly = false, $firstLetter = "", $startsWith = "") -{ - global $conn; - $conditions = Array(); - if ($timingPointsOnly) $conditions[] = "substr(stop_code,1,2) != 'Wj'"; - if ($firstLetter != "") $conditions[] = "substr(stop_name,1,1) = :firstLetter"; - if ($startsWith != "") $conditions[] = "stop_name like :startsWith"; - $query = "Select * from stops"; - if (sizeof($conditions) > 0) { - if (sizeof($conditions) > 1) { - $query.= " Where " . implode(" AND ", $conditions) . " "; - } - else { - $query.= " Where " . $conditions[0] . " "; - } - } - $query.= " order by stop_name;"; - $query = $conn->prepare($query); - if ($firstLetter != "") $query->bindParam(":firstLetter", $firstLetter); - - if ($startsWith != "") { - $startsWith = $startsWith."%"; - $query->bindParam(":startsWith", $startsWith); - } - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + +{ + global $conn; + $conditions = Array(); + if ($timingPointsOnly) $conditions[] = "substr(stop_code,1,2) != 'Wj'"; + if ($firstLetter != "") $conditions[] = "substr(stop_name,1,1) = :firstLetter"; + if ($startsWith != "") $conditions[] = "stop_name like :startsWith"; + $query = "Select * from stops"; + if (sizeof($conditions) > 0) { + if (sizeof($conditions) > 1) { + $query .= " Where " . implode(" AND ", $conditions) . " "; + } + else { + $query .= " Where " . $conditions[0] . " "; + } + } + $query .= " order by stop_name;"; + $query = $conn -> prepare($query); + if ($firstLetter != "") $query -> bindParam(":firstLetter", $firstLetter); + + if ($startsWith != "") { + $startsWith = $startsWith . "%"; + $query -> bindParam(":startsWith", $startsWith); + } + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getNearbyStops($lat, $lng, $limit = "", $distance = 1000) -{ - if ($lat == null || $lng == null) return Array(); - if ($limit != "") $limitSQL = " LIMIT :limit "; - global $conn; - $query = "Select *, ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE) as distance + +{ + if ($lat == null || $lng == null) return Array(); + if ($limit != "") $limitSQL = " LIMIT :limit "; + global $conn; + $query = "Select *, ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE) as distance from stops WHERE ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), :distance, FALSE) order by distance $limitSQL;"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":distance", $distance); - $query->bindParam(":limit", $limit); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":distance", $distance); + $query -> bindParam(":limit", $limit); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } +function getStopsByName($name) + +{ + global $conn; + $query = "Select * from stops where stop_name LIKE :name;"; + debug($query, "database"); + $query = $conn -> prepare($query); + $name = "%" . $name . ";%"; + $query -> bindParam(":name", $name); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getStopsBySuburb($suburb) -{ - global $conn; - $query = "Select * from stops where zone_id LIKE :suburb order by stop_name;"; - debug($query, "database"); - $query = $conn->prepare($query); - $suburb = "%" . $suburb . ";%"; - $query->bindParam(":suburb", $suburb); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} -function getStopsByStopCode($stop_code,$startsWith = "") -{ - global $conn; - $query = "Select * from stops where (stop_code = :stop_code OR stop_code LIKE :stop_code2)"; - if ($startsWith != "") $query .= " AND stop_name like :startsWith"; - - debug($query, "database"); - $query = $conn->prepare($query); - - $query->bindParam(":stop_code", $stop_code); - $stop_code2 = $stop_code . "%"; - $query->bindParam(":stop_code2", $stop_code2); - if ($startsWith != "") { - $startsWith = $startsWith."%"; - $query->bindParam(":startsWith", $startsWith); - } - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + +{ + global $conn; + $query = "Select * from stops where zone_id LIKE :suburb order by stop_name;"; + debug($query, "database"); + $query = $conn -> prepare($query); + $suburb = "%" . $suburb . ";%"; + $query -> bindParam(":suburb", $suburb); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } +function getStopsByStopCode($stop_code, $startsWith = "") + +{ + global $conn; + $query = "Select * from stops where (stop_code = :stop_code OR stop_code LIKE :stop_code2)"; + if ($startsWith != "") $query .= " AND stop_name like :startsWith"; + + debug($query, "database"); + $query = $conn -> prepare($query); + + $query -> bindParam(":stop_code", $stop_code); + $stop_code2 = $stop_code . "%"; + $query -> bindParam(":stop_code2", $stop_code2); + if ($startsWith != "") { + $startsWith = $startsWith . "%"; + $query -> bindParam(":startsWith", $startsWith); + } + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getStopRoutes($stopID, $service_period) -{ - if ($service_period == "") $service_period = service_period(); - global $conn; - $query = "SELECT distinct service_id,trips.route_id,route_short_name,route_long_name + +{ + if ($service_period == "") $service_period = service_period(); + global $conn; + $query = "SELECT distinct service_id,trips.route_id,route_short_name,route_long_name FROM stop_times join trips on trips.trip_id = stop_times.trip_id join routes on trips.route_id = routes.route_id WHERE stop_id = :stopID AND service_id=:service_period"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":service_period", $service_period); - $query->bindParam(":stopID", $stopID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":service_period", $service_period); + $query -> bindParam(":stopID", $stopID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getStopTrips($stopID, $service_period = "", $afterTime = "", $limit = "") -{ - if ($service_period == "") $service_period = service_period(); - if ($limit != "") $limitSQL = " LIMIT :limit "; - global $conn; - if ($afterTime != "") { - $query = " SELECT stop_times.trip_id,stop_times.arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name, end_times.arrival_time as end_time + +{ + if ($service_period == "") $service_period = service_period(); + if ($limit != "") $limitSQL = " LIMIT :limit "; + global $conn; + if ($afterTime != "") { + $query = " SELECT stop_times.trip_id,stop_times.arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name, end_times.arrival_time as end_time FROM stop_times join trips on trips.trip_id = stop_times.trip_id @@ -136,9 +159,9 @@ AND service_id=:service_period AND end_times.arrival_time > :afterTime ORDER BY end_time $limitSQL"; - } - else { - $query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name + } + else { + $query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name FROM stop_times join trips on trips.trip_id = stop_times.trip_id @@ -146,45 +169,46 @@ WHERE stop_times.stop_id = :stopID AND service_id=:service_period ORDER BY arrival_time $limitSQL"; - } - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":service_period", $service_period); - $query->bindParam(":stopID", $stopID); - if ($limit != "") $query->bindParam(":limit", $limit); - if ($afterTime != "") $query->bindParam(":afterTime", $afterTime); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} + } + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":service_period", $service_period); + $query -> bindParam(":stopID", $stopID); + if ($limit != "") $query -> bindParam(":limit", $limit); + if ($afterTime != "") $query -> bindParam(":afterTime", $afterTime); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function getStopTripsWithTimes($stopID, $time = "", $service_period = "", $time_range = "", $limit = "") -{ - if ($service_period == "") $service_period = service_period(); - if ($time_range == "") $time_range = (24 * 60 * 60); - if ($time == "") $time = current_time(); - if ($limit == "") $limit = 10; - $trips = getStopTrips($stopID, $service_period, $time); - $timedTrips = Array(); - if ($trips && sizeof($trips) > 0) { - foreach ($trips as $trip) { - if ($trip['arrival_time'] != "") { - if (strtotime($trip['arrival_time']) > strtotime($time) and strtotime($trip['arrival_time']) < (strtotime($time) + $time_range)) { - $timedTrips[] = $trip; - } - } - else { - $timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']); - if ($timedTrip['arrival_time'] > $time and strtotime($timedTrip['arrival_time']) < (strtotime($time) + $time_range)) { - $timedTrips[] = $timedTrip; - } - } - if (sizeof($timedTrips) > $limit) break; - } - sktimesort($timedTrips, "arrival_time", true); - } - return $timedTrips; -} + +{ + if ($service_period == "") $service_period = service_period(); + if ($time_range == "") $time_range = (24 * 60 * 60); + if ($time == "") $time = current_time(); + if ($limit == "") $limit = 10; + $trips = getStopTrips($stopID, $service_period, $time); + $timedTrips = Array(); + if ($trips && sizeof($trips) > 0) { + foreach ($trips as $trip) { + if ($trip['arrival_time'] != "") { + if (strtotime($trip['arrival_time']) > strtotime($time) and strtotime($trip['arrival_time']) < (strtotime($time) + $time_range)) { + $timedTrips[] = $trip; + } + } + else { + $timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']); + if ($timedTrip['arrival_time'] > $time and strtotime($timedTrip['arrival_time']) < (strtotime($time) + $time_range)) { + $timedTrips[] = $timedTrip; + } + } + if (sizeof($timedTrips) > $limit) break; + } + sktimesort($timedTrips, "arrival_time", true); + } + return $timedTrips; + } ?> --- a/include/db/trip-dao.inc.php +++ b/include/db/trip-dao.inc.php @@ -1,240 +1,251 @@ prepare($query); - $query->bindParam(":tripID", $tripID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetch(PDO::FETCH_ASSOC); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":tripID", $tripID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } function getTripShape($tripID) -{ - global $conn; - $query = "SELECT ST_AsKML(ST_MakeLine(geometry(a.position))) as the_route + +{ + global $conn; + $query = "SELECT ST_AsKML(ST_MakeLine(geometry(a.position))) as the_route FROM (SELECT position, stop_sequence, trips.trip_id FROM stop_times join trips on trips.trip_id = stop_times.trip_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"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":tripID", $tripID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchColumn(0); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":tripID", $tripID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchColumn(0); + } function getTimeInterpolatedTrip($tripID, $range = "") -{ - global $conn; - $query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_lat,stop_lon,stop_name,stop_code, + +{ + global $conn; + $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 FROM stop_times join trips on trips.trip_id = stop_times.trip_id join routes on trips.route_id = routes.route_id join stops on stops.stop_id = stop_times.stop_id WHERE trips.trip_id = :tripID $range ORDER BY stop_sequence"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":tripID", $tripID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - $stopTimes = $query->fetchAll(); - $cur_timepoint = Array(); - $next_timepoint = Array(); - $distance_between_timepoints = 0.0; - $distance_traveled_between_timepoints = 0.0; - $rv = Array(); - foreach ($stopTimes as $i => $stopTime) { - if ($stopTime['arrival_time'] != "") { - // is timepoint - $cur_timepoint = $stopTime; - $distance_between_timepoints = 0.0; - $distance_traveled_between_timepoints = 0.0; - if ($i + 1 < sizeof($stopTimes)) { - $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"]); - while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) { - $k+= 1; - //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"]); - } - $next_timepoint = $stopTimes[$k]; - - } - $rv[] = $stopTime; - } - else { - // is untimed point - //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"]); - //echo "$distance_traveled_between_timepoints / $distance_between_timepoints
"; - $distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints; - if ($next_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"])."
"; - $time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]); - $stopTime["arrival_time"] = date("H:i:s", $time_estimate); - } - else { - $stopTime["arrival_time"] = $cur_timepoint["arrival_time"]; - } - $rv[] = $stopTime; - - - } - } - //var_dump($rv); - return $rv; -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":tripID", $tripID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + $stopTimes = $query -> fetchAll(); + $cur_timepoint = Array(); + $next_timepoint = Array(); + $distance_between_timepoints = 0.0; + $distance_traveled_between_timepoints = 0.0; + $rv = Array(); + foreach ($stopTimes as $i => $stopTime) { + if ($stopTime['arrival_time'] != "") { + // is timepoint + $cur_timepoint = $stopTime; + $distance_between_timepoints = 0.0; + $distance_traveled_between_timepoints = 0.0; + if ($i + 1 < sizeof($stopTimes)) { + $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"]); + while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) { + $k += 1; + // 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"]); + } + $next_timepoint = $stopTimes[$k]; + + } + $rv[] = $stopTime; + } + else { + // is untimed point + // 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"]); + // echo "$distance_traveled_between_timepoints / $distance_between_timepoints
"; + $distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints; + if ($next_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"])."
"; + $time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]); + $stopTime["arrival_time"] = date("H:i:s", $time_estimate); + } + else { + $stopTime["arrival_time"] = $cur_timepoint["arrival_time"]; + } + $rv[] = $stopTime; + + + } + } + // var_dump($rv); + return $rv; + } function getTripPreviousTimePoint($tripID, $stop_sequence) -{ - global $conn; - $query = " SELECT trip_id,stop_id, + +{ + global $conn; + $query = " SELECT trip_id,stop_id, stop_sequence FROM stop_times WHERE trip_id = :tripID and stop_sequence < :stop_sequence and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence DESC LIMIT 1"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":tripID", $tripID); - $query->bindParam(":stop_sequence", $stop_sequence); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetch(PDO::FETCH_ASSOC); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":tripID", $tripID); + $query -> bindParam(":stop_sequence", $stop_sequence); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } function getTripNextTimePoint($tripID, $stop_sequence) -{ - global $conn; - $query = " SELECT trip_id,stop_id, + +{ + global $conn; + $query = " SELECT trip_id,stop_id, stop_sequence FROM stop_times WHERE trip_id = :tripID and stop_sequence > :stop_sequence and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence LIMIT 1"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":tripID", $tripID); - $query->bindParam(":stop_sequence", $stop_sequence); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetch(PDO::FETCH_ASSOC); -} + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":tripID", $tripID); + $query -> bindParam(":stop_sequence", $stop_sequence); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetch(PDO :: FETCH_ASSOC); + } function getTimeInterpolatedTripAtStop($tripID, $stop_sequence) -{ - global $conn; - // limit interpolation to between nearest actual points. - $prevTimePoint = getTripPreviousTimePoint($tripID, $stop_sequence); - $nextTimePoint = getTripNextTimePoint($tripID, $stop_sequence); - //echo " prev {$lowestDelta['stop_sequence']} next {$nextTimePoint['stop_sequence']} "; - $range = ""; - if ($prevTimePoint != "") $range .= " AND stop_sequence >= '{$prevTimePoint['stop_sequence']}'"; - if ($nextTimePoint != "") $range .= " AND stop_sequence <= '{$nextTimePoint['stop_sequence']}'"; - foreach (getTimeInterpolatedTrip($tripID, $range) as $tripStop) { - if ($tripStop['stop_sequence'] == $stop_sequence) return $tripStop; - } - return Array(); -} + +{ + global $conn; + // limit interpolation to between nearest actual points. + $prevTimePoint = getTripPreviousTimePoint($tripID, $stop_sequence); + $nextTimePoint = getTripNextTimePoint($tripID, $stop_sequence); + // echo " prev {$lowestDelta['stop_sequence']} next {$nextTimePoint['stop_sequence']} "; + $range = ""; + if ($prevTimePoint != "") $range .= " AND stop_sequence >= '{$prevTimePoint['stop_sequence']}'"; + if ($nextTimePoint != "") $range .= " AND stop_sequence <= '{$nextTimePoint['stop_sequence']}'"; + foreach (getTimeInterpolatedTrip($tripID, $range) as $tripStop) { + if ($tripStop['stop_sequence'] == $stop_sequence) return $tripStop; + } + return Array(); + } function getTripStartTime($tripID) -{ - global $conn; - $query = "Select * from stop_times + +{ + global $conn; + $query = "Select * from stop_times where trip_id = :tripID AND arrival_time IS NOT NULL AND stop_sequence = '1'"; - 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']; -} + 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 getTripEndTime($tripID) -{ - global $conn; - $query = "SELECT trip_id,max(arrival_time) as arrival_time from stop_times + +{ + 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']; -} + 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) -{ - global $conn; - 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 + +{ + global $conn; + 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 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"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":time", $time); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} -function viaPoints($tripID, $stop_sequence = "") -{ - global $conn; - $query = "SELECT stops.stop_id, stop_name, arrival_time + debug($query, "database"); + $query = $conn -> prepare($query); + $query -> bindParam(":time", $time); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } +function viaPoints($tripID, $stop_sequence = "", $timing_points_only = true) + +{ + global $conn; + $query = "SELECT stops.stop_id, stop_name, arrival_time FROM stop_times join stops on stops.stop_id = stop_times.stop_id WHERE stop_times.trip_id = :tripID -" . ($stop_sequence != "" ? " AND stop_sequence > :stop_sequence " : "") . "AND substr(stop_code,1,2) != 'Wj' ORDER BY stop_sequence"; - debug($query, "database"); - $query = $conn->prepare($query); - if ($stop_sequence != "") $query->bindParam(":stop_sequence", $stop_sequence); - $query->bindParam(":tripID", $tripID); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - return $query->fetchAll(); -} +" . ($stop_sequence != "" ? " AND stop_sequence > :stop_sequence " : "") . ($timing_points_only ? "AND substr(stop_code,1,2) != 'Wj' ": ""). " ORDER BY stop_sequence"; + debug($query, "database"); + $query = $conn -> prepare($query); + if ($stop_sequence != "") $query -> bindParam(":stop_sequence", $stop_sequence); + $query -> bindParam(":tripID", $tripID); + $query -> execute(); + if (!$query) { + databaseError($conn -> errorInfo()); + return Array(); + } + return $query -> fetchAll(); + } function viaPointNames($tripid, $stop_sequence = "") -{ - $viaPointNames = Array(); - foreach (viaPoints($tripid, $stop_sequence) as $point) { - $viaPointNames[] = $point['stop_name']; - } - if (sizeof($viaPointNames) > 0) { - return r_implode(", ", $viaPointNames); - } - else { - return ""; - } -} + +{ + $viaPointNames = Array(); + foreach (viaPoints($tripid, $stop_sequence) as $point) { + $viaPointNames[] = $point['stop_name']; + } + if (sizeof($viaPointNames) > 0) { + return r_implode(", ", $viaPointNames); + } + else { + return ""; + } + } ?> --- a/index.php +++ b/index.php @@ -25,6 +25,7 @@ Busness R&D'; +echo ' MyWay Balance and Timeliness Survey Results'; include_footer(true) ?> --- a/labs/index.php +++ b/labs/index.php @@ -1,29 +1,16 @@ - - + --- a/labs/myway_api.json.php +++ /dev/null @@ -1,141 +1,1 @@ - "SRNO", - "DOBmonth" => "month", - "DOBday" => "day", - "DOByear" => "year", - "secret_answer" => "pwrd", - "button" => "Submit" -); -foreach (Array( - "card_number", - "DOBday", - "DOBmonth", - "DOByear" -) as $field_name) { - if (isset($_REQUEST[$field_name])) { - $fields[$field_name] = filter_var($_REQUEST[$field_name], FILTER_SANITIZE_NUMBER_INT); - } - else { - $return["error"][] = $field_name. " parameter invalid or unspecified"; - } -} -if (isset($_REQUEST['secret_answer'])) { - $fields['secret_answer'] = filter_var($_REQUEST['secret_answer'], FILTER_SANITIZE_STRING, Array( - FILTER_FLAG_NO_ENCODE_QUOTES, - FILTER_FLAG_STRIP_HIGH, - FILTER_FLAG_STRIP_LOW - )); -} -else { - $return["error"][] = "secret_answer parameter invalid or unspecified"; -} -$fields['button'] = 'Submit'; -$fields_string = ""; -//url-ify the data for the POST -foreach ($fields as $key => $value) { - if (sizeof($value) === 0) $return['error'][] = $key . " parameter invalid or unspecified"; - $fields_string.= $field_mapping[$key] . '=' . $value . '&'; -} -$fields_string = rtrim($fields_string, '&'); -if (!isset($return['error'])) { - //open connection - $ch = curl_init(); - //set the url, number of POST vars, POST data - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_POST, count($fields)); - curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_REFERER, "https://www.action.act.gov.au/ARTS/getbalance.asp"); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_TIMEOUT, 30); - //execute post - $pageHTML = curl_exec($ch); - if (curl_errno($ch)) $return["error"][] = "Network error " . curl_errno($ch) . " " . curl_error($ch) . " " . $url . $fields_string; - //close connection - curl_close($ch); -} -if (!isset($return['error'])) { - include_once ('../lib/simple_html_dom.php'); - //print_r($pageHTML); - $page = str_get_html($pageHTML); - $pageAlerts = $page->find(".smartCardAlert"); - if (sizeof($pageAlerts) > 0) { - $return['error'][] = $pageAlerts[0]->plaintext; - } - if (!isset($return['error'])) { - $tableNum = 0; - $tableName = Array( - 1 => "myway_carddetails", - 2 => "myway_transactions" - ); - foreach ($page->find("table") as $table) { - $tableNum++; - $tableColumns = Array(); - $tableColumnNum = 0; - foreach ($table->find("th") as $th) { - $tableColumns[$tableColumnNum] = cleanString($th->plaintext); - $tableColumnNum++; - } - //print_r($tableColumns); - $tableRowNum = 0; - foreach ($table->find("tr") as $tr) { - $tableColumnNum = 0; - foreach ($tr->find("td") as $td) { - if ($tableNum == 1) { - // first table has card/cardholder details - $return[$tableName[$tableNum]][$tableColumns[$tableColumnNum]] = cleanString($td->plaintext); - } else { - // second table has transactions - - if ($tableColumns[$tableColumnNum] == "TX Reference No / Type") { - $return[$tableName[$tableNum]][$tableRowNum]["TX Reference No"] = substr(cleanString($td->plaintext), 0,6); - $return[$tableName[$tableNum]][$tableRowNum]["TX Type"] = substr(cleanString($td->plaintext), 7); - } else { - $return[$tableName[$tableNum]][$tableRowNum][$tableColumns[$tableColumnNum]] = cleanString($td->plaintext); - } - } - //print_r($return); - $tableColumnNum++; - } - $tableRowNum++; - } - } - } -} -if (sizeof($return) == 0) { -$return['error'][] = "No data extracted from MyWay website - API may be out of date"; -} - -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'); -if (isset($_GET['callback'])) { - $json = '(' . json_encode($return) . ');'; //must wrap in parens and end with semicolon - print_r($_GET['callback'] . $json); //callback is prepended for json-p - -} -else echo json_encode($return); -?> - --- a/labs/myway_timeliness.php +++ /dev/null @@ -1,118 +1,1 @@ - - - - -
- --- a/labs/myway_timeliness_calculate.php +++ /dev/null @@ -1,142 +1,1 @@ -prepare($query); -$query->execute(); -if (!$query) { - databaseError($conn->errorInfo()); - return Array(); -} -$uncalcdObservations = $query->fetchAll(); -//Display count -echo "

" . sizeof($uncalcdObservations) . " observations not yet processed

"; -//foreach observation not in delta -foreach ($uncalcdObservations as $obsv) { - //var_dump($obsv); - echo "

Observation {$obsv['observation_id']}:

-{$obsv['myway_stop']} @ {$obsv['time']} on {$obsv['myway_route']}
"; - if ($obsv["stop_code"] == "") { - echo "error, stop '{$obsv['myway_stop']}' unknown"; - continue; - } - if ($obsv["route_full_name"] == "") { - echo "error, route '{$obsv['myway_route']}' unknown"; - continue; - } - // convert timestamp into time of day and date -// timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html - $time = date("H:i:s", strtotime($obsv['time'])); - $time_tz = date("H:i:s", strtotime($obsv['time']))." AESST"; - $search_time = date("H:i:s", strtotime($obsv['time'])-(30*60)); // 30 minutes margin - $date = date("c", strtotime($obsv['time'])); - $timing_period = service_period(strtotime($date)); - $potentialStops = getStopsByStopCode($obsv["stop_code"], $obsv["stop_street"]); - //:get myway_stops records - //:search by starts with stopcode and starts with street if street is not null - //no result, skip and display error - if (sizeof($potentialStops) < 1) { - echo "error, potential stops for stopcode {$obsv["stop_code"]} street {$obsv["stop_street"]} unknown"; - continue; - } - //print out stops - echo "Matched stops: "; - foreach ($potentialStops as $potentialStop) echo $potentialStop['stop_code'] . " "; - echo "
"; - //:get myway_route record - //no result, skip and display error - //print out route - $potentialRoute = getRouteByFullName($obsv["route_full_name"]); - if ($potentialRoute["route_short_name"] == "") { - echo "error, route '{$obsv["route_full_name"]}' unknown"; - continue; - } - echo "Matched route: {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']} {$timing_period}
"; - $timeDeltas = Array(); - foreach ($potentialStops as $potentialStop) { - $stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period); - $foundRoute = Array(); - foreach ($stopRoutes as $stopRoute) { - //Check if this route stops at each stop - if ($stopRoute['route_short_name'] . $stopRoute['route_long_name'] == $obsv["route_full_name"]) { - echo "Matching route {$stopRoute['route_id']} found at {$potentialStop['stop_code']}
"; - $foundRoute = $stopRoute; - //if does get tripstoptimes for this route - $trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time); - foreach ($trips as $trip) { - //echo $trip['route_id']." ".$stopRoute['route_id'].";"; - if ($trip['route_id'] == $stopRoute['route_id']) { - $timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']); - $actual_time = strtotime($time); - $trip_time = strtotime($timedTrip['arrival_time']); - $timeDiff = $actual_time - $trip_time; - //work out time delta, put into array with index of delta - $timeDeltas[] = Array( - "timeDiff" => $timeDiff, - "stop_code" => $potentialStop['stop_code'], - "stop_sequence" => $timedTrip['stop_sequence'] - ); - echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_code']} (#{$potentialStop['stop_id']}, sequence #{$trip['stop_sequence']})
"; - echo "Arriving at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes
"; - } - } - break; // because have found route - - } - } - if (sizeof($foundRoute) < 1) { - //print out that stops/does not stop - echo "No matching routes found at {$potentialStop['stop_code']}
"; - var_dump($stopRoutes); - flush(); - } - } - // lowest delta is recorded delta - usort($timeDeltas, "abssort"); - $lowestDelta = $timeDeltas[0]["timeDiff"]; - if (sizeof($timeDeltas) != 0) { - echo "Lowest difference of " . round($lowestDelta / 60, 2) . " minutes will be recorded for this observation
"; - $observation_id = $obsv['observation_id']; - $route_full_name = $obsv['route_full_name']; - $stop_code = $timeDeltas[0]["stop_code"]; - $stop_sequence = $timeDeltas[0]["stop_sequence"]; - $stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_full_name, stop_code, timing_delta, time, date, timing_period, stop_sequence) - values (:observation_id, :route_full_name, :stop_code, :timing_delta, :time, :date, :timing_period, :stop_sequence)"); - $stmt->bindParam(':observation_id', $observation_id); - $stmt->bindParam(':route_full_name', $route_full_name); - $stmt->bindParam(':stop_code', $stop_code); - $stmt->bindParam(':timing_delta', $lowestDelta); - $stmt->bindParam(':time', $time_tz); - $stmt->bindParam(':date', $date); - $stmt->bindParam(':timing_period', $timing_period); - $stmt->bindParam(':stop_sequence', $stop_sequence); - // insert a record - $stmt->execute(); - if ($stmt->rowCount() > 0) { - echo "Recorded.
"; - } - var_dump($conn->errorInfo()); - flush(); - } - flush(); -} - --- a/labs/myway_timeliness_freqdist.php +++ /dev/null @@ -1,45 +1,1 @@ - - - - -
- --- a/labs/myway_timeliness_overview.php +++ /dev/null @@ -1,97 +1,1 @@ - - - - -prepare($query); -$query->execute(); -if (!$query) { - databaseError($conn->errorInfo()); - return Array(); -} -foreach ($query->fetchAll() as $row) { - echo ""; -}; -?> - - -prepare($query); -$query->execute(); -if (!$query) { - databaseError($conn->errorInfo()); - return Array(); -} -foreach ($query->fetchAll() as $row) { - echo ""; -}; -?> - - -prepare($query); -$query->execute(); -if (!$query) { - databaseError($conn->errorInfo()); - return Array(); -} -foreach ($query->fetchAll() as $row) { - echo ""; -}; -?> - -prepare($query); -$query->execute(); -if (!$query) { - databaseError($conn->errorInfo()); - return Array(); -} -foreach ($query->fetchAll() as $row) { - echo ""; -}; -?> - - - 1 order by myway_stop"; -$query = $conn->prepare($query); -$query->execute(); -if (!$query) { - databaseError($conn->errorInfo()); - return Array(); -} -foreach ($query->fetchAll() as $row) { - echo ""; -}; -?> - - 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 ""; -}; -?> - - -
MeanStandard
Deviation
Sample Size
Overall
{$row[0]}" . floor($row[1]) . "" . floor($row[2]) . "{$row[3]}
Hour of Day
{$row[0]}" . floor($row[1]) . "" . floor($row[2]) . "{$row[3]}
Day of Week
{$row[0]}" . floor($row[1]) . "" . floor($row[2]) . "{$row[3]}
Month
{$row[0]}" . floor($row[1]) . "" . floor($row[2]) . "{$row[3]}
Stop
{$row[0]}" . floor($row[1]) . "" . floor($row[2]) . "{$row[3]}
Route
{$row[0]}" . floor($row[1]) . "" . floor($row[2]) . "{$row[3]}
- - - --- a/labs/myway_timeliness_reconcile.php +++ /dev/null @@ -1,132 +1,1 @@ - $value) { - if (strstr($key, "route") && !strstr($value, "Select")) { - $myway_route = str_replace("route", "", $key); - $route_full_name = $value; - $query = "update myway_routes set route_full_name = :route_full_name where myway_route = :myway_route"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":myway_route", $myway_route,PDO::PARAM_STR, 5); - $query->bindParam(":route_full_name", $route_full_name,PDO::PARAM_STR, 42); - $query->execute(); - die(print_r($conn->errorInfo() , true)); - } - if (strstr($key, "myway_stop")) { - $myway_stop = $value; - $stop_code = $_REQUEST['stop_code']; - $stop_street = $_REQUEST['stop_street']; - $query = "update myway_stops set stop_code = :stop_code, stop_street = :stop_street where myway_stop = :myway_stop"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":myway_stop", $myway_stop, PDO::PARAM_STR, 25); - $query->bindParam(":stop_code", $stop_code, PDO::PARAM_STR, 32); - $query->bindParam(":stop_street", $stop_street); - $query->execute(); - die(print_r($conn->errorInfo() , true)); - } -} -include_header("MyWay Data Reconcile", "mywayTimeRec"); -// initialise -$count = $conn->exec("insert into myway_stops - select distinct myway_stop from myway_observations - WHERE myway_stop NOT IN - ( - SELECT myway_stop - FROM myway_stops - )"); -echo "$count new stops.
"; -if (!$count) { - print_r($conn->errorInfo()); -} -$count = $conn->exec("insert into myway_routes select distinct myway_route from myway_observations - WHERE myway_route NOT IN - ( - SELECT myway_route - FROM myway_routes - )"); -echo "$count new routes.
"; -if (!$count) { - print_r($conn->errorInfo()); -} -echo "

Stops

"; -/*stops - search start of name, display map and table nuimbered, two text boxes */ -$query = "Select * from myway_stops where stop_code is NULL and stop_street is NUll;"; -debug($query, "database"); -$query = $conn->prepare($query); -$query->execute(); -if (!$query) { - databaseError($conn->errorInfo()); - return Array(); -} -foreach ($query->fetchAll() as $myway_stop) { - echo "

{$myway_stop[0]}

"; - $stopNameParts = explode(" ", $myway_stop[0]); - $markers = array(); - $stopKey = 1; - $foundStops = getStops(false, "", $stopNameParts[0] . " " . $stopNameParts[1]); - if (sizeof($foundStops) > 0) { - echo ""; - foreach ($foundStops as $stopResult) { - $markers[] = array( - $stopResult['stop_lat'], - $stopResult['stop_lon'] - ); - echo ""; - } - echo '
" . $stopKey++ . "" . $stopResult['stop_name'] . "" . $stopResult['stop_code'] . "
'; - echo "" . staticmap($markers, 0, "icong", false) . "
\n"; - } - echo '
- -
- - -
-
- - -
-'; - echo '
'; -} -echo '

Routes

'; -/*routes - remove alpha char, search present dropdown*/ -$query = "Select * from myway_routes where route_full_name is NUll;"; -debug($query, "database"); -$query = $conn->prepare($query); -$query->execute(); -if (!$query) { - databaseError($conn->errorInfo()); - return Array(); -} -foreach ($query->fetchAll() as $myway_route) { - echo "

{$myway_route[0]}

"; - $query = "Select * from myway_observations where myway_route = :route order by time"; - debug($query, "database"); - $query = $conn->prepare($query); - $query->bindParam(":route", $myway_route[0]); - $query->execute(); - if (!$query) { - databaseError($conn->errorInfo()); - return Array(); - } - foreach ($query->fetchAll() as $myway_obvs) { - echo $myway_obvs['myway_stop'] . $myway_obvs['time'] . "
"; - } - $searchRouteNo = preg_replace("/[A-Z]/", "", $myway_route[0]); - echo $searchRouteNo; - echo '
-
"; - echo '
'; -} -include_footer(); -?> --- a/labs/myway_timeliness_route.json.php +++ /dev/null @@ -1,25 +1,1 @@ - -{ - "label": "", - "data": 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)."]"; -?> -} + --- a/labs/myway_timeliness_route.php +++ /dev/null @@ -1,125 +1,1 @@ - - - - -
- -
- - --- a/labs/myway_timeliness_stop.json.php +++ /dev/null @@ -1,32 +1,1 @@ - -{ - "label": "", - "data": 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)."]"; -?> -} --- a/labs/myway_timeliness_stop.php +++ /dev/null @@ -1,136 +1,1 @@ - - - - - -
- - --- a/labs/mywaybalance.php +++ /dev/null @@ -1,124 +1,1 @@ - -
- Back -

MyWay Balance

- Logout -
- -
'; -$return = Array(); -function logout() -{ - setcookie("card_number", "", time() - 60 * 60 * 24 * 100, "/"); - setcookie("date", "", time() - 60 * 60 * 24 * 100, "/"); - setcookie("secret_answer", "", time() - 60 * 60 * 24 * 100, "/"); - setcookie("contribute_myway", "", time() - 60 * 60 * 24 * 100, "/"); -} -function printBalance($mywayResult) -{ - if (isset($mywayResult['error'])) { - logout(); - echo '

' . $mywayResult['error'][0] . "

"; - } - else { - echo "

Balance: " . $mywayResult['myway_carddetails']['Card Balance'] . "

"; - echo '
  • Recent Transactions
  • '; - $txCount = 0; - foreach ($mywayResult['myway_transactions'] as $transaction) { - echo "
  • "; - if ($transaction["Deduction Type"] == "DEFAULT") echo 'Failed to tap off: '; - echo "" . $transaction["Date / Time"] . ""; - echo "
    " . $transaction["Route"] . " at " . $transaction["Stop Name"] . "
    "; - echo $transaction["TX Reference No"] . " " . $transaction["TX Type"] . "
    "; - echo '

    ' . $transaction["TX Amount"] . '

    '; - echo "
  • "; - $txCount++; - if ($txCount > 10) break; - } - echo "
"; - } -} -function recordMyWayObservations($mywayResult) -{ - global $conn; - if (!isset($mywayResult['error'])) { - $stmt = $conn->prepare("insert into myway_observations (observation_id, myway_stop, time, myway_route) - values (:observation_id, :myway_stop, :time, :myway_route)"); - $stmt->bindParam(':observation_id', $observation_hash); - $stmt->bindParam(':myway_stop', $myway_stop); - $stmt->bindParam(':time', $timestamp); - $stmt->bindParam(':myway_route', $myway_route); - // insert a record - $resultCount = 0; - foreach ($mywayResult['myway_transactions'] as $transaction) { - if ($transaction["Stop Name"] != "" && $transaction["Deduction Type"] != "DEFAULT") { - $observation_hash = md5($mywayResult['myway_carddetails']['MyWay Number'] . $transaction["TX Reference No"]); - $timestamp = date("c", strtotime($transaction["Date / Time"])); - $myway_stop = $transaction["Stop Name"]; - $myway_route = $transaction["Route"]; - if ($stmt->execute()) $resultCount++; - } - } - echo "

Thanks for participating in the study! $resultCount transactions were recorded

"; - } -} -if (isset($_REQUEST['card_number']) && isset($_REQUEST['date']) && isset($_REQUEST['secret_answer'])) { - $cardNumber = $_REQUEST['card_number']; - $date = explode("/", $_REQUEST['date']); - $pwrd = $_REQUEST['secret_answer']; - if ($_REQUEST['remember'] == "on") { - setcookie("card_number", $cardNumber, time() + 60 * 60 * 24 * 100, "/"); - setcookie("date", $_REQUEST['date'], time() + 60 * 60 * 24 * 100, "/"); - setcookie("contribute_myway", $_REQUEST['contribute_myway'], time() + 60 * 60 * 24 * 100, "/"); - setcookie("secret_answer", $pwrd, time() + 60 * 60 * 24 * 100, "/"); - } - $mywayResult = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd") , true); - if ($_REQUEST['contribute_myway'] == "on") recordMyWayObservations($mywayResult); - printBalance($mywayResult); -} -else if (isset($_REQUEST['logout'])) { - echo '

Logged out of MyWay balance

Back to main menu...
'; -} -else if (isset($_COOKIE['card_number']) && isset($_COOKIE['date']) && isset($_COOKIE['secret_answer'])) { - $cardNumber = $_COOKIE['card_number']; - $date = explode("/", $_COOKIE['date']); - $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); - if ($_COOKIE['contribute_myway'] == "on") recordMyWayObservations($mywayResult); - printBalance($mywayResult); -} -else { - $date = (isset($_REQUEST['date']) ? filter_var($_REQUEST['date'], FILTER_SANITIZE_STRING) : date("m/d/Y")); - echo ' -
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
- '; -} -include_footer(); -?> --- a/labs/travelAllRoutes.php +++ /dev/null @@ -1,23 +1,1 @@ -prepare($query); - $query->execute(); -echo ""; -$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 ""; -} -echo "
Route NumberFirst Trip StartFirst Trip EndLength
{$r['route_short_name']}$startTime$endTime$timeDiff seconds ie. ". ($timeDiff/60). " minutes
"; -echo "Total time: $total seconds ie. " .($total/60/60). " hours
"; -echo "$count Routes"; -?> --- a/labs/tripPlannerTester.kml.php +++ /dev/null @@ -1,208 +1,1 @@ -metadata; - $tripplan = json_decode($response); - $plans = Array(); - //var_dump(Array($info, $request)); - if (is_array($tripplan->plan->itineraries->itinerary)) { - foreach ($tripplan->plan->itineraries->itinerary as $itineraryNumber => $itinerary) { - $plans[floor($itinerary->duration / 60000) ] = $itinerary; - } - } - else { - $plans[floor($tripplan->plan->itineraries->itinerary->duration / 60000) ] = $tripplan->plan->itineraries->itinerary; - } - if ($csv) echo "{$md['i']},{$md['j']}," . min(array_keys($plans)) . ",$latdeltasize, $londeltasize,{$md['key']}\n"; - if ($kml) { - $time = min(array_keys($plans)); - $plan = ""; - if (is_array($plans[min(array_keys($plans)) ]->legs->leg)) { - foreach ($plans[min(array_keys($plans)) ]->legs->leg as $legNumber => $leg) { - $plan.= processLeg($legNumber, $leg) . ","; - } - } - else { - $plan.= processLeg(0, $plans[min(array_keys($plans)) ]->legs->leg); - } - if (isset($tripplan->error) && $tripplan->error->id == 404) { - $time = 999; - $plan = "Trip not possible without excessive walking from nearest bus stop"; - } - $testRegions[] = Array( - "lat" => $md['i'], - "lon" => $md['j'], - "time" => $time, - "latdeltasize" => $latdeltasize, - "londeltasize" => $londeltasize, - "regionname" => $md['key'], - "plan" => $plan . '
original plan' - ); - $regionTimes[] = $time; - } -} -function Gradient($HexFrom, $HexTo, $ColorSteps) -{ - $theColorBegin = hexdec($HexFrom); - $theColorEnd = hexdec($HexTo); - $theNumSteps = intval($ColorSteps); - $theR0 = ($theColorBegin & 0xff0000) >> 16; - $theG0 = ($theColorBegin & 0x00ff00) >> 8; - $theB0 = ($theColorBegin & 0x0000ff) >> 0; - $theR1 = ($theColorEnd & 0xff0000) >> 16; - $theG1 = ($theColorEnd & 0x00ff00) >> 8; - $theB1 = ($theColorEnd & 0x0000ff) >> 0; - $GradientColors = array(); - // generate gradient swathe now - for ($i = 0; $i <= $theNumSteps; $i++) { - $theR = interpolate($theR0, $theR1, $i, $theNumSteps); - $theG = interpolate($theG0, $theG1, $i, $theNumSteps); - $theB = interpolate($theB0, $theB1, $i, $theNumSteps); - $theVal = ((($theR << 8) | $theG) << 8) | $theB; - $GradientColors[] = sprintf("%06X", $theVal); - } - return $GradientColors; -} -function processLeg($legNumber, $leg) -{ - $legArray = object2array($leg); - if ($legArray["@mode"] === "BUS") { - return "bus {$legArray['@route']} " . str_replace("To", "towards", $legArray['@headsign']); - } - else { - return "walk"; - //$walkingstep = "walk "; - //if (strpos($step->streetName, "from") !== false && strpos($step->streetName, "way") !== false) { - // $walkingstep.= "footpath"; - //} - //else { - // $walkingstep.= $step->streetName; - //} - //$walkingstep.= floor($step->distance) . "m"; - //return $walkingstep; - - } -} -$csv = false; -$kml = true; -$gearthcolors = false; -if ($kml) { - header('Content-Type: application/vnd.google-earth.kml+xml'); - echo ' -'; -} -include ('../include/common.inc.php'); -$boundingBoxes = Array( - "belconnen" => Array( - "startlat" => - 35.1928, - "startlon" => 149.006, - "finishlat" => - 35.2630, - "finishlon" => 149.1045, - ) , - "north gungahlin civic" => Array( - "startlat" => - 35.1828, - "startlon" => 149.1045, - "finishlat" => - 35.2955, - "finishlon" => 149.1559, - ) , - "west duffy" => Array( - "startlat" => - 35.3252, - "startlon" => 149.0240, - "finishlat" => - 35.3997, - "finishlon" => 149.0676, - ) , - "central south" => Array( - "startlat" => - 35.3042, - "startlon" => 149.0762, - "finishlat" => - 35.3370, - "finishlon" => 149.1806, - ) , - "south" => Array( - "startlat" => - 35.3403, - "startlon" => 149.0714, - "finishlat" => - 35.4607, - "finishlon" => 149.1243, - ) -); -$latdeltasize = 0.005; -$londeltasize = 0.005; -$from = "Wattle Street"; -$fromPlace = (startsWith($from, "-") ? $from : geocode($from, false)); -$startTime = "9:00 am"; -$startDate = "03/21/2011"; // american dates, OTP does not validate! -$counter = 0; -$regionTimes = Array(); -$testRegions = Array(); -$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"; -if ($kml) echo " $from at $startTime on $startDate "; -if ($csv) echo "
";
-if ($csv) echo "lat,lon,time,latdeltasize, londeltasize, region key name\n";
-$rc = new RollingCurl("processResult_cb");
-$rc->window_size = 2;
-foreach ($boundingBoxes as $key => $boundingBox) {
-	for ($i = $boundingBox['startlat']; $i >= $boundingBox['finishlat']; $i-= $latdeltasize) {
-		for ($j = $boundingBox['startlon']; $j <= $boundingBox['finishlon']; $j+= $londeltasize) {
-			$url = $otpAPIurl . "ws/plan?date=" . urlencode($startDate) . "&time=" . urlencode($startTime) . "&mode=TRANSIT%2CWALK&optimize=QUICK&maxWalkDistance=440&wheelchair=false&toPlace=" . $i . "," . $j . "&fromPlace=$fromPlace";
-			//debug($url);
-			$request = new RollingCurlRequest($url);
-			$request->headers = Array(
-				"Accept: application/json"
-			);
-			$request->metadata = Array( "i" => $i, "j" => $j, "key" => $key, "url" => $url);
-			$rc->add($request);
-		}
-	}
-}
-$rc->execute();
-if ($kml) {
-	$colorSteps = 9;
-	//$minTime = min($regionTimes);
-	//$maxTime = max($regionTimes);
-	//$rangeTime = $maxTime - $minTime;
-	//$deltaTime = $rangeTime / $colorSteps;
-	$Gradients = Gradient(strrev("66FF00") , strrev("FF0000") , $colorSteps); // KML is BGR not RGB so strrev
-	foreach ($testRegions as $testRegion) {
-		//$band = (floor(($testRegion[time] - $minTime) / $deltaTime));
-		$band = (floor($testRegion[time] / 10));
-		if ($band > $colorSteps) $band = $colorSteps;
-		echo "
-  " . $testRegion['regionname'] . " time {$testRegion['time']} band $band
-    
-    
-   
-relativeToGround
-    
-      
-        
-          " . ($testRegion['lon'] - ($testRegion['londeltasize'] / 2)) . "," . ($testRegion['lat'] - ($testRegion['latdeltasize'] / 2)) . ",500\n" . ($testRegion['lon'] - ($testRegion['londeltasize'] / 2)) . "," . ($testRegion['lat'] + ($testRegion['latdeltasize'] / 2)) . ",500\n" . ($testRegion['lon'] + ($testRegion['londeltasize'] / 2)) . "," . ($testRegion['lat'] + ($testRegion['latdeltasize'] / 2)) . ",500\n" . ($testRegion['lon'] + ($testRegion['londeltasize'] / 2)) . "," . ($testRegion['lat'] - ($testRegion['latdeltasize'] / 2)) . ",500\n" . ($testRegion['lon'] - ($testRegion['londeltasize'] / 2)) . "," . ($testRegion['lat'] - ($testRegion['latdeltasize'] / 2)) . ",500\n" . "
-	  
-        
-      
-    
-  
-";
-	}
-	echo "\n\n";
-}
-if ($csv) echo "
"; -?> --- a/labs/tripPlannerTester.php +++ /dev/null @@ -1,96 +1,1 @@ - - - - - - - - -
- - - - --- /dev/null +++ b/lib/Protobuf-PHP/LICENSE @@ -1,1 +1,21 @@ +The MIT License +Copyright (c) 2011 Iván -DrSlump- Montes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. --- /dev/null +++ b/lib/Protobuf-PHP/README.md @@ -1,1 +1,198 @@ +Protobuf for PHP +================ +Protobuf for PHP is an implementation of Google's Protocol Buffers for the PHP +language, supporting its binary data serialization and including a `protoc` +plugin to generate PHP classes from .proto files. + +Great effort has been put into generating PHP files that include all sort of type +hints to aide IDE's with autocompletion. Therefore, it can not only be used to +communicate with Protocol Buffers services but also as a generation tool for +_data objects_ no matter what the final serialization is. + +For more information see the [included man pages](http://drslump.github.com/Protobuf-PHP/). + + +## Requirements + + - PHP 5.3 + - Pear's Console_CommandLine (for the protoc wrapper tool) + - Google's `protoc` compiler version 2.3 or above + - GMP or BC Math extensions ¹ + + ¹ Only needed for negative values in `int32`, `int64` or `fixed64` types. See + the _known issues_ section. + + +## Features + +### Working + + - Standard types (numbers, string, enums, messages, etc) + - Pluggable serialization backends (codecs) + - Standard Binary + - Standard TextFormat ¹ + - PhpArray + - JSON + - [ProtoJson](https://github.com/drslump/ProtoJson) (_TagMap_ and _Indexed_ variants) + - XML + - Protoc compiler plugin to generate the PHP classes + - Extensions + - Unknown fields + - Packed fields + - Reflection + - Dynamic messages with annotations support + - Generates service interfaces + - Includes comments from .proto files in the generated files + - Pear package for easy installation + +¹ Only serialization is supported + +### Future + + - Speed optimized code generation mode + - Support numbers beyond PHP's native limits + + + +## Example usage + + $person = new Tutorial\Person(); + $person->name = 'DrSlump'; + $person->setId(12); + + $book = new Tutorial\AddressBook(); + $book->addPerson($person); + + // Use default codec + $data = $book->serialize(); + + // Use custom codec + $codec = new \DrSlump\Protobuf\Codec\Binary(); + $data = $codec->encode($book); + // ... or ... + $data = $book->serialize($codec); + + +## Installation + +Install with Pear + + pear channel-discover pear.pollinimini.net + pear install drslump/Protobuf-beta + +You can also get the latest version by checking out a copy of the +repository in your computer. + + + +## Known issues + + +### Types + +PHP is very weak when dealing with numbers processing. Several work arounds have been applied +to the standard binary codec to reduce incompatibilities between Protobuf types and PHP ones. + + - Protobuf stores floating point values using the [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754) standard + with 64bit words for the `double` and 32bit for the `float` types. PHP supports IEEE 754 natively although + the precission is platform dependant, however it typically supports 64bit doubles. It means that + if your PHP was compiled with 64bit sized doubles (or greater) you shouldn't have any problem encoding + and decoded float and double typed values with Protobuf. + + - Integer values are also [platform dependant in PHP](http://www.php.net/manual/en/language.types.integer.php). + The library has been developed and tested against PHP binaries compiled with 64bit integers. The encoding and + decoding algorithm should in theory work no matter if PHP uses 32bit or 64bit integers internally, just take + into account that with 32bit integers the numbers cannot exceed in any case the `PHP_INT_MAX` value (2147483647). + + While Protobuf supports unsigned integers PHP does not. In fact, numbers above the compiled PHP maximum + integer (`PHP_INT_MAX`, 0x7FFFFFFFFFFFFFFF for 64bits) will be automatically casted to doubles, which + typically will offer 53bits of decimal precission, allowing to safely work with numbers upto + 0x20000000000000 (2^53), even if they are represented in PHP as floats instead of integers. Higher numbers + will loose precission or might even return an _infinity_ value, note that the library does not include + any checking for these numbers and using them might provoke unexpected behaviour. + + Negative values when encoded as `int32`, `int64` or `fixed64` types require the big integer extensions + [GMP](http://www.php.net/gmp) or [BC Math](http://www.php.net/bc) (the later only for 64bit architectures) + to be available in your PHP environment. The reason is that when encoding these negative numbers without + using _zigzag_ the binary representation uses the most significant bit for the sign, thus the numbers become + above the maximum supported values in PHP. The library will check for these conditions and will automatically + try to use GMP or BC to process the value. + + +### Strings + +The binary codec expects strings to be encoded using UTF-8. PHP does not natively support string encodings, +PHP's string data type is basically a length delimited stream of bytes, so it's not trivial to include +automatic encoding conversion into the library encoding and decoding routines. Instead of trying to guess +or offer a configuration interface for the encoding, the binary codec will process the `string` type just as +it would process `byte` one, delegating on your application the task of encoding or decoding in the desired +character set. + +### Memory usage + +Large messages might be troublesome since the way the library is modelled does not allow to parse or +serialize messages as a streams, instead the whole operation is performed in memory, which allows for faster +processing but could consume too much RAM if messages are too large. + + +### Unknown fields + +Since wire types are different across different codec's formats, it's not possible to transcode unkwnon +fields consumed in one codec to another. This means, for example, that when consuming a message using the +binary codec, if it contains unknown fields, they won't be included when serializing the message using the +Json codec. + + +## Generating PHP classes + +The generation tool is designed to be run as a `protoc` plugin, thus it should +work with any proto file supported by the official compiler. + + protoc --plugin=protoc-gen-php --php_out=./build tutorial.proto + +To make use of non-standard options in your proto files (like `php.namespace`) you'll +have to import the `php.proto` file included with the library. It's location will +depend on where you've installed this library. + + protoc -I=./Protobuf-PHP/library/DrSlump/Protobuf/Compiler/protos \ + --plugin=protoc-gen-php --php_out=./build tutorial.proto + +In order to make your life easier, the supplied protoc plugin offers an additional +execution mode, where it acts as a wrapper for the `protoc` invocation. It will +automatically include the `php.proto` path so that you don't need to worry about it. + + protoc-gen-php -o ./build tutorial.proto + + +## LICENSE: + + The MIT License + + Copyright (c) 2011 Iván -DrSlump- Montes + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + 'Software'), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + + --- /dev/null +++ b/lib/Protobuf-PHP/Rakefile @@ -1,1 +1,120 @@ +# encoding: utf-8 +namespace :pear do + support_files = ['README.md', 'LICENSE', 'protoc-gen-php.php', 'protoc-gen-php.bat'] + tpl_file = 'package.pear' + xml_file = 'library/package.xml' + + desc "Generate package.xml" + task :xml => [:clean] do |t, args| + unless ENV['version'] then + puts 'Version number not given. Use "pear:xml version=1.0"' + exit 1 + end + + # Get template contents + text = File.read(tpl_file, :encoding => "UTF-8") + # Replace the version, date and time + text = text.gsub("{VERSION}", ENV['version']) + text = text.gsub('{DATE}', Time.now.strftime('%Y-%m-%d')) + text = text.gsub('{TIME}', Time.now.strftime('%H:%M:%S')) + + # Include source files + dirs = [] + Dir.glob('library/**/*.*') do |file| + file[0, 'library/'.length] = '' + dirs << '' + dirs << '' + dirs << '' + end + + text = text.gsub('{DIRS}', dirs.join("\n")) + + # Generate a new pear package.xml + xml = File.new(xml_file, 'w') + xml.syswrite(text); + xml.close(); + end + + desc "Build a release" + task :package => ['doc:build', :xml] do + + # Copy supporting files to the package root + + support_files.each do |file| + cp file, "library/#{file}" + end + + begin + sh "pear package -n #{xml_file}" + rescue Exception => e + puts "Rolling back..." + Rake::Task['pear:clean'].execute + raise + end + + Rake::Task['pear:clean'].execute + end + + desc "Clean up" + task :clean do + puts "Cleaning up..." + + # Remove package.xml + rm_f xml_file + + # Remove supporting files + support_files.each { |file| rm_f "library/#{file}" } + end + +end + +namespace :doc do + + desc "Generate manual" + task :build do + version = ENV['version'] + ENV['RONN_MANUAL'] = "Protobuf-PHP #{version}" + ENV['RONN_ORGANIZATION'] = "Ivan -DrSlump- Montes" + sh "ronn -w -s toc -r5 --markdown man/*.ronn" + end + + desc 'Publish to github pages' + task :github => 'doc:build' do + require 'git' + require 'logger' + + remote = `git remote show origin` + .split(%r{\n}) # Ruby 1.9 only has grep() on Array + .grep(/Push.*URL/) + .first[/git@.*/] + + files = [ + 'protoc-gen-php.1.html', + 'protobuf-php.3.html', + 'protobuf-php.5.html', + ] + + root = "/tmp/checkout-#{Time.now.to_i}" + g = Git.clone(remote, root, :log => Logger.new(STDOUT)) + + # Make sure this actually switches branches. + g.checkout(g.branch('gh-pages')) + + files.each {|file| + cp "man/#{file}", "#{root}/." + g.add(file) + } + + g.commit('Regenerating Github Pages.') + + # PUSH! + g.push(g.remote('origin'), g.branch('gh-pages')) + + puts '--> GitHub Pages Commit and Push successful.' + end + +end + + + --- /dev/null +++ b/lib/Protobuf-PHP/gtfs-realtime.php @@ -1,1 +1,3673 @@ - +number = 1; + $f->name = "header"; + $f->type = 11; + $f->rule = 2; + $f->reference = '\transit_realtime\FeedHeader'; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedMessage:header) + $descriptor->addField($f); + + // repeated .transit_realtime.FeedEntity entity = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "entity"; + $f->type = 11; + $f->rule = 3; + $f->reference = '\transit_realtime\FeedEntity'; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedMessage:entity) + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + // @@protoc_insertion_point(scope_descriptor) + // @@protoc_insertion_point(descriptor_transit_realtime.FeedMessage) + + return $descriptor; + } + + /** @var \transit_realtime\FeedHeader */ + public $header = null; + + /** @var \transit_realtime\FeedEntity[] */ + public $entity = array(); + + + /** + * Check if
has a value + * + * @return boolean + */ + public function hasHeader(){ + return $this->_has(1); + } + + /** + * Clear
value + * + * @return \transit_realtime\FeedMessage + */ + public function clearHeader(){ + return $this->_clear(1); + } + + /** + * Get
value + * + * @return \transit_realtime\FeedHeader + */ + public function getHeader(){ + return $this->_get(1); + } + + /** + * Set
value + * + * @param \transit_realtime\FeedHeader $value + * @return \transit_realtime\FeedMessage + */ + public function setHeader(\transit_realtime\FeedHeader $value){ + return $this->_set(1, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasEntity(){ + return $this->_has(2); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedMessage + */ + public function clearEntity(){ + return $this->_clear(2); + } + + /** + * Get value + * + * @param int $idx + * @return \transit_realtime\FeedEntity + */ + public function getEntity($idx = NULL){ + return $this->_get(2, $idx); + } + + /** + * Set value + * + * @param \transit_realtime\FeedEntity $value + * @return \transit_realtime\FeedMessage + */ + public function setEntity(\transit_realtime\FeedEntity $value, $idx = NULL){ + return $this->_set(2, $value, $idx); + } + + /** + * Get all elements of + * + * @return \transit_realtime\FeedEntity[] + */ + public function getEntityList(){ + return $this->_get(2); + } + + /** + * Add a new element to + * + * @param \transit_realtime\FeedEntity $value + * @return \transit_realtime\FeedMessage + */ + public function addEntity(\transit_realtime\FeedEntity $value){ + return $this->_add(2, $value); + } + + + // @@protoc_insertion_point(scope_class) + // @@protoc_insertion_point(class_transit_realtime.FeedMessage) + } +} + +namespace transit_realtime\FeedHeader { + + // @@protoc_insertion_point(scope_namespace) + // @@protoc_insertion_point(namespace_transit_realtime.FeedHeader) + + class Incrementality { + const FULL_DATASET = 0; + const DIFFERENTIAL = 1; + + // @@protoc_insertion_point(scope_class) + // @@protoc_insertion_point(class_transit_realtime.FeedHeader.Incrementality) + } +} +namespace transit_realtime { + + // @@protoc_insertion_point(scope_namespace) + // @@protoc_insertion_point(namespace_transit_realtime) + + class FeedHeader extends \DrSlump\Protobuf\Message { + + /** @var \Closure[] */ + protected static $__extensions = array(); + + public static function descriptor() + { + $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'transit_realtime.FeedHeader'); + + // required gtfs_realtime_version = 1 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 1; + $f->name = "gtfs_realtime_version"; + $f->type = 9; + $f->rule = 2; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedHeader:gtfs_realtime_version) + $descriptor->addField($f); + + // optional .transit_realtime.FeedHeader.Incrementality incrementality = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "incrementality"; + $f->type = 14; + $f->rule = 1; + $f->reference = '\transit_realtime\FeedHeader\Incrementality'; + $f->default = \transit_realtime\FeedHeader\Incrementality::FULL_DATASET; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedHeader:incrementality) + $descriptor->addField($f); + + // optional timestamp = 3 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 3; + $f->name = "timestamp"; + $f->type = 4; + $f->rule = 1; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedHeader:timestamp) + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + // @@protoc_insertion_point(scope_descriptor) + // @@protoc_insertion_point(descriptor_transit_realtime.FeedHeader) + + return $descriptor; + } + + /** @var string */ + public $gtfs_realtime_version = null; + + /** @var int - \transit_realtime\FeedHeader\Incrementality */ + public $incrementality = \transit_realtime\FeedHeader\Incrementality::FULL_DATASET; + + /** @var int */ + public $timestamp = null; + + + /** + * Check if has a value + * + * @return boolean + */ + public function hasGtfsRealtimeVersion(){ + return $this->_has(1); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedHeader + */ + public function clearGtfsRealtimeVersion(){ + return $this->_clear(1); + } + + /** + * Get value + * + * @return string + */ + public function getGtfsRealtimeVersion(){ + return $this->_get(1); + } + + /** + * Set value + * + * @param string $value + * @return \transit_realtime\FeedHeader + */ + public function setGtfsRealtimeVersion( $value){ + return $this->_set(1, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasIncrementality(){ + return $this->_has(2); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedHeader + */ + public function clearIncrementality(){ + return $this->_clear(2); + } + + /** + * Get value + * + * @return int - \transit_realtime\FeedHeader\Incrementality + */ + public function getIncrementality(){ + return $this->_get(2); + } + + /** + * Set value + * + * @param int - \transit_realtime\FeedHeader\Incrementality $value + * @return \transit_realtime\FeedHeader + */ + public function setIncrementality( $value){ + return $this->_set(2, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasTimestamp(){ + return $this->_has(3); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedHeader + */ + public function clearTimestamp(){ + return $this->_clear(3); + } + + /** + * Get value + * + * @return int + */ + public function getTimestamp(){ + return $this->_get(3); + } + + /** + * Set value + * + * @param int $value + * @return \transit_realtime\FeedHeader + */ + public function setTimestamp( $value){ + return $this->_set(3, $value); + } + + + // @@protoc_insertion_point(scope_class) + // @@protoc_insertion_point(class_transit_realtime.FeedHeader) + } +} + +namespace transit_realtime { + + // @@protoc_insertion_point(scope_namespace) + // @@protoc_insertion_point(namespace_transit_realtime) + + class FeedEntity extends \DrSlump\Protobuf\Message { + + /** @var \Closure[] */ + protected static $__extensions = array(); + + public static function descriptor() + { + $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'transit_realtime.FeedEntity'); + + // required id = 1 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 1; + $f->name = "id"; + $f->type = 9; + $f->rule = 2; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedEntity:id) + $descriptor->addField($f); + + // optional is_deleted = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "is_deleted"; + $f->type = 8; + $f->rule = 1; + $f->default = false; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedEntity:is_deleted) + $descriptor->addField($f); + + // optional .transit_realtime.TripUpdate trip_update = 3 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 3; + $f->name = "trip_update"; + $f->type = 11; + $f->rule = 1; + $f->reference = '\transit_realtime\TripUpdate'; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedEntity:trip_update) + $descriptor->addField($f); + + // optional .transit_realtime.VehiclePosition vehicle = 4 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 4; + $f->name = "vehicle"; + $f->type = 11; + $f->rule = 1; + $f->reference = '\transit_realtime\VehiclePosition'; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedEntity:vehicle) + $descriptor->addField($f); + + // optional .transit_realtime.Alert alert = 5 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 5; + $f->name = "alert"; + $f->type = 11; + $f->rule = 1; + $f->reference = '\transit_realtime\Alert'; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.FeedEntity:alert) + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + // @@protoc_insertion_point(scope_descriptor) + // @@protoc_insertion_point(descriptor_transit_realtime.FeedEntity) + + return $descriptor; + } + + /** @var string */ + public $id = null; + + /** @var boolean */ + public $is_deleted = true; + + /** @var \transit_realtime\TripUpdate */ + public $trip_update = null; + + /** @var \transit_realtime\VehiclePosition */ + public $vehicle = null; + + /** @var \transit_realtime\Alert */ + public $alert = null; + + + /** + * Check if has a value + * + * @return boolean + */ + public function hasId(){ + return $this->_has(1); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedEntity + */ + public function clearId(){ + return $this->_clear(1); + } + + /** + * Get value + * + * @return string + */ + public function getId(){ + return $this->_get(1); + } + + /** + * Set value + * + * @param string $value + * @return \transit_realtime\FeedEntity + */ + public function setId( $value){ + return $this->_set(1, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasIsDeleted(){ + return $this->_has(2); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedEntity + */ + public function clearIsDeleted(){ + return $this->_clear(2); + } + + /** + * Get value + * + * @return boolean + */ + public function getIsDeleted(){ + return $this->_get(2); + } + + /** + * Set value + * + * @param boolean $value + * @return \transit_realtime\FeedEntity + */ + public function setIsDeleted( $value){ + return $this->_set(2, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasTripUpdate(){ + return $this->_has(3); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedEntity + */ + public function clearTripUpdate(){ + return $this->_clear(3); + } + + /** + * Get value + * + * @return \transit_realtime\TripUpdate + */ + public function getTripUpdate(){ + return $this->_get(3); + } + + /** + * Set value + * + * @param \transit_realtime\TripUpdate $value + * @return \transit_realtime\FeedEntity + */ + public function setTripUpdate(\transit_realtime\TripUpdate $value){ + return $this->_set(3, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasVehicle(){ + return $this->_has(4); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedEntity + */ + public function clearVehicle(){ + return $this->_clear(4); + } + + /** + * Get value + * + * @return \transit_realtime\VehiclePosition + */ + public function getVehicle(){ + return $this->_get(4); + } + + /** + * Set value + * + * @param \transit_realtime\VehiclePosition $value + * @return \transit_realtime\FeedEntity + */ + public function setVehicle(\transit_realtime\VehiclePosition $value){ + return $this->_set(4, $value); + } + + /** + * Check if has a value + * + * @return boolean + */ + public function hasAlert(){ + return $this->_has(5); + } + + /** + * Clear value + * + * @return \transit_realtime\FeedEntity + */ + public function clearAlert(){ + return $this->_clear(5); + } + + /** + * Get value + * + * @return \transit_realtime\Alert + */ + public function getAlert(){ + return $this->_get(5); + } + + /** + * Set value + * + * @param \transit_realtime\Alert $value + * @return \transit_realtime\FeedEntity + */ + public function setAlert(\transit_realtime\Alert $value){ + return $this->_set(5, $value); + } + + + // @@protoc_insertion_point(scope_class) + // @@protoc_insertion_point(class_transit_realtime.FeedEntity) + } +} + +namespace transit_realtime\TripUpdate { + + // @@protoc_insertion_point(scope_namespace) + // @@protoc_insertion_point(namespace_transit_realtime.TripUpdate) + + class StopTimeEvent extends \DrSlump\Protobuf\Message { + + /** @var \Closure[] */ + protected static $__extensions = array(); + + public static function descriptor() + { + $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'transit_realtime.TripUpdate.StopTimeEvent'); + + // optional delay = 1 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 1; + $f->name = "delay"; + $f->type = 5; + $f->rule = 1; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.TripUpdate.StopTimeEvent:delay) + $descriptor->addField($f); + + // optional time = 2 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 2; + $f->name = "time"; + $f->type = 3; + $f->rule = 1; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.TripUpdate.StopTimeEvent:time) + $descriptor->addField($f); + + // optional uncertainty = 3 + $f = new \DrSlump\Protobuf\Field(); + $f->number = 3; + $f->name = "uncertainty"; + $f->type = 5; + $f->rule = 1; + // @@protoc_insertion_point(scope_field) + // @@protoc_insertion_point(field_transit_realtime.TripUpdate.StopTimeEvent:uncertainty) + $descriptor->addField($f); + + foreach (self::$__extensions as $cb) { + $descriptor->addField($cb(), true); + } + + // @@protoc_insertion_point(scope_descriptor) + // @@protoc_insertion_point(descriptor_transit_realtime.TripUpdate.StopTimeEvent) + + return $descriptor; + } + + /** @var int */ + public $delay = null; + + /** @var int */ + public $time = null; + + /** @var int */ + public $uncertainty = null; + + + /** + * Check if has a value + * + * @return boolean + */ + public function hasDelay(){ + return $this->_has(1); + } + + /** + * Clear value + * + * @return \transit_realtime\TripUpdate\StopTimeEvent + */ + public function clearDelay(){ + return $this->_clear(1); + } + + /** + * Get value + * + * @return int + */ + public function getDelay(){ + return $this->_get(1); + } + + /** + * Set value + * + * @param int $value + * @return \transit_realtime\TripUpdate\StopTimeEvent + */ + public function setDelay( $value){ + return $this->_set(1, $value); + } + + /** + * Check if
+ +'; + foreach(getInformedAlerts($_REQUEST['edit'], "", "") as $informed) { + echo "{$informed['informed_class']}{$informed['informed_id']}{$informed['informed_action']}" . 'delete'; + } + echo ''; + ?> +
+ + +
+
+
+ + +
+ + +
+
+
+ + +
+ + +
+ --- /dev/null +++ b/servicealerts/servicealerts_twitter/NameFinder.java @@ -1,1 +1,56 @@ +InputStream modelIn = new FileInputStream("en-ner-person.bin"); +try { + TokenNameFinder model = new TokenNameFinderModel(modelIn); +} +catch (IOException e) { + e.printStackTrace(); +} +finally { + if (modelIn != null) { + try { + modelIn.close(); + } + catch (IOException e) { + } + } +} + +NameFinderME nameFinder = new NameFinderME(model); + +for (String document[][] : documents) { + + for (String[] sentence : document) { + Span nameSpans[] = find(sentence); + // do something with the names + } + + nameFinder.clearAdaptiveData() +} + + + InputStream in = getClass() + .getClassLoader() + .getResourceAsStream( + "opennlp/tools/namefind/AnnotatedSentences.txt"); + + String encoding = "ISO-8859-1"; + + ObjectStream sampleStream = new NameSampleDataStream( + new PlainTextByLineStream(new InputStreamReader(in, + encoding))); + + TokenNameFinderModel nameFinderModel = NameFinderME.train("en", + "default", sampleStream, Collections + . emptyMap(), 70, 1); + + TokenNameFinder nameFinder = new NameFinderME(nameFinderModel); + + // now test if it can detect the sample sentences + + String sentence[] = { "Alisa", "appreciated", "the", "hint", + "and", "enjoyed", "a", "delicious", "traditional", + "meal." }; + + Span names[] = nameFinder.find(sentence); + --- /dev/null +++ b/servicealerts/servicealerts_twitter/pom.xml @@ -1,1 +1,19 @@ + + 4.0.0 + org.lambdacomplex.bus + servicealerts_twitter + 0.0.1-SNAPSHOT + + + org.apache.opennlp + opennlp + 1.5.1-incubating + + + org.apache.opennlp + opennlp-tools + 1.5.1-incubating + + + --- a/servicealerts_api.php +++ b/servicealerts_api.php @@ -1,49 +1,17 @@ 0) { - $entity = Array(); - $entity['id'] = $alert['id']; - $entity['alert']['active_period']['start'] = $alert['start']; - $entity['alert']['active_period']['start'] = $alert['end']; - $entity['alert']['url']['translation'] = $alert['url']; - $entity['alert']['description']['translation'] = $alert['description']; - - foreach ($informedEntities as $informedEntity) { - $informed = Array(); - $informed[$informedEntity['informed_class']."_id"] = $informedEntity['informed_id']; - if ($informedEntity['informed_action'] != "") $informed["x-action"] = $informedEntity['informed_action']; - //$informed[$informedEntity['class']."_type"] = $informedEntity['type']; - $entity['informed'][] = $informed; - } - $return['entities'][] = $entity; - } -} + +if (basename(__FILE__) == "servicealerts_api.php") { + $return = getServiceAlertsAsJSON($_REQUEST['filter_class'],$_REQUEST['filter_id']); 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'); if (isset($_GET['callback'])) { - $json = '(' . json_encode($return) . ');'; //must wrap in parens and end with semicolon + $json = '(' . $return . ');'; //must wrap in parens and end with semicolon //print_r($_GET['callback'] . $json); //callback is prepended for json-p } -else echo json_encode($return); +else echo $return; +} ?> --- a/sitemap.xml.php +++ b/sitemap.xml.php @@ -10,6 +10,9 @@ } foreach (scandir("./labs") as $file) { if (strpos($file,".php") !== false) echo " ".curPageURL()."/labs/$file0.3\n"; +} +foreach (scandir("./myway") as $file) { + if (strpos($file,".php") !== false) echo " ".curPageURL()."/myway/$file0.3\n"; } foreach (getStops() as $stop) { echo " ".curPageURL()."stop.php?stopid=".htmlspecialchars ($stop["stop_id"]).""; --- a/updatedb.php +++ b/updatedb.php @@ -4,7 +4,16 @@ $conn = pg_connect("dbname=transitdata user=postgres password=snmc host=localhost") or die('connection failed'); $pdconn = new PDO("pgsql:dbname=transitdata;user=postgres;password=snmc;host=localhost"); - +/* + delete from agency; + delete from calendar; + delete from calendar_dates; + delete from routes; + delete from shapes; + delete from stop_times; + delete from stops; + delete from trips; +*/ // Unzip cbrfeed.zip, import all csv files to database $unzip = true; $zip = zip_open(dirname(__FILE__) . "/cbrfeed.zip"); @@ -35,10 +44,12 @@ $line = 0; $handle = fopen($tmpdir . $file, "r"); if ($tablename =="stop_times") { - $stmt = $pdconn->prepare("insert into stop_times (trip_id,stop_id,stop_sequence) values(:trip_id, :stop_id, :stop_sequence);"); + $stmt = $pdconn->prepare("insert into stop_times (trip_id,stop_id,stop_sequence,arrival_time,departure_time) values(:trip_id, :stop_id, :stop_sequence,:arrival_time,:departure_time);"); $stmt->bindParam(':trip_id',$trip_id); $stmt->bindParam(':stop_id',$stop_id); $stmt->bindParam(':stop_sequence',$stop_sequence); + $stmt->bindParam(':arrival_time',$time); + $stmt->bindParam(':departure_time',$time); } @@ -57,11 +68,12 @@ } else { $query.= "');"; } - if ($tablename =="stop_times" && $data[1] == "") { + if ($tablename =="stop_times") { // $query = "insert into $tablename (trip_id,stop_id,stop_sequence) values('{$data[0]}','{$data[3]}','{$data[4]}');"; $trip_id=$data[0]; $stop_id=$data[3]; $stop_sequence=$data[4]; + $time=($data[1] == "" ? null : $data[1]); } }