Account for bus stations in myway timeliness calculate
Account for bus stations in myway timeliness calculate

<?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 getRoute($routeID) { function getRoute($routeID) {
global $conn; global $conn;
$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");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeID", $routeID); $query->bindParam(":routeID", $routeID);
$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 getRoutesByShortName($routeShortName) { function getRoutesByShortName($routeShortName) {
global $conn; global $conn;
$query = "Select * from routes where route_short_name = :routeShortName"; $query = "Select distinct route_id, route_short_name from routes where route_short_name = :routeShortName";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeShortName", $routeShortName); $query->bindParam(":routeShortName", $routeShortName);
$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 getRouteHeadsigns($routeID) {
  global $conn;
  $query = "select distinct trip_headsign,direction_id from routes join trips on trips.route_id = routes.route_id
  join stop_times on stop_times.trip_id = trips.trip_id ";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":routeID", $routeID);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  return $query->fetchAll();
  }
   
function getRouteByFullName($routeFullName) { function getRouteByFullName($routeFullName) {
global $conn; global $conn;
$query = "Select * from routes where route_short_name||route_long_name = :routeFullName LIMIT 1"; $query = "Select * from routes where route_short_name||route_long_name = :routeFullName LIMIT 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeFullName", $routeFullName); $query->bindParam(":routeFullName", $routeFullName);
$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 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");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
return $query->fetchAll(); return $query->fetchAll();
} }
   
function 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 routes.route_id join stop_times on stop_times.trip_id = trips.trip_id
where route_short_name = :routeNumber OR route_short_name LIKE :routeNumber2 order by route_short_name;"; where route_short_name = :routeNumber OR route_short_name LIKE :routeNumber2 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");
$query = $conn->prepare($query); $query = $conn->prepare($query);
if ($routeNumber != "") { if ($routeNumber != "") {
$query->bindParam(":routeNumber", $routeNumber); $query->bindParam(":routeNumber", $routeNumber);
$routeNumber2 = "% " . $routeNumber; $routeNumber2 = "% " . $routeNumber;
$query->bindParam(":routeNumber2", $routeNumber2); $query->bindParam(":routeNumber2", $routeNumber2);
} }
$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 getRoutesByNumberSeries($routeNumberSeries = "") { function getRoutesByNumberSeries($routeNumberSeries = "") {
global $conn; global $conn;
if (strlen($routeNumberSeries) == 1) { if (strlen($routeNumberSeries) == 1) {
return getRoutesByNumber($routeNumberSeries); return getRoutesByNumber($routeNumberSeries);
} }
$seriesMin = substr($routeNumberSeries, 0, -1) . "0"; $seriesMin = substr($routeNumberSeries, 0, -1) . "0";
$seriesMax = substr($routeNumberSeries, 0, -1) . "9"; $seriesMax = substr($routeNumberSeries, 0, -1) . "9";
$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 to_number(route_short_name, 'FM999') between :seriesMin and :seriesMax OR route_short_name LIKE :routeNumberSeries order by route_short_name;"; routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where to_number(route_short_name, 'FM999') between :seriesMin and :seriesMax OR route_short_name LIKE :routeNumberSeries order by route_short_name;";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":seriesMin", $seriesMin); $query->bindParam(":seriesMin", $seriesMin);
$query->bindParam(":seriesMax", $seriesMax); $query->bindParam(":seriesMax", $seriesMax);
$routeNumberSeries = "% " . substr($routeNumberSeries, 0, -1) . "%"; $routeNumberSeries = "% " . substr($routeNumberSeries, 0, -1) . "%";
$query->bindParam(":routeNumberSeries", $routeNumberSeries); $query->bindParam(":routeNumberSeries", $routeNumberSeries);
$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 getRouteNextTrip($routeID) { function getRouteNextTrip($routeID) {
global $conn; 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 > :currentTime and routes.route_id = :routeID order by arrival_time > :currentTime and routes.route_id = :routeID order by
arrival_time limit 1"; arrival_time limit 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":currentTime", current_time()); $query->bindParam(":currentTime", current_time());
$query->bindParam(":routeID", $routeID); $query->bindParam(":routeID", $routeID);
$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);
   
// past last trip of the day special case // past last trip of the day special case
if (sizeof($r) < 16) { if (sizeof($r) < 16) {
$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 routes.route_id = :routeID order by join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID order by
arrival_time DESC limit 1"; arrival_time DESC limit 1";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeID", $routeID); $query->bindParam(":routeID", $routeID);
$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 getRouteAtStop($routeID, $stop_id) { function getRouteAtStop($routeID, $stop_id) {
$nextTrip = getRouteNextTrip($routeID); $nextTrip = getRouteNextTrip($routeID);
if ($nextTrip['trip_id']) { if ($nextTrip['trip_id']) {
foreach (getTripStopTimes($nextTrip['trip_id']) as $tripStop) { foreach (getTripStopTimes($nextTrip['trip_id']) as $tripStop) {
if ($tripStop['stop_id'] == $stop_id) if ($tripStop['stop_id'] == $stop_id)
return $tripStop; return $tripStop;
} }
} }
return Array(); return Array();
} }
   
function getRouteTrips($routeID) { function getRouteTrips($routeID) {
global $conn; global $conn;
$query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id $query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence 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 and stop_sequence = '1' order by join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID and stop_sequence = '1' order by
arrival_time "; arrival_time ";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":routeID", $routeID); $query->bindParam(":routeID", $routeID);
$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 getRoutesByDestination($destination = "", $service_period = "") { function getRoutesByDestination($destination = "", $service_period = "") {
global $conn; global $conn;
if ($service_period == "") if ($service_period == "")
$service_period = 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");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_period", $service_period); $query->bindParam(":service_period", $service_period);
if ($destination != "") if ($destination != "")
$query->bindParam(":destination", $destination); $query->bindParam(":destination", $destination);
$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 getRoutesBySuburb($suburb, $service_period = "") { function getRoutesBySuburb($suburb, $service_period = "") {
if ($service_period == "") if ($service_period == "")
$service_period = 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");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_period", $service_period); $query->bindParam(":service_period", $service_period);
$suburb = "%" . $suburb . ";%"; $suburb = "%" . $suburb . ";%";
$query->bindParam(":suburb", $suburb); $query->bindParam(":suburb", $suburb);
$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 getRoutesNearby($lat, $lng, $limit = "", $distance = 500) { function getRoutesNearby($lat, $lng, $limit = "", $distance = 500) {
if ($service_period == "") if ($service_period == "")
$service_period = service_period(); $service_period = service_period();
$service_ids = service_ids($service_period); $service_ids = service_ids($service_period);
$sidA = $service_ids[0]; $sidA = $service_ids[0];
$sidB = $service_ids[1]; $sidB = $service_ids[1];
if ($limit != "") if ($limit != "")
$limitSQL = " LIMIT :limit "; $limitSQL = " LIMIT :limit ";
global $conn; global $conn;
$query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id, $query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id,
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_periodA OR service_id=:service_periodB) WHERE (service_id=:service_periodA OR service_id=:service_periodB)
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 $limitSQL"; order by distance $limitSQL";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":service_periodA", $sidA); $query->bindParam(":service_periodA", $sidA);
$query->bindParam(":service_periodB", $sidB); $query->bindParam(":service_periodB", $sidB);
$query->bindParam(":distance", $distance); $query->bindParam(":distance", $distance);
if ($limit != "") if ($limit != "")
$query->bindParam(":limit", $limit); $query->bindParam(":limit", $limit);
$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.
*/ */
   
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 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.position))) as the_route $query = "SELECT ST_AsKML(ST_MakeLine(geometry(a.position))) as the_route
FROM (SELECT position, FROM (SELECT position,
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) as a group by a.trip_id"; WHERE trips.trip_id = :tripID ORDER BY stop_sequence) as a group by a.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();
} }
return $query->fetchColumn(0); return $query->fetchColumn(0);
} }
   
function getTripStopTimes($tripID) { function getTripStopTimes($tripID) {
global $conn; global $conn;
$query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_lat,stop_lon,stop_name,stop_code, $query = "SELECT stop_times.trip_id,trip_headsign,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 $range ORDER BY stop_sequence"; WHERE trips.trip_id = :tripID $range 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();
} }
   
/* DEPRECIATED  
function getTimeInterpolatedTrip($tripID, $range = "") {  
global $conn;  
$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  
FROM stop_times  
join trips on trips.trip_id = stop_times.trip_id  
join routes on trips.route_id = routes.route_id  
join stops on stops.stop_id = stop_times.stop_id  
WHERE trips.trip_id = :tripID $range ORDER BY stop_sequence";  
debug($query, "database");  
$query = $conn->prepare($query);  
$query->bindParam(":tripID", $tripID);  
$query->execute();  
if (!$query) {  
databaseError($conn->errorInfo());  
return Array();  
}  
$stopTimes = $query->fetchAll();  
$cur_timepoint = Array();  
$next_timepoint = Array();  
$distance_between_timepoints = 0.0;  
$distance_traveled_between_timepoints = 0.0;  
$rv = Array();  
foreach ($stopTimes as $i => $stopTime) {  
if ($stopTime['arrival_time'] != "") {  
// is timepoint  
$cur_timepoint = $stopTime;  
$distance_between_timepoints = 0.0;  
$distance_traveled_between_timepoints = 0.0;  
if ($i + 1 < sizeof($stopTimes)) {  
$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"]);  
while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) {  
$k += 1;  
// 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"]);  
}  
$next_timepoint = $stopTimes[$k];  
}  
$rv[] = $stopTime;  
} else {  
// is untimed point  
// 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"]);  
// echo "$distance_traveled_between_timepoints / $distance_between_timepoints<br>";  
$distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints;  
if ($next_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>";  
$time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]);  
$stopTime["arrival_time"] = date("H:i:s", $time_estimate);  
} else {  
$stopTime["arrival_time"] = $cur_timepoint["arrival_time"];  
}  
$rv[] = $stopTime;  
}  
}  
// var_dump($rv);  
return $rv;  
}  
   
function getTripPreviousTimePoint($tripID, $stop_sequence) {  
global $conn;  
$query = " SELECT trip_id,stop_id,  
stop_sequence  
FROM stop_times  
WHERE trip_id = :tripID and stop_sequence < :stop_sequence  
and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence DESC LIMIT 1";  
debug($query, "database");  
$query = $conn->prepare($query);  
$query->bindParam(":tripID", $tripID);  
$query->bindParam(":stop_sequence", $stop_sequence);  
$query->execute();  
if (!$query) {  
databaseError($conn->errorInfo());  
return Array();  
}  
return $query->fetch(PDO :: FETCH_ASSOC);  
}  
   
function getTripNextTimePoint($tripID, $stop_sequence) {  
global $conn;  
$query = " SELECT trip_id,stop_id,  
stop_sequence  
FROM stop_times  
WHERE trip_id = :tripID and stop_sequence > :stop_sequence  
and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence LIMIT 1";  
debug($query, "database");  
$query = $conn->prepare($query);  
$query->bindParam(":tripID", $tripID);  
$query->bindParam(":stop_sequence", $stop_sequence);  
$query->execute();  
if (!$query) {  
databaseError($conn->errorInfo());  
return Array();  
}  
return $query->fetch(PDO :: FETCH_ASSOC);  
}  
   
   
   
function getTimeInterpolatedTripAtStop($tripID, $stop_sequence) {  
global $conn;  
// limit interpolation to between nearest actual points.  
$prevTimePoint = getTripPreviousTimePoint($tripID, $stop_sequence);  
$nextTimePoint = getTripNextTimePoint($tripID, $stop_sequence);  
// echo " prev {$lowestDelta['stop_sequence']} next {$nextTimePoint['stop_sequence']} ";  
$range = "";  
if ($prevTimePoint != "")  
$range .= " AND stop_sequence >= '{$prevTimePoint['stop_sequence']}'";  
if ($nextTimePoint != "")  
$range .= " AND stop_sequence <= '{$nextTimePoint['stop_sequence']}'";  
foreach (getTimeInterpolatedTrip($tripID, $range) as $tripStop) {  
if ($tripStop['stop_sequence'] == $stop_sequence)  
return $tripStop;  
}  
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 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();
} }
   
function viaPointNames($tripid, $stop_sequence = "") { function viaPointNames($tripid, $stop_sequence = "") {
$viaPointNames = Array(); $viaPointNames = Array();
foreach (viaPoints($tripid, $stop_sequence) as $point) { foreach (viaPoints($tripid, $stop_sequence) as $point) {
$viaPointNames[] = $point['stop_name']; $viaPointNames[] = $point['stop_name'];
} }
if (sizeof($viaPointNames) > 0) { if (sizeof($viaPointNames) > 0) {
return r_implode(", ", $viaPointNames); return r_implode(", ", $viaPointNames);
} else { } else {
return ""; return "";
} }
} }
   
?> ?>
<?php <?php
   
/* /*
* Copyright 2010,2011 Alexander Sadleir * Copyright 2010,2011 Alexander Sadleir
   
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
   
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
   
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
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 ON myway_observations.myway_stop=myway_stops.myway_stop
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>";
if ($obsv["stop_id"] == "") {  
echo "error, stop '{$obsv['myway_stop']}' unknown";  
continue;  
}  
// 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']) - (30 * 60)); // 30 minutes margin $search_time = date("H:i:s", strtotime($obsv['time']) - (30 * 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));
  if (isset($obsv["stop_id"]) && $obsv["stop_id"] != "" ) {
$potentialStops = Array(getStop($obsv["stop_id"])); $potentialStops = Array(getStop($obsv["stop_id"]));
  } else {
  echo "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"])));
  }
//: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(preg_replace("/[A-Z]/", "", $obsv["myway_route"])); $potentialRoutes = getRoutesByShortName(preg_replace("/[A-Z]/", "", $obsv["myway_route"]));
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']}{$potentialRoute['route_long_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); $trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time);
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" => "{$potentialRoute['route_short_name']} {$potentialRoute['route_long_name']}", "route_name" => "{$potentialRoute['route_short_name']} {$potentialRoute['route_long_name']} {$trip['direction']}",
"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>";
} }
} }
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();
} }
   
<?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');
auth(); auth();
foreach ($_REQUEST as $key => $value) { foreach ($_REQUEST as $key => $value) {
if (strstr($key, "route") && !strstr($value, "Select")) { if (strstr($key, "route") && !strstr($value, "Select")) {
$myway_route = str_replace("route", "", $key); $myway_route = str_replace("route", "", $key);
$route_id = $value; $route_id = $value;
$query = "update myway_routes set route_id = :route_id where myway_route = :myway_route"; $query = "update myway_routes set route_id = :route_id where myway_route = :myway_route";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":myway_route", $myway_route, PDO::PARAM_STR, 5); $query->bindParam(":myway_route", $myway_route, PDO::PARAM_STR, 5);
$query->bindParam(":route_id", $route_id, PDO::PARAM_STR, 42); $query->bindParam(":route_id", $route_id, PDO::PARAM_STR, 42);
$query->execute(); $query->execute();
die(print_r($conn->errorInfo(), true)); die(print_r($conn->errorInfo(), true));
} }
if (strstr($key, "myway_stop")) { if (strstr($key, "myway_stop")) {
$myway_stop = $value; $myway_stop = $value;
$stop_id = $_REQUEST['stop_id']; $stop_id = $_REQUEST['stop_id'];
$query = "update myway_stops set stop_id = :stop_id where myway_stop = :myway_stop"; $query = "update myway_stops set stop_id = :stop_id where myway_stop = :myway_stop";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":myway_stop", $myway_stop, PDO::PARAM_STR, 25); $query->bindParam(":myway_stop", $myway_stop, PDO::PARAM_STR, 25);
$query->bindParam(":stop_id", $stop_id, PDO::PARAM_STR, 32); $query->bindParam(":stop_id", $stop_id, PDO::PARAM_STR, 32);
$query->execute(); $query->execute();
die(print_r($conn->errorInfo(), true)); die(print_r($conn->errorInfo(), true));
} }
} }
include_header("MyWay Data Reconcile", "mywayTimeRec"); include_header("MyWay Data Reconcile", "mywayTimeRec");
// initialise // initialise
$count = $conn->exec("insert into myway_stops $count = $conn->exec("insert into myway_stops
select distinct myway_stop from myway_observations select distinct myway_stop from myway_observations
WHERE myway_stop NOT IN WHERE myway_stop NOT IN
( (
SELECT myway_stop SELECT myway_stop
FROM myway_stops FROM myway_stops
)"); )");
echo "$count new stops.<br>"; echo "$count new stops.<br>";
if (!$count) { if (!$count) {
print_r($conn->errorInfo()); print_r($conn->errorInfo());
} }
$count = $conn->exec("insert into myway_routes select distinct myway_route from myway_observations $count = $conn->exec("insert into myway_routes select distinct myway_route from myway_observations
WHERE myway_route NOT IN WHERE myway_route NOT IN
( (
SELECT myway_route SELECT myway_route
FROM myway_routes FROM myway_routes
)"); )");
echo "$count new routes.<br>"; echo "$count new routes.<br>";
if (!$count) { if (!$count) {
print_r($conn->errorInfo()); print_r($conn->errorInfo());
} }
echo "<h2>Stops</h2>"; echo "<h2>Stops</h2>";
/* stops /* stops
search start of name, display map and table nuimbered, two text boxes */ search start of name, display map and table nuimbered, two text boxes */
$query = "Select * from myway_stops where stop_id is NUll;"; $query = "Select * from myway_stops where stop_id is NUll;";
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();
} }
foreach ($query->fetchAll() as $myway_stop) { foreach ($query->fetchAll() as $myway_stop) {
echo "<h3>{$myway_stop[0]}</h3>"; echo "<h3>{$myway_stop[0]}</h3>";
$markers = array(); $markers = array();
$stopKey = 0; $stopKey = 0;
$foundStops = getStops("",$myway_stop[0]); $foundStops = getStops("",$myway_stop[0]);
if (sizeof($foundStops) > 0) { if (sizeof($foundStops) > 0) {
echo "<table>"; echo "<table>";
foreach ($foundStops as $stopResult) { foreach ($foundStops as $stopResult) {
$markers[] = array( $markers[] = array(
$stopResult['stop_lat'], $stopResult['stop_lat'],
$stopResult['stop_lon'] $stopResult['stop_lon']
); );
echo "<tr><td>" . $stopKey++ . "</td><td>" . $stopResult['stop_name'] . "</td><td>" . $stopResult['stop_id'] . "</td></tr>"; echo "<tr><td>" . $stopKey++ . "</td><td>" . $stopResult['stop_name'] . "</td><td>" . $stopResult['stop_id'] . "</td></tr>";
} }
echo '</table>'; echo '</table>';
echo "" . staticmap($markers,false,false,false,true) . "<br>\n"; echo "" . staticmap($markers,false,false,false,true) . "<br>\n";
} }
echo '<form id="inputform' . md5($myway_stop[0]) . '"> echo '<form id="inputform' . md5($myway_stop[0]) . '">
<input type="hidden" name="myway_stop" value="' . $myway_stop[0] . '"> <input type="hidden" name="myway_stop" value="' . $myway_stop[0] . '">
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<label for="stop_id">Stop ID</label> <label for="stop_id">Stop ID</label>
<input type="text" name="stop_id" id="stop_id" value="' . $foundStops[0]['stop_id'] . '" /> <input type="text" name="stop_id" id="stop_id" value="' . $foundStops[0]['stop_id'] . '" />
</div> <input type="button" onclick="$.post(\'myway_timeliness_reconcile.php\', $(\'#inputform' . md5($myway_stop[0]) . '\').serialize())" value="Go!"></form> </div> <input type="button" onclick="$.post(\'myway_timeliness_reconcile.php\', $(\'#inputform' . md5($myway_stop[0]) . '\').serialize())" value="Go!"></form>
'; ';
echo '<hr>'; echo '<hr>';
} }
  echo '<h2>Routes</h2>';
  /* routes
  remove alpha char, search present dropdown */
  $query = "Select * from myway_routes where route_short_name is NUll;";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  foreach ($query->fetchAll() as $myway_route) {
  echo "<h3>{$myway_route[0]}</h3>";
  $query = "Select * from myway_observations where myway_route = :route order by time";
  debug($query, "database");
  $query = $conn->prepare($query);
  $query->bindParam(":route", $myway_route[0]);
  $query->execute();
  if (!$query) {
  databaseError($conn->errorInfo());
  return Array();
  }
  foreach ($query->fetchAll() as $myway_obvs) {
  echo $myway_obvs['myway_stop'] . $myway_obvs['time'] . "<br>";
  }
  $searchRouteNo = preg_replace("/[A-Z]/", "", $myway_route[0]);
  echo $searchRouteNo;
  echo '<form id="inputform' . $myway_route[0] . '">
  <select name="route' . $myway_route[0] . '" onchange=\'$.post("myway_timeliness_reconcile.php", $("#inputform' . $myway_route[0] . '").serialize())\'>
  <option>Select a from/to pair...</option>';
  foreach (getRoutesByShortName($searchRouteNo) as $routeResult) {
  foreach(getRouteHeadsigns($routeResult['route_id']) as $headsign ) {
  echo "<option value=\"{$routeResult['route_short_name']}{$routeResult['route_long_name']}\">
  {$routeResult['route_short_name']}{$routeResult['route_long_name']} {$headsign['trip_headsign']}</option>\n";
  }
   
  }
  echo "</select></form>";
  echo '<hr>';
  }
include_footer(); include_footer();
?> ?>