phpvms/modules/Installer/Http/Controllers/InstallerController.php
Nabeel S 073e48c396
7.0.0-beta3 Release (#541)
* 391 Notification refactorings (#441)

* Refactor notifications to allow easier plugins

* Notification refactoring

* Formatting

* Move news to NewsService; cleanup of events

* More refactoring; added send email out for news item and the template

* Formatting

* Formatting

* Fix missing newsRepo (#445)

* Refactor and add importer to Installer module #443 (#444)

* Refactor and add importer to Installer module #443

* Refactor for finances to use in import

* Import groups into roles

* Formatting

* Formatting

* Add interface in installer for import

* Notes about importing

* Check for installer folder

* Formatting

* Fix pirep->user mapping

* Unused import

* Formatting

* Replace importer with AJAX powered; better error handling #443 (#447)

* Replace importer with AJAX powered; better error handling #443

* Formatting

* Fix command line importer

* Remove bootstrap cache (#448)

* Cleanup the bootstrap/cache directory when packaging

* Fix removal of bootstrap cache

* Formatting

* Stricter checks on ACARS API data (#451)

* Stricter checks on ACARS API data

* More checks

* Fix for flight_number check forcing to exist

* Allow nullable on flight_id

* Avoid proc_open use #455 (#456)

* Use PhpExecutableFinder() closes #457 #458 (#460)

* Use DateTimeZone instead of int for creating datetime

closes #461

* Fix CSV imports giving Storage class not found #454 (#462)

* Fix CSV imports giving Storage class not found #454

* Update yarn files for security alert

* Add PHP 7.4 support (#464)

* Add PHP 7.4 to build matrix

* DB fix

* YAML parser fix in test data

* Show versions

* Package updates

* Track used ICAOs

* 7.4 METAR parsing fix

* METAR parser fix

* Formatting

* Add meters to response units

* Call instance for unit conversion

* Return value

* Catch exception for unknown quantity

* Comment fix

* Formatting

* METAR parsing fixes on PHP 7.4

* Package updates

* More random airport ID

* More random airport ID

* Properly disable toolbar

* Semver written out to version file

* Use dev as default identifier

* Fix BindingResolutionError when debug toolbar isn't present (#465)

* Fix BindingResolutionError when debug toolbar isn't present

* Formatting

* Split the importer module out from the installer module (#468)

* Split the importer module out from the installer module

* Cleanup of unused imports

* Move updater into separate module #453

* Remove unused imports/formatting

* Disable the install and importer modules at the end of the setup

* Unused imports; update IJ style

* test explicit stage for php+mysql

* add more to matrix

* Add different MariaDB versions

* undo

* Cleanup Model doc

* Pilots cannot use the dashboard or flights without admin rights (#481)

* Use auth middleware instead of specific groups for logged in state

* Auth check for admin access

* Check user admin access for updates

* Formatting

* Allow nullable field and calculate distance if nulled for flight import #478 (#482)

* Check for no roles being attached #480 (#483)

* Return the flight fares if there are no subfleet fares #488 (#489)

* Return the flight fares if there are no subfleet fares #488

* Formatting

* Formatting

* Account for units when entering fuel amounts #493

* Search for ICAO not working properly (#496)

* /flights and /flights/search direct to the same endpoint

* Properly set the distance/planned_distance on save (#497)

* 491 Installation Error (#495)

* Disable CSRF token

* Add error handling around looking up the theme and set a default

* Note about logs in issue template

* Formatting

* Fix GeoService errors when viewing PIREP #498 (#499)

* Add new command to export a specific PIREP for debugging (#501)

* Set a default model value for airports on PIREP (#500)

* Set a default model value for airports on PIREP

* Fix airport icao reference

* Default airport models

* Catch broader exception writing out config files #491

* style

* Add reference to docs on doc site (#502)

* Properly create/update rows importing #486 (#503)

* Add base Dockerfile for Dockerhub builds (#504)

* New subfleet not being attached to an airline on import #479 (#505)

* Fix subfleet not being attached to an airline on creation in import #479

* Call airline name with optional() around subfleet

* Minor cleanup

* Search flights by subfleet #484 (#506)

* API level search of flights #484

* Add Subfleet to flights page for search

* Make the fuel used optional (#512)

* Add make to Docker container

* Add getRootDomain() to Utils (#514)

* Show admin dropdown for admin-access ability (#515)

* Show admin dropdown for admin-access ability closes #509

* Formatting

* Check user permissions on the routes #508 (#516)

* Check user permissions on the routes #508

* Formatting

* Return default value on exception for setting()

* Correct text for no subfleets #507 (#518)

* Add a public_url() helper #513 (#519)

* Reduce number of queries for update check (#520)

* Try to clear caches before updating (#522)

* Try to clear caches before updating

* Add clear-compiled to maintenance cache list

* Formatting

* Set PIREPs page to public (#526)

Set PIREPs page to public

* Fix live and route map errors #527 (#528)

* Add menu bar for mobile (#529)

* Format all blade templates to 2 spaces #530 (#531)

* Fix PIREP edit endpoint closes #533 (#534)

* Fix import during flight cron #532 (#535)

* PIREPS resource except for show (#536)

* Use optional() around the airport fields (#537)

* Use optional() around the airport fields

* Add null-coalesce around full_name

* Add link to download ACARS config from profile (#539)

* Add link to download ACARS config from profile

* Formatting

* Update xml config file template (#540)
2020-02-08 13:29:34 -05:00

359 lines
11 KiB
PHP

<?php
namespace Modules\Installer\Http\Controllers;
use App\Contracts\Controller;
use App\Facades\Utils;
use App\Models\User;
use App\Repositories\AirlineRepository;
use App\Services\AnalyticsService;
use App\Services\Installer\DatabaseService;
use App\Services\Installer\InstallerService;
use App\Services\Installer\MigrationService;
use App\Services\Installer\SeederService;
use App\Services\UserService;
use App\Support\Countries;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Modules\Installer\Services\ConfigService;
use Modules\Installer\Services\RequirementsService;
class InstallerController extends Controller
{
private $airlineRepo;
private $analyticsSvc;
private $dbSvc;
private $envSvc;
private $migrationSvc;
private $reqSvc;
private $seederSvc;
private $userService;
/**
* InstallerController constructor.
*
* @param AirlineRepository $airlineRepo
* @param AnalyticsService $analyticsSvc
* @param DatabaseService $dbService
* @param ConfigService $envService
* @param MigrationService $migrationSvc
* @param RequirementsService $reqSvc
* @param SeederService $seederSvc
* @param UserService $userService
*/
public function __construct(
AirlineRepository $airlineRepo,
AnalyticsService $analyticsSvc,
DatabaseService $dbService,
ConfigService $envService,
MigrationService $migrationSvc,
RequirementsService $reqSvc,
SeederService $seederSvc,
UserService $userService
) {
$this->airlineRepo = $airlineRepo;
$this->analyticsSvc = $analyticsSvc;
$this->dbSvc = $dbService;
$this->envSvc = $envService;
$this->migrationSvc = $migrationSvc;
$this->reqSvc = $reqSvc;
$this->seederSvc = $seederSvc;
$this->userService = $userService;
\App\Support\Utils::disableDebugToolbar();
}
/**
* Display a listing of the resource.
*/
public function index()
{
if (config('app.key') !== 'base64:zdgcDqu9PM8uGWCtMxd74ZqdGJIrnw812oRMmwDF6KY=') {
return view('installer::errors/already-installed');
}
return view('installer::install/index-start');
}
protected function testDb(Request $request)
{
$this->dbSvc->checkDbConnection(
$request->post('db_conn'),
$request->post('db_host'),
$request->post('db_port'),
$request->post('db_name'),
$request->post('db_user'),
$request->post('db_pass')
);
}
/**
* Check the database connection
*/
public function dbtest(Request $request)
{
$status = 'success'; // success|warn|danger
$message = 'Database connection looks good!';
try {
$this->testDb($request);
} catch (\Exception $e) {
$status = 'danger';
$message = 'Failed! '.$e->getMessage();
}
return view('installer::install/dbtest', [
'status' => $status,
'message' => $message,
]);
}
/**
* Check if any of the items has been marked as failed
*
* @param array $arr
*
* @return bool
*/
protected function allPassed(array $arr): bool
{
foreach ($arr as $item) {
if ($item['passed'] === false) {
return false;
}
}
return true;
}
/**
* Step 1. Check the modules and permissions
*
* @param Request $request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function step1(Request $request)
{
$php_version = $this->reqSvc->checkPHPVersion();
$extensions = $this->reqSvc->checkExtensions();
$directories = $this->reqSvc->checkPermissions();
// Only pass if all the items in the ext and dirs are passed
$statuses = [
$php_version['passed'] === true,
$this->allPassed($extensions) === true,
$this->allPassed($directories) === true,
];
// Make sure there are no false values
$passed = !\in_array(false, $statuses, true);
return view('installer::install/steps/step1-requirements', [
'php' => $php_version,
'extensions' => $extensions,
'directories' => $directories,
'passed' => $passed,
]);
}
/**
* Step 2. Database Setup
*
* @param Request $request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function step2(Request $request)
{
$db_types = ['mysql' => 'mysql', 'sqlite' => 'sqlite'];
return view('installer::install/steps/step2-db', [
'db_types' => $db_types,
]);
}
/**
* Step 2a. Create the .env
*
* @param Request $request
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function envsetup(Request $request)
{
$log_str = $request->post();
$log_str['db_pass'] = '';
Log::info('ENV setup', $log_str);
// Before writing out the env file, test the DB credentials
try {
$this->testDb($request);
} catch (\Exception $e) {
Log::error('Testing db before writing configs failed');
Log::error($e->getMessage());
flash()->error($e->getMessage());
return redirect(route('installer.step2'))->withInput();
}
// Now write out the env file
$attrs = [
'SITE_NAME' => $request->post('site_name'),
'SITE_URL' => $request->post('site_url'),
'DB_CONN' => $request->post('db_conn'),
'DB_HOST' => $request->post('db_host'),
'DB_PORT' => $request->post('db_port'),
'DB_NAME' => $request->post('db_name'),
'DB_USER' => $request->post('db_user'),
'DB_PASS' => $request->post('db_pass'),
'DB_PREFIX' => $request->post('db_prefix'),
];
/*
* Create the config files and then redirect so that the
* framework can pickup all those configs, etc, before we
* setup the database and stuff
*/
try {
$this->envSvc->createConfigFiles($attrs);
} catch (\Exception $e) {
Log::error('Config files failed to write');
Log::error($e->getMessage());
flash()->error($e->getMessage());
return redirect(route('installer.step2'))->withInput();
}
// Needs to redirect so it can load the new .env
Log::info('Redirecting to database setup');
return redirect(route('installer.dbsetup'));
}
/**
* Step 2b. Setup the database
*
* @param Request $request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
*/
public function dbsetup(Request $request)
{
$console_out = '';
try {
$console_out .= $this->dbSvc->setupDB();
$console_out .= $this->migrationSvc->runAllMigrations();
$this->seederSvc->syncAllSeeds();
} catch (QueryException $e) {
Log::error('Error on db setup: '.$e->getMessage());
$this->envSvc->removeConfigFiles();
flash()->error($e->getMessage());
return redirect(route('installer.step2'))->withInput();
}
$console_out = trim($console_out);
return view('installer::install/steps/step2a-db_output', [
'console_output' => $console_out,
]);
}
/**
* Step 3. Setup the admin user and initial settings
*/
public function step3(Request $request)
{
return view('installer::install/steps/step3-user', [
'countries' => Countries::getSelectList(),
]);
}
/**
* Step 3 submit
*
* @param Request $request
*
* @throws \RuntimeException
* @throws \Prettus\Validator\Exceptions\ValidatorException
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function usersetup(Request $request)
{
$validator = Validator::make($request->all(), [
'airline_name' => 'required',
'airline_icao' => 'required|size:3|unique:airlines,icao',
'airline_country' => 'required',
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|confirmed',
]);
if ($validator->fails()) {
return redirect('install/step3')
->withErrors($validator)
->withInput();
}
/**
* Create the first airline
*/
$attrs = [
'icao' => $request->get('airline_icao'),
'name' => $request->get('airline_name'),
'country' => $request->get('airline_country'),
];
$airline = $this->airlineRepo->create($attrs);
/**
* Create the user, and associate to the airline
* Ensure the seed data at least has one airport
* KAUS, for giggles, though.
*/
$attrs = [
'name' => $request->get('name'),
'email' => $request->get('email'),
'api_key' => Utils::generateApiKey(),
'airline_id' => $airline->id,
'password' => Hash::make($request->get('password')),
];
$user = User::create($attrs);
$user = $this->userService->createUser($user, ['admin']);
Log::info('User registered: ', $user->toArray());
// Set the initial admin e-mail address
setting_save('general.admin_email', $user->email);
// Save telemetry setting
setting_save('general.telemetry', get_truth_state($request->get('telemetry')));
// Try sending telemetry info
$this->analyticsSvc->sendInstall();
return view('installer::install/steps/step3a-completed', []);
}
/**
* Final step
*
* @param Request $request
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function complete(Request $request)
{
$installerSvc = app(InstallerService::class);
$installerSvc->disableInstallerModules();
return redirect('/login');
}
}