From 3727c84f3edee841e88b8e73df5e6f0a3d439548 Mon Sep 17 00:00:00 2001 From: miguel456 Date: Sun, 15 Jan 2023 00:04:00 +0000 Subject: [PATCH] refactor: code style changes Signed-off-by: miguel456 --- app/Absence.php | 47 +++--- app/Application.php | 1 - app/Console/Commands/Install.php | 140 ++++++++--------- app/Console/Commands/SetEnv.php | 1 + app/CustomFacades/IP.php | 16 +- app/Events/ApplicationApprovedEvent.php | 2 +- .../ApplicationNotFoundException.php | 1 - app/Exceptions/VacancyNotFoundException.php | 1 - app/Facades/DigitalStorageHelper.php | 4 - app/Facades/JSON.php | 4 - app/Helpers/ContextAwareValidator.php | 15 +- app/Helpers/DigitalStorageHelper.php | 28 ++-- app/Helpers/Discord.php | 105 ++++++------- app/Helpers/JSON.php | 41 +++-- app/Helpers/Options.php | 20 ++- app/Http/Controllers/AbsenceController.php | 53 +++---- .../Controllers/ApplicationController.php | 37 ++--- .../Controllers/AppointmentController.php | 26 +--- .../Controllers/Auth/DiscordController.php | 24 +-- app/Http/Controllers/Auth/LoginController.php | 16 +- .../Controllers/Auth/RegisterController.php | 18 +-- app/Http/Controllers/CommentController.php | 4 +- app/Http/Controllers/DashboardController.php | 6 +- app/Http/Controllers/DevToolsController.php | 24 +-- app/Http/Controllers/FormController.php | 16 +- app/Http/Controllers/OptionsController.php | 20 +-- app/Http/Controllers/ProfileController.php | 28 +--- .../SecuritySettingsController.php | 17 +- app/Http/Controllers/TeamController.php | 35 ++--- app/Http/Controllers/TeamFileController.php | 64 +++----- app/Http/Controllers/UserController.php | 147 ++++++++---------- app/Http/Controllers/VacancyController.php | 15 +- .../Middleware/ApplicationEligibility.php | 11 +- app/Http/Middleware/Bancheck.php | 5 +- app/Http/Middleware/ForceLogoutMiddleware.php | 1 - .../PasswordExpirationMiddleware.php | 11 +- .../PasswordExpirationRedirectMiddleware.php | 3 +- app/Http/Middleware/TrustProxies.php | 2 - app/Http/Requests/BanUserRequest.php | 2 +- .../Requests/CancelAppointmentRequest.php | 2 +- app/Http/Requests/ProfileSave.php | 2 +- app/Http/Requests/SaveSecuritySettings.php | 2 +- app/Http/Requests/StoreAbsenceRequest.php | 3 +- app/Http/Requests/UploadFileRequest.php | 2 +- app/Http/Requests/VacancyEditRequest.php | 2 +- app/Http/Requests/VacancyRequest.php | 2 +- app/Http/Resources/ApplicationResource.php | 2 +- app/Http/Resources/FormResource.php | 2 +- app/Http/Resources/ResponseResource.php | 2 +- app/Http/Resources/UserResource.php | 2 +- app/Jobs/ProcessAccountDelete.php | 6 +- app/Jobs/ProcessDueSuspensions.php | 2 - app/Jobs/ProcessExpiredAbsences.php | 1 - app/Listeners/DenyUser.php | 2 +- app/Listeners/NewUser.php | 3 - app/Listeners/OnUserRegistration.php | 3 +- app/Listeners/PromoteUser.php | 4 +- app/Mail/UserAccountDeleteConfirmation.php | 15 +- app/Notifications/AbsenceRequestApproved.php | 4 +- app/Notifications/AbsenceRequestCancelled.php | 4 +- app/Notifications/AbsenceRequestDeclined.php | 4 +- app/Notifications/AbsenceRequestEnded.php | 4 +- app/Notifications/AccountDeleted.php | 4 +- app/Notifications/AccountUnlocked.php | 6 +- app/Notifications/ApplicationApproved.php | 6 +- app/Notifications/ApplicationConfirmed.php | 7 +- app/Notifications/ApplicationDenied.php | 4 +- app/Notifications/ApplicationMoved.php | 9 +- app/Notifications/AppointmentCancelled.php | 9 +- app/Notifications/AppointmentFinished.php | 8 +- app/Notifications/AppointmentScheduled.php | 4 +- app/Notifications/ChangedPassword.php | 4 +- app/Notifications/EmailChanged.php | 4 +- app/Notifications/NewAbsenceRequest.php | 4 +- app/Notifications/NewApplicant.php | 4 +- app/Notifications/NewComment.php | 4 +- app/Notifications/NewContact.php | 4 +- app/Notifications/NewUser.php | 6 +- app/Notifications/UserBanned.php | 4 +- app/Notifications/UserDeletedAccount.php | 4 +- app/Notifications/VacancyStatusUpdated.php | 12 +- app/Observers/UserObserver.php | 16 +- app/OneoffApplicant.php | 1 - app/Policies/AbsencePolicy.php | 32 ++-- app/Policies/ApiKeyPolicy.php | 14 +- app/Policies/AppointmentPolicy.php | 24 +-- app/Policies/BanPolicy.php | 4 +- app/Policies/TeamPolicy.php | 4 +- app/Providers/AppServiceProvider.php | 14 +- app/Providers/AuthServiceProvider.php | 18 +-- app/Providers/DigitalStorageProvider.php | 4 +- app/Providers/EventServiceProvider.php | 5 - app/Providers/JSONProvider.php | 2 +- app/Services/AbsenceService.php | 53 +++---- app/Services/AccountSuspensionService.php | 64 ++++---- app/Services/ApplicationService.php | 49 +++--- app/Services/AppointmentService.php | 38 ++--- app/Services/CommentService.php | 7 +- app/Services/ConfigurationService.php | 24 +-- app/Services/ContactService.php | 5 - app/Services/DemoService.php | 10 +- app/Services/DiscordService.php | 12 +- app/Services/FormManagementService.php | 23 ++- app/Services/MeetingNoteService.php | 12 +- app/Services/ProfileService.php | 29 ++-- app/Services/SecuritySettingsService.php | 24 +-- app/Services/TeamFileService.php | 19 +-- app/Services/TeamService.php | 29 ++-- app/Services/VacancyApplicationService.php | 2 +- app/Team.php | 2 - app/TeamFile.php | 4 +- app/Traits/Cancellable.php | 2 +- app/Traits/DisablesFeatures.php | 3 +- app/Traits/HandlesAccountDeletion.php | 30 ++-- app/UUID/UUID.php | 1 - app/User.php | 45 ++---- app/Vacancy.php | 13 +- app/View/Components/AccountStatus.php | 21 ++- app/View/Components/Alert.php | 20 +-- app/View/Components/Button.php | 28 +++- composer.json | 1 + composer.lock | 68 +++++++- config/adminlte.php | 66 ++++---- config/app.php | 7 +- config/customization.php | 2 +- config/debugbar.php | 60 +++---- config/demo.php | 2 +- config/google2fa.php | 4 +- config/laravellocalization.php | 6 +- config/localizator.php | 12 +- config/markdown.php | 12 +- config/services.php | 8 +- ...04_02_193005_create_translations_table.php | 44 +++--- ..._05_29_234431_create_permission_tables.php | 4 +- .../2021_01_01_201604_oneoff_applicants.php | 6 +- .../2021_07_20_094139_change_bans_table.php | 6 +- ...10_26_000036_add_linked_accounts_table.php | 2 - ...2022_08_20_195538_add_discord_to_users.php | 1 - database/seeders/DatabaseSeeder.php | 1 - database/seeders/DefaultOptionsSeeder.php | 4 - database/seeders/NewPermissions.php | 4 +- database/seeders/PermissionSeeder.php | 17 +- database/seeders/TeamSeeder.php | 58 +++---- database/seeders/UserSeeder.php | 7 +- routes/api.php | 9 +- routes/web.php | 43 +---- 146 files changed, 1013 insertions(+), 1341 deletions(-) diff --git a/app/Absence.php b/app/Absence.php index 2043b52..9e85969 100755 --- a/app/Absence.php +++ b/app/Absence.php @@ -13,14 +13,14 @@ class Absence extends Model use HasFactory; protected $fillable = [ - 'requesterID', - 'start', - 'predicted_end', - 'available_assist', - 'reason', - 'status', - 'reviewer', - 'reviewed_date' + 'requesterID', + 'start', + 'predicted_end', + 'available_assist', + 'reason', + 'status', + 'reviewer', + 'reviewed_date', ]; public function requester(): BelongsTo @@ -28,72 +28,69 @@ class Absence extends Model return $this->belongsTo('App\User', 'requesterID', 'id'); } - /** * Determines whether this model can be setApproved(), setDeclined() or setCancelled() * - * @param bool $toCancel Switch the check to cancellability check + * @param bool $toCancel Switch the check to cancellability check * @return bool */ public function isActionable(bool $toCancel = false): bool { - if ($toCancel) - { + if ($toCancel) { return in_array($this->getRawOriginal('status'), ['PENDING', 'APPROVED']); } return $this->getRawOriginal('status') == 'PENDING'; } - /** * Sets the Absence's status as approved * * @return Absence + * * @throws AbsenceNotActionableException */ public function setApproved(): Absence { - if ($this->isActionable()) - { + if ($this->isActionable()) { return tap($this)->update([ - 'status' => 'APPROVED' + 'status' => 'APPROVED', ]); } throw new AbsenceNotActionableException('This absence is not actionable!'); } - /** * Sets the absence's status as declined * * @return Absence + * * @throws AbsenceNotActionableException */ public function setDeclined(): Absence { if ($this->isActionable()) { return tap($this)->update([ - 'status' => 'DECLINED' + 'status' => 'DECLINED', ]); } throw new AbsenceNotActionableException('This absence is not actionable!'); } - /** * Sets the absence's status as cancelled * * @return Absence + * * @throws AbsenceNotActionableException Thrown when the switch to this status would be invalid */ public function setCancelled(): Absence { if ($this->isActionable(true)) { return tap($this)->update([ - 'status' => 'CANCELLED' + 'status' => 'CANCELLED', ]); } @@ -108,18 +105,16 @@ class Absence extends Model public function setEnded(): Absence { return tap($this)->update([ - 'status' => 'ENDED' + 'status' => 'ENDED', ]); } - // Look out when retrieving this value; //If you need the unaltered version of it, either adapt to its formatting or call getRawOriginal() - protected function status(): Attribute { + protected function status(): Attribute + { return Attribute::make( - get: fn($value) => ucfirst(strtolower($value)) + get: fn ($value) => ucfirst(strtolower($value)) ); } - } - diff --git a/app/Application.php b/app/Application.php index 4b15b06..eae5c83 100755 --- a/app/Application.php +++ b/app/Application.php @@ -64,5 +64,4 @@ class Application extends Model 'applicationStatus' => $status, ]); } - } diff --git a/app/Console/Commands/Install.php b/app/Console/Commands/Install.php index ff71cd9..54d4fc0 100755 --- a/app/Console/Commands/Install.php +++ b/app/Console/Commands/Install.php @@ -39,103 +39,89 @@ class Install extends Command public function handle() { $basePath = base_path(); - if (Storage::disk('local')->missing('INSTALLED')) - { + if (Storage::disk('local')->missing('INSTALLED')) { + $this->info('[!! Welcome to Rasberry Teams !!]'); + $this->info('>> Installing...'); + $this->call('down', [ + '--message' => 'Down for maintenance. We\'ll be right back!', + ]); + copy($basePath.'/.env.example', $basePath.'/.env'); + $this->call('key:generate'); - $this->info('[!! Welcome to Rasberry Teams !!]'); - $this->info('>> Installing...'); - $this->call('down', [ - '--message' => 'Down for maintenance. We\'ll be right back!' - ]); + $this->info('>> Installing and preparing dependencies. This may take a while, depending on your computer.'); - copy($basePath . '/.env.example', $basePath . '/.env'); - $this->call('key:generate'); + $npmOut = 0; + $npmMessages = []; - $this->info('>> Installing and preparing dependencies. This may take a while, depending on your computer.'); + $npmBuildOut = 0; + $npmBuildMessages = []; - $npmOut = 0; - $npmMessages = []; + exec('cd '.$basePath.' && npm install --silent', $npmBuildOut, $npmOut); + exec('cd '.$basePath.'&& npm run dev --silent', $npmBuildMessages, $npmBuildOut); - $npmBuildOut = 0; - $npmBuildMessages = []; + if ($npmOut !== 0 && $npmBuildOut !== 0) { + $this->error('[!] One or more errors have ocurred whilst attempting to install dependencies.'); + $this->error('[!] It is recommended to run this command again, and report a bug if it keeps happening.'); - exec('cd ' . $basePath . ' && npm install --silent', $npmBuildOut, $npmOut); - exec('cd ' . $basePath . '&& npm run dev --silent', $npmBuildMessages, $npmBuildOut); + return false; + } + $settings = []; - if($npmOut !== 0 && $npmBuildOut !== 0) - { - $this->error('[!] One or more errors have ocurred whilst attempting to install dependencies.'); - $this->error('[!] It is recommended to run this command again, and report a bug if it keeps happening.'); + $this->info('>> Configuring application - We\'re going to ask a few questions here!'); + do { + $this->info('== Database Settings (1/6) =='); - return false; - } + $settings['DB_USERNAME'] = $this->ask('Database username'); + $settings['DB_PASSWORD'] = $this->secret('Database password (Input won\'t be seen)'); + $settings['DB_DATABASE'] = $this->ask('Database name'); + $settings['DB_PORT'] = $this->ask('Database port'); + $settings['DB_HOST'] = $this->ask('Database hostname'); + $this->info('== Antispam Settings (2/6) (Recaptcha v2) =='); + $settings['RECAPTCHA_SITE_KEY'] = $this->ask('Site key'); + $settings['RECAPTCHA_PRIVATE_KEY'] = $this->ask('Private site key'); + $this->info('== IP Geolocation Settings (3/6) (refer to README.md) =='); + $settings['IPGEO_API_KEY'] = $this->ask('API Key'); - $settings = []; + $this->info('== Notification Settings (4/6) (Email) =='); + $settings['MAIL_USERNAME'] = $this->ask('SMTP Username'); + $settings['MAIL_PASSWORD'] = $this->secret('SMTP Password (Input won\'t be seen)'); + $settings['MAIL_PORT'] = $this->ask('SMTP Server Port'); + $settings['MAIL_HOST'] = $this->ask('SMTP Server Hostname'); + $settings['MAIL_FROM_ADDRESS'] = $this->ask('E-mail address to send from'); - $this->info('>> Configuring application - We\'re going to ask a few questions here!'); - do - { - $this->info('== Database Settings (1/6) =='); + $this->info('== Notification Settings (5/6) (Slack) =='); + $settings['SLACK_INTEGRATION_WEBHOOK'] = $this->ask('Integration webhook URL'); - $settings['DB_USERNAME'] = $this->ask('Database username'); - $settings['DB_PASSWORD'] = $this->secret('Database password (Input won\'t be seen)'); - $settings['DB_DATABASE'] = $this->ask('Database name'); - $settings['DB_PORT'] = $this->ask('Database port'); - $settings['DB_HOST'] = $this->ask('Database hostname'); + $this->info('== Web Settings (6/6) =='); + $settings['APP_URL'] = $this->ask('Application\'s URL (ex. https://where.you.installed.theapp.com): '); + $settings['APP_LOGO'] = $this->ask('App logo (Link to an image): '); + $settings['APP_SITEHOMEPAGE'] = $this->ask('Site homepage (appears in the main header): '); + } while (! $this->confirm('Are you sure you want to save these settings? You can always go back and try again.')); - $this->info('== Antispam Settings (2/6) (Recaptcha v2) =='); - $settings['RECAPTCHA_SITE_KEY'] = $this->ask('Site key'); - $settings['RECAPTCHA_PRIVATE_KEY'] = $this->ask('Private site key'); + foreach ($settings as $keyname => $value) { + $this->call('environment:modify', [ + 'key' => $keyname, + 'value' => $value, + ]); + } - $this->info('== IP Geolocation Settings (3/6) (refer to README.md) =='); - $settings['IPGEO_API_KEY'] = $this->ask('API Key'); + $this->info('>> Saved configuration settings!'); + $this->info('>> Preparing database...'); - $this->info('== Notification Settings (4/6) (Email) =='); - $settings['MAIL_USERNAME'] = $this->ask('SMTP Username'); - $settings['MAIL_PASSWORD'] = $this->secret('SMTP Password (Input won\'t be seen)'); - $settings['MAIL_PORT'] = $this->ask('SMTP Server Port'); - $settings['MAIL_HOST'] = $this->ask('SMTP Server Hostname'); - $settings['MAIL_FROM_ADDRESS'] = $this->ask('E-mail address to send from'); + $this->callSilent('config:cache'); + $this->call('migrate'); + $this->call('db:seed'); - $this->info('== Notification Settings (5/6) (Slack) =='); - $settings['SLACK_INTEGRATION_WEBHOOK'] = $this->ask('Integration webhook URL'); + touch($basePath.'/INSTALLED'); - $this->info('== Web Settings (6/6) =='); - $settings['APP_URL'] = $this->ask('Application\'s URL (ex. https://where.you.installed.theapp.com): '); - $settings['APP_LOGO'] = $this->ask('App logo (Link to an image): '); - $settings['APP_SITEHOMEPAGE'] = $this->ask('Site homepage (appears in the main header): '); - - - } while(!$this->confirm('Are you sure you want to save these settings? You can always go back and try again.')); - - foreach($settings as $keyname => $value) - { - $this->call('environment:modify', [ - 'key' => $keyname, - 'value' => $value - ]); - } - - $this->info('>> Saved configuration settings!'); - $this->info('>> Preparing database...'); - - $this->callSilent('config:cache'); - $this->call('migrate'); - $this->call('db:seed'); - - touch($basePath . '/INSTALLED'); - - $this->call('up'); - $this->info('>> All done! Visit ' . $basePath . ' to start using your brand new installation of Raspberry Teams!'); - - } - else - { - $this->error('[!] The application is already installed!'); + $this->call('up'); + $this->info('>> All done! Visit '.$basePath.' to start using your brand new installation of Raspberry Teams!'); + } else { + $this->error('[!] The application is already installed!'); } } } diff --git a/app/Console/Commands/SetEnv.php b/app/Console/Commands/SetEnv.php index 3c49403..ae935eb 100755 --- a/app/Console/Commands/SetEnv.php +++ b/app/Console/Commands/SetEnv.php @@ -52,6 +52,7 @@ class SetEnv extends Command /** * Execute the console command. + * * @return mixed */ public function handle() diff --git a/app/CustomFacades/IP.php b/app/CustomFacades/IP.php index 8474b80..cd99f22 100755 --- a/app/CustomFacades/IP.php +++ b/app/CustomFacades/IP.php @@ -23,7 +23,6 @@ namespace App\CustomFacades; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Log; class IP { @@ -31,14 +30,14 @@ class IP // For views, this is in a service provider, and is shared with all of them /** * Determines whether you should collect/display IP addresses in the app. + * * @return bool Whether you should collect/display IPs, in the context in which this is called */ public function shouldCollect(): bool { // should collect or display IPs? - if (config('demo.is_enabled') || config('app.hide_ips')) - { + if (config('demo.is_enabled') || config('app.hide_ips')) { return false; // do not collect! } @@ -47,7 +46,8 @@ class IP /** * Looks up information on a specified IP address. Caches results automatically. - * @param string $IP IP address to lookup + * + * @param string $IP IP address to lookup * @return object */ public function lookup(string $IP): object @@ -58,19 +58,17 @@ class IP ]; if ($this->shouldCollect()) { - - return json_decode(Cache::remember($IP, 3600, function () use ($IP) { return Http::get(config('general.urls.ipapi.ipcheck'), [ 'apiKey' => config('general.keys.ipapi.apikey'), 'ip' => $IP, ])->body(); })); - } - return new class { - public $message = "This feature is disabled."; + return new class + { + public $message = 'This feature is disabled.'; }; } } diff --git a/app/Events/ApplicationApprovedEvent.php b/app/Events/ApplicationApprovedEvent.php index 066d83c..c72d2db 100755 --- a/app/Events/ApplicationApprovedEvent.php +++ b/app/Events/ApplicationApprovedEvent.php @@ -35,7 +35,7 @@ class ApplicationApprovedEvent /** * Create a new event instance. * - * @param Application $application + * @param Application $application */ public function __construct(Application $application) { diff --git a/app/Exceptions/ApplicationNotFoundException.php b/app/Exceptions/ApplicationNotFoundException.php index 1fc29a9..5fdcc72 100755 --- a/app/Exceptions/ApplicationNotFoundException.php +++ b/app/Exceptions/ApplicationNotFoundException.php @@ -2,7 +2,6 @@ namespace App\Exceptions; -use Exception; use Illuminate\Database\Eloquent\ModelNotFoundException; class ApplicationNotFoundException extends ModelNotFoundException diff --git a/app/Exceptions/VacancyNotFoundException.php b/app/Exceptions/VacancyNotFoundException.php index 581c503..07a2c9f 100755 --- a/app/Exceptions/VacancyNotFoundException.php +++ b/app/Exceptions/VacancyNotFoundException.php @@ -2,7 +2,6 @@ namespace App\Exceptions; -use Exception; use Illuminate\Database\Eloquent\ModelNotFoundException; class VacancyNotFoundException extends ModelNotFoundException diff --git a/app/Facades/DigitalStorageHelper.php b/app/Facades/DigitalStorageHelper.php index 0ebdee0..eb80c50 100755 --- a/app/Facades/DigitalStorageHelper.php +++ b/app/Facades/DigitalStorageHelper.php @@ -1,17 +1,13 @@ value = $value; + return $this; } - /** * Converts the digital storage value to kilobytes. * @@ -45,7 +44,6 @@ class DigitalStorageHelper return $this->value / 1000; } - /** * Converts the digital storage value to megabytes. * @@ -56,7 +54,6 @@ class DigitalStorageHelper return $this->value / (1 * pow(10, 6)); // 1 times 10 to the power of 6 } - /** * Convert the digital storage value to gigabytes. Might be an approximation * @@ -67,7 +64,6 @@ class DigitalStorageHelper return $this->value / (1 * pow(10, 9)); } - /** * Convert the digital storage value to terabytes. * @@ -78,22 +74,23 @@ class DigitalStorageHelper return $this->value / (1 * pow(10, 12)); } - /** * Format the digital storage value to one of the units: b, kb, mb, gb and tb. * The method has been adapted to use both MiB and MB values. * - * @param int $precision The rounding precision - * @param bool $si Use international system units. Defaults to false + * @param int $precision The rounding precision + * @param bool $si Use international system units. Defaults to false * @return string The human readable digital storage value, in either, for instance, MB or MiB + * * @see https://stackoverflow.com/a/2510459/11540218 StackOverflow question regarding unit conversion * @since 7.3.23 */ public function formatBytes($precision = 2, $si = false): string { $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; - if ($si) + if ($si) { $units = ['B', 'KB', 'MB', 'GB', 'TB']; + } $bytes = max($this->value, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(($si) ? 1000 : 1024)); @@ -101,7 +98,6 @@ class DigitalStorageHelper $bytes /= pow(($si) ? 1000 : 1024, $pow); - return round($bytes, $precision) . ' ' . $units[$pow]; + return round($bytes, $precision).' '.$units[$pow]; } - } diff --git a/app/Helpers/Discord.php b/app/Helpers/Discord.php index e4b0a1f..7c10a78 100755 --- a/app/Helpers/Discord.php +++ b/app/Helpers/Discord.php @@ -19,30 +19,25 @@ * along with Raspberry Staff Manager. If not, see . */ - namespace App\Helpers; use App\Exceptions\AccountNotLinkedException; use App\User; use Carbon\Carbon; use Illuminate\Http\Client\RequestException; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Http; // Small wrapper for the necessary sections of the Discord API; A library is overkill here class Discord { - /** * The current working guild. Default is Home guild from app config + * * @var string */ protected string $workingGuild; - /** * Current user. * @@ -50,42 +45,43 @@ class Discord */ protected User $user; - - - public function __construct() { + public function __construct() + { if (isset($this->workingGuild)) { $this->setWorkingGuild(config('services.discord.home_guild')); } } - /** * Sets the working guild * - * @param string $workingGuild + * @param string $workingGuild * @return Discord */ public function setWorkingGuild(string $workingGuild): Discord { $this->workingGuild = $workingGuild; + return $this; } /** * Sets the current user, upon validation * - * @param User $user + * @param User $user * @return Discord + * * @throws AccountNotLinkedException */ public function setUser(User $user): Discord { - if ($user->hasDiscordConnection()) { - $this->user = $user; - return $this; - } + if ($user->hasDiscordConnection()) { + $this->user = $user; - throw new AccountNotLinkedException('Specified website user has not linked their Discord account yet.'); + return $this; + } + + throw new AccountNotLinkedException('Specified website user has not linked their Discord account yet.'); } /** @@ -93,16 +89,16 @@ class Discord * preventing unnecessary API requests. * * @return object Current user's authentication info (has no sensitive fields) + * * @throws RequestException */ - public function getAuthorizationInfo(): object { - + public function getAuthorizationInfo(): object + { if (Cache::has($this->user->discord_user_id)) { return unserialize(Cache::get($this->user->discord_user_id)); - } - else { + } else { $authInfo = (object) Http::withToken($this->user->discord_token) - ->get(config('services.discord.base_url') . '/oauth2/@me') + ->get(config('services.discord.base_url').'/oauth2/@me') ->throw() ->json(); @@ -112,43 +108,42 @@ class Discord } } - /** * Checks if the user's token is close to expiring. * Tokens should be refreshed the day before they expire. * * @return bool Whether the user's token needs to be refreshed + * * @throws RequestException */ - public function needsRefresh(): bool { + public function needsRefresh(): bool + { return Carbon::parse($this->getAuthorizationInfo()->expires)->diffInDays() == 1; } - - - public function exchangeRefreshToken() { - + public function exchangeRefreshToken() + { } - - /** * Adds current working user to current working guild. Bot must be member of target guild, and account must be linked * * @return object|bool A GuildMember object; false if member is already in guild + * * @throws RequestException Any client and server errors + * * @see https://discord.com/developers/docs/resources/guild#guild-member-object */ public function addGuildMember(): object|bool { $params = [ - 'access_token' => $this->user->discord_token + 'access_token' => $this->user->discord_token, ]; $member = Http::withBody(json_encode($params), 'application/json') ->withHeaders([ - 'Authorization' => 'Bot ' . config('services.discord.token') - ])->put(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/members/{$this->user->discord_user_id}") + 'Authorization' => 'Bot '.config('services.discord.token'), + ])->put(config('services.discord.base_url')."/guilds/{$this->workingGuild}/members/{$this->user->discord_user_id}") ->throw(); if ($member->successful() && $member->status() == 204) { @@ -158,42 +153,45 @@ class Discord } } - /** * Bans a specified user from the guild. * May be called from the suspension service optionally by the banning user * - * @param string $reason The reason to supply Discord with + * @param string $reason The reason to supply Discord with * @return void Nothing on success + * * @throws RequestException * @throws AccountNotLinkedException */ - public function addGuildBan(string $reason): void { + public function addGuildBan(string $reason): void + { Http::withHeaders([ - 'Authorization' => 'Bot ' . config('services.discord.token'), - 'X-Audit-Log-Reason' => $reason - ])->put(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}") + 'Authorization' => 'Bot '.config('services.discord.token'), + 'X-Audit-Log-Reason' => $reason, + ])->put(config('services.discord.base_url')."/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}") ->throw(); throw new AccountNotLinkedException('Specified website user has not linked their Discord account yet.'); } /** - * @param string $reason The removal reason to provide Discord with (e.g. ban expired) + * @param string $reason The removal reason to provide Discord with (e.g. ban expired) * @return null|bool Null on unnan, false if user is not banned + * * @throws RequestException */ - public function removeGuildBan(string $reason): null|bool { - + public function removeGuildBan(string $reason): null|bool + { if ($this->getGuildBan($this->user)) { Http::withHeaders([ - 'Authorization' => 'Bot ' . config('services.discord.token'), - 'X-Audit-Log-Reason' => $reason - ])->delete(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}") + 'Authorization' => 'Bot '.config('services.discord.token'), + 'X-Audit-Log-Reason' => $reason, + ])->delete(config('services.discord.base_url')."/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}") ->throw(); return null; } + return false; } @@ -201,14 +199,16 @@ class Discord * Gets (possible) ban for current user. * * @return object|bool Ban object if user is banned. Null + * * @throws RequestException + * * @see https://discord.com/developers/docs/resources/guild#ban-object */ public function getGuildBan(): object|bool { $ban = Http::withHeaders([ - 'Authorization' => 'Bot ' . config('services.discord.token') - ])->get(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}"); + 'Authorization' => 'Bot '.config('services.discord.token'), + ])->get(config('services.discord.base_url')."/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}"); if ($ban->status() == 404) { return false; @@ -217,20 +217,21 @@ class Discord return ($ban->successful()) ? (object) $ban->json() : $ban->throwIf($ban->status() !== 404); } - /** * Retrieves list of Role objects + * * @see https://discord.com/developers/docs/topics/permissions#role-object + * * @return array List of role objects * * @throws RequestException */ - public function getGuildRoles(): array { + public function getGuildRoles(): array + { return Http::withHeaders([ - 'Authorization' => 'Bot ' . config('services.discord.token') - ])->get(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/roles") + 'Authorization' => 'Bot '.config('services.discord.token'), + ])->get(config('services.discord.base_url')."/guilds/{$this->workingGuild}/roles") ->throw() ->json(); } - } diff --git a/app/Helpers/JSON.php b/app/Helpers/JSON.php index 334fb34..e864d95 100755 --- a/app/Helpers/JSON.php +++ b/app/Helpers/JSON.php @@ -1,32 +1,41 @@ type = $type; + return $this; } /** - * @param mixed $additional + * @param mixed $additional */ public function setAdditional($additional) { $this->additional = $additional; + return $this; } @@ -55,12 +64,13 @@ class JSON } /** - * @param mixed $status + * @param mixed $status * @return JSON */ public function setStatus($status) { $this->status = $status; + return $this; } @@ -73,12 +83,13 @@ class JSON } /** - * @param mixed $message + * @param mixed $message * @return JSON */ public function setMessage($message) { $this->message = $message; + return $this; } @@ -91,12 +102,13 @@ class JSON } /** - * @param mixed $code + * @param mixed $code * @return JSON */ public function setCode($code) { $this->code = $code; + return $this; } @@ -109,12 +121,13 @@ class JSON } /** - * @param mixed $data + * @param mixed $data * @return JSON */ public function setData($data) { $this->data = $data; + return $this; } @@ -126,17 +139,15 @@ class JSON 'meta' => [ 'status' => $this->getStatus(), 'message' => $this->getMessage(), - ] + ], ]; - if (!empty($this->additional)) - { - foreach($this->additional as $additionalKeyName => $key) - { + if (! empty($this->additional)) { + foreach ($this->additional as $additionalKeyName => $key) { $response[$additionalKeyName] = $key; } } + return response($response, $this->getCode(), $headers); } - } diff --git a/app/Helpers/Options.php b/app/Helpers/Options.php index 1297a23..ade3134 100755 --- a/app/Helpers/Options.php +++ b/app/Helpers/Options.php @@ -33,30 +33,28 @@ use Illuminate\Support\Facades\Log; */ class Options { - /** * Returns an assortment of settings found in the mentioned category * - * @param string $category The category + * @param string $category The category * @return Collection The settings in this category + * * @throws EmptyOptionsException */ public function getCategory(string $category): Collection { $options = Option::where('option_category', $category)->get(); - if ($options->isEmpty()) - { - throw new EmptyOptionsException('There are no options in category ' . $category); + if ($options->isEmpty()) { + throw new EmptyOptionsException('There are no options in category '.$category); } + return $options; } - public function getOption(string $option): string { $value = Cache::get($option); - if (is_null($value)) { Log::debug('Option '.$option.'not found in cache, refreshing from database'); $value = Option::where('option_name', $option)->first(); @@ -79,7 +77,7 @@ class Options 'option_name' => $option, 'option_value' => $value, 'friendly_name' => $description, - 'option_category' => $category + 'option_category' => $category, ]); Cache::put($option, $value, now()->addDay()); @@ -115,9 +113,9 @@ class Options $dbOptionInstance->save(); Log::debug('New db configuration option saved', - [ - 'option' => $dbOptionInstance->option_value, - ]); + [ + 'option' => $dbOptionInstance->option_value, + ]); Cache::put('option_name', $newValue, now()->addDay()); } else { diff --git a/app/Http/Controllers/AbsenceController.php b/app/Http/Controllers/AbsenceController.php index 1062867..1e4ee0f 100755 --- a/app/Http/Controllers/AbsenceController.php +++ b/app/Http/Controllers/AbsenceController.php @@ -5,24 +5,20 @@ namespace App\Http\Controllers; use App\Absence; use App\Exceptions\AbsenceNotActionableException; use App\Http\Requests\StoreAbsenceRequest; -use App\Http\Requests\UpdateAbsenceRequest; use App\Services\AbsenceService; use App\User; use Illuminate\Auth\Access\AuthorizationException; -use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Auth; class AbsenceController extends Controller { - private AbsenceService $absenceService; - public function __construct (AbsenceService $absenceService) { - + public function __construct(AbsenceService $absenceService) + { $this->absenceService = $absenceService; - } /** @@ -38,11 +34,11 @@ class AbsenceController extends Controller ->with('absences', Absence::paginate(6)); } - /** * Display a listing of absences belonging to the current user. * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View + * * @throws AuthorizationException */ public function showUserAbsences() @@ -54,11 +50,8 @@ class AbsenceController extends Controller return view('dashboard.absences.own') ->with('absences', $absences); - } - - /** * Show the form for creating a new absence request. * @@ -98,7 +91,8 @@ class AbsenceController extends Controller /** * Display the specified absence request. * - * @param \App\Absence $absence + * @param \App\Absence $absence + * * @throws AuthorizationException */ public function show(Absence $absence) @@ -107,28 +101,26 @@ class AbsenceController extends Controller return view('dashboard.absences.view') ->with([ - 'absence' => $absence, - 'totalDays' => Carbon::parse($absence->start)->diffInDays($absence->predicted_end) + 'absence' => $absence, + 'totalDays' => Carbon::parse($absence->start)->diffInDays($absence->predicted_end), ]); } /** * Approve the specified absence. * - * @param Absence $absence + * @param Absence $absence * @return RedirectResponse + * * @throws AuthorizationException */ public function approveAbsence(Absence $absence): RedirectResponse { $this->authorize('approve', $absence); - try - { + try { $this->absenceService->approveAbsence($absence); - } - catch (AbsenceNotActionableException $notActionableException) - { + } catch (AbsenceNotActionableException $notActionableException) { return redirect() ->back() ->with('error', $notActionableException->getMessage()); @@ -139,23 +131,21 @@ class AbsenceController extends Controller ->with('success', __('Absence request successfully approved. It will automatically transition to "Ended" on its predicted end date.')); } - /** * Decline the specified absence. * - * @param Absence $absence + * @param Absence $absence * @return RedirectResponse + * * @throws AuthorizationException */ public function declineAbsence(Absence $absence): RedirectResponse { $this->authorize('decline', $absence); - try - { + try { $this->absenceService->declineAbsence($absence); - } catch (AbsenceNotActionableException $notActionableException) - { + } catch (AbsenceNotActionableException $notActionableException) { return redirect() ->back() ->with('error', $notActionableException->getMessage()); @@ -166,24 +156,21 @@ class AbsenceController extends Controller ->with('success', __('Absence request successfully declined.')); } - /** * Cancel the specified absence. * - * @param Absence $absence + * @param Absence $absence * @return \Illuminate\Http\RedirectResponse + * * @throws AuthorizationException */ - public function cancelAbsence(Absence $absence): \Illuminate\Http\RedirectResponse + public function cancelAbsence(Absence $absence): RedirectResponse { $this->authorize('cancel', $absence); - try - { + try { $this->absenceService->cancelAbsence($absence); - } - catch (AbsenceNotActionableException $notActionableException) - { + } catch (AbsenceNotActionableException $notActionableException) { return redirect() ->back() ->with('error', $notActionableException->getMessage()); diff --git a/app/Http/Controllers/ApplicationController.php b/app/Http/Controllers/ApplicationController.php index a9b13a3..fb7f606 100755 --- a/app/Http/Controllers/ApplicationController.php +++ b/app/Http/Controllers/ApplicationController.php @@ -29,23 +29,19 @@ use App\Exceptions\IncompleteApplicationException; use App\Exceptions\InvalidAgeException; use App\Exceptions\UnavailableApplicationException; use App\Exceptions\VacancyNotFoundException; -use App\Facades\IP; use App\Services\ApplicationService; -use App\Vacancy; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class ApplicationController extends Controller { - private $applicationService; - public function __construct(ApplicationService $applicationService) { - + public function __construct(ApplicationService $applicationService) + { $this->applicationService = $applicationService; } - public function showUserApps() { return view('dashboard.user.applications') @@ -67,7 +63,6 @@ class ApplicationController extends Controller 'canVote' => $this->applicationService->canVote($application->votes), ] ); - } public function showAllApps(Request $request) @@ -76,42 +71,36 @@ class ApplicationController extends Controller return view('dashboard.appmanagement.all') ->with('applications', Application::orderBy('applicationStatus', 'ASC')->paginate(6)); - } - - public function discordApply(Request $request, $vacancySlug) { - + public function discordApply(Request $request, $vacancySlug) + { $request->session()->put('discordApplicationRedirectedSlug', $vacancySlug); - return redirect(route('discordRedirect')); + return redirect(route('discordRedirect')); } public function renderApplicationForm($vacancySlug) { try { return $this->applicationService->renderForm($vacancySlug); - } - catch (ApplicationNotFoundException $ex) { + } catch (ApplicationNotFoundException $ex) { return redirect() ->back() ->with('error', $ex->getMessage()); - } catch (DiscordAccountRequiredException $e) { - \Log::info('Redirecting user: ' . $e->getMessage(), [ - 'user' => Auth::user()->email + \Log::info('Redirecting user: '.$e->getMessage(), [ + 'user' => Auth::user()->email, ]); request()->session()->put('discordApplicationRedirectedSlug', $vacancySlug); + return redirect(route('discordRedirect')); } catch (IncompatibleAgeException $e) { - return redirect() ->to(route('dashboard')) ->with('error', $e->getMessage()); - } catch (InvalidAgeException $e) { - return view('dashboard.application-rendering.add-age'); } } @@ -121,9 +110,7 @@ class ApplicationController extends Controller if (Auth::user()->isEligible()) { try { $this->applicationService->fillForm(Auth::user(), $request->all(), $vacancySlug); - - } catch (VacancyNotFoundException | IncompleteApplicationException | UnavailableApplicationException $e) { - + } catch (VacancyNotFoundException|IncompleteApplicationException|UnavailableApplicationException $e) { return redirect() ->back() ->with('error', $e->getMessage()); @@ -146,8 +133,7 @@ class ApplicationController extends Controller try { $status = $this->applicationService->updateStatus($application, $newStatus); - } catch (\LogicException $ex) - { + } catch (\LogicException $ex) { return redirect() ->back() ->with('error', $ex->getMessage()); @@ -170,6 +156,5 @@ class ApplicationController extends Controller return redirect() ->back() ->with('success', __('Application deleted. Comments, appointments and responses have also been deleted.')); - } } diff --git a/app/Http/Controllers/AppointmentController.php b/app/Http/Controllers/AppointmentController.php index 0b94824..55e5ebf 100755 --- a/app/Http/Controllers/AppointmentController.php +++ b/app/Http/Controllers/AppointmentController.php @@ -36,13 +36,12 @@ use Illuminate\Http\Request; class AppointmentController extends Controller { - private $appointmentService; + private $meetingNoteService; - - public function __construct(AppointmentService $appointmentService, MeetingNoteService $meetingNoteService) { - + public function __construct(AppointmentService $appointmentService, MeetingNoteService $meetingNoteService) + { $this->appointmentService = $appointmentService; $this->meetingNoteService = $meetingNoteService; } @@ -56,7 +55,7 @@ class AppointmentController extends Controller return redirect() ->back() - ->with('success',__('Appointment successfully scheduled @ :appointmentTime', ['appointmentTime', $appointmentDate->toDateTimeString()])); + ->with('success', __('Appointment successfully scheduled @ :appointmentTime', ['appointmentTime', $appointmentDate->toDateTimeString()])); } /** @@ -71,10 +70,8 @@ class AppointmentController extends Controller return redirect() ->back() - ->with('success', __("Interview finished! Staff members can now vote on it.")); - - } - catch (InvalidAppointmentStatusException $ex) { + ->with('success', __('Interview finished! Staff members can now vote on it.')); + } catch (InvalidAppointmentStatusException $ex) { return redirect() ->back() ->with('error', $ex->getMessage()); @@ -86,35 +83,26 @@ class AppointmentController extends Controller $this->authorize('update', $application->appointment); try { - $this->appointmentService->deleteAppointment($application, $request->reason); return redirect() ->back() ->with('success', __('Appointment cancelled.')); - - } - catch (\Exception $ex) { + } catch (\Exception $ex) { return redirect() ->back() ->with('error', $ex->getMessage()); } - - } - - public function saveNotes(SaveNotesRequest $request, Application $application) { try { - $this->meetingNoteService->addToApplication($application, $request->noteText); return redirect() ->back() ->with('success', __('Saved notes.')); - } catch (InvalidAppointmentException $ex) { return redirect() ->back() diff --git a/app/Http/Controllers/Auth/DiscordController.php b/app/Http/Controllers/Auth/DiscordController.php index ddaf82c..067b0cb 100755 --- a/app/Http/Controllers/Auth/DiscordController.php +++ b/app/Http/Controllers/Auth/DiscordController.php @@ -21,46 +21,39 @@ namespace App\Http\Controllers\Auth; -use App\Facades\Discord; -use App\Facades\Options; use App\Http\Controllers\Controller; use App\User; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Log; -use Illuminate\Support\Str; use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Two\InvalidStateException; class DiscordController extends Controller { - - - public function discordRedirect() { + public function discordRedirect() + { return Socialite::driver('discord') ->scopes(['email', 'guilds.join', 'guilds.members.read', 'guilds']) ->redirect(); } - public function discordCallback() { - + public function discordCallback() + { try { - $discordUser = Socialite::driver('discord')->user(); - } catch (InvalidStateException $stateException) { Log::warning('Invalid state for social authentication: ', [ 'message' => $stateException->getMessage(), 'ua' => request()->userAgent(), - 'ip' => request()->ip() + 'ip' => request()->ip(), ]); + return redirect(route('discordRedirect')); } $appUser = User::where('email', $discordUser->getEmail())->first(); if ($appUser) { - $appUser->discord_token = $discordUser->token; $appUser->discord_refresh_token = $discordUser->refreshToken; $appUser->discord_user_id = $discordUser->getId(); @@ -68,9 +61,7 @@ class DiscordController extends Controller $appUser->save(); Auth::login($appUser, true); - } else { - $oAuthUser = User::create([ 'uuid' => null, 'name' => $discordUser->getName(), @@ -82,7 +73,7 @@ class DiscordController extends Controller 'discord_user_id' => $discordUser->getId(), 'discord_pfp' => $discordUser->getAvatar(), 'discord_token' => $discordUser->token, - 'discord_refresh_token' => $discordUser->refreshToken + 'discord_refresh_token' => $discordUser->refreshToken, ]); $oAuthUser->assignRole('user'); @@ -97,5 +88,4 @@ class DiscordController extends Controller return redirect() ->route('dashboard'); } - } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index b5fd5d6..fbb9007 100755 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -21,17 +21,13 @@ namespace App\Http\Controllers\Auth; +use App\Facades\IP; use App\Http\Controllers\Controller; use App\Services\AccountSuspensionService; use App\User; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Log; -use App\Facades\IP; -use Illuminate\Support\Str; -use Laravel\Socialite\Facades\Socialite; class LoginController extends Controller { @@ -79,12 +75,11 @@ class LoginController extends Controller $isLocked = $service->isLocked($user); if ($isBanned || $isLocked) { - Log::alert('Restricted user attempting to login.', [ 'ip' => $request->ip(), 'email' => $user->email, 'isBanned' => $isBanned, - 'isLocked' => $isLocked + 'isLocked' => $isLocked, ]); return false; @@ -99,17 +94,14 @@ class LoginController extends Controller public function authenticated(Request $request, User $user) { if (IP::shouldCollect()) { - if ($user->originalIP !== $request->ip()) - { + if ($user->originalIP !== $request->ip()) { Log::alert('User IP address changed from last login. Updating.', [ 'prev' => $user->originalIP, - 'new' => $request->ip() + 'new' => $request->ip(), ]); $user->currentIp = $request->ip(); $user->save(); } } } - - } diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index 00d0a62..a9dff70 100755 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -21,15 +21,12 @@ namespace App\Http\Controllers\Auth; -use App\Http\Controllers\Controller; -use App\Profile; -use App\Services\AccountSuspensionService; -use App\User; -use App\Facades\Options; use App\Facades\IP; +use App\Facades\Options; +use App\Http\Controllers\Controller; +use App\User; use Illuminate\Foundation\Auth\RegistersUsers; use Illuminate\Support\Facades\Hash; -use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Validator; class RegisterController extends Controller @@ -74,8 +71,7 @@ class RegisterController extends Controller { $password = ['required', 'string', 'confirmed']; - switch (Options::getOption('pw_security_policy')) - { // this could be better structured, switch doesn't feel right + switch (Options::getOption('pw_security_policy')) { // this could be better structured, switch doesn't feel right case 'off': $password = ['required', 'string', 'confirmed']; break; @@ -102,7 +98,7 @@ class RegisterController extends Controller 'dob.before' => __('You must be 13 years of age or older in order to sign up for an account.'), 'dob.required' => __('Please enter your date of birth.'), 'uuid.required' => __('Please enter a valid (and Premium) Minecraft username! We do not support cracked users.'), - 'acceptTerms.required' => __('Please accept the Community Guidelines, Terms of Service and Privacy Policy to continue.') + 'acceptTerms.required' => __('Please accept the Community Guidelines, Terms of Service and Privacy Policy to continue.'), ]); } @@ -117,13 +113,13 @@ class RegisterController extends Controller $ip = IP::shouldCollect() ? request()->ip() : '0.0.0.0'; $user = User::create([ - 'uuid' => $data['uuid'] ?? "disabled", + 'uuid' => $data['uuid'] ?? 'disabled', 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), 'registrationIp' => $ip, 'currentIp' => $ip, - 'dob' => $data['dob'] + 'dob' => $data['dob'], ]); $user->assignRole('user'); diff --git a/app/Http/Controllers/CommentController.php b/app/Http/Controllers/CommentController.php index 609c0e3..f4c7e98 100755 --- a/app/Http/Controllers/CommentController.php +++ b/app/Http/Controllers/CommentController.php @@ -26,13 +26,13 @@ use App\Comment; use App\Http\Requests\NewCommentRequest; use App\Services\CommentService; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Auth; class CommentController extends Controller { private $commentService; - public function __construct(CommentService $commentService) { + public function __construct(CommentService $commentService) + { $this->commentService = $commentService; } diff --git a/app/Http/Controllers/DashboardController.php b/app/Http/Controllers/DashboardController.php index 63e634d..5b41b37 100755 --- a/app/Http/Controllers/DashboardController.php +++ b/app/Http/Controllers/DashboardController.php @@ -39,12 +39,12 @@ class DashboardController extends Controller $totalDeniedSingle = Application::where([ ['applicationStatus', '=', 'DENIED'], - ['applicantUserID', '=', Auth::user()->id] + ['applicantUserID', '=', Auth::user()->id], ])->get(); $totalNewSingle = Application::where([ ['applicationStatus', '=', 'STAGE_SUBMITTED'], - ['applicantUserID', '=', Auth::user()->id] + ['applicantUserID', '=', Auth::user()->id], ])->get(); return view('dashboard.dashboard') @@ -55,7 +55,7 @@ class DashboardController extends Controller 'totalPeerReview' => $totalPeerReview, 'totalNewApplications' => $totalNewApplications, 'totalNewSingle' => $totalNewSingle->count(), - 'totalDeniedSingle' => $totalDeniedSingle->count() + 'totalDeniedSingle' => $totalDeniedSingle->count(), ]); } } diff --git a/app/Http/Controllers/DevToolsController.php b/app/Http/Controllers/DevToolsController.php index 582a09a..42dcd0d 100755 --- a/app/Http/Controllers/DevToolsController.php +++ b/app/Http/Controllers/DevToolsController.php @@ -33,17 +33,20 @@ use Illuminate\Support\Facades\Log; class DevToolsController extends Controller { - public function __construct() { + public function __construct() + { // } - private function singleAuthorise() { + private function singleAuthorise() + { if (! Auth::user()->can('admin.developertools.use')) { abort(403, __('You\'re not authorized to access this page.')); } } - public function index() { + public function index() + { $this->singleAuthorise(); return view('dashboard.administration.devtools') @@ -54,7 +57,8 @@ class DevToolsController extends Controller /** * Force an application to be approved. */ - public function forceApprovalEvent(Request $request) { + public function forceApprovalEvent(Request $request) + { $this->singleAuthorise(); $application = Application::find($request->application); @@ -80,20 +84,19 @@ class DevToolsController extends Controller ->with('success', __('Event dispatched; Candidate rejection sequence initiated.')); } - public function evaluateVotes() { - + public function evaluateVotes() + { $this->singleAuthorise(); - $code = Artisan::call("votes:evaluate"); + $code = Artisan::call('votes:evaluate'); return redirect() ->back() ->with('success', __('Ran vote evaluation logic, with exit code :exitCode ', ['exitCode' => $code])); - } - public function purgeSuspensions(AccountSuspensionService $service) { - + public function purgeSuspensions(AccountSuspensionService $service) + { $this->singleAuthorise(); if ($service->purgeExpired()) { @@ -105,7 +108,6 @@ class DevToolsController extends Controller return redirect() ->back() ->with('error', __('There were no expired suspensions (or no suspensions at all) to purge.')); - } public function endAbsencesNow(AbsenceService $service) diff --git a/app/Http/Controllers/FormController.php b/app/Http/Controllers/FormController.php index 366475f..d97938c 100755 --- a/app/Http/Controllers/FormController.php +++ b/app/Http/Controllers/FormController.php @@ -25,14 +25,14 @@ use App\Exceptions\EmptyFormException; use App\Exceptions\FormHasConstraintsException; use App\Form; use App\Services\FormManagementService; -use ContextAwareValidator; use Illuminate\Http\Request; class FormController extends Controller { private $formService; - public function __construct(FormManagementService $formService) { + public function __construct(FormManagementService $formService) + { $this->formService = $formService; } @@ -56,17 +56,14 @@ class FormController extends Controller { try { $form = $this->formService->addForm($request->all()); - } - catch (EmptyFormException $ex) - { + } catch (EmptyFormException $ex) { return redirect() ->back() ->with('exception', $ex->getMessage()); } // Form is boolean or array - if ($form) - { + if ($form) { return redirect() ->back() ->with('success', __('Form created!')); @@ -81,18 +78,15 @@ class FormController extends Controller { $this->authorize('delete', $form); try { - $this->formService->deleteForm($form); + return redirect() ->back() ->with('success', __('Form deleted successfuly')); - } catch (FormHasConstraintsException $ex) { - return redirect() ->back() ->with('error', $ex->getMessage()); - } } diff --git a/app/Http/Controllers/OptionsController.php b/app/Http/Controllers/OptionsController.php index 10b03e7..7fbbcc3 100755 --- a/app/Http/Controllers/OptionsController.php +++ b/app/Http/Controllers/OptionsController.php @@ -24,20 +24,17 @@ namespace App\Http\Controllers; use App\Exceptions\InvalidGamePreferenceException; use App\Exceptions\OptionNotFoundException; use App\Facades\Options; -use App\Options as Option; use App\Services\ConfigurationService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Log; class OptionsController extends Controller { private $configurationService; - public function __construct(ConfigurationService $configurationService) { - + public function __construct(ConfigurationService $configurationService) + { $this->configurationService = $configurationService; - } /** @@ -56,16 +53,15 @@ class OptionsController extends Controller 'graceperiod' => Options::getOption('graceperiod'), 'pwExpiry' => Options::getOption('password_expiry'), 'requiresPMC' => Options::getOption('requireGameLicense'), - 'enforce2fa' => Options::getOption('force2fa') + 'enforce2fa' => Options::getOption('force2fa'), ], - 'currentGame' => Options::getOption('currentGame') + 'currentGame' => Options::getOption('currentGame'), ]); } public function saveSettings(Request $request): \Illuminate\Http\RedirectResponse { try { - if (Auth::user()->can('admin.settings.edit')) { $this->configurationService->saveConfiguration($request->all()); @@ -73,13 +69,10 @@ class OptionsController extends Controller ->back() ->with('success', __('Options updated successfully!')); } - - } catch (OptionNotFoundException | \Exception $ex) { - + } catch (OptionNotFoundException|\Exception $ex) { return redirect() ->back() ->with('error', $ex->getMessage()); - } return redirect() @@ -90,12 +83,11 @@ class OptionsController extends Controller public function saveGameIntegration(Request $request) { try { - $this->configurationService->saveGameIntegration($request->gamePref); + return redirect() ->back() ->with('success', __('Game preference updated.')); - } catch (InvalidGamePreferenceException $ex) { return redirect() ->back() diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index 767b7f3..11742e2 100755 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -21,8 +21,6 @@ namespace App\Http\Controllers; -use App\Exceptions\ProfileAlreadyExistsException; -use App\Exceptions\ProfileCreationFailedException; use App\Exceptions\ProfileNotFoundException; use App\Facades\IP; use App\Http\Requests\ProfileSave; @@ -32,13 +30,13 @@ use App\User; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; -use Spatie\Permission\Models\Role; class ProfileController extends Controller { private ProfileService $profileService; - public function __construct(ProfileService $profileService) { + public function __construct(ProfileService $profileService) + { $this->profileService = $profileService; } @@ -60,27 +58,22 @@ class ProfileController extends Controller public function showSingleProfile(AccountSuspensionService $accountSuspensionService, User $user) { - if (is_null($user->profile)) { - return redirect() ->back() ->with('error', "This user doesn't have a profile."); - } $socialMediaProfiles = json_decode($user->profile->socialLinks, true); $createdDate = Carbon::parse($user->created_at); - $suspensionInfo = null; - if ($accountSuspensionService->isSuspended($user)) - { + if ($accountSuspensionService->isSuspended($user)) { $suspensionInfo = [ 'isPermanent' => $user->bans->isPermanent, 'reason' => $user->bans->reason, - 'bannedUntil' => $user->bans->bannedUntil + 'bannedUntil' => $user->bans->bannedUntil, ]; } @@ -94,7 +87,7 @@ class ProfileController extends Controller 'discord' => $socialMediaProfiles['links']['discord'] ?? 'UpdateMe#12345', 'since' => $createdDate->englishMonth.' '.$createdDate->year, 'ipInfo' => IP::lookup($user->currentIp), - 'suspensionInfo' => $suspensionInfo + 'suspensionInfo' => $suspensionInfo, ]); } else { abort(403, __('You cannot view someone else\'s profile.')); @@ -104,23 +97,20 @@ class ProfileController extends Controller public function saveProfile(ProfileSave $request) { $this->profileService->updateProfile(Auth::user()->id, $request); + return redirect() ->back() ->with('success', __('Profile updated.')); } - public function createProfile(Request $request) { - try { $this->profileService->createProfile($request->user()); } catch (\Exception $e) { - return redirect() ->back() ->with('error', $e->getMessage()); - } return redirect() @@ -128,24 +118,18 @@ class ProfileController extends Controller ->with('success', __('Your profile has been created.')); } - - public function deleteProfile(Request $request) { - try { $this->profileService->deleteProfile($request->user()); } catch (ProfileNotFoundException $e) { - return redirect() ->back() ->with('error', $e->getMessage()); - } return redirect() ->back() ->with('success', __('Profile deleted successfully.')); - } } diff --git a/app/Http/Controllers/SecuritySettingsController.php b/app/Http/Controllers/SecuritySettingsController.php index fbe8e7d..af0ba31 100755 --- a/app/Http/Controllers/SecuritySettingsController.php +++ b/app/Http/Controllers/SecuritySettingsController.php @@ -2,34 +2,29 @@ namespace App\Http\Controllers; -use App\Facades\Options; use App\Http\Requests\SaveSecuritySettings; use App\Services\SecuritySettingsService; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Log; - -use function PHPSTORM_META\map; class SecuritySettingsController extends Controller { private $securityService; - public function __construct(SecuritySettingsService $securityService) { + public function __construct(SecuritySettingsService $securityService) + { $this->securityService = $securityService; } public function save(SaveSecuritySettings $request) { $this->securityService->save($request->secPolicy, [ - 'graceperiod' => $request->graceperiod, - 'pwExpiry' => $request->pwExpiry, - 'enforce2fa' => $request->enforce2fa, - 'requirePMC' => $request->requirePMC + 'graceperiod' => $request->graceperiod, + 'pwExpiry' => $request->pwExpiry, + 'enforce2fa' => $request->enforce2fa, + 'requirePMC' => $request->requirePMC, ]); return redirect() ->back() ->with('success', __('Settings saved.')); - } } diff --git a/app/Http/Controllers/TeamController.php b/app/Http/Controllers/TeamController.php index 56b735b..fff9db5 100755 --- a/app/Http/Controllers/TeamController.php +++ b/app/Http/Controllers/TeamController.php @@ -27,7 +27,6 @@ use App\Exceptions\UserAlreadyInvitedException; use App\Http\Requests\EditTeamRequest; use App\Http\Requests\NewTeamRequest; use App\Http\Requests\SendInviteRequest; -use App\Mail\InviteToTeam; use App\Services\TeamService; use App\Team; use App\User; @@ -35,22 +34,19 @@ use App\Vacancy; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Mail; use Mpociot\Teamwork\Exceptions\UserNotInTeamException; -use Mpociot\Teamwork\Facades\Teamwork; -use Mpociot\Teamwork\TeamInvite; class TeamController extends Controller { private $teamService; - public function __construct(TeamService $teamService) { + public function __construct(TeamService $teamService) + { $this->teamService = $teamService; } /** * Display a listing of the resource. - * */ public function index() { @@ -65,8 +61,9 @@ class TeamController extends Controller /** * Store a newly created resource in storage. * - * @param NewTeamRequest $request + * @param NewTeamRequest $request * @return RedirectResponse + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function store(NewTeamRequest $request) @@ -82,27 +79,30 @@ class TeamController extends Controller /** * Show the form for editing the specified resource. * - * @param Team $team + * @param Team $team * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function edit(Team $team) { $this->authorize('update', $team); + return view('dashboard.teams.edit-team') ->with([ - 'team' => $team, - 'users' => User::all(), - 'vacancies' => Vacancy::with('teams')->get()->all() + 'team' => $team, + 'users' => User::all(), + 'vacancies' => Vacancy::with('teams')->get()->all(), ]); } /** * Update the specified resource in storage. * - * @param EditTeamRequest $request - * @param Team $team + * @param EditTeamRequest $request + * @param Team $team * @return RedirectResponse + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function update(EditTeamRequest $request, Team $team): RedirectResponse @@ -110,7 +110,6 @@ class TeamController extends Controller $this->authorize('update', $team); $team = $this->teamService->updateTeam($team, $request->teamDescription, $request->joinType); - if ($team) { return redirect() ->to(route('teams.index')) @@ -138,14 +137,12 @@ class TeamController extends Controller $this->authorize('invite', $team); try { - $this->teamService->inviteUser($team, $request->user); return redirect() ->back() ->with('success', __('User invited successfully!')); - - } catch (UserAlreadyInvitedException | PublicTeamInviteException $ex) { + } catch (UserAlreadyInvitedException|PublicTeamInviteException $ex) { return redirect() ->back() ->with('error', $ex->getMessage()); @@ -155,19 +152,15 @@ class TeamController extends Controller public function processInviteAction(Request $request, $action, $token): RedirectResponse { try { - $this->teamService->processInvite(Auth::user(), $action, $token); return redirect() ->to(route('teams.index')) ->with('success', __('Invite processed successfully!')); - } catch (InvalidInviteException $e) { - return redirect() ->back() ->with('error', $e->getMessage()); - } } diff --git a/app/Http/Controllers/TeamFileController.php b/app/Http/Controllers/TeamFileController.php index dae8163..a669d04 100755 --- a/app/Http/Controllers/TeamFileController.php +++ b/app/Http/Controllers/TeamFileController.php @@ -4,46 +4,38 @@ namespace App\Http\Controllers; // Most of these namespaces have no effect on the code, however, they're used by IDEs so they can resolve return types and for PHPDocumentor as well - use App\Exceptions\FileUploadException; +use App\Http\Requests\UploadFileRequest; use App\Services\TeamFileService; use App\TeamFile; -use App\Http\Requests\UploadFileRequest; - - -use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Storage; -use League\Flysystem\FileNotFoundException; -// Documentation-purpose namespaces -use Illuminate\Contracts\Foundation\Application; -use Illuminate\Contts\View\Factory; -use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; -use Illuminate\Http\Response; - - +use Illuminate\Support\Facades\Auth; +// Documentation-purpose namespaces +use Illuminate\Support\Facades\Storage; +use League\Flysystem\FileNotFoundException; class TeamFileController extends Controller { private $fileService; - public function __construct(TeamFileService $fileService) { + public function __construct(TeamFileService $fileService) + { $this->fileService = $fileService; } /** * Display a listing of the resource. * - * @param Request $request + * @param Request $request */ public function index(Request $request) { $this->authorize('index', TeamFile::class); - if (is_null(Auth::user()->currentTeam)) - { + if (is_null(Auth::user()->currentTeam)) { $request->session()->flash('error', __('Please choose a team before viewing it\'s files.')); + return redirect()->to(route('teams.index')); } @@ -51,19 +43,17 @@ class TeamFileController extends Controller ->with('files', TeamFile::with('team', 'uploader')->paginate(6)); } - /** * Store a newly created resource in storage. * - * @param UploadFileRequest $request + * @param UploadFileRequest $request * @return RedirectResponse */ public function store(UploadFileRequest $request) { $this->authorize('store', TeamFile::class); - if (config('demo.is_enabled')) - { + if (config('demo.is_enabled')) { return redirect() ->back() ->with('error', __('This feature is disabled')); @@ -78,61 +68,49 @@ class TeamFileController extends Controller return redirect() ->back() ->with('success', __('File uploaded successfully.')); - } catch (FileUploadException $uploadException) { - return redirect() ->back() ->with('error', $uploadException->getMessage()); - } - } - public function download(Request $request, TeamFile $teamFile) { $this->authorize('download', TeamFile::class); - try - { + try { return Storage::download($teamFile->fs_location, $teamFile->name); - } - catch (FileNotFoundException $ex) - { - $request->session()->flash('error', __('Sorry, but the requested file could not be found in storage. Sometimes, files may be physically deleted by admins, but not from the app\'s database.')); - return redirect()->back(); + } catch (FileNotFoundException $ex) { + $request->session()->flash('error', __('Sorry, but the requested file could not be found in storage. Sometimes, files may be physically deleted by admins, but not from the app\'s database.')); + return redirect()->back(); } } /** * Remove the specified resource from storage. * - * @param Request $request - * @param \App\TeamFile $teamFile + * @param Request $request + * @param \App\TeamFile $teamFile * @return RedirectResponse */ public function destroy(Request $request, TeamFile $teamFile) { $this->authorize('delete', $teamFile); - if (config('demo.is_enabled')) - { + if (config('demo.is_enabled')) { return redirect() ->back() ->with('error', __('This feature is disabled')); } - try - { + try { Storage::delete($teamFile->fs_location); $teamFile->delete(); $request->session()->flash('success', __('File deleted successfully.')); - } - catch (\Exception $ex) - { + } catch (\Exception $ex) { $request->session()->flash('error', __('There was an error deleting the file: :msg', ['msg' => $ex->getMessage()])); } diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 95cba26..e1ab5d4 100755 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -22,7 +22,6 @@ namespace App\Http\Controllers; use App\Ban; -use App\Facades\IP; use App\Facades\Options; use App\Http\Requests\Add2FASecretRequest; use App\Http\Requests\AddDobRequest; @@ -44,7 +43,6 @@ use App\Services\AccountSuspensionService; use App\Services\DiscordService; use App\Traits\DisablesFeatures; use App\Traits\HandlesAccountDeletion; -use App\Traits\ReceivesAccountTokens; use App\User; use Google2FA; use Illuminate\Contracts\Foundation\Application; @@ -61,11 +59,11 @@ class UserController extends Controller { use HandlesAccountDeletion, DisablesFeatures; - /** * Shows list of users * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function showUsers() @@ -80,13 +78,14 @@ class UserController extends Controller ]); } - /** * Searches for a player with the given search query. * * @deprecated Until Algolia implementation - * @param SearchPlayerRequest $request + * + * @param SearchPlayerRequest $request * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function showPlayersLike(SearchPlayerRequest $request) @@ -115,12 +114,12 @@ class UserController extends Controller } } - /** * Shows the user account's settings page * - * @param Request $request + * @param Request $request * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View + * * @throws \PragmaRX\Google2FA\Exceptions\IncompatibleWithGoogleAuthenticatorException * @throws \PragmaRX\Google2FA\Exceptions\InvalidCharactersException * @throws \PragmaRX\Google2FA\Exceptions\SecretKeyTooShortException @@ -138,9 +137,9 @@ class UserController extends Controller } $QRCode = Google2FA::getQRCodeInline( - config('app.name'), - $request->user()->email, - $twoFactorSecret + config('app.name'), + $request->user()->email, + $twoFactorSecret ); } @@ -149,19 +148,18 @@ class UserController extends Controller ->with('twofaQRCode', $QRCode); } - /** * Show account management screen * - * @param AccountSuspensionService $suspensionService - * @param Request $request - * @param User $user + * @param AccountSuspensionService $suspensionService + * @param Request $request + * @param User $user * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function showAcocuntManagement(AccountSuspensionService $suspensionService, Request $request, User $user) { - $this->authorize('adminEdit', $user); $systemRoles = Role::all()->pluck('name')->all(); @@ -179,7 +177,7 @@ class UserController extends Controller return view('dashboard.user.manage') ->with([ - 'user' => $user, + 'user' => $user, 'roles' => $roleList, 'isVerified' => $user->isVerified(), 'isLocked' => $suspensionService->isLocked($user), @@ -190,15 +188,16 @@ class UserController extends Controller 'suspensionReason' => $suspensionService->getSuspensionReason($user), 'suspensionDuration' => $suspensionService->getSuspensionDuration($user), 'has2FA' => $user->has2FA(), - 'applications' => $user->applications()->get() + 'applications' => $user->applications()->get(), ]); } /** * Log out other sessions for the current user * - * @param FlushSessionsRequest $request + * @param FlushSessionsRequest $request * @return \Illuminate\Http\RedirectResponse + * * @throws \Illuminate\Auth\AuthenticationException */ public function flushSessions(FlushSessionsRequest $request) @@ -208,23 +207,21 @@ class UserController extends Controller Auth::logoutOtherDevices($request->currentPasswordFlush); Log::notice('User '.Auth::user()->name.' has logged out other devices in their account', - [ - 'originIPAddress' => $request->ip(), - 'userID' => Auth::user()->id, - 'timestamp' => now(), - ]); + [ + 'originIPAddress' => $request->ip(), + 'userID' => Auth::user()->id, + 'timestamp' => now(), + ]); $request->session()->flash('success', __('Successfully logged out other devices. Remember to change your password if you think you\'ve been compromised.')); return redirect()->back(); } - - /** * Change the current user's password * - * @param ChangePasswordRequest $request + * @param ChangePasswordRequest $request * @return \Illuminate\Http\RedirectResponse|void */ public function changePassword(ChangePasswordRequest $request) @@ -255,17 +252,15 @@ class UserController extends Controller } } - /** * Sets a new password for the user. * - * @param SetNewPasswordRequest $request + * @param SetNewPasswordRequest $request * @return Application|RedirectResponse|Redirector */ - public function setPassword(SetNewPasswordRequest $request) { - - if (!Auth::user()->hasPassword()) { - + public function setPassword(SetNewPasswordRequest $request) + { + if (! Auth::user()->hasPassword()) { Auth::user()->password = Hash::make($request->newpass); Auth::user()->save(); @@ -281,12 +276,11 @@ class UserController extends Controller ->with('error', __('Your account already has a password.')); } - /** * Sets a user's password and removes their discord information from storage * - * @param User $user - * @param SetNewPasswordRequest $request + * @param User $user + * @param SetNewPasswordRequest $request * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function unlinkDiscordAccount(Request $request, DiscordService $discordService) @@ -295,40 +289,39 @@ class UserController extends Controller try { $discordService->revokeAccountTokens(Auth::user()); Log::warning('Revoking social account tokens, user initiated', [ - 'user' => Auth::user()->email + 'user' => Auth::user()->email, ]); } catch (RequestException $requestException) { - if ($requestException->getCode() == 401) { return redirect(route('discordRedirect')); } Log::error('Error while trying to revoke Discord credentials', [$requestException->getMessage()]); + return redirect() ->back() ->with('error', __('An unknown error ocurred. Please try again later.')); } $request->session()->flash('success', __('Discord account unlinked successfully. Link it again by re-authorizing the app with the same account in the login screen, or through your account settings.')); + return redirect()->back(); } return redirect() ->back() ->with('error', __('Please set a password for your account first before trying to unlink Discord.')); - } - /** * Change the current user's email address * - * @param ChangeEmailRequest $request + * @param ChangeEmailRequest $request * @return \Illuminate\Http\RedirectResponse */ public function changeEmail(ChangeEmailRequest $request) { - $this->disable(); + $this->disable(); $user = User::find(Auth::user()->id); @@ -351,16 +344,16 @@ class UserController extends Controller return redirect()->back(); } - /** * Removes the user's password and notifies them. * - * @param User $user The user to remove the password for + * @param User $user The user to remove the password for * @return \Illuminate\Http\RedirectResponse + * * @throws \Illuminate\Auth\Access\AuthorizationException */ - public function forcePasswordReset(User $user) { - + public function forcePasswordReset(User $user) + { $this->authorize('adminEdit', $user); if ($user->hasPassword()) { @@ -369,10 +362,9 @@ class UserController extends Controller $user->password = null; $user->save(); - - Log::alert("Removed account password", [ + Log::alert('Removed account password', [ 'target' => $user, - 'actor' => Auth::user() + 'actor' => Auth::user(), ]); return redirect() @@ -385,15 +377,14 @@ class UserController extends Controller ->with('error', __('This user doesn\'t have a password to reset.')); } - /** * Adds a user's date of birth if they don't have one. * - * @param AddDobRequest $request + * @param AddDobRequest $request * @return RedirectResponse */ - public function addDob(AddDobRequest $request) { - + public function addDob(AddDobRequest $request) + { Auth::user()->dob = $request->dob; Auth::user()->save(); @@ -401,13 +392,13 @@ class UserController extends Controller ->back(); } - /** * Delete the given user's account * - * @param DeleteUserRequest $request - * @param User $user + * @param DeleteUserRequest $request + * @param User $user * @return \Illuminate\Http\RedirectResponse + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function delete(DeleteUserRequest $request, User $user) @@ -426,13 +417,13 @@ class UserController extends Controller return redirect()->route('registeredPlayerList'); } - /** * Update a given user's details * - * @param UpdateUserRequest $request - * @param User $user + * @param UpdateUserRequest $request + * @param User $user * @return \Illuminate\Http\RedirectResponse + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function update(UpdateUserRequest $request, User $user) @@ -470,12 +461,12 @@ class UserController extends Controller return redirect()->back(); } - /** * Generate and add a 2FA secret for the current user * - * @param Add2FASecretRequest $request + * @param Add2FASecretRequest $request * @return \Illuminate\Http\RedirectResponse + * * @throws \PragmaRX\Google2FA\Exceptions\IncompatibleWithGoogleAuthenticatorException * @throws \PragmaRX\Google2FA\Exceptions\InvalidCharactersException * @throws \PragmaRX\Google2FA\Exceptions\SecretKeyTooShortException @@ -522,11 +513,10 @@ class UserController extends Controller return redirect()->back(); } - /** * Remove the current user's two factor secret key * - * @param Remove2FASecretRequest $request + * @param Remove2FASecretRequest $request * @return \Illuminate\Http\RedirectResponse */ public function remove2FASecret(Remove2FASecretRequest $request) @@ -544,15 +534,15 @@ class UserController extends Controller return redirect()->back(); } - /** * Remove the given user's two factor secret key * - * @param Reset2FASecretRequest $request - * @param User $user + * @param Reset2FASecretRequest $request + * @param User $user * @return \Illuminate\Http\RedirectResponse */ - public function reset2FASecret(Reset2FASecretRequest $request, User $user) { + public function reset2FASecret(Reset2FASecretRequest $request, User $user) + { // note: could invalidate other sessions for increased security if ($user->has2FA()) { Log::warning('SECURITY: Disabling two factor authentication (admin initiated)', [ @@ -580,10 +570,11 @@ class UserController extends Controller /** * Suspend the given user * - * @param AccountSuspensionService $suspensionService - * @param BanUserRequest $request - * @param User $user + * @param AccountSuspensionService $suspensionService + * @param BanUserRequest $request + * @param User $user * @return \Illuminate\Http\RedirectResponse + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function suspend(AccountSuspensionService $suspensionService, BanUserRequest $request, User $user) @@ -591,17 +582,15 @@ class UserController extends Controller $this->authorize('create', [Ban::class, $user]); $this->disable(); - if ($suspensionService->isSuspended($user)) - { + if ($suspensionService->isSuspended($user)) { return redirect() ->back() ->with('error', __('Account already suspended.')); } - if ($request->suspensionType = "on") { + if ($request->suspensionType = 'on') { $suspensionService->suspend($user, $request->reason, $request->duration); - } - else { + } else { $suspensionService->suspend($user, $request->reason); } @@ -611,10 +600,11 @@ class UserController extends Controller /** * Unsuspend the given user * - * @param AccountSuspensionService $suspensionService - * @param Request $request - * @param User $user + * @param AccountSuspensionService $suspensionService + * @param Request $request + * @param User $user * @return \Illuminate\Http\RedirectResponse + * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function unsuspend(AccountSuspensionService $suspensionService, Request $request, User $user) @@ -623,15 +613,12 @@ class UserController extends Controller $this->disable(); if ($suspensionService->isSuspended($user)) { - $suspensionService->unsuspend($user); $request->session()->flash('success', __('Account unsuspended successfully!')); - } else { $request->session()->flash('error', __('This account isn\'t suspended!')); } return redirect()->back(); } - } diff --git a/app/Http/Controllers/VacancyController.php b/app/Http/Controllers/VacancyController.php index 84d5870..02e7a24 100755 --- a/app/Http/Controllers/VacancyController.php +++ b/app/Http/Controllers/VacancyController.php @@ -21,7 +21,6 @@ namespace App\Http\Controllers; -use App\Facades\JSON; use App\Form; use App\Http\Requests\VacancyEditRequest; use App\Http\Requests\VacancyRequest; @@ -50,8 +49,6 @@ class VacancyController extends Controller $messageIsError = false; $this->authorize('create', Vacancy::class); - - $form = Form::find($request->vacancyFormID); if (! is_null($form)) { @@ -71,12 +68,11 @@ class VacancyController extends Controller 'vacancyFormID' => $request->vacancyFormID, 'vacancyCount' => $request->vacancyCount, 'requiresDiscord' => $request->requireDiscordAccount == 'on', - 'requiredAge' => $request->requiredAge + 'requiredAge' => $request->requiredAge, ]); $message = __('Vacancy successfully opened. It will now show in the home page.'); - } else { $message = __('You cannot create a vacancy without a valid form.'); $messageIsError = true; @@ -108,12 +104,9 @@ class VacancyController extends Controller break; default: - $message = __("Please do not tamper with the URLs. To report a bug, please contact an administrator."); + $message = __('Please do not tamper with the URLs. To report a bug, please contact an administrator.'); $type = 'error'; - } - - } else { $message = __("The position you're trying to update doesn't exist!"); $type = 'error'; @@ -126,7 +119,6 @@ class VacancyController extends Controller return redirect() ->back() ->with($type, $message); - } public function edit(Request $request, Vacancy $vacancy) @@ -141,7 +133,7 @@ class VacancyController extends Controller { $this->authorize('update', $vacancy); - $vacancy->vacancyFullDescription = $request->vacancyFullDescription; + $vacancy->vacancyFullDescription = $request->vacancyFullDescription; $vacancy->vacancyDescription = $request->vacancyDescription; $vacancy->vacancyCount = $request->vacancyCount; $vacancy->requiresDiscord = $request->requireDiscordAccount == 'on'; @@ -159,7 +151,6 @@ class VacancyController extends Controller $this->authorize('delete', $vacancy); if ($vacancy->teams->isEmpty()) { - $vacancy->delete(); return redirect() diff --git a/app/Http/Middleware/ApplicationEligibility.php b/app/Http/Middleware/ApplicationEligibility.php index c28efc4..5f8f1e3 100755 --- a/app/Http/Middleware/ApplicationEligibility.php +++ b/app/Http/Middleware/ApplicationEligibility.php @@ -23,7 +23,6 @@ namespace App\Http\Middleware; use App\Application; use App\User; -use Carbon\Carbon; use Closure; use Exception; use Illuminate\Http\Request; @@ -38,9 +37,11 @@ class ApplicationEligibility * * @deprecated Deprecated in 0.9.0 * @see User::isEligible() - * @param Request $request - * @param Closure $next + * + * @param Request $request + * @param Closure $next * @return mixed + * * @throws Exception */ public function handle($request, Closure $next) @@ -49,7 +50,6 @@ class ApplicationEligibility $daysRemaining = __('N/A'); if (Auth::check()) { - $lastApplication = Application::where('applicantUserID', Auth::user()->id)->latest()->first(); if (is_null($lastApplication)) { @@ -61,7 +61,6 @@ class ApplicationEligibility $daysRemaining = $lastApplication->created_at->addMonth()->diffInDays(now()); if ($lastApplication->created_at->diffInMonths(now()) > 1 && in_array($lastApplication->applicationStatus, ['DENIED', 'APPROVED'])) { - $eligible = true; } @@ -69,7 +68,7 @@ class ApplicationEligibility 'eligible' => $eligible, 'daysRemaining' => $daysRemaining, 'ipAddress' => Auth::user()->originalIP, - 'checkUserID' => Auth::user()->id + 'checkUserID' => Auth::user()->id, ]); View::share('isEligibleForApplication', $eligible); diff --git a/app/Http/Middleware/Bancheck.php b/app/Http/Middleware/Bancheck.php index a7880d2..711e3e8 100755 --- a/app/Http/Middleware/Bancheck.php +++ b/app/Http/Middleware/Bancheck.php @@ -31,12 +31,11 @@ class Bancheck { private AccountSuspensionService $suspensionService; - - public function __construct(AccountSuspensionService $suspensionService) { + public function __construct(AccountSuspensionService $suspensionService) + { $this->suspensionService = $suspensionService; } - /** * Handle an incoming request. * diff --git a/app/Http/Middleware/ForceLogoutMiddleware.php b/app/Http/Middleware/ForceLogoutMiddleware.php index a8b23fa..30d1d9a 100755 --- a/app/Http/Middleware/ForceLogoutMiddleware.php +++ b/app/Http/Middleware/ForceLogoutMiddleware.php @@ -36,7 +36,6 @@ class ForceLogoutMiddleware */ public function handle($request, Closure $next) { - if ((new AccountSuspensionService())->isSuspended(Auth::user())) { Auth::logout(); $request->session()->flash('error', __('Your account is suspended. If you think this was a mistake, please contact an admin.')); diff --git a/app/Http/Middleware/PasswordExpirationMiddleware.php b/app/Http/Middleware/PasswordExpirationMiddleware.php index e76210c..56cbddf 100755 --- a/app/Http/Middleware/PasswordExpirationMiddleware.php +++ b/app/Http/Middleware/PasswordExpirationMiddleware.php @@ -19,20 +19,15 @@ class PasswordExpirationMiddleware */ public function handle(Request $request, Closure $next) { - if(Auth::check()) - { + if (Auth::check()) { $sinceUpdate = Carbon::parse(Auth::user()->password_last_updated)->diffInDays(now()); $updateThreshold = Options::getOption('password_expiry'); - if ($updateThreshold !== 0 && $sinceUpdate > $updateThreshold) - { + if ($updateThreshold !== 0 && $sinceUpdate > $updateThreshold) { session()->put('passwordExpired', true); - } - else - { + } else { session()->put('passwordExpired', false); } - } return $next($request); diff --git a/app/Http/Middleware/PasswordExpirationRedirectMiddleware.php b/app/Http/Middleware/PasswordExpirationRedirectMiddleware.php index b4a687f..b87abe4 100755 --- a/app/Http/Middleware/PasswordExpirationRedirectMiddleware.php +++ b/app/Http/Middleware/PasswordExpirationRedirectMiddleware.php @@ -17,8 +17,7 @@ class PasswordExpirationRedirectMiddleware */ public function handle(Request $request, Closure $next) { - if (Auth::check() && session('passwordExpired')) - { + if (Auth::check() && session('passwordExpired')) { // WARNING!! Routes under the profile group must not have this middleware, because it'll result in an infinite redirect loop. return redirect(route('showAccountSettings')); } diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 938be5d..7f429d7 100755 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -24,7 +24,6 @@ namespace App\Http\Middleware; use Illuminate\Http\Middleware\TrustProxies as Middleware; use Illuminate\Http\Request; - class TrustProxies extends Middleware { /** @@ -45,5 +44,4 @@ class TrustProxies extends Middleware Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_AWS_ELB; - } diff --git a/app/Http/Requests/BanUserRequest.php b/app/Http/Requests/BanUserRequest.php index 943bd90..404b176 100755 --- a/app/Http/Requests/BanUserRequest.php +++ b/app/Http/Requests/BanUserRequest.php @@ -53,7 +53,7 @@ class BanUserRequest extends FormRequest public function messages() { return [ - 'duration.required_if' => __('You must provide a duration if the suspension is temporary.') + 'duration.required_if' => __('You must provide a duration if the suspension is temporary.'), ]; } } diff --git a/app/Http/Requests/CancelAppointmentRequest.php b/app/Http/Requests/CancelAppointmentRequest.php index 4ba920e..812465d 100755 --- a/app/Http/Requests/CancelAppointmentRequest.php +++ b/app/Http/Requests/CancelAppointmentRequest.php @@ -24,7 +24,7 @@ class CancelAppointmentRequest extends FormRequest public function rules() { return [ - 'reason' => 'string|required' + 'reason' => 'string|required', ]; } } diff --git a/app/Http/Requests/ProfileSave.php b/app/Http/Requests/ProfileSave.php index 7d79846..fd431c8 100755 --- a/app/Http/Requests/ProfileSave.php +++ b/app/Http/Requests/ProfileSave.php @@ -29,7 +29,7 @@ class ProfileSave extends FormRequest /** * Determine if the user is authorized to make this request. * - * @param Profile $profile + * @param Profile $profile * @return bool */ public function authorize(Profile $profile) diff --git a/app/Http/Requests/SaveSecuritySettings.php b/app/Http/Requests/SaveSecuritySettings.php index 245d630..5964894 100755 --- a/app/Http/Requests/SaveSecuritySettings.php +++ b/app/Http/Requests/SaveSecuritySettings.php @@ -28,7 +28,7 @@ class SaveSecuritySettings extends FormRequest 'graceperiod' => 'required|integer', 'pwExpiry' => 'required|integer', 'enforce2fa' => 'required|boolean', - 'requirePMC' => 'required|boolean' + 'requirePMC' => 'required|boolean', ]; } } diff --git a/app/Http/Requests/StoreAbsenceRequest.php b/app/Http/Requests/StoreAbsenceRequest.php index 77d9355..402f64b 100755 --- a/app/Http/Requests/StoreAbsenceRequest.php +++ b/app/Http/Requests/StoreAbsenceRequest.php @@ -5,7 +5,6 @@ namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; - class StoreAbsenceRequest extends FormRequest { /** @@ -30,7 +29,7 @@ class StoreAbsenceRequest extends FormRequest 'start_date' => 'required|date', 'predicted_end' => 'required|date|after:start_date', 'available_assist' => 'required|string', - 'invalidAbsenceAgreement' => 'required|accepted' + 'invalidAbsenceAgreement' => 'required|accepted', ]; } } diff --git a/app/Http/Requests/UploadFileRequest.php b/app/Http/Requests/UploadFileRequest.php index 46b5ea7..200ccac 100755 --- a/app/Http/Requests/UploadFileRequest.php +++ b/app/Http/Requests/UploadFileRequest.php @@ -26,7 +26,7 @@ class UploadFileRequest extends FormRequest return [ 'caption' => 'required|string|max:100', 'description' => 'required|string|max:800', - 'file' => 'required|file|mimes:jpeg,jpg,png,bmp,tiff,docx,doc,odt,ott,xls,xlsx,ods,ots,gif,pdf,mp3,mp4,pptx,ppt,odp,ppsx,pub,psd,svg' + 'file' => 'required|file|mimes:jpeg,jpg,png,bmp,tiff,docx,doc,odt,ott,xls,xlsx,ods,ots,gif,pdf,mp3,mp4,pptx,ppt,odp,ppsx,pub,psd,svg', ]; } } diff --git a/app/Http/Requests/VacancyEditRequest.php b/app/Http/Requests/VacancyEditRequest.php index 9c9544c..6bba155 100755 --- a/app/Http/Requests/VacancyEditRequest.php +++ b/app/Http/Requests/VacancyEditRequest.php @@ -48,7 +48,7 @@ class VacancyEditRequest extends FormRequest 'vacancyFullDescription' => 'nullable|string', 'vacancyCount' => 'required|integer|min:1', 'requireDiscordAccount' => 'required|string', - 'requiredAge' => 'required|integer|numeric|min:13|max:100' + 'requiredAge' => 'required|integer|numeric|min:13|max:100', ]; } } diff --git a/app/Http/Requests/VacancyRequest.php b/app/Http/Requests/VacancyRequest.php index 2e7251d..0c02f79 100755 --- a/app/Http/Requests/VacancyRequest.php +++ b/app/Http/Requests/VacancyRequest.php @@ -53,7 +53,7 @@ class VacancyRequest extends FormRequest 'vacancyCount' => 'required|integer', 'vacancyFormID' => 'required|integer', 'requireDiscordAccount' => 'required|string', - 'requiredAge' => 'required|integer|numeric|min:13|max:100' + 'requiredAge' => 'required|integer|numeric|min:13|max:100', ]; } } diff --git a/app/Http/Resources/ApplicationResource.php b/app/Http/Resources/ApplicationResource.php index 3994e00..88d1714 100755 --- a/app/Http/Resources/ApplicationResource.php +++ b/app/Http/Resources/ApplicationResource.php @@ -22,7 +22,7 @@ class ApplicationResource extends JsonResource 'applicant' => new UserResource(User::findOrFail($this->applicantUserID)), 'response' => new ResponseResource(Response::findOrFail($this->applicantFormResponseID)), 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at + 'updated_at' => $this->updated_at, ]; } } diff --git a/app/Http/Resources/FormResource.php b/app/Http/Resources/FormResource.php index d3009ac..57c261b 100755 --- a/app/Http/Resources/FormResource.php +++ b/app/Http/Resources/FormResource.php @@ -20,7 +20,7 @@ class FormResource extends JsonResource 'formStructure' => json_decode($this->formStructure), 'formStatus' => $this->formStatus, 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at + 'updated_at' => $this->updated_at, ]; } } diff --git a/app/Http/Resources/ResponseResource.php b/app/Http/Resources/ResponseResource.php index 14c6dc6..a2dff70 100755 --- a/app/Http/Resources/ResponseResource.php +++ b/app/Http/Resources/ResponseResource.php @@ -22,7 +22,7 @@ class ResponseResource extends JsonResource 'responseData' => json_decode($this->responseData), 'vacancy' => new VacancyResource(Vacancy::findOrFail($this->associatedVacancyID)), 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at + 'updated_at' => $this->updated_at, ]; } } diff --git a/app/Http/Resources/UserResource.php b/app/Http/Resources/UserResource.php index 012c71c..f4557a7 100755 --- a/app/Http/Resources/UserResource.php +++ b/app/Http/Resources/UserResource.php @@ -22,7 +22,7 @@ class UserResource extends JsonResource 'username' => $this->username, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, - 'current_team_id' => $this->current_team_id + 'current_team_id' => $this->current_team_id, ]; } } diff --git a/app/Jobs/ProcessAccountDelete.php b/app/Jobs/ProcessAccountDelete.php index f287751..3a402d0 100755 --- a/app/Jobs/ProcessAccountDelete.php +++ b/app/Jobs/ProcessAccountDelete.php @@ -6,7 +6,6 @@ use App\Notifications\AccountDeleted; use App\Notifications\UserDeletedAccount; use App\User; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; @@ -25,7 +24,6 @@ class ProcessAccountDelete implements ShouldQueue */ protected User $user; - /** * Create a new job instance. * @@ -44,7 +42,7 @@ class ProcessAccountDelete implements ShouldQueue public function handle() { Log::alert('[Worker] Processing account deletion request', [ - 'email' => $this->user->email + 'email' => $this->user->email, ]); $email = $this->user->email; @@ -52,7 +50,7 @@ class ProcessAccountDelete implements ShouldQueue if ($this->user->delete()) { Notification::route('mail', [ - $email => $name + $email => $name, ])->notify(new AccountDeleted($name)); // Notify admins diff --git a/app/Jobs/ProcessDueSuspensions.php b/app/Jobs/ProcessDueSuspensions.php index ca9e352..6627aec 100755 --- a/app/Jobs/ProcessDueSuspensions.php +++ b/app/Jobs/ProcessDueSuspensions.php @@ -21,9 +21,7 @@ namespace App\Jobs; -use App\Ban; use App\Services\AccountSuspensionService; -use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; diff --git a/app/Jobs/ProcessExpiredAbsences.php b/app/Jobs/ProcessExpiredAbsences.php index e953f81..be3671c 100755 --- a/app/Jobs/ProcessExpiredAbsences.php +++ b/app/Jobs/ProcessExpiredAbsences.php @@ -4,7 +4,6 @@ namespace App\Jobs; use App\Services\AbsenceService; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; diff --git a/app/Listeners/DenyUser.php b/app/Listeners/DenyUser.php index 34095ca..1ef29ff 100755 --- a/app/Listeners/DenyUser.php +++ b/app/Listeners/DenyUser.php @@ -40,7 +40,7 @@ class DenyUser /** * Handle the event. * - * @param ApplicationDeniedEvent $event + * @param ApplicationDeniedEvent $event * @return void */ public function handle(ApplicationDeniedEvent $event) diff --git a/app/Listeners/NewUser.php b/app/Listeners/NewUser.php index 5d3f228..0a1a750 100755 --- a/app/Listeners/NewUser.php +++ b/app/Listeners/NewUser.php @@ -2,9 +2,6 @@ namespace App\Listeners; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Queue\InteractsWithQueue; - class NewUser { /** diff --git a/app/Listeners/OnUserRegistration.php b/app/Listeners/OnUserRegistration.php index c866cd5..5e88e00 100755 --- a/app/Listeners/OnUserRegistration.php +++ b/app/Listeners/OnUserRegistration.php @@ -50,10 +50,9 @@ class OnUserRegistration Log::info('User '.$event->user->name.' has just registered for an account.'); User::whereHas('roles', function ($q) { - $q->where('name', 'admin'); + $q->where('name', 'admin'); })->get()->each(function ($user, $key) use ($event) { $user->notify(new NewUser($event->user)); }); - } } diff --git a/app/Listeners/PromoteUser.php b/app/Listeners/PromoteUser.php index 93675cd..858e38a 100755 --- a/app/Listeners/PromoteUser.php +++ b/app/Listeners/PromoteUser.php @@ -40,7 +40,7 @@ class PromoteUser /** * Handle the event. * - * @param ApplicationApprovedEvent $event + * @param ApplicationApprovedEvent $event * @return void */ public function handle(ApplicationApprovedEvent $event) @@ -48,7 +48,7 @@ class PromoteUser Log::info('User promoted automatically (application approved)', [ 'user' => $event->application->user->name, 'vacancy' => $event->application->response->vacancy->vacancyName, - 'role' => 'staff' + 'role' => 'staff', ]); $event->application->setStatus('APPROVED'); diff --git a/app/Mail/UserAccountDeleteConfirmation.php b/app/Mail/UserAccountDeleteConfirmation.php index 3ab4110..a8ad4b3 100755 --- a/app/Mail/UserAccountDeleteConfirmation.php +++ b/app/Mail/UserAccountDeleteConfirmation.php @@ -31,11 +31,16 @@ class UserAccountDeleteConfirmation extends Mailable use Queueable, SerializesModels; public string - $approveLink, - $cancelLink, - $name, - $userID; + $approveLink; + public string + $cancelLink; + + public string + $name; + + public string + $userID; /** * Create a new message instance. @@ -58,7 +63,7 @@ class UserAccountDeleteConfirmation extends Mailable */ public function build() { - return $this->subject(config('app.name') . ' - please confirm account removal (action required)') + return $this->subject(config('app.name').' - please confirm account removal (action required)') ->view('mail.deleted-account'); } } diff --git a/app/Notifications/AbsenceRequestApproved.php b/app/Notifications/AbsenceRequestApproved.php index 4da1094..df86cc4 100755 --- a/app/Notifications/AbsenceRequestApproved.php +++ b/app/Notifications/AbsenceRequestApproved.php @@ -44,13 +44,13 @@ class AbsenceRequestApproved extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - absence request approved') ->line("Your recent Leave of Absence request from {$this->absence->created_at} has just been approved by an admin.") ->line('Your inactivity during the period you selected won\'t be counted. You will receive another email notification when your request ends, or if you decide to cancel it.') ->action('View your request', url(route('absences.show', ['absence' => $this->absence->id]))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/AbsenceRequestCancelled.php b/app/Notifications/AbsenceRequestCancelled.php index 7e3d27f..b603d3b 100755 --- a/app/Notifications/AbsenceRequestCancelled.php +++ b/app/Notifications/AbsenceRequestCancelled.php @@ -44,13 +44,13 @@ class AbsenceRequestCancelled extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - absence request cancelled') ->line("This notification confirms that your recent Leave of Absence from {$this->absence->created_at} has just been cancelled by you.") ->line('Please note that any inactivity will be counted in our activity metrics. You may also make a new request if you wish.') ->action('Send new request', url(route('absences.create'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/AbsenceRequestDeclined.php b/app/Notifications/AbsenceRequestDeclined.php index 3fd5da3..3bd48c6 100755 --- a/app/Notifications/AbsenceRequestDeclined.php +++ b/app/Notifications/AbsenceRequestDeclined.php @@ -44,13 +44,13 @@ class AbsenceRequestDeclined extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - absence request declined') ->line("Your recent Leave of Absence request from {$this->absence->created_at} has just been declined by an admin.") ->line('Please note that any inactivity will be counted in our activity metrics. You may make a new request, but we recommend you ask your team lead regarding your declined request.') ->action('Send new request', url(route('absences.create'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/AbsenceRequestEnded.php b/app/Notifications/AbsenceRequestEnded.php index cbbf512..d590a4d 100755 --- a/app/Notifications/AbsenceRequestEnded.php +++ b/app/Notifications/AbsenceRequestEnded.php @@ -44,13 +44,13 @@ class AbsenceRequestEnded extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - absence request expired') ->line("Your Leave of Absence request from {$this->absence->created_at} (until {$this->absence->predicted_end}) has expired today.") ->line('Please note that any inactivity will be counted in our activity metrics. You may now make a new request if you still need more time.') ->action('Send new request', url(route('absences.create'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/AccountDeleted.php b/app/Notifications/AccountDeleted.php index 4300d9d..d0f3464 100755 --- a/app/Notifications/AccountDeleted.php +++ b/app/Notifications/AccountDeleted.php @@ -44,14 +44,14 @@ class AccountDeleted extends Notification implements ShouldQueue { // Adjust to notify external user return (new MailMessage) - ->greeting('Hi ' . $this->name . ',') + ->greeting('Hi '.$this->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - account deleted permanently') ->line('Thank you for confirming your account deletion request. We\'re sorry to see you go!') ->line('Unless you sign up again, this is the last email you\'ll be receiving from us.') ->line('Please let us know if there\'s any feedback you\'d like to share. You can use the feedback widget located on the left-hand side of our website, or the chat widget located on the lower right corner.') ->line('See you around!') - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/AccountUnlocked.php b/app/Notifications/AccountUnlocked.php index fd5dfb9..5fc8b14 100755 --- a/app/Notifications/AccountUnlocked.php +++ b/app/Notifications/AccountUnlocked.php @@ -41,14 +41,14 @@ class AccountUnlocked extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - account unlocked') - ->line('We wanted to let you know that your account at ' . config('app.name') . ' is now unlocked. This means the circumstances surrounding your account\'s standing are now resolved.') + ->line('We wanted to let you know that your account at '.config('app.name').' is now unlocked. This means the circumstances surrounding your account\'s standing are now resolved.') ->line('You can sign in and use the app normally again.') ->line('If there\'s anything we can help you with, don\'t hesitate to reach out.') ->action('Sign in', url(route('login'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/ApplicationApproved.php b/app/Notifications/ApplicationApproved.php index d4c6ca3..c756b70 100755 --- a/app/Notifications/ApplicationApproved.php +++ b/app/Notifications/ApplicationApproved.php @@ -35,13 +35,11 @@ class ApplicationApproved extends Notification implements ShouldQueue { use Queueable, Cancellable; - /** * @var Application The application we're notifying about */ public Application $application; - /** * @var User The candidate */ @@ -76,7 +74,7 @@ class ApplicationApproved extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - application approved') ->line('Congratulations! Your most recent application has been approved by the reviewing team.') @@ -84,7 +82,7 @@ class ApplicationApproved extends Notification implements ShouldQueue ->line('You should have received more information about your onboarding process by now.') ->line('Good luck and welcome aboard!') ->action('Sign in', url(route('login'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } public function toSlack($notifiable) diff --git a/app/Notifications/ApplicationConfirmed.php b/app/Notifications/ApplicationConfirmed.php index 33148d2..c1e2982 100755 --- a/app/Notifications/ApplicationConfirmed.php +++ b/app/Notifications/ApplicationConfirmed.php @@ -4,7 +4,6 @@ namespace App\Notifications; use App\Application; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; @@ -44,13 +43,13 @@ class ApplicationConfirmed extends Notification public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) - ->subject(config('app.name') . ' - application confirmed') + ->subject(config('app.name').' - application confirmed') ->line('We\'re writing you to let you know that your recent application with us has been received, and will be processed in 24/48 hours.') ->line('You will receive regular notifications about your application\'s status.') ->action('View active applications', url(route('showUserApps'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/ApplicationDenied.php b/app/Notifications/ApplicationDenied.php index 427d75e..d96e4b8 100755 --- a/app/Notifications/ApplicationDenied.php +++ b/app/Notifications/ApplicationDenied.php @@ -64,14 +64,14 @@ class ApplicationDenied extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - application denied') ->line('We\'re sorry to inform you that your application with us has been reviewed and declined.') ->line('Our review team denies applications for several reasons, including poor answers, missing information, or lacking qualifications.') ->line('Please review your application and try again later. You can view your account\'s eligibility status in your dashboard.') ->action('Review application', url(route('showUserApp', ['application' => $this->application->id]))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } public function toSlack($notifiable) diff --git a/app/Notifications/ApplicationMoved.php b/app/Notifications/ApplicationMoved.php index b8d8d56..8bbd481 100755 --- a/app/Notifications/ApplicationMoved.php +++ b/app/Notifications/ApplicationMoved.php @@ -46,15 +46,16 @@ class ApplicationMoved extends Notification implements ShouldQueue public function channels() { Log::debug('Application moved notification: channels chosen', [ - 'channels' => $this->chooseChannelsViaOptions() + 'channels' => $this->chooseChannelsViaOptions(), ]); + return $this->chooseChannelsViaOptions(); } public function optOut($notifiable) { Log::debug('Application moved notification: opt out verified', [ - 'opt-out' => Options::getOption('notify_application_status_change') != 1 + 'opt-out' => Options::getOption('notify_application_status_change') != 1, ]); return Options::getOption('notify_application_status_change') != 1; @@ -69,13 +70,13 @@ class ApplicationMoved extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - application updated') ->line('Your application has been moved to the next step.') ->line('This means our team has reviewed it and an interview will be scheduled soon.') ->action('Sign in', url(route('login'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/AppointmentCancelled.php b/app/Notifications/AppointmentCancelled.php index 3bfc80e..c95f13b 100755 --- a/app/Notifications/AppointmentCancelled.php +++ b/app/Notifications/AppointmentCancelled.php @@ -5,7 +5,6 @@ namespace App\Notifications; use App\Application; use Carbon\Carbon; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; @@ -14,7 +13,9 @@ class AppointmentCancelled extends Notification use Queueable; private $application; + private $reason; + private $appointmentDate; /** @@ -51,16 +52,16 @@ class AppointmentCancelled extends Notification // TODO: Switch to HTML & Blade. return (new MailMessage) - ->greeting("Hi " . $notifiable->name . ",") + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - interview cancelled') ->line('The interview that was previously scheduled with you has been cancelled.') ->line('Date and time of the old appointment: '.$this->appointmentDate) - ->line('Your appointment was cancelled for the following reason: ' . $this->reason) + ->line('Your appointment was cancelled for the following reason: '.$this->reason) ->line('A team member may contact you to reschedule within a new timeframe - you may also let us know of a date and time that suits you.') ->line('Your application will likely be declined if you do not reschedule an interview.') ->action('View active applications', url(route('showUserApps'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/AppointmentFinished.php b/app/Notifications/AppointmentFinished.php index a16b2b2..a34e954 100755 --- a/app/Notifications/AppointmentFinished.php +++ b/app/Notifications/AppointmentFinished.php @@ -31,7 +31,6 @@ class AppointmentFinished extends Notification implements ShouldQueue { use Queueable; - public $appointment; /** @@ -64,14 +63,13 @@ class AppointmentFinished extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting("Hi " . $notifiable->name . ",") + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - appointment completed') - ->line('Your appointment, "' . $this->appointment->appointmentDescription . '", has been marked as completed!') + ->line('Your appointment, "'.$this->appointment->appointmentDescription.'", has been marked as completed!') ->line('Please allow an additional day for your application to be fully processed.') ->action('View applications', url(route('showUserApps'))) - ->salutation('The team at ' . config('app.name')); - + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/AppointmentScheduled.php b/app/Notifications/AppointmentScheduled.php index 74c062d..947a158 100755 --- a/app/Notifications/AppointmentScheduled.php +++ b/app/Notifications/AppointmentScheduled.php @@ -63,14 +63,14 @@ class AppointmentScheduled extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - Interview scheduled') ->line('An interview has been scheduled for you @ '.$this->appointment->appointmentDate.'.') ->line('With the following details: '.$this->appointment->appointmentDescription) ->line('This meeting will take place @ '.$this->appointment->appointmentLocation.'.') ->action('Sign in', url(route('login'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/ChangedPassword.php b/app/Notifications/ChangedPassword.php index 9c6df1f..9d0eda0 100755 --- a/app/Notifications/ChangedPassword.php +++ b/app/Notifications/ChangedPassword.php @@ -60,13 +60,13 @@ class ChangedPassword extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - Account password changed') ->line('The password for the account registered to this email address has just been changed.') ->line('If this was not you, please contact an administrator immediately.') ->action('Sign in', url(route('login'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/EmailChanged.php b/app/Notifications/EmailChanged.php index 26dbd6c..fa1b5c5 100755 --- a/app/Notifications/EmailChanged.php +++ b/app/Notifications/EmailChanged.php @@ -60,13 +60,13 @@ class EmailChanged extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - Email address changed') ->line('The email address for your account has just been updated.') ->line('If this was not you, please change your password immediately. We recommend you also activate multi-factor authentication.') ->action('Sign in', url(route('login'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/NewAbsenceRequest.php b/app/Notifications/NewAbsenceRequest.php index 51add0b..0169d77 100755 --- a/app/Notifications/NewAbsenceRequest.php +++ b/app/Notifications/NewAbsenceRequest.php @@ -44,13 +44,13 @@ class NewAbsenceRequest extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - new absence request pending review') ->line("A new absence request has just been submitted, scheduled to end {$this->absence->predicted_end}. Please review this request and take the appropriate action(s). The requester will be notified of your decision by email.") ->line("You are receiving this email because you're a site admin.") ->action('Review request', url(route('absences.show', ['absence' => $this->absence->id]))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/NewApplicant.php b/app/Notifications/NewApplicant.php index 70b70dd..821200a 100755 --- a/app/Notifications/NewApplicant.php +++ b/app/Notifications/NewApplicant.php @@ -73,13 +73,13 @@ class NewApplicant extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - New application') ->line('Someone has just applied for a position. Check it out!') ->line('You are receiving this because you\'re a staff member at '.config('app.name').'.') ->action('View Application', url(route('showUserApp', ['application' => $this->application->id]))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } public function toSlack($notifiable) diff --git a/app/Notifications/NewComment.php b/app/Notifications/NewComment.php index 571b5a9..1c22fd7 100755 --- a/app/Notifications/NewComment.php +++ b/app/Notifications/NewComment.php @@ -60,13 +60,13 @@ class NewComment extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - New comment') ->line('Someone has just posted a new comment on an application you follow.') ->line('You\'re receiving this email because you\'ve voted/commented on this application.') ->action('Check it out', url(route('showUserApp', ['application' => $this->application->id]))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/NewContact.php b/app/Notifications/NewContact.php index 2edba6e..d2ba4b0 100755 --- a/app/Notifications/NewContact.php +++ b/app/Notifications/NewContact.php @@ -67,7 +67,7 @@ class NewContact extends Notification 'email', ])) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->line('We\'ve received a new contact form submission in the StaffManagement app center.') ->line('This is what they sent: ') ->line('') @@ -75,7 +75,7 @@ class NewContact extends Notification ->line('') ->line('This message was received from '.$this->message->get('ip').' and submitted by '.$this->message->get('email').'.') ->action('Sign in', url(route('login'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } throw new \InvalidArgumentException('Invalid arguments supplied to NewContact!'); diff --git a/app/Notifications/NewUser.php b/app/Notifications/NewUser.php index 83d99db..cae1583 100755 --- a/app/Notifications/NewUser.php +++ b/app/Notifications/NewUser.php @@ -66,14 +66,14 @@ class NewUser extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - New user') ->line($this->user->name.' has created a new account.') - ->line('This request came from the IP address ' . $this->user->originalIP . '.') + ->line('This request came from the IP address '.$this->user->originalIP.'.') ->line('You are receiving this email because you\'re a site admin, and the app is configured to send new user notifications.') ->action('View user', url(route('showSingleProfile', ['user' => $this->user->id]))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } public function toSlack($notifiable) diff --git a/app/Notifications/UserBanned.php b/app/Notifications/UserBanned.php index cf81d50..7a320e2 100755 --- a/app/Notifications/UserBanned.php +++ b/app/Notifications/UserBanned.php @@ -67,13 +67,13 @@ class UserBanned extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->line('Hello, ') ->line('Moderators have just suspended user '.$this->user->name.' for '.$this->ban->reason) ->line('This ban will remain in effect until '.$this->ban->bannedUntil.'.') ->action('View profile', url(route('showSingleProfile', ['user' => $this->user->id]))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/UserDeletedAccount.php b/app/Notifications/UserDeletedAccount.php index 29fe4f6..2e0096f 100755 --- a/app/Notifications/UserDeletedAccount.php +++ b/app/Notifications/UserDeletedAccount.php @@ -46,13 +46,13 @@ class UserDeletedAccount extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) ->subject(config('app.name').' - someone deleted their account') ->line("The user {$this->deletedEmail} has just deleted their account. You may wish to review the situation.") ->line('You are receiving this email because you\'re a site admin.') ->action('View current users', url(route('registeredPlayerList'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Notifications/VacancyStatusUpdated.php b/app/Notifications/VacancyStatusUpdated.php index d3c1359..e6b6c8c 100755 --- a/app/Notifications/VacancyStatusUpdated.php +++ b/app/Notifications/VacancyStatusUpdated.php @@ -36,7 +36,6 @@ class VacancyStatusUpdated extends Notification implements ShouldQueue protected string $status; - protected Vacancy $vacancy; /** @@ -49,7 +48,7 @@ class VacancyStatusUpdated extends Notification implements ShouldQueue // there's no simpler solution to this for now, but an array works $statusDict = [ 'open' => 'opened', - 'close' => 'closed' + 'close' => 'closed', ]; $this->vacancy = $vacancy; @@ -69,16 +68,15 @@ class VacancyStatusUpdated extends Notification implements ShouldQueue */ public function toMail($notifiable) { - return (new MailMessage) - ->greeting('Hi ' . $notifiable->name . ',') + ->greeting('Hi '.$notifiable->name.',') ->from(config('notification.sender.address'), config('notification.sender.name')) - ->subject(config('app.name').' - Vacancy ' . $this->status) - ->line('The vacancy '.$this->vacancy->vacancyName.', with '.$this->vacancy->vacancyCount.' remaining slots, has just been ' . $this->status . '.') + ->subject(config('app.name').' - Vacancy '.$this->status) + ->line('The vacancy '.$this->vacancy->vacancyName.', with '.$this->vacancy->vacancyCount.' remaining slots, has just been '.$this->status.'.') ->line('Please be aware that this position may be change at any time.') ->line('You are receiving this email because you currently have staff/team member privileges. Depending on your access level, you may not be able to view the list of positions on the backoffice.') ->action('View positions', url(route('showPositions'))) - ->salutation('The team at ' . config('app.name')); + ->salutation('The team at '.config('app.name')); } /** diff --git a/app/Observers/UserObserver.php b/app/Observers/UserObserver.php index 298ac07..388fab4 100755 --- a/app/Observers/UserObserver.php +++ b/app/Observers/UserObserver.php @@ -23,7 +23,6 @@ namespace App\Observers; use App\Exceptions\ProfileAlreadyExistsException; use App\Exceptions\ProfileCreationFailedException; -use App\Profile; use App\Services\ProfileService; use App\User; use Illuminate\Support\Facades\Log; @@ -45,20 +44,15 @@ class UserObserver { $profileService = new ProfileService(); - try - { + try { $profileService->createProfile($user); - } - catch (ProfileAlreadyExistsException $exception) - { + } catch (ProfileAlreadyExistsException $exception) { Log::error('Attempting to create profile that already exists!', [ - 'trace' => $exception->getTrace() + 'trace' => $exception->getTrace(), ]); - } - catch (ProfileCreationFailedException $e) - { + } catch (ProfileCreationFailedException $e) { Log::error('Failed creating a new profile!', [ - 'trace' => $e->getTrace() + 'trace' => $e->getTrace(), ]); } } diff --git a/app/OneoffApplicant.php b/app/OneoffApplicant.php index 9a25c9e..deed501 100755 --- a/app/OneoffApplicant.php +++ b/app/OneoffApplicant.php @@ -14,4 +14,3 @@ class OneoffApplicant extends Model return $this->belongsTo('App\Application', 'id', 'application_id'); } } - diff --git a/app/Policies/AbsencePolicy.php b/app/Policies/AbsencePolicy.php index 7e5c68f..aca7423 100755 --- a/app/Policies/AbsencePolicy.php +++ b/app/Policies/AbsencePolicy.php @@ -3,7 +3,6 @@ namespace App\Policies; use App\Absence; -use App\Response; use App\User; use Illuminate\Auth\Access\HandlesAuthorization; @@ -19,15 +18,13 @@ class AbsencePolicy */ public function viewAny(User $user) { - if ($user->hasPermissionTo('admin.viewAllAbsences')) - { + if ($user->hasPermissionTo('admin.viewAllAbsences')) { return true; } return false; } - public function viewOwn(User $user): bool { if ($user->hasPermissionTo('reviewer.viewAbsence')) { @@ -46,8 +43,7 @@ class AbsencePolicy */ public function view(User $user, Absence $absence) { - if ($user->hasPermissionTo('reviewer.viewAbsence') && $user->is($absence->requester) || $user->hasPermissionTo('admin.manageAbsences')) - { + if ($user->hasPermissionTo('reviewer.viewAbsence') && $user->is($absence->requester) || $user->hasPermissionTo('admin.manageAbsences')) { return true; } @@ -65,29 +61,25 @@ class AbsencePolicy return $user->hasPermissionTo('reviewer.requestAbsence'); } - /** * Determine whether the user can approve the absence request * - * @param User $user - * @param Absence $absence + * @param User $user + * @param Absence $absence * @return bool */ public function approve(User $user, Absence $absence): bool { - if ($user->can('admin.manageAbsences') && $user->isNot($absence->requester)) - { + if ($user->can('admin.manageAbsences') && $user->isNot($absence->requester)) { return true; } return false; } - public function decline(User $user, Absence $absence): bool { - if ($user->can('admin.manageAbsences') && $user->isNot($absence->requester)) - { + if ($user->can('admin.manageAbsences') && $user->isNot($absence->requester)) { return true; } @@ -97,13 +89,13 @@ class AbsencePolicy /** * Determine whether the user can cancel the absence request * - * @param User $user - * @param Absence $absence + * @param User $user + * @param Absence $absence * @return bool */ - public function cancel(User $user, Absence $absence): bool { - - if($user->is($absence->requester) && $user->can('reviewer.withdrawAbsence')) { + public function cancel(User $user, Absence $absence): bool + { + if ($user->is($absence->requester) && $user->can('reviewer.withdrawAbsence')) { return true; } @@ -121,6 +113,4 @@ class AbsencePolicy { return $user->hasPermissionTo('admin.manageAbsences'); } - - } diff --git a/app/Policies/ApiKeyPolicy.php b/app/Policies/ApiKeyPolicy.php index eb728bc..99fed01 100755 --- a/app/Policies/ApiKeyPolicy.php +++ b/app/Policies/ApiKeyPolicy.php @@ -18,13 +18,13 @@ class ApiKeyPolicy */ public function viewAny(User $user) { - if ($user->hasRole('admin')) + if ($user->hasRole('admin')) { return true; + } return false; } - /** * Determine whether the user can create models. * @@ -33,8 +33,9 @@ class ApiKeyPolicy */ public function create(User $user) { - if ($user->hasRole('admin')) + if ($user->hasRole('admin')) { return true; + } return false; } @@ -48,8 +49,9 @@ class ApiKeyPolicy */ public function update(User $user, ApiKey $apiKey) { - if ($user->hasRole('admin')) + if ($user->hasRole('admin')) { return true; + } return false; } @@ -63,10 +65,10 @@ class ApiKeyPolicy */ public function delete(User $user, ApiKey $apiKey) { - if ($user->hasRole('admin')) + if ($user->hasRole('admin')) { return true; + } return false; } - } diff --git a/app/Policies/AppointmentPolicy.php b/app/Policies/AppointmentPolicy.php index 29a5b50..7ad1b34 100755 --- a/app/Policies/AppointmentPolicy.php +++ b/app/Policies/AppointmentPolicy.php @@ -32,7 +32,7 @@ class AppointmentPolicy /** * Determine whether the user can view any models. * - * @param User $user + * @param User $user * @return mixed */ public function viewAny(User $user) @@ -43,8 +43,8 @@ class AppointmentPolicy /** * Determine whether the user can view the model. * - * @param User $user - * @param Appointment $appointment + * @param User $user + * @param Appointment $appointment * @return mixed */ public function view(User $user, Appointment $appointment) @@ -55,7 +55,7 @@ class AppointmentPolicy /** * Determine whether the user can create models. * - * @param User $user + * @param User $user * @return mixed */ public function create(User $user) @@ -66,8 +66,8 @@ class AppointmentPolicy /** * Determine whether the user can update the model. * - * @param User $user - * @param Appointment $appointment + * @param User $user + * @param Appointment $appointment * @return mixed */ public function update(User $user, Appointment $appointment) @@ -78,8 +78,8 @@ class AppointmentPolicy /** * Determine whether the user can delete the model. * - * @param User $user - * @param Appointment $appointment + * @param User $user + * @param Appointment $appointment * @return mixed */ public function delete(User $user, Appointment $appointment) @@ -90,8 +90,8 @@ class AppointmentPolicy /** * Determine whether the user can restore the model. * - * @param User $user - * @param Appointment $appointment + * @param User $user + * @param Appointment $appointment * @return mixed */ public function restore(User $user, Appointment $appointment) @@ -102,8 +102,8 @@ class AppointmentPolicy /** * Determine whether the user can permanently delete the model. * - * @param User $user - * @param Appointment $appointment + * @param User $user + * @param Appointment $appointment * @return mixed */ public function forceDelete(User $user, Appointment $appointment) diff --git a/app/Policies/BanPolicy.php b/app/Policies/BanPolicy.php index 0eaa62e..287ee66 100755 --- a/app/Policies/BanPolicy.php +++ b/app/Policies/BanPolicy.php @@ -57,8 +57,8 @@ class BanPolicy /** * Determine whether the user can create models. * - * @param \App\User $user - * @param User $targetUser + * @param \App\User $user + * @param User $targetUser * @return mixed */ public function create(User $user, User $targetUser) diff --git a/app/Policies/TeamPolicy.php b/app/Policies/TeamPolicy.php index ad135cf..b93fc3e 100755 --- a/app/Policies/TeamPolicy.php +++ b/app/Policies/TeamPolicy.php @@ -37,11 +37,9 @@ class TeamPolicy return $user->isOwnerOfTeam($team) || $user->hasPermissionTo('teams.update'); } - public function invite(User $user, Team $team) { - if (!$team->openJoin && $user->isOwnerOfTeam($team) || !$team->openJoin && $user->hasPermissionTo('teams.invite')) - { + if (! $team->openJoin && $user->isOwnerOfTeam($team) || ! $team->openJoin && $user->hasPermissionTo('teams.invite')) { return true; } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 148fb87..5103ba7 100755 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -21,24 +21,17 @@ namespace App\Providers; -use App\Facades\Options; use App\Application; -use App\Observers\ApplicationObserver; use App\Observers\UserObserver; -use App\Observers\VacancyObserver; use App\User; -use App\Vacancy; use Illuminate\Pagination\Paginator; -use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\View; use Illuminate\Support\ServiceProvider; use Sentry; - class AppServiceProvider extends ServiceProvider { - /** * Register any application services. * @@ -66,18 +59,17 @@ class AppServiceProvider extends ServiceProvider $https = ($this->app->environment() != 'local'); $collect = true; - if(config('app.force_secure') && $this->app->environment() != 'production') + if (config('app.force_secure') && $this->app->environment() != 'production') { $https = true; + } - if (config('app.hide_ips') || config('demo.is_enabled')) - { + if (config('app.hide_ips') || config('demo.is_enabled')) { $collect = false; } // Initialize user observer User::observe(UserObserver::class); - $this->app['request']->server->set('HTTPS', $https); View::share('shouldCollect', $collect); diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 3118a7f..36de47b 100755 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -22,13 +22,11 @@ namespace App\Providers; use App\Absence; -use App\ApiKey; use App\Application; use App\Appointment; use App\Ban; use App\Form; use App\Policies\AbsencePolicy; -use App\Policies\ApiKeyPolicy; use App\Policies\ApplicationPolicy; use App\Policies\AppointmentPolicy; use App\Policies\BanPolicy; @@ -69,7 +67,7 @@ class AuthServiceProvider extends ServiceProvider Appointment::class => AppointmentPolicy::class, Team::class => TeamPolicy::class, TeamFile::class => TeamFilePolicy::class, - Absence::class => AbsencePolicy::class + Absence::class => AbsencePolicy::class, ]; /** @@ -82,25 +80,23 @@ class AuthServiceProvider extends ServiceProvider $this->registerPolicies(); VerifyEmail::toMailUsing(function ($notifiable, $url) { - return (new MailMessage) - ->greeting("Hi {$notifiable->name}! Welcome to " . config('app.name') . ".") + ->greeting("Hi {$notifiable->name}! Welcome to ".config('app.name').'.') ->line('To finish setting up your account, you must verify your email. This is to ensure only real users access our website.') ->line('If you didn\'t sign up for an account, you can safely ignore this email.') ->action('Verify account', $url) - ->salutation('The team at ' . config('app.name')); - + ->salutation('The team at '.config('app.name')); }); - Gate::define('viewLogViewer', function (?User $user){ + Gate::define('viewLogViewer', function (?User $user) { return $user->hasPermissionTo('admin.developertools.use'); }); - Gate::define('downloadLogFile', function (User $user){ - return $user->hasPermissionTo('admin.developertools.use'); + Gate::define('downloadLogFile', function (User $user) { + return $user->hasPermissionTo('admin.developertools.use'); }); - Gate::define('deleteLogFile', function (User $user){ + Gate::define('deleteLogFile', function (User $user) { return $user->hasPermissionTo('admin.developertools.use'); }); } diff --git a/app/Providers/DigitalStorageProvider.php b/app/Providers/DigitalStorageProvider.php index fe594ef..e8db8b3 100755 --- a/app/Providers/DigitalStorageProvider.php +++ b/app/Providers/DigitalStorageProvider.php @@ -2,8 +2,8 @@ namespace App\Providers; -use Illuminate\Support\ServiceProvider; use App; +use Illuminate\Support\ServiceProvider; class DigitalStorageProvider extends ServiceProvider { @@ -24,7 +24,7 @@ class DigitalStorageProvider extends ServiceProvider */ public function boot() { - App::bind('digitalStorageHelperFacadeRoot', function (){ + App::bind('digitalStorageHelperFacadeRoot', function () { return new App\Helpers\DigitalStorageHelper(); }); } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 0bc0112..37720f1 100755 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -25,11 +25,6 @@ use App\Application; use App\Listeners\LogAuthenticationFailure; use App\Listeners\LogAuthenticationSuccess; use App\Listeners\OnUserRegistration; -use App\Observers\ApplicationObserver; -use App\Observers\UserObserver; -use App\Observers\VacancyObserver; -use App\User; -use App\Vacancy; use Illuminate\Auth\Events\Failed; use Illuminate\Auth\Events\Login; use Illuminate\Auth\Events\Registered; diff --git a/app/Providers/JSONProvider.php b/app/Providers/JSONProvider.php index b5ef403..1232aee 100755 --- a/app/Providers/JSONProvider.php +++ b/app/Providers/JSONProvider.php @@ -26,7 +26,7 @@ class JSONProvider extends ServiceProvider public function boot() { App::bind('json', function () { - return new JSON(); + return new JSON(); }); } } diff --git a/app/Services/AbsenceService.php b/app/Services/AbsenceService.php index 91e0710..669aecd 100755 --- a/app/Services/AbsenceService.php +++ b/app/Services/AbsenceService.php @@ -15,29 +15,24 @@ use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Log; -use Spatie\Permission\Models\Role; - class AbsenceService { - /** * Determines whether someone already has an active leave of absence request * - * @param User $user The user to check + * @param User $user The user to check * @return bool Their status */ - public function hasActiveRequest(Authenticatable $user): bool { - + public function hasActiveRequest(Authenticatable $user): bool + { $absences = Absence::where('requesterID', $user->id)->get(); foreach ($absences as $absence) { - // Or we could adjust the query (using a model scope) to only return valid absences; // If there are any, refuse to store more, but this approach also works // A model scope that only returns cancelled, declined and ended absences could also be implemented for future use - if (in_array($absence->getRawOriginal('status'), ['PENDING', 'APPROVED'])) - { + if (in_array($absence->getRawOriginal('status'), ['PENDING', 'APPROVED'])) { return true; } } @@ -47,12 +42,11 @@ class AbsenceService public function createAbsence(Authenticatable $requester, Request $request) { - $absence = Absence::create([ 'requesterID' => $requester->id, 'start' => $request->start_date, 'predicted_end' => $request->predicted_end, - 'available_assist' => $request->available_assist == "on", + 'available_assist' => $request->available_assist == 'on', 'reason' => $request->reason, 'status' => 'PENDING', ]); @@ -65,22 +59,21 @@ class AbsenceService } }); - Log::info('Processing new leave of absence request.', [ 'requesting_user' => $requester->email, 'absenceid' => $absence->id, - 'reason' => $request->reason + 'reason' => $request->reason, ]); return $absence; } - /** * Sets an absence as Approved. * - * @param Absence $absence The absence to approve. + * @param Absence $absence The absence to approve. * @return Absence The approved absence. + * * @throws AbsenceNotActionableException */ public function approveAbsence(Absence $absence) @@ -88,19 +81,19 @@ class AbsenceService Log::info('An absence request has just been approved.', [ 'absenceid' => $absence->id, 'reviewing_admim' => Auth::user()->email, - 'new_status' => 'APPROVED' + 'new_status' => 'APPROVED', ]); $absence->setApproved() ->requester->notify(new AbsenceRequestApproved($absence)); } - /** * Sets an absence as Declined. * - * @param Absence $absence The absence to decline. + * @param Absence $absence The absence to decline. * @return Absence The declined absence. + * * @throws AbsenceNotActionableException */ public function declineAbsence(Absence $absence) @@ -108,26 +101,26 @@ class AbsenceService Log::warning('An absence request has just been declined.', [ 'absenceid' => $absence->id, 'reviewing_admim' => Auth::user()->email, - 'new_status' => 'DECLINED' + 'new_status' => 'DECLINED', ]); $absence->setDeclined() ->requester->notify(new AbsenceRequestDeclined($absence)); } - /** * Sets an absence as Cancelled. * - * @param Absence $absence The absence to cancel. + * @param Absence $absence The absence to cancel. * @return Absence The cancelled absence. + * * @throws AbsenceNotActionableException */ public function cancelAbsence(Absence $absence) { Log::warning('An absence request has just been cancelled (only cancellable by requester).', [ 'absenceid' => $absence->id, - 'new_status' => 'CANCELLED' + 'new_status' => 'CANCELLED', ]); $absence->setCancelled() @@ -137,14 +130,14 @@ class AbsenceService /** * Sets an absence as Ended. * - * @param Absence $absence + * @param Absence $absence * @return bool */ public function endAbsence(Absence $absence) { Log::info('An absence request has just expired.', [ 'absenceid' => $absence->id, - 'new_status' => 'ENDED' + 'new_status' => 'ENDED', ]); $absence->setEnded() @@ -154,7 +147,7 @@ class AbsenceService /** * Removes an absence * - * @param Absence $absence The absence to remove. + * @param Absence $absence The absence to remove. * @return bool Whether the absence was removed. */ public function removeAbsence(Absence $absence): bool @@ -169,20 +162,16 @@ class AbsenceService /** * End all expired absences in the application + * * @return void */ public function endExpired(): void { - foreach (Absence::all() as $absence) - { + foreach (Absence::all() as $absence) { // tell the absence we want to check for cancelability - if (!Carbon::parse($absence->predicted_end)->isFuture() && $absence->isActionable(true)) { + if (! Carbon::parse($absence->predicted_end)->isFuture() && $absence->isActionable(true)) { $this->endAbsence($absence); } } } - - - } - diff --git a/app/Services/AccountSuspensionService.php b/app/Services/AccountSuspensionService.php index 4a9236a..cad6b56 100755 --- a/app/Services/AccountSuspensionService.php +++ b/app/Services/AccountSuspensionService.php @@ -1,5 +1,6 @@ - $target->email, 'suspended_by' => Auth::user()->email, - 'reason' => $reason + 'reason' => $reason, ]); if ($duration > 0) { @@ -40,18 +40,18 @@ class AccountSuspensionService 'reason' => $reason, 'bannedUntil' => ($duration > 0) ? $expiryDate->format('Y-m-d H:i:s') : null, 'authorUserID' => Auth::user()->id, - 'isPermanent' => ($duration == 0) ? true : false + 'isPermanent' => ($duration == 0) ? true : false, ]); } /** * Lifts someone's suspension * - * @param User $user The user to unsuspend + * @param User $user The user to unsuspend */ - public function unsuspend(User $user): void { - - Log::alert("A suspension has just been lifted.", [ + public function unsuspend(User $user): void + { + Log::alert('A suspension has just been lifted.', [ 'target_email' => $user->email, ]); @@ -61,29 +61,27 @@ class AccountSuspensionService /** * Checks whether a user is suspended * - * @param User $user The user to check + * @param User $user The user to check * @return bool Whether the mentioned user is suspended */ - public function isSuspended(User $user): bool { - return !is_null($user->bans); + public function isSuspended(User $user): bool + { + return ! is_null($user->bans); } - - - /** * Sets an administrative lock on a user account. * Used to prevent logins after a deletion process is initiated, but may be used for * other things where a suspension is not necessary/warranted, such as a security breach event. * These locks cannot be overridden manually be administrators. * - * @param User $user The account to lock + * @param User $user The account to lock * @return bool */ public function lockAccount(User $user): bool { Log::alert('User account locked!', [ - 'email' => $user->email + 'email' => $user->email, ]); $user->administratively_locked = 1; @@ -92,17 +90,16 @@ class AccountSuspensionService return $user->save(); } - /** * Unlocks a user account. Reverse of lockAccount(). * - * @param User $user + * @param User $user * @return bool */ public function unlockAccount(User $user): bool { Log::alert('User account unlocked!', [ - 'email' => $user->email + 'email' => $user->email, ]); $user->administratively_locked = 0; @@ -114,25 +111,28 @@ class AccountSuspensionService /** * Checks whether an account is locked * - * @param User $user The user to check + * @param User $user The user to check * @return bool Whether the mentioned account is locked */ - public function isLocked(User $user): bool { + public function isLocked(User $user): bool + { return $user->administratively_locked == 1; } /** * Retrieves the reason for the user's suspension. * - * @param User $user The user account to check + * @param User $user The user account to check * @return string|bool Reason for the suspension, false if not suspended */ - public function getSuspensionReason(User $user): string|bool { + public function getSuspensionReason(User $user): string|bool + { return ($this->isSuspended($user)) ? $user->bans->reason : false; } - public function getSuspensionDuration(User $user): string|null { - if ($this->isSuspended($user) && !is_null($user->bans->bannedUntil)) { + public function getSuspensionDuration(User $user): string|null + { + if ($this->isSuspended($user) && ! is_null($user->bans->bannedUntil)) { return $user->bans->bannedUntil->diffForHumans(); } @@ -149,6 +149,4 @@ class AccountSuspensionService // Unban on the last day, not on the exact time (with Carbon::now()). return (bool) Ban::whereDate('bannedUntil', '=', Carbon::today())->delete(); } - - } diff --git a/app/Services/ApplicationService.php b/app/Services/ApplicationService.php index d5d02cd..b318e9f 100755 --- a/app/Services/ApplicationService.php +++ b/app/Services/ApplicationService.php @@ -1,26 +1,24 @@ first(); if (is_null(Auth::user()->dob)) { - throw new InvalidAgeException("User must have added their age to apply for this vacancy."); - } elseif(Carbon::parse(Auth::user()->dob)->age < $firstVacancy->requiredAge) { + throw new InvalidAgeException('User must have added their age to apply for this vacancy.'); + } elseif (Carbon::parse(Auth::user()->dob)->age < $firstVacancy->requiredAge) { throw new IncompatibleAgeException("Sorry, you must be {$firstVacancy->requiredAge} or older to apply to {$firstVacancy->vacancyName}."); } - - if ($firstVacancy->requiresDiscord && !Auth::user()->hasDiscordConnection()) { + if ($firstVacancy->requiresDiscord && ! Auth::user()->hasDiscordConnection()) { throw new DiscordAccountRequiredException('A discord account is required beyond this point.'); } - if (!$vacancyWithForm->isEmpty() && $firstVacancy->vacancyCount !== 0 && $firstVacancy->vacancyStatus == 'OPEN') { + if (! $vacancyWithForm->isEmpty() && $firstVacancy->vacancyCount !== 0 && $firstVacancy->vacancyStatus == 'OPEN') { return view('dashboard.application-rendering.apply') ->with([ 'vacancy' => $vacancyWithForm->first(), 'preprocessedForm' => json_decode($vacancyWithForm->first()->forms->formStructure, true), ]); } else { - throw new ApplicationNotFoundException(__('The application you\'re looking for could not be found or it is currently unavailable.'), 404); - } } @@ -72,14 +67,11 @@ class ApplicationService $vacancy = Vacancy::with('forms')->where('vacancySlug', $vacancySlug)->get(); if ($vacancy->isEmpty()) { - throw new VacancyNotFoundException('This vacancy doesn\'t exist; Please use the proper buttons to apply to one.', 404); - } if ($vacancy->first()->vacancyCount == 0 || $vacancy->first()->vacancyStatus !== 'OPEN') { - - throw new UnavailableApplicationException("This application is unavailable."); + throw new UnavailableApplicationException('This application is unavailable.'); } Log::info('Processing new application!'); @@ -87,10 +79,9 @@ class ApplicationService $formStructure = json_decode($vacancy->first()->forms->formStructure, true); $responseValidation = ContextAwareValidator::getResponseValidator($formData, $formStructure); - Log::info('Built response & validator structure!'); - if (!$responseValidation->get('validator')->fails()) { + if (! $responseValidation->get('validator')->fails()) { $response = Response::create([ 'responseFormID' => $vacancy->first()->forms->id, 'associatedVacancyID' => $vacancy->first()->id, // Since a form can be used by multiple vacancies, we can only know which specific vacancy this response ties to by using a vacancy ID @@ -99,7 +90,7 @@ class ApplicationService Log::info('Registered form response!', [ 'applicant' => $applicant->name, - 'vacancy' => $vacancy->first()->vacancyName + 'vacancy' => $vacancy->first()->vacancyName, ]); $application = Application::create([ @@ -110,7 +101,7 @@ class ApplicationService Log::info('Submitted an application!', [ 'responseID' => $response->id, - 'applicant' => $applicant->name + 'applicant' => $applicant->name, ]); User::whereHas('roles', function ($q) { @@ -122,10 +113,9 @@ class ApplicationService $application->user->notify(new ApplicationConfirmed($application)); return true; - } - Log::warning('Application form for ' . $applicant->name . ' contained errors, resetting!'); + Log::warning('Application form for '.$applicant->name.' contained errors, resetting!'); throw new IncompleteApplicationException('There are one or more errors in your application. Please make sure none of your fields are empty, since they are all required.'); } @@ -136,12 +126,12 @@ class ApplicationService case 'deny': event(new ApplicationDeniedEvent($application)); - $message = __("Application denied successfully."); + $message = __('Application denied successfully.'); break; case 'interview': - Log::info(' Moved application ID ' . $application->id . 'to interview stage!'); + Log::info(' Moved application ID '.$application->id.'to interview stage!'); $message = __('Application moved to interview stage!'); $application->setStatus('STAGE_INTERVIEW'); @@ -150,7 +140,7 @@ class ApplicationService break; default: - throw new \LogicException("Wrong status parameter. Please notify a developer."); + throw new \LogicException('Wrong status parameter. Please notify a developer.'); } return $message; @@ -164,7 +154,6 @@ class ApplicationService return $application->delete(); } - public function canVote($votes): bool { $allvotes = collect([]); @@ -175,6 +164,6 @@ class ApplicationService } } - return !(($allvotes->count() == 1)); + return ! (($allvotes->count() == 1)); } } diff --git a/app/Services/AppointmentService.php b/app/Services/AppointmentService.php index 9e976f4..83a6037 100755 --- a/app/Services/AppointmentService.php +++ b/app/Services/AppointmentService.php @@ -1,13 +1,10 @@ user->notify(new AppointmentScheduled($appointment)); - return true; } - /** * Cancels an appointment for the provided application. * - * @param Application $application The target application. - * @param string $reason The reason for cancelling the appointment. + * @param Application $application The target application. + * @param string $reason The reason for cancelling the appointment. + * * @throws \Exception Thrown when there's no appointment to cancel */ public function deleteAppointment(Application $application, string $reason): bool { - if (!empty($application->appointment)) - { + if (! empty($application->appointment)) { $application->user->notify(new AppointmentCancelled($application, Carbon::parse($application->appointment->appointmentDate), $reason)); $application->appointment->delete(); @@ -77,14 +72,13 @@ class AppointmentService Log::info('An interview appointment has just been cancelled.', [ 'actor' => Auth::user()->name, 'applicant' => $application->user->name, - 'reason' => $reason + 'reason' => $reason, ]); return true; } throw new \Exception("This application doesn't have an appointment!"); - } /** @@ -97,22 +91,17 @@ class AppointmentService */ public function updateAppointment(Application $application, $status, $updateApplication = true) { - if ($status == 'SCHEDULED' || $status == 'concluded') - { + if ($status == 'SCHEDULED' || $status == 'concluded') { $application->appointment->appointmentStatus = strtoupper($status); $application->appointment->save(); - if ($updateApplication) - { + if ($updateApplication) { $application->setStatus('STAGE_PEERAPPROVAL'); $application->user->notify(new AppointmentFinished($application->appointment)); } + } else { + throw new InvalidAppointmentStatusException('Invalid appointment status!'); } - else - { - throw new InvalidAppointmentStatusException("Invalid appointment status!"); - } - } /** @@ -122,5 +111,4 @@ class AppointmentService { return $this->allowedPlatforms; } - } diff --git a/app/Services/CommentService.php b/app/Services/CommentService.php index 545d3d5..fbcf12c 100755 --- a/app/Services/CommentService.php +++ b/app/Services/CommentService.php @@ -1,17 +1,15 @@ Auth::user()->id, 'applicationID' => $application->id, @@ -23,5 +21,4 @@ class CommentService { return $comment->delete(); } - } diff --git a/app/Services/ConfigurationService.php b/app/Services/ConfigurationService.php index 249a24d..fecea6f 100755 --- a/app/Services/ConfigurationService.php +++ b/app/Services/ConfigurationService.php @@ -1,28 +1,21 @@ $option) { try { - Log::debug('Going through option '.$optionName); if (Options::optionExists($optionName)) { Log::debug('Option exists, updating to new values', [ @@ -31,9 +24,7 @@ class ConfigurationService ]); Options::changeOption($optionName, $option); } - } catch (\Exception $ex) { - Log::error('Unable to update options!', [ 'msg' => $ex->getMessage(), 'trace' => $ex->getTraceAsString(), @@ -49,27 +40,26 @@ class ConfigurationService * Saves the chosen game integration * * @throws InvalidGamePreferenceException + * * @returns bool */ public function saveGameIntegration($gamePreference): bool { - // TODO: Find solution to dynamically support games $supportedGames = [ 'RUST', 'MINECRAFT', 'SE', - 'GMOD' + 'GMOD', ]; - if (!is_null($gamePreference) && in_array($gamePreference, $supportedGames)) - { + if (! is_null($gamePreference) && in_array($gamePreference, $supportedGames)) { Options::changeOption('currentGame', $gamePreference); + return true; } - throw new InvalidGamePreferenceException("Unsupported game " . $gamePreference); + throw new InvalidGamePreferenceException('Unsupported game '.$gamePreference); } - } diff --git a/app/Services/ContactService.php b/app/Services/ContactService.php index 86c7938..c3ea637 100755 --- a/app/Services/ContactService.php +++ b/app/Services/ContactService.php @@ -1,9 +1,7 @@ post(config('services.discord.base_url') . '/oauth2/token/revoke', [ + $req = Http::asForm()->post(config('services.discord.base_url').'/oauth2/token/revoke', [ 'client_id' => config('services.discord.client_id'), 'client_secret' => config('services.discord.client_secret'), 'token' => $user->discord_token, ])->throw(); - - $user->discord_token = null; $user->discord_user_id = null; $user->discord_refresh_token = null; @@ -37,6 +35,4 @@ class DiscordService return $req->ok(); } - - } diff --git a/app/Services/FormManagementService.php b/app/Services/FormManagementService.php index 0a59544..9c4846e 100755 --- a/app/Services/FormManagementService.php +++ b/app/Services/FormManagementService.php @@ -1,6 +1,5 @@ 'ACTIVE', ] ); + return true; } + return $contextValidation->get('validator')->errors()->getMessages(); } - public function deleteForm(Form $form) { - + public function deleteForm(Form $form) + { $deletable = true; if (! is_null($form->vacancies) && $form->vacancies->count() !== 0 || ! is_null($form->responses)) { @@ -44,19 +44,16 @@ class FormManagementService } if ($deletable) { - $form->delete(); + return true; - } else { - throw new FormHasConstraintsException(__('You cannot delete this form because it\'s tied to one or more applications and ranks, or because it doesn\'t exist.')); - } } - public function updateForm(Form $form, $fields) { - + public function updateForm(Form $form, $fields) + { $contextValidation = ContextAwareValidator::getValidator($fields, true); if (! $contextValidation->get('validator')->fails()) { @@ -67,10 +64,8 @@ class FormManagementService $form->save(); return $form; - } else { return $contextValidation->get('validator')->errors()->getMessages(); } } - } diff --git a/app/Services/MeetingNoteService.php b/app/Services/MeetingNoteService.php index e1136e9..e8256ab 100755 --- a/app/Services/MeetingNoteService.php +++ b/app/Services/MeetingNoteService.php @@ -1,9 +1,7 @@ load('appointment'); @@ -26,11 +25,8 @@ class MeetingNoteService $application->appointment->save(); return true; - } else { throw new InvalidAppointmentException('There\'s no appointment to save notes to!'); } - } - } diff --git a/app/Services/ProfileService.php b/app/Services/ProfileService.php index 3aa4b97..43fc124 100755 --- a/app/Services/ProfileService.php +++ b/app/Services/ProfileService.php @@ -1,33 +1,29 @@ profile)) { - $profile = Profile::create([ 'profileShortBio' => 'Write a one-liner about you here!', @@ -42,7 +38,7 @@ class ProfileService } Log::info('Created profile for new user', [ - 'userid' => $targetUser->id + 'userid' => $targetUser->id, ]); return $profile; @@ -56,7 +52,8 @@ class ProfileService * * @throws ProfileNotFoundException */ - public function updateProfile($userID, Request $request) { + public function updateProfile($userID, Request $request) + { $profile = User::find($userID)->profile; $social = []; @@ -85,23 +82,22 @@ class ProfileService return $profile->save(); } - throw new ProfileNotFoundException("This profile does not exist."); + throw new ProfileNotFoundException('This profile does not exist.'); } /** * Delete specified user's profile * - * @param User $targetUser + * @param User $targetUser * @return bool + * * @throws ProfileNotFoundException */ public function deleteProfile(User $targetUser): bool { - - if (!is_null($targetUser->profile)) { - + if (! is_null($targetUser->profile)) { Log::alert('Deleted user profile', [ - 'userid' => $targetUser->id + 'userid' => $targetUser->id, ]); return $targetUser->profile->delete(); @@ -109,5 +105,4 @@ class ProfileService throw new ProfileNotFoundException(__('Attempting to delete non-existant profile!')); } - } diff --git a/app/Services/SecuritySettingsService.php b/app/Services/SecuritySettingsService.php index 1f84477..b170b0f 100755 --- a/app/Services/SecuritySettingsService.php +++ b/app/Services/SecuritySettingsService.php @@ -1,44 +1,38 @@ $policy + 'new_value' => $policy, ]); - } - else - { + } else { Log::debug('[WARN] Ignoring bogus policy', [ 'avaliable' => $validPolicies, - 'given' => $policy + 'given' => $policy, ]); } @@ -48,7 +42,5 @@ class SecuritySettingsService Options::changeOption('requireGameLicense', $options['requirePMC']); return true; - } - } diff --git a/app/Services/TeamFileService.php b/app/Services/TeamFileService.php index c94719c..dcbbde8 100755 --- a/app/Services/TeamFileService.php +++ b/app/Services/TeamFileService.php @@ -1,19 +1,15 @@ store('uploads'); $originalFileName = $upload->getClientOriginalName(); $originalFileExtension = $upload->extension(); @@ -27,16 +23,13 @@ class TeamFileService 'description' => $description, 'fs_location' => $file, 'extension' => $originalFileExtension, - 'size' => $originalFileSize + 'size' => $originalFileSize, ]); - if ($fileEntry && !is_bool($file)) - { - return $fileEntry; + if ($fileEntry && ! is_bool($file)) { + return $fileEntry; } - throw new FileUploadException("There was an unknown error whilst trying to upload your file."); - + throw new FileUploadException('There was an unknown error whilst trying to upload your file.'); } - } diff --git a/app/Services/TeamService.php b/app/Services/TeamService.php index 9e7c8c0..d85c405 100755 --- a/app/Services/TeamService.php +++ b/app/Services/TeamService.php @@ -1,9 +1,7 @@ $teamName, 'owner_id' => $ownerID, @@ -40,7 +37,6 @@ class TeamService public function updateTeam(Team $team, $teamDescription, $joinType): bool { - $team->description = $teamDescription; $team->openJoin = $joinType; @@ -55,7 +51,6 @@ class TeamService */ public function inviteUser(Team $team, $userID): bool { - $user = User::findOrFail($userID); if (! $team->openJoin) { @@ -63,6 +58,7 @@ class TeamService Teamwork::inviteToTeam($user, $team, function (TeamInvite $invite) use ($user) { Mail::to($user)->send(new InviteToTeam($invite)); }); + return true; } else { throw new UserAlreadyInvitedException('This user has already been invited.'); @@ -70,20 +66,20 @@ class TeamService } else { throw new PublicTeamInviteException('You can\'t invite users to public teams.'); } - } /** * Accepts or denies a user invite * - * @param Authenticatable $user + * @param Authenticatable $user * @param $action * @param $token * @return bool True on success or exception on failure + * * @throws InvalidInviteException Thrown when the invite code / url is invalid */ - public function processInvite(Authenticatable $user, $action, $token): bool { - + public function processInvite(Authenticatable $user, $action, $token): bool + { switch ($action) { case 'accept': @@ -91,9 +87,7 @@ class TeamService if ($invite && $invite->user->is($user)) { Teamwork::acceptInvite($invite); - } else { - throw new InvalidInviteException('Invalid or expired invite URL.'); } @@ -104,11 +98,8 @@ class TeamService $invite = Teamwork::getInviteFromDenyToken($token); if ($invite && $invite->user->is($user)) { - Teamwork::denyInvite($invite); - } else { - throw new InvalidInviteException('Invalid or expired invite URL.'); } @@ -119,18 +110,15 @@ class TeamService } return true; - } - /** - * @param Team $team + * @param Team $team * @param $associatedVacancies * @return string The success message, exception/bool if error */ public function updateVacancies(Team $team, $associatedVacancies): string { - // P.S. To future developers // This method gave me a lot of trouble lol. It's hard to write code when you're half asleep. // There may be an n+1 query in the view and I don't think there's a way to avoid that without writing a lot of extra code. @@ -160,6 +148,7 @@ class TeamService } else { $team->vacancies()->attach($requestVacancies); } + return 'Assignments changed successfully.'; } } diff --git a/app/Services/VacancyApplicationService.php b/app/Services/VacancyApplicationService.php index c1fbddc..777032f 100755 --- a/app/Services/VacancyApplicationService.php +++ b/app/Services/VacancyApplicationService.php @@ -29,7 +29,7 @@ class VacancyApplicationService /** * Finds all applications associated with $model. * - * @param Vacancy $model The model you want to search through. + * @param Vacancy $model The model you want to search through. * @return Illuminate\Support\Collection A collection of applications */ public function findApplications(Vacancy $model) diff --git a/app/Team.php b/app/Team.php index 7705421..77c372b 100755 --- a/app/Team.php +++ b/app/Team.php @@ -37,8 +37,6 @@ class Team extends TeamworkTeam return $this->belongsToMany('App\Vacancy', 'team_has_vacancy'); } - - public function files() { return $this->hasMany('App\TeamFile', 'team_id'); diff --git a/app/TeamFile.php b/app/TeamFile.php index 8a5fedb..db6c780 100755 --- a/app/TeamFile.php +++ b/app/TeamFile.php @@ -11,7 +11,6 @@ class TeamFile extends Model { use HasFactory, UsedByTeams; - protected $fillable = [ 'uploaded_by', 'team_id', @@ -20,7 +19,7 @@ class TeamFile extends Model 'extension', 'size', 'caption', - 'description' + 'description', ]; public function uploader() @@ -33,7 +32,6 @@ class TeamFile extends Model return $this->belongsTo('App\Team'); } - public function getSizeAttribute($value) { return DigitalStorageHelper::setValue($value)->formatBytes(2, true); diff --git a/app/Traits/Cancellable.php b/app/Traits/Cancellable.php index 1139202..86e8352 100755 --- a/app/Traits/Cancellable.php +++ b/app/Traits/Cancellable.php @@ -37,7 +37,7 @@ trait Cancellable } Log::debug('Cancellable: current channels list', [ - 'channels' => $channels + 'channels' => $channels, ]); return $channels; diff --git a/app/Traits/DisablesFeatures.php b/app/Traits/DisablesFeatures.php index 7c8ea26..9da833a 100755 --- a/app/Traits/DisablesFeatures.php +++ b/app/Traits/DisablesFeatures.php @@ -6,7 +6,6 @@ use Illuminate\Http\RedirectResponse; trait DisablesFeatures { - /** * Checks if demo mode is active. If so, it stops any more logic from running. * @@ -19,7 +18,7 @@ trait DisablesFeatures ->back() ->with('error', __('This feature is disabled')); } + return null; } - } diff --git a/app/Traits/HandlesAccountDeletion.php b/app/Traits/HandlesAccountDeletion.php index 054f260..9664f37 100755 --- a/app/Traits/HandlesAccountDeletion.php +++ b/app/Traits/HandlesAccountDeletion.php @@ -35,18 +35,16 @@ use Illuminate\Support\Facades\URL; trait HandlesAccountDeletion { - /** * Starts the user account deletion process. * - * @param AccountSuspensionService $suspensionService - * @param UserDeleteRequest $request + * @param AccountSuspensionService $suspensionService + * @param UserDeleteRequest $request * @return \Illuminate\Http\RedirectResponse */ public function userDelete(AccountSuspensionService $suspensionService, UserDeleteRequest $request) { - if (config('demo.is_enabled')) - { + if (config('demo.is_enabled')) { return redirect() ->back() ->with('error', 'This feature is disabled'); @@ -58,7 +56,7 @@ trait HandlesAccountDeletion ), 'cancelURL' => URL::temporarySignedRoute( 'processDeleteConfirmation', now()->addDays(7), ['accountID' => $request->user()->id, 'action' => 'cancel'] - ) + ), ]; Mail::to($request->user()) @@ -69,33 +67,31 @@ trait HandlesAccountDeletion Auth::logout(); $request->session()->flash('success', __('Please check your email to finish deleting your account.')); + return redirect()->to('/'); } - /** * Dispatches the correct jobs and events to delete the specified user account * - * @param Request $request - * @param AccountSuspensionService $suspensionService + * @param Request $request + * @param AccountSuspensionService $suspensionService * @param $accountID * @param $action * @return \Illuminate\Http\RedirectResponse|void */ public function processDeleteConfirmation(Request $request, AccountSuspensionService $suspensionService, $accountID, $action) { - if (config('demo.is_enabled') || !$request->hasValidSignature()) - { - abort(403); + if (config('demo.is_enabled') || ! $request->hasValidSignature()) { + abort(403); } // It's almost impossible for this to fail, unless the model has already been deleted by someone else, because: // The request URL can't be tampered with and the request can't be initiated without a valid account in the first place $account = User::find($accountID); - if (!is_null($account)) - { - if (!$suspensionService->isLocked($account)) { + if (! is_null($account)) { + if (! $suspensionService->isLocked($account)) { abort(403); } @@ -125,13 +121,11 @@ trait HandlesAccountDeletion return redirect() ->route('login'); - } Log::error("Cannot delete account that doesn't exist!", [ - 'validSignature' => $request->hasValidSignature() + 'validSignature' => $request->hasValidSignature(), ]); abort(400); - } } diff --git a/app/UUID/UUID.php b/app/UUID/UUID.php index 9a7ab32..40c20c3 100755 --- a/app/UUID/UUID.php +++ b/app/UUID/UUID.php @@ -44,7 +44,6 @@ class UUID // Note: Caching could simply be assigning the username to it's UUID, however, to make this work, we'd need to loop over all cache items, which would be slighly ineffective public function toUsername(string $uuid) { - $shortUUID = substr($uuid, 0, 8); $username = Cache::remember('uuid_'.$shortUUID, now()->addDays(30), function () use ($shortUUID, $uuid) { $response = json_decode(Http::get(trim(config('general.urls.mojang.session')).'/session/minecraft/profile/'.$uuid)->body(), true); diff --git a/app/User.php b/app/User.php index c0c9210..c216e24 100755 --- a/app/User.php +++ b/app/User.php @@ -21,18 +21,10 @@ namespace App; -use App\Services\AccountSuspensionService; -use App\Traits\HandlesAccountTokens; use Illuminate\Contracts\Auth\MustVerifyEmail; -use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; -use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Crypt; -use Illuminate\Support\Facades\Log; -use Illuminate\Support\Facades\View; use Mpociot\Teamwork\Traits\UserHasTeams; use Spatie\Permission\Traits\HasRoles; @@ -58,7 +50,7 @@ class User extends Authenticatable implements MustVerifyEmail 'currentIp', 'discord_user_id', 'discord_token', - 'discord_refresh_token' + 'discord_refresh_token', ]; /** @@ -67,7 +59,7 @@ class User extends Authenticatable implements MustVerifyEmail * @var array */ protected $hidden = [ - 'password', 'remember_token', 'discord_token', 'discord_refresh_token' + 'password', 'remember_token', 'discord_token', 'discord_refresh_token', ]; /** @@ -78,7 +70,7 @@ class User extends Authenticatable implements MustVerifyEmail protected $casts = [ 'email_verified_at' => 'datetime', 'discord_token' => 'encrypted', - 'discord_refresh_token' => 'encrypted' + 'discord_refresh_token' => 'encrypted', ]; // RELATIONSHIPS @@ -91,7 +83,6 @@ class User extends Authenticatable implements MustVerifyEmail public function votes() { return $this->hasMany('App\Vote', 'userID', 'id'); - } public function profile() @@ -119,8 +110,8 @@ class User extends Authenticatable implements MustVerifyEmail return $this->hasMany('App\Absence', 'requesterID'); } - - public function isEligible(): bool { + public function isEligible(): bool + { $lastApplication = Application::where('applicantUserID', $this->getAttribute('id'))->latest()->first(); if (is_null($lastApplication)) { @@ -134,15 +125,16 @@ class User extends Authenticatable implements MustVerifyEmail return false; } - - public function isVerified(): bool { - return !is_null($this->email_verified_at); + public function isVerified(): bool + { + return ! is_null($this->email_verified_at); } /** * Checks if user is staff * * @deprecated This method is being replaced by a better way of checking permissions, rather than checking for group name. + * * @return bool */ public function isStaffMember(): bool @@ -168,12 +160,9 @@ class User extends Authenticatable implements MustVerifyEmail */ public function hasTeam($team): bool { - if ($team instanceof Team || is_int($team)) - { + if ($team instanceof Team || is_int($team)) { return $this->teams->contains($team); - } - else - { + } else { /** * In PHP 8, we can just use union types and let PHP enforce this for us. */ @@ -186,18 +175,18 @@ class User extends Authenticatable implements MustVerifyEmail * * @return bool */ - public function hasDiscordConnection(): bool { - return !is_null($this->discord_token) && !is_null($this->discord_refresh_token); + public function hasDiscordConnection(): bool + { + return ! is_null($this->discord_token) && ! is_null($this->discord_refresh_token); } - /** * Check if user has a password * * @return bool */ - public function hasPassword(): bool { - return !is_null($this->password); + public function hasPassword(): bool + { + return ! is_null($this->password); } - } diff --git a/app/Vacancy.php b/app/Vacancy.php index 4bf8d27..f975b74 100755 --- a/app/Vacancy.php +++ b/app/Vacancy.php @@ -45,14 +45,14 @@ class Vacancy extends Model 'vacancySlug', 'team_id', 'requiresDiscord', - 'requiredAge' + 'requiredAge', ]; /** * Get the HTML variant of the vacancyFullDescription attribute. * - * @param string $value The original value + * @param string $value The original value * @return string */ public function getVacancyFullDescriptionAttribute($value) @@ -94,15 +94,14 @@ class Vacancy extends Model public function decrease() { - if ($this->vacancyCount !== 0) - { + if ($this->vacancyCount !== 0) { $this->update([ - 'vacancyCount' => $this->vacancyCount - 1 + 'vacancyCount' => $this->vacancyCount - 1, ]); Log::info('Vacancies: Decreased vacancy slots by one.', [ 'vacancyId' => $this->id, - 'vacancyName' => $this->vacancyName + 'vacancyName' => $this->vacancyName, ]); } } @@ -110,7 +109,7 @@ class Vacancy extends Model /** * Check if the Modal is attached to the $checkingTeam Model. * - * @param Team $checkingTeam The mdoel you want to check against + * @param Team $checkingTeam The mdoel you want to check against * @return bool Whether the models are attached */ public function hasTeam(Team $checkingTeam): bool diff --git a/app/View/Components/AccountStatus.php b/app/View/Components/AccountStatus.php index 1180ce6..d821b4d 100755 --- a/app/View/Components/AccountStatus.php +++ b/app/View/Components/AccountStatus.php @@ -2,17 +2,26 @@ namespace App\View\Components; -use App\User; use Illuminate\View\Component; class AccountStatus extends Component { public bool - $isVerified, - $isSuspended, - $isLocked, - $has2FA, - $hasDiscord, + $isVerified; + + public bool + $isSuspended; + + public bool + $isLocked; + + public bool + $has2FA; + + public bool + $hasDiscord; + + public bool $hasPassword; /** diff --git a/app/View/Components/Alert.php b/app/View/Components/Alert.php index a7586df..a99fd32 100755 --- a/app/View/Components/Alert.php +++ b/app/View/Components/Alert.php @@ -25,19 +25,21 @@ use Illuminate\View\Component; class Alert extends Component { - public - $alertType, - $extraStyling, - $title, - $icon; + public $alertType; + + public $extraStyling; + + public $title; + + public $icon; /** * Create a new component instance. * - * @param string $alertType The color the alert should have. - * @param string $title The alert's title - * @param string $icon The alert's icon, placed before the title - * @param string $extraStyling Any extra CSS classes to add + * @param string $alertType The color the alert should have. + * @param string $title The alert's title + * @param string $icon The alert's icon, placed before the title + * @param string $extraStyling Any extra CSS classes to add */ public function __construct(string $alertType, string $title = '', string $icon = '', string $extraStyling = '') { diff --git a/app/View/Components/Button.php b/app/View/Components/Button.php index 71761c1..8ac7d61 100755 --- a/app/View/Components/Button.php +++ b/app/View/Components/Button.php @@ -7,13 +7,27 @@ use Illuminate\View\Component; class Button extends Component { public string - $type, - $icon, - $link, - $target, - $size, - $color, - $disabled, + $type; + + public string + $icon; + + public string + $link; + + public string + $target; + + public string + $size; + + public string + $color; + + public string + $disabled; + + public string $id; public function __construct($id, $color, $type = 'button', $disabled = false, $size = '', $target = '', $link = '', $icon = '') diff --git a/composer.json b/composer.json index fa67569..e215817 100755 --- a/composer.json +++ b/composer.json @@ -40,6 +40,7 @@ "barryvdh/laravel-debugbar": "^3.3", "barryvdh/laravel-ide-helper": "^2.12", "fakerphp/faker": "^1.19", + "laravel/pint": "^1.4", "laravel/sail": "^1.15", "mockery/mockery": "^1.3.1", "nunomaduro/collision": "^6.1", diff --git a/composer.lock b/composer.lock index a693842..8f68182 100755 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "04e34fbbef2bf9b12382145e6a9f4fb4", + "content-hash": "9ebe2207f617199a090bd8d2c19e1597", "packages": [ { "name": "almasaeed2010/adminlte", @@ -9740,6 +9740,72 @@ ], "time": "2022-01-07T12:00:00+00:00" }, + { + "name": "laravel/pint", + "version": "v1.4.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/pint.git", + "reference": "0e7ffdb0af871be10d798e234772ea5d4020ae4a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/pint/zipball/0e7ffdb0af871be10d798e234772ea5d4020ae4a", + "reference": "0e7ffdb0af871be10d798e234772ea5d4020ae4a", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-mbstring": "*", + "ext-tokenizer": "*", + "ext-xml": "*", + "php": "^8.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "~3.13.1", + "illuminate/view": "^9.32.0", + "laravel-zero/framework": "^9.2.0", + "mockery/mockery": "^1.5.1", + "nunomaduro/larastan": "^2.2.0", + "nunomaduro/termwind": "^1.14.0", + "pestphp/pest": "^1.22.1" + }, + "bin": [ + "builds/pint" + ], + "type": "project", + "autoload": { + "psr-4": { + "App\\": "app/", + "Database\\Seeders\\": "database/seeders/", + "Database\\Factories\\": "database/factories/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "An opinionated code formatter for PHP.", + "homepage": "https://laravel.com", + "keywords": [ + "format", + "formatter", + "lint", + "linter", + "php" + ], + "support": { + "issues": "https://github.com/laravel/pint/issues", + "source": "https://github.com/laravel/pint" + }, + "time": "2023-01-10T20:03:42+00:00" + }, { "name": "laravel/sail", "version": "v1.15.4", diff --git a/config/adminlte.php b/config/adminlte.php index d9042b0..43842db 100755 --- a/config/adminlte.php +++ b/config/adminlte.php @@ -235,7 +235,7 @@ return [ [ 'text' => 'Dashboard', 'icon' => 'fas fa-tachometer-alt', - 'url' => '/dashboard' + 'url' => '/dashboard', ], [ 'header' => 'h_applications', @@ -243,7 +243,7 @@ return [ ], [ 'text' => 'm_my_applications', - 'icon' => 'fas fa-fw fa-list-ul', + 'icon' => 'fas fa-fw fa-list-ul', 'can' => 'applications.view.own', 'submenu' => [ [ @@ -269,7 +269,7 @@ return [ ], [ 'header' => 'Human Resources', - 'can' => 'reviewer.requestAbsence' + 'can' => 'reviewer.requestAbsence', ], [ 'text' => 'Absence Management', @@ -280,13 +280,13 @@ return [ 'text' => 'New request', 'icon' => 'fas fa-plus', 'can' => 'reviewer.requestAbsence', - 'route' => 'absences.create' + 'route' => 'absences.create', ], [ 'text' => 'My requests', 'icon' => 'fas fa-business-time', 'can' => 'reviewer.viewAbsence', - 'route' => 'showUserAbsences' + 'route' => 'showUserAbsences', ], ], @@ -295,7 +295,7 @@ return [ 'text' => 'Absence requests', 'icon' => 'fas fa-address-card', 'can' => 'admin.manageAbsences', - 'route' => 'absences.index' + 'route' => 'absences.index', ], [ 'header' => 'h_app_management', @@ -317,15 +317,15 @@ return [ 'text' => 'Available Teams', 'icon' => 'fas fa-clipboard', 'url' => 'teams', - 'can' => 'teams.view' + 'can' => 'teams.view', ], [ 'text' => 'Files', 'icon' => 'fas fa-file-alt', 'url' => 'team/files', - 'can' => 'teams.view' + 'can' => 'teams.view', ], - ] + ], ], [ 'header' => 'h_admin', @@ -583,24 +583,24 @@ return [ 'location' => '/css/authpages.css', ], ], - ], - [ - 'name' => 'BootstrapMultiselectDropdown', - 'active' => true, - 'files' => [ - [ - 'type' => 'js', - 'asset' => 'false', - 'location' => 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js', - ], - [ - 'type' => 'css', - 'asset' => false, - 'location' => 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css', - ], + ], + [ + 'name' => 'BootstrapMultiselectDropdown', + 'active' => true, + 'files' => [ + [ + 'type' => 'js', + 'asset' => 'false', + 'location' => 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js', + ], + [ + 'type' => 'css', + 'asset' => false, + 'location' => 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css', ], - ], + + ], [ 'name' => 'BootstrapToggleButton', 'active' => true, @@ -624,14 +624,14 @@ return [ [ 'type' => 'css', 'asset' => false, - 'location' => 'https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css' + 'location' => 'https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css', ], [ 'type' => 'js', 'asset' => false, - 'location' => 'https://cdn.jsdelivr.net/npm/flatpickr' - ] - ] + 'location' => 'https://cdn.jsdelivr.net/npm/flatpickr', + ], + ], ], [ 'name' => 'Pusher', @@ -640,9 +640,9 @@ return [ [ 'type' => 'js', 'asset' => false, - 'location' => 'https://js.pusher.com/beams/1.0/push-notifications-cdn.js' - ] - ] - ] + 'location' => 'https://js.pusher.com/beams/1.0/push-notifications-cdn.js', + ], + ], + ], ], ]; diff --git a/config/app.php b/config/app.php index 4fa2d1d..12b310d 100755 --- a/config/app.php +++ b/config/app.php @@ -46,9 +46,6 @@ return [ */ 'sitehomepage' => env('APP_SITEHOMEPAGE', 'https://google.com'), - - - /* |-------------------------------------------------------------------------- | Application Version @@ -77,7 +74,6 @@ return [ */ 'force_secure' => env('NONPROD_FORCE_SECURE', false), - /* |-------------------------------------------------------------------------- | IP address anonymity @@ -94,7 +90,6 @@ return [ */ 'hide_ips' => env('HIDE_IPS'), - /* |-------------------------------------------------------------------------- | Legal documents & source code @@ -351,7 +346,7 @@ return [ 'ContextAwareValidator' => App\Facades\ContextAwareValidation::class, 'Settings' => App\Facades\Options::class, 'JSON' => App\Facades\JSON::class, - 'DiscordOauth' => App\Facades\Discord::class + 'DiscordOauth' => App\Facades\Discord::class, ], diff --git a/config/customization.php b/config/customization.php index 26b502a..e8cba53 100755 --- a/config/customization.php +++ b/config/customization.php @@ -2,6 +2,6 @@ return [ - 'authbanner' => env('APP_AUTH_BANNER') + 'authbanner' => env('APP_AUTH_BANNER'), ]; diff --git a/config/debugbar.php b/config/debugbar.php index 87b003e..22d03ff 100755 --- a/config/debugbar.php +++ b/config/debugbar.php @@ -52,11 +52,11 @@ return [ | */ 'storage' => [ - 'enabled' => true, - 'driver' => 'file', // redis, file, pdo, custom - 'path' => storage_path('debugbar'), // For file driver + 'enabled' => true, + 'driver' => 'file', // redis, file, pdo, custom + 'path' => storage_path('debugbar'), // For file driver 'connection' => null, // Leave null for default connection (Redis/PDO) - 'provider' => '', // Instance of StorageInterface for custom driver + 'provider' => '', // Instance of StorageInterface for custom driver ], /* @@ -121,29 +121,29 @@ return [ */ 'collectors' => [ - 'phpinfo' => true, // Php version - 'messages' => true, // Messages - 'time' => true, // Time Datalogger - 'memory' => true, // Memory usage - 'exceptions' => true, // Exception displayer - 'log' => true, // Logs from Monolog (merged in messages if enabled) - 'db' => true, // Show database (PDO) queries and bindings - 'views' => true, // Views with their data - 'route' => true, // Current route information - 'auth' => false, // Display Laravel authentication status - 'gate' => true, // Display Laravel Gate checks - 'session' => true, // Display session data + 'phpinfo' => true, // Php version + 'messages' => true, // Messages + 'time' => true, // Time Datalogger + 'memory' => true, // Memory usage + 'exceptions' => true, // Exception displayer + 'log' => true, // Logs from Monolog (merged in messages if enabled) + 'db' => true, // Show database (PDO) queries and bindings + 'views' => true, // Views with their data + 'route' => true, // Current route information + 'auth' => false, // Display Laravel authentication status + 'gate' => true, // Display Laravel Gate checks + 'session' => true, // Display session data 'symfony_request' => true, // Only one can be enabled.. - 'mail' => true, // Catch mail messages - 'laravel' => false, // Laravel version and environment - 'events' => false, // All events fired + 'mail' => true, // Catch mail messages + 'laravel' => false, // Laravel version and environment + 'events' => false, // All events fired 'default_request' => false, // Regular or special Symfony request logger - 'logs' => false, // Add the latest log messages - 'files' => false, // Show the included files - 'config' => false, // Display config settings - 'cache' => false, // Display cache events - 'models' => true, // Display models - 'livewire' => true, // Display Livewire (when available) + 'logs' => false, // Add the latest log messages + 'files' => false, // Show the included files + 'config' => false, // Display config settings + 'cache' => false, // Display cache events + 'models' => true, // Display models + 'livewire' => true, // Display Livewire (when available) ], /* @@ -160,16 +160,16 @@ return [ 'show_name' => true, // Also show the users name/email in the debugbar ], 'db' => [ - 'with_params' => true, // Render SQL with the parameters substituted - 'backtrace' => true, // Use a backtrace to find the origin of the query in your files. + 'with_params' => true, // Render SQL with the parameters substituted + 'backtrace' => true, // Use a backtrace to find the origin of the query in your files. 'backtrace_exclude_paths' => [], // Paths to exclude from backtrace. (in addition to defaults) - 'timeline' => false, // Add the queries to the timeline + 'timeline' => false, // Add the queries to the timeline 'explain' => [ // Show EXPLAIN output on queries 'enabled' => false, 'types' => ['SELECT'], // Deprecated setting, is always only SELECT ], - 'hints' => false, // Show hints for common mistakes - 'show_copy' => false, // Show copy button next to the query + 'hints' => false, // Show hints for common mistakes + 'show_copy' => false, // Show copy button next to the query ], 'mail' => [ 'full_log' => false, diff --git a/config/demo.php b/config/demo.php index a9824c3..e7cd14d 100755 --- a/config/demo.php +++ b/config/demo.php @@ -2,6 +2,6 @@ return [ - 'is_enabled' => env('DEMO_MODE', false) + 'is_enabled' => env('DEMO_MODE', false), ]; diff --git a/config/google2fa.php b/config/google2fa.php index 6cd127d..84ed032 100755 --- a/config/google2fa.php +++ b/config/google2fa.php @@ -78,9 +78,9 @@ return [ * One Time Password error message. */ 'error_messages' => [ - 'wrong_otp' => 'Your one time code was incorrect.', + 'wrong_otp' => 'Your one time code was incorrect.', 'cannot_be_empty' => 'The one time code cannot be empty.', - 'unknown' => 'An unknown error has occurred. Please try again.', + 'unknown' => 'An unknown error has occurred. Please try again.', ], /* diff --git a/config/laravellocalization.php b/config/laravellocalization.php index f4cf111..e77bc7d 100755 --- a/config/laravellocalization.php +++ b/config/laravellocalization.php @@ -25,9 +25,9 @@ return [ // These are sorted by the native name, which is the order you might show them in a language selector. // Regional languages are sorted by their base language, so "British English" sorts as "English, British" 'supportedLocales' => [ - 'pt' => ['name' => 'Portuguese', 'script' => 'Latn', 'native' => 'Português', 'regional' => 'pt_PT'], - 'en' => ['name' => 'English', 'script' => 'Latn', 'native' => 'English', 'regional' => 'en_GB'], - 'pt-br' => ['name' => 'Brazillian Portuguese', 'script' => 'Latn', 'native' => 'Português do Brasil', 'regional' =>'pt_BR'] + 'pt' => ['name' => 'Portuguese', 'script' => 'Latn', 'native' => 'Português', 'regional' => 'pt_PT'], + 'en' => ['name' => 'English', 'script' => 'Latn', 'native' => 'English', 'regional' => 'en_GB'], + 'pt-br' => ['name' => 'Brazillian Portuguese', 'script' => 'Latn', 'native' => 'Português do Brasil', 'regional' => 'pt_BR'], ], // Requires middleware `LaravelSessionRedirect.php`. diff --git a/config/localizator.php b/config/localizator.php index 9dbf321..37ba524 100755 --- a/config/localizator.php +++ b/config/localizator.php @@ -17,35 +17,35 @@ return [ * Translations strings as key. * They are stored in JSON file for each locale. */ - 'json' => true, + 'json' => true, ], /** * Search criteria for files. */ - 'search' => [ + 'search' => [ /** * Directories which should be looked inside. */ - 'dirs' => ['resources/views', 'app/Http/Controllers'], + 'dirs' => ['resources/views', 'app/Http/Controllers'], /** * Patterns by which files should be queried. * The values can be a regular expression, glob, or just a string. */ - 'patterns' => ['*.php'], + 'patterns' => ['*.php'], /** * Functions that the strings will be extracted from. * Add here any custom defined functions. * NOTE: The translation string should always be the first argument. */ - 'functions' => ['__', 'trans_choice', 'trans', '@lang'] + 'functions' => ['__', 'trans_choice', 'trans', '@lang'], ], /** * Should the localize command sort extracted strings alphabetically? */ - 'sort' => true, + 'sort' => true, ]; diff --git a/config/markdown.php b/config/markdown.php index 718e37a..29c663c 100755 --- a/config/markdown.php +++ b/config/markdown.php @@ -67,7 +67,7 @@ return [ 'renderer' => [ 'block_separator' => "\n", 'inner_separator' => "\n", - 'soft_break' => "\n", + 'soft_break' => "\n", ], /* @@ -88,10 +88,10 @@ return [ */ 'commonmark' => [ - 'enable_em' => true, - 'enable_strong' => true, - 'use_asterisk' => true, - 'use_underscore' => true, + 'enable_em' => true, + 'enable_strong' => true, + 'use_asterisk' => true, + 'use_underscore' => true, 'unordered_list_markers' => ['-', '+', '*'], ], @@ -150,7 +150,7 @@ return [ 'slug_normalizer' => [ 'max_length' => 255, - 'unique' => 'document', + 'unique' => 'document', ], ]; diff --git a/config/services.php b/config/services.php index 87a0eaf..aeb132a 100755 --- a/config/services.php +++ b/config/services.php @@ -45,10 +45,10 @@ return [ 'staff_home_roles' => env('DISCORD_HOME_GUILD_ROLES'), // optional - 'allow_gif_avatars' => (bool)env('DISCORD_AVATAR_GIF', true), + 'allow_gif_avatars' => (bool) env('DISCORD_AVATAR_GIF', true), 'avatar_default_extension' => env('DISCORD_EXTENSION_DEFAULT', 'jpg'), // only pick from jpg, png, webp 'home_guild' => env('DISCORD_HOME_GUILD'), - 'staff_guild' => env('DISCORD_STAFF_GUILD', null) + 'staff_guild' => env('DISCORD_STAFF_GUILD', null), ], 'mailgun' => [ @@ -73,6 +73,6 @@ return [ ], 'cpanel' => [ - 'api_token' => env('CPANEL_API_TOKEN', null) - ] + 'api_token' => env('CPANEL_API_TOKEN', null), + ], ]; diff --git a/database/migrations/2014_04_02_193005_create_translations_table.php b/database/migrations/2014_04_02_193005_create_translations_table.php index 053d09c..2006800 100644 --- a/database/migrations/2014_04_02_193005_create_translations_table.php +++ b/database/migrations/2014_04_02_193005_create_translations_table.php @@ -1,20 +1,19 @@ collation = 'utf8mb4_bin'; +class CreateTranslationsTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('ltm_translations', function (Blueprint $table) { + $table->collation = 'utf8mb4_bin'; $table->bigIncrements('id'); $table->integer('status')->default(0); $table->string('locale'); @@ -23,16 +22,15 @@ class CreateTranslationsTable extends Migration { $table->text('value')->nullable(); $table->timestamps(); }); - } + } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { Schema::drop('ltm_translations'); - } - + } } diff --git a/database/migrations/2020_05_29_234431_create_permission_tables.php b/database/migrations/2020_05_29_234431_create_permission_tables.php index e790941..b9b26ea 100755 --- a/database/migrations/2020_05_29_234431_create_permission_tables.php +++ b/database/migrations/2020_05_29_234431_create_permission_tables.php @@ -66,7 +66,7 @@ class CreatePermissionTables extends Migration ->onDelete('cascade'); $table->primary(['permission_id', $columnNames['model_morph_key'], 'model_type'], - 'model_has_permissions_permission_model_type_primary'); + 'model_has_permissions_permission_model_type_primary'); }); Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames) { @@ -82,7 +82,7 @@ class CreatePermissionTables extends Migration ->onDelete('cascade'); $table->primary(['role_id', $columnNames['model_morph_key'], 'model_type'], - 'model_has_roles_role_model_type_primary'); + 'model_has_roles_role_model_type_primary'); }); Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames) { diff --git a/database/migrations/2021_01_01_201604_oneoff_applicants.php b/database/migrations/2021_01_01_201604_oneoff_applicants.php index 192100d..f10613e 100755 --- a/database/migrations/2021_01_01_201604_oneoff_applicants.php +++ b/database/migrations/2021_01_01_201604_oneoff_applicants.php @@ -13,8 +13,7 @@ class OneoffApplicants extends Migration */ public function up() { - Schema::create('oneoff_applicants', function(Blueprint $table){ - + Schema::create('oneoff_applicants', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); @@ -24,10 +23,9 @@ class OneoffApplicants extends Migration $table->foreign('application_id') ->references('id') ->on('applications') - + ->onDelete('cascade') ->onUpdate('cascade'); - }); } diff --git a/database/migrations/2021_07_20_094139_change_bans_table.php b/database/migrations/2021_07_20_094139_change_bans_table.php index 422ba10..73d9f04 100755 --- a/database/migrations/2021_07_20_094139_change_bans_table.php +++ b/database/migrations/2021_07_20_094139_change_bans_table.php @@ -14,10 +14,8 @@ class ChangeBansTable extends Migration public function up() { Schema::table('bans', function (Blueprint $table) { - $table->dropColumn('userAgent'); $table->boolean('isPermanent')->default(false); - }); } @@ -29,8 +27,8 @@ class ChangeBansTable extends Migration public function down() { Schema::table('bans', function (Blueprint $table) { - $table->dropColumn('isPermanent'); - $table->string('userAgent')->after('bannedUntil'); + $table->dropColumn('isPermanent'); + $table->string('userAgent')->after('bannedUntil'); }); } } diff --git a/database/migrations/2021_10_26_000036_add_linked_accounts_table.php b/database/migrations/2021_10_26_000036_add_linked_accounts_table.php index 712b9fb..f44f1d3 100755 --- a/database/migrations/2021_10_26_000036_add_linked_accounts_table.php +++ b/database/migrations/2021_10_26_000036_add_linked_accounts_table.php @@ -1,8 +1,6 @@ string('password')->nullable()->change(); // social login requires no pw (still required upon normal reg) $table->string('registrationIp')->nullable()->change(); diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 527e506..b1884f2 100755 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -20,7 +20,6 @@ namespace Database\Seeders; - use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder diff --git a/database/seeders/DefaultOptionsSeeder.php b/database/seeders/DefaultOptionsSeeder.php index b4ed1ce..bafb01f 100755 --- a/database/seeders/DefaultOptionsSeeder.php +++ b/database/seeders/DefaultOptionsSeeder.php @@ -19,7 +19,6 @@ * along with Raspberry Staff Manager. If not, see . */ - namespace Database\Seeders; use App\Facades\Options; @@ -41,7 +40,6 @@ class DefaultOptionsSeeder extends Seeder Options::setOption('notify_applicant_approved', true, 'Notify when an applicant is approved', 'notifications'); // done Options::setOption('notify_vacancystatus_change', false, 'Notify when a vacancy\'s status changes', 'notifications'); // done - // added in 0.6.2 Options::setOption('pw_security_policy', 'low', 'Describes the current password security policy.', 'app_security'); Options::setOption('graceperiod', 7, '2FA Grace Period', 'app_security'); @@ -51,10 +49,8 @@ class DefaultOptionsSeeder extends Seeder Options::setOption('requireGameLicense', true, 'Defines whether people need to validate their game license', 'app_security'); Options::setOption('currentGame', 'MINECRAFT', 'Defines what game we\'re working with', 'app_integration'); - Options::setOption('enable_slack_notifications', true, 'Enable slack notifications', 'notifications'); Options::setOption('enable_email_notifications', true, 'Enable e-mail notifications', 'notifications'); - } } diff --git a/database/seeders/NewPermissions.php b/database/seeders/NewPermissions.php index 6c3f118..56055ae 100755 --- a/database/seeders/NewPermissions.php +++ b/database/seeders/NewPermissions.php @@ -34,7 +34,7 @@ class NewPermissions extends Seeder public function run() { $developer = Role::create([ - 'name' => 'developer' + 'name' => 'developer', ]); $admin = Role::where('name', 'admin')->first(); @@ -45,7 +45,5 @@ class NewPermissions extends Seeder $developer->givePermissionTo('admin.developertools.use'); $admin->givePermissionTo('admin.settings.view'); $admin->givePermissionTo('admin.settings.edit'); - - } } diff --git a/database/seeders/PermissionSeeder.php b/database/seeders/PermissionSeeder.php index d88be6e..3d4cd78 100755 --- a/database/seeders/PermissionSeeder.php +++ b/database/seeders/PermissionSeeder.php @@ -38,28 +38,28 @@ class PermissionSeeder extends Seeder // $user = Role::create( [ - 'name' => 'user' + 'name' => 'user', ] ); $staff = Role::create([ - 'name' => 'staff' + 'name' => 'staff', ]); $reviewer = Role::create( [ - 'name' => 'reviewer' + 'name' => 'reviewer', ] ); $hiringManager = Role::create( [ - 'name' => 'hiringManager' + 'name' => 'hiringManager', ] ); $admin = Role::create([ - 'name' => 'admin' + 'name' => 'admin', ]); // Spatie wildcard permissions (same concept of MC permissions) @@ -101,15 +101,14 @@ class PermissionSeeder extends Seeder 'admin.developertools.use', ]; - foreach ($permissions as $permission) - { + foreach ($permissions as $permission) { Permission::create(['name' => $permission]); } $user->givePermissionTo([ 'applications.submit', 'applications.view.own', - 'profiles.view.others' + 'profiles.view.others', ]); $staff->givePermissionTo([ @@ -121,7 +120,7 @@ class PermissionSeeder extends Seeder // Able to view applications and vote on them once they reach the right stage, but not approve applications up to said stage $reviewer->givePermissionTo([ 'applications.view.all', - 'applications.vote' + 'applications.vote', ]); $hiringManager->givePermissionTo('admin.viewAllAbsences', 'admin.manageAbsences', 'appointments.*', 'applications.*', 'admin.hiring.*'); diff --git a/database/seeders/TeamSeeder.php b/database/seeders/TeamSeeder.php index ddbc45f..b6f6605 100755 --- a/database/seeders/TeamSeeder.php +++ b/database/seeders/TeamSeeder.php @@ -22,13 +22,11 @@ namespace Database\Seeders; use Illuminate\Database\Seeder; -use Illuminate\Support\Collection; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role; class TeamSeeder extends Seeder { - /** * Run the database seeds. * @@ -36,49 +34,43 @@ class TeamSeeder extends Seeder */ public function run() { - $teamUserPermissions = [ + $teamUserPermissions = [ - 'teams.files.view', - 'teams.files.upload', - 'teams.files.download', - 'teams.files.delete', - ]; + 'teams.files.view', + 'teams.files.upload', + 'teams.files.download', + 'teams.files.delete', + ]; - // Some of these perms also check whether the user is a member or owner to determine access to resources. - $teamPermissions = [ + // Some of these perms also check whether the user is a member or owner to determine access to resources. + $teamPermissions = [ - 'teams.view', - 'teams.create', - 'teams.update', - 'teams.invite' - ]; + 'teams.view', + 'teams.create', + 'teams.update', + 'teams.invite', + ]; $admin = Role::where('name', 'admin')->first(); $reviewer = Role::where('name', 'reviewer')->first(); - foreach($teamPermissions as $permission) - { - foreach ($teamUserPermissions as $userPermission) - { - $permCheck = Permission::where('name', $permission)->get()->all(); + foreach ($teamPermissions as $permission) { + foreach ($teamUserPermissions as $userPermission) { + $permCheck = Permission::where('name', $permission)->get()->all(); - if (empty($permCheck)) - { - Permission::create(['name' => $permission]); - } + if (empty($permCheck)) { + Permission::create(['name' => $permission]); + } - $userPermCheck = Permission::where('name', $userPermission)->get()->all(); + $userPermCheck = Permission::where('name', $userPermission)->get()->all(); - if (empty($userPermCheck)) - { - Permission::create(['name' => $userPermission]); - } - } - } + if (empty($userPermCheck)) { + Permission::create(['name' => $userPermission]); + } + } + } $admin->givePermissionTo($teamPermissions); $reviewer->givePermissionTo($teamUserPermissions); - - } } diff --git a/database/seeders/UserSeeder.php b/database/seeders/UserSeeder.php index 6e833dd..27d3f0d 100755 --- a/database/seeders/UserSeeder.php +++ b/database/seeders/UserSeeder.php @@ -20,7 +20,6 @@ namespace Database\Seeders; -use App\Profile; use App\User; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Hash; @@ -34,7 +33,6 @@ class UserSeeder extends Seeder */ public function run() { - $ghostAccount = User::create([ 'uuid' => 'b741345057274a519144881927be0290', // Ghost 'name' => 'Ghost (deleted account)', @@ -43,7 +41,7 @@ class UserSeeder extends Seeder 'username' => 'ghost', 'registrationIp' => '0.0.0.0', 'currentIp' => '0.0.0.0', - 'password' => 'locked' + 'password' => 'locked', ])->assignRole('user'); // There can't be role-less users $admin = User::create(([ @@ -54,7 +52,7 @@ class UserSeeder extends Seeder 'username' => 'admin', 'registrationIp' => '0.0.0.0', 'currentIp' => '0.0.0.0', - 'password' => Hash::make('admin') + 'password' => Hash::make('admin'), ]))->assignRole('user', 'reviewer', 'hiringManager', 'admin'); $users = User::factory() @@ -64,6 +62,5 @@ class UserSeeder extends Seeder foreach ($users as $user) { $user->assignRole('user'); } - } } diff --git a/routes/api.php b/routes/api.php index 0d3e50a..c7471e0 100755 --- a/routes/api.php +++ b/routes/api.php @@ -20,7 +20,6 @@ */ use App\Http\Controllers\ApplicationController; -use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; /* @@ -34,21 +33,15 @@ use Illuminate\Support\Facades\Route; | */ -Route::middleware(['api'])->group(function (){ - - +Route::middleware(['api'])->group(function () { Route::group(['prefix' => 'applications'], function () { - Route::get('/', [ApplicationController::class, 'showAllApps']); Route::get('view/{application}', [ApplicationController::class, 'showUserApp']); Route::post('apply/{vacancySlug}', [ApplicationController::class, 'saveApplicationAnswers']); Route::patch('update/{application}/{newStatus}', [ApplicationController::class, 'updateApplicationStatus']); Route::delete('delete/{application}', [ApplicationController::class, 'delete']); - }); Route::group(['prefix' => 'vacancies'], function () { - }); - }); diff --git a/routes/web.php b/routes/web.php index d1b9003..0ca0148 100755 --- a/routes/web.php +++ b/routes/web.php @@ -29,18 +29,17 @@ use App\Http\Controllers\DashboardController; use App\Http\Controllers\DevToolsController; use App\Http\Controllers\FormController; use App\Http\Controllers\HomeController; +use App\Http\Controllers\OptionsController; use App\Http\Controllers\ProfileController; +use App\Http\Controllers\SecuritySettingsController; use App\Http\Controllers\TeamController; use App\Http\Controllers\TeamFileController; use App\Http\Controllers\UserController; use App\Http\Controllers\VacancyController; use App\Http\Controllers\VoteController; -use App\Http\Controllers\OptionsController; -use App\Http\Controllers\SecuritySettingsController; use Illuminate\Support\Facades\Route; use Mcamara\LaravelLocalization\Facades\LaravelLocalization; - /* |-------------------------------------------------------------------------- | Web Routes @@ -53,34 +52,30 @@ use Mcamara\LaravelLocalization\Facades\LaravelLocalization; */ Route::get('/uptime', function () { - return response()->json([ 'app' => config('app.name'), 'status' => 'up', 'version' => '0.7.2', 'meta' => [ 'demo_enabled' => config('demo.is_enabled'), - ] + ], ]); - })->name('uptime'); Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['localeSessionRedirect', 'localizationRedirect', 'localeViewPath']], function () { Route::group(['prefix' => 'auth', 'middleware' => ['usernameUUID']], function () { Auth::routes([ - 'verify' => true + 'verify' => true, ]); Route::post('/twofa/authenticate', [TwofaController::class, 'verify2FA']) ->name('verify2FA'); - Route::get('/redirect/discord', [DiscordController::class, 'discordRedirect']) ->name('discordRedirect'); Route::get('/callback/discord', [DiscordController::class, 'discordCallback']) ->name('discordCallback'); - }); Route::get('/', [HomeController::class, 'index']) @@ -94,11 +89,7 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo ->name('discord-apply'); Route::group(['middleware' => ['auth', 'forcelogout', 'passwordexpiration', '2fa', 'verified']], function () { - - - - Route::group(['middleware' => ['passwordredirect']], function(){ - + Route::group(['middleware' => ['passwordredirect']], function () { Route::get('/dashboard', [DashboardController::class, 'index']) ->name('dashboard') ->middleware('eligibility'); @@ -117,8 +108,6 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::get('teams/invites/{action}/{token}', [TeamController::class, 'processInviteAction']) ->name('processInvite'); - - Route::get('team/files', [TeamFileController::class, 'index']) ->name('showTeamFiles'); @@ -130,7 +119,6 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::get('team/files/{teamFile}/download', [TeamFileController::class, 'download']) ->name('downloadTeamFile'); - }); Route::group(['prefix' => '/applications', 'middleware' => ['passwordredirect']], function () { @@ -159,7 +147,6 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::get('/staff/all', [ApplicationController::class, 'showAllApps']) ->name('allApplications'); - Route::post('{application}/staff/vote', [VoteController::class, 'vote']) ->name('voteApplication'); }); @@ -185,7 +172,6 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo // Further locking down the profile section by adding the middleware to everything but the required routes Route::group(['prefix' => '/profile'], function () { - Route::get('/settings', [ProfileController::class, 'showProfile']) ->name('showProfileSettings') ->middleware('passwordredirect'); @@ -206,15 +192,12 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo ->name('deleteProfile') ->middleware('passwordredirect'); - Route::get('/settings/account', [UserController::class, 'showAccount']) ->name('showAccountSettings'); - Route::patch('/settings/account/change-password', [UserController::class, 'changePassword']) ->name('changePassword'); - Route::patch('/settings/account/add-password', [UserController::class, 'setPassword']) ->name('addPassword'); Route::patch('/settings/account/unlink-oauth', [UserController::class, 'unlinkDiscordAccount']) @@ -222,8 +205,6 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::patch('settings/account/add-age', [UserController::class, 'addDob']) ->name('add-dob'); - - Route::patch('/settings/account/change-email', [UserController::class, 'changeEmail']) ->name('changeEmail') ->middleware('passwordredirect'); @@ -246,7 +227,6 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo }); Route::group(['prefix' => '/hr', 'middleware' => ['passwordredirect']], function () { - Route::get('users', [UserController::class, 'showUsers']) ->name('registeredPlayerList'); @@ -256,12 +236,9 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::patch('staff-members/terminate/{user}', [UserController::class, 'terminate']) ->name('terminateStaffMember'); - - Route::resource('absences', AbsenceController::class); Route::controller(AbsenceController::class)->group(function () { - Route::get('my-absences', 'showUserAbsences') ->name('showUserAbsences'); @@ -273,16 +250,13 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::patch('absences/{absence}/cancel', 'cancelAbsence') ->name('cancelAbsence'); - }); - }); Route::group(['prefix' => 'admin', 'middleware' => ['passwordredirect']], function () { Route::get('settings', [OptionsController::class, 'index']) ->name('showSettings'); - Route::post('settings/save', [OptionsController::class, 'saveSettings']) ->name('saveSettings'); @@ -292,7 +266,6 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::patch('settings/game/update', [OptionsController::class, 'saveGameIntegration']) ->name('saveGameIntegration'); - Route::post('accounts/suspend/{user}', [UserController::class, 'suspend']) ->name('banUser'); @@ -343,7 +316,6 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::get('forms', [FormController::class, 'index']) ->name('showForms'); - Route::get('forms/preview/{form}', [FormController::class, 'preview']) ->name('previewForm'); @@ -353,13 +325,10 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::patch('forms/update/{form}', [FormController::class, 'update']) ->name('updateForm'); - Route::group(['prefix' => 'developers'], function () { - Route::get('/', [DevToolsController::class, 'index']) ->name('devTools'); - Route::post('/applications/force-approval', [DevToolsController::class, 'forceApprovalEvent']) ->name('devForceApprovalEvent'); @@ -374,9 +343,7 @@ Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['lo Route::delete('/absences/purge-expired', [DevToolsController::class, 'endAbsencesNow']) ->name('devPurgeExpiredAbsences'); - }); - }); }); });