diff --git a/.unshifted-lumen-files/app/Console/Kernel.php b/.unshifted-lumen-files/app/Console/Kernel.php new file mode 100644 index 0000000..97925b8 --- /dev/null +++ b/.unshifted-lumen-files/app/Console/Kernel.php @@ -0,0 +1,71 @@ +job(new HourlySummary())->hourlyAt(0); + $schedule->job(new ProcessANPCAllDataV2())->everyTwoMinutes(); + $schedule->job(new ProcessDataForHistoryTotal())->everyTwoMinutes(); + //$schedule->job(new ProcessMadeiraWarnings())->everyTenMinutes(); + //$schedule->job(new ProcessPlanes())->everyFiveMinutes(); + $schedule->job(new ProcessRCM(true))->daily()->at('09:00'); + $schedule->job(new ProcessRCM(false))->hourly(); // update RCM + $schedule->job(new ProcessRCM(true, true))->daily()->at('18:00'); + + $schedule->job(new UpdateICNFData(0))->everyFourHours(); + $schedule->job(new UpdateICNFData(1))->twiceDaily(); + $schedule->job(new UpdateICNFData(2))->dailyAt('06:00'); + $schedule->job(new UpdateICNFData(3))->cron('0 2 */2 * *'); // every 2 days + $schedule->job(new UpdateICNFData(4))->cron('0 3 * * 1,5'); // twice a week, monday and thursday + $schedule->job(new UpdateICNFData(5))->cron('0 3 * * 1,5'); // twice a week, monday and thursday + $schedule->job(new UpdateICNFData(6))->cron('0 3 * * 3'); // once a week, wednesday + + $schedule->job(new UpdateWeatherStations())->daily()->at('03:21'); + $schedule->job(new UpdateWeatherData())->everyTwoHours(); + + $schedule->job(new UpdateWeatherDataDaily())->daily()->at('04:21'); + + $schedule->job(new DailySummary())->daily()->at('09:30'); + + //$schedule->job(new HandleANEPCImportantData())->everyTenMinutes(); + //$schedule->job(new HandleANEPCPositEmail())->everyTenMinutes(); + } + } +} diff --git a/.unshifted-lumen-files/app/Exceptions/Handler.php b/.unshifted-lumen-files/app/Exceptions/Handler.php new file mode 100644 index 0000000..b6e9bb0 --- /dev/null +++ b/.unshifted-lumen-files/app/Exceptions/Handler.php @@ -0,0 +1,58 @@ +bound('sentry') && $this->shouldReport($exception)) { + app('sentry')->captureException($exception); + } + + if ($exception instanceof ModelNotFoundException && $request->wantsJson()) { + return response()->json(['message' => 'Not Found!'], 404); + } + + return parent::render($request, $exception); + } +} diff --git a/.unshifted-lumen-files/app/Http/Middleware/Authenticate.php b/.unshifted-lumen-files/app/Http/Middleware/Authenticate.php new file mode 100644 index 0000000..b93b5b4 --- /dev/null +++ b/.unshifted-lumen-files/app/Http/Middleware/Authenticate.php @@ -0,0 +1,40 @@ +auth = $auth; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param null|string $guard + * @return mixed + */ + public function handle($request, Closure $next, $guard = null) + { + if ($this->auth->guard($guard)->guest()) { + return response('Unauthorized.', 401); + } + + return $next($request); + } +} diff --git a/.unshifted-lumen-files/app/Models/User.php b/.unshifted-lumen-files/app/Models/User.php new file mode 100644 index 0000000..49dc9d0 --- /dev/null +++ b/.unshifted-lumen-files/app/Models/User.php @@ -0,0 +1,35 @@ +environment('production')) { + URL::forceScheme('https'); + } + } +} diff --git a/.unshifted-lumen-files/app/Providers/AuthServiceProvider.php b/.unshifted-lumen-files/app/Providers/AuthServiceProvider.php new file mode 100644 index 0000000..10dfe61 --- /dev/null +++ b/.unshifted-lumen-files/app/Providers/AuthServiceProvider.php @@ -0,0 +1,28 @@ +app['auth']->viaRequest('api', function ($request) { + if ($request->input('api_token')) { + return User::where('api_token', $request->input('api_token'))->first(); + } + + return null; + }); + } +} diff --git a/.unshifted-lumen-files/app/Providers/EventServiceProvider.php b/.unshifted-lumen-files/app/Providers/EventServiceProvider.php new file mode 100644 index 0000000..4873fdf --- /dev/null +++ b/.unshifted-lumen-files/app/Providers/EventServiceProvider.php @@ -0,0 +1,15 @@ +bootstrap(); + +date_default_timezone_set(env('APP_TIMEZONE', 'UTC')); + +/* +|-------------------------------------------------------------------------- +| Create The Application +|-------------------------------------------------------------------------- +| +| Here we will load the environment and create the application instance +| that serves as the central piece of this framework. We'll use this +| application as an "IoC" container and router for this framework. +| +*/ + +$app = new Laravel\Lumen\Application( + dirname(__DIR__) +); + +/* +|-------------------------------------------------------------------------- +| Register Container Bindings +|-------------------------------------------------------------------------- +| +| Now we will register a few bindings in the service container. We will +| register the exception handler and the console kernel. You may add +| your own bindings here if you like or you can make another file. +| +*/ + +$app->singleton( + Illuminate\Contracts\Debug\ExceptionHandler::class, + App\Exceptions\Handler::class +); + +$app->singleton( + Illuminate\Contracts\Console\Kernel::class, + App\Console\Kernel::class +); + +/* +|-------------------------------------------------------------------------- +| Register Config Files +|-------------------------------------------------------------------------- +| +| Now we will register the "app" configuration file. If the file exists in +| your configuration directory it will be loaded; otherwise, we'll load +| the default version. You may register other files below as needed. +| +*/ +$app->configure('app'); + +/* +|-------------------------------------------------------------------------- +| Register Middleware +|-------------------------------------------------------------------------- +| +| Next, we will register the middleware with the application. These can +| be global middleware that run before and after each request into a +| route or middleware that'll be assigned to some specific routes. +| +*/ + +// $app->middleware([ +// App\Http\Middleware\ExampleMiddleware::class +// ]); + +// $app->routeMiddleware([ +// 'auth' => App\Http\Middleware\Authenticate::class, +// ]); + +/* +|-------------------------------------------------------------------------- +| Register Service Providers +|-------------------------------------------------------------------------- +| +| Here we will register all of the application's service providers which +| are used to bind services into the container. Service providers are +| totally optional, so you are not required to uncomment this line. +| +*/ + +$app->register(App\Providers\AppServiceProvider::class); +// $app->register(App\Providers\AuthServiceProvider::class); +// $app->register(App\Providers\EventServiceProvider::class); +$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class); +$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class); +$app->register(Illuminate\Redis\RedisServiceProvider::class); +$app->register(Sentry\Laravel\ServiceProvider::class); +$app->register(Anik\Form\FormRequestServiceProvider::class); + +$app->withFacades(); +$app->withEloquent(); + +/* +|-------------------------------------------------------------------------- +| Load The Application Routes +|-------------------------------------------------------------------------- +| +| Next we will include the routes file so that they can all be added to +| the application. This will provide all of the URLs the application +| can respond to, as well as the controllers that may handle them. +| +*/ + +$app->router->group([], static fn (Router $router) => require __DIR__.'/../routes/web.php'); + +return $app; diff --git a/.unshifted-lumen-files/config/database.php b/.unshifted-lumen-files/config/database.php new file mode 100644 index 0000000..3b0f4a9 --- /dev/null +++ b/.unshifted-lumen-files/config/database.php @@ -0,0 +1,46 @@ + 'mongodb', + 'connections' => [ + 'mongodb' => [ + 'driver' => 'mongodb', + 'host' => env('DB_HOST', 'localhost'), + 'port' => env('DB_PORT', 27017), + 'database' => env('DB_DATABASE'), + 'username' => env('DB_USERNAME'), + 'password' => env('DB_PASSWORD'), + 'options' => [ + 'database' => 'admin', // sets the authentication database required by mongo 3 + ], + ], + ], + 'migrations' => 'migrations', + + 'redis' => [ + 'client' => env('REDIS_CLIENT', 'phpredis'), + + 'options' => [ + 'cluster' => env('REDIS_CLUSTER', 'redis'), + 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'lumen'), '_').'_database_'), + ], + + 'default' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'password' => env('REDIS_PASSWORD', null), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_DB', '0'), + ], + + 'cache' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'password' => env('REDIS_PASSWORD', null), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_CACHE_DB', '1'), + ], + ], +]; diff --git a/.unshifted-lumen-files/config/logging.php b/.unshifted-lumen-files/config/logging.php new file mode 100644 index 0000000..3eb02bd --- /dev/null +++ b/.unshifted-lumen-files/config/logging.php @@ -0,0 +1,117 @@ + env('LOG_CHANNEL', 'stack'), + + /* + |-------------------------------------------------------------------------- + | Deprecations Log Channel + |-------------------------------------------------------------------------- + | + | This option controls the log channel that should be used to log warnings + | regarding deprecated PHP and library features. This allows you to get + | your application ready for upcoming major versions of dependencies. + | + */ + + 'deprecations' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), + + /* + |-------------------------------------------------------------------------- + | Log Channels + |-------------------------------------------------------------------------- + | + | Here you may configure the log channels for your application. Out of + | the box, Laravel uses the Monolog PHP logging library. This gives + | you a variety of powerful log handlers / formatters to utilize. + | + | Available Drivers: "single", "daily", "slack", "syslog", + | "errorlog", "monolog", + | "custom", "stack" + | + */ + + 'channels' => [ + 'stack' => [ + 'driver' => 'stack', + 'channels' => ['daily'], + ], + + 'single' => [ + 'driver' => 'single', + 'path' => storage_path('logs/lumen.log'), + 'level' => 'debug', + ], + + 'anepc' => [ + 'driver' => 'single', + 'path' => storage_path('logs/anepc.log'), + 'level' => 'debug', + ], + + 'daily' => [ + 'driver' => 'daily', + 'path' => storage_path('logs/lumen.log'), + 'level' => 'debug', + 'days' => 14, + ], + + 'slack' => [ + 'driver' => 'slack', + 'url' => env('LOG_SLACK_WEBHOOK_URL'), + 'username' => 'Lumen Log', + 'emoji' => ':boom:', + 'level' => 'critical', + ], + + 'papertrail' => [ + 'driver' => 'monolog', + 'level' => 'debug', + 'handler' => SyslogUdpHandler::class, + 'handler_with' => [ + 'host' => env('PAPERTRAIL_URL'), + 'port' => env('PAPERTRAIL_PORT'), + ], + ], + + 'stderr' => [ + 'driver' => 'monolog', + 'handler' => StreamHandler::class, + 'with' => [ + 'stream' => 'php://stderr', + ], + ], + + 'syslog' => [ + 'driver' => 'syslog', + 'level' => 'debug', + ], + + 'errorlog' => [ + 'driver' => 'errorlog', + 'level' => 'debug', + ], + + 'null' => [ + 'driver' => 'monolog', + 'handler' => NullHandler::class, + ], + ], + +]; diff --git a/app/Console/Commands/FixFMA.php b/app/Console/Commands/FixFMA.php index 09b1f22..664f5d1 100644 --- a/app/Console/Commands/FixFMA.php +++ b/app/Console/Commands/FixFMA.php @@ -40,7 +40,7 @@ public function handle() { $incidents = Incident::where('isFMA', 'exists', false)->get(); - foreach($incidents as $incident){ + foreach ($incidents as $incident) { $isFMA = in_array($incident['naturezaCode'], Incident::NATUREZA_CODE_FMA); $incident->isFMA = $isFMA; diff --git a/app/Console/Commands/FixKMLData.php b/app/Console/Commands/FixKMLData.php index 5ec7f26..efc2121 100644 --- a/app/Console/Commands/FixKMLData.php +++ b/app/Console/Commands/FixKMLData.php @@ -47,8 +47,8 @@ public function handle() 'verify' => false, ]; - foreach($incidents as $incident){ - if(filter_var($incident->kml, FILTER_VALIDATE_URL)){ + foreach ($incidents as $incident) { + if (filter_var($incident->kml, FILTER_VALIDATE_URL)) { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', $incident->kml, $options); $kml = $res->getBody()->getContents(); diff --git a/app/Console/Commands/FixWeatherStationsId.php b/app/Console/Commands/FixWeatherStationsId.php index d5a6d06..dfebb13 100644 --- a/app/Console/Commands/FixWeatherStationsId.php +++ b/app/Console/Commands/FixWeatherStationsId.php @@ -2,7 +2,6 @@ namespace App\Console\Commands; -use App\Models\Incident; use App\Models\WeatherStation; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; @@ -40,7 +39,7 @@ public function __construct() */ public function handle() { - $url = "https://api.ipma.pt/open-data/observation/meteorology/stations/stations.json"; + $url = 'https://api.ipma.pt/open-data/observation/meteorology/stations/stations.json'; $options = [ 'headers' => [ @@ -49,32 +48,32 @@ public function handle() 'verify' => false, ]; - try{ + try { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', $url, $options); $data = $res->getBody()->getContents(); - } - catch(\GuzzleHttp\Exception\RequestException $e) { + } catch (\GuzzleHttp\Exception\RequestException $e) { Log::error('Error occurred in request.', ['url' => $url, 'statusCode' => $e->getCode(), 'message' => $e->getMessage()]); + return; } $data = json_decode($data); - foreach($data as $d){ + foreach ($data as $d) { $id = $d->properties->idEstacao; $station = WeatherStation::where('id', $id)->get(); - if(isset($station[0])){ + if (isset($station[0])) { $station = $station[0]; } else { $station = new WeatherStation(); - $station->id = (int)$id; + $station->id = (int) $id; } - $station->type = "point"; + $station->type = 'point'; $station->location = $d->properties->localEstacao; $station->coordinates = $d->geometry->coordinates; diff --git a/app/Console/Commands/GetICNFBurnAreaLegacy.php b/app/Console/Commands/GetICNFBurnAreaLegacy.php index 91549c8..44aa7fe 100644 --- a/app/Console/Commands/GetICNFBurnAreaLegacy.php +++ b/app/Console/Commands/GetICNFBurnAreaLegacy.php @@ -6,7 +6,6 @@ use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; -use Mockery\Exception; use voku\helper\UTF8; class GetICNFBurnAreaLegacy extends Command @@ -44,39 +43,38 @@ public function handle() { ini_set('memory_limit', '-1'); - $urls = array( + $urls = [ 'https://github.com/vostpt/ICNF_DATA/raw/main/icnf_2017_raw.csv', 'https://github.com/vostpt/ICNF_DATA/raw/main/icnf_2018_raw.csv', 'https://github.com/vostpt/ICNF_DATA/raw/main/icnf_2019_raw.csv', 'https://github.com/vostpt/ICNF_DATA/raw/main/icnf_2020_raw.csv', - 'https://github.com/vostpt/ICNF_DATA/raw/main/icnf_2021_raw.csv' - ); + 'https://github.com/vostpt/ICNF_DATA/raw/main/icnf_2021_raw.csv', + ]; - foreach($urls as $url){ + foreach ($urls as $url) { - echo 'Getting ' . $url . PHP_EOL; + echo 'Getting '.$url.PHP_EOL; $csv = file_get_contents($url); - $rows = explode("\n",$csv); - $data = array(); - foreach($rows as $row) { - $data[] = explode(",",$row); + $rows = explode("\n", $csv); + $data = []; + foreach ($rows as $row) { + $data[] = explode(',', $row); } - echo ' Total: ' . count($data) . PHP_EOL; - + echo ' Total: '.count($data).PHP_EOL; unset($data[0]); $i = 0; - foreach ($data as $d){ - if(!isset($d[14])){ + foreach ($data as $d) { + if (! isset($d[14])) { return; } - if($i % 1000 === 0){ - echo PHP_EOL . ' . ' . $i . PHP_EOL; + if ($i % 1000 === 0) { + echo PHP_EOL.' . '.$i.PHP_EOL; } else { echo '.'; } @@ -85,7 +83,7 @@ public function handle() $incident = Incident::where('id', $d[14])->get(); - if(isset($incident[0])){ + if (isset($incident[0])) { $incident = $incident[0]; $icnfData = []; @@ -109,58 +107,58 @@ public function handle() $icnfData['reacendimentos'] = (bool) $d[8]; } - if (isset($d[9]) && boolval((int)$d[9])) { - $icnfData['queimada'] = boolval((int)$d[9]); + if (isset($d[9]) && boolval((int) $d[9])) { + $icnfData['queimada'] = boolval((int) $d[9]); } - if (isset($d[10]) && boolval((int)$d[10])) { - $icnfData['falsoalarme'] = boolval((int)$d[10]); + if (isset($d[10]) && boolval((int) $d[10])) { + $icnfData['falsoalarme'] = boolval((int) $d[10]); } - if (isset($d[11]) && boolval((int)$d[11])) { - $icnfData['fogacho'] = boolval((int)$d[11]); + if (isset($d[11]) && boolval((int) $d[11])) { + $icnfData['fogacho'] = boolval((int) $d[11]); } - if (isset($d[12]) && boolval((int)$d[12])) { - $icnfData['incendio'] = boolval((int)$d[12]); + if (isset($d[12]) && boolval((int) $d[12])) { + $icnfData['incendio'] = boolval((int) $d[12]); } - if (isset($d[13]) && boolval((int)$d[13])) { - $icnfData['agricola'] = boolval((int)$d[13]); + if (isset($d[13]) && boolval((int) $d[13])) { + $icnfData['agricola'] = boolval((int) $d[13]); } - if (isset($d[41]) && boolval((int)$d[41])) { - $icnfData['queima'] = boolval((int)$d[41]); + if (isset($d[41]) && boolval((int) $d[41])) { + $icnfData['queima'] = boolval((int) $d[41]); } - if (isset($d[21]) && !empty((string)$d[21])) { + if (isset($d[21]) && ! empty((string) $d[21])) { $icnfData['fontealerta'] = (string) $d[21]; } - if (isset($d[31]) && !empty((string) $d[31])) { + if (isset($d[31]) && ! empty((string) $d[31])) { $icnfData['causa'] = (string) $d[31]; } - if (isset($d[32]) && !empty((string) $d[32])) { + if (isset($d[32]) && ! empty((string) $d[32])) { $icnfData['tipocausa'] = (string) $d[32]; } - if (isset($d[44]) && !empty((string) $d[44])) { + if (isset($d[44]) && ! empty((string) $d[44])) { $icnfData['causafamilia'] = (string) $d[44]; } $kmlUrl = false; - if (isset($d[66]) && !empty((string) $d[66])) { + if (isset($d[66]) && ! empty((string) $d[66])) { $kmlUrl = (string) $d[66]; } - if (isset($d[67]) && !empty((string) $d[67])) { + if (isset($d[67]) && ! empty((string) $d[67])) { $kmlUrl = (string) $d[67]; } if ($kmlUrl) { - try{ + try { $options = [ 'headers' => [ 'User-Agent' => 'Fogos.pt/3.0', @@ -173,7 +171,7 @@ public function handle() $kml = $res->getBody()->getContents(); $incident->kml = utf8_encode($kml); - } catch (\Exception $e){ + } catch (\Exception $e) { Log::debug($e->getMessage()); } @@ -183,8 +181,7 @@ public function handle() $incident->icnf = $icnfData; $incident->save(); - } - else { + } else { $point = $this->prepareData($d, true); $incident = new Incident($point); $incident->sentCheckImportant = false; @@ -192,91 +189,89 @@ public function handle() } } - } -/* - Array - ( - [0] => - [1] => DISTRITO - [2] => TIPO - [3] => ANO - [4] => AREAPOV - [5] => AREAMATO - [6] => AREAAGRIC - [7] => AREATOTAL - [8] => REACENDIMENTOS - [9] => QUEIMADA - [10] => FALSOALARME - [11] => FOGACHO - [12] => INCENDIO - [13] => AGRICOLA - [14] => NCCO - [15] => NOMECCO - [16] => DATAALERTA - [17] => HORAALERTA - [18] => LOCAL - [19] => CONCELHO - [20] => FREGUESIA - [21] => FONTEALERTA - [22] => INE - [23] => X - [24] => Y - [25] => DIA - [26] => MES - [27] => HORA - [28] => OPERADOR - [29] => PERIMETRO - [30] => APS - [31] => CAUSA - [32] => TIPOCAUSA - [33] => DHINICIO - [34] => DHFIM - [35] => DURACAO - [36] => HAHORA - [37] => DATAEXTINCAO - [38] => HORAEXTINCAO - [39] => DATA1INTERVENCAO - [40] => HORA1INTERVENCAO - [41] => QUEIMA - [42] => LAT - [43] => LON - [44] => CAUSAFAMILIA - [45] => TEMPERATURA - [46] => HUMIDADERELATIVA - [47] => VENTOINTENSIDADE - [48] => VENTOINTENSIDADE_VETOR - [49] => VENTODIRECAO_VETOR - [50] => PRECEPITACAO - [51] => FFMC - [52] => DMC - [53] => DC - [54] => ISI - [55] => BUI - [56] => FWI - [57] => DSR - [58] => THC - [59] => MODFARSITE - [60] => ALTITUDEMEDIA - [61] => DECLIVEMEDIO - [62] => HORASEXPOSICAOMEDIA - [63] => DENDIDADERV - [64] => COSN5VARIEDADE - [65] => AREAMANCHAMODFARSITE - [66] => AREASFICHEIROS_GNR - [67] => AREASFICHEIROS_GTF - [68] => FICHEIROIMAGEM_GNR - [69] => AREASFICHEIROSHP_GTF - [70] => AREASFICHEIROSHPXML_GTF - [71] => AREASFICHEIRODBF_GTF - [72] => AREASFICHEIROPRJ_GTF - [73] => AREASFICHEIROSBN_GTF - [74] => AREASFICHEIROSBX_GTF - [75] => AREASFICHEIROSHX_GTF - [76] => AREASFICHEIROZIP_SAA -) -*/ - + /* + Array + ( + [0] => + [1] => DISTRITO + [2] => TIPO + [3] => ANO + [4] => AREAPOV + [5] => AREAMATO + [6] => AREAAGRIC + [7] => AREATOTAL + [8] => REACENDIMENTOS + [9] => QUEIMADA + [10] => FALSOALARME + [11] => FOGACHO + [12] => INCENDIO + [13] => AGRICOLA + [14] => NCCO + [15] => NOMECCO + [16] => DATAALERTA + [17] => HORAALERTA + [18] => LOCAL + [19] => CONCELHO + [20] => FREGUESIA + [21] => FONTEALERTA + [22] => INE + [23] => X + [24] => Y + [25] => DIA + [26] => MES + [27] => HORA + [28] => OPERADOR + [29] => PERIMETRO + [30] => APS + [31] => CAUSA + [32] => TIPOCAUSA + [33] => DHINICIO + [34] => DHFIM + [35] => DURACAO + [36] => HAHORA + [37] => DATAEXTINCAO + [38] => HORAEXTINCAO + [39] => DATA1INTERVENCAO + [40] => HORA1INTERVENCAO + [41] => QUEIMA + [42] => LAT + [43] => LON + [44] => CAUSAFAMILIA + [45] => TEMPERATURA + [46] => HUMIDADERELATIVA + [47] => VENTOINTENSIDADE + [48] => VENTOINTENSIDADE_VETOR + [49] => VENTODIRECAO_VETOR + [50] => PRECEPITACAO + [51] => FFMC + [52] => DMC + [53] => DC + [54] => ISI + [55] => BUI + [56] => FWI + [57] => DSR + [58] => THC + [59] => MODFARSITE + [60] => ALTITUDEMEDIA + [61] => DECLIVEMEDIO + [62] => HORASEXPOSICAOMEDIA + [63] => DENDIDADERV + [64] => COSN5VARIEDADE + [65] => AREAMANCHAMODFARSITE + [66] => AREASFICHEIROS_GNR + [67] => AREASFICHEIROS_GTF + [68] => FICHEIROIMAGEM_GNR + [69] => AREASFICHEIROSHP_GTF + [70] => AREASFICHEIROSHPXML_GTF + [71] => AREASFICHEIRODBF_GTF + [72] => AREASFICHEIROPRJ_GTF + [73] => AREASFICHEIROSBN_GTF + [74] => AREASFICHEIROSBX_GTF + [75] => AREASFICHEIROSHX_GTF + [76] => AREASFICHEIROZIP_SAA + ) + */ } @@ -293,7 +288,7 @@ private function prepareData($data, $create = false) $isFire = true; $isTransportFire = false; $isUrbanFire = false; - $isOtherFire =false; + $isOtherFire = false; $isOtherIncident = false; $isFMA = false; @@ -301,7 +296,7 @@ private function prepareData($data, $create = false) $point = [ 'id' => $data[14], 'coords' => true, - 'dateTime' => Carbon::parse($data[37] . ' ' . $data[38], 'Europe/Lisbon'), + 'dateTime' => Carbon::parse($data[37].' '.$data[38], 'Europe/Lisbon'), 'date' => $data[37], 'hour' => $data[38], 'location' => $distrito.', '.$concelho.', '.$freguesia, @@ -323,10 +318,10 @@ private function prepareData($data, $create = false) 'isTransporteFire' => $isTransportFire, 'isOtherFire' => $isOtherFire, 'isOtherIncident' => $isOtherIncident, - 'isFMA' => $isFMA + 'isFMA' => $isFMA, ]; - if($create){ + if ($create) { $data['important'] = false; $data['heliFight'] = 0; $data['heliCoord'] = 0; @@ -355,58 +350,58 @@ private function prepareData($data, $create = false) $icnfData['reacendimentos'] = (bool) $data[8]; } - if (isset($data[9]) && boolval((int)$data[9])) { - $icnfData['queimada'] = boolval((int)$data[9]); + if (isset($data[9]) && boolval((int) $data[9])) { + $icnfData['queimada'] = boolval((int) $data[9]); } - if (isset($data[10]) && boolval((int)$data[10])) { - $icnfData['falsoalarme'] = boolval((int)$data[10]); + if (isset($data[10]) && boolval((int) $data[10])) { + $icnfData['falsoalarme'] = boolval((int) $data[10]); } - if (isset($data[11]) && boolval((int)$data[11])) { - $icnfData['fogacho'] = boolval((int)$data[11]); + if (isset($data[11]) && boolval((int) $data[11])) { + $icnfData['fogacho'] = boolval((int) $data[11]); } - if (isset($data[12]) && boolval((int)$data[12])) { - $icnfData['incendio'] = boolval((int)$data[12]); + if (isset($data[12]) && boolval((int) $data[12])) { + $icnfData['incendio'] = boolval((int) $data[12]); } - if (isset($data[13]) && boolval((int)$data[13])) { - $icnfData['agricola'] = boolval((int)$data[13]); + if (isset($data[13]) && boolval((int) $data[13])) { + $icnfData['agricola'] = boolval((int) $data[13]); } - if (isset($data[41]) && boolval((int)$data[41])) { - $icnfData['queima'] = boolval((int)$data[41]); + if (isset($data[41]) && boolval((int) $data[41])) { + $icnfData['queima'] = boolval((int) $data[41]); } - if (isset($data[21]) && !empty((string)$data[21])) { + if (isset($data[21]) && ! empty((string) $data[21])) { $icnfData['fontealerta'] = (string) $data[21]; } - if (isset($data[31]) && !empty((string) $data[31])) { + if (isset($data[31]) && ! empty((string) $data[31])) { $icnfData['causa'] = (string) $data[31]; } - if (isset($data[32]) && !empty((string) $data[32])) { + if (isset($data[32]) && ! empty((string) $data[32])) { $icnfData['tipocausa'] = (string) $data[32]; } - if (isset($data[44]) && !empty((string) $data[44])) { + if (isset($data[44]) && ! empty((string) $data[44])) { $icnfData['causafamilia'] = (string) $data[44]; } $kmlUrl = false; - if (isset($data[66]) && !empty((string) $data[66])) { + if (isset($data[66]) && ! empty((string) $data[66])) { $kmlUrl = (string) $data[66]; } - if (isset($data[67]) && !empty((string) $data[67])) { + if (isset($data[67]) && ! empty((string) $data[67])) { $kmlUrl = (string) $data[67]; } if ($kmlUrl) { - try{ + try { $options = [ 'headers' => [ 'User-Agent' => 'Fogos.pt/3.0', @@ -429,8 +424,6 @@ private function prepareData($data, $create = false) $point['icnf'] = $icnfData; - - return $point; } } diff --git a/app/Console/Commands/ImportLocations.php b/app/Console/Commands/ImportLocations.php index a59604b..a04e785 100644 --- a/app/Console/Commands/ImportLocations.php +++ b/app/Console/Commands/ImportLocations.php @@ -17187,8 +17187,7 @@ public function handle() } ]'); - - foreach ($locations as $l){ + foreach ($locations as $l) { $location = new Location(); $location->level = $l->level; $location->name = $l->name; diff --git a/app/Console/Commands/SaveWarningAndSendNotificationAndSocial.php b/app/Console/Commands/SaveWarningAndSendNotificationAndSocial.php index 27593f1..862ed35 100644 --- a/app/Console/Commands/SaveWarningAndSendNotificationAndSocial.php +++ b/app/Console/Commands/SaveWarningAndSendNotificationAndSocial.php @@ -51,12 +51,12 @@ public function handle() NotificationTool::sendWarningNotification($status); - $text = "ALERTA: \r\n" . $status; + $text = "ALERTA: \r\n".$status; TwitterTool::tweet($text); TelegramTool::publish($text); BlueskyTool::publish($text); - $message = "ALERTA: %0A" . $status; + $message = 'ALERTA: %0A'.$status; FacebookTool::publish($message); } } diff --git a/app/Console/Commands/TestStuff.php b/app/Console/Commands/TestStuff.php index 85cb150..a898399 100644 --- a/app/Console/Commands/TestStuff.php +++ b/app/Console/Commands/TestStuff.php @@ -7,7 +7,6 @@ use App\Jobs\HandleANEPCImportantData; use App\Jobs\HandleANEPCPositEmail; use App\Jobs\HandleNewIncidentSocialMedia; -use App\Jobs\ProcessANPCAllData; use App\Jobs\ProcessANPCAllDataV2; use App\Jobs\ProcessICNFFireData; use App\Jobs\ProcessICNFPDF; @@ -23,14 +22,11 @@ use App\Tools\TwitterTool; use App\Tools\TwitterToolV2; use Carbon\Carbon; +use HeadlessChromium\Browser; +use HeadlessChromium\Communication\Connection; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; -use PhpImap\Imap; -use PhpImap\Mailbox; use Spatie\Browsershot\Browsershot; -use HeadlessChromium\Communication\Connection; -use HeadlessChromium\Browser; -use voku\helper\UTF8; class TestStuff extends Command { @@ -180,43 +176,43 @@ public function handle() */ - // $text = 'Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,'; + // $text = 'Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,Test API, Test API,'; //TwitterToolV2::tweet($text, false, false,false, true); - // BlueskyTool::publish($text); - -// $url = 'https://apiprociv.geomai.mai.gov.pt/api/v1/ocorrencias/abertas'; -// -// -// $options = [ -// 'headers' => [ -// 'User-Agent' => 'Fogos.pt/3.0', -// 'Authorization' => 'Basic ' . base64_encode(env('ANEPC_API_USERNAME') . ':' .env('ANEPC_API_PASSWORD')) -// ], -// -// ]; -// -// if(env('PROXY_ENABLE')){ -// $options['proxy'] = env('PROXY_URL'); -// } -// -// $client = new \GuzzleHttp\Client(); -// $res = $client->request('GET', $url, $options); -// -// $data = json_decode($res->getBody(), true); -// -// print_r($data); -// -// -// dispatch(new ProcessANPCAllDataV2()); + // BlueskyTool::publish($text); + + // $url = 'https://apiprociv.geomai.mai.gov.pt/api/v1/ocorrencias/abertas'; + // + // + // $options = [ + // 'headers' => [ + // 'User-Agent' => 'Fogos.pt/3.0', + // 'Authorization' => 'Basic ' . base64_encode(env('ANEPC_API_USERNAME') . ':' .env('ANEPC_API_PASSWORD')) + // ], + // + // ]; + // + // if(env('PROXY_ENABLE')){ + // $options['proxy'] = env('PROXY_URL'); + // } + // + // $client = new \GuzzleHttp\Client(); + // $res = $client->request('GET', $url, $options); + // + // $data = json_decode($res->getBody(), true); + // + // print_r($data); + // + // + // dispatch(new ProcessANPCAllDataV2()); //dispatch(new ProcessRCM(false,false)); -// - // dispatch(new HandleANEPCImportantData()); + // + // dispatch(new HandleANEPCImportantData()); //dispatch( new HandleANEPCPositEmail()); -// Create PhpImap\Mailbox instance for all further actions + // Create PhpImap\Mailbox instance for all further actions //dispatch(new UpdateICNFData(1)); //dispatch(new DailySummary()); @@ -249,42 +245,41 @@ public function handle() //exec('node /var/www/html/screenshot-script.js --url https://fogos.pt/ --width 1000 --height 1300 --name screenshot-twitter '); -// Browsershot::url('https://fogos.pt') -// ->useCookies(['CookieConsent' => "{stamp:'m+a2sHQeOOuoPJRBktiiVf5mOGWDtiqvOKiLgCLNxxLwBBxXgfbaWQ=='%2Cnecessary:true%2Cpreferences:true%2Cstatistics:true%2Cmarketing:true%2Cver:1}"]) -// //->setDelay(10000) -// ->ignoreHttpsErrors() -// ->windowSize(env('SCREENSHOT_WIDTH'), env('SCREENSHOT_HEIGHT')) -// ->setRemoteInstance($ip) -// //->waitUntilNetworkIdle() -// ->save('/var/www/html/asd4.jpg'); + // Browsershot::url('https://fogos.pt') + // ->useCookies(['CookieConsent' => "{stamp:'m+a2sHQeOOuoPJRBktiiVf5mOGWDtiqvOKiLgCLNxxLwBBxXgfbaWQ=='%2Cnecessary:true%2Cpreferences:true%2Cstatistics:true%2Cmarketing:true%2Cver:1}"]) + // //->setDelay(10000) + // ->ignoreHttpsErrors() + // ->windowSize(env('SCREENSHOT_WIDTH'), env('SCREENSHOT_HEIGHT')) + // ->setRemoteInstance($ip) + // //->waitUntilNetworkIdle() + // ->save('/var/www/html/asd4.jpg'); // chrome devtools uri -// $webSocketUri = 'ws://'.$ip.':9222/devtools/browser/xxx'; -// -//// create connection given a web socket uri -// $connection = new Connection($webSocketUri); -// $connection->connect(); -// -//// create browser -// $browser = new Browser($connection); -// -// -// -// try { -// // creates a new page and navigate to an url -// $page = $browser->createPage(); -// $page->navigate('https://fogos.pt')->waitForNavigation(); -// -// -// // screenshot - Say "Cheese"! 😄 -// $page->screenshot()->saveToFile('/var/www/html/asd.png'); -// -// } finally { -// // bye -// $browser->close(); -// } + // $webSocketUri = 'ws://'.$ip.':9222/devtools/browser/xxx'; + // + //// create connection given a web socket uri + // $connection = new Connection($webSocketUri); + // $connection->connect(); + // + //// create browser + // $browser = new Browser($connection); + // + // + // + // try { + // // creates a new page and navigate to an url + // $page = $browser->createPage(); + // $page->navigate('https://fogos.pt')->waitForNavigation(); + // + // + // // screenshot - Say "Cheese"! 😄 + // $page->screenshot()->saveToFile('/var/www/html/asd.png'); + // + // } finally { + // // bye + // $browser->close(); + // } //TwitterTool::retweetVost("1559872724645941254"); } - } diff --git a/app/Console/Commands/UpdateExtraProperty.php b/app/Console/Commands/UpdateExtraProperty.php index 8f2799c..47b9075 100644 --- a/app/Console/Commands/UpdateExtraProperty.php +++ b/app/Console/Commands/UpdateExtraProperty.php @@ -47,6 +47,6 @@ public function handle() $incident->extra = $status; $incident->save(); - NotificationTool::send($status,$incident->location,$incident->id); + NotificationTool::send($status, $incident->location, $incident->id); } } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index b8920e4..854bcc8 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -2,73 +2,30 @@ namespace App\Console; -use App\Jobs\DailySummary; -use App\Jobs\HandleANEPCImportantData; -use App\Jobs\HandleANEPCPositEmail; -use App\Jobs\HourlySummary; -use App\Jobs\ProcessANPCAllData; -use App\Jobs\ProcessANPCAllDataV2; -use App\Jobs\ProcessDataForHistoryTotal; -use App\Jobs\ProcessMadeiraWarnings; -use App\Jobs\ProcessPlanes; -use App\Jobs\ProcessRCM; -use App\Jobs\UpdateICNFData; -use App\Jobs\UpdateWeatherData; -use App\Jobs\UpdateWeatherDataDaily; -use App\Jobs\UpdateWeatherStations; use Illuminate\Console\Scheduling\Schedule; -use Laravel\Lumen\Console\Kernel as ConsoleKernel; +use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** - * The Artisan commands provided by your application. + * Define the application's command schedule. * - * @var array + * @return void */ - protected $commands = [ - \App\Console\Commands\TestStuff::class, - \App\Console\Commands\FixKMLData::class, - \App\Console\Commands\FixFMA::class, - \App\Console\Commands\SaveWarningAndSendNotificationAndSocial::class, - \App\Console\Commands\GetICNFBurnAreaLegacy::class, - \App\Console\Commands\ImportLocations::class - ]; + protected function schedule(Schedule $schedule) + { + // $schedule->command('inspire')->hourly(); + } /** - * Define the application's command schedule. + * Register the commands for the application. + * + * @return void */ - protected function schedule(Schedule $schedule) + protected function commands() { - if (env('SCHEDULER_ENABLE')) { - $schedule->job(new HourlySummary())->hourlyAt(0); - $schedule->job(new ProcessANPCAllDataV2())->everyTwoMinutes(); - $schedule->job(new ProcessDataForHistoryTotal())->everyTwoMinutes(); - //$schedule->job(new ProcessMadeiraWarnings())->everyTenMinutes(); - //$schedule->job(new ProcessPlanes())->everyFiveMinutes(); - $schedule->job(new ProcessRCM(true))->daily()->at('09:00'); - $schedule->job(new ProcessRCM(false))->hourly(); // update RCM - $schedule->job(new ProcessRCM(true, true))->daily()->at('18:00'); - - $schedule->job(new UpdateICNFData(0))->everyFourHours(); - $schedule->job(new UpdateICNFData(1))->twiceDaily(); - $schedule->job(new UpdateICNFData(2))->dailyAt('06:00'); - $schedule->job(new UpdateICNFData(3))->cron('0 2 */2 * *'); // every 2 days - $schedule->job(new UpdateICNFData(4))->cron('0 3 * * 1,5'); // twice a week, monday and thursday - $schedule->job(new UpdateICNFData(5))->cron('0 3 * * 1,5'); // twice a week, monday and thursday - $schedule->job(new UpdateICNFData(6))->cron('0 3 * * 3'); // once a week, wednesday - - - $schedule->job(new UpdateWeatherStations())->daily()->at('03:21'); - $schedule->job(new UpdateWeatherData())->everyTwoHours(); - - $schedule->job(new UpdateWeatherDataDaily())->daily()->at('04:21'); - - $schedule->job(new DailySummary())->daily()->at('09:30'); - + $this->load(__DIR__.'/Commands'); - //$schedule->job(new HandleANEPCImportantData())->everyTenMinutes(); - //$schedule->job(new HandleANEPCPositEmail())->everyTenMinutes(); - } + require base_path('routes/console.php'); } } diff --git a/app/Events/Event.php b/app/Events/Event.php deleted file mode 100644 index b8230f0..0000000 --- a/app/Events/Event.php +++ /dev/null @@ -1,10 +0,0 @@ -> */ protected $dontReport = [ - AuthorizationException::class, - HttpException::class, - ModelNotFoundException::class, - ValidationException::class, + // ]; /** - * Report or log an exception. + * A list of the inputs that are never flashed for validation exceptions. * - * This is a great spot to send exceptions to Sentry, Bugsnag, etc. - * - * @throws \Exception + * @var array */ - public function report(Throwable $exception) - { - parent::report($exception); - } + protected $dontFlash = [ + 'current_password', + 'password', + 'password_confirmation', + ]; /** - * Render an exception into an HTTP response. - * - * @param \Illuminate\Http\Request $request + * Register the exception handling callbacks for the application. * - * @throws \Throwable - * - * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response + * @return void */ - public function render($request, Throwable $exception) + public function register() { - if (app()->bound('sentry') && $this->shouldReport($exception)) { - app('sentry')->captureException($exception); - } - - if ($exception instanceof ModelNotFoundException && $request->wantsJson()) { - return response()->json(['message' => 'Not Found!'], 404); - } - - return parent::render($request, $exception); + $this->reportable(function (Throwable $e) { + // + }); } - - } diff --git a/app/Http/Controllers/Auth/ConfirmPasswordController.php b/app/Http/Controllers/Auth/ConfirmPasswordController.php new file mode 100644 index 0000000..138c1f0 --- /dev/null +++ b/app/Http/Controllers/Auth/ConfirmPasswordController.php @@ -0,0 +1,40 @@ +middleware('auth'); + } +} diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php new file mode 100644 index 0000000..465c39c --- /dev/null +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -0,0 +1,22 @@ +middleware('guest')->except('logout'); + } +} diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php new file mode 100644 index 0000000..ffcb3b8 --- /dev/null +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -0,0 +1,71 @@ +middleware('guest'); + } + + /** + * Get a validator for an incoming registration request. + * + * @return \Illuminate\Contracts\Validation\Validator + */ + protected function validator(array $data) + { + return Validator::make($data, [ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], + 'password' => ['required', 'string', 'min:8', 'confirmed'], + ]); + } + + /** + * Create a new user instance after a valid registration. + * + * @return \App\Models\User + */ + protected function create(array $data) + { + return User::create([ + 'name' => $data['name'], + 'email' => $data['email'], + 'password' => Hash::make($data['password']), + ]); + } +} diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php new file mode 100644 index 0000000..b1726a3 --- /dev/null +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -0,0 +1,30 @@ +middleware('auth'); + $this->middleware('signed')->only('verify'); + $this->middleware('throttle:6,1')->only('verify', 'resend'); + } +} diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php new file mode 100644 index 0000000..a0a2a8a --- /dev/null +++ b/app/Http/Controllers/Controller.php @@ -0,0 +1,13 @@ +get('otherfire'); $concelho = $request->get('concelho'); - if($request->exists('limit')){ - $limit = (int)$request->get('limit'); + if ($request->exists('limit')) { + $limit = (int) $request->get('limit'); } else { $limit = 300; } - $geoJson = filter_var($request->get('geojson'), FILTER_VALIDATE_BOOLEAN);; + $geoJson = filter_var($request->get('geojson'), FILTER_VALIDATE_BOOLEAN); $csv = $request->get('csv'); $csv2 = $request->get('csv2'); $subRegion = $request->get('subRegion'); - $incidents = Incident::isActive() - ->when(!$all, function ($query, $all){ - return $query->isFire(); - })->when($isFMA, function ($query, $isFMA){ - return $query->isFMA(); - })->when($isOtherFire, function ($query, $isOtherFire){ - return $query->isOtherFire(); - })->when($concelho, function ($query, $concelho){ - return $query->where('concelho', $concelho); - })->when($subRegion, function ($query, $subRegion){ - return $query->where('sub_regiao', $subRegion); - }) - ->orderBy('created_at', 'desc') - ->paginate($limit); - - if($csv) { + ->when(! $all, function ($query, $all) { + return $query->isFire(); + })->when($isFMA, function ($query, $isFMA) { + return $query->isFMA(); + })->when($isOtherFire, function ($query, $isOtherFire) { + return $query->isOtherFire(); + })->when($concelho, function ($query, $concelho) { + return $query->where('concelho', $concelho); + })->when($subRegion, function ($query, $subRegion) { + return $query->where('sub_regiao', $subRegion); + }) + ->orderBy('created_at', 'desc') + ->paginate($limit); + + if ($csv) { $csv = 'incendios.csv'; - header('Content-Disposition: attachment; filename="' . $csv . '";'); + header('Content-Disposition: attachment; filename="'.$csv.'";'); header('Content-Type: application/csv; charset=UTF-8'); // open the "output" stream $f = fopen('php://output', 'w'); // Write utf-8 bom to the file - fputs($f, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fwrite($f, chr(0xEF).chr(0xBB).chr(0xBF)); fputcsv($f, array_keys($incidents[0]->toArray()), ';'); - foreach ($incidents as $i) { $_i = $i->toArray(); unset($_i['icnf']); @@ -77,31 +72,30 @@ public function active(Request $request): JsonResponse fputcsv($f, $_i, ';'); } - // use exit to get rid of unexpected output afterward exit(); - } else if($csv2){ + } elseif ($csv2) { $csv = 'incendios.csv'; - header('Content-Disposition: attachment; filename="' . $csv . '";'); + header('Content-Disposition: attachment; filename="'.$csv.'";'); header('Content-Type: application/csv; charset=UTF-8'); // open the "output" stream $f = fopen('php://output', 'w'); // Write utf-8 bom to the file - fputs($f, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fwrite($f, chr(0xEF).chr(0xBB).chr(0xBF)); - if(empty($incidents)){ + if (empty($incidents)) { Log::debug(json_encode($incidents)); $incidents = Incident::isActive() - ->when(!$all, function ($query, $all){ + ->when(! $all, function ($query, $all) { return $query->isFire(); - })->when($isFMA, function ($query, $isFMA){ + })->when($isFMA, function ($query, $isFMA) { return $query->isFMA(); - })->when($isOtherFire, function ($query, $isOtherFire){ + })->when($isOtherFire, function ($query, $isOtherFire) { return $query->isOtherFire(); - })->when($concelho, function ($query, $concelho){ + })->when($concelho, function ($query, $concelho) { return $query->where('concelho', $concelho); }) ->orderBy('created_at', 'desc') @@ -110,7 +104,7 @@ public function active(Request $request): JsonResponse $arr = IncidentResource::collection($incidents)->resolve(); - if(isset($arr[0])){ + if (isset($arr[0])) { $keys = $arr[0]; unset($keys['_id']); unset($keys['dateTime']); @@ -122,7 +116,6 @@ public function active(Request $request): JsonResponse fputcsv($f, array_keys($keys), ';'); - foreach ($arr as &$i) { $_i = $i; unset($_i['_id']); @@ -141,7 +134,6 @@ public function active(Request $request): JsonResponse ->orderBy('created_at', 'desc') ->paginate(1); - $arr = IncidentResource::collection($incident)->resolve(); $keys = $arr[0]; @@ -158,18 +150,18 @@ public function active(Request $request): JsonResponse } // use exit to get rid of unexpected output afterward exit(); - } else if($geoJson){ + } elseif ($geoJson) { return new JsonResponse($this->transformToGeoJSON(IncidentResource::collection($incidents))); } else { - if(env('TROLL_MODE')){ + if (env('TROLL_MODE')) { $ua = $request->userAgent(); $ref = $request->headers->get('referer'); $allowedUas = [ env('UA1'), env('UA2'), - env('UA3') + env('UA3'), ]; $allowedRefs = [ @@ -178,16 +170,16 @@ public function active(Request $request): JsonResponse 'https://beta.fogos.pt/', 'https://emergencias.pt/', 'https://www.emergencias.pt/', - 'https://sgmai.maps.arcgis.com/apps/dashboards/fc641a97229142b8a80f17af034d62a7' + 'https://sgmai.maps.arcgis.com/apps/dashboards/fc641a97229142b8a80f17af034d62a7', ]; - if(!in_array($ua, $allowedUas) || !in_array($ref,$allowedRefs)){ + if (! in_array($ua, $allowedUas) || ! in_array($ref, $allowedRefs)) { $troll = new Incident(); $troll->id = 123123123123; $troll->coords = 1; - $troll->dateTime = "2023-05-17T06:38:00.000000Z"; + $troll->dateTime = '2023-05-17T06:38:00.000000Z'; $troll->date = '17-05-2023'; - $troll->hour= '07:38'; + $troll->hour = '07:38'; $troll->location = 'Uso a API do Fogos.pt 🥁'; $troll->aerial = 100; $troll->meios_aquaticos = 100; @@ -204,24 +196,22 @@ public function active(Request $request): JsonResponse $troll->especieName = 'Utilização indevida'; $troll->familiaName = 'Utilização indevida'; $troll->statusCode = 5; - $troll->statusColor = "B81E1F"; + $troll->statusColor = 'B81E1F'; $troll->status = 'Em Curso'; $troll->important = false; $troll->localidade = 'Uso a API do Fogos.pt 🥁'; $troll->active = true; $troll->sadoId = 123123123; $troll->sharepointId = 123123123; - $troll->extra = $ua . ' => ' . $ref; + $troll->extra = $ua.' => '.$ref; $troll->disappear = false; $troll->created = '2023-05-18T07:58:09.600000Z'; $troll->updated = '2023-05-18T07:58:09.600000Z'; - $incidents[] = $troll; } } - return new JsonResponse([ 'success' => true, 'data' => IncidentResource::collection($incidents), @@ -236,8 +226,8 @@ public function activeKML(Request $request): JsonResponse $isOtherFire = $request->get('otherfire'); $concelho = $request->get('concelho'); - if($request->exists('limit')){ - $limit = (int)$request->get('limit'); + if ($request->exists('limit')) { + $limit = (int) $request->get('limit'); } else { $limit = 300; } @@ -245,25 +235,25 @@ public function activeKML(Request $request): JsonResponse $geoJson = $request->get('geojson'); $incidents = Incident::isActive() - ->when(!$all, function ($query, $all){ + ->when(! $all, function ($query, $all) { return $query->isFire(); - })->when($isFMA, function ($query, $isFMA){ + })->when($isFMA, function ($query, $isFMA) { return $query->isFMA(); - })->when($isOtherFire, function ($query, $isOtherFire){ + })->when($isOtherFire, function ($query, $isOtherFire) { return $query->isOtherFire(); - })->when($concelho, function ($query, $concelho){ + })->when($concelho, function ($query, $concelho) { return $query->where('concelho', $concelho); }) ->orderBy('created_at', 'desc') ->paginate($limit); - $r=new \XMLWriter(); + $r = new \XMLWriter(); $r->openMemory(); - $r->startDocument('1.0','UTF-8'); + $r->startDocument('1.0', 'UTF-8'); $r->startElement('kml'); $r->startElement('document'); $r->startElement('Placemark'); - foreach($incidents as $i){ + foreach ($incidents as $i) { $r->startElement('name'); $r->text($i['location']); $r->endElement(); @@ -282,24 +272,23 @@ public function activeKML(Request $request): JsonResponse $r->endElement(); // kml $newxml = $r->outputMemory(true); - echo $newxml; - die(); + exit(); } private function transformToGeoJSON($data) { $features = []; - foreach($data as $d) { - $features[] = array( + foreach ($data as $d) { + $features[] = [ 'type' => 'Feature', - 'geometry' => array('type' => 'Point', 'coordinates' => array((float)$d['lng'],(float)$d['lat'])), + 'geometry' => ['type' => 'Point', 'coordinates' => [(float) $d['lng'], (float) $d['lat']]], 'properties' => $d, - ); - }; + ]; + } - $allfeatures = array('type' => 'FeatureCollection', 'features' => $features); + $allfeatures = ['type' => 'FeatureCollection', 'features' => $features]; return $allfeatures; } @@ -312,25 +301,24 @@ public function search(IncidentSearchRequest $request) $naturezaCode = $request->get('naturezaCode'); - - if($request->exists('limit')){ - $limit = (int)$request->get('limit'); + if ($request->exists('limit')) { + $limit = (int) $request->get('limit'); } else { $limit = 50; } - if($day && ($before || $after)){ + if ($day && ($before || $after)) { abort(422); } $timeRange = false; - if($after){ + if ($after) { $after = new Carbon($after); $before = new Carbon($before); $timeRange = [$after, $before]; } - if($day){ + if ($day) { $day = new Carbon($day); } @@ -341,55 +329,54 @@ public function search(IncidentSearchRequest $request) $subRegion = $request->get('subRegion'); - - $incidents = Incident::when($day, function($query, $day){ + $incidents = Incident::when($day, function ($query, $day) { return $query->whereBetween( 'dateTime', [ Carbon::parse($day->startOfDay()), - Carbon::parse($day->endOfDay()) + Carbon::parse($day->endOfDay()), ] ); - })->when($timeRange, function($query,$timeRange){ + })->when($timeRange, function ($query, $timeRange) { return $query->whereBetween( 'dateTime', [ Carbon::parse($timeRange[0]->startOfDay()), - Carbon::parse($timeRange[1]->endOfDay()) + Carbon::parse($timeRange[1]->endOfDay()), ] ); - })->when($concelho, function($query, $concelho){ + })->when($concelho, function ($query, $concelho) { return $query->where('concelho', $concelho); - })->when(!$all, function ($query, $all){ + })->when(! $all, function ($query, $all) { return $query->isFire(); - })->when($extend, function ($query, $extend){ + })->when($extend, function ($query, $extend) { return $query->with(['history', 'statusHistory']); - })->when($isFMA, function ($query, $isFMA){ + })->when($isFMA, function ($query, $isFMA) { return $query->isFMA(); - })->when($naturezaCode, function ($query, $naturezaCode){ - return $query->where('naturezaCode', (string)$naturezaCode); - })->when($subRegion, function ($query, $subRegion){ - return $query->where('sub_regiao', (string)$subRegion); + })->when($naturezaCode, function ($query, $naturezaCode) { + return $query->where('naturezaCode', (string) $naturezaCode); + })->when($subRegion, function ($query, $subRegion) { + return $query->where('sub_regiao', (string) $subRegion); }); $csv2 = $request->get('csv2'); - if($csv2){ + if ($csv2) { $csv = 'incidents.csv'; - header('Content-Disposition: attachment; filename="' . $csv . '";'); + header('Content-Disposition: attachment; filename="'.$csv.'";'); header('Content-Type: application/csv; charset=UTF-8'); // open the "output" stream $f = fopen('php://output', 'w'); // Write utf-8 bom to the file - fputs($f, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fwrite($f, chr(0xEF).chr(0xBB).chr(0xBF)); $incidents = $incidents->get(); $arr = IncidentResource::collection($incidents)->resolve(); - if(isset($arr[0])){ + if (isset($arr[0])) { $keys = $arr[0]; unset($keys['_id']); unset($keys['dateTime']); @@ -421,7 +408,7 @@ public function search(IncidentSearchRequest $request) $paginator = [ 'currentPage' => $incidents->currentPage(), 'totalPages' => $incidents->lastPage(), - 'totalItems' => $incidents->total() + 'totalItems' => $incidents->total(), ]; return new JsonResponse([ @@ -438,10 +425,10 @@ public function kml(Request $request, $id) $incidentkml = $incident->kml; $response = new StreamedResponse(); - $response->setCallBack(function () use($incidentkml) { + $response->setCallBack(function () use ($incidentkml) { echo $incidentkml; }); - $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $incident->id . '.kml'); + $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $incident->id.'.kml'); $response->headers->set('Content-Disposition', $disposition); return $response; @@ -453,10 +440,10 @@ public function kmlVost(Request $request, $id) $incidentkml = $incident->kmlVost; $response = new StreamedResponse(); - $response->setCallBack(function () use($incidentkml) { + $response->setCallBack(function () use ($incidentkml) { echo $incidentkml; }); - $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $incident->id . '.kml'); + $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $incident->id.'.kml'); $response->headers->set('Content-Disposition', $disposition); return $response; @@ -464,8 +451,8 @@ public function kmlVost(Request $request, $id) public function burnMoreThan1000(Request $request) { - if($request->exists('limit')){ - $limit = (int)$request->get('limit'); + if ($request->exists('limit')) { + $limit = (int) $request->get('limit'); } else { $limit = 500; } @@ -477,7 +464,7 @@ public function burnMoreThan1000(Request $request) $paginator = [ 'currentPage' => $incidents->currentPage(), 'totalPages' => $incidents->lastPage(), - 'totalItems' => $incidents->total() + 'totalItems' => $incidents->total(), ]; return new JsonResponse([ @@ -491,7 +478,7 @@ public function addPosit(Request $request, $id) { $key = $request->header('key'); - if(env('API_WRITE_KEY') !== $key){ + if (env('API_WRITE_KEY') !== $key) { abort(401); } @@ -512,7 +499,7 @@ public function addKML(Request $request, $id) { $key = $request->header('key'); - if(env('API_WRITE_KEY') !== $key){ + if (env('API_WRITE_KEY') !== $key) { abort(401); } @@ -522,17 +509,15 @@ public function addKML(Request $request, $id) $incident->save(); - $url = "fogo/{$incident->id}/detalhe?aasd=" . rand(0,255); - $name = "screenshot-{$incident->id}" . rand(0,255); + $url = "fogo/{$incident->id}/detalhe?aasd=".rand(0, 255); + $name = "screenshot-{$incident->id}".rand(0, 255); $path = "/var/www/html/public/screenshots/{$name}.png"; $status = $request->post('status'); - if($status) - { + if ($status) { ScreenShotTool::takeScreenShot($url, $name, 1200, 450); - TwitterTool::tweet($status, false, $path, false, true); ScreenShotTool::removeScreenShotFile($name); diff --git a/app/Http/Controllers/LegacyController.php b/app/Http/Controllers/LegacyController.php index 2e81500..db12e05 100644 --- a/app/Http/Controllers/LegacyController.php +++ b/app/Http/Controllers/LegacyController.php @@ -18,7 +18,6 @@ use Carbon\Carbon; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use Laravel\Lumen\Routing\Controller; use voku\helper\UTF8; /** @deprecated */ @@ -29,20 +28,20 @@ public function newFires(Request $request): JsonResponse $concelho = $request->get('concelho'); $distrito = $request->get('distrito'); - $incidents = Incident::isActive()->isFire()->when($concelho, function($query, $concelho){ + $incidents = Incident::isActive()->isFire()->when($concelho, function ($query, $concelho) { return $query->where('concelho', $concelho); - })->when($distrito, function($query, $distrito){ + })->when($distrito, function ($query, $distrito) { return $query->where('district', $distrito); })->get(); - if(env('TROLL_MODE')){ + if (env('TROLL_MODE')) { $ua = $request->userAgent(); $ref = $request->headers->get('referer'); $allowedUas = [ env('UA1'), env('UA2'), - env('UA3') + env('UA3'), ]; $allowedRefs = [ @@ -51,16 +50,16 @@ public function newFires(Request $request): JsonResponse 'https://beta.fogos.pt/', 'https://emergencias.pt/', 'https://www.emergencias.pt/', - 'https://sgmai.maps.arcgis.com/apps/dashboards/fc641a97229142b8a80f17af034d62a7' + 'https://sgmai.maps.arcgis.com/apps/dashboards/fc641a97229142b8a80f17af034d62a7', ]; - if(!in_array($ua, $allowedUas) || !in_array($ref,$allowedRefs)){ + if (! in_array($ua, $allowedUas) || ! in_array($ref, $allowedRefs)) { $troll = new Incident(); $troll->id = 123123123123; $troll->coords = 1; - $troll->dateTime = "2023-05-17T06:38:00.000000Z"; + $troll->dateTime = '2023-05-17T06:38:00.000000Z'; $troll->date = '17-05-2023'; - $troll->hour= '07:38'; + $troll->hour = '07:38'; $troll->location = 'Uso a API do Fogos.pt 🥁'; $troll->aerial = 100; $troll->meios_aquaticos = 100; @@ -77,24 +76,22 @@ public function newFires(Request $request): JsonResponse $troll->especieName = 'Utilização indevida'; $troll->familiaName = 'Utilização indevida'; $troll->statusCode = 5; - $troll->statusColor = "B81E1F"; + $troll->statusColor = 'B81E1F'; $troll->status = 'Em Curso'; $troll->important = false; $troll->localidade = 'Uso a API do Fogos.pt 🥁'; $troll->active = true; $troll->sadoId = 123123123; $troll->sharepointId = 123123123; - $troll->extra = $ua . ' => ' . $ref; + $troll->extra = $ua.' => '.$ref; $troll->disappear = false; $troll->created = '2023-05-18T07:58:09.600000Z'; $troll->updated = '2023-05-18T07:58:09.600000Z'; - $incidents[] = $troll; } } - $response = new JsonResponse([ 'success' => true, 'data' => IncidentResource::collection($incidents), @@ -179,7 +176,7 @@ public function fires(Request $request) abort(404); } - public function warnings() : JsonResponse + public function warnings(): JsonResponse { $warnings = Warning::orderBy('created', 'desc') ->limit(50) @@ -233,7 +230,7 @@ public function statsWeek() $timestampLast = strtotime(date('Y-m-d 00:00')); $return = []; - for ($i = 0; $i <= 8; ++$i) { + for ($i = 0; $i <= 8; $i++) { $start = strtotime("-{$i} days", $timestampLast); $date_start = Carbon::parse($start)->startOfDay(); $date_end = Carbon::parse($start)->endOfDay(); @@ -241,7 +238,7 @@ public function statsWeek() $incidents = Incident::where('isFire', true)->where([['dateTime', '>=', $date_start], ['dateTime', '<=', $date_end]]); $_r = [ - 'label' => $date_start->format('Y-m-d', ), + 'label' => $date_start->format('Y-m-d'), 'total' => $incidents->count(), ]; $return[] = $_r; @@ -287,7 +284,6 @@ public function statsYesterday() return response()->json($response); } - public function firesDanger(Request $request) { $id = $request->get('id'); @@ -300,7 +296,6 @@ public function firesDanger(Request $request) ->orderBy('created', 'desc') ->get(); - if (isset($rcm[0])) { $rcm = $rcm[0]; $created = $rcm->created; @@ -338,7 +333,7 @@ public function firesStatus(Request $request) 'label' => $incident['date'].' '.$incident['hour'], 'status' => 'Início', 'statusCode' => 99, - 'created' => strtotime($incident['dateTime']), + 'created' => strtotime($incident['dateTime']), ]; $data = HistoryStatusResource::collection($statusHistory)->toArray($request); @@ -347,7 +342,7 @@ public function firesStatus(Request $request) return response()->json([ 'success' => true, - 'data' => $data + 'data' => $data, ]); } abort(404); @@ -418,10 +413,10 @@ private function getForStatsTimestamp($start, $end) $total = $incidents->count(); $distritos = []; foreach ($incidents as $r) { - if (!isset($distritos[$r['district']])) { + if (! isset($distritos[$r['district']])) { $distritos[$r['district']] = 1; } else { - ++$distritos[$r['district']]; + $distritos[$r['district']]++; } } @@ -443,7 +438,7 @@ private function getForBurnedArea($start, $end) $total = 0; foreach ($incidents as $r) { - $total += (float)$r['icnf']['burnArea']['total']; + $total += (float) $r['icnf']['burnArea']['total']; } return $total; @@ -456,18 +451,17 @@ private function getForMotive($start, $end) ->where([['dateTime', '>=', $start], ['dateTime', '<=', $end]]) ->get(); - $motives = []; foreach ($incidents as $r) { $key = false; - if(isset($r['icnf']['tipocausa']) && isset($r['icnf']['causafamilia'])){ - $key = $r['icnf']['tipocausa'] . ' ' . $r['icnf']['causafamilia']; + if (isset($r['icnf']['tipocausa']) && isset($r['icnf']['causafamilia'])) { + $key = $r['icnf']['tipocausa'].' '.$r['icnf']['causafamilia']; } - if($key && isset($motives[$key])){ + if ($key && isset($motives[$key])) { $motives[$key]++; - } elseif ($key){ + } elseif ($key) { $motives[$key] = 1; } } @@ -573,7 +567,7 @@ public function motivesThisMonths() { $timestampLast = Carbon::today(); $timestamp = Carbon::today()->startOfMonth(); - $data = $this->getForMotive($timestamp,$timestampLast); + $data = $this->getForMotive($timestamp, $timestampLast); $response = [ 'success' => true, @@ -656,14 +650,14 @@ public function aerial() } else { $distritos = []; foreach ($active as $r) { - if (!isset($distritos[$r['district']])) { + if (! isset($distritos[$r['district']])) { $distritos[$r['district']] = [ 'm' => $r['aerial'], 't' => 1, ]; } else { $distritos[$r['district']]['m'] += $r['aerial']; - ++$distritos[$r['district']]['t']; + $distritos[$r['district']]['t']++; } } $status = "Distrito - Meios aéreos / incêndios ativos:\r\n"; diff --git a/app/Http/Controllers/OtherController.php b/app/Http/Controllers/OtherController.php index 2a560e0..343650d 100644 --- a/app/Http/Controllers/OtherController.php +++ b/app/Http/Controllers/OtherController.php @@ -5,7 +5,6 @@ use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\RequestException; use Illuminate\Support\Facades\Redis; -use Laravel\Lumen\Routing\Controller; class OtherController extends Controller { diff --git a/app/Http/Controllers/PlanesController.php b/app/Http/Controllers/PlanesController.php index 9c515a7..4029af3 100644 --- a/app/Http/Controllers/PlanesController.php +++ b/app/Http/Controllers/PlanesController.php @@ -1,11 +1,9 @@ true, - 'data' =>$plane, + 'data' => $plane, ]); } } diff --git a/app/Http/Controllers/RCMController.php b/app/Http/Controllers/RCMController.php index f5fce21..b1e75a4 100644 --- a/app/Http/Controllers/RCMController.php +++ b/app/Http/Controllers/RCMController.php @@ -3,10 +3,9 @@ namespace App\Http\Controllers; use App\Models\RCM; +use App\Models\RCMForJS; use App\Tools\RCMTool; use Illuminate\Http\Request; -use Laravel\Lumen\Routing\Controller; -use App\Models\RCMForJS; use voku\helper\UTF8; class RCMController extends Controller @@ -69,7 +68,7 @@ public function parish(Request $request) ->limit(1) ->get(); - if (!isset($risk[0])) { + if (! isset($risk[0])) { abort(404); } diff --git a/app/Http/Controllers/StatsController.php b/app/Http/Controllers/StatsController.php index 10bba8d..d3a810f 100644 --- a/app/Http/Controllers/StatsController.php +++ b/app/Http/Controllers/StatsController.php @@ -3,11 +3,9 @@ namespace App\Http\Controllers; use App\Models\Incident; -use App\Resources\IncidentResource; use Carbon\Carbon; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use Laravel\Lumen\Routing\Controller; class StatsController extends Controller { @@ -15,28 +13,27 @@ public function ignitionsHourly(Request $request) { $day = $request->get('day'); - if($day){ + if ($day) { $day = new Carbon($day); } else { $day = Carbon::today(); } - $incidents = Incident::whereBetween( - 'dateTime', - [ - Carbon::parse($day->startOfDay()), - Carbon::parse($day->endOfDay()) - ] - ) - ->where('isFire', true) - ->get(); + 'dateTime', + [ + Carbon::parse($day->startOfDay()), + Carbon::parse($day->endOfDay()), + ] + ) + ->where('isFire', true) + ->get(); $hours = []; - foreach ($incidents as $i){ - $k = $i->dateTime->startOfHour()->hour . 'H' . ' - ' . ($i->dateTime->startOfHour()->hour + 1) . 'H'; - if(isset($hours[$k])){ + foreach ($incidents as $i) { + $k = $i->dateTime->startOfHour()->hour.'H'.' - '.($i->dateTime->startOfHour()->hour + 1).'H'; + if (isset($hours[$k])) { $hours[$k]++; } else { $hours[$k] = 1; diff --git a/app/Http/Controllers/WarningsController.php b/app/Http/Controllers/WarningsController.php index 0a6a4c0..6657342 100644 --- a/app/Http/Controllers/WarningsController.php +++ b/app/Http/Controllers/WarningsController.php @@ -3,27 +3,19 @@ namespace App\Http\Controllers; use App\Models\Warning; -use App\Models\WeatherStation; use App\Tools\FacebookTool; use App\Tools\NotificationTool; use App\Tools\TelegramTool; use App\Tools\TwitterTool; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\ClientException; -use GuzzleHttp\Exception\RequestException; -use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Redis; -use Laravel\Lumen\Routing\Controller; use Illuminate\Http\Request; - class WarningsController extends Controller { public function add(Request $request) { $key = $request->header('key'); - if(env('API_WRITE_KEY') !== $key){ + if (env('API_WRITE_KEY') !== $key) { abort(401); } @@ -35,11 +27,11 @@ public function add(Request $request) NotificationTool::sendWarningNotification($status); - $text = "ALERTA: \r\n" . $status; + $text = "ALERTA: \r\n".$status; TwitterTool::tweet($text); TelegramTool::publish($text); - $message = "ALERTA: %0A" . $status; + $message = 'ALERTA: %0A'.$status; FacebookTool::publish($message); } } diff --git a/app/Http/Controllers/WeatherController.php b/app/Http/Controllers/WeatherController.php index 0cf788c..2a2b2df 100644 --- a/app/Http/Controllers/WeatherController.php +++ b/app/Http/Controllers/WeatherController.php @@ -9,22 +9,20 @@ use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\RequestException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Redis; -use Laravel\Lumen\Routing\Controller; use Illuminate\Http\Request; - +use Illuminate\Support\Facades\Redis; class WeatherController extends Controller { public static function getMeteoByLatAndLng($lat, $lng) { if (env('APP_ENV') === 'production') { - $exists = Redis::get('weather:' . $lat . ':' . $lng); + $exists = Redis::get('weather:'.$lat.':'.$lng); if ($exists) { return json_decode($exists, true); } else { $client = self::getClient(); - $weatherUrl = self::$weatherUrl . 'lat=' . $lat . '&lon=' . $lng . '&APPID=' . env('OPENWEATHER_API') . '&units=metric&lang=pt'; + $weatherUrl = self::$weatherUrl.'lat='.$lat.'&lon='.$lng.'&APPID='.env('OPENWEATHER_API').'&units=metric&lang=pt'; try { $response = $client->request('GET', $weatherUrl); @@ -38,7 +36,8 @@ public static function getMeteoByLatAndLng($lat, $lng) $body = $response->getBody(); $result = json_decode($body->getContents(), true); - Redis::set('weather:' . $lat . ':' . $lng, json_encode($result), 'EX', 10800); + Redis::set('weather:'.$lat.':'.$lng, json_encode($result), 'EX', 10800); + return $result; } } @@ -85,9 +84,9 @@ public function stations(Request $request) $id = $request->get('id'); $place = $request->get('place'); - if($id){ - $station = WeatherStation::where('id', (int)$id)->get(); - } elseif($place){ + if ($id) { + $station = WeatherStation::where('id', (int) $id)->get(); + } elseif ($place) { $station = WeatherStation::where('place', $place)->get(); } else { $station = WeatherStation::all(); @@ -102,11 +101,10 @@ public function stations(Request $request) public function daily(Request $request) { - if(!$request->exists('date')){ + if (! $request->exists('date')) { abort(410); } - $date = $request->get('date'); $date = new Carbon($date); @@ -135,8 +133,8 @@ public function ipmaServicesHTTPS() $result = $body->getContents(); $data = str_replace('http://', 'https://', $result); - header("Content-Type: application/xml; charset=utf-8"); + header('Content-Type: application/xml; charset=utf-8'); echo $data; - die(); + exit(); } } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php new file mode 100644 index 0000000..d3722c2 --- /dev/null +++ b/app/Http/Kernel.php @@ -0,0 +1,67 @@ + + */ + protected $middleware = [ + // \App\Http\Middleware\TrustHosts::class, + \App\Http\Middleware\TrustProxies::class, + \Fruitcake\Cors\HandleCors::class, + \App\Http\Middleware\PreventRequestsDuringMaintenance::class, + \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, + \App\Http\Middleware\TrimStrings::class, + \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, + ]; + + /** + * The application's route middleware groups. + * + * @var array> + */ + protected $middlewareGroups = [ + 'web' => [ + \App\Http\Middleware\EncryptCookies::class, + \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, + \Illuminate\Session\Middleware\StartSession::class, + // \Illuminate\Session\Middleware\AuthenticateSession::class, + \Illuminate\View\Middleware\ShareErrorsFromSession::class, + \App\Http\Middleware\VerifyCsrfToken::class, + \Illuminate\Routing\Middleware\SubstituteBindings::class, + ], + + 'api' => [ + // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, + 'throttle:api', + \Illuminate\Routing\Middleware\SubstituteBindings::class, + ], + ]; + + /** + * The application's route middleware. + * + * These middleware may be assigned to groups or used individually. + * + * @var array + */ + protected $routeMiddleware = [ + 'auth' => \App\Http\Middleware\Authenticate::class, + 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, + 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, + 'can' => \Illuminate\Auth\Middleware\Authorize::class, + 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, + 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, + 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, + 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, + 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, + ]; +} diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index 4f6c380..704089a 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -2,40 +2,20 @@ namespace App\Http\Middleware; -use Closure; -use Illuminate\Contracts\Auth\Factory as Auth; +use Illuminate\Auth\Middleware\Authenticate as Middleware; -class Authenticate +class Authenticate extends Middleware { /** - * The authentication guard factory instance. + * Get the path the user should be redirected to when they are not authenticated. * - * @var \Illuminate\Contracts\Auth\Factory + * @param \Illuminate\Http\Request $request + * @return string|null */ - protected $auth; - - /** - * Create a new middleware instance. - */ - public function __construct(Auth $auth) + protected function redirectTo($request) { - $this->auth = $auth; - } - - /** - * Handle an incoming request. - * - * @param \Illuminate\Http\Request $request - * @param null|string $guard - * - * @return mixed - */ - public function handle($request, Closure $next, $guard = null) - { - if ($this->auth->guard($guard)->guest()) { - return response('Unauthorized.', 401); + if (! $request->expectsJson()) { + return route('login'); } - - return $next($request); } } diff --git a/app/Http/Middleware/EncryptCookies.php b/app/Http/Middleware/EncryptCookies.php new file mode 100644 index 0000000..867695b --- /dev/null +++ b/app/Http/Middleware/EncryptCookies.php @@ -0,0 +1,17 @@ + + */ + protected $except = [ + // + ]; +} diff --git a/app/Http/Middleware/PreventRequestsDuringMaintenance.php b/app/Http/Middleware/PreventRequestsDuringMaintenance.php new file mode 100644 index 0000000..74cbd9a --- /dev/null +++ b/app/Http/Middleware/PreventRequestsDuringMaintenance.php @@ -0,0 +1,17 @@ + + */ + protected $except = [ + // + ]; +} diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php new file mode 100644 index 0000000..4e7c24b --- /dev/null +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -0,0 +1,31 @@ +check()) { + return redirect(RouteServiceProvider::HOME); + } + } + + return $next($request); + } +} diff --git a/app/Http/Middleware/TrimStrings.php b/app/Http/Middleware/TrimStrings.php new file mode 100644 index 0000000..88cadca --- /dev/null +++ b/app/Http/Middleware/TrimStrings.php @@ -0,0 +1,19 @@ + + */ + protected $except = [ + 'current_password', + 'password', + 'password_confirmation', + ]; +} diff --git a/app/Http/Middleware/TrustHosts.php b/app/Http/Middleware/TrustHosts.php new file mode 100644 index 0000000..7186414 --- /dev/null +++ b/app/Http/Middleware/TrustHosts.php @@ -0,0 +1,20 @@ + + */ + public function hosts() + { + return [ + $this->allSubdomainsOfApplicationUrl(), + ]; + } +} diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php new file mode 100644 index 0000000..3391630 --- /dev/null +++ b/app/Http/Middleware/TrustProxies.php @@ -0,0 +1,28 @@ +|string|null + */ + protected $proxies; + + /** + * The headers that should be used to detect proxies. + * + * @var int + */ + protected $headers = + Request::HEADER_X_FORWARDED_FOR | + Request::HEADER_X_FORWARDED_HOST | + Request::HEADER_X_FORWARDED_PORT | + Request::HEADER_X_FORWARDED_PROTO | + Request::HEADER_X_FORWARDED_AWS_ELB; +} diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php new file mode 100644 index 0000000..9e86521 --- /dev/null +++ b/app/Http/Middleware/VerifyCsrfToken.php @@ -0,0 +1,17 @@ + + */ + protected $except = [ + // + ]; +} diff --git a/app/Http/Requests/IncidentSearchRequest.php b/app/Http/Requests/IncidentSearchRequest.php index 605de61..3c57074 100644 --- a/app/Http/Requests/IncidentSearchRequest.php +++ b/app/Http/Requests/IncidentSearchRequest.php @@ -8,8 +8,6 @@ class IncidentSearchRequest extends FormRequest { /** * Determine if the user is authorized to make this request. - * - * @return bool */ protected function authorize(): bool { @@ -18,8 +16,6 @@ protected function authorize(): bool /** * Get the validation rules that apply to the request. - * - * @return array */ protected function rules(): array { @@ -29,7 +25,7 @@ protected function rules(): array 'day' => 'date_format:Y-m-d', 'before' => 'date_format:Y-m-d', 'after' => 'date_format:Y-m-d', - 'extend' => 'boolean' + 'extend' => 'boolean', ]; } } diff --git a/app/Jobs/CheckImportantFireIncident.php b/app/Jobs/CheckImportantFireIncident.php index fac8fb3..602c0b4 100644 --- a/app/Jobs/CheckImportantFireIncident.php +++ b/app/Jobs/CheckImportantFireIncident.php @@ -9,11 +9,10 @@ use App\Tools\NotificationTool; use App\Tools\TelegramTool; use App\Tools\TwitterTool; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldBeUnique; -use Illuminate\Support\Facades\Log; +use Illuminate\Contracts\Queue\ShouldQueue; -class CheckImportantFireIncident extends Job implements ShouldQueue, ShouldBeUnique +class CheckImportantFireIncident extends Job implements ShouldBeUnique, ShouldQueue { /** * Create a new job instance. @@ -37,17 +36,14 @@ public function handle() ->where('sentCheckImportant', false) ->get(); - - foreach ($incidents as $incident) { - if(isset($incidents->sentCheckImportant) && $incidents->sentCheckImportant){ + if (isset($incidents->sentCheckImportant) && $incidents->sentCheckImportant) { return; } $totalAssets = $incident->aerial + $incident->terrain; - - if ($totalAssets > (int)env('IMPORTANT_INCIDENT_TOTAL_ASSETS')) { + if ($totalAssets > (int) env('IMPORTANT_INCIDENT_TOTAL_ASSETS')) { $timestampLast = time(); $timestampLast = strtotime('-3 hours', $timestampLast); diff --git a/app/Jobs/CheckIsActive.php b/app/Jobs/CheckIsActive.php index 80e8a01..69896b7 100644 --- a/app/Jobs/CheckIsActive.php +++ b/app/Jobs/CheckIsActive.php @@ -9,12 +9,13 @@ class CheckIsActive extends Job { public $data; + public $activeIds; /** * Create a new job instance. * - * @param mixed $data + * @param mixed $data */ public function __construct($data) { diff --git a/app/Jobs/CheckNewWarning.php b/app/Jobs/CheckNewWarning.php index e363b53..9b3862b 100644 --- a/app/Jobs/CheckNewWarning.php +++ b/app/Jobs/CheckNewWarning.php @@ -1,10 +1,7 @@ where([['dateTime', '>=', $start], ['dateTime', '<=', $end]]) ->get(); - $totalBurnArea = 0; $total = 0; $maxMan = 0; @@ -40,23 +38,23 @@ public function handle() foreach ($incidents as $r) { $total += 1; - if(isset($r['icnf']) && isset($r['icnf']['burnArea']) && isset($r['icnf']['burnArea']['total'])){ - $totalBurnArea += (float)$r['icnf']['burnArea']['total']; + if (isset($r['icnf']) && isset($r['icnf']['burnArea']) && isset($r['icnf']['burnArea']['total'])) { + $totalBurnArea += (float) $r['icnf']['burnArea']['total']; } $history = $r->history()->get()->toArray(); - if(!empty($history)){ - if(!empty(array_column($history, 'man'))){ - $maxMan += max(array_column($history, 'man')) ; + if (! empty($history)) { + if (! empty(array_column($history, 'man'))) { + $maxMan += max(array_column($history, 'man')); } - if(!empty(array_column($history, 'terrain'))){ - $maxCars += max(array_column($history, 'terrain')) ; + if (! empty(array_column($history, 'terrain'))) { + $maxCars += max(array_column($history, 'terrain')); } - if(!empty(array_column($history, 'aerial'))){ - $maxPlanes += max(array_column($history, 'aerial')) ; + if (! empty(array_column($history, 'aerial'))) { + $maxPlanes += max(array_column($history, 'aerial')); } } } diff --git a/app/Jobs/HandleANEPCImportantData.php b/app/Jobs/HandleANEPCImportantData.php index e35e42e..7aca0e0 100644 --- a/app/Jobs/HandleANEPCImportantData.php +++ b/app/Jobs/HandleANEPCImportantData.php @@ -30,19 +30,19 @@ public function handle() $options = [ 'headers' => [ 'User-Agent' => 'Fogos.pt/3.0', - 'Accept' => 'application/json; odata=verbose' + 'Accept' => 'application/json; odata=verbose', ], 'verify' => false, ]; - try{ + try { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', $url, $options); $data = $res->getBody()->getContents(); - } - catch(\GuzzleHttp\Exception\RequestException $e) { + } catch (\GuzzleHttp\Exception\RequestException $e) { Log::error('Error occurred in request.', ['url' => $url, 'statusCode' => $e->getCode(), 'message' => $e->getMessage()]); + return; } @@ -57,16 +57,16 @@ public function handle() $rows = $tables->item(0)->getElementsByTagName('tr'); $i = 0; - $fires = array(); + $fires = []; foreach ($rows as $row) { - if($i !== 0){ + if ($i !== 0) { $cols = $row->getElementsByTagName('td'); $j = 0; $fire = []; - foreach($cols as $col){ - switch ($j){ + foreach ($cols as $col) { + switch ($j) { case 0: $fire['id'] = $col->nodeValue; break; @@ -86,7 +86,7 @@ public function handle() $i++; } - foreach($fires as $fire){ + foreach ($fires as $fire) { $incident = Incident::where('id', $fire['id'])->get()[0]; $incident->pco = $fire['pco']; diff --git a/app/Jobs/HandleANEPCPositEmail.php b/app/Jobs/HandleANEPCPositEmail.php index 4c5e700..51ed839 100644 --- a/app/Jobs/HandleANEPCPositEmail.php +++ b/app/Jobs/HandleANEPCPositEmail.php @@ -3,7 +3,6 @@ namespace App\Jobs; use App\Models\Incident; -use Illuminate\Support\Facades\Log; use PhpImap\Mailbox; use voku\helper\UTF8; @@ -36,19 +35,20 @@ public function handle() try { $mailsIds = $mailbox->searchMailbox('UNSEEN'); - } catch(PhpImap\Exceptions\ConnectionException $ex) { - echo "IMAP connection failed: " . implode(",", $ex->getErrors('all')); + } catch (PhpImap\Exceptions\ConnectionException $ex) { + echo 'IMAP connection failed: '.implode(',', $ex->getErrors('all')); + return; } - if(!$mailsIds) { + if (! $mailsIds) { return; } - foreach($mailsIds as $mailId){ + foreach ($mailsIds as $mailId) { $mail = $mailbox->getMail($mailId); - if($mail->fromAddress === env('MAIL_ANEPC_FROM')){ + if ($mail->fromAddress === env('MAIL_ANEPC_FROM')) { $content = $mail->textHtml; $dom = new \DOMDocument(); @@ -59,27 +59,27 @@ public function handle() $rows = $tables->item(0)->getElementsByTagName('tr'); - $fires = array(); + $fires = []; foreach ($rows as $row) { $cols = $row->getElementsByTagName('td'); $j = 0; $fire = []; - foreach($cols as $col){ + foreach ($cols as $col) { - switch ($j){ + switch ($j) { case 0: $fire['id'] = $col->nodeValue; break; case 11: - $fire['heliFight'] = (int)$col->nodeValue; + $fire['heliFight'] = (int) $col->nodeValue; break; case 12: - $fire['planeFight'] = (int)$col->nodeValue; + $fire['planeFight'] = (int) $col->nodeValue; break; case 13: - $fire['heliCoord'] = (int)$col->nodeValue; + $fire['heliCoord'] = (int) $col->nodeValue; break; case 15: $fire['cos'] = UTF8::fix_utf8($col->nodeValue); @@ -95,7 +95,7 @@ public function handle() } } - foreach($fires as $fire){ + foreach ($fires as $fire) { $incident = Incident::where('id', $fire['id'])->get()[0]; $incident->pco = $fire['pco']; diff --git a/app/Jobs/HandleHJProject.php b/app/Jobs/HandleHJProject.php index 7cbd010..9c7fffb 100644 --- a/app/Jobs/HandleHJProject.php +++ b/app/Jobs/HandleHJProject.php @@ -3,14 +3,13 @@ namespace App\Jobs; use App\Models\Incident; -use Illuminate\Support\Facades\Log; -use PhpImap\Mailbox; -use voku\helper\UTF8; class HandleHJProject extends Job { public $incident; + public $telegramChannel; + /** * Create a new job instance. * @@ -40,7 +39,7 @@ public function handle() $data = [ 'chat_id' => env('HL_PROJECT_TELEGRAM_CHANNEL'), 'text' => $status, - 'message_thread_id' => $this->telegramChannel + 'message_thread_id' => $this->telegramChannel, ]; file_get_contents("https://api.telegram.org/bot{$apiToken}/sendMessage?".http_build_query($data)); diff --git a/app/Jobs/HandleNewIncidentEmergenciasSocialMedia.php b/app/Jobs/HandleNewIncidentEmergenciasSocialMedia.php index cc9aaba..ea3eeff 100644 --- a/app/Jobs/HandleNewIncidentEmergenciasSocialMedia.php +++ b/app/Jobs/HandleNewIncidentEmergenciasSocialMedia.php @@ -6,8 +6,6 @@ use App\Tools\FacebookTool; use App\Tools\HashTagTool; use App\Tools\NotificationTool; -use App\Tools\ScreenShotTool; -use App\Tools\TelegramTool; use App\Tools\TwitterTool; class HandleNewIncidentEmergenciasSocialMedia extends Job @@ -34,7 +32,6 @@ public function handle() $status = "⚠🚨 Nova emergência em {$this->incident->location} - {$this->incident->natureza} {$hashTag} 🚨⚠"; $statusFb = "⚠🚨 Nova emergência em {$this->incident->location} - {$this->incident->natureza} 🚨⚠"; - //$lastTweetId = TwitterTool::tweet($status, $this->incident->lastTweetId, false, true); //$this->incident->lastTweetId = $lastTweetId; diff --git a/app/Jobs/HandleNewIncidentSocialMedia.php b/app/Jobs/HandleNewIncidentSocialMedia.php index 102afb2..7b3727b 100644 --- a/app/Jobs/HandleNewIncidentSocialMedia.php +++ b/app/Jobs/HandleNewIncidentSocialMedia.php @@ -33,7 +33,7 @@ public function handle() $hashTag = HashTagTool::getHashTag($this->incident->concelho); $url = "fogo/{$this->incident->id}/detalhe"; - $name = "screenshot-{$this->incident->id}" . rand(0,255); + $name = "screenshot-{$this->incident->id}".rand(0, 255); $path = "/var/www/html/public/screenshots/{$name}.png"; ScreenShotTool::takeScreenShot($url, $name); @@ -49,7 +49,7 @@ public function handle() $urlImage = "https://api-dev.fogos.pt/screenshots/{$name}.png"; - FacebookTool::publishWithImage($status,$urlImage); + FacebookTool::publishWithImage($status, $urlImage); TelegramTool::publish($status); BlueskyTool::publish($status); diff --git a/app/Jobs/HourlySummary.php b/app/Jobs/HourlySummary.php index 34c618b..895c966 100644 --- a/app/Jobs/HourlySummary.php +++ b/app/Jobs/HourlySummary.php @@ -55,7 +55,7 @@ public function handle() $statusf = "{$date} - {$total} {$incendio} em curso. Meios Mobilizados:%0A👩‍ {$man}%0A🚒 {$cars}%0A🚁 {$areal} %0A"; } - if($incidentsNotActive->count() === 0){ + if ($incidentsNotActive->count() === 0) { $status .= ' https://fogos.pt #FogosPT #Status'; $statusf .= ' https://fogos.pt #FogosPT #Status'; } else { @@ -76,7 +76,7 @@ public function handle() } $url = 'estatisticas?phantom=1'; - $name = 'stats' . rand(0,255); + $name = 'stats'.rand(0, 255); $path = "/var/www/html/public/screenshots/{$name}.png"; $urlImage = "https://api-dev.fogos.pt/screenshots/{$name}.png"; diff --git a/app/Jobs/ProcessANPCAllData.php b/app/Jobs/ProcessANPCAllData.php index ab2e02b..a2172ff 100644 --- a/app/Jobs/ProcessANPCAllData.php +++ b/app/Jobs/ProcessANPCAllData.php @@ -4,12 +4,12 @@ use App\Models\Incident; use Carbon\Carbon; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldBeUnique; +use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Log; use voku\helper\UTF8; -class ProcessANPCAllData extends Job implements ShouldQueue, ShouldBeUnique +class ProcessANPCAllData extends Job implements ShouldBeUnique, ShouldQueue { /** * Create a new job instance. @@ -51,14 +51,15 @@ public function handle() Log::channel('anepc')->debug(json_encode($incidents)); - if(empty($incidents)){ + if (empty($incidents)) { Log::debug('empty incidents retuning'); + return; } $this->handleIncidents($incidents); - if($res->getStatusCode() === 200){ + if ($res->getStatusCode() === 200) { dispatch(new CheckIsActive($incidents)); } @@ -110,7 +111,7 @@ private function prepareData($data, $create = false) $isTransportFire = in_array($data['Natureza']['Codigo'], Incident::NATUREZA_CODE_TRANSPORT_FIRE); $isUrbanFire = in_array($data['Natureza']['Codigo'], Incident::NATUREZA_CODE_URBAN_FIRE); $isOtherFire = in_array($data['Natureza']['Codigo'], Incident::NATUREZA_CODE_OTHER_FIRE); - $isOtherIncident = !$isFire && !$isTransportFire && !$isUrbanFire && !$isOtherFire; + $isOtherIncident = ! $isFire && ! $isTransportFire && ! $isUrbanFire && ! $isOtherFire; $isFMA = in_array($data['Natureza']['Codigo'], Incident::NATUREZA_CODE_FMA); @@ -148,10 +149,10 @@ private function prepareData($data, $create = false) 'isTransporteFire' => $isTransportFire, 'isOtherFire' => $isOtherFire, 'isOtherIncident' => $isOtherIncident, - 'isFMA' => $isFMA + 'isFMA' => $isFMA, ]; - if($create){ + if ($create) { $data['important'] = false; $data['heliFight'] = 0; $data['heliCoord'] = 0; diff --git a/app/Jobs/ProcessANPCAllDataV2.php b/app/Jobs/ProcessANPCAllDataV2.php index fd58225..efcaad9 100644 --- a/app/Jobs/ProcessANPCAllDataV2.php +++ b/app/Jobs/ProcessANPCAllDataV2.php @@ -6,10 +6,9 @@ use App\Models\Location; use App\Tools\DiscordTool; use Carbon\Carbon; +use GuzzleHttp\Exception\ClientException; use Illuminate\Support\Facades\Log; use voku\helper\UTF8; -use GuzzleHttp\Exception\ClientException; - class ProcessANPCAllDataV2 extends Job { @@ -32,21 +31,19 @@ public function handle() { $url = env('ANEPC_API_URL'); - - $options = [ 'headers' => [ 'User-Agent' => 'Fogos.pt/3.0', - 'Authorization' => 'Basic ' . base64_encode(env('ANEPC_API_USERNAME') . ':' .env('ANEPC_API_PASSWORD')) + 'Authorization' => 'Basic '.base64_encode(env('ANEPC_API_USERNAME').':'.env('ANEPC_API_PASSWORD')), ], ]; - if(env('PROXY_ENABLE')){ + if (env('PROXY_ENABLE')) { $options['proxy'] = env('PROXY_URL'); } - try{ + try { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', $url, $options); } catch (ClientException $e) { @@ -57,17 +54,17 @@ public function handle() return; } - $incidents = json_decode($res->getBody(), true); - if(empty($incidents)){ + if (empty($incidents)) { Log::debug('empty incidents retuning'); + return; } $this->handleIncidents($incidents); - if($res->getStatusCode() === 200){ + if ($res->getStatusCode() === 200) { dispatch(new CheckIsActive($incidents)); } @@ -104,25 +101,25 @@ private function createIncident($data) private function prepareData($data, $create = false) { - if($data['outra_localizacao'] === 'Espanha'){ + if ($data['outra_localizacao'] === 'Espanha') { $locationData = [ 'DICO' => '00', - 'distrito' => 'Espanha' + 'distrito' => 'Espanha', ]; $data['concelho'] = 'Espanha'; $data['freguesia'] = 'Espanha'; } else { - $locationData = $this->getLocationData($data['concelho'],$data['numero_sado']); + $locationData = $this->getLocationData($data['concelho'], $data['numero_sado']); } - if(strlen($locationData['DICO']) !== 4){ - $locationData['DICO'] = '0' . $locationData['DICO']; + if (strlen($locationData['DICO']) !== 4) { + $locationData['DICO'] = '0'.$locationData['DICO']; } $distrito = UTF8::ucwords(mb_strtolower($locationData['distrito'])); $concelho = $data['concelho']; $freguesia = UTF8::ucwords(mb_strtolower($data['freguesia'])); - $localidade = UTF8::ucwords(mb_strtolower($data['local'] . ' ' . $data['outra_localizacao'])); + $localidade = UTF8::ucwords(mb_strtolower($data['local'].' '.$data['outra_localizacao'])); $man = $data['operacionais']; @@ -132,7 +129,7 @@ private function prepareData($data, $create = false) $isTransportFire = in_array($data['codigo_natureza'], Incident::NATUREZA_CODE_TRANSPORT_FIRE); $isUrbanFire = in_array($data['codigo_natureza'], Incident::NATUREZA_CODE_URBAN_FIRE); $isOtherFire = in_array($data['codigo_natureza'], Incident::NATUREZA_CODE_OTHER_FIRE); - $isOtherIncident = !$isFire && !$isTransportFire && !$isUrbanFire && !$isOtherFire; + $isOtherIncident = ! $isFire && ! $isTransportFire && ! $isUrbanFire && ! $isOtherFire; $isFMA = in_array($data['codigo_natureza'], Incident::NATUREZA_CODE_FMA); @@ -171,10 +168,10 @@ private function prepareData($data, $create = false) 'isOtherIncident' => $isOtherIncident, 'isFMA' => $isFMA, 'regiao' => $data['regiao'], - 'sub_regiao' => $data['sub_regiao'] + 'sub_regiao' => $data['sub_regiao'], ]; - if($create){ + if ($create) { $point['important'] = false; $point['heliFight'] = 0; $point['heliCoord'] = 0; @@ -184,44 +181,45 @@ private function prepareData($data, $create = false) $point['important'] = @$data['significativa']; } - if($point['status'] === 'Despacho de 1.º Alerta'){ + if ($point['status'] === 'Despacho de 1.º Alerta') { $point['status'] = 'Despacho de 1º Alerta'; // fix para a app } return $point; } - private function getLocationData($concelho, $x) { $location = Location::where('name', $concelho)->where('level', 2)->get(); - if(!isset($location[0])){ - DiscordTool::postError('Concelho not found => ' . $concelho . ' => ' . $x); - Log::debug('Concelho not found => ' . $concelho . ' => ' . $x); + if (! isset($location[0])) { + DiscordTool::postError('Concelho not found => '.$concelho.' => '.$x); + Log::debug('Concelho not found => '.$concelho.' => '.$x); + return; } $location = $location[0]; - $distritoCode = (string)$location->code; + $distritoCode = (string) $location->code; - if(strlen($distritoCode) === 3){ - $distritoCode = (int) substr($distritoCode,0,1); + if (strlen($distritoCode) === 3) { + $distritoCode = (int) substr($distritoCode, 0, 1); } else { - $distritoCode = (int) substr($distritoCode,0,2); + $distritoCode = (int) substr($distritoCode, 0, 2); } $distrito = Location::where('level', 1)->where('code', $distritoCode)->get(); - if(!isset($distrito[0])){ - DiscordTool::postError('Distrito code not found => ' . $distritoCode); + if (! isset($distrito[0])) { + DiscordTool::postError('Distrito code not found => '.$distritoCode); + return; } $l = [ 'DICO' => $location->code, - 'distrito' => $distrito[0]->name + 'distrito' => $distrito[0]->name, ]; return $l; diff --git a/app/Jobs/ProcessICNFFireData.php b/app/Jobs/ProcessICNFFireData.php index 6f65c61..5a2e377 100644 --- a/app/Jobs/ProcessICNFFireData.php +++ b/app/Jobs/ProcessICNFFireData.php @@ -10,7 +10,6 @@ use App\Tools\ScreenShotTool; use App\Tools\TelegramTool; use App\Tools\TwitterTool; -use GuzzleHttp\Client; use Illuminate\Support\Facades\Log; class ProcessICNFFireData extends Job @@ -39,14 +38,14 @@ public function handle() 'verify' => false, ]; - try{ + try { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', $url, $options); $data = $res->getBody()->getContents(); - } - catch(\GuzzleHttp\Exception\RequestException $e) { + } catch (\GuzzleHttp\Exception\RequestException $e) { Log::error('Error occurred in request.', ['url' => $url, 'statusCode' => $e->getCode(), 'message' => $e->getMessage()]); + return; } @@ -54,7 +53,7 @@ public function handle() $data = $xml->CODIGO; - if (!$data) { + if (! $data) { return; } @@ -71,9 +70,8 @@ public function handle() 'total' => (float) $data->AREATOTAL->__toString(), ]; - - if (!isset($this->incident->icnf['burnArea'])) { - if($totalBurned !== 0){ + if (! isset($this->incident->icnf['burnArea'])) { + if ($totalBurned !== 0) { $notifyBurn = true; } } @@ -87,62 +85,62 @@ public function handle() $icnfData['reacendimentos'] = (bool) $data->REACENDIMENTOS->__toString(); } - if (isset($data->QUEIMADA) && boolval((int)$data->QUEIMADA->__toString())) { - $icnfData['queimada'] = boolval((int)$data->QUEIMADA->__toString()); + if (isset($data->QUEIMADA) && boolval((int) $data->QUEIMADA->__toString())) { + $icnfData['queimada'] = boolval((int) $data->QUEIMADA->__toString()); } - if (isset($data->FALSOALARME) && boolval((int)$data->FALSOALARME->__toString())) { - $icnfData['falsoalarme'] = boolval((int)$data->FALSOALARME->__toString()); + if (isset($data->FALSOALARME) && boolval((int) $data->FALSOALARME->__toString())) { + $icnfData['falsoalarme'] = boolval((int) $data->FALSOALARME->__toString()); } - if (isset($data->FOGACHO) && boolval((int)$data->FOGACHO->__toString())) { - $icnfData['fogacho'] = boolval((int)$data->FOGACHO->__toString()); + if (isset($data->FOGACHO) && boolval((int) $data->FOGACHO->__toString())) { + $icnfData['fogacho'] = boolval((int) $data->FOGACHO->__toString()); } - if (isset($data->INCENDIO) && boolval((int)$data->INCENDIO->__toString())) { - $icnfData['incendio'] = boolval((int)$data->INCENDIO->__toString()); + if (isset($data->INCENDIO) && boolval((int) $data->INCENDIO->__toString())) { + $icnfData['incendio'] = boolval((int) $data->INCENDIO->__toString()); } - if (isset($data->AGRICOLA) && boolval((int)$data->AGRICOLA->__toString())) { - $icnfData['agricola'] = boolval((int)$data->AGRICOLA->__toString()); + if (isset($data->AGRICOLA) && boolval((int) $data->AGRICOLA->__toString())) { + $icnfData['agricola'] = boolval((int) $data->AGRICOLA->__toString()); } - if (isset($data->QUEIMA) && boolval((int)$data->QUEIMA->__toString())) { - $icnfData['queima'] = boolval((int)$data->QUEIMA->__toString()); + if (isset($data->QUEIMA) && boolval((int) $data->QUEIMA->__toString())) { + $icnfData['queima'] = boolval((int) $data->QUEIMA->__toString()); } $notifyFonte = false; - if (isset($data->FONTEALERTA) && !empty((string) $data->FONTEALERTA->__toString())) { + if (isset($data->FONTEALERTA) && ! empty((string) $data->FONTEALERTA->__toString())) { $icnfData['fontealerta'] = (string) $data->FONTEALERTA; - if (!isset($this->incident->icnf['fontealerta']) || (isset($this->incident->icnf['fontealerta']) && $this->incident->icnf['fontealerta'] !== (string) $data->FONTEALERTA->__toString())) { + if (! isset($this->incident->icnf['fontealerta']) || (isset($this->incident->icnf['fontealerta']) && $this->incident->icnf['fontealerta'] !== (string) $data->FONTEALERTA->__toString())) { $notifyFonte = true; } } $notifyCausa = false; - if (isset($data->CAUSA) && !empty((string) $data->CAUSA->__toString())) { + if (isset($data->CAUSA) && ! empty((string) $data->CAUSA->__toString())) { $icnfData['causa'] = (string) $data->CAUSA; - if (!isset($this->incident->icnf['causa']) || (isset($this->incident->icnf['causa']) && $this->incident->icnf['causa'] !== (string) $data->CAUSA->__toString())) { + if (! isset($this->incident->icnf['causa']) || (isset($this->incident->icnf['causa']) && $this->incident->icnf['causa'] !== (string) $data->CAUSA->__toString())) { $notifyCausa = true; } } - if (isset($data->TIPOCAUSA) && !empty((string) $data->TIPOCAUSA)) { + if (isset($data->TIPOCAUSA) && ! empty((string) $data->TIPOCAUSA)) { $icnfData['tipocausa'] = (string) $data->TIPOCAUSA; } - if (isset($data->CAUSAFAMILIA) && !empty((string) $data->CAUSAFAMILIA)) { + if (isset($data->CAUSAFAMILIA) && ! empty((string) $data->CAUSAFAMILIA)) { $icnfData['causafamilia'] = (string) $data->CAUSAFAMILIA; } $kmlUrl = false; - if (isset($data->AREASFICHEIROS_GNR) && !empty((string) $data->AREASFICHEIROS_GNR->__toString())) { + if (isset($data->AREASFICHEIROS_GNR) && ! empty((string) $data->AREASFICHEIROS_GNR->__toString())) { $kmlUrl = (string) $data->AREASFICHEIROS_GNR; } - if (isset($data->AREASFICHEIROS_GTF) && !empty((string) $data->AREASFICHEIROS_GTF->__toString())) { + if (isset($data->AREASFICHEIROS_GTF) && ! empty((string) $data->AREASFICHEIROS_GTF->__toString())) { $kmlUrl = (string) $data->AREASFICHEIROS_GTF; } @@ -152,10 +150,9 @@ public function handle() $res = $client->request('GET', $kmlUrl, $options); $kml = $res->getBody()->getContents(); - - if (!isset($this->incident->kml)) { + if (! isset($this->incident->kml)) { $notifyKML = true; - } else if (isset($this->incident->kml) && empty($this->incident->kml)) { + } elseif (isset($this->incident->kml) && empty($this->incident->kml)) { $notifyKML = true; } @@ -192,7 +189,7 @@ public function handle() NotificationTool::send($notification, $this->incident->location, $this->incident->id); $url = "fogo/{$this->incident->id}/detalhe"; - $name = "screenshot-{$this->incident->id}" . rand(0,255); + $name = "screenshot-{$this->incident->id}".rand(0, 255); $path = "/var/www/html/public/screenshots/{$name}.png"; ScreenShotTool::takeScreenShot($url, $name); @@ -213,7 +210,7 @@ public function handle() $status = "ℹ🗺 Area ardida disponível https://{$domain}/fogo/{$this->incident->id}/detalhe {$hashTag} #FogosPT 🗺ℹ"; $url = "fogo/{$this->incident->id}/detalhe"; - $name = "screenshot-{$this->incident->id}" . rand(0,255); + $name = "screenshot-{$this->incident->id}".rand(0, 255); $path = "/var/www/html/public/screenshots/{$name}.png"; ScreenShotTool::takeScreenShot($url, $name); @@ -229,14 +226,14 @@ public function handle() ScreenShotTool::removeScreenShotFile($name); } - if($notifyBurn){ + if ($notifyBurn) { $this->updateIncident(); - if($totalBurned > 0.5){ + if ($totalBurned > 0.5) { $status = "ℹ Total de área ardida: {$totalBurned} ha https://{$domain}/fogo/{$this->incident->id}/detalhe {$hashTag} #FogosPT ℹ"; $url = "fogo/{$this->incident->id}/detalhe"; - $name = "screenshot-{$this->incident->id}" . rand(0,255); + $name = "screenshot-{$this->incident->id}".rand(0, 255); $path = "/var/www/html/public/screenshots/{$name}.png"; ScreenShotTool::takeScreenShot($url, $name); diff --git a/app/Jobs/ProcessICNFPDF.php b/app/Jobs/ProcessICNFPDF.php index 5f4c63a..db7f607 100644 --- a/app/Jobs/ProcessICNFPDF.php +++ b/app/Jobs/ProcessICNFPDF.php @@ -11,12 +11,13 @@ class ProcessICNFPDF extends Job implements ShouldQueue { public $incident; + public $url; /** * Create a new job instance. * - * @param mixed $url + * @param mixed $url */ public function __construct(Incident $incident, $url) { @@ -69,12 +70,12 @@ public function handle() } $this->incident->save(); - ++$i; + $i++; } $domain = env('SOCIAL_LINK_DOMAIN'); - if (!$cbvExists) { + if (! $cbvExists) { $hashtag = HashTagTool::getHashTag($this->incident->concelho); $status = "ℹ Incêndio na área de actuação própria do {$this->incident->cbv} https://{$domain}/fogo/{$this->incident->id} {$hashtag} ℹ"; $lastTweetId = TwitterTool::tweet($status, $this->incident->lastTweetId); @@ -82,7 +83,7 @@ public function handle() $this->incident->save(); } - if (!$alertFromExists) { + if (! $alertFromExists) { $hashtag = HashTagTool::getHashTag($this->incident->concelho); $status = "ℹ Alerta dado por {$this->incident->alertFrom} https://{$domain}/fogo/{$this->incident->id} {$hashtag} ℹ"; $lastTweetId = TwitterTool::tweet($status, $this->incident->lastTweetId); diff --git a/app/Jobs/ProcessICNFPDFData.php b/app/Jobs/ProcessICNFPDFData.php index f95fbe1..348e017 100644 --- a/app/Jobs/ProcessICNFPDFData.php +++ b/app/Jobs/ProcessICNFPDFData.php @@ -10,7 +10,7 @@ use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; -class ProcessICNFPDFData extends Job implements ShouldQueue, ShouldBeUnique +class ProcessICNFPDFData extends Job implements ShouldBeUnique, ShouldQueue { public $incident; @@ -48,11 +48,11 @@ public function handle() $i = 0; foreach ($result[1] as $r) { if ($i === 0 || $i === 1) { - ++$i; + $i++; continue; } - ++$i; + $i++; $rr = explode("',", $r); @@ -96,14 +96,14 @@ private function getKml($kml) { if (isset($this->incident[0])) { $kmlExists = false; - if (isset($this->incident[0]->kml) && !empty($this->incident[0]->kml)) { + if (isset($this->incident[0]->kml) && ! empty($this->incident[0]->kml)) { $kmlExists = true; } $this->incident[0]->kml = $kml; $this->incident[0]->save(); - if (!$kmlExists) { + if (! $kmlExists) { $hashtag = HashTagTool::getHashTag($this->incident[0]->concelho); $domain = env('SOCIAL_LINK_DOMAIN'); diff --git a/app/Jobs/ProcessMadeiraWarnings.php b/app/Jobs/ProcessMadeiraWarnings.php index 1613f44..6fbdfe2 100644 --- a/app/Jobs/ProcessMadeiraWarnings.php +++ b/app/Jobs/ProcessMadeiraWarnings.php @@ -7,10 +7,10 @@ use App\Tools\FacebookTool; use App\Tools\NotificationTool; use App\Tools\TwitterTool; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldBeUnique; +use Illuminate\Contracts\Queue\ShouldQueue; -class ProcessMadeiraWarnings extends Job implements ShouldQueue, ShouldBeUnique +class ProcessMadeiraWarnings extends Job implements ShouldBeUnique, ShouldQueue { /** * Create a new job instance. @@ -42,7 +42,7 @@ public function handle() $exists = WarningMadeira::where('id', $id)->get(); - if (!isset($exists[0])) { + if (! isset($exists[0])) { if (preg_match('/fogo|incêndio|incendio/i', $d['title']) || preg_match('/fogo|incêndio|incendio/i', $d['description'])) { $d['id'] = $id; diff --git a/app/Jobs/ProcessRCM.php b/app/Jobs/ProcessRCM.php index b3447a9..f986522 100644 --- a/app/Jobs/ProcessRCM.php +++ b/app/Jobs/ProcessRCM.php @@ -5,24 +5,22 @@ use App\Models\RCM; use App\Models\RCMForJS; use App\Tools\FacebookTool; -use App\Tools\ScreenShotTool; -use App\Tools\TelegramTool; use App\Tools\TwitterTool; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldBeUnique; - use Illuminate\Support\Facades\Log; +use Illuminate\Contracts\Queue\ShouldQueue; use voku\helper\UTF8; -class ProcessRCM extends Job implements ShouldQueue, ShouldBeUnique +class ProcessRCM extends Job implements ShouldBeUnique, ShouldQueue { private $publishSocial = false; + private $tomorrow = false; /** * Create a new job instance. * - * @param mixed $publishSocial - * @param mixed $tomorrow + * @param mixed $publishSocial + * @param mixed $tomorrow */ public function __construct($publishSocial = false, $tomorrow = false) { @@ -364,9 +362,9 @@ public function handle() $all = []; foreach ($cities['features'] as $c) { - ++$i; + $i++; $data = [ - 'concelho' => UTF8::ucwords(mb_strtolower( UTF8::fix_simple_utf8($c['properties']['Concelho']), 'UTF-8')), + 'concelho' => UTF8::ucwords(mb_strtolower(UTF8::fix_simple_utf8($c['properties']['Concelho']), 'UTF-8')), 'date' => $riscoHoje['dataPrev'], 'hoje' => RCM::RCM_TO_HUMAN[$riscoHoje['local'][$c['properties']['DICO']]['data']['rcm']], 'amanha' => RCM::RCM_TO_HUMAN[$riscoAmanha['local'][$c['properties']['DICO']]['data']['rcm']], @@ -410,7 +408,7 @@ private function publishSocial($all) } } - if (!count($moderado)) { + if (! count($moderado)) { $status = date('d-m-Y')." - Sem registo de concelhos com risco de incêndio Moderado {$when2}"; TwitterTool::tweet($status); FacebookTool::publish($status); @@ -431,7 +429,7 @@ private function publishSocial($all) FacebookTool::publish($statusFacebook); } - if (!count($elevado)) { + if (! count($elevado)) { $status = date('d-m-Y')." - Sem registo de concelhos com risco de incêndio Elevado {$when2}"; TwitterTool::tweet($status); FacebookTool::publish($status); @@ -452,7 +450,7 @@ private function publishSocial($all) FacebookTool::publish($statusFacebook); } - if (!count($muitoElevado)) { + if (! count($muitoElevado)) { $status = date('d-m-Y')." - Sem registo de concelhos com risco de incêndio Muito Elevado {$when2}"; TwitterTool::tweet($status); FacebookTool::publish($status); @@ -472,7 +470,7 @@ private function publishSocial($all) FacebookTool::publish($statusFacebook); } - if (!count($maximo)) { + if (! count($maximo)) { $status = date('d-m-Y')." - Sem registo de concelhos com risco de incêndio Máximo {$when2}"; TwitterTool::tweet($status); FacebookTool::publish($status); diff --git a/app/Jobs/SaveIncidentHistory.php b/app/Jobs/SaveIncidentHistory.php index bf07732..c3987fe 100644 --- a/app/Jobs/SaveIncidentHistory.php +++ b/app/Jobs/SaveIncidentHistory.php @@ -131,11 +131,11 @@ public function handle() NotificationTool::send($status, $this->incident->location, $this->incident->id); } - if ($this->incident->man >= env('BIG_INCIDENT_MAN') && !$this->incident['notifyBig']) { + if ($this->incident->man >= env('BIG_INCIDENT_MAN') && ! $this->incident['notifyBig']) { $this->incident->notifyBig = true; $this->incident->save(); - if($this->incident->isFire){ + if ($this->incident->isFire) { $date = date('H:i'); $status = "ℹ🚨 {$date} - {$this->incident->location} - Grande mobilização de meios:\r\n 👩‍🚒 {$this->incident->man}\r\n 🚒 {$this->incident->terrain}\r\n 🚁 {$this->incident->aerial}\r\n https://{$domain}/fogo/{$this->incident->id} {$hashTag} #FogosPT 🚨ℹ"; diff --git a/app/Jobs/SaveIncidentStatusHistory.php b/app/Jobs/SaveIncidentStatusHistory.php index d9a06d4..85c0fbb 100644 --- a/app/Jobs/SaveIncidentStatusHistory.php +++ b/app/Jobs/SaveIncidentStatusHistory.php @@ -57,13 +57,13 @@ public function handle() } }*/ - if($this->incident->isFire){ + if ($this->incident->isFire) { if ($this->incident->status === 'Em Curso') { - if ($last['status'] === 'Conclusão' || $last['status'] === 'Em Resolução' || $last['status'] === 'Vigilância'){ + if ($last['status'] === 'Conclusão' || $last['status'] === 'Em Resolução' || $last['status'] === 'Vigilância') { $hashTag = HashTagTool::getHashTag($this->incident->concelho); $url = "fogo/{$this->incident->id}/detalhe"; - $name = "screenshot-{$this->incident->id}" . rand(0,255); + $name = "screenshot-{$this->incident->id}".rand(0, 255); $path = "/var/www/html/public/screenshots/{$name}.png"; ScreenShotTool::takeScreenShot($url, $name); @@ -89,7 +89,7 @@ public function handle() $hashTag = HashTagTool::getHashTag($this->incident->concelho); $url = "fogo/{$this->incident->id}/detalhe"; - $name = "screenshot-{$this->incident->id}" . rand(0,255); + $name = "screenshot-{$this->incident->id}".rand(0, 255); $path = "/var/www/html/public/screenshots/{$name}.png"; ScreenShotTool::takeScreenShot($url, $name); diff --git a/app/Jobs/UpdateICNFData.php b/app/Jobs/UpdateICNFData.php index 6ab3111..2b01e95 100644 --- a/app/Jobs/UpdateICNFData.php +++ b/app/Jobs/UpdateICNFData.php @@ -54,7 +54,7 @@ public function handle() [ 'before' => Carbon::now()->subDays(90), 'after' => Carbon::now()->subDays(180), - ] + ], ]; $incidents = Incident::where('created', '>=', $intervals[$this->interval]['after']) diff --git a/app/Jobs/UpdateWeatherData.php b/app/Jobs/UpdateWeatherData.php index 88c6f63..13e15b8 100644 --- a/app/Jobs/UpdateWeatherData.php +++ b/app/Jobs/UpdateWeatherData.php @@ -25,7 +25,7 @@ public function __construct() */ public function handle() { - $url = "https://api.ipma.pt/open-data/observation/meteorology/stations/observations.json"; + $url = 'https://api.ipma.pt/open-data/observation/meteorology/stations/observations.json'; $options = [ 'headers' => [ @@ -34,29 +34,29 @@ public function handle() 'verify' => false, ]; - try{ + try { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', $url, $options); $data = $res->getBody()->getContents(); - } - catch(\GuzzleHttp\Exception\RequestException $e) { + } catch (\GuzzleHttp\Exception\RequestException $e) { Log::error('Error occurred in request.', ['url' => $url, 'statusCode' => $e->getCode(), 'message' => $e->getMessage()]); + return; } $data = json_decode($data); - foreach($data as $date => $stations){ + foreach ($data as $date => $stations) { $ddate = Carbon::parse($date); - foreach($stations as $stationId => $d){ + foreach ($stations as $stationId => $d) { - if($d){ + if ($d) { $weatherData = WeatherData::where('stationId', $stationId) ->where('date', $ddate) ->get(); - if(!isset($weatherData[0])){ + if (! isset($weatherData[0])) { $weatherData = new WeatherData(); $weatherData->intensidadeVentoKM = $d->intensidadeVentoKM; diff --git a/app/Jobs/UpdateWeatherDataDaily.php b/app/Jobs/UpdateWeatherDataDaily.php index 54a6fd5..66eae18 100644 --- a/app/Jobs/UpdateWeatherDataDaily.php +++ b/app/Jobs/UpdateWeatherDataDaily.php @@ -2,7 +2,6 @@ namespace App\Jobs; -use App\Models\WeatherData; use App\Models\WeatherDataDaily; use Carbon\Carbon; use Illuminate\Support\Facades\Log; @@ -26,7 +25,7 @@ public function __construct() */ public function handle() { - $url = "https://api.ipma.pt/public-data/observation/surface-stations/daily-observations.json"; + $url = 'https://api.ipma.pt/public-data/observation/surface-stations/daily-observations.json'; $options = [ 'headers' => [ @@ -35,30 +34,30 @@ public function handle() 'verify' => false, ]; - try{ + try { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', $url, $options); $data = $res->getBody()->getContents(); - } - catch(\GuzzleHttp\Exception\RequestException $e) { + } catch (\GuzzleHttp\Exception\RequestException $e) { Log::error('Error occurred in request.', ['url' => $url, 'statusCode' => $e->getCode(), 'message' => $e->getMessage()]); + return; } $data = json_decode($data); - foreach($data as $date => $stations){ + foreach ($data as $date => $stations) { $ddate = Carbon::parse($date); print_r($ddate); - foreach($stations as $stationId => $d){ + foreach ($stations as $stationId => $d) { - if($d){ + if ($d) { $weatherData = WeatherDataDaily::where('stationId', $stationId) ->where('date', $ddate) ->get(); - if(!isset($weatherData[0])){ + if (! isset($weatherData[0])) { $weatherData = new WeatherDataDaily(); $weatherData->hum_min = $d->hum_min; diff --git a/app/Jobs/UpdateWeatherStations.php b/app/Jobs/UpdateWeatherStations.php index 4faeed1..4284481 100644 --- a/app/Jobs/UpdateWeatherStations.php +++ b/app/Jobs/UpdateWeatherStations.php @@ -24,7 +24,7 @@ public function __construct() */ public function handle() { - $url = "https://api.ipma.pt/open-data/observation/meteorology/stations/stations.json"; + $url = 'https://api.ipma.pt/open-data/observation/meteorology/stations/stations.json'; $options = [ 'headers' => [ @@ -33,38 +33,38 @@ public function handle() 'verify' => false, ]; - try{ + try { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', $url, $options); $data = $res->getBody()->getContents(); - } - catch(\GuzzleHttp\Exception\RequestException $e) { + } catch (\GuzzleHttp\Exception\RequestException $e) { Log::error('Error occurred in request.', ['url' => $url, 'statusCode' => $e->getCode(), 'message' => $e->getMessage()]); + return; } $data = json_decode($data); - foreach($data as $d){ - $id = (int)$d->properties->idEstacao; + foreach ($data as $d) { + $id = (int) $d->properties->idEstacao; $station = WeatherStation::where('id', $id)->get(); - if(isset($station[0])){ + if (isset($station[0])) { $station = $station[0]; } else { $station = new WeatherStation(); - $station->id = (int)$id; + $station->id = (int) $id; } - $station->type = "point"; + $station->type = 'point'; $station->location = $d->properties->localEstacao; $station->coordinates = $d->geometry->coordinates; - if($station->coordinates[1] < 34){ + if ($station->coordinates[1] < 34) { $station->place = 'Madeira'; - } elseif ($station->coordinates[0] < -20 && $station->coordinates[1] > 34){ + } elseif ($station->coordinates[0] < -20 && $station->coordinates[1] > 34) { $station->place = 'Açores'; } else { $station->place = 'Portugal'; diff --git a/app/Models/HistoryTotal.php b/app/Models/HistoryTotal.php index ea1b05c..f445be1 100644 --- a/app/Models/HistoryTotal.php +++ b/app/Models/HistoryTotal.php @@ -7,10 +7,13 @@ class HistoryTotal extends Model { protected $connection = 'mongodb'; + protected $collection = 'historyTotal'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/Incident.php b/app/Models/Incident.php index d8f8821..c2dc9bf 100644 --- a/app/Models/Incident.php +++ b/app/Models/Incident.php @@ -11,10 +11,13 @@ class Incident extends Model use IncidentObserver; protected $connection = 'mongodb'; + protected $collection = 'data'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $dates = ['dateTime', 'created', 'updated']; @@ -48,7 +51,7 @@ class Incident extends Model 'heliFight' => 'integer', 'heliCoord' => 'integer', 'planeFight' => 'integer', - 'anepcDirectUpdate' => 'boolean' + 'anepcDirectUpdate' => 'boolean', ]; protected $fillable = [ @@ -100,7 +103,7 @@ class Incident extends Model 'anepcDirectUpdate', 'regiao', 'sub_regiao', - 'meios_aquaticos' + 'meios_aquaticos', ]; public const NATUREZA_CODE_FIRE = [ @@ -141,7 +144,7 @@ class Incident extends Model '2203', '3111', '3109', - '3107' + '3107', ]; public const NATUREZA_CODE_FMA = [ @@ -164,7 +167,7 @@ class Incident extends Model ]; public const NOT_ACTIVE_STATUS_CODES = [ - 7,8,9,10,11,12 + 7, 8, 9, 10, 11, 12, ]; public const STATUS_ID = [ @@ -174,10 +177,9 @@ class Incident extends Model 'Conclusão' => 8, 'Vigilância' => 9, 'Em Curso' => 5, - 'Chegada ao TO' => 6 + 'Chegada ao TO' => 6, ]; - public const STATUS_COLORS = [ ' DESPACHO DE 1º ALERTA' => 'FF6E02', // sometimes we get this value... ' Encerrada' => '6ABF59', // sometimes we get this value... diff --git a/app/Models/IncidentHistory.php b/app/Models/IncidentHistory.php index e2fcdf7..90ad1be 100644 --- a/app/Models/IncidentHistory.php +++ b/app/Models/IncidentHistory.php @@ -7,10 +7,13 @@ class IncidentHistory extends Model { protected $connection = 'mongodb'; + protected $collection = 'history'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/IncidentStatusHistory.php b/app/Models/IncidentStatusHistory.php index a0e129c..e0d0be3 100644 --- a/app/Models/IncidentStatusHistory.php +++ b/app/Models/IncidentStatusHistory.php @@ -7,10 +7,13 @@ class IncidentStatusHistory extends Model { protected $connection = 'mongodb'; + protected $collection = 'statusHistory'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $dateFormat = 'd-m-Y H:i'; diff --git a/app/Models/Location.php b/app/Models/Location.php index 6c1713b..0cd367d 100644 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -2,18 +2,19 @@ namespace App\Models; -use Jenssegers\Mongodb\Eloquent\Builder; use Jenssegers\Mongodb\Eloquent\Model; class Location extends Model { protected $connection = 'mongodb'; + protected $collection = 'locations'; + protected $primaryKey = '_id'; protected $fillable = [ 'level', 'code', - 'name' + 'name', ]; } diff --git a/app/Models/Planes.php b/app/Models/Planes.php index 4cde132..25a2aaa 100644 --- a/app/Models/Planes.php +++ b/app/Models/Planes.php @@ -7,10 +7,13 @@ class Planes extends Model { protected $connection = 'mongodb'; + protected $collection = 'pplanes'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/RCM.php b/app/Models/RCM.php index f0e2458..d8f47aa 100644 --- a/app/Models/RCM.php +++ b/app/Models/RCM.php @@ -7,10 +7,13 @@ class RCM extends Model { protected $connection = 'mongodb'; + protected $collection = 'rcm'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/RCMForJS.php b/app/Models/RCMForJS.php index af0734a..155cb61 100644 --- a/app/Models/RCMForJS.php +++ b/app/Models/RCMForJS.php @@ -7,10 +7,13 @@ class RCMForJS extends Model { protected $connection = 'mongodb'; + protected $collection = 'rcmJS'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/User.php b/app/Models/User.php index 49dc9d0..79fec77 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -2,34 +2,42 @@ namespace App\Models; -use Illuminate\Auth\Authenticatable; -use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; -use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Illuminate\Database\Eloquent\Model; -use Laravel\Lumen\Auth\Authorizable; +use Illuminate\Foundation\Auth\User as Authenticatable; +use Illuminate\Notifications\Notifiable; +use Laravel\Sanctum\HasApiTokens; -class User extends Model implements AuthenticatableContract, AuthorizableContract +class User extends Authenticatable { - use Authenticatable; - use Authorizable; - use HasFactory; + use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ - 'name', 'email', + 'name', + 'email', + 'password', ]; /** - * The attributes excluded from the model's JSON form. + * The attributes that should be hidden for serialization. * - * @var array + * @var array */ protected $hidden = [ 'password', + 'remember_token', + ]; + + /** + * The attributes that should be cast. + * + * @var array + */ + protected $casts = [ + 'email_verified_at' => 'datetime', ]; } diff --git a/app/Models/Warning.php b/app/Models/Warning.php index 395bbfa..2169622 100644 --- a/app/Models/Warning.php +++ b/app/Models/Warning.php @@ -7,10 +7,13 @@ class Warning extends Model { protected $connection = 'mongodb'; + protected $collection = 'warning'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/WarningMadeira.php b/app/Models/WarningMadeira.php index b87239b..0cafca4 100644 --- a/app/Models/WarningMadeira.php +++ b/app/Models/WarningMadeira.php @@ -7,10 +7,13 @@ class WarningMadeira extends Model { protected $connection = 'mongodb'; + protected $collection = 'warningMadeira'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/WarningSite.php b/app/Models/WarningSite.php index b1fa2c8..88a8752 100644 --- a/app/Models/WarningSite.php +++ b/app/Models/WarningSite.php @@ -7,10 +7,13 @@ class WarningSite extends Model { protected $connection = 'mongodb'; + protected $collection = 'warningSite'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/WeatherData.php b/app/Models/WeatherData.php index f846f13..9f67781 100644 --- a/app/Models/WeatherData.php +++ b/app/Models/WeatherData.php @@ -7,10 +7,13 @@ class WeatherData extends Model { protected $connection = 'mongodb'; + protected $collection = 'weatherData'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $dates = ['date', 'created', 'updated']; @@ -38,6 +41,6 @@ class WeatherData extends Model 'humidade', 'pressao', 'date', - 'stationId' + 'stationId', ]; } diff --git a/app/Models/WeatherDataDaily.php b/app/Models/WeatherDataDaily.php index 301349d..e4b0910 100644 --- a/app/Models/WeatherDataDaily.php +++ b/app/Models/WeatherDataDaily.php @@ -7,10 +7,13 @@ class WeatherDataDaily extends Model { protected $connection = 'mongodb'; + protected $collection = 'weatherDataDaily'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $dates = ['date', 'created', 'updated']; @@ -44,7 +47,7 @@ class WeatherDataDaily extends Model 'prec_quant', 'hum_max', 'date', - 'stationId' + 'stationId', ]; public function station() diff --git a/app/Models/WeatherStation.php b/app/Models/WeatherStation.php index fef6230..59a2579 100644 --- a/app/Models/WeatherStation.php +++ b/app/Models/WeatherStation.php @@ -7,10 +7,13 @@ class WeatherStation extends Model { protected $connection = 'mongodb'; + protected $collection = 'weatherStations'; + protected $primaryKey = '_id'; public const CREATED_AT = 'created'; + public const UPDATED_AT = 'updated'; protected $fillable = [ diff --git a/app/Models/WeatherWarning.php b/app/Models/WeatherWarning.php index b22bcea..7594695 100644 --- a/app/Models/WeatherWarning.php +++ b/app/Models/WeatherWarning.php @@ -1,10 +1,7 @@ dateTime->year >= 2022 ){ + if ($incident->dateTime->year >= 2022) { dispatch(new SaveIncidentHistory($incident)); dispatch(new SaveIncidentStatusHistory($incident)); @@ -30,7 +30,7 @@ protected static function boot() dispatch(new HandleNewIncidentEmergenciasSocialMedia($incident)); - if ( $incident->naturezaCode === '2409' ) { + if ($incident->naturezaCode === '2409') { DiscordTool::postAero("🚨 Novo acidente aereo em {$incident->location} 🚨"); } } @@ -39,17 +39,17 @@ protected static function boot() $hlDico2 = explode(',', env('HL_PROJECT_TELEGRAM_CHANNEL_2_DICOS')); $hlDico3 = explode(',', env('HL_PROJECT_TELEGRAM_CHANNEL_3_DICOS')); - if(in_array($incident->dico, $hlDico1)){ + if (in_array($incident->dico, $hlDico1)) { dispatch(new HandleHJProject($incident, env('HL_PROJECT_TELEGRAM_CHANNEL_1'))); - } elseif (in_array($incident->dico, $hlDico2)){ + } elseif (in_array($incident->dico, $hlDico2)) { dispatch(new HandleHJProject($incident, env('HL_PROJECT_TELEGRAM_CHANNEL_2'))); - } elseif (in_array($incident->dico, $hlDico3)){ + } elseif (in_array($incident->dico, $hlDico3)) { dispatch(new HandleHJProject($incident, env('HL_PROJECT_TELEGRAM_CHANNEL_3'))); } }); static::updated(function ($incident) { - if($incident->dateTime->year >= 2022 ) { + if ($incident->dateTime->year >= 2022) { //Log::info("Incident updated Event Fire observer: ".$incident); dispatch(new SaveIncidentStatusHistory($incident)); dispatch(new SaveIncidentHistory($incident)); diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index d72aa39..ee8ca5b 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,15 +2,27 @@ namespace App\Providers; -use Illuminate\Support\Facades\URL; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { - public function boot(): void + /** + * Register any application services. + * + * @return void + */ + public function register() { - if (app()->environment('production')) { - URL::forceScheme('https'); - } + // + } + + /** + * Bootstrap any application services. + * + * @return void + */ + public function boot() + { + // } } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 10dfe61..59e239f 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -2,27 +2,28 @@ namespace App\Providers; -use App\Models\User; -use Illuminate\Support\ServiceProvider; +use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** - * Boot the authentication services for the application. + * The policy mappings for the application. + * + * @var array */ - public function boot(): void - { - // Here you may define how you wish users to be authenticated for your Lumen - // application. The callback which receives the incoming request instance - // should return either a User instance or null. You're free to obtain - // the User instance via an API token or any other method necessary. + protected $policies = [ + // 'App\Models\Model' => 'App\Policies\ModelPolicy', + ]; - $this->app['auth']->viaRequest('api', function ($request) { - if ($request->input('api_token')) { - return User::where('api_token', $request->input('api_token'))->first(); - } + /** + * Register any authentication / authorization services. + * + * @return void + */ + public function boot() + { + $this->registerPolicies(); - return null; - }); + // } } diff --git a/app/Providers/BroadcastServiceProvider.php b/app/Providers/BroadcastServiceProvider.php new file mode 100644 index 0000000..395c518 --- /dev/null +++ b/app/Providers/BroadcastServiceProvider.php @@ -0,0 +1,21 @@ +> */ - protected $listen = []; + protected $listen = [ + Registered::class => [ + SendEmailVerificationNotification::class, + ], + ]; + + /** + * Register any events for your application. + * + * @return void + */ + public function boot() + { + // + } } diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php new file mode 100644 index 0000000..3bd3c81 --- /dev/null +++ b/app/Providers/RouteServiceProvider.php @@ -0,0 +1,63 @@ +configureRateLimiting(); + + $this->routes(function () { + Route::prefix('api') + ->middleware('api') + ->namespace($this->namespace) + ->group(base_path('routes/api.php')); + + Route::middleware('web') + ->namespace($this->namespace) + ->group(base_path('routes/web.php')); + }); + } + + /** + * Configure the rate limiters for the application. + * + * @return void + */ + protected function configureRateLimiting() + { + RateLimiter::for('api', function (Request $request) { + return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip()); + }); + } +} diff --git a/app/Resources/IncidentResource.php b/app/Resources/IncidentResource.php index 7c5efdd..4e6d7d8 100644 --- a/app/Resources/IncidentResource.php +++ b/app/Resources/IncidentResource.php @@ -57,7 +57,7 @@ public function toArray($request): array ]; - if($request->get('extend')){ + if ($request->get('extend')) { $ob['history'] = $this->history; $ob['statusHistory'] = $this->statusHistory; } diff --git a/app/Tools/BlueskyTool.php b/app/Tools/BlueskyTool.php index 4119c85..955dff5 100644 --- a/app/Tools/BlueskyTool.php +++ b/app/Tools/BlueskyTool.php @@ -4,7 +4,6 @@ use Carbon\Carbon; use Illuminate\Support\Facades\Log; -use phpDocumentor\Reflection\Types\Self_; class BlueskyTool { @@ -14,15 +13,16 @@ private static function getToken() $data = [ 'identifier' => 'fogospt.bsky.social', - 'password' => env('BSKY_APP_PASSWORD') + 'password' => env('BSKY_APP_PASSWORD'), ]; $response = $client->request('POST', 'https://bsky.social/xrpc/com.atproto.server.createSession', ['json' => $data]); - $result = json_decode($response->getBody(),true); + $result = json_decode($response->getBody(), true); return $result; } + public static function publish($status) { $session = self::getToken(); @@ -35,21 +35,21 @@ public static function publish($status) 'record' => [ '$type' => 'app.bsky.feed.post', 'text' => $status, - 'createdAt' => Carbon::now() - ] + 'createdAt' => Carbon::now(), + ], ]; $headers = [ 'json' => $data, 'headers' => [ - 'Authorization' => "Bearer " . $session['accessJwt'] - ] + 'Authorization' => 'Bearer '.$session['accessJwt'], + ], ]; - try{ + try { $client = new \GuzzleHttp\Client(); $client->request('POST', 'https://bsky.social/xrpc/com.atproto.repo.createRecord', $headers); - } catch (\Exception $e){ + } catch (\Exception $e) { Log::error($e->getMessage()); } } diff --git a/app/Tools/DiscordTool.php b/app/Tools/DiscordTool.php index 5e50352..493eda2 100644 --- a/app/Tools/DiscordTool.php +++ b/app/Tools/DiscordTool.php @@ -6,7 +6,7 @@ class DiscordTool { public static function post($message) { - if (!env('DISCORD_ENABLE')) { + if (! env('DISCORD_ENABLE')) { return; } @@ -30,7 +30,7 @@ public static function post($message) public static function postAero($message) { - if (!env('DISCORD_ENABLE')) { + if (! env('DISCORD_ENABLE')) { return; } diff --git a/app/Tools/FacebookTool.php b/app/Tools/FacebookTool.php index f584a0e..254e17c 100644 --- a/app/Tools/FacebookTool.php +++ b/app/Tools/FacebookTool.php @@ -39,27 +39,27 @@ private static function getImageUrl($message, $imageUrl) public static function publish($status) { - if (!env('FACEBOOK_ENABLE')) { + if (! env('FACEBOOK_ENABLE')) { return; } - try{ + try { $client = new \GuzzleHttp\Client(); $client->request('POST', self::getUrl($status)); - } catch (\Exception $e){ + } catch (\Exception $e) { Log::error($e->getMessage()); } } public static function publishWithImage($status, $imageUrl) { - if (!env('FACEBOOK_ENABLE')) { + if (! env('FACEBOOK_ENABLE')) { return; } - try{ + try { $client = new \GuzzleHttp\Client(); $client->request('POST', self::getImageUrl($status, $imageUrl)); - } catch (\Exception $e){ + } catch (\Exception $e) { Log::error($e->getMessage()); } @@ -67,14 +67,14 @@ public static function publishWithImage($status, $imageUrl) public static function publishEmergencias($status) { - if (!env('FACEBOOK_ENABLE')) { + if (! env('FACEBOOK_ENABLE')) { return; } - try{ + try { $client = new \GuzzleHttp\Client(); $response = $client->request('POST', self::getEmergenciasUrl($status)); - } catch (\Exception $e){ + } catch (\Exception $e) { Log::error($e->getMessage()); } diff --git a/app/Tools/NotificationTool.php b/app/Tools/NotificationTool.php index 5b89e47..564217a 100644 --- a/app/Tools/NotificationTool.php +++ b/app/Tools/NotificationTool.php @@ -3,14 +3,13 @@ namespace App\Tools; use App\Models\Incident; -use App\Models\IncidentStatusHistory; use Illuminate\Support\Facades\Log; class NotificationTool { private static function sendRequest($topic, $status, $location, $id) { - if (!env('NOTIFICATIONS_ENABLE')) { + if (! env('NOTIFICATIONS_ENABLE')) { return; } @@ -31,18 +30,18 @@ private static function sendRequest($topic, $status, $location, $id) ], 'data' => [ 'click_action' => 'FLUTTER_NOTIFICATION_CLICK', - 'fireId' => $id + 'fireId' => $id, ], 'android' => [ - 'priority' => 'high' + 'priority' => 'high', ], 'apns' => [ [ 'headers' => [ - 'apns-priority' => "5" - ] - ] - ] + 'apns-priority' => '5', + ], + ], + ], ], ]; @@ -53,7 +52,7 @@ private static function sendRequest($topic, $status, $location, $id) private static function sendCustomTitleRequest($topic, $status, $title, $forceEnable = false) { Log::debug(); - if (!env('NOTIFICATIONS_ENABLE')) { + if (! env('NOTIFICATIONS_ENABLE')) { return; } @@ -73,15 +72,15 @@ private static function sendCustomTitleRequest($topic, $status, $title, $forceEn 'icon' => 'https://fogos.pt/img/logo.svg', ], 'android' => [ - 'priority' => 'high' + 'priority' => 'high', ], 'apns' => [ [ 'headers' => [ - 'apns-priority' => "5" - ] - ] - ] + 'apns-priority' => '5', + ], + ], + ], ], ]; @@ -133,7 +132,7 @@ private static function buildTopic($id, $important = false) public static function send($status, $location, $id, $topic = false) { - if (!$topic) { + if (! $topic) { $topic = self::buildTopic($id, true); } @@ -168,12 +167,11 @@ public static function sendImportant($status, $incidentId) ], 'data' => [ 'click_action' => 'FLUTTER_NOTIFICATION_CLICK', - 'fireId' => $incidentId - ] + 'fireId' => $incidentId, + ], ], ]; - $client = new \GuzzleHttp\Client(); $response = $client->request('POST', 'https://fcm.googleapis.com/fcm/send', $headers); } @@ -200,7 +198,6 @@ public static function sendWarning($status, $topic) ], ]; - $client = new \GuzzleHttp\Client(); $response = $client->request('POST', 'https://fcm.googleapis.com/fcm/send', $headers); } @@ -291,7 +288,7 @@ public static function sendPlaneNotification($status) { $topic = "'mobile-android-planes' in topics || 'mobile-ios-planes' in topics"; $title = 'Fogos.pt - Meio Aéreo'; - self::sendCustomTitleRequest($topic, $status, $title,true); + self::sendCustomTitleRequest($topic, $status, $title, true); } public static function sendWarningNotification($status) diff --git a/app/Tools/RCMTool.php b/app/Tools/RCMTool.php index 78900f9..32e0466 100644 --- a/app/Tools/RCMTool.php +++ b/app/Tools/RCMTool.php @@ -1,9 +1,7 @@ features as $feature){ + foreach ($geoJson->features as $feature) { $dico = $feature->properties->DICO; $rcm = $dicos[$dico]; $feature->properties->data = $rcm['data']; diff --git a/app/Tools/ScreenShotTool.php b/app/Tools/ScreenShotTool.php index 77fa5b3..0cb6bb1 100644 --- a/app/Tools/ScreenShotTool.php +++ b/app/Tools/ScreenShotTool.php @@ -6,10 +6,10 @@ class ScreenShotTool { public static function takeScreenShot($url, $name, $width = false, $height = false) { - if (!$width) { + if (! $width) { $width = env('SCREENSHOT_WIDTH'); } - if (!$height) { + if (! $height) { $height = env('SCREENSHOT_HEIGHT'); } @@ -20,7 +20,7 @@ public static function takeScreenShot($url, $name, $width = false, $height = fal public static function removeScreenShotFile($name) { - if(file_exists("/var/www/html/public/screenshots/{$name}.png")){ + if (file_exists("/var/www/html/public/screenshots/{$name}.png")) { unlink("/var/www/html/public/screenshots/{$name}.png"); } } diff --git a/app/Tools/TelegramTool.php b/app/Tools/TelegramTool.php index 20197ec..c0536cf 100644 --- a/app/Tools/TelegramTool.php +++ b/app/Tools/TelegramTool.php @@ -6,7 +6,7 @@ class TelegramTool { public static function publish($status) { - if (!env('TELEGRAM_ENABLE')) { + if (! env('TELEGRAM_ENABLE')) { return; } @@ -22,7 +22,7 @@ public static function publish($status) public static function publishImage($status, $imagePath) { - if (!env('TELEGRAM_ENABLE')) { + if (! env('TELEGRAM_ENABLE')) { return; } diff --git a/app/Tools/TwitterTool.php b/app/Tools/TwitterTool.php index 06f73c6..b628873 100644 --- a/app/Tools/TwitterTool.php +++ b/app/Tools/TwitterTool.php @@ -2,17 +2,17 @@ namespace App\Tools; -use Illuminate\Support\Facades\Log; use Noweh\TwitterApi\Client; class TwitterTool { private static $client = false; + private static $clientVOST = false; public static function getClient() { - if (!self::$client) { + if (! self::$client) { $settings = [ 'access_token' => env('TWITTER_OAUTH_ACCESS_TOKEN'), 'access_token_secret' => env('TWITTER_OAUTH_ACCESS_TOKEN_SECRET'), @@ -30,7 +30,7 @@ public static function getClient() public static function getVOSTClient() { - if (!self::$clientVOST) { + if (! self::$clientVOST) { $settings = [ 'oauth_access_token' => env('TWITTER_OAUTH_ACCESS_TOKEN_VOST'), 'oauth_access_token_secret' => env('TWITTER_OAUTH_ACCESS_TOKEN_SECRET_VOST'), @@ -46,7 +46,7 @@ public static function getVOSTClient() public static function getClientEmergencias() { - if (!self::$client) { + if (! self::$client) { $settings = [ 'oauth_access_token' => env('TWITTER_OAUTH_ACCESS_TOKEN_EMERGENCIAS'), 'oauth_access_token_secret' => env('TWITTER_OAUTH_ACCESS_TOKEN_SECRET_EMERGENCIAS'), @@ -80,7 +80,7 @@ private static function splitTweets($long_string, $max_length = 280, $max_senten $sentences_array = []; $ended_word = 0; - for ($sentence = 0; $sentence < $max_sentences; ++$sentence) { + for ($sentence = 0; $sentence < $max_sentences; $sentence++) { $short_string = ''; foreach ($words_array as $word_number => $current_word) { @@ -96,7 +96,7 @@ private static function splitTweets($long_string, $max_length = 280, $max_senten $sentences_array[] = $short_string; $words_array = array_slice($words_array, $ended_word); - if (!$words_array) { + if (! $words_array) { break; } } @@ -106,13 +106,13 @@ private static function splitTweets($long_string, $max_length = 280, $max_senten public static function tweet($text, $lastId = false, $imagePath = false, $emergencias = false, $vost = false) { - if (!env('TWITTER_ENABLE')) { + if (! env('TWITTER_ENABLE')) { return false; } - if($vost){ + if ($vost) { $client = self::getVOSTClient(); - } else if($emergencias){ + } elseif ($emergencias) { $client = self::getClientEmergencias(); } else { $client = self::getClient(); @@ -125,9 +125,9 @@ public static function tweet($text, $lastId = false, $imagePath = false, $emerge $media_info = $client->uploadMedia()->upload($file_data); // Extract media id - $id = $media_info["media_id"]; + $id = $media_info['media_id']; - $fields['media']['media_ids'] = [(string)$id]; + $fields['media']['media_ids'] = [(string) $id]; } $tweets = self::splitTweets($text); @@ -143,17 +143,18 @@ public static function tweet($text, $lastId = false, $imagePath = false, $emerge $fields ); - if(isset($response->data->id)){ + if (isset($response->data->id)) { $lastId = $response->data->id; } else { $lastId = null; } - if(isset($fields['media']['media_ids'])){ + if (isset($fields['media']['media_ids'])) { unset($fields['media']['media_ids']); unset($fields['media']); } } + return $lastId; } @@ -161,7 +162,7 @@ public static function retweetVost($id) { $client = self::getVOSTClient(); - $url = 'https://api.twitter.com/1.1/statuses/retweet/' . $id . '.json'; + $url = 'https://api.twitter.com/1.1/statuses/retweet/'.$id.'.json'; $response = $client ->buildOauth($url, 'POST') diff --git a/artisan b/artisan old mode 100644 new mode 100755 index 6a9d095..67a3329 --- a/artisan +++ b/artisan @@ -1,21 +1,23 @@ #!/usr/bin/env php make( - 'Illuminate\Contracts\Console\Kernel' +$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class); + +$status = $kernel->handle( + $input = new Symfony\Component\Console\Input\ArgvInput, + new Symfony\Component\Console\Output\ConsoleOutput ); -exit($kernel->handle(new ArgvInput, new ConsoleOutput)); +/* +|-------------------------------------------------------------------------- +| Shutdown The Application +|-------------------------------------------------------------------------- +| +| Once Artisan has finished running, we will fire off the shutdown events +| so that any final work may be done by the application before we shut +| down the process. This is the last thing to happen to the request. +| +*/ + +$kernel->terminate($input, $status); + +exit($status); diff --git a/bootstrap/app.php b/bootstrap/app.php index 9b3b496..037e17d 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,44 +1,34 @@ bootstrap(); - -date_default_timezone_set(env('APP_TIMEZONE', 'UTC')); - /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | -| Here we will load the environment and create the application instance -| that serves as the central piece of this framework. We'll use this -| application as an "IoC" container and router for this framework. +| The first thing we will do is create a new Laravel application instance +| which serves as the "glue" for all the components of Laravel, and is +| the IoC container for the system binding all of the various parts. | */ -$app = new Laravel\Lumen\Application( - dirname(__DIR__) +$app = new Illuminate\Foundation\Application( + $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__) ); /* |-------------------------------------------------------------------------- -| Register Container Bindings +| Bind Important Interfaces |-------------------------------------------------------------------------- | -| Now we will register a few bindings in the service container. We will -| register the exception handler and the console kernel. You may add -| your own bindings here if you like or you can make another file. +| Next, we need to bind some important interfaces into the container so +| we will be able to resolve them when needed. The kernels serve the +| incoming requests to this application from both the web and CLI. | */ $app->singleton( - Illuminate\Contracts\Debug\ExceptionHandler::class, - App\Exceptions\Handler::class + Illuminate\Contracts\Http\Kernel::class, + App\Http\Kernel::class ); $app->singleton( @@ -46,71 +36,20 @@ App\Console\Kernel::class ); -/* -|-------------------------------------------------------------------------- -| Register Config Files -|-------------------------------------------------------------------------- -| -| Now we will register the "app" configuration file. If the file exists in -| your configuration directory it will be loaded; otherwise, we'll load -| the default version. You may register other files below as needed. -| -*/ -$app->configure('app'); - -/* -|-------------------------------------------------------------------------- -| Register Middleware -|-------------------------------------------------------------------------- -| -| Next, we will register the middleware with the application. These can -| be global middleware that run before and after each request into a -| route or middleware that'll be assigned to some specific routes. -| -*/ - -// $app->middleware([ -// App\Http\Middleware\ExampleMiddleware::class -// ]); - -// $app->routeMiddleware([ -// 'auth' => App\Http\Middleware\Authenticate::class, -// ]); - -/* -|-------------------------------------------------------------------------- -| Register Service Providers -|-------------------------------------------------------------------------- -| -| Here we will register all of the application's service providers which -| are used to bind services into the container. Service providers are -| totally optional, so you are not required to uncomment this line. -| -*/ - -$app->register(App\Providers\AppServiceProvider::class); -// $app->register(App\Providers\AuthServiceProvider::class); -// $app->register(App\Providers\EventServiceProvider::class); -$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class); -$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class); -$app->register(Illuminate\Redis\RedisServiceProvider::class); -$app->register(Sentry\Laravel\ServiceProvider::class); -$app->register(Anik\Form\FormRequestServiceProvider::class); - -$app->withFacades(); -$app->withEloquent(); +$app->singleton( + Illuminate\Contracts\Debug\ExceptionHandler::class, + App\Exceptions\Handler::class +); /* |-------------------------------------------------------------------------- -| Load The Application Routes +| Return The Application |-------------------------------------------------------------------------- | -| Next we will include the routes file so that they can all be added to -| the application. This will provide all of the URLs the application -| can respond to, as well as the controllers that may handle them. +| This script returns the application instance. The instance is given to +| the calling script so we can separate the building of the instances +| from the actual running of the application and sending responses. | */ -$app->router->group([], static fn (Router $router) => require __DIR__.'/../routes/web.php'); - return $app; diff --git a/bootstrap/cache/.gitignore b/bootstrap/cache/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/bootstrap/cache/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/composer.json b/composer.json index ab0e317..76b9197 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,9 @@ "description": "FogosPT API.", "keywords": [ "fogospt", - "api" + "api", + "framework", + "laravel" ], "license": "Apache-2.0", "type": "project", @@ -14,25 +16,30 @@ "ext-mongodb": "*", "anik/form-request": "^4.2", "flipbox/lumen-generator": "^8.2", - "guzzlehttp/guzzle": "^7.0", - "illuminate/redis": "^8.40", + "guzzlehttp/guzzle": "^7.0.1", "j7mbo/twitter-api-php": "^1.0", "jenssegers/mongodb": "^3.8", - "laravel/lumen-framework": "^8.0", "noweh/twitter-api-v2-php": "^3.4", "php-imap/php-imap": "^5.0", "predis/predis": "^1.1", "sentry/sentry-laravel": "^2.7", "smalot/pdfparser": "^1.0", "spatie/pdf-to-text": "^1.4", - "voku/portable-utf8": "^5.4" + "voku/portable-utf8": "^5.4", + "laravel/framework": "^8.75", + "fruitcake/laravel-cors": "^2.0", + "laravel/sanctum": "^2.11", + "laravel/tinker": "^2.5" }, "require-dev": { "roave/security-advisories": "dev-latest", "fakerphp/faker": "^1.9.1", "friendsofphp/php-cs-fixer": "^3.0", - "mockery/mockery": "^1.3.1", - "phpunit/phpunit": "^9.3" + "mockery/mockery": "^1.4.4", + "phpunit/phpunit": "^9.5.10", + "facade/ignition": "^2.5", + "laravel/sail": "^1.0.1", + "nunomaduro/collision": "^5.10" }, "autoload": { "psr-4": { @@ -42,23 +49,38 @@ } }, "autoload-dev": { - "classmap": [ - "tests/" - ], "psr-4": { - "Tests\\": "tests/" + "Tests\\": [ + "tests/", + "tests/" + ] } }, "config": { + "optimize-autoloader": true, "preferred-install": "dist", - "sort-packages": true, - "optimize-autoloader": true + "sort-packages": true }, "minimum-stability": "dev", "prefer-stable": true, "scripts": { + "post-autoload-dump": [ + "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", + "@php artisan package:discover --ansi" + ], + "post-update-cmd": [ + "@php artisan vendor:publish --tag=laravel-assets --ansi --force" + ], "post-root-package-install": [ "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" + ], + "post-create-project-cmd": [ + "@php artisan key:generate --ansi" ] + }, + "extra": { + "laravel": { + "dont-discover": [] + } } } diff --git a/config/app.php b/config/app.php new file mode 100644 index 0000000..a8d1a82 --- /dev/null +++ b/config/app.php @@ -0,0 +1,235 @@ + env('APP_NAME', 'Laravel'), + + /* + |-------------------------------------------------------------------------- + | Application Environment + |-------------------------------------------------------------------------- + | + | This value determines the "environment" your application is currently + | running in. This may determine how you prefer to configure various + | services the application utilizes. Set this in your ".env" file. + | + */ + + 'env' => env('APP_ENV', 'production'), + + /* + |-------------------------------------------------------------------------- + | Application Debug Mode + |-------------------------------------------------------------------------- + | + | When your application is in debug mode, detailed error messages with + | stack traces will be shown on every error that occurs within your + | application. If disabled, a simple generic error page is shown. + | + */ + + 'debug' => (bool) env('APP_DEBUG', false), + + /* + |-------------------------------------------------------------------------- + | Application URL + |-------------------------------------------------------------------------- + | + | This URL is used by the console to properly generate URLs when using + | the Artisan command line tool. You should set this to the root of + | your application so that it is used when running Artisan tasks. + | + */ + + 'url' => env('APP_URL', 'http://localhost'), + + 'asset_url' => env('ASSET_URL', null), + + /* + |-------------------------------------------------------------------------- + | Application Timezone + |-------------------------------------------------------------------------- + | + | Here you may specify the default timezone for your application, which + | will be used by the PHP date and date-time functions. We have gone + | ahead and set this to a sensible default for you out of the box. + | + */ + + 'timezone' => 'UTC', + + /* + |-------------------------------------------------------------------------- + | Application Locale Configuration + |-------------------------------------------------------------------------- + | + | The application locale determines the default locale that will be used + | by the translation service provider. You are free to set this value + | to any of the locales which will be supported by the application. + | + */ + + 'locale' => 'en', + + /* + |-------------------------------------------------------------------------- + | Application Fallback Locale + |-------------------------------------------------------------------------- + | + | The fallback locale determines the locale to use when the current one + | is not available. You may change the value to correspond to any of + | the language folders that are provided through your application. + | + */ + + 'fallback_locale' => 'en', + + /* + |-------------------------------------------------------------------------- + | Faker Locale + |-------------------------------------------------------------------------- + | + | This locale will be used by the Faker PHP library when generating fake + | data for your database seeds. For example, this will be used to get + | localized telephone numbers, street address information and more. + | + */ + + 'faker_locale' => 'en_US', + + /* + |-------------------------------------------------------------------------- + | Encryption Key + |-------------------------------------------------------------------------- + | + | This key is used by the Illuminate encrypter service and should be set + | to a random, 32 character string, otherwise these encrypted strings + | will not be safe. Please do this before deploying an application! + | + */ + + 'key' => env('APP_KEY'), + + 'cipher' => 'AES-256-CBC', + + /* + |-------------------------------------------------------------------------- + | Autoloaded Service Providers + |-------------------------------------------------------------------------- + | + | The service providers listed here will be automatically loaded on the + | request to your application. Feel free to add your own services to + | this array to grant expanded functionality to your applications. + | + */ + + 'providers' => [ + + /* + * Laravel Framework Service Providers... + */ + Illuminate\Auth\AuthServiceProvider::class, + Illuminate\Broadcasting\BroadcastServiceProvider::class, + Illuminate\Bus\BusServiceProvider::class, + Illuminate\Cache\CacheServiceProvider::class, + Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, + Illuminate\Cookie\CookieServiceProvider::class, + Illuminate\Database\DatabaseServiceProvider::class, + Illuminate\Encryption\EncryptionServiceProvider::class, + Illuminate\Filesystem\FilesystemServiceProvider::class, + Illuminate\Foundation\Providers\FoundationServiceProvider::class, + Illuminate\Hashing\HashServiceProvider::class, + Illuminate\Mail\MailServiceProvider::class, + Illuminate\Notifications\NotificationServiceProvider::class, + Illuminate\Pagination\PaginationServiceProvider::class, + Illuminate\Pipeline\PipelineServiceProvider::class, + Illuminate\Queue\QueueServiceProvider::class, + Illuminate\Redis\RedisServiceProvider::class, + Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, + Illuminate\Session\SessionServiceProvider::class, + Illuminate\Translation\TranslationServiceProvider::class, + Illuminate\Validation\ValidationServiceProvider::class, + Illuminate\View\ViewServiceProvider::class, + + /* + * Package Service Providers... + */ + + /* + * Application Service Providers... + */ + App\Providers\AppServiceProvider::class, + App\Providers\AuthServiceProvider::class, + // App\Providers\BroadcastServiceProvider::class, + App\Providers\EventServiceProvider::class, + App\Providers\RouteServiceProvider::class, + + ], + + /* + |-------------------------------------------------------------------------- + | Class Aliases + |-------------------------------------------------------------------------- + | + | This array of class aliases will be registered when this application + | is started. However, feel free to register as many as you wish as + | the aliases are "lazy" loaded so they don't hinder performance. + | + */ + + 'aliases' => [ + + 'App' => Illuminate\Support\Facades\App::class, + 'Arr' => Illuminate\Support\Arr::class, + 'Artisan' => Illuminate\Support\Facades\Artisan::class, + 'Auth' => Illuminate\Support\Facades\Auth::class, + 'Blade' => Illuminate\Support\Facades\Blade::class, + 'Broadcast' => Illuminate\Support\Facades\Broadcast::class, + 'Bus' => Illuminate\Support\Facades\Bus::class, + 'Cache' => Illuminate\Support\Facades\Cache::class, + 'Config' => Illuminate\Support\Facades\Config::class, + 'Cookie' => Illuminate\Support\Facades\Cookie::class, + 'Crypt' => Illuminate\Support\Facades\Crypt::class, + 'Date' => Illuminate\Support\Facades\Date::class, + 'DB' => Illuminate\Support\Facades\DB::class, + 'Eloquent' => Illuminate\Database\Eloquent\Model::class, + 'Event' => Illuminate\Support\Facades\Event::class, + 'File' => Illuminate\Support\Facades\File::class, + 'Gate' => Illuminate\Support\Facades\Gate::class, + 'Hash' => Illuminate\Support\Facades\Hash::class, + 'Http' => Illuminate\Support\Facades\Http::class, + 'Js' => Illuminate\Support\Js::class, + 'Lang' => Illuminate\Support\Facades\Lang::class, + 'Log' => Illuminate\Support\Facades\Log::class, + 'Mail' => Illuminate\Support\Facades\Mail::class, + 'Notification' => Illuminate\Support\Facades\Notification::class, + 'Password' => Illuminate\Support\Facades\Password::class, + 'Queue' => Illuminate\Support\Facades\Queue::class, + 'RateLimiter' => Illuminate\Support\Facades\RateLimiter::class, + 'Redirect' => Illuminate\Support\Facades\Redirect::class, + // 'Redis' => Illuminate\Support\Facades\Redis::class, + 'Request' => Illuminate\Support\Facades\Request::class, + 'Response' => Illuminate\Support\Facades\Response::class, + 'Route' => Illuminate\Support\Facades\Route::class, + 'Schema' => Illuminate\Support\Facades\Schema::class, + 'Session' => Illuminate\Support\Facades\Session::class, + 'Storage' => Illuminate\Support\Facades\Storage::class, + 'Str' => Illuminate\Support\Str::class, + 'URL' => Illuminate\Support\Facades\URL::class, + 'Validator' => Illuminate\Support\Facades\Validator::class, + 'View' => Illuminate\Support\Facades\View::class, + + ], + +]; diff --git a/config/auth.php b/config/auth.php new file mode 100644 index 0000000..d8c6cee --- /dev/null +++ b/config/auth.php @@ -0,0 +1,111 @@ + [ + 'guard' => 'web', + 'passwords' => 'users', + ], + + /* + |-------------------------------------------------------------------------- + | Authentication Guards + |-------------------------------------------------------------------------- + | + | Next, you may define every authentication guard for your application. + | Of course, a great default configuration has been defined for you + | here which uses session storage and the Eloquent user provider. + | + | All authentication drivers have a user provider. This defines how the + | users are actually retrieved out of your database or other storage + | mechanisms used by this application to persist your user's data. + | + | Supported: "session" + | + */ + + 'guards' => [ + 'web' => [ + 'driver' => 'session', + 'provider' => 'users', + ], + ], + + /* + |-------------------------------------------------------------------------- + | User Providers + |-------------------------------------------------------------------------- + | + | All authentication drivers have a user provider. This defines how the + | users are actually retrieved out of your database or other storage + | mechanisms used by this application to persist your user's data. + | + | If you have multiple user tables or models you may configure multiple + | sources which represent each model / table. These sources may then + | be assigned to any extra authentication guards you have defined. + | + | Supported: "database", "eloquent" + | + */ + + 'providers' => [ + 'users' => [ + 'driver' => 'eloquent', + 'model' => App\Models\User::class, + ], + + // 'users' => [ + // 'driver' => 'database', + // 'table' => 'users', + // ], + ], + + /* + |-------------------------------------------------------------------------- + | Resetting Passwords + |-------------------------------------------------------------------------- + | + | You may specify multiple password reset configurations if you have more + | than one user table or model in the application and you want to have + | separate password reset settings based on the specific user types. + | + | The expire time is the number of minutes that each reset token will be + | considered valid. This security feature keeps tokens short-lived so + | they have less time to be guessed. You may change this as needed. + | + */ + + 'passwords' => [ + 'users' => [ + 'provider' => 'users', + 'table' => 'password_resets', + 'expire' => 60, + 'throttle' => 60, + ], + ], + + /* + |-------------------------------------------------------------------------- + | Password Confirmation Timeout + |-------------------------------------------------------------------------- + | + | Here you may define the amount of seconds before a password confirmation + | times out and the user is prompted to re-enter their password via the + | confirmation screen. By default, the timeout lasts for three hours. + | + */ + + 'password_timeout' => 10800, + +]; diff --git a/config/broadcasting.php b/config/broadcasting.php new file mode 100644 index 0000000..2d52982 --- /dev/null +++ b/config/broadcasting.php @@ -0,0 +1,64 @@ + env('BROADCAST_DRIVER', 'null'), + + /* + |-------------------------------------------------------------------------- + | Broadcast Connections + |-------------------------------------------------------------------------- + | + | Here you may define all of the broadcast connections that will be used + | to broadcast events to other systems or over websockets. Samples of + | each available type of connection are provided inside this array. + | + */ + + 'connections' => [ + + 'pusher' => [ + 'driver' => 'pusher', + 'key' => env('PUSHER_APP_KEY'), + 'secret' => env('PUSHER_APP_SECRET'), + 'app_id' => env('PUSHER_APP_ID'), + 'options' => [ + 'cluster' => env('PUSHER_APP_CLUSTER'), + 'useTLS' => true, + ], + ], + + 'ably' => [ + 'driver' => 'ably', + 'key' => env('ABLY_KEY'), + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => 'default', + ], + + 'log' => [ + 'driver' => 'log', + ], + + 'null' => [ + 'driver' => 'null', + ], + + ], + +]; diff --git a/config/cache.php b/config/cache.php new file mode 100644 index 0000000..8736c7a --- /dev/null +++ b/config/cache.php @@ -0,0 +1,110 @@ + env('CACHE_DRIVER', 'file'), + + /* + |-------------------------------------------------------------------------- + | Cache Stores + |-------------------------------------------------------------------------- + | + | Here you may define all of the cache "stores" for your application as + | well as their drivers. You may even define multiple stores for the + | same cache driver to group types of items stored in your caches. + | + | Supported drivers: "apc", "array", "database", "file", + | "memcached", "redis", "dynamodb", "octane", "null" + | + */ + + 'stores' => [ + + 'apc' => [ + 'driver' => 'apc', + ], + + 'array' => [ + 'driver' => 'array', + 'serialize' => false, + ], + + 'database' => [ + 'driver' => 'database', + 'table' => 'cache', + 'connection' => null, + 'lock_connection' => null, + ], + + 'file' => [ + 'driver' => 'file', + 'path' => storage_path('framework/cache/data'), + ], + + 'memcached' => [ + 'driver' => 'memcached', + 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), + 'sasl' => [ + env('MEMCACHED_USERNAME'), + env('MEMCACHED_PASSWORD'), + ], + 'options' => [ + // Memcached::OPT_CONNECT_TIMEOUT => 2000, + ], + 'servers' => [ + [ + 'host' => env('MEMCACHED_HOST', '127.0.0.1'), + 'port' => env('MEMCACHED_PORT', 11211), + 'weight' => 100, + ], + ], + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => 'cache', + 'lock_connection' => 'default', + ], + + 'dynamodb' => [ + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'endpoint' => env('DYNAMODB_ENDPOINT'), + ], + + 'octane' => [ + 'driver' => 'octane', + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Cache Key Prefix + |-------------------------------------------------------------------------- + | + | When utilizing a RAM based store such as APC or Memcached, there might + | be other applications utilizing the same cache. So, we'll specify a + | value to get prefixed to all our keys so we can avoid collisions. + | + */ + + 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'), + +]; diff --git a/config/cors.php b/config/cors.php new file mode 100644 index 0000000..8a39e6d --- /dev/null +++ b/config/cors.php @@ -0,0 +1,34 @@ + ['api/*', 'sanctum/csrf-cookie'], + + 'allowed_methods' => ['*'], + + 'allowed_origins' => ['*'], + + 'allowed_origins_patterns' => [], + + 'allowed_headers' => ['*'], + + 'exposed_headers' => [], + + 'max_age' => 0, + + 'supports_credentials' => false, + +]; diff --git a/config/database.php b/config/database.php index 3b0f4a9..b42d9b3 100644 --- a/config/database.php +++ b/config/database.php @@ -3,28 +3,127 @@ use Illuminate\Support\Str; return [ - 'default' => 'mongodb', + + /* + |-------------------------------------------------------------------------- + | Default Database Connection Name + |-------------------------------------------------------------------------- + | + | Here you may specify which of the database connections below you wish + | to use as your default connection for all database work. Of course + | you may use many connections at once using the Database library. + | + */ + + 'default' => env('DB_CONNECTION', 'mysql'), + + /* + |-------------------------------------------------------------------------- + | Database Connections + |-------------------------------------------------------------------------- + | + | Here are each of the database connections setup for your application. + | Of course, examples of configuring each database platform that is + | supported by Laravel is shown below to make development simple. + | + | + | All database work in Laravel is done through the PHP PDO facilities + | so make sure you have the driver for your particular database of + | choice installed on your machine before you begin development. + | + */ + 'connections' => [ - 'mongodb' => [ - 'driver' => 'mongodb', + + 'sqlite' => [ + 'driver' => 'sqlite', + 'url' => env('DATABASE_URL'), + 'database' => env('DB_DATABASE', database_path('database.sqlite')), + 'prefix' => '', + 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), + ], + + 'mysql' => [ + 'driver' => 'mysql', + 'url' => env('DATABASE_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'forge'), + 'username' => env('DB_USERNAME', 'forge'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_unicode_ci', + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ], + + 'pgsql' => [ + 'driver' => 'pgsql', + 'url' => env('DATABASE_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '5432'), + 'database' => env('DB_DATABASE', 'forge'), + 'username' => env('DB_USERNAME', 'forge'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => 'utf8', + 'prefix' => '', + 'prefix_indexes' => true, + 'schema' => 'public', + 'sslmode' => 'prefer', + ], + + 'sqlsrv' => [ + 'driver' => 'sqlsrv', + 'url' => env('DATABASE_URL'), 'host' => env('DB_HOST', 'localhost'), - 'port' => env('DB_PORT', 27017), - 'database' => env('DB_DATABASE'), - 'username' => env('DB_USERNAME'), - 'password' => env('DB_PASSWORD'), - 'options' => [ - 'database' => 'admin', // sets the authentication database required by mongo 3 - ], + 'port' => env('DB_PORT', '1433'), + 'database' => env('DB_DATABASE', 'forge'), + 'username' => env('DB_USERNAME', 'forge'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => 'utf8', + 'prefix' => '', + 'prefix_indexes' => true, ], + ], + + /* + |-------------------------------------------------------------------------- + | Migration Repository Table + |-------------------------------------------------------------------------- + | + | This table keeps track of all the migrations that have already run for + | your application. Using this information, we can determine which of + | the migrations on disk haven't actually been run in the database. + | + */ + 'migrations' => 'migrations', + /* + |-------------------------------------------------------------------------- + | Redis Databases + |-------------------------------------------------------------------------- + | + | Redis is an open source, fast, and advanced key-value store that also + | provides a richer body of commands than a typical key-value system + | such as APC or Memcached. Laravel makes it easy to dig right in. + | + */ + 'redis' => [ + 'client' => env('REDIS_CLIENT', 'phpredis'), 'options' => [ 'cluster' => env('REDIS_CLUSTER', 'redis'), - 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'lumen'), '_').'_database_'), + 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), ], 'default' => [ @@ -42,5 +141,7 @@ 'port' => env('REDIS_PORT', '6379'), 'database' => env('REDIS_CACHE_DB', '1'), ], + ], + ]; diff --git a/config/filesystems.php b/config/filesystems.php new file mode 100644 index 0000000..760ef97 --- /dev/null +++ b/config/filesystems.php @@ -0,0 +1,73 @@ + env('FILESYSTEM_DRIVER', 'local'), + + /* + |-------------------------------------------------------------------------- + | Filesystem Disks + |-------------------------------------------------------------------------- + | + | Here you may configure as many filesystem "disks" as you wish, and you + | may even configure multiple disks of the same driver. Defaults have + | been setup for each driver as an example of the required options. + | + | Supported Drivers: "local", "ftp", "sftp", "s3" + | + */ + + 'disks' => [ + + 'local' => [ + 'driver' => 'local', + 'root' => storage_path('app'), + ], + + 'public' => [ + 'driver' => 'local', + 'root' => storage_path('app/public'), + 'url' => env('APP_URL').'/storage', + 'visibility' => 'public', + ], + + 's3' => [ + 'driver' => 's3', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION'), + 'bucket' => env('AWS_BUCKET'), + 'url' => env('AWS_URL'), + 'endpoint' => env('AWS_ENDPOINT'), + 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Symbolic Links + |-------------------------------------------------------------------------- + | + | Here you may configure the symbolic links that will be created when the + | `storage:link` Artisan command is executed. The array keys should be + | the locations of the links and the values should be their targets. + | + */ + + 'links' => [ + public_path('storage') => storage_path('app/public'), + ], + +]; diff --git a/config/hashing.php b/config/hashing.php new file mode 100644 index 0000000..bcd3be4 --- /dev/null +++ b/config/hashing.php @@ -0,0 +1,52 @@ + 'bcrypt', + + /* + |-------------------------------------------------------------------------- + | Bcrypt Options + |-------------------------------------------------------------------------- + | + | Here you may specify the configuration options that should be used when + | passwords are hashed using the Bcrypt algorithm. This will allow you + | to control the amount of time it takes to hash the given password. + | + */ + + 'bcrypt' => [ + 'rounds' => env('BCRYPT_ROUNDS', 10), + ], + + /* + |-------------------------------------------------------------------------- + | Argon Options + |-------------------------------------------------------------------------- + | + | Here you may specify the configuration options that should be used when + | passwords are hashed using the Argon algorithm. These will allow you + | to control the amount of time it takes to hash the given password. + | + */ + + 'argon' => [ + 'memory' => 65536, + 'threads' => 1, + 'time' => 4, + ], + +]; diff --git a/config/logging.php b/config/logging.php index d561b96..880cd92 100644 --- a/config/logging.php +++ b/config/logging.php @@ -50,40 +50,34 @@ 'channels' => [ 'stack' => [ 'driver' => 'stack', - 'channels' => ['daily'], + 'channels' => ['single'], + 'ignore_exceptions' => false, ], 'single' => [ 'driver' => 'single', - 'path' => storage_path('logs/lumen.log'), - 'level' => 'debug', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), ], - 'anepc' => [ - 'driver' => 'single', - 'path' => storage_path('logs/anepc.log'), - 'level' => 'debug', - ], - - 'daily' => [ 'driver' => 'daily', - 'path' => storage_path('logs/lumen.log'), - 'level' => 'debug', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), 'days' => 14, ], 'slack' => [ 'driver' => 'slack', 'url' => env('LOG_SLACK_WEBHOOK_URL'), - 'username' => 'Lumen Log', + 'username' => 'Laravel Log', 'emoji' => ':boom:', - 'level' => 'critical', + 'level' => env('LOG_LEVEL', 'critical'), ], 'papertrail' => [ 'driver' => 'monolog', - 'level' => 'debug', + 'level' => env('LOG_LEVEL', 'debug'), 'handler' => SyslogUdpHandler::class, 'handler_with' => [ 'host' => env('PAPERTRAIL_URL'), @@ -93,7 +87,9 @@ 'stderr' => [ 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), 'handler' => StreamHandler::class, + 'formatter' => env('LOG_STDERR_FORMATTER'), 'with' => [ 'stream' => 'php://stderr', ], @@ -101,18 +97,22 @@ 'syslog' => [ 'driver' => 'syslog', - 'level' => 'debug', + 'level' => env('LOG_LEVEL', 'debug'), ], 'errorlog' => [ 'driver' => 'errorlog', - 'level' => 'debug', + 'level' => env('LOG_LEVEL', 'debug'), ], 'null' => [ 'driver' => 'monolog', 'handler' => NullHandler::class, ], + + 'emergency' => [ + 'path' => storage_path('logs/laravel.log'), + ], ], ]; diff --git a/config/mail.php b/config/mail.php new file mode 100644 index 0000000..f96c6c7 --- /dev/null +++ b/config/mail.php @@ -0,0 +1,118 @@ + env('MAIL_MAILER', 'smtp'), + + /* + |-------------------------------------------------------------------------- + | Mailer Configurations + |-------------------------------------------------------------------------- + | + | Here you may configure all of the mailers used by your application plus + | their respective settings. Several examples have been configured for + | you and you are free to add your own as your application requires. + | + | Laravel supports a variety of mail "transport" drivers to be used while + | sending an e-mail. You will specify which one you are using for your + | mailers below. You are free to add additional mailers as required. + | + | Supported: "smtp", "sendmail", "mailgun", "ses", + | "postmark", "log", "array", "failover" + | + */ + + 'mailers' => [ + 'smtp' => [ + 'transport' => 'smtp', + 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), + 'port' => env('MAIL_PORT', 587), + 'encryption' => env('MAIL_ENCRYPTION', 'tls'), + 'username' => env('MAIL_USERNAME'), + 'password' => env('MAIL_PASSWORD'), + 'timeout' => null, + 'auth_mode' => null, + ], + + 'ses' => [ + 'transport' => 'ses', + ], + + 'mailgun' => [ + 'transport' => 'mailgun', + ], + + 'postmark' => [ + 'transport' => 'postmark', + ], + + 'sendmail' => [ + 'transport' => 'sendmail', + 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -t -i'), + ], + + 'log' => [ + 'transport' => 'log', + 'channel' => env('MAIL_LOG_CHANNEL'), + ], + + 'array' => [ + 'transport' => 'array', + ], + + 'failover' => [ + 'transport' => 'failover', + 'mailers' => [ + 'smtp', + 'log', + ], + ], + ], + + /* + |-------------------------------------------------------------------------- + | Global "From" Address + |-------------------------------------------------------------------------- + | + | You may wish for all e-mails sent by your application to be sent from + | the same address. Here, you may specify a name and address that is + | used globally for all e-mails that are sent by your application. + | + */ + + 'from' => [ + 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), + 'name' => env('MAIL_FROM_NAME', 'Example'), + ], + + /* + |-------------------------------------------------------------------------- + | Markdown Mail Settings + |-------------------------------------------------------------------------- + | + | If you are using Markdown based email rendering, you may configure your + | theme and component paths here, allowing you to customize the design + | of the emails. Or, you may simply stick with the Laravel defaults! + | + */ + + 'markdown' => [ + 'theme' => 'default', + + 'paths' => [ + resource_path('views/vendor/mail'), + ], + ], + +]; diff --git a/config/queue.php b/config/queue.php new file mode 100644 index 0000000..25ea5a8 --- /dev/null +++ b/config/queue.php @@ -0,0 +1,93 @@ + env('QUEUE_CONNECTION', 'sync'), + + /* + |-------------------------------------------------------------------------- + | Queue Connections + |-------------------------------------------------------------------------- + | + | Here you may configure the connection information for each server that + | is used by your application. A default configuration has been added + | for each back-end shipped with Laravel. You are free to add more. + | + | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" + | + */ + + 'connections' => [ + + 'sync' => [ + 'driver' => 'sync', + ], + + 'database' => [ + 'driver' => 'database', + 'table' => 'jobs', + 'queue' => 'default', + 'retry_after' => 90, + 'after_commit' => false, + ], + + 'beanstalkd' => [ + 'driver' => 'beanstalkd', + 'host' => 'localhost', + 'queue' => 'default', + 'retry_after' => 90, + 'block_for' => 0, + 'after_commit' => false, + ], + + 'sqs' => [ + 'driver' => 'sqs', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), + 'queue' => env('SQS_QUEUE', 'default'), + 'suffix' => env('SQS_SUFFIX'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'after_commit' => false, + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => 'default', + 'queue' => env('REDIS_QUEUE', 'default'), + 'retry_after' => 90, + 'block_for' => null, + 'after_commit' => false, + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Failed Queue Jobs + |-------------------------------------------------------------------------- + | + | These options configure the behavior of failed queue job logging so you + | can control which database and table are used to store the jobs that + | have failed. You may change them to any database / table you wish. + | + */ + + 'failed' => [ + 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), + 'database' => env('DB_CONNECTION', 'mysql'), + 'table' => 'failed_jobs', + ], + +]; diff --git a/config/sanctum.php b/config/sanctum.php new file mode 100644 index 0000000..9281c92 --- /dev/null +++ b/config/sanctum.php @@ -0,0 +1,65 @@ + explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( + '%s%s', + 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', + env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : '' + ))), + + /* + |-------------------------------------------------------------------------- + | Sanctum Guards + |-------------------------------------------------------------------------- + | + | This array contains the authentication guards that will be checked when + | Sanctum is trying to authenticate a request. If none of these guards + | are able to authenticate the request, Sanctum will use the bearer + | token that's present on an incoming request for authentication. + | + */ + + 'guard' => ['web'], + + /* + |-------------------------------------------------------------------------- + | Expiration Minutes + |-------------------------------------------------------------------------- + | + | This value controls the number of minutes until an issued token will be + | considered expired. If this value is null, personal access tokens do + | not expire. This won't tweak the lifetime of first-party sessions. + | + */ + + 'expiration' => null, + + /* + |-------------------------------------------------------------------------- + | Sanctum Middleware + |-------------------------------------------------------------------------- + | + | When authenticating your first-party SPA with Sanctum you may need to + | customize some of the middleware Sanctum uses while processing the + | request. You may change the middleware listed below as required. + | + */ + + 'middleware' => [ + 'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class, + 'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class, + ], + +]; diff --git a/config/services.php b/config/services.php new file mode 100644 index 0000000..2a1d616 --- /dev/null +++ b/config/services.php @@ -0,0 +1,33 @@ + [ + 'domain' => env('MAILGUN_DOMAIN'), + 'secret' => env('MAILGUN_SECRET'), + 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), + ], + + 'postmark' => [ + 'token' => env('POSTMARK_TOKEN'), + ], + + 'ses' => [ + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + ], + +]; diff --git a/config/session.php b/config/session.php new file mode 100644 index 0000000..ac0802b --- /dev/null +++ b/config/session.php @@ -0,0 +1,201 @@ + env('SESSION_DRIVER', 'file'), + + /* + |-------------------------------------------------------------------------- + | Session Lifetime + |-------------------------------------------------------------------------- + | + | Here you may specify the number of minutes that you wish the session + | to be allowed to remain idle before it expires. If you want them + | to immediately expire on the browser closing, set that option. + | + */ + + 'lifetime' => env('SESSION_LIFETIME', 120), + + 'expire_on_close' => false, + + /* + |-------------------------------------------------------------------------- + | Session Encryption + |-------------------------------------------------------------------------- + | + | This option allows you to easily specify that all of your session data + | should be encrypted before it is stored. All encryption will be run + | automatically by Laravel and you can use the Session like normal. + | + */ + + 'encrypt' => false, + + /* + |-------------------------------------------------------------------------- + | Session File Location + |-------------------------------------------------------------------------- + | + | When using the native session driver, we need a location where session + | files may be stored. A default has been set for you but a different + | location may be specified. This is only needed for file sessions. + | + */ + + 'files' => storage_path('framework/sessions'), + + /* + |-------------------------------------------------------------------------- + | Session Database Connection + |-------------------------------------------------------------------------- + | + | When using the "database" or "redis" session drivers, you may specify a + | connection that should be used to manage these sessions. This should + | correspond to a connection in your database configuration options. + | + */ + + 'connection' => env('SESSION_CONNECTION', null), + + /* + |-------------------------------------------------------------------------- + | Session Database Table + |-------------------------------------------------------------------------- + | + | When using the "database" session driver, you may specify the table we + | should use to manage the sessions. Of course, a sensible default is + | provided for you; however, you are free to change this as needed. + | + */ + + 'table' => 'sessions', + + /* + |-------------------------------------------------------------------------- + | Session Cache Store + |-------------------------------------------------------------------------- + | + | While using one of the framework's cache driven session backends you may + | list a cache store that should be used for these sessions. This value + | must match with one of the application's configured cache "stores". + | + | Affects: "apc", "dynamodb", "memcached", "redis" + | + */ + + 'store' => env('SESSION_STORE', null), + + /* + |-------------------------------------------------------------------------- + | Session Sweeping Lottery + |-------------------------------------------------------------------------- + | + | Some session drivers must manually sweep their storage location to get + | rid of old sessions from storage. Here are the chances that it will + | happen on a given request. By default, the odds are 2 out of 100. + | + */ + + 'lottery' => [2, 100], + + /* + |-------------------------------------------------------------------------- + | Session Cookie Name + |-------------------------------------------------------------------------- + | + | Here you may change the name of the cookie used to identify a session + | instance by ID. The name specified here will get used every time a + | new session cookie is created by the framework for every driver. + | + */ + + 'cookie' => env( + 'SESSION_COOKIE', + Str::slug(env('APP_NAME', 'laravel'), '_').'_session' + ), + + /* + |-------------------------------------------------------------------------- + | Session Cookie Path + |-------------------------------------------------------------------------- + | + | The session cookie path determines the path for which the cookie will + | be regarded as available. Typically, this will be the root path of + | your application but you are free to change this when necessary. + | + */ + + 'path' => '/', + + /* + |-------------------------------------------------------------------------- + | Session Cookie Domain + |-------------------------------------------------------------------------- + | + | Here you may change the domain of the cookie used to identify a session + | in your application. This will determine which domains the cookie is + | available to in your application. A sensible default has been set. + | + */ + + 'domain' => env('SESSION_DOMAIN', null), + + /* + |-------------------------------------------------------------------------- + | HTTPS Only Cookies + |-------------------------------------------------------------------------- + | + | By setting this option to true, session cookies will only be sent back + | to the server if the browser has a HTTPS connection. This will keep + | the cookie from being sent to you when it can't be done securely. + | + */ + + 'secure' => env('SESSION_SECURE_COOKIE'), + + /* + |-------------------------------------------------------------------------- + | HTTP Access Only + |-------------------------------------------------------------------------- + | + | Setting this value to true will prevent JavaScript from accessing the + | value of the cookie and the cookie will only be accessible through + | the HTTP protocol. You are free to modify this option if needed. + | + */ + + 'http_only' => true, + + /* + |-------------------------------------------------------------------------- + | Same-Site Cookies + |-------------------------------------------------------------------------- + | + | This option determines how your cookies behave when cross-site requests + | take place, and can be used to mitigate CSRF attacks. By default, we + | will set this value to "lax" since this is a secure default value. + | + | Supported: "lax", "strict", "none", null + | + */ + + 'same_site' => 'lax', + +]; diff --git a/config/view.php b/config/view.php new file mode 100644 index 0000000..22b8a18 --- /dev/null +++ b/config/view.php @@ -0,0 +1,36 @@ + [ + resource_path('views'), + ], + + /* + |-------------------------------------------------------------------------- + | Compiled View Path + |-------------------------------------------------------------------------- + | + | This option determines where all the compiled Blade templates will be + | stored for your application. Typically, this is within the storage + | directory. However, as usual, you are free to change this value. + | + */ + + 'compiled' => env( + 'VIEW_COMPILED_PATH', + realpath(storage_path('framework/views')) + ), + +]; diff --git a/phpunit.xml b/phpunit.xml index 853e786..4ae4d97 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -5,13 +5,27 @@ colors="true" > - - ./tests + + ./tests/Unit + + + ./tests/Feature + + + ./app + + - - - + + + + + + + + + diff --git a/public/index.php b/public/index.php index 04aa086..1d69f3a 100644 --- a/public/index.php +++ b/public/index.php @@ -1,28 +1,55 @@ run(); +$app = require_once __DIR__.'/../bootstrap/app.php'; + +$kernel = $app->make(Kernel::class); + +$response = $kernel->handle( + $request = Request::capture() +)->send(); + +$kernel->terminate($request, $response); diff --git a/resources/css/app.css b/resources/css/app.css new file mode 100644 index 0000000..e69de29 diff --git a/resources/js/app.js b/resources/js/app.js new file mode 100644 index 0000000..40c55f6 --- /dev/null +++ b/resources/js/app.js @@ -0,0 +1 @@ +require('./bootstrap'); diff --git a/resources/js/bootstrap.js b/resources/js/bootstrap.js new file mode 100644 index 0000000..6922577 --- /dev/null +++ b/resources/js/bootstrap.js @@ -0,0 +1,28 @@ +window._ = require('lodash'); + +/** + * We'll load the axios HTTP library which allows us to easily issue requests + * to our Laravel back-end. This library automatically handles sending the + * CSRF token as a header based on the value of the "XSRF" token cookie. + */ + +window.axios = require('axios'); + +window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; + +/** + * Echo exposes an expressive API for subscribing to channels and listening + * for events that are broadcast by Laravel. Echo and event broadcasting + * allows your team to easily build robust real-time web applications. + */ + +// import Echo from 'laravel-echo'; + +// window.Pusher = require('pusher-js'); + +// window.Echo = new Echo({ +// broadcaster: 'pusher', +// key: process.env.MIX_PUSHER_APP_KEY, +// cluster: process.env.MIX_PUSHER_APP_CLUSTER, +// forceTLS: true +// }); diff --git a/resources/lang/en/auth.php b/resources/lang/en/auth.php new file mode 100644 index 0000000..6598e2c --- /dev/null +++ b/resources/lang/en/auth.php @@ -0,0 +1,20 @@ + 'These credentials do not match our records.', + 'password' => 'The provided password is incorrect.', + 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', + +]; diff --git a/resources/lang/en/pagination.php b/resources/lang/en/pagination.php new file mode 100644 index 0000000..d481411 --- /dev/null +++ b/resources/lang/en/pagination.php @@ -0,0 +1,19 @@ + '« Previous', + 'next' => 'Next »', + +]; diff --git a/resources/lang/en/passwords.php b/resources/lang/en/passwords.php new file mode 100644 index 0000000..2345a56 --- /dev/null +++ b/resources/lang/en/passwords.php @@ -0,0 +1,22 @@ + 'Your password has been reset!', + 'sent' => 'We have emailed your password reset link!', + 'throttled' => 'Please wait before retrying.', + 'token' => 'This password reset token is invalid.', + 'user' => "We can't find a user with that email address.", + +]; diff --git a/resources/lang/en/validation.php b/resources/lang/en/validation.php new file mode 100644 index 0000000..783003c --- /dev/null +++ b/resources/lang/en/validation.php @@ -0,0 +1,163 @@ + 'The :attribute must be accepted.', + 'accepted_if' => 'The :attribute must be accepted when :other is :value.', + 'active_url' => 'The :attribute is not a valid URL.', + 'after' => 'The :attribute must be a date after :date.', + 'after_or_equal' => 'The :attribute must be a date after or equal to :date.', + 'alpha' => 'The :attribute must only contain letters.', + 'alpha_dash' => 'The :attribute must only contain letters, numbers, dashes and underscores.', + 'alpha_num' => 'The :attribute must only contain letters and numbers.', + 'array' => 'The :attribute must be an array.', + 'before' => 'The :attribute must be a date before :date.', + 'before_or_equal' => 'The :attribute must be a date before or equal to :date.', + 'between' => [ + 'numeric' => 'The :attribute must be between :min and :max.', + 'file' => 'The :attribute must be between :min and :max kilobytes.', + 'string' => 'The :attribute must be between :min and :max characters.', + 'array' => 'The :attribute must have between :min and :max items.', + ], + 'boolean' => 'The :attribute field must be true or false.', + 'confirmed' => 'The :attribute confirmation does not match.', + 'current_password' => 'The password is incorrect.', + 'date' => 'The :attribute is not a valid date.', + 'date_equals' => 'The :attribute must be a date equal to :date.', + 'date_format' => 'The :attribute does not match the format :format.', + 'declined' => 'The :attribute must be declined.', + 'declined_if' => 'The :attribute must be declined when :other is :value.', + 'different' => 'The :attribute and :other must be different.', + 'digits' => 'The :attribute must be :digits digits.', + 'digits_between' => 'The :attribute must be between :min and :max digits.', + 'dimensions' => 'The :attribute has invalid image dimensions.', + 'distinct' => 'The :attribute field has a duplicate value.', + 'email' => 'The :attribute must be a valid email address.', + 'ends_with' => 'The :attribute must end with one of the following: :values.', + 'enum' => 'The selected :attribute is invalid.', + 'exists' => 'The selected :attribute is invalid.', + 'file' => 'The :attribute must be a file.', + 'filled' => 'The :attribute field must have a value.', + 'gt' => [ + 'numeric' => 'The :attribute must be greater than :value.', + 'file' => 'The :attribute must be greater than :value kilobytes.', + 'string' => 'The :attribute must be greater than :value characters.', + 'array' => 'The :attribute must have more than :value items.', + ], + 'gte' => [ + 'numeric' => 'The :attribute must be greater than or equal to :value.', + 'file' => 'The :attribute must be greater than or equal to :value kilobytes.', + 'string' => 'The :attribute must be greater than or equal to :value characters.', + 'array' => 'The :attribute must have :value items or more.', + ], + 'image' => 'The :attribute must be an image.', + 'in' => 'The selected :attribute is invalid.', + 'in_array' => 'The :attribute field does not exist in :other.', + 'integer' => 'The :attribute must be an integer.', + 'ip' => 'The :attribute must be a valid IP address.', + 'ipv4' => 'The :attribute must be a valid IPv4 address.', + 'ipv6' => 'The :attribute must be a valid IPv6 address.', + 'json' => 'The :attribute must be a valid JSON string.', + 'lt' => [ + 'numeric' => 'The :attribute must be less than :value.', + 'file' => 'The :attribute must be less than :value kilobytes.', + 'string' => 'The :attribute must be less than :value characters.', + 'array' => 'The :attribute must have less than :value items.', + ], + 'lte' => [ + 'numeric' => 'The :attribute must be less than or equal to :value.', + 'file' => 'The :attribute must be less than or equal to :value kilobytes.', + 'string' => 'The :attribute must be less than or equal to :value characters.', + 'array' => 'The :attribute must not have more than :value items.', + ], + 'mac_address' => 'The :attribute must be a valid MAC address.', + 'max' => [ + 'numeric' => 'The :attribute must not be greater than :max.', + 'file' => 'The :attribute must not be greater than :max kilobytes.', + 'string' => 'The :attribute must not be greater than :max characters.', + 'array' => 'The :attribute must not have more than :max items.', + ], + 'mimes' => 'The :attribute must be a file of type: :values.', + 'mimetypes' => 'The :attribute must be a file of type: :values.', + 'min' => [ + 'numeric' => 'The :attribute must be at least :min.', + 'file' => 'The :attribute must be at least :min kilobytes.', + 'string' => 'The :attribute must be at least :min characters.', + 'array' => 'The :attribute must have at least :min items.', + ], + 'multiple_of' => 'The :attribute must be a multiple of :value.', + 'not_in' => 'The selected :attribute is invalid.', + 'not_regex' => 'The :attribute format is invalid.', + 'numeric' => 'The :attribute must be a number.', + 'password' => 'The password is incorrect.', + 'present' => 'The :attribute field must be present.', + 'prohibited' => 'The :attribute field is prohibited.', + 'prohibited_if' => 'The :attribute field is prohibited when :other is :value.', + 'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.', + 'prohibits' => 'The :attribute field prohibits :other from being present.', + 'regex' => 'The :attribute format is invalid.', + 'required' => 'The :attribute field is required.', + 'required_array_keys' => 'The :attribute field must contain entries for: :values.', + 'required_if' => 'The :attribute field is required when :other is :value.', + 'required_unless' => 'The :attribute field is required unless :other is in :values.', + 'required_with' => 'The :attribute field is required when :values is present.', + 'required_with_all' => 'The :attribute field is required when :values are present.', + 'required_without' => 'The :attribute field is required when :values is not present.', + 'required_without_all' => 'The :attribute field is required when none of :values are present.', + 'same' => 'The :attribute and :other must match.', + 'size' => [ + 'numeric' => 'The :attribute must be :size.', + 'file' => 'The :attribute must be :size kilobytes.', + 'string' => 'The :attribute must be :size characters.', + 'array' => 'The :attribute must contain :size items.', + ], + 'starts_with' => 'The :attribute must start with one of the following: :values.', + 'string' => 'The :attribute must be a string.', + 'timezone' => 'The :attribute must be a valid timezone.', + 'unique' => 'The :attribute has already been taken.', + 'uploaded' => 'The :attribute failed to upload.', + 'url' => 'The :attribute must be a valid URL.', + 'uuid' => 'The :attribute must be a valid UUID.', + + /* + |-------------------------------------------------------------------------- + | Custom Validation Language Lines + |-------------------------------------------------------------------------- + | + | Here you may specify custom validation messages for attributes using the + | convention "attribute.rule" to name the lines. This makes it quick to + | specify a specific custom language line for a given attribute rule. + | + */ + + 'custom' => [ + 'attribute-name' => [ + 'rule-name' => 'custom-message', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Validation Attributes + |-------------------------------------------------------------------------- + | + | The following language lines are used to swap our attribute placeholder + | with something more reader friendly such as "E-Mail Address" instead + | of "email". This simply helps us make our message more expressive. + | + */ + + 'attributes' => [], + +]; diff --git a/resources/views/welcome.blade.php b/resources/views/welcome.blade.php new file mode 100644 index 0000000..dd6a45d --- /dev/null +++ b/resources/views/welcome.blade.php @@ -0,0 +1,132 @@ + + + + + + + Laravel + + + + + + + + + + +
+ @if (Route::has('login')) + + @endif + +
+
+ + + + + +
+ +
+
+
+ + +
+
+ Laravel has wonderful, thorough documentation covering every aspect of the framework. Whether you are new to the framework or have previous experience with Laravel, we recommend reading all of the documentation from beginning to end. +
+
+
+ +
+
+ + +
+ +
+
+ Laracasts offers thousands of video tutorials on Laravel, PHP, and JavaScript development. Check them out, see for yourself, and massively level up your development skills in the process. +
+
+
+ +
+
+ + +
+ +
+
+ Laravel News is a community driven portal and newsletter aggregating all of the latest and most important news in the Laravel ecosystem, including new package releases and tutorials. +
+
+
+ +
+
+ +
Vibrant Ecosystem
+
+ +
+
+ Laravel's robust library of first-party tools and libraries, such as Forge, Vapor, Nova, and Envoyer help you take your projects to the next level. Pair them with powerful open source libraries like Cashier, Dusk, Echo, Horizon, Sanctum, Telescope, and more. +
+
+
+
+
+ +
+
+
+ + + + + + Shop + + + + + + + + Sponsor + +
+
+ +
+ Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }}) +
+
+
+
+ + diff --git a/routes/api.php b/routes/api.php new file mode 100644 index 0000000..cefa813 --- /dev/null +++ b/routes/api.php @@ -0,0 +1,110 @@ + $router->app->version()); + +// LEGACY +Route::get('/new/fires', '\App\Http\Controllers\LegacyController@newFires'); +Route::get('/fires/data', '\App\Http\Controllers\LegacyController@firesData'); + +Route::group(['prefix' => 'fires'], function () { + Route::get('/', '\App\Http\Controllers\LegacyController@fires'); + Route::get('/danger', '\App\Http\Controllers\LegacyController@firesDanger'); + Route::get('/status', '\App\Http\Controllers\LegacyController@firesStatus'); +}); + +Route::group(['prefix' => 'madeira'], function () { + Route::get('/fires', '\App\Http\Controllers\LegacyController@firesMadeira'); + Route::get('/fires/status', '\App\Http\Controllers\LegacyController@firesStatusMadeira'); +}); + +Route::group(['prefix' => 'v1'], function () { + Route::get('warnings', '\App\Http\Controllers\LegacyController@warnings'); + Route::get('warnings/site', '\App\Http\Controllers\LegacyController@warningsSite'); + Route::get('madeira/warnings', '\App\Http\Controllers\LegacyController@warningsMadeira'); + Route::get('now', '\App\Http\Controllers\LegacyController@now'); + Route::get('now/data', '\App\Http\Controllers\LegacyController@nowData'); + Route::get('status', '\App\Http\Controllers\LegacyController@status'); + Route::get('active', '\App\Http\Controllers\LegacyController@active'); + Route::get('aerial', '\App\Http\Controllers\LegacyController@aerial'); + Route::get('stats', '\App\Http\Controllers\LegacyController@stats'); + Route::get('risk', '\App\Http\Controllers\LegacyController@risk'); + Route::get('risk-today', '\App\Http\Controllers\LegacyController@riskToday'); + Route::get('risk-tomorrow', '\App\Http\Controllers\LegacyController@riskTomorrow'); + Route::get('risk-after', '\App\Http\Controllers\LegacyController@riskAfter'); + Route::get('list', '\App\Http\Controllers\LegacyController@listConcelho'); + + Route::group(['prefix' => 'stats'], function () { + Route::get('8hours', '\App\Http\Controllers\LegacyController@stats8hours'); + Route::get('8hours/yesterday', '\App\Http\Controllers\LegacyController@stats8hoursYesterday'); + Route::get('last-night', '\App\Http\Controllers\LegacyController@lastNight'); + Route::get('week', '\App\Http\Controllers\LegacyController@statsWeek'); + Route::get('today', '\App\Http\Controllers\LegacyController@statsToday'); + Route::get('yesterday', '\App\Http\Controllers\LegacyController@statsYesterday'); + Route::get('burn-area', '\App\Http\Controllers\LegacyController@burnedAreaLastDays'); + Route::get('motive', '\App\Http\Controllers\LegacyController@motivesThisMonths'); + + }); +}); + +Route::group(['prefix' => 'v2'], function () { + Route::group(['prefix' => 'other'], function () { + Route::get('mobile-contributors', '\App\Http\Controllers\OtherController@getMobileContributors'); + }); + + Route::group(['prefix' => 'incidents'], function () { + Route::get('search', '\App\Http\Controllers\IncidentController@search'); + Route::get('active/kml', '\App\Http\Controllers\IncidentController@activeKML'); + Route::get('active', '\App\Http\Controllers\IncidentController@active'); + Route::get('1000ha-burned', '\App\Http\Controllers\IncidentController@burnMoreThan1000'); + Route::get('{id}/kml', '\App\Http\Controllers\IncidentController@kml'); + Route::get('{id}/kmlVost', '\App\Http\Controllers\IncidentController@kmlVost'); + + Route::post('{id}/posit', '\App\Http\Controllers\IncidentController@addPosit'); + Route::post('{id}/kml', '\App\Http\Controllers\IncidentController@addKML'); + }); + + Route::group(['prefix' => 'weather'], function () { + Route::get('thunders', '\App\Http\Controllers\WeatherController@thunders'); + Route::get('stations', '\App\Http\Controllers\WeatherController@stations'); + Route::get('daily', '\App\Http\Controllers\WeatherController@daily'); + Route::get('ipma-services', '\App\Http\Controllers\WeatherController@ipmaServicesHTTPS'); + }); + + Route::group(['prefix' => 'rcm'], function () { + Route::get('today', '\App\Http\Controllers\RCMController@today'); + Route::get('tomorrow', '\App\Http\Controllers\RCMController@tomorrow'); + Route::get('after', '\App\Http\Controllers\RCMController@after'); + Route::get('parish', '\App\Http\Controllers\RCMController@parish'); + }); + + Route::group(['prefix' => 'planes'], function () { + Route::get('{icao}', '\App\Http\Controllers\PlanesController@icao'); + + }); + + Route::group(['prefix' => 'warnings'], function () { + Route::post('add', '\App\Http\Controllers\WarningsController@add'); + }); + + Route::group(['prefix' => 'stats'], function () { + Route::group(['prefix' => 'today'], function () { + Route::get('ignitions-hourly', '\App\Http\Controllers\StatsController@ignitionsHourly'); + + }); + + }); +}); diff --git a/routes/channels.php b/routes/channels.php new file mode 100644 index 0000000..5d451e1 --- /dev/null +++ b/routes/channels.php @@ -0,0 +1,18 @@ +id === (int) $id; +}); diff --git a/routes/console.php b/routes/console.php new file mode 100644 index 0000000..e05f4c9 --- /dev/null +++ b/routes/console.php @@ -0,0 +1,19 @@ +comment(Inspiring::quote()); +})->purpose('Display an inspiring quote'); diff --git a/routes/web.php b/routes/web.php index 44933af..b130397 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,97 +1,18 @@ get('/', fn () => $router->app->version()); - -// LEGACY -$router->get('/new/fires', '\App\Http\Controllers\LegacyController@newFires'); -$router->get('/fires/data', '\App\Http\Controllers\LegacyController@firesData'); - -$router->group(['prefix' => 'fires'], function () use ($router) { - $router->get('/', '\App\Http\Controllers\LegacyController@fires'); - $router->get('/danger', '\App\Http\Controllers\LegacyController@firesDanger'); - $router->get('/status', '\App\Http\Controllers\LegacyController@firesStatus'); -}); - -$router->group(['prefix' => 'madeira'], function () use ($router) { - $router->get('/fires', '\App\Http\Controllers\LegacyController@firesMadeira'); - $router->get('/fires/status', '\App\Http\Controllers\LegacyController@firesStatusMadeira'); -}); - -$router->group(['prefix' => 'v1'], function () use ($router) { - $router->get('warnings', '\App\Http\Controllers\LegacyController@warnings'); - $router->get('warnings/site', '\App\Http\Controllers\LegacyController@warningsSite'); - $router->get('madeira/warnings', '\App\Http\Controllers\LegacyController@warningsMadeira'); - $router->get('now', '\App\Http\Controllers\LegacyController@now'); - $router->get('now/data', '\App\Http\Controllers\LegacyController@nowData'); - $router->get('status', '\App\Http\Controllers\LegacyController@status'); - $router->get('active', '\App\Http\Controllers\LegacyController@active'); - $router->get('aerial', '\App\Http\Controllers\LegacyController@aerial'); - $router->get('stats', '\App\Http\Controllers\LegacyController@stats'); - $router->get('risk', '\App\Http\Controllers\LegacyController@risk'); - $router->get('risk-today', '\App\Http\Controllers\LegacyController@riskToday'); - $router->get('risk-tomorrow', '\App\Http\Controllers\LegacyController@riskTomorrow'); - $router->get('risk-after', '\App\Http\Controllers\LegacyController@riskAfter'); - $router->get('list', '\App\Http\Controllers\LegacyController@listConcelho'); - - $router->group(['prefix' => 'stats'], function () use ($router) { - $router->get('8hours', '\App\Http\Controllers\LegacyController@stats8hours'); - $router->get('8hours/yesterday', '\App\Http\Controllers\LegacyController@stats8hoursYesterday'); - $router->get('last-night', '\App\Http\Controllers\LegacyController@lastNight'); - $router->get('week', '\App\Http\Controllers\LegacyController@statsWeek'); - $router->get('today', '\App\Http\Controllers\LegacyController@statsToday'); - $router->get('yesterday', '\App\Http\Controllers\LegacyController@statsYesterday'); - $router->get('burn-area', '\App\Http\Controllers\LegacyController@burnedAreaLastDays'); - $router->get('motive', '\App\Http\Controllers\LegacyController@motivesThisMonths'); - - }); -}); - -$router->group(['prefix' => 'v2'], function () use ($router) { - $router->group(['prefix' => 'other'], function () use ($router) { - $router->get('mobile-contributors', '\App\Http\Controllers\OtherController@getMobileContributors'); - }); - - $router->group(['prefix' => 'incidents'], function () use ($router) { - $router->get('search', '\App\Http\Controllers\IncidentController@search'); - $router->get('active/kml', '\App\Http\Controllers\IncidentController@activeKML'); - $router->get('active', '\App\Http\Controllers\IncidentController@active'); - $router->get('1000ha-burned', '\App\Http\Controllers\IncidentController@burnMoreThan1000'); - $router->get('{id}/kml', '\App\Http\Controllers\IncidentController@kml'); - $router->get('{id}/kmlVost', '\App\Http\Controllers\IncidentController@kmlVost'); - - $router->post('{id}/posit', '\App\Http\Controllers\IncidentController@addPosit'); - $router->post('{id}/kml', '\App\Http\Controllers\IncidentController@addKML'); - }); - - $router->group(['prefix' => 'weather'], function () use ($router) { - $router->get('thunders', '\App\Http\Controllers\WeatherController@thunders'); - $router->get('stations', '\App\Http\Controllers\WeatherController@stations'); - $router->get('daily', '\App\Http\Controllers\WeatherController@daily'); - $router->get('ipma-services', '\App\Http\Controllers\WeatherController@ipmaServicesHTTPS'); - }); - - $router->group(['prefix' => 'rcm'], function () use ($router) { - $router->get('today', '\App\Http\Controllers\RCMController@today'); - $router->get('tomorrow', '\App\Http\Controllers\RCMController@tomorrow'); - $router->get('after', '\App\Http\Controllers\RCMController@after'); - $router->get('parish', '\App\Http\Controllers\RCMController@parish'); - }); - - $router->group(['prefix' => 'planes'], function () use ($router) { - $router->get('{icao}', '\App\Http\Controllers\PlanesController@icao'); - - }); - - $router->group(['prefix' => 'warnings'], function () use ($router) { - $router->post('add', '\App\Http\Controllers\WarningsController@add'); - }); - - $router->group(['prefix' => 'stats'], function () use ($router) { - $router->group(['prefix' => 'today'], function () use ($router) { - $router->get('ignitions-hourly', '\App\Http\Controllers\StatsController@ignitionsHourly'); - - }); - - }); +use Illuminate\Support\Facades\Route; + +/* +|-------------------------------------------------------------------------- +| Web Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register web routes for your application. These +| routes are loaded by the RouteServiceProvider within a group which +| contains the "web" middleware group. Now create something great! +| +*/ + +Route::get('/', function () { + return view('welcome'); }); diff --git a/server.php b/server.php new file mode 100644 index 0000000..c25c5a0 --- /dev/null +++ b/server.php @@ -0,0 +1,19 @@ + + */ +$uri = urldecode( + parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? '' +); + +// This file allows us to emulate Apache's "mod_rewrite" functionality from the +// built-in PHP web server. This provides a convenient way to test a Laravel +// application without having installed a "real" web server software here. +if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) { + return false; +} + +require_once __DIR__.'/public/index.php'; diff --git a/tests/CreatesApplication.php b/tests/CreatesApplication.php new file mode 100644 index 0000000..547152f --- /dev/null +++ b/tests/CreatesApplication.php @@ -0,0 +1,22 @@ +make(Kernel::class)->bootstrap(); + + return $app; + } +} diff --git a/tests/Feature/Controllers/LegacyController/NewFiresTest.php b/tests/Feature/Controllers/LegacyController/NewFiresTest.php index 50c8d93..3aeb115 100644 --- a/tests/Feature/Controllers/LegacyController/NewFiresTest.php +++ b/tests/Feature/Controllers/LegacyController/NewFiresTest.php @@ -3,7 +3,7 @@ namespace Tests\Feature\Controllers\LegacyController; use Database\Factories\IncidentFactory; -use Laravel\Lumen\Testing\DatabaseMigrations; +use Illuminate\Foundation\Testing\DatabaseMigrations; use Tests\TestCase; class NewFiresTest extends TestCase diff --git a/tests/TestCase.php b/tests/TestCase.php index aebda3a..74d0753 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,8 +2,8 @@ namespace Tests; +use Illuminate\Foundation\Testing\TestCase as BaseTestCase; use Laravel\Lumen\Application; -use Laravel\Lumen\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { diff --git a/tests/Unit/Models/IncidentModelTest.php b/tests/Unit/Models/IncidentModelTest.php index 0954963..2608062 100644 --- a/tests/Unit/Models/IncidentModelTest.php +++ b/tests/Unit/Models/IncidentModelTest.php @@ -73,6 +73,7 @@ public function it_has_correct_dates_properties_casted(): void /** * @test + * * @dataProvider propertiesCastsProvider */ public function it_casts_properties_to_correct_type(string $propertyName, string $cast): void