Refactor to use PostGIS database instead of gtfs tools
[busui.git] / include / db / trip-dao.inc.php
blob:a/include/db/trip-dao.inc.php -> blob:b/include/db/trip-dao.inc.php
<?php <?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.
  */
   
function getTrip($tripID) { function getTrip($tripID) {
/* def handle_json_GET_triprows(self, params): global $conn;
"""Return a list of rows from the feed file that are related to this $query = "Select * from trips
trip.""" join routes on trips.route_id = routes.route_id
schedule = self.server.schedule where trip_id = :tripID
try: LIMIT 1";
trip = schedule.GetTrip(params.get('trip', None)) debug($query, "database");
except KeyError: $query = $conn->prepare($query);
# if a non-existent trip is searched for, the return nothing $query->bindParam(":tripID", $tripID);
return $query->execute();
route = schedule.GetRoute(trip.route_id) if (!$query) {
trip_row = dict(trip.iteritems()) databaseError($conn->errorInfo());
route_row = dict(route.iteritems())  
return [['trips.txt', trip_row], ['routes.txt', route_row]] return Array();
*/ }
} return $query->fetch(PDO :: FETCH_ASSOC);
function getTripShape() { }
/* def handle_json_GET_tripstoptimes(self, params): function getTripStops($tripID) {
schedule = self.server.schedule global $conn;
try: $query = "SELECT stops.stop_id, stop_name, ST_AsKML(position) as positionkml,
trip = schedule.GetTrip(params.get('trip')) stop_sequence, trips.trip_id
except KeyError: FROM stop_times
# if a non-existent trip is searched for, the return nothing join trips on trips.trip_id = stop_times.trip_id
return join stops on stops.stop_id = stop_times.stop_id
time_stops = trip.GetTimeInterpolatedStops() WHERE trips.trip_id = :tripID ORDER BY stop_sequence";
stops = [] debug($query, "database");
times = [] $query = $conn->prepare($query);
for arr,ts,is_timingpoint in time_stops: $query->bindParam(":tripID", $tripID);
stops.append(StopToTuple(ts.stop)) $query->execute();
times.append(arr) if (!$query) {
return [stops, times] databaseError($conn->errorInfo());
  return Array();
def handle_json_GET_tripshape(self, params): }
schedule = self.server.schedule return $query->fetchAll();
try: }
trip = schedule.GetTrip(params.get('trip')) function getTripShape($tripID) {
except KeyError: // todo, use shapes table if shape_id specified
# if a non-existent trip is searched for, the return nothing global $conn;
return $query = "SELECT ST_AsKML(ST_MakeLine(geometry(a.shape_pt))) as the_route
points = [] FROM (SELECT shapes.shape_id,shape_pt from shapes
if trip.shape_id: inner join trips on shapes.shape_id = trips.shape_id
shape = schedule.GetShape(trip.shape_id) WHERE trips.trip_id = :tripID ORDER BY shape_pt_sequence) as a group by a.shape_id";
for (lat, lon, dist) in shape.points: debug($query, "database");
points.append((lat, lon)) $query = $conn->prepare($query);
else: $query->bindParam(":tripID", $tripID);
time_stops = trip.GetTimeStops() $query->execute();
for arr,dep,stop in time_stops: if (!$query) {
points.append((stop.stop_lat, stop.stop_lon)) databaseError($conn->errorInfo());
return points*/ return Array();
} }
function tripStopTimes($tripID, $after_time, $limit) { return $query->fetchColumn(0);
/* rv = [] }
   
stoptimes = self.GetStopTimes() function getTripStopTimes($tripID) {
# If there are no stoptimes [] is the correct return value but if the start global $conn;
# or end are missing times there is no correct return value. $query = "SELECT stop_times.trip_id,trip_headsign,arrival_time,stop_times.stop_id
if not stoptimes: ,stop_lat,stop_lon,stop_name,stop_desc,stop_code,
return [] stop_sequence,service_id,trips.route_id,route_short_name,route_long_name
if (stoptimes[0].GetTimeSecs() is None or FROM stop_times
stoptimes[-1].GetTimeSecs() is None): join trips on trips.trip_id = stop_times.trip_id
raise ValueError("%s must have time at first and last stop" % (self)) join routes on trips.route_id = routes.route_id
  join stops on stops.stop_id = stop_times.stop_id
cur_timepoint = None WHERE trips.trip_id = :tripID ORDER BY stop_sequence";
next_timepoint = None debug($query, "database");
distance_between_timepoints = 0 $query = $conn->prepare($query);
distance_traveled_between_timepoints = 0 $query->bindParam(":tripID", $tripID);
  $query->execute();
for i, st in enumerate(stoptimes): if (!$query) {
if st.GetTimeSecs() != None: databaseError($conn->errorInfo());
cur_timepoint = st return Array();
distance_between_timepoints = 0 }
distance_traveled_between_timepoints = 0 $stopTimes = $query->fetchAll();
if i + 1 < len(stoptimes): return $stopTimes;
k = i + 1 }
distance_between_timepoints += util.ApproximateDistanceBetweenStops(stoptimes[k-1].stop, stoptimes[k].stop)  
while stoptimes[k].GetTimeSecs() == None: function getTripAtStop($tripID, $stop_sequence) {
k += 1 global $conn;
distance_between_timepoints += util.ApproximateDistanceBetweenStops(stoptimes[k-1].stop, stoptimes[k].stop) foreach (getTripStopTimes($tripID) as $tripStop) {
next_timepoint = stoptimes[k] if ($tripStop['stop_sequence'] == $stop_sequence)
rv.append( (st.GetTimeSecs(), st, True) ) return $tripStop;
else: }
distance_traveled_between_timepoints += util.ApproximateDistanceBetweenStops(stoptimes[i-1].stop, st.stop) return Array();
distance_percent = distance_traveled_between_timepoints / distance_between_timepoints }
total_time = next_timepoint.GetTimeSecs() - cur_timepoint.GetTimeSecs()  
time_estimate = distance_percent * total_time + cur_timepoint.GetTimeSecs() function getTripStartTime($tripID) {
rv.append( (int(round(time_estimate)), st, False) ) global $conn;
  $query = "Select * from stop_times
return rv*/ where trip_id = :tripID
} AND arrival_time IS NOT NULL
  AND stop_sequence = '1'";
function tripStartTime($tripID) { debug($query, "database");
$query = 'SELECT arrival_secs,departure_secs FROM stop_times WHERE trip_id=? ORDER BY stop_sequence LIMIT 1'; $query = $conn->prepare($query);
  $query->bindParam(":tripID", $tripID);
} $query->execute();
  if (!$query) {
function viaPoints($tripid, $stopid, $timingPointsOnly = false) databaseError($conn->errorInfo());
{ return Array();
global $APIurl; }
$url = $APIurl . "/json/tripstoptimes?trip=" . $tripid; $r = $query->fetch(PDO :: FETCH_ASSOC);
$json = json_decode(getPage($url)); return $r['arrival_time'];
debug(print_r($json, true)); }
$stops = $json[0];  
$times = $json[1]; function getTripEndTime($tripID) {
$foundStop = false; global $conn;
$viaPoints = Array(); $query = "SELECT trip_id,max(arrival_time) as arrival_time from stop_times
foreach ($stops as $key => $row) { WHERE stop_times.arrival_time IS NOT NULL and trip_id = :tripID group by trip_id";
if ($foundStop) { debug($query, "database");
if (!$timingPointsOnly || !startsWith($row[5], "Wj")) { $query = $conn->prepare($query);
$viaPoints[] = Array( $query->bindParam(":tripID", $tripID);
"id" => $row[0], $query->execute();
"name" => $row[1], if (!$query) {
"time" => $times[$key] databaseError($conn->errorInfo());
); return Array();
} }
} $r = $query->fetch(PDO :: FETCH_ASSOC);
else { return $r['arrival_time'];
if ($row[0] == $stopid) $foundStop = true; }
} function getTripStartingPoint($tripID) {
} global $conn;
return $viaPoints; $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
function viaPointNames($tripid, $stopid) WHERE trip_id = :tripID and stop_sequence = '1' limit 1";
{ debug($query, "database");
$points = viaPoints($tripid, $stopid, true); $query = $conn->prepare($query);
$pointNames = Array(); $query->bindParam(":tripID", $tripID);
foreach ($points as $point) { $query->execute();
$pointNames[] = $point['name']; if (!$query) {
} databaseError($conn->errorInfo());
return implode(", ", $pointNames); return Array();
} }
?> $r = $query->fetch(PDO :: FETCH_ASSOC);
  return $r;
  }
   
  function getTripDestination($tripID) {
  global $conn;
  $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
  WHERE trip_id = :tripID order by stop_sequence desc limit 1";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":tripID", $tripID);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  $r = $query->fetch(PDO :: FETCH_ASSOC);
  return $r;
  }
   
  function getActiveTrips($time) {
  global $conn;
  if ($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
  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";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":time", $time);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  return $query->fetchAll();
  }
   
  function viaPoints($tripID, $stop_sequence = "") {
  global $conn;
  $query = "SELECT stops.stop_id, stop_name, arrival_time
  FROM stop_times join stops on stops.stop_id = stop_times.stop_id
  WHERE stop_times.trip_id = :tripID
  " . ($stop_sequence != "" ? " AND stop_sequence > :stop_sequence " : "") . " ORDER BY stop_sequence";
  debug($query, "database");
  $query = $conn->prepare($query);
  if ($stop_sequence != "")
  $query->bindParam(":stop_sequence", $stop_sequence);
  $query->bindParam(":tripID", $tripID);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  return $query->fetchAll();
  }