Example #1
0
 public function calculate_position($timestamp = 0)
 {
     /*
     	Metoda zwraca id lotniska, w którym znajduje lub będzie się znajdował samolot w danym czasie (timestamp).
     	Pozycja 0 oznacza, że samolot jest w powietrzu.
     */
     if ($timestamp == 0) {
         $timestamp = time();
     }
     $flights = Flight::where('airplane_id', $this->id)->get();
     foreach ($flights as $flight) {
         $departure_timestamp = strtotime($flight->departure_time);
         $arrival_timestamp = strtotime($flight->arrival_time);
         if ($departure_timestamp < $timestamp and $timestamp < $arrival_timestamp) {
             //Ten lot właśnie trwa
             return false;
             //samolot w powietrzu
         }
     }
     //Samolot nie jest w powietrzu, sprawdzamy więc lotnisko na którym obecnie stoi
     $last_flight = Flight::where('airplane_id', $this->id)->where('departure_time', '<', date('Y-m-d H:i:s', $timestamp))->orderBy('departure_time', 'desc')->first();
     if (!$last_flight) {
         //Ten samolot nigdy nie leciał, wiec stoi w bazie, wiec zwracamy lotnisko-bazę
         return $this->airline->headquarter;
     } else {
         return $last_flight->destination;
     }
     //dd($last_flight);
 }
 public function account()
 {
     //Spaghetti code!!!
     //TODO: Refactor this method (move all logic from controller to models!!!)
     $arrived_and_not_accounted_flights = Flight::where('arrival_time', '<', DB::raw('UTC_TIMESTAMP()'))->where('accounted', 0)->get();
     $accounted = 0;
     //TODO: Improve tickets cost, based on real flight prices:
     // http://www.pasazer.com/news/7538/raport,ile,naprawde,kosztuje,lot.html
     foreach ($arrived_and_not_accounted_flights as $flight) {
         $fuel_price_litre = 1.18;
         $fuel = -1 * ((strtotime($flight->arrival_time) - strtotime($flight->departure_time)) / 3600 * $flight->airplane->model->fuel_usage * $fuel_price_litre);
         $taxes = 0;
         echo $flight;
         foreach ($flight->airline->deals as $deal) {
             if ($deal->pivot->airport_id == $flight->origin_airport_id || $deal->pivot->airport_id == $flight->destination_airport_id) {
                 $taxes -= $deal->pivot->operation_fee;
                 $taxes -= $deal->pivot->passenger_fee * ($flight->passengers_economy + $flight->passengers_buissnes + $flight->passengers_firstclass);
             }
         }
         echo 'TAXES: ' . $taxes . '$<hr>';
         //MVC violation!!! Move this to View
         $tickets = round(($flight->passengers_economy * 0.26 + $flight->passengers_buissnes * 0.86 + $flight->passengers_firstclass * 1.59) * $flight->distance);
         $bilance = $tickets + $fuel + $taxes;
         DB::table('airlines')->where('id', $flight->airline_id)->increment('funds', $bilance);
         //Repository Pattern violation!!!
         App::make('FinanceOperationsController')->create($flight->airline_id, 'flight', $bilance);
         $flight->bilance_tickets = $tickets;
         $flight->bilance_fuel = $fuel;
         $flight->bilance_taxes = $taxes;
         $flight->accounted = 1;
         $flight->save();
         $accounted++;
     }
     return $accounted . ' flights accounted.';
 }
Example #3
0
 function index()
 {
     $q = trim(Input::get('q'));
     if (empty($q) || !Input::has('q')) {
         return Redirect::home();
     }
     if (!Input::has('guess') || Input::get('guess') != 'no') {
         $regex = array('pilot' => '[0-9]+', 'airport' => '[A-Z0-9]{4}', 'airline' => '[A-Z0-9]{3}', 'airportIata' => '[A-Z0-9]{3}', 'citypair' => '([A-Z0-9]{3,4})(?:(?:\\s*?[-|>]\\s*?)|\\s+to\\s+|\\s+)([A-Z0-9]{3,4})', 'callsign' => '.*');
         $search = new Search($q);
         foreach ($regex as $type => $pattern) {
             if (preg_match('/^' . $pattern . '$/i', $q, $matches) && ($match = $search->quick($type, $matches))) {
                 Messages::info('You were redirected here by a best guess of the search system. <a href="' . URL::route('search', array('q' => $q, 'guess' => 'no')) . '" class="alert-link">Return to search results.</a>');
                 return $match;
             }
         }
     }
     $pilots = Pilot::where(function ($search) use($q) {
         $search->where('vatsim_id', '=', $q);
         $search->orWhere(function ($name) use($q) {
             $name->where('name', 'LIKE', '%' . $q . '%');
             $name->where('anonymous', '=', false);
         });
     })->where('vatsim_id', '!=', 0)->get();
     $flights = Flight::where('callsign', '=', $q)->orderBy('departure_time', 'desc')->get();
     $airlines = Airline::where('icao', '=', $q)->orWhere('name', 'LIKE', '%' . $q . '%')->get();
     $airports = Airport::where('icao', '=', $q)->orWhere('iata', '=', $q)->orWhere('name', 'LIKE', '%' . $q . '%')->orWhere('city', 'LIKE', '%' . $q . '%')->get();
     $this->autoRender(compact('q', 'flights', 'pilots', 'airlines', 'airports'), 'Search');
 }
 function fire($job, $data)
 {
     Log::info('queue:legacy[' . $job->getJobId() . '] - started airline ' . $data['airline']);
     $running = Cache::get('legacy.airlines.' . $data['airline'], false);
     if ($running != $job->getJobId() && $running !== false) {
         Log::info('queue:legacy[' . $job->getJobId() . '] - already running ' . $data['airline']);
         Cache::forget('legacy.airlines.' . $data['airline']);
         $job->delete();
         return;
     } else {
         Cache::forever('legacy.airlines.' . $data['airline'], $job->getJobId());
     }
     $flights = Flight::where('callsign', 'LIKE', $data['airline'] . '%')->whereState(2)->whereProcessed(false)->take($this->take)->get();
     $totalFlights = $flights->count();
     Log::info('queue:legacy[' . $job->getJobId() . '] - selected flights ' . $totalFlights);
     if ($flights->count() == 0) {
         Log::info('queue:legacy[' . $job->getJobId() . '] - no more flights for ' . $data['airline']);
         $airline = Airline::whereIcao($data['airline'])->first();
         $airline->duration = $airline->flights()->whereState(2)->sum('duration');
         $airline->save();
         return $this->finishJob($job, $data['airline']);
     }
     $job->delete();
     if ($job->attempts() > 1) {
         return;
     }
     DB::statement("create temporary table if not exists flights_temp (\n\t\t\t`id` int(10) unsigned NOT NULL,\n\t\t\t`callsign_type` tinyint(1) NOT NULL DEFAULT '0',\n\t\t\t`airline_id` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,\n\t\t\t`duration` smallint(6) NOT NULL DEFAULT '0',\n\t\t\t`distance` smallint(6) NOT NULL DEFAULT '0',\n\t\t\tPRIMARY KEY (`id`)\n\t\t)");
     Log::info('queue:legacy[' . $job->getJobId() . '] - created temp table');
     foreach ($flights as $i => $flight) {
         $callsign = str_replace('-', '', strtoupper($flight->callsign));
         if (preg_match('/^' . $data['airline'] . '[0-9]{1,5}[A-Z]{0,2}$/', $flight->callsign)) {
             // Airline
             $flight->isAirline($data['airline']);
         } elseif (!is_null($registration = $this->getRegistrations($callsign))) {
             $flight->isPrivate($registration->country_id);
             unset($registration);
         } else {
             $flight->airline_id = null;
         }
         if (!is_null($flight->departure_time) && !is_null($flight->arrival_time)) {
             $duration = $this->duration($flight->departure_time, $flight->arrival_time);
             $flight->duration = $duration;
             unset($duration);
         }
         // $distance = 0;
         // foreach($flight->positions as $key => $position) {
         // 	if($key > 0) $distance += $this->distance($position->lat, $position->lon, $previous->lat, $previous->lon);
         // 	$previous = $position;
         // }
         // $flight->distance = $distance;
         // $flight->processed = true;
         // $flight->save();
         $newFlights[] = array('id' => $flight->id, 'callsign_type' => $flight->callsign_type, 'airline_id' => $flight->airline_id, 'duration' => $flight->duration, 'distance' => $flight->distance);
         unset($flight, $i, $newFlight);
     }
     Log::info('queue:legacy[' . $job->getJobId() . '] - processed flights');
     unset($flights);
     $remaining = count($newFlights);
     $step = 0;
     do {
         Log::info('queue:legacy[' . $job->getJobId() . '] - inserted flights - ' . $remaining);
         DB::table('flights_temp')->insert(array_slice($newFlights, 100 * $step, 100));
         $remaining -= 100;
         $step++;
     } while ($remaining > 0);
     Log::info('queue:legacy[' . $job->getJobId() . '] - inserted flights - done');
     DB::statement("update flights dest, flights_temp src set\n\t\t\tdest.callsign_type = src.callsign_type,\n\t\t\tdest.airline_id = src.airline_id,\n\t\t\tdest.duration = src.duration,\n\t\t\tdest.processed = 2\n\t\twhere dest.id = src.id\n\t\t");
     Log::info('queue:legacy[' . $job->getJobId() . '] - updated flights');
     Log::info('queue:legacy[' . $job->getJobId() . '] - finished airline ' . $data['airline']);
     Cache::forget('legacy.airlines.' . $data['airline']);
 }
 /**
  * Processes the flights in the datafeed, both new and existing
  * in the database. As well as any flights in the database that
  * have not arrived yet but are missing from the datafeed.
  *
  * @return void
  */
 protected function pilots()
 {
     $this->elevations();
     // First we will select all flights from the database which
     // have not yet been marked as arrived and are not missing.
     $database = Flight::where('state', '!=', '2')->get();
     $insert = array();
     $update = array();
     $default = array('route' => '', 'remarks' => '', 'altitude' => '', 'speed' => '', 'flighttype' => 'I', 'last_lat' => '0', 'last_lon' => '0', 'last_altitude' => '0', 'last_speed' => '0', 'last_heading' => '0', 'missing' => '0', 'startdate' => date('Y-m-d'), 'revision' => '0', 'callsign' => '', 'callsign_type' => '0', 'airline_id' => null, 'vatsim_id' => '', 'aircraft_code' => '', 'aircraft_id' => null, 'departure_id' => '', 'arrival_id' => '', 'state' => '4', 'departure_time' => null, 'arrival_time' => null, 'departure_country_id' => '', 'arrival_country_id' => '', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now());
     foreach ($this->pilots as $entry) {
         try {
             // Find the flight in the data we fetched using the callsign
             // and vatsim id of the pilot. If the flight does not exist
             // in the database we will create a new one.
             $flightKey = null;
             $flight = $database->first(function ($key, $flight) use($entry, &$flightKey) {
                 if (str_replace('-', '', $flight->callsign) == str_replace('-', '', $entry['callsign']) && $flight->vatsim_id == $entry['cid']) {
                     $flightKey = $key;
                     return true;
                 }
                 return false;
             }, new Flight());
             // Some data will have to be refreshed with every update of
             // the datafeed. Pilots have the ability to update the route,
             // remarks, altitude and speed at all times using a new flight plan.
             $flight->route = $entry['planned_route'];
             $flight->remarks = $entry['planned_remarks'];
             $flight->altitude = $entry['planned_altitude'];
             $flight->speed = $entry['planned_tascruise'];
             $flight->flighttype = $entry['planned_flighttype'];
             // Update last known coordinates
             $flight->last_lat = $entry['latitude'];
             $flight->last_lon = $entry['longitude'];
             $flight->last_altitude = $entry['altitude'];
             $flight->last_speed = $entry['groundspeed'];
             $flight->last_heading = $entry['heading'];
             // We also need to ensure that the flight is not marked as missing,
             // now that we have a record of the flight again.
             $flight->missing = 0;
             // If the flight does not exist we need to load the basic
             // data, such as date, pilot, callsign, aircraft, etc.
             if (!$flight->exists) {
                 $flight->startdate = Carbon::createFromFormat('YmdHis', $entry['time_logon'], 'UTC')->toDateString();
                 $flight->revision = $entry['planned_revision'];
                 $callsign = $this->callsign($entry['callsign']);
                 $flight->callsign = $callsign['callsign'];
                 $flight->callsign_type = $callsign['callsign_type'];
                 $flight->airline_id = $callsign['airline_id'];
                 $flight->vatsim_id = $entry['cid'];
                 $flight->aircraft_code = $entry['planned_aircraft'];
                 $flight->aircraft_id = $this->aircraft($entry['planned_aircraft']);
                 $flight->departure_id = $entry['planned_depairport'];
                 $flight->arrival_id = $entry['planned_destairport'];
                 $flight->state = 4;
                 $this->vatsimUser($entry['cid']);
                 try {
                     if ($entry['planned_deptime'] > 0 && $entry['planned_deptime'] < 2359 && !empty($entry['planned_deptime'])) {
                         $date = $flight->startdate;
                         list($hour, $minute) = str_split(str_pad($entry['planned_deptime'], 4, '0', STR_PAD_LEFT), 2);
                         $flight->departure_time = Carbon::createFromFormat('Y-m-d H:i', $date . ' ' . $hour . ':' . $minute, 'UTC');
                     }
                 } catch (InvalidArgumentException $e) {
                     Log::warning($entry['planned_deptime']);
                     Log::warning($e);
                 }
             } else {
                 // Update distance
                 try {
                     $flight->distance += acos(sin(deg2rad($flight->getOriginal('last_lat'))) * sin(deg2rad($entry['latitude'])) + cos(deg2rad($flight->getOriginal('last_lat'))) * cos(deg2rad($entry['latitude'])) * cos(deg2rad($flight->getOriginal('last_lon')) - deg2rad($entry['longitude']))) * 6371;
                 } catch (ErrorException $e) {
                     Log::debug($e);
                 }
                 // Add the position report
                 $this->positionReport($entry, $flight->id);
                 // Only allow the departure airport/time to be updated if the
                 // current state is preparing(4) or departing(0). If done after
                 // that it's technically too late since they have already departed.
                 if (in_array($flight->state, [0, 4]) && $entry['planned_deptime'] > 0 && $entry['planned_deptime'] < 2359 && !empty($entry['planned_deptime'])) {
                     $date = $flight->startdate;
                     list($hour, $minute) = str_split(str_pad($entry['planned_deptime'], 4, '0', STR_PAD_LEFT), 2);
                     $flight->departure_time = Carbon::createFromFormat('Y-m-d H:i', $date . ' ' . $hour . ':' . $minute, 'UTC');
                 }
                 $flight->departure_id = $entry['planned_depairport'];
                 $flight->arrival_id = $entry['planned_destairport'];
             }
             // Update the arrival time to always be the planned flight time
             // from the departure time.
             if (!is_null($flight->departure_time)) {
                 $flight->arrival_time = Carbon::instance($flight->departure_time)->addHours($entry['planned_hrsenroute'])->addMinutes($entry['planned_minenroute']);
             } else {
                 $flight->arrival_time = null;
             }
             // Workflow processes
             // Flight is preparing and plane has taken off
             if (($flight->state == 4 || $flight->state == 0) && $this->hasTakenOff($flight, $entry)) {
                 $flight->state = 1;
                 $flight->departure_time = $this->updateDate;
                 $flight->arrival_time = Carbon::instance($flight->departure_time)->addHours($entry['planned_hrsenroute'])->addMinutes($entry['planned_minenroute']);
             } elseif ($flight->state == 4 && $this->hasMoved($flight, $entry)) {
                 $flight->state = 0;
             } elseif ($flight->state == 1 && $this->hasLanded($flight, $entry)) {
                 $flight->state = 3;
             } elseif ($flight->state == 3) {
                 $airport = $this->hasLanded($flight, $entry);
                 // Mark flight as arrived when still near airport
                 if ($airport) {
                     $flight->state = 5;
                     $flight->arrival_id = $airport;
                     $flight->arrival_time = $this->updateDate;
                     $flight->duration = $this->duration($flight->departure_time, $flight->arrival_time);
                 } else {
                     $flight->state = 1;
                 }
             }
             // We want to get the airport country IDs as one of the last things
             // because they are dependent on the other information pertaining to
             // this flight and it is not needed for anything else.
             $flight->departure_country_id = $this->airportCountry($flight->departure_id);
             $flight->arrival_country_id = $this->airportCountry($flight->arrival_id);
             $flight->aircraft_code = $entry['planned_aircraft'];
             $flight->aircraft_id = $this->aircraft($entry['planned_aircraft']);
             // Skip this record if the callsign is empty
             if (empty($flight->callsign)) {
                 continue;
             } elseif ($flight->exists) {
                 $update[$flight->id] = array_except($flight->toArray(), array('startdate', 'callsign', 'callsign_type', 'airline_id', 'vatsim_id', 'route_parsed', 'created_at', 'updated_at', 'deleted_at'));
                 $database->forget($flightKey);
             } else {
                 $flight->created_at = Carbon::now();
                 $flight->updated_at = Carbon::now();
                 $insert[] = array_merge($default, array_except($flight->toArray(), array('deleted_at')));
             }
             unset($flight, $entry, $callsign);
         } catch (Exception $e) {
             Log::error($e);
         }
     }
     // Insert new flights into the flights table right away
     $this->progressiveInsert(new Flight(), $insert);
     unset($insert, $default);
     // Create temporary flights table for records that are to be updated
     DB::statement("create temporary table if not exists flights_temp (\n\t\t\t`id` int(10) unsigned NOT NULL,\n\t\t\t`departure_id` varchar(6) COLLATE utf8_unicode_ci NOT NULL,\n\t\t\t`arrival_id` varchar(6) COLLATE utf8_unicode_ci NOT NULL,\n\t\t\t`departure_country_id` varchar(2) COLLATE utf8_unicode_ci NOT NULL,\n\t\t\t`arrival_country_id` varchar(2) COLLATE utf8_unicode_ci NOT NULL,\n\t\t\t`route` text COLLATE utf8_unicode_ci NOT NULL,\n\t\t\t`remarks` text COLLATE utf8_unicode_ci NOT NULL,\n\t\t\t`altitude` varchar(15) COLLATE utf8_unicode_ci NOT NULL,\n\t\t\t`speed` smallint(6) NOT NULL,\n\t\t\t`flighttype` char(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'I',\n\t\t\t`state` tinyint(4) NOT NULL,\n\t\t\t`missing` tinyint(1) NOT NULL DEFAULT '0',\n\t\t\t`aircraft_code` varchar(20) COLLATE utf8_unicode_ci NOT NULL,\n\t\t\t`aircraft_id` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,\n\t\t\t`departure_time` datetime DEFAULT NULL,\n\t\t\t`arrival_time` datetime DEFAULT NULL,\n\t\t\t`duration` smallint(6) NOT NULL DEFAULT '0',\n\t\t\t`distance` smallint(6) NOT NULL DEFAULT '0',\n\t\t\t`processed` tinyint(1) NOT NULL DEFAULT '0',\n\t\t\t`revision` tinyint(4) NOT NULL DEFAULT '1',\n\t\t\t`last_lat` decimal(10,6) NOT NULL,\n\t\t\t`last_lon` decimal(10,6) NOT NULL,\n\t\t\t`last_altitude` mediumint(6) NOT NULL,\n\t\t\t`last_speed` smallint(4) unsigned NOT NULL,\n\t\t\t`last_heading` smallint(3) unsigned NOT NULL,\n\t\t\tPRIMARY KEY (`id`)\n\t\t)");
     // Insert flights to be updated into temporary table
     $this->progressiveInsert('flights_temp', $update);
     // Update flights table with data in temporary table
     DB::statement("update flights dest, flights_temp src set\n\t\t\tdest.departure_id = src.departure_id,\n\t\t\tdest.arrival_id = src.arrival_id,\n\t\t\tdest.departure_country_id = src.departure_country_id,\n\t\t\tdest.arrival_country_id = src.arrival_country_id,\n\t\t\tdest.route = src.route,\n\t\t\tdest.remarks = src.remarks,\n\t\t\tdest.altitude = src.altitude,\n\t\t\tdest.speed = src.speed,\n\t\t\tdest.flighttype = src.flighttype,\n\t\t\tdest.state = src.state,\n\t\t\tdest.missing = 0,\n\t\t\tdest.aircraft_code = src.aircraft_code,\n\t\t\tdest.aircraft_id = src.aircraft_id,\n\t\t\tdest.departure_time = src.departure_time,\n\t\t\tdest.arrival_time = src.arrival_time,\n\t\t\tdest.duration = src.duration,\n\t\t\tdest.distance = src.distance,\n\t\t\tdest.processed = src.processed,\n\t\t\tdest.revision = src.revision,\n\t\t\tdest.last_lat = src.last_lat,\n\t\t\tdest.last_lon = src.last_lon,\n\t\t\tdest.last_altitude = src.last_altitude,\n\t\t\tdest.last_speed = src.last_speed,\n\t\t\tdest.last_heading = src.last_heading,\n\t\t\tdest.updated_at = CURRENT_TIMESTAMP()\n\t\twhere dest.id = src.id");
     if (count($this->positions) > 0) {
         $this->progressiveInsert(new Position(), $this->positions);
         unset($this->positions);
     }
     unset($update);
     $delete = array();
     $disappeared = array();
     foreach ($database as $missing) {
         if ($missing->state == 5) {
             $missing->state = 2;
             $missing->missing = 0;
             $missing->duration = $this->duration($missing->departure_time, $missing->arrival_time);
             $missing->save();
             $missing->pilot->counter++;
             $missing->pilot->distance += $missing->distance;
             $missing->pilot->duration += $missing->duration;
             $missing->pilot->save();
         } elseif ($missing->missing && Carbon::now()->diffInMinutes($missing->updated_at) >= 60) {
             $delete[] = $missing->id;
         } else {
             if (($missing->state == 1 || $missing->state == 3) && ($airport = $this->hasLanded($missing))) {
                 $missing->state = 2;
                 $missing->missing = 0;
                 $missing->arrival_id = $airport;
                 $missing->arrival_time = $missing->updated_at;
                 $missing->duration = $this->duration($missing->departure_time, $missing->arrival_time);
                 $missing->save();
                 $missing->pilot->counter++;
                 $missing->pilot->distance += $missing->distance;
                 $missing->pilot->duration += $missing->duration;
                 $missing->pilot->save();
             } elseif (!$missing->missing) {
                 $disappeared[] = $missing->id;
             }
         }
         unset($airport, $missing);
     }
     // Delete flights that have been missing for more than an hour
     if (count($delete) > 0) {
         Flight::destroy($delete);
     }
     // Set flights to missing
     if (count($disappeared) > 0) {
         Flight::whereIn('id', $disappeared)->update(array('missing' => '1'));
     }
     unset($database, $delete, $disappeared, $missings);
 }