예제 #1
0
 public static function getRoutes(Agency $agency, $version = 0)
 {
     /**
      * @var DB
      */
     $dbObj = DBPool::getInstance();
     $version = $version == 0 ? TableUpdate::getVersion() : $version;
     $dbObj->bindParams(array($agency->getId(), $version));
     $routes = $dbObj->get_results("SELECT * FROM route WHERE agency_id=?\n            AND version = ? ORDER BY position");
     if ($dbObj->num_rows > 0) {
         $routeArray = array();
         foreach ($routes as $r) {
             $routeObj = new Route();
             $routeObj->setId($r->id);
             $routeObj->setAgency($agency);
             $routeObj->setTag($r->tag);
             $routeObj->setColor($r->color);
             $routeObj->setTitle($r->title);
             $routeObj->setShortTitle($r->short_title);
             $routeObj->setLatMin($r->lat_min);
             $routeObj->setLatMax($r->lat_max);
             $routeObj->setLonMin($r->lon_min);
             $routeObj->setLonMax($r->lon_max);
             $routeObj->setVehicleType($r->vehicle_type);
             $routeObj->setPosition($r->position);
             $routeArray[$r->tag] = $routeObj;
         }
         return $routeArray;
     } else {
         //TODO: Don't use a generic exception
         throw new Exception("No data available - Route::getRoutes");
     }
 }
예제 #2
0
 public static function getStops(Agency $agency, $version = 0)
 {
     /**
      * @var DB
      */
     $dbObj = DBPool::getInstance();
     $version = $version == 0 ? TableUpdate::getVersion() : $version;
     $dbObj->bindParams(array($agency->getId(), TableUpdate::getVersion()));
     $stops = $dbObj->get_results("SELECT * FROM stop WHERE agency_id=?\n            AND version = ?");
     if ($dbObj->num_rows > 0) {
         $stopArray = array();
         foreach ($stops as $s) {
             $stopObj = new Stop();
             $stopObj->setId($s->id);
             $stopObj->setAgency($agency);
             $stopObj->setFlipStopTag($s->flip_stop_tag);
             $stopObj->setTag($s->tag);
             $stopObj->setTitle($s->title);
             $stopObj->setPrettyTitle($s->pretty_title);
             $stopObj->setLatitude($s->latitude);
             $stopObj->setLongitude($s->longitude);
             $stopArray[$s->tag] = $stopObj;
         }
         return $stopArray;
     } else {
         //TODO: Don't use a generic exception
         throw new Exception("No data available - Stop::getStops");
     }
 }
 public static function getDirections(Route $route, $version = 0)
 {
     /**
      * @var DB
      */
     $dbObj = DBPool::getInstance();
     $version = $version == 0 ? TableUpdate::getVersion() : $version;
     $dbObj->bindParams(array($route->getId(), $version));
     $directions = $dbObj->get_results("SELECT * FROM direction WHERE route_id=?\n            AND version = ?");
     if ($dbObj->num_rows > 0) {
         $directionArray = array();
         foreach ($directions as $d) {
             $dirObj = new Direction();
             $dirObj->setId($d->id);
             $dirObj->setName($d->name);
             $dirObj->setPrettyName($d->pretty_name);
             $dirObj->setRoute($route);
             $dirObj->setTag($d->tag);
             $dirObj->setTitle($d->title);
             $dirObj->setPrettyTitle($d->pretty_title);
             $dirObj->setUseForUi($d->use_for_ui);
             $dirObj->setShow($d->show);
             $directionArray[$d->tag] = $dirObj;
         }
         return $directionArray;
     } else {
         //TODO: Don't use a generic exception
         throw new Exception("No data available - Direction::getDirections");
     }
 }
 /**
  *
  * @return Boolean - true if changes are present in the current version
  */
 public static function changesPresentInCurrentVersion()
 {
     $dbObj = DBPool::getInstance();
     $query = "SELECT changes_present FROM version WHERE id = " . TableUpdate::getVersion();
     if (true == $dbObj->get_var($query)) {
         return true;
     } else {
         return false;
     }
 }
function generateXMLFile(Agency $agencyObj)
{
    $dbObj = DBPool::getInstance();
    $routeArray = Route::getRoutes($agencyObj);
    $stopArray = Stop::getStops($agencyObj);
    $xmlStr = '<?xml version="1.0" encoding="UTF-8" ?><agency title="' . $agencyObj->getTitle() . '" shortTitle="' . $agencyObj->getShortTitle() . '"></agency>';
    $xml = new SimpleXMLElement($xmlStr);
    foreach ($stopArray as $s) {
        $stop = $xml->addChild("stop");
        $stop->addAttribute("tag", $s->getTag());
        $stop->addAttribute("title", $s->getPrettyTitle());
        $stop->addAttribute("lat", $s->getLatitude());
        $stop->addAttribute("lon", $s->getLongitude());
        $stop->addAttribute("oppositeStopTag", $s->getFlipStopTag());
    }
    foreach ($routeArray as $r) {
        $route = $xml->addChild("route");
        $route->addAttribute("tag", $r->getTag());
        $route->addAttribute("title", $r->getTitle());
        $route->addAttribute("shortTitle", $r->getShortTitle());
        $route->addAttribute("color", $r->getColor());
        $route->addAttribute("latMin", $r->getLatMin());
        $route->addAttribute("latMax", $r->getLatMax());
        $route->addAttribute("lonMin", $r->getLonMin());
        $route->addAttribute("lonMax", $r->getLonMax());
        $route->addAttribute("vehicle", $r->getVehicleType());
        $route->addAttribute("sortOrder", $r->getPosition());
        $directionsArray = Direction::getDirections($r);
        foreach ($directionsArray as $d) {
            $dir = $route->addChild("direction");
            $dir->addAttribute("tag", $d->getTag());
            $dir->addAttribute("title", $d->getPrettyTitle());
            $dir->addAttribute("name", $d->getPrettyName());
            $dir->addAttribute("show", $d->getShow() ? "true" : "false");
            $dir->addAttribute("useForUI", $d->getUseForUi() ? "true" : "false");
            $dbObj->bindParams(array($d->getId()));
            $stopDirMap = $dbObj->get_results("SELECT a.tag, b.position\n                                                FROM stop as a, stop_direction_map as b\n                                                WHERE a.id=b.stop_id AND b.direction_id=?\n                                                ORDER BY b.position");
            if ($dbObj->num_rows > 0) {
                foreach ($stopDirMap as $m) {
                    $map = $dir->addChild("stop");
                    $map->addAttribute("tag", $m->tag);
                }
            }
        }
    }
    $fileName = Util::getBaseDirectoryPath(Util::XML_FILE) . $agencyObj->getShortTitle() . ".xml";
    Util::prettyPrintXml($xml, $fileName);
}
예제 #6
0
 public static function getAgencies()
 {
     $dbObj = DBPool::getInstance();
     $agencies = $dbObj->get_results("SELECT * FROM agency");
     if ($dbObj->num_rows > 0) {
         $agencyArray = array();
         foreach ($agencies as $a) {
             $agencyObj = new Agency();
             $agencyObj->setId($a->id);
             $agencyObj->setTitle($a->title);
             $agencyObj->setShortTitle($a->short_title);
             $agencyObj->setDefaultVehicleType($a->default_vehicle);
             $agencyArray[$a->short_title] = $agencyObj;
         }
         return $agencyArray;
     } else {
         throw new Exception("There are no agencies in the database");
     }
 }
 public function updateStopDirMap()
 {
     /**
      * @var DB
      */
     $dbObj = DBPool::getInstance();
     $routeArray = Route::getRoutes($this->agency);
     $stopArray = Stop::getStops($this->agency);
     $bartApiKey = $this->appConfig['BART_API_KEY'];
     foreach ($routeArray as $routeTag => $routeObj) {
         $pos = 0;
         $directionArray = Direction::getDirections($routeObj);
         foreach ($directionArray as $dirTag => $dirObj) {
             //We're only interested in the directions we're showing
             if (!$dirObj->getShow()) {
                 continue;
             }
             //Fetch the direction details
             $apiURL = str_replace(BartApiEndPoints::DIRECTION, $dirObj->getTag(), BartApiEndPoints::ROUTE_INFO . $bartApiKey);
             $dirInfoXmlBuilder = new XmlObjBuilder($apiURL);
             $dirInfoXml = $dirInfoXmlBuilder->getXmlObj();
             foreach ($dirInfoXml->routes->route->config as $c) {
                 foreach ($c as $station) {
                     $pos++;
                     $stopTag = (string) $station;
                     $tempStopObj = $stopArray[$stopTag];
                     $stopId = $tempStopObj->getId();
                     $tempDirObj = $directionArray[$dirTag];
                     $dirId = $tempDirObj->getId();
                     $dbObj->bindParams(array($stopId, $dirId, $pos, TableUpdate::getVersion()));
                     $dbObj->query("INSERT INTO stop_direction_map\n                            (stop_id, direction_id, position, version, created_date)\n                            VALUES (?, ?, ?, ?, NOW())");
                     if ($dbObj->rows_affected != 1) {
                         //TODO: Log it
                     }
                 }
                 //Stations
             }
         }
         //Directions
     }
     //Routes
 }
function getRoutes(Agency $agency, $version)
{
    $dbObj = DBPool::getInstance();
    $routeArray = array();
    $finalRouteArray = array();
    //Get the routes
    $dbObj->bindParams(array($version, $agency->getId()));
    $routes = $dbObj->get_results("SELECT b.tag AS routetag, a.tag AS dirtag\n                                    FROM direction as a, route as b\n                                    WHERE a.route_id=b.id\n                                        AND a.use_for_ui=true\n                                        AND a.version=?\n                                        AND b.agency_id=?\n                                    ORDER BY b.tag;");
    if ($dbObj->num_rows > 0) {
        foreach ($routes as $r) {
            $routeTag = (string) $r->routetag;
            $routeArray[$routeTag][] = (string) $r->dirtag;
        }
        //Pick only the ones with more than 2 directions
        foreach ($routeArray as $routeTag => $dirs) {
            if (count($dirs) > 2) {
                $finalRouteArray[$routeTag] = $dirs;
            }
        }
    }
    return $finalRouteArray;
}
 public function updateStopDirMap()
 {
     /**
      * @var DB
      */
     $dbObj = DBPool::getInstance();
     $routeArray = Route::getRoutes($this->agency);
     $stopArray = Stop::getStops($this->agency);
     foreach ($this->xml->route as $r) {
         $routeTag = (string) $r['tag'];
         $routeObj = $routeArray[$routeTag];
         foreach ($r->direction as $d) {
             $pos = 0;
             $dirTag = (string) $d['tag'];
             $directionArray = Direction::getDirections($routeObj);
             $dirObj = $directionArray[$dirTag];
             //We're only interested in the directions we're showing
             //if (!$dirObj->getShow()) { continue; }
             foreach ($d->stop as $s) {
                 $pos++;
                 $stopTag = (string) $s['tag'];
                 $tempStop = $stopArray[$stopTag];
                 if (empty($tempStop)) {
                     var_dump("{$routeTag} {$stopTag}");
                 }
                 $stopId = $tempStop->getId();
                 $tempDir = $directionArray[$dirTag];
                 $dirId = $tempDir->getId();
                 $dbObj->bindParams(array($stopId, $dirId, $pos, TableUpdate::getVersion()));
                 $dbObj->query("INSERT INTO stop_direction_map\n                        (stop_id, direction_id, position, version, created_date)\n                        VALUES (?, ?, ?, ?, NOW())");
                 if ($dbObj->rows_affected != 1) {
                     //TODO: Log it
                 }
             }
         }
     }
 }
예제 #10
0
<?php

define("ROOT", "../");
require ROOT . 'www/common.php';
header("Content-Type: text/xml");
$dbObj = DBPool::getInstance();
$response = '<?xml version="1.0" encoding="UTF-8" ?>';
if (isset($_GET['v'])) {
    $version = $_GET['v'];
    if (!ctype_digit($version)) {
        exit;
    }
    $dbObj->bindParams(array($version));
    $versionDetails = $dbObj->get_row("SELECT id, created_date FROM version WHERE id=?");
} else {
    $versionDetails = $dbObj->get_row("SELECT id, created_date FROM version WHERE active=true");
}
if (null == $versionDetails) {
    $response .= '<error>Check if the version number is valid or if there is a live version in the database</error>';
} else {
    $response = '<update version="' . $versionDetails->id . '" resource="http://' . $_SERVER["HTTP_HOST"] . '/check.php" updateTime="' . strtotime($versionDetails->created_date) . '">
                    <data resource="http://' . $_SERVER["HTTP_HOST"] . '/data/xml/' . $versionDetails->id . '/data.zip" />
                    <images resource="http://' . $_SERVER["HTTP_HOST"] . '/data/images/' . $versionDetails->id . '/images.zip" />
                 </update>';
}
print $response;
function generateMapImages($version)
{
    require ROOT . 'lib/GoogleMaps.php';
    $dbObj = DBPool::getInstance();
    $versionClause = " AND version={$version}";
    $logger = Logger::getInstance();
    $zipFileContents = array();
    $basePathOrig = "./data/images/{$version}/orig_static_maps/";
    $basePathConverted = "./data/images/{$version}/";
    //If the images already exist, we're re-generating. Delete the existing images
    if (file_exists($basePathConverted)) {
        Util::deleteAll($basePathConverted);
    }
    //Constants
    define("LEFT_EDGE", 28);
    define("RIGHT_EDGE", 28);
    define("TOP_EDGE", 130);
    define("BOTTOM_EDGE", 10);
    define("MAP_SIZE_X", 320);
    define("MAP_SIZE_Y", 600);
    define("FOOTER_HEIGHT", 30);
    define("FINAL_MAP_SIZE_Y", 367);
    //NOTE: The co-ordinate system starts at the top left corner for the purposes of
    //these calculations
    define("MARKER_MIN_X", LEFT_EDGE);
    define("MARKER_MAX_X", MAP_SIZE_X - RIGHT_EDGE);
    define("MARKER_MIN_Y", TOP_EDGE);
    define("MARKER_MAX_Y", FINAL_MAP_SIZE_Y - BOTTOM_EDGE);
    define("BASE_ZOOM", 13);
    define("PATH_LINE_WEIGHT", 2);
    $agencyArray = Agency::getAgencies();
    $xmlStr = '<?xml version="1.0" encoding="UTF-8" ?><body></body>';
    $xml = new SimpleXMLElement($xmlStr);
    foreach ($agencyArray as $agencyTitle => $agencyObj) {
        //if("bart" == $agencyTitle || "actransit" == $agencyTitle) { continue; }
        if ("bart" == $agencyTitle) {
            continue;
        }
        //print $agencyTitle;
        $agencyNode = $xml->addChild("agency");
        $agencyNode->addAttribute("title", $agencyObj->getTitle());
        $agencyNode->addAttribute("shortTitle", $agencyObj->getShortTitle());
        //Get the routes
        $routeArray = Route::getRoutes($agencyObj);
        foreach ($routeArray as $routeTag => $routeObj) {
            //if("1" != $routeObj->getTag()) { continue; }
            $zoom = BASE_ZOOM;
            $routeNode = $agencyNode->addChild("route");
            $routeNode->addAttribute("tag", $routeObj->getTag());
            //Calculate the co-ordinates for the center of the map
            $lat_avg = ($routeObj->getLatMin() + $routeObj->getLatMax()) / 2;
            $lon_avg = ($routeObj->getLonMin() + $routeObj->getLonMax()) / 2;
            //Calculate center as pixel coordinates in world map
            $center_y = Google_Maps::LatToY($lat_avg);
            $center_x = Google_Maps::LonToX($lon_avg);
            //Calculate center as pixel coordinates in image
            $center_offset_x = round(MAP_SIZE_X / 2);
            $center_offset_y = round(MAP_SIZE_Y / 2);
            $SW_target_y = Google_Maps::LatToY($routeObj->getLatMin());
            $SW_target_x = Google_Maps::LonToX($routeObj->getLonMin());
            $NE_target_y = Google_Maps::LatToY($routeObj->getLatMax());
            $NE_target_x = Google_Maps::LonToX($routeObj->getLonMax());
            //Fetch the last stop for all the directions in this route (with show=true)
            //NOTE: I know, very inefficient
            $dbObj->bindParams(array($routeObj->getId()));
            $dirs = $dbObj->get_results("SELECT id, tag FROM direction WHERE \n                    route_id=? AND show=true {$versionClause}");
            //if($dbObj->num_rows == 0) { print "<br />$agencyTitle - ". $routeObj->getTag() . "<br />"; }
            while (true) {
                $SW_delta_x = $SW_target_x - $center_x >> 21 - $zoom;
                $SW_delta_y = $SW_target_y - $center_y >> 21 - $zoom;
                $SW_marker_x = $center_offset_x + $SW_delta_x;
                $SW_marker_y = $center_offset_y + $SW_delta_y;
                $NE_delta_x = $NE_target_x - $center_x >> 21 - $zoom;
                $NE_delta_y = $NE_target_y - $center_y >> 21 - $zoom;
                $NE_marker_x = $center_offset_x + $NE_delta_x;
                $NE_marker_y = $center_offset_y + $NE_delta_y;
                $SW_X_LIMIT = LEFT_EDGE;
                $SW_Y_LIMIT = MAP_SIZE_Y / 2 + round((FINAL_MAP_SIZE_Y - TOP_EDGE - BOTTOM_EDGE) / 2);
                $NE_X_LIMIT = MAP_SIZE_X - RIGHT_EDGE;
                $NE_Y_LIMIT = MAP_SIZE_Y / 2 - round((FINAL_MAP_SIZE_Y - TOP_EDGE - BOTTOM_EDGE) / 2);
                if ($SW_marker_x > $SW_X_LIMIT && $SW_marker_y < $SW_Y_LIMIT && $NE_marker_x < $NE_X_LIMIT && $NE_marker_y > $NE_Y_LIMIT) {
                    break;
                } else {
                    $zoom--;
                }
            }
            //This iteration is to determine the x and y co-ordinates with the final
            //calculated zoom
            $dirIds = array();
            $dirXYDetails = array();
            foreach ($dirs as $d) {
                $dbObj->bindParams(array($d->id));
                $stopDetails = $dbObj->get_row("SELECT * FROM stop WHERE id =\n                                                (SELECT stop_id FROM stop_direction_map\n                                                    WHERE direction_id = ? {$versionClause}\n                                                    ORDER BY position DESC LIMIT 1) {$versionClause}");
                $target_y = Google_Maps::LatToY($stopDetails->latitude);
                $target_x = Google_Maps::LonToX($stopDetails->longitude);
                $delta_x = $target_x - $center_x >> 21 - $zoom;
                $delta_y = $target_y - $center_y >> 21 - $zoom;
                $marker_x = $center_offset_x + $delta_x;
                $marker_y = $center_offset_y + $delta_y;
                //print "Route:".$routeObj->getTag()." | Direction: ".$d->tag." | zoom:".($zoom)." | x:$marker_x | y:$marker_y<br />";
                $dirXYDetails[$d->tag] = array('x' => $marker_x, 'y' => $marker_y);
                $dirIds[] = $d->id;
            }
            $routeNode->addAttribute("center", "{$lat_avg},{$lon_avg}");
            $routeNode->addAttribute("zoom", $zoom);
            //Get the path co-ordinates
            //We fetch the direction with the largest number of stops and draw a
            //path for that
            $dirWithStops = $dbObj->get_results("SELECT direction_id, COUNT(*) as stops\n                                                FROM stop_direction_map\n                                                WHERE direction_id IN (" . implode(",", $dirIds) . ") {$versionClause}\n                                                    GROUP BY direction_id\n                                                    ORDER BY stops DESC");
            //$dbObj->debug();
            $dirStopsArray = array();
            foreach ($dirWithStops as $dirStops) {
                $skipCondition = $dirStops->stops % 2 == 0 ? " AND mod(b.position, 2) = 0 " : " AND mod(b.position, 2) = 1 ";
                $stopsForPath = $dbObj->get_results("SELECT a.tag, b.position, a.latitude, a.longitude\n                                                        FROM stop AS a, stop_direction_map AS b\n                                                        WHERE a.id=b.stop_id AND a.id IN\n                                                            (SELECT stop_id\n                                                                FROM stop_direction_map\n                                                                WHERE direction_id = " . $dirStops->direction_id . " {$versionClause})\n                                                                AND b.direction_id = " . $dirStops->direction_id . $skipCondition . " AND a.version={$version}\n                                                                ORDER BY b.position DESC");
                //$dbObj->debug();exit;
                $pathArray = array();
                foreach ($stopsForPath as $sp) {
                    $pathArray[] = $sp->latitude . "," . $sp->longitude;
                }
                if ("actransit" == $agencyTitle) {
                    $pathColor = "0x008969";
                } elseif ("sf-muni" == $agencyTitle) {
                    $pathColor = "0xC74F3A";
                }
                $getParamStr = "path=weight:" . PATH_LINE_WEIGHT . "|" . getPathString($pathArray);
                $dirStopsArray[$dirStops->direction_id] = $getParamStr;
            }
            //Get the image from the Google Static Maps API
            $url = "http://maps.google.com/maps/api/staticmap?center={$lat_avg},{$lon_avg}&zoom={$zoom}&size=" . MAP_SIZE_X . "x" . MAP_SIZE_Y . "&maptype=roadmap&sensor=false&" . implode("&", $dirStopsArray);
            $pngImgFileName = $agencyTitle . "_" . $routeObj->getTag() . ".png";
            if (!file_exists($basePathOrig)) {
                //print $basePathOrig;exit;
                Util::createDir($basePathOrig);
            }
            $filePath = $basePathOrig . $pngImgFileName;
            //print "$url<br />$fileName<br /><br />";
            if (!copy($url, $filePath)) {
                $logStr = "Failed to copy {$fileName} \n";
                $logger->log($logStr, Logger::WARN, "IMAGE");
            }
            //Crop the image
            $intermediateImg_Y = MAP_SIZE_Y / 2 + round((FINAL_MAP_SIZE_Y - TOP_EDGE - BOTTOM_EDGE) / 2) + BOTTOM_EDGE;
            $intermediateImg = imagecreatetruecolor(MAP_SIZE_X, $intermediateImg_Y);
            list($current_width, $current_height) = getimagesize($filePath);
            if (!imagecopy($intermediateImg, imagecreatefrompng($filePath), 0, 0, 0, 0, $current_width, $current_height)) {
                $logStr = "Failed to crop and copy image [{$filePath}]";
                $logger->log($logStr, Logger::WARN, "IMAGE");
            }
            $fileName = $agencyTitle . "_" . $routeObj->getTag() . ".jpg";
            $newFilePath = $basePathConverted . $fileName;
            $startFromTop_Y = $intermediateImg_Y - FINAL_MAP_SIZE_Y;
            $newImage = imagecreatetruecolor(MAP_SIZE_X, FINAL_MAP_SIZE_Y);
            if (!imagecopy($newImage, $intermediateImg, 0, 0, 0, $startFromTop_Y, MAP_SIZE_X, FINAL_MAP_SIZE_Y)) {
                $logStr = "Failed to crop and copy image [{$newFilePath}]";
                $logger->log($logStr, Logger::WARN, "IMAGE");
            } else {
                imagejpeg($newImage, $newFilePath);
            }
            imagedestroy($newImage);
            imagedestroy($intermediateImg);
            //Add file name to zip file contents array
            $zipFileContents[] = $newFilePath;
            foreach ($dirXYDetails as $dirTag => $xyDetails) {
                $dirFinalY = $xyDetails['y'] - $startFromTop_Y;
                $dirNode = $routeNode->addChild("direction");
                $dirNode->addAttribute("tag", $dirTag);
                $dirNode->addAttribute("x", $xyDetails['x']);
                $dirNode->addAttribute("y", $dirFinalY);
            }
            $routeNode->addAttribute("yCropPixels", $startFromTop_Y);
            sleep(1);
            //if($cnt++ == 1) { break;}
        }
    }
    $fileName = Util::getBaseDirectoryPath(Util::IMAGE_FILE) . "map_overlay_coordinates.xml";
    Util::prettyPrintXml($xml, $fileName);
    //Create the zip file
    $zipFileContents[] = $fileName;
    Util::createZip($zipFileContents, getImagesPath(), true);
}
 public static function generate()
 {
     $dbObj = DBPool::getInstance();
 }
 private static function calculateLiveVersion()
 {
     $dbObj = DBPool::getInstance();
     $liveVersion = $dbObj->get_var("SELECT id FROM version WHERE active=true");
     TableUpdate::$liveVersion = (int) $liveVersion;
 }
 function __construct(Agency $agency)
 {
     $this->agency = $agency;
     $this->dbObj = DBPool::getInstance();
 }