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 --- --- 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,32 +1,33 @@ @@ -36,29 +37,28 @@ - '; - 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 ($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']} + } 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 $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...

@@ -213,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.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/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 @@ - - - - -
- --- 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 ""; -}; -?> - -
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