Fix service alert filtering
Fix service alert filtering

<?php <?php
   
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
   
// Copyright 2009 Google Inc. All Rights Reserved. // Copyright 2009 Google Inc. All Rights Reserved.
$GA_ACCOUNT = "MO-22173039-1"; $GA_ACCOUNT = "MO-22173039-1";
$GA_PIXEL = "/lib/ga.php"; $GA_PIXEL = "/lib/ga.php";
   
function googleAnalyticsGetImageUrl() { function googleAnalyticsGetImageUrl() {
global $GA_ACCOUNT, $GA_PIXEL; global $GA_ACCOUNT, $GA_PIXEL;
//if (stristr($_SERVER['HTTP_USER_AGENT'], 'Googlebot') return ""; //if (stristr($_SERVER['HTTP_USER_AGENT'], 'Googlebot') return "";
$url = ""; $url = "";
$url.= $GA_PIXEL . "?"; $url.= $GA_PIXEL . "?";
$url.= "utmac=" . $GA_ACCOUNT; $url.= "utmac=" . $GA_ACCOUNT;
$url.= "&utmn=" . rand(0, 0x7fffffff); $url.= "&utmn=" . rand(0, 0x7fffffff);
$referer = (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : ""); $referer = (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
$query = $_SERVER["QUERY_STRING"]; $query = $_SERVER["QUERY_STRING"];
$path = $_SERVER["REQUEST_URI"]; $path = $_SERVER["REQUEST_URI"];
if (empty($referer)) { if (empty($referer)) {
$referer = "-"; $referer = "-";
} }
$url.= "&utmr=" . urlencode($referer); $url.= "&utmr=" . urlencode($referer);
if (!empty($path)) { if (!empty($path)) {
$url.= "&utmp=" . urlencode($path); $url.= "&utmp=" . urlencode($path);
} }
$url.= "&guid=ON"; $url.= "&guid=ON";
return str_replace("&", "&amp;", $url); return str_replace("&", "&amp;", $url);
} }
   
function include_header($pageTitle, $pageType, $opendiv = true, $geolocate = false, $datepicker = false) { function include_header($pageTitle, $pageType, $opendiv = true, $geolocate = false, $datepicker = false) {
global $basePath, $GTFSREnabled, $stopid, $routeid; global $basePath, $GTFSREnabled, $stopid, $routeid;
echo ' echo '
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>' . $pageTitle . ' - Canberra Bus Timetable</title> <title>' . $pageTitle . ' - Canberra Bus Timetable</title>
<meta name="google-site-verification" content="-53T5Qn4TB_de1NyfR_ZZkEVdUNcNFSaYKSFkWKx-sY" /> <meta name="google-site-verification" content="-53T5Qn4TB_de1NyfR_ZZkEVdUNcNFSaYKSFkWKx-sY" />
<link rel="dns-prefetch" href="//code.jquery.com"> <link rel="dns-prefetch" href="//code.jquery.com">
<link rel="dns-prefetch" href="//ajax.googleapis.com"> <link rel="dns-prefetch" href="//ajax.googleapis.com">
<link rel="stylesheet" href="' . $basePath . 'css/jquery-ui-1.8.12.custom.css" />'; <link rel="stylesheet" href="' . $basePath . 'css/jquery-ui-1.8.12.custom.css" />';
$jqmVersion = "1.0.1"; $jqmVersion = "1.0.1";
if (isDebugServer()) { if (isDebugServer()) {
$jqmcss = $basePath . "css/jquery.mobile-$jqmVersion.css"; $jqmcss = $basePath . "css/jquery.mobile-$jqmVersion.css";
$jqjs = $basePath . "js/jquery-1.6.4.min.js"; $jqjs = $basePath . "js/jquery-1.6.4.min.js";
$jqmjs = $basePath . "js/jquery.mobile-$jqmVersion.js"; $jqmjs = $basePath . "js/jquery.mobile-$jqmVersion.js";
   
$jqmcss = $basePath . "css/jquery.mobile-b90eab4935.css"; $jqmcss = $basePath . "css/jquery.mobile-b90eab4935.css";
$jqmjs = $basePath . "js/jquery.mobile-b90eab4935.js"; $jqmjs = $basePath . "js/jquery.mobile-b90eab4935.js";
} else { } else {
$jqmcss = "//code.jquery.com/mobile/$jqmVersion/jquery.mobile-$jqmVersion.min.css"; $jqmcss = "//code.jquery.com/mobile/$jqmVersion/jquery.mobile-$jqmVersion.min.css";
$jqjs = "//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"; $jqjs = "//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js";
$jqmjs = "//code.jquery.com/mobile/$jqmVersion/jquery.mobile-$jqmVersion.min.js"; $jqmjs = "//code.jquery.com/mobile/$jqmVersion/jquery.mobile-$jqmVersion.min.js";
} }
echo '<link rel="stylesheet" href="' . $jqmcss . '" /> echo '<link rel="stylesheet" href="' . $jqmcss . '" />
<script src="' . $jqjs . '"></script> <script src="' . $jqjs . '"></script>
<script>$(document).bind("mobileinit", function(){ <script>$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false; $.mobile.ajaxEnabled = false;
}); });
</script> </script>
<script src="' . $jqmjs . '"></script> <script src="' . $jqmjs . '"></script>
   
<script src="' . $basePath . 'js/jquery.ui.core.min.js"></script> <script src="' . $basePath . 'js/jquery.ui.core.min.js"></script>
<script src="' . $basePath . 'js/jquery.ui.position.min.js"></script> <script src="' . $basePath . 'js/jquery.ui.position.min.js"></script>
<script src="' . $basePath . 'js/jquery.ui.widget.min.js"></script> <script src="' . $basePath . 'js/jquery.ui.widget.min.js"></script>
<script src="' . $basePath . 'js/jquery.ui.autocomplete.min.js"></script> <script src="' . $basePath . 'js/jquery.ui.autocomplete.min.js"></script>
<script> <script>
$(function() { $(function() {
$( "#geolocate" ).autocomplete({ $( "#geolocate" ).autocomplete({
source: "lib/autocomplete.php", source: "lib/autocomplete.php",
minLength: 2 minLength: 2
}); });
$( "#from" ).autocomplete({ $( "#from" ).autocomplete({
source: "lib/autocomplete.php", source: "lib/autocomplete.php",
minLength: 2 minLength: 2
}); });
$( "#to" ).autocomplete({ $( "#to" ).autocomplete({
source: "lib/autocomplete.php", source: "lib/autocomplete.php",
minLength: 2 minLength: 2
}); });
}); });
</script>'; </script>';
echo '<style type="text/css">'; echo '<style type="text/css">';
if (strstr($_SERVER['HTTP_USER_AGENT'], 'Android')) if (strstr($_SERVER['HTTP_USER_AGENT'], 'Android'))
echo '.ui-shadow,.ui-btn-up-a,.ui-btn-hover-a,.ui-btn-down-a,.ui-body-b,.ui-btn-up-b,.ui-btn-hover-b, echo '.ui-shadow,.ui-btn-up-a,.ui-btn-hover-a,.ui-btn-down-a,.ui-body-b,.ui-btn-up-b,.ui-btn-hover-b,
.ui-btn-down-b,.ui-bar-c,.ui-body-c,.ui-btn-up-c,.ui-btn-hover-c,.ui-btn-down-c,.ui-bar-c,.ui-body-d, .ui-btn-down-b,.ui-bar-c,.ui-body-c,.ui-btn-up-c,.ui-btn-hover-c,.ui-btn-down-c,.ui-bar-c,.ui-body-d,
.ui-btn-up-d,.ui-btn-hover-d,.ui-btn-down-d,.ui-bar-d,.ui-body-e,.ui-btn-up-e,.ui-btn-hover-e, .ui-btn-up-d,.ui-btn-hover-d,.ui-btn-down-d,.ui-bar-d,.ui-body-e,.ui-btn-up-e,.ui-btn-hover-e,
.ui-btn-down-e,.ui-bar-e,.ui-overlay-shadow,.ui-shadow,.ui-btn-active,.ui-body-a,.ui-bar-a { .ui-btn-down-e,.ui-bar-e,.ui-overlay-shadow,.ui-shadow,.ui-btn-active,.ui-body-a,.ui-bar-a {
text-shadow: none; text-shadow: none;
box-shadow: none; box-shadow: none;
-webkit-box-shadow: none; -webkit-box-shadow: none;
}'; }';
echo '</style>'; echo '</style>';
echo '<link rel="stylesheet" href="' . $basePath . 'css/local.css.php" />'; echo '<link rel="stylesheet" href="' . $basePath . 'css/local.css.php" />';
if (isIOSDevice()) { if (isIOSDevice()) {
echo '<meta name="apple-mobile-web-app-capable" content="yes" /> echo '<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-startup-image" href="startup.png" /> <link rel="apple-touch-startup-image" href="startup.png" />
<link rel="apple-touch-icon" href="apple-touch-icon.png" />'; <link rel="apple-touch-icon" href="apple-touch-icon.png" />';
} }
if ($geolocate) { if ($geolocate) {
echo "<script> echo "<script>
   
function success(position) { function success(position) {
$('#error').val('Location now detected. Please wait for data to load.'); $('#error').val('Location now detected. Please wait for data to load.');
$('#geolocate').val(position.coords.latitude+','+position.coords.longitude); $('#geolocate').val(position.coords.latitude+','+position.coords.longitude);
$.ajax({ async: false, $.ajax({ async: false,
success: function(){ success: function(){
location.reload(true); location.reload(true);
}, },
url: \"include/common.inc.php?geolocate=yes&lat=\"+position.coords.latitude+\"&lon=\"+position.coords.longitude }); url: \"include/common.inc.php?geolocate=yes&lat=\"+position.coords.latitude+\"&lon=\"+position.coords.longitude });
} }
function error(msg) { function error(msg) {
$('#error').val('Error: '+msg); $('#error').val('Error: '+msg);
} }
   
function geolocate() { function geolocate() {
if (navigator.geolocation) { if (navigator.geolocation) {
var options = { var options = {
enableHighAccuracy: true, enableHighAccuracy: true,
timeout: 60000, timeout: 60000,
maximumAge: 10000 maximumAge: 10000
} }
navigator.geolocation.getCurrentPosition(success, error, options); navigator.geolocation.getCurrentPosition(success, error, options);
} }
} }
$(document).ready(function() { $(document).ready(function() {
$('#here').click(function(event) { $('#geolocate').val(geolocate()); return false;}); $('#here').click(function(event) { $('#geolocate').val(geolocate()); return false;});
$('#here').show(); $('#here').show();
}); });
"; ";
if (!isset($_SESSION['lat']) || $_SESSION['lat'] == "") if (!isset($_SESSION['lat']) || $_SESSION['lat'] == "")
echo "geolocate();"; echo "geolocate();";
echo "</script> "; echo "</script> ";
} }
if (isAnalyticsOn()) if (isAnalyticsOn())
echo ' echo '
<script type="text/javascript">' . " <script type="text/javascript">' . "
   
var _gaq = _gaq || []; var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-22173039-1']); _gaq.push(['_setAccount', 'UA-22173039-1']);
_gaq.push(['_trackPageview']); _gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']); _gaq.push(['_trackPageLoadTime']);
</script>"; </script>";
echo '</head> echo '</head>
<body> <body>
<div id="skip"> <div id="skip">
<a href="#maincontent">Skip to content</a> <a href="#maincontent">Skip to content</a>
</div> </div>
'; ';
if ($opendiv) { if ($opendiv) {
echo '<div data-role="page"> echo '<div data-role="page">
<div data-role="header" data-position="inline"> <div data-role="header" data-position="inline">
<a href="' . (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "javascript:history.go(-1)") . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a> <a href="' . (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "javascript:history.go(-1)") . '" data-icon="arrow-l" data-rel="back" class="ui-btn-left">Back</a>
<h1>' . $pageTitle . '</h1> <h1>' . $pageTitle . '</h1>
<a href="' . $basePath . '/index.php" data-icon="home" class="ui-btn-right">Home</a> <a href="' . $basePath . '/index.php" data-icon="home" class="ui-btn-right">Home</a>
</div><!-- /header --> </div><!-- /header -->
<a name="maincontent" id="maincontent"></a> <a name="maincontent" id="maincontent"></a>
<div data-role="content"> '; <div data-role="content"> ';
if ($GTFSREnabled) { if ($GTFSREnabled) {
$overrides = getServiceOverride(); $overrides = getServiceOverride();
if (isset($overrides['service_id'])) { if (isset($overrides['service_id'])) {
if ($overrides['service_id'] == "noservice") { if ($overrides['service_id'] == "noservice") {
echo '<div id="servicewarning">Buses are <strong>not running today</strong> due to industrial action/public holiday. See <a echo '<div id="servicewarning">Buses are <strong>not running today</strong> due to industrial action/public holiday. See <a
href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>'; href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>';
} else { } else {
echo '<div id="servicewarning">Buses are running on an altered timetable today due to industrial action/public holiday. See <a href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>'; echo '<div id="servicewarning">Buses are running on an altered timetable today due to industrial action/public holiday. See <a href="http://www.action.act.gov.au">http://www.action.act.gov.au</a> for details.</div>';
} }
} }
$serviceAlerts = Array(); $serviceAlerts = Array();
$globalAlerts = getServiceAlertsAsArray("agency", "0"); $globalAlerts = getServiceAlertsAsArray("agency", "0");
if ($globalAlerts != nullarray) { if ($globalAlerts != nullarray) {
  // echo "getting alerts due to network wide";
$serviceAlerts = array_merge($serviceAlerts, $globalAlerts); $serviceAlerts = array_merge($serviceAlerts, $globalAlerts);
} }
if (isset($stopid)) { if (isset($stopid)) {
$stopAlerts = getServiceAlertsAsArray("stop", $stopid); $stopAlerts = getServiceAlertsAsArray("stop", $stopid);
if ($stopAlerts != nullarray) { if ($stopAlerts != nullarray) {
  // echo "getting alerts due to stop $stopid";
$serviceAlerts = array_merge($serviceAlerts, $stopAlerts); $serviceAlerts = array_merge($serviceAlerts, $stopAlerts);
} }
} }
if (isset($routeid)) { if (isset($routeid)) {
$routeAlerts = getServiceAlertsAsArray("route", $routeid); $routeAlerts = getServiceAlertsAsArray("route", $routeid);
if ($routeAlerts != nullarray) { if ($routeAlerts != nullarray) {
  // echo "getting alerts due to route $routeid";
$serviceAlerts = array_merge($serviceAlerts, $routeAlerts); $serviceAlerts = array_merge($serviceAlerts, $routeAlerts);
} }
} }
if (isset($serviceAlerts['entity']) && sizeof($serviceAlerts['entity']) > 0) { if (isset($serviceAlerts['entity']) && sizeof($serviceAlerts['entity']) > 0) {
foreach ($serviceAlerts['entity'] as $entity) { foreach ($serviceAlerts['entity'] as $entity) {
echo "<div id='servicewarning'><b>{$entity['alert']['header_text']['translation'][0]['text']}</b>&nbsp;<small>" echo "<div id='servicewarning'><b>{$entity['alert']['header_text']['translation'][0]['text']}</b>&nbsp;<small>"
. date("F jS Y, g:i a", $entity['alert']['active_period'][0]['start']) . " to " . date("F jS Y, g:i a", $entity['alert']['active_period'][0]['start']) . " to "
. date("F jS Y, g:i a", $entity['alert']['active_period'][0]['end']) . "</small> . date("F jS Y, g:i a", $entity['alert']['active_period'][0]['end']) . "</small>
<br>Warning: {$entity['alert']['description_text']['translation'][0]['text']} <br>Warning: {$entity['alert']['description_text']['translation'][0]['text']}
<br><a href='{$entity['alert']['url']['translation'][0]['text']}'>Source</a> </div>"; <br><a href='{$entity['alert']['url']['translation'][0]['text']}'>Source</a> </div>";
} }
} }
} }
} }
} }
   
function include_footer() { function include_footer() {
global $basePath; global $basePath;
echo '<div id="footer"><a href="' . $basePath . 'about.php">About/Contact Us</a>&nbsp;<a href="' . $basePath . 'feedback.php">Feedback/Bug Report</a>&nbsp;<a href="' . $basePath . 'privacy.php">Privacy Policy</a>'; echo '<div id="footer"><a href="' . $basePath . 'about.php">About/Contact Us</a>&nbsp;<a href="' . $basePath . 'feedback.php">Feedback/Bug Report</a>&nbsp;<a href="' . $basePath . 'privacy.php">Privacy Policy</a>';
echo '</div>'; echo '</div>';
if (isAnalyticsOn()) { if (isAnalyticsOn()) {
echo "<script> (function() { echo "<script> (function() {
var ga = document.createElement('script'); ga.type = var ga = document.createElement('script'); ga.type =
'text/javascript'; ga.async = true; 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? ga.src = ('https:' == document.location.protocol ?
'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s); s.parentNode.insertBefore(ga, s);
})();</script>"; })();</script>";
$googleAnalyticsImageUrl = googleAnalyticsGetImageUrl(); $googleAnalyticsImageUrl = googleAnalyticsGetImageUrl();
echo '<noscript><img src="' . $googleAnalyticsImageUrl . '" /></noscript>'; echo '<noscript><img src="' . $googleAnalyticsImageUrl . '" /></noscript>';
} }
echo "\n</div></div></body></html>"; echo "\n</div></div></body></html>";
} }
   
function timeSettings() { function timeSettings() {
global $service_periods; global $service_periods;
echo '<div id="settings" data-role="collapsible" data-collapsed="true"> echo '<div id="settings" data-role="collapsible" data-collapsed="true">
<h3>Change Time (' . (isset($_REQUEST['time']) ? $_REQUEST['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3> <h3>Change Time (' . (isset($_REQUEST['time']) ? $_REQUEST['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3>
<form action="' . basename($_SERVER['PHP_SELF']) . '" method="GET"> <form action="' . basename($_SERVER['PHP_SELF']) . '" method="GET">
<input type="hidden" name="suburb" id="suburb" value="' . (isset($_REQUEST['suburb']) ? $_REQUEST['suburb'] : "") . '"/> <input type="hidden" name="suburb" id="suburb" value="' . (isset($_REQUEST['suburb']) ? $_REQUEST['suburb'] : "") . '"/>
<input type="hidden" name="stopid" id="stopid" value="' . (isset($_REQUEST['stopid']) ? $_REQUEST['stopid'] : "") . '"/> <input type="hidden" name="stopid" id="stopid" value="' . (isset($_REQUEST['stopid']) ? $_REQUEST['stopid'] : "") . '"/>
<input type="hidden" name="stopcode" id="stopcode" value="' . (isset($_REQUEST['stopcode']) ? $_REQUEST['stopcode'] : "") . '"/> <input type="hidden" name="stopcode" id="stopcode" value="' . (isset($_REQUEST['stopcode']) ? $_REQUEST['stopcode'] : "") . '"/>
<div class="ui-body"> <div class="ui-body">
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="time"> Time: </label> <label for="time"> Time: </label>
<input type="time" name="time" id="time" value="' . (isset($_REQUEST['time']) ? $_REQUEST['time'] : date("H:i")) . '"/> <input type="time" name="time" id="time" value="' . (isset($_REQUEST['time']) ? $_REQUEST['time'] : date("H:i")) . '"/>
<a href="#" name="currentTime" id="currentTime" onClick="var d = new Date();' . "$('#time').val(d.getHours() +':'+ (d.getMinutes().toString().length == 1 ? '0'+ d.getMinutes(): d.getMinutes()));" . '">Current Time?</a> <a href="#" name="currentTime" id="currentTime" onClick="var d = new Date();' . "$('#time').val(d.getHours() +':'+ (d.getMinutes().toString().length == 1 ? '0'+ d.getMinutes(): d.getMinutes()));" . '">Current Time?</a>
</div> </div>
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="service_period"> Service Period: </label> <label for="service_period"> Service Period: </label>
<select name="service_period" id="service_period">'; <select name="service_period" id="service_period">';
foreach ($service_periods as $service_period) { foreach ($service_periods as $service_period) {
echo "<option value=\"$service_period\"" . (service_period() === $service_period ? " SELECTED" : "") . '>' . ucwords($service_period) . '</option>'; echo "<option value=\"$service_period\"" . (service_period() === $service_period ? " SELECTED" : "") . '>' . ucwords($service_period) . '</option>';
} }
echo '</select> echo '</select>
<a href="#" style="display:none" name="currentPeriod" id="currentPeriod">Current Period?</a> <a href="#" style="display:none" name="currentPeriod" id="currentPeriod">Current Period?</a>
</div> </div>
<input type="submit" value="Update"/> <input type="submit" value="Update"/>
</div></form> </div></form>
</div>'; </div>';
} }
   
function placeSettings() { function placeSettings() {
   
$geoerror = false; $geoerror = false;
$geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == ""; $geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "";
   
echo '<div id="error">'; echo '<div id="error">';
if ($geoerror) { if ($geoerror) {
echo 'Sorry, but your location could not currently be detected. echo 'Sorry, but your location could not currently be detected.
Please allow location permission, wait for your location to be detected, Please allow location permission, wait for your location to be detected,
or enter an address/co-ordinates in the box below.'; or enter an address/co-ordinates in the box below.';
} }
echo '</div>'; echo '</div>';
echo '<div id="settings" data-role="collapsible" data-collapsed="' . !$geoerror . '"> echo '<div id="settings" data-role="collapsible" data-collapsed="' . !$geoerror . '">
<h3>Change Location...</h3> <h3>Change Location...</h3>
<form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post"> <form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post">
<div class="ui-body"> <div class="ui-body">
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="geolocate"> Current Location: </label> <label for="geolocate"> Current Location: </label>
<input type="text" id="geolocate" name="geolocate" value="' . (isset($_SESSION['lat']) && isset($_SESSION['lon']) ? $_SESSION['lat'] . "," . $_SESSION['lon'] : "Enter co-ordinates or address here") . '"/> <a href="#" style="display:none" name="here" id="here">Here?</a> <input type="text" id="geolocate" name="geolocate" value="' . (isset($_SESSION['lat']) && isset($_SESSION['lon']) ? $_SESSION['lat'] . "," . $_SESSION['lon'] : "Enter co-ordinates or address here") . '"/> <a href="#" style="display:none" name="here" id="here">Here?</a>
</div> </div>
<input type="submit" value="Update"/> <input type="submit" value="Update"/>
</div></form> </div></form>
</div>'; </div>';
} }
   
function trackEvent($category, $action, $label = "", $value = - 1) { function trackEvent($category, $action, $label = "", $value = - 1) {
if (isAnalyticsOn()) { if (isAnalyticsOn()) {
echo "\n<script> _gaq.push(['_trackEvent', '$category', '$action'" . ($label != "" ? ", '$label'" : "") . ($value != - 1 ? ", $value" : "") . "]);</script>"; echo "\n<script> _gaq.push(['_trackEvent', '$category', '$action'" . ($label != "" ? ", '$label'" : "") . ($value != - 1 ? ", $value" : "") . "]);</script>";
} }
} }
   
//stop list collapsing //stop list collapsing
function stopCompare($stopName) { function stopCompare($stopName) {
return substr(trim(preg_replace("/\(Platform.*/", "", $stopName)), 0, 9); return substr(trim(preg_replace("/\(Platform.*/", "", $stopName)), 0, 9);
} }
   
function stopGroupTitle($stopName, $stopdesc) { function stopGroupTitle($stopName, $stopdesc) {
if (preg_match("/Dr |Cct |Cir |Av |St |Cr |Parade |Way |Bank /", $stopName)) { if (preg_match("/Dr |Cct |Cir |Av |St |Cr |Parade |Way |Bank /", $stopName)) {
$descParts = explode("<br>", $stopdesc); $descParts = explode("<br>", $stopdesc);
return trim(str_replace("Street: ", "", $descParts[0])); return trim(str_replace("Street: ", "", $descParts[0]));
} else { } else {
return trim(preg_replace("/\(Platform.*/", "", $stopName)); return trim(preg_replace("/\(Platform.*/", "", $stopName));
} }
} }
   
function viaPointNames($tripid, $stop_sequence = "") { function viaPointNames($tripid, $stop_sequence = "") {
$viaPointNames = Array(); $viaPointNames = Array();
foreach (viaPoints($tripid, $stop_sequence) as $point) { foreach (viaPoints($tripid, $stop_sequence) as $point) {
if (strstr($point['stop_name'], "Station") if (strstr($point['stop_name'], "Station")
|| strstr($point['stop_name'], "Shops") || strstr($point['stop_name'], "Shops")
|| strstr($point['stop_name'], "CIT") || strstr($point['stop_name'], "CIT")
|| strstr($point['stop_name'], "School") || strstr($point['stop_name'], "School")
|| strstr($point['stop_name'], "University") || strstr($point['stop_name'], "University")
) { ) {
$viaPointNames[] = $point['stop_name']; $viaPointNames[] = $point['stop_name'];
} }
} }
if (sizeof($viaPointNames) > 0) { if (sizeof($viaPointNames) > 0) {
return r_implode(", ", $viaPointNames); return r_implode(", ", $viaPointNames);
} else { } else {
return ""; return "";
} }
} }
   
<?php <?php
   
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
$service_periods = Array( $service_periods = Array(
'sunday', 'sunday',
'saturday', 'saturday',
'weekday' 'weekday'
); );
   
function service_period($date = "") { function service_period($date = "") {
   
if (isset($_REQUEST['service_period'])) { if (isset($_REQUEST['service_period'])) {
return $_REQUEST['service_period']; return $_REQUEST['service_period'];
} }
   
$override = getServiceOverride($date); $override = getServiceOverride($date);
if (isset($override['service_id'])) { if (isset($override['service_id'])) {
return strtolower($override['service_id']); return strtolower($override['service_id']);
} }
$date = ($date != "" ? $date : time()); $date = ($date != "" ? $date : time());
$dow = date('w', $date); $dow = date('w', $date);
   
switch ($dow) { switch ($dow) {
case 0: case 0:
return 'sunday'; return 'sunday';
case 6: case 6:
return 'saturday'; return 'saturday';
default: default:
return 'weekday'; return 'weekday';
} }
} }
   
function service_ids($service_period, $date = "") { function service_ids($service_period, $date = "") {
switch ($service_period) { switch ($service_period) {
case 'sunday': case 'sunday':
return Array("Sunday", "Sunday"); return Array("Sunday", "Sunday");
case 'saturday': case 'saturday':
return Array("Saturday", "Saturday"); return Array("Saturday", "Saturday");
default: default:
$date = ($date != "" ? $date : time()); $date = ($date != "" ? $date : time());
// school holidays // school holidays
$ymd = date('Ymd', $date); $ymd = date('Ymd', $date);
$dow = date('w', $date); $dow = date('w', $date);
if (intval($ymd) < "20120203" && $dow != 0 && $dow != 6) { if (intval($ymd) < "20120203" && $dow != 0 && $dow != 6) {
return Array("Weekday-SchoolVacation", "Weekday-SchoolVacation"); return Array("Weekday-SchoolVacation", "Weekday-SchoolVacation");
} else { } else {
return Array("Weekday", "Weekday"); return Array("Weekday", "Weekday");
} }
} }
} }
   
function valid_service_ids() { function valid_service_ids() {
return array_merge(service_ids(""), service_ids('saturday'), service_ids('sunday')); return array_merge(service_ids(""), service_ids('saturday'), service_ids('sunday'));
} }
   
function midnight_seconds($time = "") { function midnight_seconds($time = "") {
// from http://www.perturb.org/display/Perlfunc__Seconds_Since_Midnight.html // from http://www.perturb.org/display/Perlfunc__Seconds_Since_Midnight.html
if ($time != "") { if ($time != "") {
return (date("G", $time) * 3600) + (date("i", $time) * 60) + date("s", $time); return (date("G", $time) * 3600) + (date("i", $time) * 60) + date("s", $time);
} }
if (isset($_SESSION['time'])) { if (isset($_SESSION['time'])) {
$time = strtotime($_SESSION['time']); $time = strtotime($_SESSION['time']);
return (date("G", $time) * 3600) + (date("i", $time) * 60) + date("s", $time); return (date("G", $time) * 3600) + (date("i", $time) * 60) + date("s", $time);
} }
return (date("G") * 3600) + (date("i") * 60) + date("s"); return (date("G") * 3600) + (date("i") * 60) + date("s");
} }
   
function midnight_seconds_to_time($seconds) { function midnight_seconds_to_time($seconds) {
if ($seconds > 0) { if ($seconds > 0) {
$midnight = mktime(0, 0, 0, date("n"), date("j"), date("Y")); $midnight = mktime(0, 0, 0, date("n"), date("j"), date("Y"));
return date("h:ia", $midnight + $seconds); return date("h:ia", $midnight + $seconds);
} else { } else {
return ""; return "";
} }
} }
   
if ($GTFSREnabled) { if ($GTFSREnabled) {
$serviceAlertCause = Array( $serviceAlertCause = Array(
"UNKNOWN_CAUSE" => "Unknown cause", "UNKNOWN_CAUSE" => "Unknown cause",
"OTHER_CAUSE" => "Other cause", "OTHER_CAUSE" => "Other cause",
"TECHNICAL_PROBLEM" => "Technical problem", "TECHNICAL_PROBLEM" => "Technical problem",
"STRIKE" => "Strike", "STRIKE" => "Strike",
"DEMONSTRATION" => "Demonstration", "DEMONSTRATION" => "Demonstration",
"ACCIDENT" => "Accident", "ACCIDENT" => "Accident",
"HOLIDAY" => "Holiday", "HOLIDAY" => "Holiday",
"WEATHER" => "Weather", "WEATHER" => "Weather",
"MAINTENANCE" => "Maintenance", "MAINTENANCE" => "Maintenance",
"CONSTRUCTION" => "Construction", "CONSTRUCTION" => "Construction",
"POLICE_ACTIVITY" => "Police activity", "POLICE_ACTIVITY" => "Police activity",
"MEDICAL_EMERGENCY" => "Medical emergency" "MEDICAL_EMERGENCY" => "Medical emergency"
); );
$serviceAlertEffect = Array( $serviceAlertEffect = Array(
"NO_SERVICE" => "No service", "NO_SERVICE" => "No service",
"REDUCED_SERVICE" => "Reduced service", "REDUCED_SERVICE" => "Reduced service",
"SIGNIFICANT_DELAYS" => "Significant delays", "SIGNIFICANT_DELAYS" => "Significant delays",
"DETOUR" => "Detour", "DETOUR" => "Detour",
"ADDITIONAL_SERVICE" => "Additional service", "ADDITIONAL_SERVICE" => "Additional service",
"MODIFIED_SERVICE" => "Modified service", "MODIFIED_SERVICE" => "Modified service",
"OTHER_EFFECT" => "Other effect", "OTHER_EFFECT" => "Other effect",
"UNKNOWN_EFFECT" => "Unknown effect", "UNKNOWN_EFFECT" => "Unknown effect",
"STOP_MOVED" => "Stop moved"); "STOP_MOVED" => "Stop moved");
   
set_include_path(get_include_path() . PATH_SEPARATOR . ($basePath . "lib/Protobuf-PHP/library/DrSlump/")); set_include_path(get_include_path() . PATH_SEPARATOR . ($basePath . "lib/Protobuf-PHP/library/DrSlump/"));
   
include_once("Protobuf.php"); include_once("Protobuf.php");
include_once("Protobuf/Message.php"); include_once("Protobuf/Message.php");
include_once("Protobuf/Registry.php"); include_once("Protobuf/Registry.php");
include_once("Protobuf/Descriptor.php"); include_once("Protobuf/Descriptor.php");
include_once("Protobuf/Field.php"); include_once("Protobuf/Field.php");
   
include_once($basePath . "lib/Protobuf-PHP/gtfs-realtime.php"); include_once($basePath . "lib/Protobuf-PHP/gtfs-realtime.php");
include_once("Protobuf/CodecInterface.php"); include_once("Protobuf/CodecInterface.php");
include_once("Protobuf/Codec/PhpArray.php"); include_once("Protobuf/Codec/PhpArray.php");
include_once("Protobuf/Codec/Binary.php"); include_once("Protobuf/Codec/Binary.php");
include_once("Protobuf/Codec/Binary/Writer.php"); include_once("Protobuf/Codec/Binary/Writer.php");
include_once("Protobuf/Codec/Json.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 also need last modified epoch of client gtfs
   
- add,remove,patch,inform (null) - add,remove,patch,inform (null)
- stop - stop
- trip - trip
- network - network
- classes (WHERE=) - classes (WHERE=)
- route (short_name or route_id) - route (short_name or route_id)
- street - street
- stop - stop
- trip - trip
Currently support: Currently support:
network inform network inform
trip patch: stop remove trip patch: stop remove
street inform: route inform, trip inform, stop inform street inform: route inform, trip inform, stop inform
route patch: trip remove route patch: trip remove
*/ */
$current_alerts = getCurrentAlerts(); $current_alerts = getCurrentAlerts();
$informed_count = 0; $informed_count = 0;
if (sizeof($current_alerts) > 0) { if (sizeof($current_alerts) > 0) {
   
$fm = new transit_realtime\FeedMessage(); $fm = new transit_realtime\FeedMessage();
$fh = new transit_realtime\FeedHeader(); $fh = new transit_realtime\FeedHeader();
$fh->setGtfsRealtimeVersion(1); $fh->setGtfsRealtimeVersion(1);
$fh->setTimestamp(time()); $fh->setTimestamp(time());
$fm->setHeader($fh); $fm->setHeader($fh);
foreach ($current_alerts as $current_alert) { foreach ($current_alerts as $current_alert) {
  $affectsFilteredEntities = false;
$fe = new transit_realtime\FeedEntity(); $fe = new transit_realtime\FeedEntity();
$fe->setId($current_alert['id']); $fe->setId($current_alert['id']);
$fe->setIsDeleted(false); $fe->setIsDeleted(false);
$alert = new transit_realtime\Alert(); $alert = new transit_realtime\Alert();
$tr = new transit_realtime\TimeRange(); $tr = new transit_realtime\TimeRange();
$tr->setStart($current_alert['start']); $tr->setStart($current_alert['start']);
$tr->setEnd($current_alert['end']); $tr->setEnd($current_alert['end']);
$alert->addActivePeriod($tr); $alert->addActivePeriod($tr);
$informedEntities = getInformedAlerts($current_alert['id'], $filter_class, $filter_id); $informedEntities = getInformedAlerts($current_alert['id'], $filter_class, $filter_id);
if (sizeof($informedEntities) > 0) { if (sizeof($informedEntities) > 0) {
   
  $affectsFilteredEntities = true;
$informed_count++; $informed_count++;
$informed = Array(); $informed = Array();
$es = new transit_realtime\EntitySelector(); $es = new transit_realtime\EntitySelector();
if ($informedEntity['informed_class'] == "agency") { if ($informedEntity['informed_class'] == "agency") {
$es->setAgencyId($informedEntity['informed_id']); $es->setAgencyId($informedEntity['informed_id']);
} }
if ($informedEntity['informed_class'] == "stop") { if ($informedEntity['informed_class'] == "stop") {
$es->setStopId($informedEntity['informed_id']); $es->setStopId($informedEntity['informed_id']);
} }
if ($informedEntity['informed_class'] == "route") { if ($informedEntity['informed_class'] == "route") {
$es->setRouteId($informedEntity['informed_id']); $es->setRouteId($informedEntity['informed_id']);
} }
if ($informedEntity['informed_class'] == "trip") { if ($informedEntity['informed_class'] == "trip") {
$td = new transit_realtime\TripDescriptor(); $td = new transit_realtime\TripDescriptor();
$td->setTripId($informedEntity['informed_id']); $td->setTripId($informedEntity['informed_id']);
$es->setTrip($td); $es->setTrip($td);
} }
$alert->addInformedEntity($es); $alert->addInformedEntity($es);
} }
if ($current_alert['cause'] != "") { if ($current_alert['cause'] != "") {
$alert->setCause(constant("transit_realtime\Alert\Cause::" . $current_alert['cause'])); $alert->setCause(constant("transit_realtime\Alert\Cause::" . $current_alert['cause']));
} }
if ($current_alert['effect'] != "") { if ($current_alert['effect'] != "") {
$alert->setEffect(constant("transit_realtime\Alert\Effect::" . $current_alert['effect'])); $alert->setEffect(constant("transit_realtime\Alert\Effect::" . $current_alert['effect']));
} }
if ($current_alert['url'] != "") { if ($current_alert['url'] != "") {
$tsUrl = new transit_realtime\TranslatedString(); $tsUrl = new transit_realtime\TranslatedString();
$tUrl = new transit_realtime\TranslatedString\Translation(); $tUrl = new transit_realtime\TranslatedString\Translation();
$tUrl->setText($current_alert['url']); $tUrl->setText($current_alert['url']);
$tUrl->setLanguage("en"); $tUrl->setLanguage("en");
$tsUrl->addTranslation($tUrl); $tsUrl->addTranslation($tUrl);
$alert->setUrl($tsUrl); $alert->setUrl($tsUrl);
} }
if ($current_alert['header'] != "") { if ($current_alert['header'] != "") {
$tsHeaderText = new transit_realtime\TranslatedString(); $tsHeaderText = new transit_realtime\TranslatedString();
$tHeaderText = new transit_realtime\TranslatedString\Translation(); $tHeaderText = new transit_realtime\TranslatedString\Translation();
$tHeaderText->setText($current_alert['header']); $tHeaderText->setText($current_alert['header']);
$tHeaderText->setLanguage("en"); $tHeaderText->setLanguage("en");
$tsHeaderText->addTranslation($tHeaderText); $tsHeaderText->addTranslation($tHeaderText);
$alert->setHeaderText($tsHeaderText); $alert->setHeaderText($tsHeaderText);
} }
if ($current_alert['description'] != "") { if ($current_alert['description'] != "") {
$tsDescriptionText = new transit_realtime\TranslatedString(); $tsDescriptionText = new transit_realtime\TranslatedString();
$tDescriptionText = new transit_realtime\TranslatedString\Translation(); $tDescriptionText = new transit_realtime\TranslatedString\Translation();
$tDescriptionText->setText($current_alert['description']); $tDescriptionText->setText($current_alert['description']);
$tDescriptionText->setLanguage("en"); $tDescriptionText->setLanguage("en");
$tsDescriptionText->addTranslation($tDescriptionText); $tsDescriptionText->addTranslation($tDescriptionText);
$alert->setDescriptionText($tsDescriptionText); $alert->setDescriptionText($tsDescriptionText);
} }
$fe->setAlert($alert); $fe->setAlert($alert);
$fm->addEntity($fe); if ($affectsFilteredEntities) {
  $fm->addEntity($fe);
  }
} }
if ($informed_count > 0) { if ($informed_count > 0) {
return $fm; return $fm;
} else { } else {
return null; return null;
} }
} else } else
return null; return null;
} }
   
function getServiceAlertsAsArray($filter_class = "", $filter_id = "") { function getServiceAlertsAsArray($filter_class = "", $filter_id = "") {
   
$alerts = getServiceAlerts($filter_class, $filter_id); $alerts = getServiceAlerts($filter_class, $filter_id);
if ($alerts != null) { if ($alerts != null) {
$codec = new DrSlump\Protobuf\Codec\PhpArray(); $codec = new DrSlump\Protobuf\Codec\PhpArray();
   
return $codec->encode($alerts); return $codec->encode($alerts);
} else { } else {
return nullarray; return nullarray;
} }
} }
   
function getServiceAlertsAsBinary($filter_class = "", $filter_id = "") { function getServiceAlertsAsBinary($filter_class = "", $filter_id = "") {
$codec = new DrSlump\Protobuf\Codec\Binary(); $codec = new DrSlump\Protobuf\Codec\Binary();
return $codec->encode(getServiceAlerts($filter_class, $filter_id)); return $codec->encode(getServiceAlerts($filter_class, $filter_id));
} }
   
function getServiceAlertsAsJSON($filter_class = "", $filter_id = "") { function getServiceAlertsAsJSON($filter_class = "", $filter_id = "") {
$codec = new DrSlump\Protobuf\Codec\Json(); $codec = new DrSlump\Protobuf\Codec\Json();
return $codec->encode(getServiceAlerts($filter_class, $filter_id)); return $codec->encode(getServiceAlerts($filter_class, $filter_id));
} }
   
function getServiceAlertsByClass() { function getServiceAlertsByClass() {
$return = Array(); $return = Array();
$alerts = getServiceAlertsAsArray("", ""); $alerts = getServiceAlertsAsArray("", "");
foreach ($alerts['entities'] as $entity) { foreach ($alerts['entities'] as $entity) {
foreach ($entity['informed'] as $informed) { foreach ($entity['informed'] as $informed) {
foreach ($informed as $key => $value) { foreach ($informed as $key => $value) {
if (strpos("_id", $key) > 0) { if (strpos("_id", $key) > 0) {
$parts = explode($key); $parts = explode($key);
$class = $parts[0]; $class = $parts[0];
$id = $value; $id = $value;
} }
} }
$return[$class][$id][] = $entity; $return[$class][$id][] = $entity;
} }
} }
} }
   
function getTripUpdates($filter_class = "", $filter_id = "") { function getTripUpdates($filter_class = "", $filter_id = "") {
$fm = new transit_realtime\FeedMessage(); $fm = new transit_realtime\FeedMessage();
$fh = new transit_realtime\FeedHeader(); $fh = new transit_realtime\FeedHeader();
$fh->setGtfsRealtimeVersion(1); $fh->setGtfsRealtimeVersion(1);
$fh->setTimestamp(time()); $fh->setTimestamp(time());
$fm->setHeader($fh); $fm->setHeader($fh);
foreach (getCurrentAlerts() as $alert) { foreach (getCurrentAlerts() as $alert) {
$informedEntities = getInformedAlerts($alert['id'], $_REQUEST['filter_class'], $_REQUEST['filter_id']); $informedEntities = getInformedAlerts($alert['id'], $_REQUEST['filter_class'], $_REQUEST['filter_id']);
$stops = Array(); $stops = Array();
$routestrips = Array(); $routestrips = Array();
if (sizeof($informedEntities) > 0) { if (sizeof($informedEntities) > 0) {
if ($informedEntity['informed_class'] == "stop" && $informed["x-action"] == "remove") { if ($informedEntity['informed_class'] == "stop" && $informed["x-action"] == "remove") {
$stops[] = $informedEntity['informed_id']; $stops[] = $informedEntity['informed_id'];
} }
if (($informedEntity['informed_class'] == "route" || $informedEntity['informed_class'] == "trip") && $informed["x-action"] == "patch") { if (($informedEntity['informed_class'] == "route" || $informedEntity['informed_class'] == "trip") && $informed["x-action"] == "patch") {
$routestrips[] = Array("id" => $informedEntity['informed_id'], $routestrips[] = Array("id" => $informedEntity['informed_id'],
"type" => $informedEntity['informed_class']); "type" => $informedEntity['informed_class']);
} }
} }
foreach ($routestrips as $routetrip) { foreach ($routestrips as $routetrip) {
$fe = new transit_realtime\FeedEntity(); $fe = new transit_realtime\FeedEntity();
$fe->setId($alert['id'] . $routetrip['id']); $fe->setId($alert['id'] . $routetrip['id']);
$fe->setIsDeleted(false); $fe->setIsDeleted(false);
$tu = new transit_realtime\TripUpdate(); $tu = new transit_realtime\TripUpdate();
$td = new transit_realtime\TripDescriptor(); $td = new transit_realtime\TripDescriptor();
if ($routetrip['type'] == "route") { if ($routetrip['type'] == "route") {
$td->setRouteId($routetrip['id']); $td->setRouteId($routetrip['id']);
} else if ($routetrip['type'] == "trip") { } else if ($routetrip['type'] == "trip") {
$td->setTripId($routetrip['id']); $td->setTripId($routetrip['id']);
} }
$tu->setTrip($td); $tu->setTrip($td);
foreach ($stops as $stop) { foreach ($stops as $stop) {
$stu = new transit_realtime\TripUpdate\StopTimeUpdate(); $stu = new transit_realtime\TripUpdate\StopTimeUpdate();
$stu->setStopId($stop); $stu->setStopId($stop);
$stu->setScheduleRelationship(transit_realtime\TripUpdate\StopTimeUpdate\ScheduleRelationship::SKIPPED); $stu->setScheduleRelationship(transit_realtime\TripUpdate\StopTimeUpdate\ScheduleRelationship::SKIPPED);
$tu->addStopTimeUpdate($stu); $tu->addStopTimeUpdate($stu);
} }
$fe->setTripUpdate($tu); $fe->setTripUpdate($tu);
$fm->addEntity($fe); $fm->addEntity($fe);
} }
} }
return $fm; return $fm;
} }
   
function getTripUpdatesAsArray($filter_class = "", $filter_id = "") { function getTripUpdatesAsArray($filter_class = "", $filter_id = "") {
$codec = new DrSlump\Protobuf\Codec\PhpArray(); $codec = new DrSlump\Protobuf\Codec\PhpArray();
return $codec->encode(getTripUpdates($filter_class, $filter_id)); return $codec->encode(getTripUpdates($filter_class, $filter_id));
} }
   
function getTripUpdatesAsBinary($filter_class = "", $filter_id = "") { function getTripUpdatesAsBinary($filter_class = "", $filter_id = "") {
$codec = new DrSlump\Protobuf\Codec\Binary(); $codec = new DrSlump\Protobuf\Codec\Binary();
return $codec->encode(getTripUpdates($filter_class, $filter_id)); return $codec->encode(getTripUpdates($filter_class, $filter_id));
} }
   
function getTripUpdatesAsJSON($filter_class = "", $filter_id = "") { function getTripUpdatesAsJSON($filter_class = "", $filter_id = "") {
$codec = new DrSlump\Protobuf\Codec\Json(); $codec = new DrSlump\Protobuf\Codec\Json();
return $codec->encode(getTripUpdates($filter_class, $filter_id)); return $codec->encode(getTripUpdates($filter_class, $filter_id));
} }
   
} }
   
<?php <?php
   
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
   
function getServiceOverride($date = "") { function getServiceOverride($date = "") {
global $conn; global $conn;
$query = "Select * from calendar_dates where date = :date and exception_type = '1' LIMIT 1"; $query = "Select * from calendar_dates where date = :date and exception_type = '1' LIMIT 1";
// debug($query,"database"); // debug($query,"database");
$query = $conn->prepare($query); // Create a prepared statement $query = $conn->prepare($query); // Create a prepared statement
$query->bindParam(":date", date("Ymd", ($date != "" ? $date : time()))); $query->bindParam(":date", date("Ymd", ($date != "" ? $date : time())));
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO :: FETCH_ASSOC); return $query->fetch(PDO :: FETCH_ASSOC);
} }
   
function getServiceAlert($alertID) { function getServiceAlert($alertID) {
global $conn; global $conn;
$query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from \"end\") as \"end\",cause,effect,header,description,url from servicealerts_alerts where id = :servicealert_id"; $query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from \"end\") as \"end\",cause,effect,header,description,url from servicealerts_alerts where id = :servicealert_id";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":servicealert_id", $alertID); $query->bindParam(":servicealert_id", $alertID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO :: FETCH_ASSOC); return $query->fetch(PDO :: FETCH_ASSOC);
} }
   
function updateServiceAlert($alertID, $alert) { function updateServiceAlert($alertID, $alert) {
global $conn; global $conn;
$query = 'update servicealerts_alerts set start=:start, "end"=:end, header=:header, description=:description, url=:url, cause=:cause, effect=:effect where id = :servicealert_id'; $query = 'update servicealerts_alerts set start=:start, "end"=:end, header=:header, description=:description, url=:url, cause=:cause, effect=:effect where id = :servicealert_id';
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindValue(":servicealert_id", $alertID); $query->bindValue(":servicealert_id", $alertID);
$query->bindValue(":start", $alert['startdate']); $query->bindValue(":start", $alert['startdate']);
$query->bindValue(":end", $alert['enddate']); $query->bindValue(":end", $alert['enddate']);
$query->bindValue(":header", $alert['header']); $query->bindValue(":header", $alert['header']);
$query->bindValue(":description", $alert['description']); $query->bindValue(":description", $alert['description']);
$query->bindValue(":url", $alert['url']); $query->bindValue(":url", $alert['url']);
$query->bindValue(":cause", $alert['cause']); $query->bindValue(":cause", $alert['cause']);
$query->bindValue(":effect", $alert['effect']); $query->bindValue(":effect", $alert['effect']);
$query->execute(); $query->execute();
   
print_r($conn->errorInfo()); print_r($conn->errorInfo());
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO :: FETCH_ASSOC); return $query->fetch(PDO :: FETCH_ASSOC);
} }
   
function addServiceAlert($alert) { function addServiceAlert($alert) {
global $conn; global $conn;
$query = 'INSERT INTO servicealerts_alerts (start, "end", header, description, url,cause,effect) VALUES (:start, :end, :header, :description, :url,:cause,:effect) '; $query = 'INSERT INTO servicealerts_alerts (start, "end", header, description, url,cause,effect) VALUES (:start, :end, :header, :description, :url,:cause,:effect) ';
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
//print_r($alert); //print_r($alert);
$query->bindValue(":start", $alert['startdate']); $query->bindValue(":start", $alert['startdate']);
$query->bindValue(":end", $alert['enddate']); $query->bindValue(":end", $alert['enddate']);
$query->bindValue(":header", $alert['header']); $query->bindValue(":header", $alert['header']);
$query->bindValue(":description", $alert['description']); $query->bindValue(":description", $alert['description']);
$query->bindValue(":url", $alert['url']); $query->bindValue(":url", $alert['url']);
$query->bindValue(":cause", $alert['cause']); $query->bindValue(":cause", $alert['cause']);
$query->bindValue(":effect", $alert['effect']); $query->bindValue(":effect", $alert['effect']);
$query->execute(); $query->execute();
   
print_r($conn->errorInfo()); print_r($conn->errorInfo());
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetch(PDO :: FETCH_ASSOC); return $query->fetch(PDO :: FETCH_ASSOC);
} }
   
function getCurrentAlerts() { function getCurrentAlerts() {
global $conn; global $conn;
$query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from \"end\") as \"end\",cause,effect,header,description,url from servicealerts_alerts where NOW() > start and NOW() < \"end\""; $query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from \"end\") as \"end\",cause,effect,header,description,url from servicealerts_alerts where NOW() > start and NOW() < \"end\"";
// debug($query, "database"); // debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
   
function getFutureAlerts() { function getFutureAlerts() {
global $conn; global $conn;
$query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from \"end\") as \"end\",cause,effect,header,description,url from servicealerts_alerts where NOW() > start or NOW() < \"end\""; $query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from \"end\") as \"end\",cause,effect,header,description,url from servicealerts_alerts where NOW() > start or NOW() < \"end\"";
// debug($query, "database"); // debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
   
function getInformedAlerts($id, $filter_class, $filter_id) { function getInformedAlerts($id, $filter_class, $filter_id) {
   
global $conn; global $conn;
  //echo "$id, $filter_class, $filter_id\n";
$query = "SELECT * from servicealerts_informed where servicealert_id = :servicealert_id"; $query = "SELECT * from servicealerts_informed where servicealert_id = :servicealert_id";
   
if ($filter_class != "") { if ($filter_class != "") {
$query .= " AND informed_class = :informed_class "; $query .= " AND informed_class = :informed_class ";
} }
if ($filter_id != "") { if ($filter_id != "") {
$query .= " AND informed_id = :informed_id "; $query .= " AND informed_id = :informed_id ";
} }
// debug($query, "database"); // debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
if ($filter_class != "") { if ($filter_class != "") {
$query->bindParam(":informed_class", $filter_class); $query->bindParam(":informed_class", $filter_class);
} }
if ($filter_id != "") { if ($filter_id != "") {
$query->bindParam(":informed_id", $filter_id); $query->bindParam(":informed_id", $filter_id);
} }
$query->bindParam(":servicealert_id", $id); $query->bindParam(":servicealert_id", $id);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
   
function deleteInformedAlert($serviceAlertID, $class, $id) { function deleteInformedAlert($serviceAlertID, $class, $id) {
global $conn; global $conn;
$query = 'DELETE from servicealerts_informed where servicealert_id = :servicealert_id and informed_class = :informed_class AND informed_id = :informed_id'; $query = 'DELETE from servicealerts_informed where servicealert_id = :servicealert_id and informed_class = :informed_class AND informed_id = :informed_id';
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":servicealert_id", $serviceAlertID); $query->bindParam(":servicealert_id", $serviceAlertID);
$query->bindParam(":informed_class", $class); $query->bindParam(":informed_class", $class);
$query->bindParam(":informed_id", $id); $query->bindParam(":informed_id", $id);
$query->execute(); $query->execute();
print_r($conn->errorInfo()); print_r($conn->errorInfo());
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return null; return null;
} }
   
function addInformedAlert($serviceAlertID, $class, $id, $action) { function addInformedAlert($serviceAlertID, $class, $id, $action) {
global $conn; global $conn;
$query = 'INSERT INTO servicealerts_informed (servicealert_id , informed_class , informed_id, informed_action) $query = 'INSERT INTO servicealerts_informed (servicealert_id , informed_class , informed_id, informed_action)
VALUES(:servicealert_id ,:informed_class, :informed_id, :informed_action)'; VALUES(:servicealert_id ,:informed_class, :informed_id, :informed_action)';
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":servicealert_id", $serviceAlertID); $query->bindParam(":servicealert_id", $serviceAlertID);
$query->bindParam(":informed_class", $class); $query->bindParam(":informed_class", $class);
$query->bindParam(":informed_id", $id); $query->bindParam(":informed_id", $id);
$query->bindParam(":informed_action", $action); $query->bindParam(":informed_action", $action);
$query->execute(); $query->execute();
   
print_r($conn->errorInfo()); print_r($conn->errorInfo());
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return null; return null;
} }
   
  <?php
 
  /*
  * Copyright 2010,2011 Alexander Sadleir
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
  http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  */
  include ('include/common.inc.php');
  function accept_header($header = false) {
  // http://jrgns.net/parse_http_accept_header
  $toret = null;
  $header = $header ? $header : (array_key_exists('HTTP_ACCEPT', $_SERVER) ? $_SERVER['HTTP_ACCEPT']: false);
  if ($header) {
  $types = explode(',', $header);
  $types = array_map('trim', $types);
  foreach ($types as $one_type) {
  $one_type = explode(';', $one_type);
  $type = array_shift($one_type);
  if ($type) {
  list($precedence, $tokens) = self::accept_header_options($one_type);
  list($main_type, $sub_type) = array_map('trim', explode('/', $type));
  $toret[] = array('main_type' => $main_type, 'sub_type' => $sub_type, 'precedence' => (float)$precedence, 'tokens' => $tokens);
  }
  }
  usort($toret, array('Parser', 'compare_media_ranges'));
  }
  return $toret;
  }
  $json_types = Array("application/json","application/x-javascript","text/javascript","text/x-javascript","text/x-json");
  if ($_REQUEST['json']) {
  $return = getServiceAlertsAsJSON($_REQUEST['filter_class'], $_REQUEST['filter_id']);
  header('Content-Type: application/json; 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 = '(' . $return . ');'; //must wrap in parens and end with semicolon
  //print_r($_GET['callback'] . $json); //callback is prepended for json-p
  }
  else
  echo $return;
  }
  ?>
  <?php
 
  /*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */
  ?>
 
file:a/servicealerts_api.php (deleted)
<?php  
 
/*  
* Copyright 2010,2011 Alexander Sadleir  
 
Licensed under the Apache License, Version 2.0 (the "License");  
you may not use this file except in compliance with the License.  
You may obtain a copy of the License at  
 
http://www.apache.org/licenses/LICENSE-2.0  
 
Unless required by applicable law or agreed to in writing, software  
distributed under the License is distributed on an "AS IS" BASIS,  
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
See the License for the specific language governing permissions and  
limitations under the License.  
*/  
include ('include/common.inc.php');  
 
if (basename(__FILE__) == "servicealerts_api.php") {  
$return = getServiceAlertsAsJSON($_REQUEST['filter_class'], $_REQUEST['filter_id']);  
header('Content-Type: text/javascript; charset=utf8');  
// header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/');  
header('Access-Control-Max-Age: 3628800');  
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');  
if (isset($_GET['callback'])) {  
$json = '(' . $return . ');'; //must wrap in parens and end with semicolon  
//print_r($_GET['callback'] . $json); //callback is prepended for json-p  
}  
else  
echo $return;  
}  
?>