Refactor trip/route view
Refactor trip/route view

<?php <?php
   
function getRoute($routeID) { function getRoute($routeID) {
$query = "Select * from routes where route_id = '$routeID' LIMIT 1"; $query = "Select * from routes where route_id = '$routeID' LIMIT 1";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_assoc($result); return pg_fetch_assoc($result);
} }
function getRoutes() { function getRoutes() {
global $conn; global $conn;
$query = "Select * from routes order by route_short_name;"; $query = "Select * from routes order by route_short_name;";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
   
function getRoutesByNumber($routeNumber = "") { function getRoutesByNumber($routeNumber = "") {
global $conn; global $conn;
if ($routeNumber != "") { if ($routeNumber != "") {
$query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id = $query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id =
routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where route_short_name = '$routeNumber' order by route_short_name;"; routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where route_short_name = '$routeNumber' order by route_short_name;";
} else { } else {
$query = "SELECT DISTINCT route_short_name from routes order by route_short_name"; $query = "SELECT DISTINCT route_short_name from routes order by route_short_name";
} }
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
   
function getRouteNextTrip($routeID) { function getRouteNextTrip($routeID) {
  global $conn;
$query = "select * from routes join trips on trips.route_id = routes.route_id $query = "select * from routes join trips on trips.route_id = routes.route_id
join stop_times on stop_times.trip_id = trips.trip_id where join stop_times on stop_times.trip_id = trips.trip_id where
arrival_time > CURRENT_TIME and routes.route_id = '$routeID' order by arrival_time > CURRENT_TIME and routes.route_id = '$routeID' order by
arrival_time limit 1"; arrival_time limit 1";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_assoc($result); return pg_fetch_assoc($result);
} }
  function getRouteTrips($routeID) {
  global $conn;
  $query = "select * from routes join trips on trips.route_id = routes.route_id
  join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = '$routeID' order by
  arrival_time ";
  debug($query,"database");
  $result = pg_query($conn, $query);
  if (!$result) {
  databaseError(pg_result_error($result));
  return Array();
  }
  return pg_fetch_all($result);
  }
function getRoutesByDestination($destination = "", $service_period = "") { function getRoutesByDestination($destination = "", $service_period = "") {
global $conn; global $conn;
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
if ($destination != "") { if ($destination != "") {
$query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id $query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id
FROM stop_times join trips on trips.trip_id = FROM stop_times join trips on trips.trip_id =
stop_times.trip_id join routes on trips.route_id = routes.route_id stop_times.trip_id join routes on trips.route_id = routes.route_id
WHERE route_long_name = '$destination' AND service_id='$service_period' order by route_short_name"; WHERE route_long_name = '$destination' AND service_id='$service_period' order by route_short_name";
} else { } else {
$query = "SELECT DISTINCT route_long_name $query = "SELECT DISTINCT route_long_name
FROM stop_times join trips on trips.trip_id = FROM stop_times join trips on trips.trip_id =
stop_times.trip_id join routes on trips.route_id = routes.route_id stop_times.trip_id join routes on trips.route_id = routes.route_id
WHERE service_id='$service_period' order by route_long_name"; WHERE service_id='$service_period' order by route_long_name";
} }
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
   
function getRoutesBySuburb($suburb, $service_period = "") { function getRoutesBySuburb($suburb, $service_period = "") {
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
global $conn; global $conn;
$query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name $query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name
FROM stop_times join trips on trips.trip_id = stop_times.trip_id FROM stop_times 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 zone_id LIKE '%$suburb;%' AND service_id='$service_period' ORDER BY route_short_name"; WHERE zone_id LIKE '%$suburb;%' AND service_id='$service_period' ORDER BY route_short_name";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
   
function getRoutesNearby($lat, $lng, $limit = "", $distance = 500) { function getRoutesNearby($lat, $lng, $limit = "", $distance = 500) {
   
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
if ($limit != "") $limit = " LIMIT $limit "; if ($limit != "") $limit = " LIMIT $limit ";
global $conn; global $conn;
$query = "SELECT service_id,trips.route_id,route_short_name,route_long_name, $query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,
min(ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE)) as distance min(ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE)) as distance
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 service_id='$service_period' WHERE service_id='$service_period'
AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), $distance, FALSE) AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), $distance, FALSE)
group by service_id,trips.route_id,route_short_name,route_long_name group by service_id,trips.route_id,route_short_name,route_long_name
order by distance $limit"; order by distance $limit";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
?> ?>
<?php <?php
function getTrip($tripID) function getTrip($tripID)
{ {
global $conn; global $conn;
$query = "Select * from trips where trip_id = '$tripID' join routes on trips.route_id = routes.route_id LIMIT 1"; $query = "Select * from trips
  join routes on trips.route_id = routes.route_id
  where trip_id = '$tripID'
  LIMIT 1";
debug($query, "database"); debug($query, "database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_assoc($result); return pg_fetch_assoc($result);
} }
function getTripShape() function getTripShape()
{ {
/* def handle_json_GET_tripstopTimes(self, params): /* def handle_json_GET_tripstopTimes(self, params):
schedule = self.server.schedule schedule = self.server.schedule
try: try:
trip = schedule.GetTrip(params.get('trip')) trip = schedule.GetTrip(params.get('trip'))
except KeyError: except KeyError:
# if a non-existent trip is searched for, the return nothing # if a non-existent trip is searched for, the return nothing
return return
time_stops = trip.GetTimeInterpolatedStops() time_stops = trip.GetTimeInterpolatedStops()
stops = [] stops = []
times = [] times = []
for arr,ts,is_timingpoint in time_stops: for arr,ts,is_timingpoint in time_stops:
stops.append(StopToTuple(ts.stop)) stops.append(StopToTuple(ts.stop))
times.append(arr) times.append(arr)
return [stops, times] return [stops, times]
def handle_json_GET_tripshape(self, params): def handle_json_GET_tripshape(self, params):
schedule = self.server.schedule schedule = self.server.schedule
try: try:
trip = schedule.GetTrip(params.get('trip')) trip = schedule.GetTrip(params.get('trip'))
except KeyError: except KeyError:
# if a non-existent trip is searched for, the return nothing # if a non-existent trip is searched for, the return nothing
return return
points = [] points = []
if trip.shape_id: if trip.shape_id:
shape = schedule.GetShape(trip.shape_id) shape = schedule.GetShape(trip.shape_id)
for (lat, lon, dist) in shape.points: for (lat, lon, dist) in shape.points:
points.append((lat, lon)) points.append((lat, lon))
else: else:
time_stops = trip.GetTimeStops() time_stops = trip.GetTimeStops()
for arr,dep,stop in time_stops: for arr,dep,stop in time_stops:
points.append((stop.stop_lat, stop.stop_lon)) points.append((stop.stop_lat, stop.stop_lon))
return points*/ return points*/
} }
function getTimeInterpolatedTrip($tripID) function getTimeInterpolatedTrip($tripID)
{ {
global $conn; global $conn;
$query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_lat,stop_lon, $query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_lat,stop_lon,stop_name,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' ORDER BY stop_sequence"; WHERE trips.trip_id = '$tripID' ORDER BY stop_sequence";
debug($query, "database"); debug($query, "database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
$stopTimes = pg_fetch_all($result); $stopTimes = pg_fetch_all($result);
$cur_timepoint = Array(); $cur_timepoint = Array();
$next_timepoint = Array(); $next_timepoint = Array();
$distance_between_timepoints = 0.0; $distance_between_timepoints = 0.0;
$distance_traveled_between_timepoints = 0.0; $distance_traveled_between_timepoints = 0.0;
$rv = Array(); $rv = Array();
foreach ($stopTimes as $i => $stopTime) { foreach ($stopTimes as $i => $stopTime) {
if ($stopTime['arrival_time'] != "") { if ($stopTime['arrival_time'] != "") {
// is timepoint // is timepoint
$cur_timepoint = $stopTime; $cur_timepoint = $stopTime;
$distance_between_timepoints = 0.0; $distance_between_timepoints = 0.0;
$distance_traveled_between_timepoints = 0.0; $distance_traveled_between_timepoints = 0.0;
if ($i + 1 < sizeof($stopTimes)) { if ($i + 1 < sizeof($stopTimes)) {
$k = $i + 1; $k = $i + 1;
$distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]); $distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) { while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) {
$k += 1; $k += 1;
//echo "k".$k; //echo "k".$k;
$distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]); $distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
} }
$next_timepoint = $stopTimes[$k]; $next_timepoint = $stopTimes[$k];
$rv[] = $stopTime; $rv[] = $stopTime;
} }
} }
else { else {
// is untimed point // is untimed point
//echo "i".$i; //echo "i".$i;
$distance_traveled_between_timepoints += distance($stopTimes[$i - 1]["stop_lat"], $stopTimes[$i - 1]["stop_lon"], $stopTimes[$i]["stop_lat"], $stopTimes[$i]["stop_lon"]); $distance_traveled_between_timepoints += distance($stopTimes[$i - 1]["stop_lat"], $stopTimes[$i - 1]["stop_lon"], $stopTimes[$i]["stop_lat"], $stopTimes[$i]["stop_lon"]);
//echo "$distance_traveled_between_timepoints / $distance_between_timepoints<br>"; //echo "$distance_traveled_between_timepoints / $distance_between_timepoints<br>";
$distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints; $distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints;
if ($next_timepoint["arrival_time"] != "") { if ($next_timepoint["arrival_time"] != "") {
$total_time = strtotime($next_timepoint["arrival_time"]) - strtotime($cur_timepoint["arrival_time"]); $total_time = strtotime($next_timepoint["arrival_time"]) - strtotime($cur_timepoint["arrival_time"]);
//echo strtotime($next_timepoint["arrival_time"])." - ".strtotime($cur_timepoint["arrival_time"])."<br>"; //echo strtotime($next_timepoint["arrival_time"])." - ".strtotime($cur_timepoint["arrival_time"])."<br>";
$time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]); $time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]);
$stopTime["arrival_time"] = date("H:i:s", $time_estimate); $stopTime["arrival_time"] = date("H:i:s", $time_estimate);
} else { } else {
$stopTime["arrival_time"] = $cur_timepoint["arrival_time"]; $stopTime["arrival_time"] = $cur_timepoint["arrival_time"];
} }
$rv[] = $stopTime; $rv[] = $stopTime;
//var_dump($rv); //var_dump($rv);
} }
} }
return $rv; return $rv;
} }
function getTimeInterpolatedTripAtStop($tripID, $stop_sequence) function getTimeInterpolatedTripAtStop($tripID, $stop_sequence)
{ {
foreach (getTimeInterpolatedTrip($tripID) as $tripStop) { foreach (getTimeInterpolatedTrip($tripID) as $tripStop) {
if ($tripStop['stop_sequence'] == $stop_sequence) return $tripStop; if ($tripStop['stop_sequence'] == $stop_sequence) 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");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
$r = pg_fetch_assoc($result); $r = pg_fetch_assoc($result);
return $r['arrival_time']; return $r['arrival_time'];
} }
function viaPointNames($tripid, $stopid) function viaPointNames($tripid, $stop_sequence = "")
{ {
global $conn; global $conn;
$query = "SELECT stop_name $query = "SELECT stop_name
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'
AND stop_sequence > '$stop_sequence' ".($stop_sequence != "" ? "AND stop_sequence > '$stop_sequence'" : "").
AND substr(stop_code,1,2) != 'Wj' ORDER BY stop_sequence"; "AND substr(stop_code,1,2) != 'Wj' ORDER BY stop_sequence";
debug($query, "database"); debug($query, "database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
$pointNames = pg_fetch_all($result); $pointNames = pg_fetch_all($result);
return r_implode(", ", $pointNames); return r_implode(", ", $pointNames);
} }
?> ?>
file:a/stop.php -> file:b/stop.php
<?php <?php
include ('include/common.inc.php'); include ('include/common.inc.php');
$stopid = filter_var($_REQUEST['stopid'], FILTER_SANITIZE_NUMBER_INT); $stopid = filter_var($_REQUEST['stopid'], FILTER_SANITIZE_NUMBER_INT);
$stopcode = filter_var($_REQUEST['stopcode'], FILTER_SANITIZE_STRING); $stopcode = filter_var($_REQUEST['stopcode'], FILTER_SANITIZE_STRING);
if ($stopid) $stop = getStop($stopid); if ($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($_REQUEST['stopids'])) { if (isset($_REQUEST['stopids'])) {
$stopids = explode(",", filter_var($_REQUEST['stopids'], FILTER_SANITIZE_STRING)); $stopids = explode(",", filter_var($_REQUEST['stopids'], FILTER_SANITIZE_STRING));
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: "; $stopLinks.= "Individual stop pages: ";
foreach ($stops as $key => $sub_stop) { foreach ($stops as $key => $sub_stop) {
// $stopNames[$key] = $sub_stop[1] . ' Stop #' . ($key + 1); // $stopNames[$key] = $sub_stop[1] . ' Stop #' . ($key + 1);
if (strpos($stop["stop_name"], "Station")) { if (strpos($stop["stop_name"], "Station")) {
$stopNames[$key] = 'Platform ' . ($key + 1); $stopNames[$key] = 'Platform ' . ($key + 1);
$stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . '</a> '; $stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . '</a> ';
} }
else { else {
$stopNames[$key] = '#' . ($key + 1); $stopNames[$key] = '#' . ($key + 1);
$stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . ' Stop #' . ($key + 1) . '</a> '; $stopLinks.= '<a href="stop.php?stopid=' . $sub_stop["stop_id"] . '&stopcode=' . $sub_stop["stop_code"] . '">' . $sub_stop["stop_name"] . ' Stop #' . ($key + 1) . '</a> ';
} }
$stopPositions[$key] = Array( $stopPositions[$key] = Array(
$sub_stop["stop_lat"], $sub_stop["stop_lat"],
$sub_stop["stop_lon"] $sub_stop["stop_lon"]
); );