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