From: Maxious Date: Fri, 16 Sep 2011 03:53:46 +0000 Subject: Purge openid-php X-Git-Url: https://maxious.lambdacomplex.org/git/?p=busui.git&a=commitdiff&h=0dc105deddf45bf359e88445ba8371b31ec212e4 --- Purge openid-php --- --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ /labs/tiles/16 /labs/tiles/17 /labs/tiles/19 +/nbproject/private/ --- a/about.php +++ b/about.php @@ -21,10 +21,6 @@ , 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/busuiphp.sh +++ b/aws/busuiphp.sh @@ -9,6 +9,7 @@ chcon -R -t httpd_sys_content_rw_t /var/www/labs/tiles chmod -R 777 /var/www/labs/tiles +mkdir /var/www/lib/openid-php/oid_store 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 --- a/include/common-auth.inc.php +++ b/include/common-auth.inc.php @@ -1,83 +1,33 @@ mode) { + $openid->required = array('contact/email'); + $openid->identity = 'https://www.google.com/accounts/o8/id'; + header('Location: ' . $openid->authUrl()); + } + } -function getScheme() { - $scheme = 'http'; - if (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') { - $scheme .= 's'; - } - return $scheme; -} -function getTrustRoot() { - return sprintf("%s://%s:%s%s/", getScheme(), $_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT'], dirname($_SERVER['PHP_SELF'])); -} +function auth() -// Includes required files -set_include_path(get_include_path() . PATH_SEPARATOR . $basePath . "lib/openid-php/"); -require_once "Auth/OpenID/Consumer.php"; -require_once "Auth/OpenID/FileStore.php"; -require_once "Auth/OpenID/AX.php"; - -function login() { - // Just tested this with/for Google, needs trying with others ... - $oid_identifier = 'https://www.google.com/accounts/o8/id'; - // 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 - $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); - } - - // 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") { +{ + if ($_SESSION['authed'] == true) return true; + global $openid; + + if($openid->mode) { + $attr = $openid->getAttributes(); + if ($attr["contact/email"] != "maxious@gmail.com") { die("Access Denied"); + } else { + $_SESSION['authed'] = true; + } } else { - $_SESSION['authed'] = true; - } - } else { login(); - } -} - -if ($_REQUEST['janrain_nonce']) - auth(); + } + } ?> --- a/include/common-geo.inc.php +++ b/include/common-geo.inc.php @@ -1,166 +1,153 @@ $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 $labsPath; + $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 . ' - Canberra Bus Timetable +' . $pageTitle . ' - '; - 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 ' - + '; + 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 ' + - - - - - - + + + + + + '; - 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 ($GTFSREnabled) { - $serviceAlerts = getServiceAlertsAsArray("agency", "0"); - foreach ($serviceAlerts['entity'] as $entity) { - echo "
" . date("F j, g:i a", strtotime($entity['alert']['active_period'][0]['start'])) . " to " . date("F j, g:i a", strtotime($entity['alert']['active_period'][0]['end'])) . "{$entity['alert']['header_text']['translation'][0]['text']}
Warning: {$entity['alert']['description_text']['translation'][0]['text']} -
Source
"; - } - } - } -} - -function include_footer() { - global $basePath; - 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...

@@ -215,12 +210,11 @@
'; } - -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,7 @@ return ""; } } -if ($GTFSREnabled) { + $serviceAlertCause = Array( "UNKNOWN_CAUSE" => "Unknown cause", "OTHER_CAUSE" => "Other cause", @@ -71,22 +71,7 @@ "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 = "") { +function getServiceAlerts($filter_class, $filter_id) { /* also need last modified epoch of client gtfs @@ -106,82 +91,40 @@ 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); +$return = Array(); +$return['header']['gtfs_realtime_version'] = "1"; +$return['header']['timestamp'] = time(); +$return['header']['incrementality'] = "FULL_DATASET"; +$return['entities'] = Array(); 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']); + $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']); + $entity = Array(); + $entity['id'] = $alert['id']; + $entity['alert']['active_period']['start'] = $alert['start']; + $entity['alert']['active_period']['end'] = $alert['end']; + $entity['alert']['url']['translation']['text'] = $alert['url']; + $entity['alert']['url']['translation']['language'] = 'en'; + $entity['alert']['header_text']['translation']['text'] = $alert['header']; + $entity['alert']['header_text']['translation']['language'] = 'en'; + $entity['alert']['description_text']['translation']['text'] = $alert['description']; + $entity['alert']['description_text']['translation']['language'] = 'en'; + + 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; } - 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); + $return['entities'][] = $entity; } - $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)); +return $return; } function getServiceAlertsByClass() { $return = Array(); - $alerts = getServiceAlertsAsArray("",""); + $alerts = getServiceAlerts("",""); foreach ($alerts['entities'] as $entity) { foreach ($entity['informed'] as $informed) { foreach($informed as $key => $value){ @@ -191,70 +134,10 @@ $id = $value; } } - $return[$class][$id][] = $entity; + $return[$class][$id][]['entity'] = $entity; + $return[$class][$id][]['action'] = $informed["x-action"]; } } } - -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,43 +1,39 @@ \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 debug($msg, $debugReason = "other") { - if (isDebug($debugReason)) - echo "\n\n"; +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 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 bracketsMeanNewLine($input) +{ + return str_replace(")", "
", str_replace("(", "
", $input)); } - -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 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 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 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 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 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 id,extract('epoch', start) as start, extract('epoch', end) as end,cause,effect,header,description,url from servicealerts_alerts where id = :servicealert_id"; + $query = 'SELECT * from servicealerts_alerts where id = :servicealert_id'; debug($query, "database"); $query = $conn -> prepare($query); $query -> bindParam(":servicealert_id", $alertID); @@ -30,16 +30,15 @@ } -function updateServiceAlert($alertID, $start, $end, $header, $description, $url) +function updateServiceAlert($alertID, $start, $end, $description, $url) { global $conn; - $query = 'update servicealerts_alerts set start=:start, "end"=:end, header=:header, description=:description, url=:url where id = :servicealert_id'; + $query = 'update servicealerts_alerts set start=:start, "end"=:end, 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(); @@ -52,15 +51,14 @@ return $query -> fetch(PDO :: FETCH_ASSOC); } - function addServiceAlert($start, $end, $header, $description, $url) + function addServiceAlert($start, $end, $description, $url) { global $conn; - $query = 'INSERT INTO servicealerts_alerts (start, "end", header, description, url) VALUES (:start, :end, :header, :description, :url) '; + $query = 'INSERT INTO servicealerts_alerts (start, "end", description, url) VALUES (:start, :end, :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(); @@ -76,7 +74,7 @@ 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\""; + $query = 'SELECT * from servicealerts_alerts where NOW() > start and NOW() < "end"'; // debug($query, "database"); $query = $conn -> prepare($query); $query -> execute(); @@ -90,7 +88,7 @@ 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\""; + $query = 'SELECT * 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,7 +25,6 @@ Busness R&D'; -echo ' MyWay Balance and Timeliness Survey Results'; include_footer(true) ?> --- a/labs/index.php +++ b/labs/index.php @@ -2,15 +2,40 @@ include ('../include/common.inc.php'); include_header("Busness R&D", "index"); + if ($_SESSION['authed'] == true) { + echo ''; + } ?> - + + --- /dev/null +++ b/labs/myway_api.json.php @@ -1,1 +1,142 @@ + "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); +} +?> + --- /dev/null +++ b/labs/myway_timeliness.php @@ -1,1 +1,118 @@ + + + + +
+