Fix php syntax issues
Fix php syntax issues

<?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.
*/ */
// you have to open the session to be able to modify or remove it // you have to open the session to be able to modify or remove it
session_start(); session_start();
if (isset($_REQUEST['geolocate']) && $_REQUEST['geolocate'] != "Enter co-ordinates or address here") { if (isset($_REQUEST['geolocate']) && $_REQUEST['geolocate'] != "Enter co-ordinates or address here") {
$geocoded = false; $geocoded = false;
if (isset($_REQUEST['lat']) && isset($_REQUEST['lon'])) { if (isset($_REQUEST['lat']) && isset($_REQUEST['lon'])) {
$_SESSION['lat'] = trim(filter_var($_REQUEST['lat'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)); $_SESSION['lat'] = trim(filter_var($_REQUEST['lat'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$_SESSION['lon'] = trim(filter_var($_REQUEST['lon'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)); $_SESSION['lon'] = trim(filter_var($_REQUEST['lon'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
} else { } else {
if (startsWith($geolocate, "-")) { if (startsWith($geolocate, "-")) {
$locateparts = explode(",", $geolocate); $locateparts = explode(",", $geolocate);
$_SESSION['lat'] = $locateparts[0]; $_SESSION['lat'] = $locateparts[0];
$_SESSION['lon'] = $locateparts[1]; $_SESSION['lon'] = $locateparts[1];
} else if (strpos($geolocate, "(") !== false) { } else if (strpos($geolocate, "(") !== false) {
$geoParts = explode("(", $geolocate); $geoParts = explode("(", $geolocate);
$locateparts = explode(",", str_replace(")", "", $geoParts[1])); $locateparts = explode(",", str_replace(")", "", $geoParts[1]));
$_SESSION['lat'] = $locateparts[0]; $_SESSION['lat'] = $locateparts[0];
$_SESSION['lon'] = $locateparts[1]; $_SESSION['lon'] = $locateparts[1];
} else { } else {
$contents = geocode($geolocate, true); $contents = geocode($geolocate, true);
print_r($contents); print_r($contents);
if (isset($contents[0]->centroid)) { if (isset($contents[0]->centroid)) {
$geocoded = true; $geocoded = true;
$_SESSION['lat'] = $contents[0]->centroid->coordinates[0]; $_SESSION['lat'] = $contents[0]->centroid->coordinates[0];
$_SESSION['lon'] = $contents[0]->centroid->coordinates[1]; $_SESSION['lon'] = $contents[0]->centroid->coordinates[1];
} else { } else {
$_SESSION['lat'] = ""; $_SESSION['lat'] = "";
$_SESSION['lon'] = ""; $_SESSION['lon'] = "";
} }
} }
} }
sessionUpdated(); sessionUpdated();
} }
   
function sessionUpdated() { function sessionUpdated() {
$_SESSION['lastUpdated'] = time(); $_SESSION['lastUpdated'] = time();
} }
   
// timeoutSession // timeoutSession
$TIMEOUT_LIMIT = 60 * 5; // 5 minutes $TIMEOUT_LIMIT = 60 * 5; // 5 minutes
if (isset($_SESSION['lastUpdated']) && $_SESSION['lastUpdated'] + $TIMEOUT_LIMIT < time()) { if (isset($_SESSION['lastUpdated']) && $_SESSION['lastUpdated'] + $TIMEOUT_LIMIT < time()) {
debug("Session timeout " . ($_SESSION['lastUpdated'] + $TIMEOUT_LIMIT) . ">" . time(), "session"); debug("Session timeout " . ($_SESSION['lastUpdated'] + $TIMEOUT_LIMIT) . ">" . time(), "session");
session_destroy(); session_destroy();
session_start(); session_start();
} }
   
//debug(print_r($_SESSION, true) , "session"); //debug(print_r($_SESSION, true) , "session");
function current_time($time = "") { function current_time($time = "") {
if ($_REQUEST['time']) return $_REQUEST['time']; if (isset($_REQUEST['time'])) return $_REQUEST['time'];
else if ($time != "") date("H:i:s",$time); else if ($time != "") date("H:i:s",$time);
else return date("H:i:s"); else return date("H:i:s");
} }
   
?> ?>
   
<?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 getTrip($tripID) { function getTrip($tripID) {
global $conn; global $conn;
$query = "Select * from trips $query = "Select * from trips
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
where trip_id = :tripID where trip_id = :tripID
LIMIT 1"; LIMIT 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$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 getTripStops($tripID) { function getTripStops($tripID) {
global $conn; global $conn;
$query = "SELECT stop_id, stop_name, ST_AsKML(position) as positionkml, $query = "SELECT stop_id, stop_name, ST_AsKML(position) as positionkml,
stop_sequence, trips.trip_id stop_sequence, trips.trip_id
FROM stop_times FROM stop_times
join trips on trips.trip_id = stop_times.trip_id join trips on trips.trip_id = stop_times.trip_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE trips.trip_id = :tripID ORDER BY stop_sequence"; WHERE trips.trip_id = :tripID ORDER BY stop_sequence";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchColumn(0); return $query->fetchColumn(0);
} }
function getTripShape($tripID) { function getTripShape($tripID) {
// todo, use shapes table if shape_id specified // todo, use shapes table if shape_id specified
global $conn; global $conn;
$query = "SELECT ST_AsKML(ST_MakeLine(geometry(a.shape_pt))) as the_route $query = "SELECT ST_AsKML(ST_MakeLine(geometry(a.shape_pt))) as the_route
FROM (SELECT shapes.shape_id,shape_pt from shapes FROM (SELECT shapes.shape_id,shape_pt from shapes
inner join trips on shapes.shape_id = trips.shape_id inner join trips on shapes.shape_id = trips.shape_id
WHERE trips.trip_id = :tripID ORDER BY shape_pt_sequence) as a group by a.shape_id"; WHERE trips.trip_id = :tripID ORDER BY shape_pt_sequence) as a group by a.shape_id";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchColumn(0); return $query->fetchColumn(0);
} }
   
function getTripStopTimes($tripID) { function getTripStopTimes($tripID) {
global $conn; global $conn;
$query = "SELECT stop_times.trip_id,trip_headsign,arrival_time,stop_times.stop_id $query = "SELECT stop_times.trip_id,trip_headsign,arrival_time,stop_times.stop_id
,stop_lat,stop_lon,stop_name,stop_desc,stop_code, ,stop_lat,stop_lon,stop_name,stop_desc,stop_code,
stop_sequence,service_id,trips.route_id,route_short_name,route_long_name stop_sequence,service_id,trips.route_id,route_short_name,route_long_name
FROM stop_times FROM stop_times
join trips on trips.trip_id = stop_times.trip_id join trips on trips.trip_id = stop_times.trip_id
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE trips.trip_id = :tripID $range ORDER BY stop_sequence"; WHERE trips.trip_id = :tripID ORDER BY stop_sequence";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$stopTimes = $query->fetchAll(); $stopTimes = $query->fetchAll();
return $stopTimes; return $stopTimes;
} }
   
function getTripAtStop($tripID, $stop_sequence) { function getTripAtStop($tripID, $stop_sequence) {
global $conn; global $conn;
foreach (getTripStopTimes($tripID) as $tripStop) { foreach (getTripStopTimes($tripID) as $tripStop) {
if ($tripStop['stop_sequence'] == $stop_sequence) if ($tripStop['stop_sequence'] == $stop_sequence)
return $tripStop; return $tripStop;
} }
return Array(); return Array();
} }
   
function getTripStartTime($tripID) { function getTripStartTime($tripID) {
global $conn; global $conn;
$query = "Select * from stop_times $query = "Select * from stop_times
where trip_id = :tripID where trip_id = :tripID
AND arrival_time IS NOT NULL AND arrival_time IS NOT NULL
AND stop_sequence = '1'"; AND stop_sequence = '1'";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$r = $query->fetch(PDO :: FETCH_ASSOC); $r = $query->fetch(PDO :: FETCH_ASSOC);
return $r['arrival_time']; return $r['arrival_time'];
} }
   
function getTripEndTime($tripID) { function getTripEndTime($tripID) {
global $conn; global $conn;
$query = "SELECT trip_id,max(arrival_time) as arrival_time from stop_times $query = "SELECT trip_id,max(arrival_time) as arrival_time from stop_times
WHERE stop_times.arrival_time IS NOT NULL and trip_id = :tripID group by trip_id"; WHERE stop_times.arrival_time IS NOT NULL and trip_id = :tripID group by trip_id";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$r = $query->fetch(PDO :: FETCH_ASSOC); $r = $query->fetch(PDO :: FETCH_ASSOC);
return $r['arrival_time']; return $r['arrival_time'];
} }
function getTripStartingPoint($tripID) { function getTripStartingPoint($tripID) {
global $conn; global $conn;
$query = "SELECT stops.stop_id, stops.stop_name, stops.stop_desc $query = "SELECT stops.stop_id, stops.stop_name, stops.stop_desc
from stop_times inner join stops on stop_times.stop_id = stops.stop_id from stop_times inner join stops on stop_times.stop_id = stops.stop_id
WHERE trip_id = :tripID and stop_sequence = '1' limit 1"; WHERE trip_id = :tripID and stop_sequence = '1' limit 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$r = $query->fetch(PDO :: FETCH_ASSOC); $r = $query->fetch(PDO :: FETCH_ASSOC);
return $r; return $r;
} }
   
function getTripDestination($tripID) { function getTripDestination($tripID) {
global $conn; global $conn;
$query = "SELECT stops.stop_id, stops.stop_name, stops.stop_desc $query = "SELECT stops.stop_id, stops.stop_name, stops.stop_desc
from stop_times inner join stops on stop_times.stop_id = stops.stop_id from stop_times inner join stops on stop_times.stop_id = stops.stop_id
WHERE trip_id = :tripID order by stop_sequence desc limit 1"; WHERE trip_id = :tripID order by stop_sequence desc limit 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$r = $query->fetch(PDO :: FETCH_ASSOC); $r = $query->fetch(PDO :: FETCH_ASSOC);
return $r; return $r;
} }
   
function getActiveTrips($time) { function getActiveTrips($time) {
global $conn; global $conn;
if ($time == "") if ($time == "")
$time = current_time(); $time = current_time();
$query = "Select distinct stop_times.trip_id, start_times.arrival_time as start_time, end_times.arrival_time as end_time from stop_times, (SELECT trip_id,arrival_time from stop_times WHERE stop_times.arrival_time IS NOT NULL $query = "Select distinct stop_times.trip_id, start_times.arrival_time as start_time, end_times.arrival_time as end_time from stop_times, (SELECT trip_id,arrival_time from stop_times WHERE stop_times.arrival_time IS NOT NULL
AND stop_sequence = '1') as start_times, (SELECT trip_id,max(arrival_time) as arrival_time from stop_times WHERE stop_times.arrival_time IS NOT NULL group by trip_id) as end_times AND stop_sequence = '1') as start_times, (SELECT trip_id,max(arrival_time) as arrival_time from stop_times WHERE stop_times.arrival_time IS NOT NULL group by trip_id) as end_times
WHERE start_times.trip_id = end_times.trip_id AND stop_times.trip_id = end_times.trip_id AND :time > start_times.arrival_time AND :time < end_times.arrival_time"; WHERE start_times.trip_id = end_times.trip_id AND stop_times.trip_id = end_times.trip_id AND :time > start_times.arrival_time AND :time < end_times.arrival_time";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":time", $time); $query->bindParam(":time", $time);
$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 viaPoints($tripID, $stop_sequence = "") { function viaPoints($tripID, $stop_sequence = "") {
global $conn; global $conn;
$query = "SELECT stops.stop_id, stop_name, arrival_time $query = "SELECT stops.stop_id, stop_name, arrival_time
FROM stop_times join stops on stops.stop_id = stop_times.stop_id FROM stop_times join stops on stops.stop_id = stop_times.stop_id
WHERE stop_times.trip_id = :tripID WHERE stop_times.trip_id = :tripID
" . ($stop_sequence != "" ? " AND stop_sequence > :stop_sequence " : "") . " ORDER BY stop_sequence"; " . ($stop_sequence != "" ? " AND stop_sequence > :stop_sequence " : "") . " ORDER BY stop_sequence";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
if ($stop_sequence != "") if ($stop_sequence != "")
$query->bindParam(":stop_sequence", $stop_sequence); $query->bindParam(":stop_sequence", $stop_sequence);
$query->bindParam(":tripID", $tripID); $query->bindParam(":tripID", $tripID);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
   
   
?> ?>
<?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.
*/ */
include ('../include/common.inc.php'); include ('../include/common.inc.php');
include_header("MyWay Delta Calculate", "mywayDeltaCalc"); include_header("MyWay Delta Calculate", "mywayDeltaCalc");
flush(); flush();
ob_flush(); ob_flush();
   
function abssort($a, $b) { function abssort($a, $b) {
if ($a['timeDiff'] == $b['timeDiff']) { if ($a['timeDiff'] == $b['timeDiff']) {
return 0; return 0;
} }
return (abs($a['timeDiff']) < abs($b['timeDiff'])) ? -1 : 1; return (abs($a['timeDiff']) < abs($b['timeDiff'])) ? -1 : 1;
} }
   
//collect all observation not in delta //collect all observation not in delta
$query = "select * from myway_observations INNER JOIN myway_stops $query = "select * from myway_observations INNER JOIN myway_stops
ON myway_observations.myway_stop=myway_stops.myway_stop INNER JOIN myway_routes ON myway_observations.myway_stop=myway_stops.myway_stop INNER JOIN myway_routes
ON myway_observations.myway_route=myway_routes.myway_route ON myway_observations.myway_route=myway_routes.myway_route
WHERE observation_id NOT IN WHERE observation_id NOT IN
( (
SELECT observation_id SELECT observation_id
FROM myway_timingdeltas FROM myway_timingdeltas
)"; )";
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();
} }
$uncalcdObservations = $query->fetchAll(); $uncalcdObservations = $query->fetchAll();
//Display count //Display count
echo "<h3>" . sizeof($uncalcdObservations) . " observations not yet processed</h2>"; echo "<h3>" . sizeof($uncalcdObservations) . " observations not yet processed</h2>";
//foreach observation not in delta //foreach observation not in delta
foreach ($uncalcdObservations as $obsv) { foreach ($uncalcdObservations as $obsv) {
//var_dump($obsv); //var_dump($obsv);
echo "<h3>Observation {$obsv['observation_id']}:</h1> echo "<h3>Observation {$obsv['observation_id']}:</h1>
<small>{$obsv['myway_stop']} @ {$obsv['time']} on {$obsv['myway_route']}</small><br>"; <small>{$obsv['myway_stop']} @ {$obsv['time']} on {$obsv['myway_route']}</small><br>";
// convert timestamp into time of day and date // convert timestamp into time of day and date
// timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html // timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html
$time = date("H:i:s", strtotime($obsv['time'])); $time = date("H:i:s", strtotime($obsv['time']));
$time_tz = date("H:i:s", strtotime($obsv['time'])) . " AESST"; $time_tz = date("H:i:s", strtotime($obsv['time'])) . " AESST";
$search_time = date("H:i:s", strtotime($obsv['time']) - (60 * 60)); // 30 minutes margin $search_time = date("H:i:s", strtotime($obsv['time']) - (60 * 60)); // 30 minutes margin
$date = date("c", strtotime($obsv['time'])); $date = date("c", strtotime($obsv['time']));
$timing_period = service_period(strtotime($date)); $timing_period = service_period(strtotime($date));
// little hack for public holidays nolonger active; weekdays and 900+ route numbers don't make sense // little hack for public holidays nolonger active; weekdays and 900+ route numbers don't make sense
if ($timing_period == "weekday" && preg_match('/9../',$obsv["route_short_name"])) { if ($timing_period == "weekday" && preg_match('/9../',$obsv["route_short_name"])) {
echo "Potential public holiday detected, trying Sunday timetable.<br>"; echo "Potential public holiday detected, trying Sunday timetable.<br>";
$timing_period = "sunday"; $timing_period = "sunday";
} }
if (isset($obsv["stop_id"]) && $obsv["stop_id"] != "" && $obsv["stop_id"] != "*") { if (isset($obsv["stop_id"]) && $obsv["stop_id"] != "" && $obsv["stop_id"] != "*") {
$potentialStops = Array(getStop($obsv["stop_id"])); $potentialStops = Array(getStop($obsv["stop_id"]));
} else { } else {
echo "No stop_id recorded for this stop_name, potential stops are a bus station<br>"; echo "No stop_id recorded for this stop_name, potential stops are a bus station<br>";
$potentialStops = getStops("", trim(str_replace(Array("Arrival","Arrivals","Arrive Platform 3 Set down only.","Arrive","Set Down Only"), "", $obsv["myway_stop"]))); $potentialStops = getStops("", trim(str_replace(Array("Arrival","Arrivals","Arrive Platform 3 Set down only.","Arrive","Set Down Only"), "", $obsv["myway_stop"])));
} }
//:get myway_stops records //:get myway_stops records
//:search by starts with stopcode and starts with street if street is not null //:search by starts with stopcode and starts with street if street is not null
//no result, skip and display error //no result, skip and display error
if (sizeof($potentialStops) < 1) { if (sizeof($potentialStops) < 1) {
echo "error, potential stops for stopid {$obsv["stop_id"]} unknown"; echo "error, potential stops for stopid {$obsv["stop_id"]} unknown";
continue; continue;
} }
//print out stops //print out stops
echo "Matched stops: "; echo "Matched stops: ";
foreach ($potentialStops as $potentialStop) { foreach ($potentialStops as $potentialStop) {
echo $potentialStop['stop_id'] . " " . $potentialStop['stop_name'] . " "; echo $potentialStop['stop_id'] . " " . $potentialStop['stop_name'] . " ";
} }
echo "<br>"; echo "<br>";
//:get myway_route record //:get myway_route record
//no result, skip and display error //no result, skip and display error
//print out route //print out route
$potentialRoutes = getRoutesByShortName($obsv["route_short_name"]); $potentialRoutes = getRoutesByShortName($obsv["route_short_name"]);
if (sizeof($potentialRoutes) < 1) { if (sizeof($potentialRoutes) < 1) {
echo "error, route '{$obsv["myway_route"]}' unknown"; echo "error, route '{$obsv["myway_route"]}' unknown";
continue; continue;
} }
$timeDeltas = Array(); $timeDeltas = Array();
foreach ($potentialRoutes as $potentialRoute) { foreach ($potentialRoutes as $potentialRoute) {
echo "Matched route: {$potentialRoute['route_id']} {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']} {$timing_period}<br>"; echo "Matched route: {$potentialRoute['route_id']} {$potentialRoute['route_short_name']} {$timing_period}<br>";
foreach ($potentialStops as $potentialStop) { foreach ($potentialStops as $potentialStop) {
$stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period); $stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period);
$foundRoute = Array(); $foundRoute = Array();
foreach ($stopRoutes as $stopRoute) { foreach ($stopRoutes as $stopRoute) {
//Check if this route stops at each stop //Check if this route stops at each stop
if ($stopRoute['route_id'] == $potentialRoute['route_id']) { if ($stopRoute['route_id'] == $potentialRoute['route_id']) {
echo "Matching route {$stopRoute['route_id']} found at stop #{$potentialStop['stop_id']}<br>"; echo "Matching route {$stopRoute['route_id']} found at stop #{$potentialStop['stop_id']}<br>";
$foundRoute = $stopRoute; $foundRoute = $stopRoute;
//if does get tripstoptimes for this route //if does get tripstoptimes for this route
$trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time, 10, $potentialRoute['route_short_name']); $trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time, 10, $potentialRoute['route_short_name']);
foreach ($trips as $trip) { foreach ($trips as $trip) {
//echo $trip['route_id']." ".$stopRoute['route_id'].";"; //echo $trip['route_id']." ".$stopRoute['route_id'].";";
if ($trip['route_id'] == $stopRoute['route_id']) { if ($trip['route_id'] == $stopRoute['route_id']) {
$timedTrip = getTripAtStop($trip['trip_id'], $trip['stop_sequence']); $timedTrip = getTripAtStop($trip['trip_id'], $trip['stop_sequence']);
$actual_time = strtotime($time); $actual_time = strtotime($time);
$trip_time = strtotime($timedTrip['arrival_time']); $trip_time = strtotime($timedTrip['arrival_time']);
$timeDiff = $actual_time - $trip_time; $timeDiff = $actual_time - $trip_time;
//work out time delta, put into array with index of delta //work out time delta, put into array with index of delta
$timeDeltas[] = Array( $timeDeltas[] = Array(
"timeDiff" => $timeDiff, "timeDiff" => $timeDiff,
"stop_id" => $potentialStop['stop_id'], "stop_id" => $potentialStop['stop_id'],
"stop_sequence" => $trip['stop_sequence'], "stop_sequence" => $trip['stop_sequence'],
"route_name" => "{$trip['route_short_name']} {$trip['trip_headsign']}", "route_name" => "{$trip['route_short_name']} {$trip['trip_headsign']}",
"route_id" => $trip['route_id'] "route_id" => $trip['route_id']
); );
echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_id']} (#{$potentialStop['stop_name']}, sequence #{$trip['stop_sequence']})<br>"; echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_id']} (#{$potentialStop['stop_name']}, sequence #{$trip['stop_sequence']})<br>";
echo "Arriving at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes<br>"; echo "Arriving at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes<br>";
} else { } else {
echo "{$trip['route_id']} != {$stopRoute['route_id']}<br>"; echo "{$trip['route_id']} != {$stopRoute['route_id']}<br>";
} }
} }
if (sizeof($timeDeltas) == 0) echo "Error, no trips found.<bR>"; if (sizeof($timeDeltas) == 0) echo "Error, no trips found.<bR>";
break; // because have found route break; // because have found route
} }
} }
if (sizeof($foundRoute) < 1) { if (sizeof($foundRoute) < 1) {
//print out that stops/does not stop //print out that stops/does not stop
echo "No matching routes found at {$potentialStop['stop_id']}<br>"; echo "No matching routes found at {$potentialStop['stop_id']}<br>";
//var_dump($stopRoutes); //var_dump($stopRoutes);
flush(); flush();
} }
} }
} }
// lowest delta is recorded delta // lowest delta is recorded delta
usort($timeDeltas, "abssort"); usort($timeDeltas, "abssort");
$lowestDelta = $timeDeltas[0]["timeDiff"]; $lowestDelta = $timeDeltas[0]["timeDiff"];
if (sizeof($timeDeltas) != 0) { if (sizeof($timeDeltas) != 0) {
if (abs($lowestDelta) > 9999) { if (abs($lowestDelta) > 9999) {
echo "Difference of " . round($lowestDelta / 60, 2) . " minutes is too high. Will not record this observation<br>"; echo "Difference of " . round($lowestDelta / 60, 2) . " minutes is too high. Will not record this observation<br>";
} else { } else {
echo "Lowest difference of " . round($lowestDelta / 60, 2) . " minutes will be recorded for this observation<br>"; echo "Lowest difference of " . round($lowestDelta / 60, 2) . " minutes will be recorded for this observation<br>";
$observation_id = $obsv['observation_id']; $observation_id = $obsv['observation_id'];
$route_name = $timeDeltas[0]["route_name"]; $route_name = $timeDeltas[0]["route_name"];
$route_id = $timeDeltas[0]["route_id"]; $route_id = $timeDeltas[0]["route_id"];
$stop_id = $timeDeltas[0]["stop_id"]; $stop_id = $timeDeltas[0]["stop_id"];
$myway_stop = $obsv["myway_stop"]; $myway_stop = $obsv["myway_stop"];
$stop_sequence = $timeDeltas[0]["stop_sequence"]; $stop_sequence = $timeDeltas[0]["stop_sequence"];
$stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_id, stop_id, timing_delta, time, date, timing_period, stop_sequence,myway_stop,route_name) $stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_id, stop_id, timing_delta, time, date, timing_period, stop_sequence,myway_stop,route_name)
values (:observation_id, :route_id, :stop_id, :timing_delta, :time, :date, :timing_period, :stop_sequence,:myway_stop,:route_name)"); values (:observation_id, :route_id, :stop_id, :timing_delta, :time, :date, :timing_period, :stop_sequence,:myway_stop,:route_name)");
$stmt->bindParam(':observation_id', $observation_id); $stmt->bindParam(':observation_id', $observation_id);
$stmt->bindParam(':route_id', $route_id); $stmt->bindParam(':route_id', $route_id);
$stmt->bindParam(':route_name', $route_name); $stmt->bindParam(':route_name', $route_name);
$stmt->bindParam(':stop_id', $stop_id); $stmt->bindParam(':stop_id', $stop_id);
$stmt->bindParam(':myway_stop', $myway_stop); $stmt->bindParam(':myway_stop', $myway_stop);
$stmt->bindParam(':timing_delta', $lowestDelta); $stmt->bindParam(':timing_delta', $lowestDelta);
$stmt->bindParam(':time', $time_tz); $stmt->bindParam(':time', $time_tz);
$stmt->bindParam(':date', $date); $stmt->bindParam(':date', $date);
$stmt->bindParam(':timing_period', $timing_period); $stmt->bindParam(':timing_period', $timing_period);
$stmt->bindParam(':stop_sequence', $stop_sequence); $stmt->bindParam(':stop_sequence', $stop_sequence);
// insert a record // insert a record
$stmt->execute(); $stmt->execute();
if ($stmt->rowCount() > 0) { if ($stmt->rowCount() > 0) {
echo "Recorded.<br>"; echo "Recorded.<br>";
} }
var_dump($conn->errorInfo()); var_dump($conn->errorInfo());
flush(); flush();
} }
} }
flush(); flush();
} }
   
file:a/stop.php -> file:b/stop.php
<?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.
*/ */
include ('include/common.inc.php'); include ('include/common.inc.php');
if ($stopid) if ($stopid)
$stop = getStop($stopid); $stop = getStop($stopid);
/* if ($stopcode != "" && $stop[5] != $stopcode) { /* if ($stopcode != "" && $stop[5] != $stopcode) {
$url = $APIurl . "/json/stopcodesearch?q=" . $stopcode; $url = $APIurl . "/json/stopcodesearch?q=" . $stopcode;
$stopsearch = json_decode(getPage($url)); $stopsearch = json_decode(getPage($url));
$stopid = $stopsearch[0][0]; $stopid = $stopsearch[0][0];
$url = $APIurl . "/json/stop?stop_id=" . $stopid; $url = $APIurl . "/json/stop?stop_id=" . $stopid;
$stop = json_decode(getPage($url)); $stop = json_decode(getPage($url));
} }
if (!startsWith($stop[5], "Wj") && strpos($stop[1], "Platform") === false) { if (!startsWith($stop[5], "Wj") && strpos($stop[1], "Platform") === false) {
// expand out to all platforms // expand out to all platforms
   
} */ } */
   
$stops = Array(); $stops = Array();
$stopPositions = Array(); $stopPositions = Array();
$stopNames = Array(); $stopNames = Array();
$tripStopNumbers = Array(); $tripStopNumbers = Array();
$allStopsTrips = Array(); $allStopsTrips = Array();
$fetchedTripSequences = Array(); $fetchedTripSequences = Array();
$stopLinks = ""; $stopLinks = "";
if (isset($stopids)) { if (isset($stopids)) {
foreach ($stopids as $sub_stopid) { foreach ($stopids as $sub_stopid) {
$stops[] = getStop($sub_stopid); $stops[] = getStop($sub_stopid);
} }
$stop = $stops[0]; $stop = $stops[0];
$stopid = $stops[0]["stop_id"]; $stopid = $stops[0]["stop_id"];
$stopLinks.= "Individual stop pages: <br>"; $stopLinks.= "Individual stop pages: <br>";
foreach ($stops as $key => $sub_stop) { foreach ($stops as $key => $sub_stop) {
   
$stopNames[$key] = $sub_stop["stop_name"]; $stopNames[$key] = $sub_stop["stop_name"];
$stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&amp;stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . '</a> '; $stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&amp;stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . '</a> ';
   
$stopPositions[$key] = Array( $stopPositions[$key] = Array(
$sub_stop["stop_lat"], $sub_stop["stop_lat"],
$sub_stop["stop_lon"] $sub_stop["stop_lon"]
); );
$trips = getStopTrips($sub_stop["stop_id"]); $trips = getStopTrips($sub_stop["stop_id"]);
$tripSequence = ""; $tripSequence = "";
foreach ($trips as $trip) { foreach ($trips as $trip) {
$tripSequence.= "{$trip['trip_id']},"; $tripSequence.= "{$trip['trip_id']},";
$tripStopNumbers[$trip['trip_id']][] = $key; $tripStopNumbers[$trip['trip_id']][] = $key;
} }
if (!in_array($tripSequence, $fetchedTripSequences)) { if (!in_array($tripSequence, $fetchedTripSequences)) {
// only fetch new trip sequences // only fetch new trip sequences
$fetchedTripSequences[] = $tripSequence; $fetchedTripSequences[] = $tripSequence;
$trips = getStopTripsWithTimes($sub_stop["stop_id"]); $trips = getStopTripsWithTimes($sub_stop["stop_id"]);
foreach ($trips as $trip) { foreach ($trips as $trip) {
if (!isset($allStopsTrips[$trip["trip_id"]])) if (!isset($allStopsTrips[$trip["trip_id"]]))
$allStopsTrips[$trip["trip_id"]] = $trip; $allStopsTrips[$trip["trip_id"]] = $trip;
} }
} }
//else { //else {
// echo "skipped sequence $tripSequence"; // echo "skipped sequence $tripSequence";
//} //}
} }
} }
if (sizeof($stops) > 0) { if (sizeof($stops) > 0) {
$stopDescParts = explode("<br>",$stop['stop_desc']); $stopDescParts = explode("<br>",$stop['stop_desc']);
include_header(trim(str_replace("Street: ","",$stopDescParts[0])), "stop"); include_header(trim(str_replace("Street: ","",$stopDescParts[0])), "stop");
} else { } else {
include_header($stop['stop_name']); include_header($stop['stop_name']);
} }
/* $serviceAlerts = json_decode(getPage(curPageURL() . "/servicealerts_api.php?filter_class=stop&filter_id=".$stopid) , true); /* $serviceAlerts = json_decode(getPage(curPageURL() . "/servicealerts_api.php?filter_class=stop&filter_id=".$stopid) , true);
   
foreach($serviceAlerts['entities'] as $serviceAlert) { foreach($serviceAlerts['entities'] as $serviceAlert) {
echo '<div id="servicewarning">'.$serviceAlert['alert']['description']['translation'].'</div>'; echo '<div id="servicewarning">'.$serviceAlert['alert']['description']['translation'].'</div>';
} */ } */
   
echo '<span class="content-secondary">'; echo '<span class="content-secondary">';
echo $stopLinks; echo $stopLinks;
if (sizeof($stops) > 0) { if (sizeof($stops) > 0) {
trackEvent("View Stops", "View Combined Stops", $stop["stop_name"], $stop["stop_id"]); trackEvent("View Stops", "View Combined Stops", $stop["stop_name"], $stop["stop_id"]);
echo staticmap($stopPositions); echo staticmap($stopPositions);
} else { } else {
trackEvent("View Stops", "View Single Stop", $stop["stop_name"], $stop["stop_id"]); trackEvent("View Stops", "View Single Stop", $stop["stop_name"], $stop["stop_id"]);
echo staticmap(Array( echo staticmap(Array(
0 => Array( 0 => Array(
$stop["stop_lat"], $stop["stop_lat"],
$stop["stop_lon"] $stop["stop_lon"]
) )
)); ));
} }
   
timeSettings(); timeSettings();
   
echo '</span><span class="content-primary">'; echo '</span><span class="content-primary">';
echo ' <ul data-role="listview" data-inset="true">'; echo ' <ul data-role="listview" data-inset="true">';
if (sizeof($allStopsTrips) > 0) { if (sizeof($allStopsTrips) > 0) {
sktimesort($allStopsTrips, "arrival_time", true); sktimesort($allStopsTrips, "arrival_time", true);
$trips = $allStopsTrips; $trips = $allStopsTrips;
} else { } else {
$trips = getStopTripsWithTimes($stopid); $trips = getStopTripsWithTimes($stopid);
} }
   
echo "<div class='ui-header' style='overflow: visible; height: 2.5em'>"; echo "<div class='ui-header' style='overflow: visible; height: 2.5em'>";
// if we have too many trips, cut down to size. // if we have too many trips, cut down to size.
if (sizeof($trips) > 10) { if (sizeof($trips) > 10) {
$trips = array_splice($trips, 0,10); $trips = array_splice($trips, 0,10);
} }
// later/earlier button setup // later/earlier button setup
if (sizeof($trips) == 0) { if (sizeof($trips) == 0) {
$time = isset($_REQUEST['time']) ? strtotime($_REQUEST['time']) : time(); $time = isset($_REQUEST['time']) ? strtotime($_REQUEST['time']) : time();
$earlierTime = $time - (90 * 60); $earlierTime = $time - (90 * 60);
$laterTime = $time + (90 * 60); $laterTime = $time + (90 * 60);
} else { } else {
$tripsKeys = array_keys($trips); $tripsKeys = array_keys($trips);
$earlierTime = strtotime($trips[$tripsKeys[0]]['arrival_time']) - (90 * 60); $earlierTime = strtotime($trips[$tripsKeys[0]]['arrival_time']) - (90 * 60);
$laterTime = strtotime($trips[$tripsKeys[sizeof($trips) - 1]]['arrival_time']) - 60; $laterTime = strtotime($trips[$tripsKeys[sizeof($trips) - 1]]['arrival_time']) - 60;
} }
if (sizeof($stopids) > 0) { if (isset($stopids) && sizeof($stopids) > 0) {
$stopidurl = "stopids=" . implode(",", $stopids); $stopidurl = "stopids=" . implode(",", $stopids);
} else { } else {
$stopidurl = "stopid=$stopid"; $stopidurl = "stopid=$stopid";
} }
if (sizeof($trips) >= 10) { if (sizeof($trips) >= 10) {
echo '<a href="stop.php?' . $stopidurl . '&service_period=' . service_period() . '&time=' . date("H:i", $laterTime) . '" data-icon="arrow-r" class="ui-btn-right">Later Trips</a>'; echo '<a href="stop.php?' . $stopidurl . '&service_period=' . service_period() . '&time=' . date("H:i", $laterTime) . '" data-icon="arrow-r" class="ui-btn-right">Later Trips</a>';
} }
echo '<a href="stop.php?' . $stopidurl . '&service_period=' . service_period() . '&time=' . date("H:i", $earlierTime) . '" data-icon="arrow-l" class="ui-btn-left">Earlier Trips</a>'; echo '<a href="stop.php?' . $stopidurl . '&service_period=' . service_period() . '&time=' . date("H:i", $earlierTime) . '" data-icon="arrow-l" class="ui-btn-left">Earlier Trips</a>';
echo "</div>"; echo "</div>";
if (sizeof($trips) == 0) { if (sizeof($trips) == 0) {
echo "<li style='text-align: center;'>No trips in the near future.</li>"; echo "<li style='text-align: center;'>No trips in the near future.</li>";
} else { } else {
foreach ($trips as $trip) { foreach ($trips as $trip) {
echo '<li>'; echo '<li>';
   
$destination = getTripDestination($trip['trip_id']); $destination = getTripDestination($trip['trip_id']);
echo '<a href="trip.php?stopid=' . $stopid . '&amp;tripid=' . $trip['trip_id'] . '"><h3>'. $trip['route_short_name'] . " towards " . $destination['stop_name'] . "</h3><p>"; echo '<a href="trip.php?stopid=' . $stopid . '&amp;tripid=' . $trip['trip_id'] . '"><h3>'. $trip['route_short_name'] . " towards " . $destination['stop_name'] . "</h3><p>";
$viaPoints = viaPointNames($trip['trip_id'], $trip['stop_sequence']); $viaPoints = viaPointNames($trip['trip_id'], $trip['stop_sequence']);
if ($viaPoints != "") if ($viaPoints != "")
echo '<br><span class="viaPoints">Via: ' . $viaPoints . '</span>'; echo '<br><span class="viaPoints">Via: ' . $viaPoints . '</span>';
if (sizeof($tripStopNumbers) > 0) { if (sizeof($tripStopNumbers) > 0) {
echo '<br><small>Boarding At: '; echo '<br><small>Boarding At: ';
if (sizeof($tripStopNumbers[$trip['trip_id']]) == sizeof($stopids)) { if (sizeof($tripStopNumbers[$trip['trip_id']]) == sizeof($stopids)) {
echo "All Stops"; echo "All Stops";
} else { } else {
foreach ($tripStopNumbers[$trip['trip_id']] as $key) { foreach ($tripStopNumbers[$trip['trip_id']] as $key) {
echo $stopNames[$key] . ', '; echo $stopNames[$key] . ', ';
} }
} }
echo '</small>'; echo '</small>';
} }
echo '</p>'; echo '</p>';
echo '<p class="ui-li-aside"><strong>' . $trip['arrival_time'] . '</strong></p>'; echo '<p class="ui-li-aside"><strong>' . $trip['arrival_time'] . '</strong></p>';
echo '</a></li>'; echo '</a></li>';
flush(); flush();
@ob_flush(); @ob_flush();
} }
} }
echo '</ul>'; echo '</ul>';
echo '</span>'; echo '</span>';
include_footer(); include_footer();
?> ?>
   
<?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.
*/ */
include ('include/common.inc.php'); include ('include/common.inc.php');
$stops = Array(); $stops = Array();
   
function navbar() { function navbar() {
echo ' echo '
<div data-role="navbar"> <div data-role="navbar">
<ul> <ul>
<li><a href="stopList.php">Stops by Name</a></li> <li><a href="stopList.php">Stops by Name</a></li>
<li><a href="stopList.php?bysuburbs=yes">By Suburb</a></li> <li><a href="stopList.php?bysuburbs=yes">By Suburb</a></li>
<li><a href="stopList.php?nearby=yes">Nearby Stops</a></li> <li><a href="stopList.php?nearby=yes">Nearby Stops</a></li>
</ul> </ul>
</div> </div>
'; ';
} }
   
// By suburb // By suburb
if (isset($bysuburbs)) { if (isset($bysuburbs)) {
include_header("Stops by Suburb", "stopList"); include_header("Stops by Suburb", "stopList");
navbar(); navbar();
echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; echo ' <ul data-role="listview" data-filter="true" data-inset="true" >';
if (!isset($firstLetter)) { if (!isset($firstLetter)) {
foreach (range('A', 'Y') as $letter) { // no suburbs start with J, Q, U, V, X or Z foreach (range('A', 'Y') as $letter) { // no suburbs start with J, Q, U, V, X or Z
if ($letter != "J" && $letter != "Q" && $letter != "U" && $letter != "V" && $letter != "X") echo "<li><a href=\"stopList.php?firstLetter=$letter&amp;bysuburbs=yes\">$letter...</a></li>\n"; if ($letter != "J" && $letter != "Q" && $letter != "U" && $letter != "V" && $letter != "X") echo "<li><a href=\"stopList.php?firstLetter=$letter&amp;bysuburbs=yes\">$letter...</a></li>\n";
} }
} else { } else {
foreach ($suburbs as $suburb) { foreach ($suburbs as $suburb) {
if (startsWith($suburb, $firstLetter)) { if (startsWith($suburb, $firstLetter)) {
echo '<li><a href="stopList.php?suburb=' . urlencode($suburb) . '">' . $suburb . '</a></li>'; echo '<li><a href="stopList.php?suburb=' . urlencode($suburb) . '">' . $suburb . '</a></li>';
} }
} }
} }
echo '</ul>'; echo '</ul>';
} else { } else {
// Timing Points / All stops // Timing Points / All stops
if (isset($nearby)) { if (isset($nearby)) {
$listType = 'nearby=yes'; $listType = 'nearby=yes';
include_header("Nearby Stops", "stopList", true, true); include_header("Nearby Stops", "stopList", true, true);
trackEvent("Stop Lists", "Stops Nearby", $_SESSION['lat'] . "," . $_SESSION['lon']); trackEvent("Stop Lists", "Stops Nearby", $_SESSION['lat'] . "," . $_SESSION['lon']);
navbar(); navbar();
if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") { if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") {
placeSettings(); placeSettings();
include_footer(); include_footer();
die(); die();
} }
$stops = getNearbyStops($_SESSION['lat'], $_SESSION['lon'], 15); $stops = getNearbyStops($_SESSION['lat'], $_SESSION['lon'], 15);
echo '<span class="content-secondary">'; echo '<span class="content-secondary">';
$stopPositions[] = Array( $stopPositions[] = Array(
$_SESSION['lat'], $_SESSION['lat'],
$_SESSION['lon'] $_SESSION['lon']
); );
foreach ($stops as $sub_stop) { foreach ($stops as $sub_stop) {
$stopPositions[] = Array( $stopPositions[] = Array(
$sub_stop["stop_lat"], $sub_stop["stop_lat"],
$sub_stop["stop_lon"] $sub_stop["stop_lon"]
); );
} }
echo staticmap($stopPositions, true, true); echo staticmap($stopPositions, true, true);
placeSettings(); placeSettings();
echo '</span><span class="content-primary">'; echo '</span><span class="content-primary">';
} else if (isset($suburb)) { } else if (isset($suburb)) {
$stops = getStopsBySuburb($suburb); $stops = getStopsBySuburb($suburb);
include_header("Stops in " . ucwords($suburb), "stopList"); include_header("Stops in " . ucwords($suburb), "stopList");
navbar(); navbar();
trackEvent("Stop Lists", "Stops By Suburb", $suburb); trackEvent("Stop Lists", "Stops By Suburb", $suburb);
} else { } else {
$listType = 'allstops=yes'; $listType = 'allstops=yes';
$stops = getStops($firstLetter); $stops = getStops($firstLetter);
include_header("Stops by Name", "stopList"); include_header("Stops by Name", "stopList");
navbar(); navbar();
} }
echo ' <ul data-role="listview" data-filter="true" data-inset="true" >'; echo ' <ul data-role="listview" data-filter="true" data-inset="true" >';
if (!isset($firstLetter) && !isset($suburb) && !isset($nearby)) { // all stops by letter if (!isset($firstLetter) && !isset($suburb) && !isset($nearby)) { // all stops by letter
foreach (range('A', 'Y') as $letter) { // no streets start with X or Z foreach (range('A', 'Y') as $letter) { // no streets start with X or Z
if ($letter != "X") echo "<li><a href=\"stopList.php?firstLetter=$letter&amp;$listType\">$letter...</a></li>\n"; if ($letter != "X") echo "<li><a href=\"stopList.php?firstLetter=$letter&amp;$listType\">$letter...</a></li>\n";
} }
} else { } else {
//var_dump($stops); //var_dump($stops);
$stopsGrouped = Array(); $stopsGrouped = Array();
foreach ($stops as $key => $stop) { foreach ($stops as $key => $stop) {
if (stopCompare($stops[$key]["stop_name"]) if ($key + 1 >= sizeof($stops) ||
!= stopCompare($stops[$key + 1]["stop_name"]) stopCompare($stops[$key]["stop_name"]) != stopCompare($stops[$key + 1]["stop_name"])) {
|| $key + 1 >= sizeof($stops)) {  
if (sizeof($stopsGrouped) > 0) { if (sizeof($stopsGrouped) > 0) {
// print and empty grouped stops // print and empty grouped stops
// subsequent duplicates // subsequent duplicates
$stopsGrouped["stop_ids"][] = $stop['stop_id']; $stopsGrouped["stop_ids"][] = $stop['stop_id'];
echo '<li>'; echo '<li>';
echo '<a href="stop.php?stopids=' . implode(",", $stopsGrouped['stop_ids']) . '&stopcodes=' . implode(",", $stopsGrouped['stop_codes']) . '">'; echo '<a href="stop.php?stopids=' . implode(",", $stopsGrouped['stop_ids']) . '&stopcodes=' . implode(",", $stopsGrouped['stop_codes']) . '">';
if (isset($_SESSION['lat']) && isset($_SESSION['lon'])) { if (isset($_SESSION['lat']) && isset($_SESSION['lon'])) {
echo '<span class="ui-li-count">' . distance($stop['stop_lat'], $stop['stop_lon'], $_SESSION['lat'], $_SESSION['lon'], true) . 'm away</span>'; echo '<span class="ui-li-count">' . distance($stop['stop_lat'], $stop['stop_lon'], $_SESSION['lat'], $_SESSION['lon'], true) . 'm away</span>';
} }
echo stopGroupTitle($stop['stop_name'],$stop['stop_desc']) . '<br><small>' . sizeof($stopsGrouped["stop_ids"]) . ' stops</small>'; echo stopGroupTitle($stop['stop_name'],$stop['stop_desc']) . '<br><small>' . sizeof($stopsGrouped["stop_ids"]) . ' stops</small>';
echo "</a></li>\n"; echo "</a></li>\n";
flush(); flush();
@ob_flush(); @ob_flush();
$stopsGrouped = Array(); $stopsGrouped = Array();
} else { } else {
// just a normal stop // just a normal stop
echo '<li>'; echo '<li>';
echo '<a href="stop.php?stopid=' . $stop['stop_id'] . '&amp;stopcode=' . $stop['stop_code'] . '">'; echo '<a href="stop.php?stopid=' . $stop['stop_id'] . '&amp;stopcode=' . $stop['stop_code'] . '">';
if (isset($_SESSION['lat']) && isset($_SESSION['lon'])) { if (isset($_SESSION['lat']) && isset($_SESSION['lon'])) {
echo '<span class="ui-li-count">' . distance($stop['stop_lat'], $stop['stop_lon'], $_SESSION['lat'], $_SESSION['lon'], true) . 'm away</span>'; echo '<span class="ui-li-count">' . distance($stop['stop_lat'], $stop['stop_lon'], $_SESSION['lat'], $_SESSION['lon'], true) . 'm away</span>';
} }
echo $stop['stop_name']; echo $stop['stop_name'];
echo "</a></li>\n"; echo "</a></li>\n";
flush(); flush();
@ob_flush(); @ob_flush();
} }
} else { } else {
// this is a duplicated line item // this is a duplicated line item
if ($key - 1 <= 0 || stopCompare($stops[$key]['stop_name']) != stopCompare($stops[$key - 1]['stop_name'])) { if ($key - 1 <= 0 || stopCompare($stops[$key]['stop_name']) != stopCompare($stops[$key - 1]['stop_name'])) {
// first duplicate // first duplicate
$stopsGrouped = Array( $stopsGrouped = Array(
"name" => trim(preg_replace("/\(Platform.*/", "", $stop['stop_name'])), "name" => trim(preg_replace("/\(Platform.*/", "", $stop['stop_name'])),
"stop_ids" => Array( "stop_ids" => Array(
$stop['stop_id'] $stop['stop_id']
), ),
"stop_codes" => Array( "stop_codes" => Array(
$stop['stop_code'] $stop['stop_code']
) )
); );
} else { } else {
// subsequent duplicates // subsequent duplicates
$stopsGrouped["stop_ids"][] = $stop['stop_id']; $stopsGrouped["stop_ids"][] = $stop['stop_id'];
} }
} }
} }
} }
echo '</ul>'; echo '</ul>';
if (isset($nearby)) if (isset($nearby))
echo '</span>'; echo '</span>';
} }
include_footer(); include_footer();
?> ?>