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: https://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 --- --- 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/include/common-auth.inc.php +++ b/include/common-auth.inc.php @@ -1,91 +1,83 @@ begin($oid_identifier); - + $auth = $consumer->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); - } - + foreach ($attribute as $attr) { + $ax->add($attr); + } + // Add AX fetch request to authentication request - $auth -> addExtension($ax); + $auth->addExtension($ax); $_SESSION['returnURL'] = curPageURL(); // Redirect to OpenID provider for authentication - $url = $auth -> redirectURL(getTrustRoot(), $_SESSION['returnURL']); + $url = $auth->redirectURL(getTrustRoot(), $_SESSION['returnURL']); header('Location: ' . $url); - } +} +function auth() { + if ($_SESSION['authed'] == true) + return true; -function auth() + // 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 ($_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) { + 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") { + $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 { + $_SESSION['authed'] = true; + } + } else { login(); - } - } - if ($_REQUEST['janrain_nonce']) auth(); + } +} + +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.
'; - } - } - if ($serviceAlertsEnabled) { - $serviceAlerts = getServiceAlerts("network","network"); - foreach ($serviceAlerts['entities'] as $entity) { - echo "
".date("F j, g:i a",strtotime($entity['alert']['active_period']['start']))." to ". date("F j, g:i a", strtotime($entity['alert']['active_period']['end']))."
Warning: {$entity['alert']['description']['translation']} -
Source
"; - } - } - } -} -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...

@@ -210,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,7 +45,48 @@ return ""; } } -function getServiceAlerts($filter_class, $filter_id) { +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 @@ -65,35 +106,82 @@ street inform: route inform, trip inform, stop inform route patch: trip remove */ -$return = Array(); -$return['header']['gtrtfs_version'] = "1"; -$return['header']['timestamp'] = time(); -$return['entities'] = Array(); + $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']); +$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) { - $entity = Array(); - $entity['id'] = $alert['id']; - $entity['alert']['active_period']['start'] = $alert['start']; - $entity['alert']['active_period']['end'] = $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; - } -} -return $return; + $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 = getServiceAlerts("",""); + $alerts = getServiceAlertsAsArray("",""); foreach ($alerts['entities'] as $entity) { foreach ($entity['informed'] as $informed) { foreach($informed as $key => $value){ @@ -103,10 +191,70 @@ $id = $value; } } - $return[$class][$id][]['entity'] = $entity; - $return[$class][$id][]['action'] = $informed["x-action"]; - } - } + $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,39 +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/servicealert-dao.inc.php +++ b/include/db/servicealert-dao.inc.php @@ -17,7 +17,7 @@ function getServiceAlert($alertID) { global $conn; - $query = 'SELECT * from servicealerts_alerts where id = :servicealert_id'; + $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); @@ -30,15 +30,16 @@ } -function updateServiceAlert($alertID, $start, $end, $description, $url) +function updateServiceAlert($alertID, $start, $end, $header, $description, $url) { global $conn; - $query = 'update servicealerts_alerts set start=:start, "end"=:end, description=:description, url=:url where id = :servicealert_id'; + $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(); @@ -51,14 +52,15 @@ return $query -> fetch(PDO :: FETCH_ASSOC); } - function addServiceAlert($start, $end, $description, $url) + function addServiceAlert($start, $end, $header, $description, $url) { global $conn; - $query = 'INSERT INTO servicealerts_alerts (start, "end", description, url) VALUES (:start, :end, :description, :url) '; + $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(); @@ -74,7 +76,7 @@ function getCurrentAlerts() { global $conn; - $query = 'SELECT * from servicealerts_alerts where NOW() > start and NOW() < "end"'; + $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(); @@ -88,7 +90,7 @@ function getFutureAlerts() { global $conn; - $query = 'SELECT * from servicealerts_alerts where NOW() > start or NOW() < "end"'; + $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(); --- 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 @@ -2,40 +2,15 @@ include ('../include/common.inc.php'); include_header("Busness R&D", "index"); - if ($_SESSION['authed'] == true) { - echo ''; - } ?> - - + --- a/labs/myway_api.json.php +++ /dev/null @@ -1,142 +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"; -} -if (basename(__FILE__) == "myway_api.json.php") { -header('Content-Type: text/javascript; charset=utf8'); -// header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/'); -header('Access-Control-Max-Age: 3628800'); -header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); -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 @@ - - - - -
-