Beispiel #1
0
 function execute($pid, $script)
 {
     $s = new Stop();
     $s->Execute($pid, $script);
     $s = new Start();
     $s->Execute($pid, $script);
 }
Beispiel #2
0
 protected function transformData($serverData)
 {
     $stops = array();
     //BEGIN: O 20:29 +8'&nbsp;<a.*? >(.*?)</a><br>
     //NORMAL: | 20:50 +9'&nbsp;<a href="/mobile/SearchStation.aspx?l=NL&s=1&sid=1265&tr=20:45-60&da=D&p=2">Zele</a><br>
     //AT: =&gt;22:01&nbsp;<a href="/mobile/SearchStation.aspx?l=NL&s=1&sid=318&tr=22:00-60&da=D&p=2">Denderleeuw</a></font><br>
     //END: O 23:28&nbsp;<a href="/mobile/SearchStation.aspx?l=NL&s=1&sid=973&tr=23:15-60&da=D&p=2">Poperinge</a><br>
     preg_match_all("/(\\d\\d:\\d\\d)( \\+(\\d\\d?)')?&nbsp;<a href=\"\\/mobile\\/SearchStation.*?>(.*?)<\\/a>/smi", $serverData, $matches);
     $delays = $matches[3];
     $times = $matches[0];
     $stationnames = $matches[4];
     $i = 0;
     foreach ($stationnames as $st) {
         if (isset($delays[$i])) {
             $delay = $delays[$i] * 60;
         } else {
             $delay = 0;
         }
         $time = Input::transformTime("00d" . $times[$i] . ":00", date("Ymd"));
         $stops[$i] = new Stop(parent::getStation($st), $delay, $time);
         $i++;
     }
     preg_match("/=&gt;(\\d\\d:\\d\\d)( \\+(\\d\\d?)')?&nbsp;<a href=\"\\/mobile\\/SearchStation.*? >(.*?)<\\/a>/smi", $serverData, $matches);
     if (isset($matches[4])) {
         $now = new Stop($matches[4], "1", "1");
         $locationX = $now->getStation()->getX();
         $locationY = $now->getStation()->getY();
     } else {
         $locationX = 0;
         $locationY = 0;
     }
     return new Route($stops, $locationX, $locationY, $this->request->getVehicleId());
 }
 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");
     }
 }
Beispiel #4
0
 public static function createFromXml(\SimpleXMLElement $xml, \DateTime $date, $isArrival, Prognosis $obj = null)
 {
     if (!$obj) {
         $obj = new Prognosis();
     }
     if ($isArrival) {
         if ($xml->Arr) {
             if ($xml->Arr->Platform) {
                 $obj->platform = (string) $xml->Arr->Platform->Text;
             }
             if ($xml->Arr->Time) {
                 $obj->arrival = Stop::calculateDateTime((string) $xml->Arr->Time, $date)->format(\DateTime::ISO8601);
             }
         }
     } else {
         if ($xml->Dep) {
             if ($xml->Dep->Platform) {
                 $obj->platform = (string) $xml->Dep->Platform->Text;
             }
             if ($xml->Dep->Time) {
                 $obj->departure = Stop::calculateDateTime((string) $xml->Dep->Time, $date)->format(\DateTime::ISO8601);
             }
         }
     }
     if ($xml->Capacity1st) {
         $obj->capacity1st = (int) $xml->Capacity1st;
     }
     if ($xml->Capacity2nd) {
         $obj->capacity2nd = (int) $xml->Capacity2nd;
     }
     return $obj;
 }
 /**
  * @param   \SimpleXMLElement   $xml
  * @param   string              $date   The date that will be assigned to this journey
  * @param   Journey             $obj    An optional existing journey to overwrite
  * @return  Journey
  */
 public static function createFromXml(\SimpleXMLElement $xml, \DateTime $date, Journey $obj = null)
 {
     if (!$obj) {
         $obj = new StationBoardJourney();
     }
     $obj = Journey::createFromXml($xml, $date, $obj);
     $obj->stop = Stop::createFromXml($xml->MainStop->BasicStop, $date, null);
     return $obj;
 }
 protected function dataUpdated(Stop $o, Stop $n)
 {
     $changes = array();
     if ($o->getFlipStopTag() != $n->getFlipStopTag()) {
         $changes["flip stop tag"] = $o->getFlipStopTag() . " | " . $n->getFlipStopTag();
     }
     if ($o->getTitle() != $n->getTitle()) {
         $changes["title"] = $o->getTitle() . " | " . $n->getTitle();
     }
     if ($o->getLatitude() != $n->getLatitude()) {
         $changes["latitude"] = $o->getLatitude() . " | " . $n->getLatitude();
     }
     if ($o->getLongitude() != $n->getLongitude()) {
         $changes["longitude"] = $o->getLongitude() . " | " . $n->getLongitude();
     }
     return $changes;
 }
 /**
  * @param \SimpleXMLElement   $xml
  * @param \DateTime           $date The date that will be assigned to this journey
  * @param StationBoardJourney $obj  An optional existing journey to overwrite
  *
  * @return StationBoardJourney
  */
 public static function createStationBoardFromXml(\SimpleXMLElement $xml, \DateTime $date, StationBoardJourney $obj = null)
 {
     if (!$obj) {
         $obj = new self();
     }
     $stop = Stop::createFromXml($xml->MainStop->BasicStop, $date, null);
     // use resolved date from main stop
     $date = new \DateTime($stop->departure);
     /* @var $obj StationBoardJourney */
     $obj = Journey::createFromXml($xml, $date, $obj);
     $obj->stop = $stop;
     return $obj;
 }
function importRouteStops()
{
    include_once "../public_html/apps/routecoorddistances.php";
    $url = "http://shuttles.rpi.edu/displays/netlink.js";
    $data = json_decode(getUrl($url));
    //print_ar($data);exit;
    foreach ($data as $type => $datum) {
        switch ($type) {
            case 'stops':
                foreach ($datum as $stop) {
                    /* update 'stops' table */
                    if ($stop->short_name) {
                        if (Stop::get($stop->short_name)) {
                            Stop::update($stop->short_name, $stop);
                        } else {
                            Stop::insert($stop);
                        }
                    }
                    foreach ($stop->routes as $stop_route) {
                        /* update 'stop_routes' table */
                        if (!StopRoute::get($stop->short_name, $stop_route->id)) {
                            StopRoute::insert($stop->short_name, $stop_route->id);
                        }
                    }
                }
                break;
            case 'routes':
                foreach ($datum as $route) {
                    /* update 'route' table */
                    if (Route::get($route->id)) {
                        Route::update($route->id, $route);
                    } else {
                        Route::insert($route->id, $route);
                    }
                    if ($route->coords) {
                        RouteCoords::delete($route->id);
                        /* delete all coords for route */
                        $seq = 0;
                        foreach ($route->coords as $route_coord) {
                            /* update 'route_coords' table */
                            RouteCoords::insert($route->id, $seq, $route_coord);
                            $seq++;
                        }
                    }
                }
                break;
        }
    }
    RouteCoordDistances::loadDistanceTable();
}
 /**
  * get list of stops based on location
  *
  * @param  int  $location_id
  * @return Response
  */
 public function getByLocation($location_id)
 {
     if ($location_id) {
         // get all stops based on the condition
         $stops = Stop::LocationId($location_id)->get();
     } else {
         // get all
         $stops = Stop::get();
     }
     if ($stops->count()) {
         echo json_encode($stops);
     } else {
         echo json_encode(array());
     }
 }
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);
}
 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
 }
 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
                 }
             }
         }
     }
 }
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', function () {
    $stops = Stop::orderBy('name')->get(array('name', 'id'));
    return View::make('hello')->with(array('stops' => $stops));
});
Route::get('/stop/{id}', function ($id) {
    $stop = Stop::find($id);
    $sum = 0;
    $max = 5;
    if ($stop) {
        $buses = $stop->buses;
        foreach ($buses as $bus) {
            $weekend = date('N', strtotime(date('now'))) >= 6;
            $now = new DateTime('now');
            $timetables = $bus->timetables;
            foreach ($timetables as $timetable) {
                if ($sum == $max) {
                    break;
                }
                $bus_time = new DateTime($timetable->time);
                if ($bus_time > $now) {
                    if ($weekend && $timetable->type == 'working_day') {
Beispiel #14
0
 public static function createFromXml(\SimpleXMLElement $xml, \DateTime $date, Journey $obj = null)
 {
     if (!$obj) {
         $obj = new self();
     }
     // TODO: get attributes
     if ($xml->JourneyAttributeList) {
         foreach ($xml->JourneyAttributeList->JourneyAttribute as $journeyAttribute) {
             switch ($journeyAttribute->Attribute['type']) {
                 case 'NAME':
                     $obj->name = (string) $journeyAttribute->Attribute->AttributeVariant->Text;
                     break;
                 case 'CATEGORY':
                     $obj->category = (string) $journeyAttribute->Attribute->AttributeVariant->Text;
                     $obj->categoryCode = (int) $journeyAttribute->Attribute['code'];
                     break;
                 case 'INTERNALCATEGORY':
                     $obj->subcategory = (string) $journeyAttribute->Attribute->AttributeVariant->Text;
                     break;
                 case 'LINE':
                     $line = (string) $journeyAttribute->Attribute->AttributeVariant->Text;
                     if ($line && !$obj->number) {
                         $obj->number = $line;
                     }
                     break;
                 case 'NUMBER':
                     $number = (string) $journeyAttribute->Attribute->AttributeVariant->Text;
                     if ($number && !$obj->number) {
                         $obj->number = $number;
                     }
                     break;
                 case 'OPERATOR':
                     foreach ($journeyAttribute->Attribute->AttributeVariant as $journeyAttributeVariant) {
                         if ($journeyAttributeVariant['type'] == 'NORMAL') {
                             $obj->operator = (string) $journeyAttributeVariant->Text;
                         }
                     }
                     break;
                 case 'DIRECTION':
                     $obj->to = (string) $journeyAttribute->Attribute->AttributeVariant->Text;
                     break;
             }
         }
     }
     $capacities1st = [];
     $capacities2nd = [];
     if ($xml->PassList->BasicStop) {
         foreach ($xml->PassList->BasicStop as $basicStop) {
             if ($basicStop->Arr || $basicStop->Dep) {
                 $stop = Stop::createFromXml($basicStop, $date, null);
                 if ($stop->prognosis->capacity1st) {
                     $capacities1st[] = (int) $stop->prognosis->capacity1st;
                 }
                 if ($stop->prognosis->capacity2nd) {
                     $capacities2nd[] = (int) $stop->prognosis->capacity2nd;
                 }
                 $obj->passList[] = $stop;
             }
         }
     }
     if (count($capacities1st) > 0) {
         $obj->capacity1st = max($capacities1st);
     }
     if (count($capacities2nd) > 0) {
         $obj->capacity2nd = max($capacities2nd);
     }
     return $obj;
 }
Beispiel #15
0
    $limit = 5;
    // default;
    $time = time();
    // show stuff just passed also just in case it turns out to be useful; 5 minutes
    if (date('H') < 5) {
        $time = mktime(23, 58, 0, date('m'), date('d') - 1, date('Y'));
    }
}
// full lists of stops in both directions
//$inbound_stop_ids = array(3148, 3149, 3150, 3151, 3152, 3153, 3154, 3631, 2780, 2515, 2781, 2782, 2783, 3620, 2785);
//$outbound_stop_ids = array(3621, 3619, 2673, 2674, 2675, 2676, 2515, 2677, 3589, 3155, 3156, 3157, 3158, 3159, 3160, 3161);
// truncated lists, skipping a few
$inbound_stop_ids = array(3148, 3149, 3150, 3151, 3152, 3153, 3154, 2515, 2781, 2782, 3620);
$outbound_stop_ids = array(3619, 2673, 2675, 2676, 2515, 2677, 3155, 3156, 3158, 3159, 3161);
$inbound_stops = Stop::CreateStopsFromList($inbound_stop_ids);
$outbound_stops = Stop::CreateStopsFromList($outbound_stop_ids);
$routes = array(new Route(12), new Route(29));
$inbound_trips = Trip::GetTrips($routes, $inbound_stops, '0', $limit, $time);
$inbound_times = Trip::GetStopTimesForTrips($inbound_trips, $inbound_stops);
uasort($inbound_times, 'TripTimeComparer');
// TODO: when we are displaying a day's last trip + some morning trips, we want to treat the 24:48:00 differently than we
// treat a day's list with the last trip wrapping over. Currently the last trip(s) are sorting to the end, which is highly
// undesired. We do however need the sort for merging the two routes' schedules during weekdays.
// Some thoughts: 1) other than the route merge, sorting seems to be handled by the database. This may however be implicit
// by trip_id, which is not the safest. See if we can sort in SQL. (Still a problem since evening+morning come from two separate
// SQL queries, but we can just sort inside GetTrips in that case.) 2) if not, incorporate some sort of day/timestamp identity
// to each stoptime returned. This is somewhat absurd, as we'd probably need full timestamp to avoid problems wrapping
// over ends of service periods, months, years, etc.
// Currently leaving unsolved -- ~qviri, 2009.02.22
$outbound_trips = Trip::GetTrips($routes, $outbound_stops, '1', $limit, $time);
$outbound_times = Trip::GetStopTimesForTrips($outbound_trips, $outbound_stops);
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function show($id)
 {
     $data = Stop::all();
     return response()->json(json_encode($data));
 }
 /**
  * Create stop
  *
  * @var $stop string
  * @return object
  */
 protected function create_stop($stop)
 {
     $stop = new Stop(array('name' => $stop));
     $stop->save();
     return $stop;
 }
 public function produceTimetable($stop, $forceLive = NULL)
 {
     // Check for stop existence
     $stopData = Stop::select(DB::raw('*, ST_AsText(location) AS location'))->where('id', '=', $stop)->get();
     $plannedData = FALSE;
     if ($stopData->isEmpty()) {
         return View::make('timetable')->withTitle('Timetable')->withError('Invalid stop entered');
     } else {
         $stopData = Stop::select(DB::raw('*, ST_AsText(location) AS location'))->where('id', '=', $stop)->get();
         $coords = explode(' ', $stopData[0]['location']);
         $stopData[0]['lon'] = filter_var($coords[0], FILTER_SANITIZE_NUMBER_FLOAT, ['flags' => FILTER_FLAG_ALLOW_FRACTION]);
         $stopData[0]['lat'] = filter_var($coords[1], FILTER_SANITIZE_NUMBER_FLOAT, ['flags' => FILTER_FLAG_ALLOW_FRACTION]);
     }
     if (Redis::exists($stop)) {
         $timedata = json_decode(Redis::get($stop), TRUE);
         $creditMessage = 'Retrieved from cache. Public sector information from Traveline licensed under the Open Government Licence v2.0.';
     } else {
         if (Session::has('foreign')) {
             return Redirect::to('/regionblock');
         } else {
             // Determine the data provider to use
             if (isset($forceLive)) {
                 $timedata = TimetableController::getNationalData($stop);
                 $creditMessage = 'Retrieved from live data per user request. Public sector information from Traveline licensed under the Open Government Licence v2.0.';
             } else {
                 if (substr($stop, 0, 3) === '180') {
                     $timedata = TimetableController::getManchesterData($stop);
                     $creditMessage = 'Retrieved from planned timetables and may not take into account sudden service changes. Public sector information from Transport for Greater Manchester. Contains Ordnance Survey data &copy; Crown copyright and database rights 2014';
                     $plannedData = TRUE;
                 } else {
                     if (substr($stop, 0, 3) === '490') {
                         $timedata = TimetableController::getLondonData($stop);
                         $creditMessage = 'Retrieved from live data. Data provided by Transport for London';
                     } else {
                         $timedata = TimetableController::getNationalData($stop);
                         $creditMessage = 'Retrieved from live data. Public sector information from Traveline licensed under the Open Government Licence v2.0.';
                     }
                 }
             }
         }
     }
     // Extract the location info
     if ($timedata === FALSE) {
         return View::make('timetable')->withTitle('Timetable')->withScheduled($plannedData)->withStop($stopData)->withError('No services found at this stop.');
     } else {
         return View::make('timetable')->withTimetable($timedata)->withScheduled($plannedData)->withStop($stopData)->withTitle('Timetable')->withCredit($creditMessage);
     }
 }
 public function updateStops()
 {
     $routeArray = Route::getRoutes($this->agency);
     $stopArray = array();
     //Final list of Stop objects
     $bartApiKey = $this->appConfig['BART_API_KEY'];
     //Platform mapping
     $xmlStr = '<?xml version="1.0"?><agency title="BART" shortTitle="bart"></agency>';
     $platformXml = new SimpleXMLElement($xmlStr);
     foreach ($this->xml->stations->station as $s) {
         $stationTag = (string) $s->abbr;
         //Fetch the station details
         $apiURL = str_replace(BartApiEndPoints::ORIG, $stationTag, BartApiEndPoints::STATION_INFO . $bartApiKey);
         $stationInfoXmlBuilder = new XmlObjBuilder($apiURL);
         $stationInfoXml = $stationInfoXmlBuilder->getXmlObj();
         $stopObj = new Stop();
         $stopObj->setAgency($this->agency);
         $stopObj->setTag($stationTag);
         $stopObj->setTitle((string) $stationInfoXml->stations->station->name);
         $stopObj->setLatitude((string) $stationInfoXml->stations->station->gtfs_latitude);
         $stopObj->setLongitude((string) $stationInfoXml->stations->station->gtfs_longitude);
         $stopArray[$stationTag] = $stopObj;
         /************* Add to platform XML object ****************/
         //Add stop node
         $stopNode = $platformXml->addChild("stop");
         $stopNode->addAttribute("tag", $stationTag);
         //Add platform node as a child of the stop node (north)
         $platformNode = $stopNode->addChild("platform");
         $northPlatforms = array();
         foreach ($stationInfoXml->stations->station->north_platforms as $p) {
             foreach ($p as $pNum) {
                 $northPlatforms[] = trim((string) $pNum);
             }
         }
         $platformNode->addAttribute("number", implode(",", $northPlatforms));
         //Add directions as a children of the platform node
         foreach ($stationInfoXml->stations->station->north_routes as $r) {
             foreach ($r->route as $direction) {
                 $dirStr = trim((string) $direction);
                 $dirTagArray = explode(" ", $dirStr);
                 $dirTag = $dirTagArray[1];
                 $platformNode->addChild("direction", $dirTag);
             }
         }
         //Add platform node as a child of the stop node (south)
         $platformNode = $stopNode->addChild("platform");
         $southPlatforms = array();
         foreach ($stationInfoXml->stations->station->south_platforms as $p) {
             foreach ($p as $pNum) {
                 $southPlatforms[] = trim((string) $pNum);
             }
         }
         $platformNode->addAttribute("number", implode(",", $southPlatforms));
         //Add directions as a children of the platform node
         foreach ($stationInfoXml->stations->station->south_routes as $r) {
             foreach ($r as $direction) {
                 $dirStr = trim((string) $direction);
                 $dirTagArray = explode(" ", $dirStr);
                 $dirTag = $dirTagArray[1];
                 $platformNode->addChild("direction", $dirTag);
             }
         }
     }
     //Write platform mapping XML to file
     $fileName = Util::getBaseDirectoryPath(Util::XML_FILE) . "bart-platforms.xml";
     Util::prettyPrintXml($platformXml, $fileName);
     //Write the stops to the database
     try {
         //Pass it to the base RouteUpdate class
         $stopUpdate = new StopUpdate($this->agency, $stopArray);
         $stopUpdate->updateDB();
     } catch (Exception $ex) {
         throw new Exception($ex->getMessage());
     }
 }
 public function updateStops()
 {
     $routeArray = Route::getRoutes($this->agency);
     $flipStopMap = $this->getFlipStopOverrides();
     $stopTitleMap = array();
     $stopLatLonMap = array();
     $uniqueStopsAcrossRoutes = array();
     //Generate maps of stopTag => StopTitle and stopTag => [lat, lon] for
     //later look up
     foreach ($this->xml->route as $r) {
         foreach ($r->stop as $s) {
             $stopTag = (string) $s['tag'];
             $stopTitle = html_entity_decode((string) $s['title']);
             $lat = (string) $s['lat'];
             $lon = (string) $s['lon'];
             $stopTitleMap[$stopTag] = $stopTitle;
             $stopLatLonMap[$stopTag] = array("lat" => $lat, "lon" => $lon);
             $uniqueStopsAcrossRoutes[] = $stopTag;
         }
         //Stops
     }
     //Routes
     //We'll only consider the stops in the directions with show=true
     foreach ($this->xml->route as $r) {
         $routeTag = (string) $r['tag'];
         //if($routeTag != "25") {continue;}
         $routeObj = $routeArray[$routeTag];
         $dirArray = Direction::getDirections($routeObj);
         $agencyName = $routeObj->getAgency()->getShortTitle();
         $trackDuplicatesInDir = array();
         /**
          * @var Array $routeDirDetails - Array representation of the
          * directions and stops in a route
          */
         $routeDirDetails = array();
         foreach ($r->direction as $d) {
             $dirTag = (string) $d['tag'];
             $dirObj = $dirArray[$dirTag];
             $dirStops = array();
             //if ($dirObj->getShow()) {
             foreach ($d->stop as $s) {
                 $stopTag = (string) $s['tag'];
                 $stopTitle = $stopTitleMap[$stopTag];
                 $dirStops[$stopTag] = $stopTitle;
             }
             //Stops
             $routeDirDetails[$dirObj->getTag()] = $dirStops;
             //} //Check for show=true
         }
         //Directions
         //Now that we have the details of the directions for this group,
         //let's find the flip stops
         foreach ($routeDirDetails as $fDirTag => $fDirStops) {
             foreach ($routeDirDetails as $fDirTagDiffDir => $fDirStopsDiffDir) {
                 if ($fDirTag == $fDirTagDiffDir) {
                     continue;
                 }
                 foreach ($fDirStops as $fStopTag => $fStopTitle) {
                     //Check if we have one or more matching flip stops in the
                     //direction we are checking against
                     $fFlipStopInOppDir = $this->getFlipStopsInOppDir($fStopTag, $fStopTitle, $fDirStopsDiffDir);
                     //If we don't have any flip stops continue to the next stop
                     if (count($fFlipStopInOppDir) == 0) {
                         continue;
                     }
                     if (count($fFlipStopInOppDir) > 1) {
                         //We have encountered more than one stop at the
                         //same intersection in a different direction
                         //TODO: This has to go in the e-mail report
                         //Generate the (stopTag, lat, lon) string
                         $fstopLatLonMap = array();
                         $fstopLatLonMap[] = "{$fStopTag}," . implode(",", $stopLatLonMap[$fStopTag]);
                         foreach ($fFlipStopInOppDir as $tempStopForOppDir) {
                             $fstopLatLonMap[] = "{$tempStopForOppDir}," . implode(",", $stopLatLonMap[$tempStopForOppDir]);
                         }
                         $logStr = "More than one stop in diff. direction [agency: " . $agencyName . "] [route: " . $routeTag . "] [current stop|dir: {$fStopTag}|{$fDirTag}] [other stops|dir: " . implode(",", $fFlipStopInOppDir) . "|{$fDirTagDiffDir}] [stop title: " . $fStopTitle . "] [" . implode("|", $fstopLatLonMap) . "]";
                         //$this->logger->log($logStr, Logger::WARN, NxtbusStop::PACKAGE);
                     } else {
                         if (!array_key_exists($fStopTag, $flipStopMap)) {
                             $tempFlipStopTag = $fFlipStopInOppDir[0];
                             $flipStopMap[$fStopTag] = $tempFlipStopTag;
                             $flipStopMap[$tempFlipStopTag] = $fStopTag;
                         }
                     }
                 }
             }
             // Inner loop
         }
         //Find flip stops
     }
     //Routes
     //Check if any of the stops don't have a flip stop
     $uniqueStopsAcrossRoutes = array_unique($uniqueStopsAcrossRoutes);
     foreach ($uniqueStopsAcrossRoutes as $finalCheckStopTag) {
         if (!array_key_exists($finalCheckStopTag, $flipStopMap)) {
             $flipStopMap[$finalCheckStopTag] = "";
         }
     }
     //Create the Stop objects
     $stopArray = array();
     foreach ($this->xml->route as $r) {
         foreach ($r->stop as $s) {
             $stopTag = (string) $s['tag'];
             $stopTitle = html_entity_decode($s['title']);
             if (array_key_exists($stopTag, $flipStopMap) && !array_key_exists($stopTag, $stopArray)) {
                 $stopObj = new Stop();
                 $stopObj->setAgency($this->agency);
                 $stopObj->setTag($stopTag);
                 $stopObj->setTitle((string) $stopTitle);
                 $stopObj->setFlipStopTag($flipStopMap[$stopTag]);
                 $stopObj->setLatitude((string) $s['lat']);
                 $stopObj->setLongitude((string) $s['lon']);
                 $stopArray[$stopTag] = $stopObj;
             }
         }
         //Stops
     }
     //Routes
     try {
         //Pass it to the base RouteUpdate class
         $stopUpdate = new StopUpdate($this->agency, $stopArray);
         $stopUpdate->updateDB();
     } catch (Exception $ex) {
         throw new Exception($ex->getMessage());
     }
 }
Beispiel #21
0
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', function () {
    return View::make('homepage', ['title' => 'Home']);
});
Route::get('/location/', function () {
    if (Input::has('lat') && Input::has('lon')) {
        return Redirect::to('/location/' . Input::get('lat') . '/' . Input::get('lon'));
    } else {
        return Redirect::to('/')->withMessage('An error occurred.');
    }
});
Route::get('/location/{lat}/{lon}', array('as' => 'location', function ($lat, $lon) {
    $stops = Stop::select(DB::raw('*, ST_AsText(location) AS location'))->where('inuse', '=', true)->whereRaw('ST_DWithin(location, ST_GeographyFromText(\'SRID=4326;POINT(' . floatval($lon) . ' ' . floatval($lat) . ')\'), 1000)')->orderByRaw('ST_Distance(location, ST_GeographyFromText(\'SRID=4326;POINT(' . floatval($lon) . ' ' . floatval($lat) . ')\'))')->limit(10)->get();
    if (!$stops->isEmpty()) {
        $colours = array("black", "brown", "green", "purple", "yellow", "blue", "gray", "orange", "red", "white");
        $letter = "A";
        foreach ($stops as &$stop) {
            $stop['colour'] = current($colours);
            $stop['letter'] = $letter;
            $letter++;
            next($colours);
            $coords = explode(' ', $stop['location']);
            $stop['lon'] = filter_var($coords[0], FILTER_SANITIZE_NUMBER_FLOAT, ['flags' => FILTER_FLAG_ALLOW_FRACTION]);
            $stop['lat'] = filter_var($coords[1], FILTER_SANITIZE_NUMBER_FLOAT, ['flags' => FILTER_FLAG_ALLOW_FRACTION]);
        }
        return View::make('stoplist')->withStops($stops)->withTitle('Stops');
    } else {
        return Redirect::to('/')->withMessage('We couldn\'t find any stops within 3km of your location.');