From 70208d2157e46d96604fadf2113c49f782ade20d Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 5 Jan 2023 17:01:42 +0000 Subject: [PATCH] Apply Laravel coding style Shift automatically applies the Laravel coding style - which uses the PSR-12 coding style as a base with some minor additions. You may customize the code style applied by configuring [Pint](https://laravel.com/docs/pint), [PHP CS Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer), or [PHP CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer) for your project root. For more information on customizing the code style applied by Shift, [watch this short video](https://laravelshift.com/videos/shift-code-style). --- app/Classes/Pterodactyl.php | 263 +++-- app/Classes/Settings/Invoices.php | 25 +- app/Classes/Settings/Language.php | 27 +- app/Classes/Settings/Misc.php | 61 +- app/Classes/Settings/Payments.php | 49 +- app/Classes/Settings/System.php | 124 +-- app/Console/Commands/ChargeCreditsCommand.php | 18 +- .../Commands/ImportUsersFromPteroCommand.php | 40 +- app/Console/Commands/MakeUserCommand.php | 17 +- app/Console/Commands/notify.php | 3 +- app/Console/Commands/update.php | 26 +- app/Console/Kernel.php | 6 +- app/Events/UserUpdateCreditsEvent.php | 6 +- .../Admin/ActivityLogController.php | 15 +- .../Admin/ApplicationApiController.php | 43 +- .../Controllers/Admin/InvoiceController.php | 20 +- .../Controllers/Admin/OverViewController.php | 82 +- .../Controllers/Admin/PaymentController.php | 224 ++-- .../Controllers/Admin/ProductController.php | 119 +-- .../Controllers/Admin/ServerController.php | 96 +- .../Controllers/Admin/SettingsController.php | 8 +- .../Admin/ShopProductController.php | 90 +- .../Admin/UsefulLinkController.php | 40 +- app/Http/Controllers/Admin/UserController.php | 155 +-- .../Controllers/Admin/VoucherController.php | 109 +- .../Api/NotificationController.php | 69 +- app/Http/Controllers/Api/ServerController.php | 17 +- app/Http/Controllers/Api/UserController.php | 152 +-- .../Controllers/Api/VoucherController.php | 27 +- .../Auth/ForgotPasswordController.php | 5 - app/Http/Controllers/Auth/LoginController.php | 9 +- .../Controllers/Auth/RegisterController.php | 67 +- .../Controllers/Auth/SocialiteController.php | 54 +- app/Http/Controllers/HomeController.php | 59 +- .../Moderation/TicketsController.php | 166 +-- .../Controllers/NotificationController.php | 13 +- app/Http/Controllers/PartnerController.php | 109 +- app/Http/Controllers/ProductController.php | 43 +- app/Http/Controllers/ProfileController.php | 69 +- app/Http/Controllers/ServerController.php | 137 +-- app/Http/Controllers/StoreController.php | 21 +- app/Http/Controllers/TicketsController.php | 128 +-- .../Controllers/TranslationController.php | 7 +- app/Http/Kernel.php | 4 +- app/Http/Middleware/ApiAuthToken.php | 13 +- app/Http/Middleware/CheckSuspended.php | 1 + app/Http/Middleware/GlobalNames.php | 8 +- app/Http/Middleware/LastSeen.php | 11 +- app/Http/Middleware/SetLocale.php | 17 +- app/Http/Middleware/VerifyCsrfToken.php | 2 +- app/Http/Middleware/isAdmin.php | 4 +- app/Http/Middleware/isMod.php | 4 +- app/Listeners/UnsuspendServers.php | 8 +- app/Listeners/Verified.php | 4 +- app/Models/ApplicationApi.php | 5 +- app/Models/DiscordUser.php | 32 +- app/Models/Egg.php | 13 +- app/Models/Invoice.php | 3 +- app/Models/Location.php | 23 +- app/Models/Nest.php | 21 +- app/Models/Node.php | 22 +- app/Models/PartnerDiscount.php | 23 +- app/Models/Payment.php | 6 +- app/Models/Product.php | 13 +- app/Models/Server.php | 30 +- app/Models/Settings.php | 7 +- app/Models/ShopProduct.php | 27 +- app/Models/Ticket.php | 26 +- app/Models/TicketBlacklist.php | 8 +- app/Models/TicketCategory.php | 12 +- app/Models/TicketComment.php | 28 +- app/Models/UsefulLink.php | 2 +- app/Models/User.php | 29 +- app/Models/Voucher.php | 23 +- .../ConfirmPaymentNotification.php | 9 +- app/Notifications/DynamicNotification.php | 16 +- app/Notifications/InvoiceNotification.php | 25 +- app/Notifications/ReferralNotification.php | 21 +- app/Notifications/ServerCreationError.php | 15 +- .../ServersSuspendedNotification.php | 18 +- .../Ticket/Admin/AdminCreateNotification.php | 15 +- .../Ticket/Admin/AdminReplyNotification.php | 18 +- .../Ticket/User/CreateNotification.php | 12 +- .../Ticket/User/ReplyNotification.php | 20 +- app/Notifications/WelcomeMessage.php | 45 +- app/Providers/AppServiceProvider.php | 19 +- app/Providers/AuthServiceProvider.php | 1 - app/Providers/EventServiceProvider.php | 2 +- app/Providers/RouteServiceProvider.php | 1 - config/app.php | 10 +- config/currency_codes.php | 2 +- config/filesystems.php | 1 - config/invoices.php | 18 +- config/recaptcha.php | 65 +- config/services.php | 4 +- config/trustedproxy.php | 2 +- database/factories/ApplicationApiFactory.php | 2 +- database/factories/DiscordUserFactory.php | 2 +- database/factories/PaymentFactory.php | 6 +- database/factories/ProductFactory.php | 8 +- database/factories/ServerFactory.php | 4 +- database/factories/VoucherFactory.php | 11 +- .../2014_10_12_000000_create_users_table.php | 1 + ...02_08_190205_create_activity_log_table.php | 4 +- ...021_02_16_162655_create_payments_table.php | 12 +- ...4_11_190944_create_discord_users_table.php | 1 - ..._08_164658_create_configurations_table.php | 1 + ...06_09_213306_create_useful_links_table.php | 1 - ..._090026_update_price_to_payments_table.php | 2 +- ...6_add__currency_code_to_payments_table.php | 2 +- ...21_11_05_071456_add_tax_to_paymentlogs.php | 4 +- ..._12_15_120346_update_to_payments_table.php | 3 +- ...28_203515_rename_paypal_products_table.php | 1 - ..._05_144858_rename_configurations_table.php | 3 +- ...22_05_30_085900_rename_credits_product.php | 4 +- .../2022_06_02_081655_referral_code.php | 27 +- ...2022_06_02_091921_table-user-referrals.php | 5 +- .../2022_07_12_051152_decimals-in-price.php | 2 +- ...2022_08_01_170819_create_tickets_table.php | 6 +- ...1_171633_create_ticketcategories_table.php | 29 +- ..._01_181607_create_ticketcomments_table.php | 6 +- ...1_151039_create_ticket_blacklist_table.php | 2 +- ..._202109_create_partner_discounts_table.php | 2 +- .../2022_11_29_075851_email_verify_d_b.php | 1 - database/seeders/DatabaseSeeder.php | 1 - database/seeders/ExampleItemsSeeder.php | 5 +- .../seeders/Seeds/ApplicationApiSeeder.php | 2 +- database/seeders/Seeds/ProductSeeder.php | 6 +- database/seeders/Seeds/SettingsSeeder.php | 457 +++++---- database/seeders/Seeds/UsefulLinksSeeder.php | 8 +- database/seeders/Seeds/UserSeeder.php | 2 +- public/install/dotenv.php | 11 +- public/install/forms.php | 261 +++-- public/install/functions.php | 61 +- public/install/index.php | 122 +-- public/install/phpmailer/Exception.php | 2 +- public/install/phpmailer/PHPMailer.php | 958 +++++++++--------- public/install/phpmailer/SMTP.php | 234 ++--- resources/lang/cs/auth.php | 2 +- resources/lang/cs/pagination.php | 2 +- resources/lang/cs/passwords.php | 8 +- resources/lang/cs/validation.php | 198 ++-- resources/lang/de/auth.php | 2 +- resources/lang/de/pagination.php | 2 +- resources/lang/de/passwords.php | 8 +- resources/lang/de/validation.php | 198 ++-- resources/lang/es/auth.php | 2 +- resources/lang/es/pagination.php | 2 +- resources/lang/es/passwords.php | 8 +- resources/lang/es/validation.php | 200 ++-- resources/lang/fr/auth.php | 2 +- resources/lang/fr/pagination.php | 2 +- resources/lang/fr/passwords.php | 8 +- resources/lang/fr/validation.php | 198 ++-- resources/lang/hi/auth.php | 2 +- resources/lang/hi/pagination.php | 2 +- resources/lang/hi/passwords.php | 8 +- resources/lang/hi/validation.php | 198 ++-- resources/lang/it/auth.php | 2 +- resources/lang/it/pagination.php | 2 +- resources/lang/it/passwords.php | 8 +- resources/lang/it/validation.php | 198 ++-- resources/lang/nl/auth.php | 2 +- resources/lang/nl/pagination.php | 2 +- resources/lang/nl/passwords.php | 8 +- resources/lang/nl/validation.php | 198 ++-- resources/lang/pl/auth.php | 2 +- resources/lang/pl/pagination.php | 2 +- resources/lang/pl/passwords.php | 8 +- resources/lang/pl/validation.php | 198 ++-- routes/web.php | 75 +- server.php | 2 - tests/Feature/TestApiAuthorization.php | 14 +- tests/Feature/TestUsefulLinksController.php | 133 +-- tests/Feature/TestVouchersController.php | 354 +++---- tests/Unit/TestUserCommand.php | 14 +- 176 files changed, 4080 insertions(+), 4062 deletions(-) diff --git a/app/Classes/Pterodactyl.php b/app/Classes/Pterodactyl.php index 95893dca..528a2c4b 100644 --- a/app/Classes/Pterodactyl.php +++ b/app/Classes/Pterodactyl.php @@ -5,8 +5,8 @@ namespace App\Classes; use App\Models\Egg; use App\Models\Nest; use App\Models\Node; -use App\Models\Server; use App\Models\Product; +use App\Models\Server; use Exception; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Client\Response; @@ -22,136 +22,160 @@ class Pterodactyl public static function client() { return Http::withHeaders([ - 'Authorization' => 'Bearer ' . config("SETTINGS::SYSTEM:PTERODACTYL:TOKEN"), - 'Content-type' => 'application/json', - 'Accept' => 'Application/vnd.pterodactyl.v1+json', - ])->baseUrl(config("SETTINGS::SYSTEM:PTERODACTYL:URL") . '/api'); + 'Authorization' => 'Bearer '.config('SETTINGS::SYSTEM:PTERODACTYL:TOKEN'), + 'Content-type' => 'application/json', + 'Accept' => 'Application/vnd.pterodactyl.v1+json', + ])->baseUrl(config('SETTINGS::SYSTEM:PTERODACTYL:URL').'/api'); } public static function clientAdmin() { return Http::withHeaders([ - 'Authorization' => 'Bearer ' . config("SETTINGS::SYSTEM:PTERODACTYL:ADMIN_USER_TOKEN"), - 'Content-type' => 'application/json', - 'Accept' => 'Application/vnd.pterodactyl.v1+json', - ])->baseUrl(config("SETTINGS::SYSTEM:PTERODACTYL:URL") . '/api'); + 'Authorization' => 'Bearer '.config('SETTINGS::SYSTEM:PTERODACTYL:ADMIN_USER_TOKEN'), + 'Content-type' => 'application/json', + 'Accept' => 'Application/vnd.pterodactyl.v1+json', + ])->baseUrl(config('SETTINGS::SYSTEM:PTERODACTYL:URL').'/api'); } + /** * @return Exception */ - private static function getException(string $message = "", int $status = 0): Exception + private static function getException(string $message = '', int $status = 0): Exception { if ($status == 404) { - return new Exception("Ressource does not exist on pterodactyl - " . $message, 404); + return new Exception('Ressource does not exist on pterodactyl - '.$message, 404); } if ($status == 403) { - return new Exception("No permission on pterodactyl, check pterodactyl token and permissions - " . $message, 403); + return new Exception('No permission on pterodactyl, check pterodactyl token and permissions - '.$message, 403); } if ($status == 401) { - return new Exception("No pterodactyl token set - " . $message, 401); + return new Exception('No pterodactyl token set - '.$message, 401); } if ($status == 500) { - return new Exception("Pterodactyl server error - " . $message, 500); + return new Exception('Pterodactyl server error - '.$message, 500); } - return new Exception('Request Failed, is pterodactyl set-up correctly? - ' . $message); + return new Exception('Request Failed, is pterodactyl set-up correctly? - '.$message); } /** - * @param Nest $nest + * @param Nest $nest * @return mixed + * * @throws Exception */ public static function getEggs(Nest $nest) { try { - $response = self::client()->get("/application/nests/{$nest->id}/eggs?include=nest,variables&per_page=" . config("SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT")); + $response = self::client()->get("/application/nests/{$nest->id}/eggs?include=nest,variables&per_page=".config('SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT')); } catch (Exception $e) { throw self::getException($e->getMessage()); } - if ($response->failed()) throw self::getException("Failed to get eggs from pterodactyl - ", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to get eggs from pterodactyl - ', $response->status()); + } + return $response->json()['data']; } /** * @return mixed + * * @throws Exception */ public static function getNodes() { try { - $response = self::client()->get('/application/nodes?per_page=' . config("SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT")); + $response = self::client()->get('/application/nodes?per_page='.config('SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT')); } catch (Exception $e) { throw self::getException($e->getMessage()); } - if ($response->failed()) throw self::getException("Failed to get nodes from pterodactyl - ", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to get nodes from pterodactyl - ', $response->status()); + } + return $response->json()['data']; } /** * @return mixed + * * @throws Exception * @description Returns the infos of a single node */ - public static function getNode($id) { + public static function getNode($id) + { try { - $response = self::client()->get('/application/nodes/' . $id); - } catch(Exception $e) { - throw self::getException($e->getMessage()); - } - if($response->failed()) throw self::getException("Failed to get node id " . $id . " - " . $response->status()); - return $response->json()['attributes']; - } - - - - public static function getServers() { - try { - $response = self::client()->get('/application/servers?per_page=' . config("SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT")); + $response = self::client()->get('/application/nodes/'.$id); } catch (Exception $e) { throw self::getException($e->getMessage()); } - if($response->failed()) throw self::getException("Failed to get list of servers - ", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to get node id '.$id.' - '.$response->status()); + } + + return $response->json()['attributes']; + } + + public static function getServers() + { + try { + $response = self::client()->get('/application/servers?per_page='.config('SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT')); + } catch (Exception $e) { + throw self::getException($e->getMessage()); + } + if ($response->failed()) { + throw self::getException('Failed to get list of servers - ', $response->status()); + } + return $response->json()['data']; } /** * @return null + * * @throws Exception */ public static function getNests() { try { - $response = self::client()->get('/application/nests?per_page=' . config("SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT")); + $response = self::client()->get('/application/nests?per_page='.config('SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT')); } catch (Exception $e) { throw self::getException($e->getMessage()); } - if ($response->failed()) throw self::getException("Failed to get nests from pterodactyl", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to get nests from pterodactyl', $response->status()); + } + return $response->json()['data']; } /** * @return mixed + * * @throws Exception */ public static function getLocations() { try { - $response = self::client()->get('/application/locations?per_page=' . config("SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT")); + $response = self::client()->get('/application/locations?per_page='.config('SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT')); } catch (Exception $e) { throw self::getException($e->getMessage()); } - if ($response->failed()) throw self::getException("Failed to get locations from pterodactyl - ", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to get locations from pterodactyl - ', $response->status()); + } return $response->json()['data']; } /** - * @param Node $node + * @param Node $node * @return mixed + * * @throws Exception */ public static function getFreeAllocationId(Node $node) @@ -160,8 +184,9 @@ class Pterodactyl } /** - * @param Node $node + * @param Node $node * @return array|mixed|null + * * @throws Exception */ public static function getFreeAllocations(Node $node) @@ -170,9 +195,11 @@ class Pterodactyl $freeAllocations = []; if (isset($response['data'])) { - if (!empty($response['data'])) { + if (! empty($response['data'])) { foreach ($response['data'] as $allocation) { - if (!$allocation['attributes']['assigned']) array_push($freeAllocations, $allocation); + if (! $allocation['attributes']['assigned']) { + array_push($freeAllocations, $allocation); + } } } } @@ -181,8 +208,9 @@ class Pterodactyl } /** - * @param Node $node + * @param Node $node * @return array|mixed + * * @throws Exception */ public static function getAllocations(Node $node) @@ -193,51 +221,53 @@ class Pterodactyl } catch (Exception $e) { throw self::getException($e->getMessage()); } - if ($response->failed()) throw self::getException("Failed to get allocations from pterodactyl - ", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to get allocations from pterodactyl - ', $response->status()); + } return $response->json(); } /** - * @param String $route + * @param string $route * @return string */ public static function url(string $route): string { - return config("SETTINGS::SYSTEM:PTERODACTYL:URL") . $route; + return config('SETTINGS::SYSTEM:PTERODACTYL:URL').$route; } /** - * @param Server $server - * @param Egg $egg - * @param int $allocationId + * @param Server $server + * @param Egg $egg + * @param int $allocationId * @return Response */ public static function createServer(Server $server, Egg $egg, int $allocationId) { - return self::client()->post("/application/servers", [ - "name" => $server->name, - "external_id" => $server->id, - "user" => $server->user->pterodactyl_id, - "egg" => $egg->id, - "docker_image" => $egg->docker_image, - "startup" => $egg->startup, - "environment" => $egg->getEnvironmentVariables(), - "limits" => [ - "memory" => $server->product->memory, - "swap" => $server->product->swap, - "disk" => $server->product->disk, - "io" => $server->product->io, - "cpu" => $server->product->cpu + return self::client()->post('/application/servers', [ + 'name' => $server->name, + 'external_id' => $server->id, + 'user' => $server->user->pterodactyl_id, + 'egg' => $egg->id, + 'docker_image' => $egg->docker_image, + 'startup' => $egg->startup, + 'environment' => $egg->getEnvironmentVariables(), + 'limits' => [ + 'memory' => $server->product->memory, + 'swap' => $server->product->swap, + 'disk' => $server->product->disk, + 'io' => $server->product->io, + 'cpu' => $server->product->cpu, ], - "feature_limits" => [ - "databases" => $server->product->databases, - "backups" => $server->product->backups, - "allocations" => $server->product->allocations, + 'feature_limits' => [ + 'databases' => $server->product->databases, + 'backups' => $server->product->backups, + 'allocations' => $server->product->allocations, + ], + 'allocation' => [ + 'default' => $allocationId, ], - "allocation" => [ - "default" => $allocationId - ] ]); } @@ -248,7 +278,9 @@ class Pterodactyl } catch (Exception $e) { throw self::getException($e->getMessage()); } - if ($response->failed()) throw self::getException("Failed to suspend server from pterodactyl - ", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to suspend server from pterodactyl - ', $response->status()); + } return $response; } @@ -260,14 +292,17 @@ class Pterodactyl } catch (Exception $e) { throw self::getException($e->getMessage()); } - if ($response->failed()) throw self::getException("Failed to unsuspend server from pterodactyl - ", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to unsuspend server from pterodactyl - ', $response->status()); + } return $response; } /** * Get user by pterodactyl id - * @param int $pterodactylId + * + * @param int $pterodactylId * @return mixed */ public function getUser(int $pterodactylId) @@ -277,14 +312,17 @@ class Pterodactyl } catch (Exception $e) { throw self::getException($e->getMessage()); } - if ($response->failed()) throw self::getException("Failed to get user from pterodactyl - ", $response->status()); + if ($response->failed()) { + throw self::getException('Failed to get user from pterodactyl - ', $response->status()); + } return $response->json()['attributes']; } /** * Get serverAttributes by pterodactyl id - * @param int $pterodactylId + * + * @param int $pterodactylId * @return mixed */ public static function getServerAttributes(int $pterodactylId, bool $deleteOn404 = false) @@ -297,51 +335,55 @@ class Pterodactyl //print response body - - - if ($response->failed()){ - if($deleteOn404){ //Delete the server if it does not exist (server deleted on pterodactyl) + if ($response->failed()) { + if ($deleteOn404) { //Delete the server if it does not exist (server deleted on pterodactyl) Server::where('pterodactyl_id', $pterodactylId)->first()->delete(); + return; + } else { + throw self::getException('Failed to get server attributes from pterodactyl - ', $response->status()); } - else throw self::getException("Failed to get server attributes from pterodactyl - ", $response->status()); } + return $response->json()['attributes']; } /** * Update Server Resources - * @param Server $server - * @param Product $product + * + * @param Server $server + * @param Product $product * @return Response */ public static function updateServer(Server $server, Product $product) { return self::client()->patch("/application/servers/{$server->pterodactyl_id}/build", [ - "allocation" => $server->allocation, - "memory" => $product->memory, - "swap" => $product->swap, - "disk" => $product->disk, - "io" => $product->io, - "cpu" => $product->cpu, - "threads" => null, - "feature_limits" => [ - "databases" => $product->databases, - "backups" => $product->backups, - "allocations" => $product->allocations, - ] + 'allocation' => $server->allocation, + 'memory' => $product->memory, + 'swap' => $product->swap, + 'disk' => $product->disk, + 'io' => $product->io, + 'cpu' => $product->cpu, + 'threads' => null, + 'feature_limits' => [ + 'databases' => $product->databases, + 'backups' => $product->backups, + 'allocations' => $product->allocations, + ], ]); } + /** * Power Action Specific Server - * @param Server $server - * @param string $action + * + * @param Server $server + * @param string $action * @return Response */ public static function powerAction(Server $server, $action) { return self::clientAdmin()->post("/client/servers/{$server->identifier}/power", [ - "signal" => $action + 'signal' => $action, ]); } @@ -350,16 +392,16 @@ class Pterodactyl */ public static function getClientUser() { - return self::clientAdmin()->get("/client/account"); + return self::clientAdmin()->get('/client/account'); } - /** * Check if node has enough free resources to allocate the given resources - * @param Node $node - * @param int $requireMemory - * @param int $requireDisk - * @return boolean + * + * @param Node $node + * @param int $requireMemory + * @param int $requireDisk + * @return bool */ public static function checkNodeResources(Node $node, int $requireMemory, int $requireDisk) { @@ -369,14 +411,15 @@ class Pterodactyl throw self::getException($e->getMessage()); } $node = $response['attributes']; - $freeMemory = ($node['memory']*($node['memory_overallocate']+100)/100) - $node['allocated_resources']['memory']; - $freeDisk = ($node['disk']*($node['disk_overallocate']+100)/100) - $node['allocated_resources']['disk']; + $freeMemory = ($node['memory'] * ($node['memory_overallocate'] + 100) / 100) - $node['allocated_resources']['memory']; + $freeDisk = ($node['disk'] * ($node['disk_overallocate'] + 100) / 100) - $node['allocated_resources']['disk']; if ($freeMemory < $requireMemory) { return false; - } - if ($freeDisk < $requireDisk) { + } + if ($freeDisk < $requireDisk) { return false; - } - return true; + } + + return true; } } diff --git a/app/Classes/Settings/Invoices.php b/app/Classes/Settings/Invoices.php index 425af60c..72a809da 100644 --- a/app/Classes/Settings/Invoices.php +++ b/app/Classes/Settings/Invoices.php @@ -10,9 +10,8 @@ class Invoices { public function __construct() { - return; - } + } public function updateSettings(Request $request) { @@ -22,29 +21,27 @@ class Invoices $values = [ //SETTINGS::VALUE => REQUEST-VALUE (coming from the html-form) - "SETTINGS::INVOICE:COMPANY_NAME" => "company-name", - "SETTINGS::INVOICE:COMPANY_ADDRESS" => "company-address", - "SETTINGS::INVOICE:COMPANY_PHONE" => "company-phone", - "SETTINGS::INVOICE:COMPANY_MAIL" => "company-mail", - "SETTINGS::INVOICE:COMPANY_VAT" => "company-vat", - "SETTINGS::INVOICE:COMPANY_WEBSITE" => "company-web", - "SETTINGS::INVOICE:PREFIX" => "invoice-prefix", - "SETTINGS::INVOICE:ENABLED" => "enable-invoices", + 'SETTINGS::INVOICE:COMPANY_NAME' => 'company-name', + 'SETTINGS::INVOICE:COMPANY_ADDRESS' => 'company-address', + 'SETTINGS::INVOICE:COMPANY_PHONE' => 'company-phone', + 'SETTINGS::INVOICE:COMPANY_MAIL' => 'company-mail', + 'SETTINGS::INVOICE:COMPANY_VAT' => 'company-vat', + 'SETTINGS::INVOICE:COMPANY_WEBSITE' => 'company-web', + 'SETTINGS::INVOICE:PREFIX' => 'invoice-prefix', + 'SETTINGS::INVOICE:ENABLED' => 'enable-invoices', ]; foreach ($values as $key => $value) { $param = $request->get($value); Settings::where('key', $key)->updateOrCreate(['key' => $key], ['value' => $param]); - Cache::forget("setting" . ':' . $key); + Cache::forget('setting'.':'.$key); } - if ($request->hasFile('logo')) { $request->file('logo')->storeAs('public', 'logo.png'); } - - return redirect(route('admin.settings.index') . '#invoices')->with('success', __('Invoice settings updated!')); + return redirect(route('admin.settings.index').'#invoices')->with('success', __('Invoice settings updated!')); } } diff --git a/app/Classes/Settings/Language.php b/app/Classes/Settings/Language.php index 5f9b87fe..4e2bc3c2 100644 --- a/app/Classes/Settings/Language.php +++ b/app/Classes/Settings/Language.php @@ -8,14 +8,12 @@ use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Validator; - class Language { public function __construct() { - return; - } + } public function updateSettings(Request $request) { @@ -28,34 +26,31 @@ class Language 'datatable-language' => 'required|string', ]); - if ($validator->fails()) { - return redirect(route('admin.settings.index') . '#language')->with('error', __('Language settings have not been updated!'))->withErrors($validator); + return redirect(route('admin.settings.index').'#language')->with('error', __('Language settings have not been updated!'))->withErrors($validator); } $values = [ //SETTINGS::VALUE => REQUEST-VALUE (coming from the html-form) - "SETTINGS::LOCALE:DEFAULT" => "defaultLanguage", - "SETTINGS::LOCALE:DYNAMIC" => "autotranslate", - "SETTINGS::LOCALE:CLIENTS_CAN_CHANGE" => "canClientChangeLanguage", - "SETTINGS::LOCALE:AVAILABLE" => "languages", - "SETTINGS::LOCALE:DATATABLES" => "datatable-language" + 'SETTINGS::LOCALE:DEFAULT' => 'defaultLanguage', + 'SETTINGS::LOCALE:DYNAMIC' => 'autotranslate', + 'SETTINGS::LOCALE:CLIENTS_CAN_CHANGE' => 'canClientChangeLanguage', + 'SETTINGS::LOCALE:AVAILABLE' => 'languages', + 'SETTINGS::LOCALE:DATATABLES' => 'datatable-language', ]; - foreach ($values as $key => $value) { $param = $request->get($value); if (is_array($param)) { - $param = implode(",", $param); + $param = implode(',', $param); } Settings::where('key', $key)->updateOrCreate(['key' => $key], ['value' => $param]); - Cache::forget("setting" . ':' . $key); - Session::remove("locale"); + Cache::forget('setting'.':'.$key); + Session::remove('locale'); } - - return redirect(route('admin.settings.index') . '#language')->with('success', __('Language settings updated!')); + return redirect(route('admin.settings.index').'#language')->with('success', __('Language settings updated!')); } } diff --git a/app/Classes/Settings/Misc.php b/app/Classes/Settings/Misc.php index 496bac73..abd4a138 100644 --- a/app/Classes/Settings/Misc.php +++ b/app/Classes/Settings/Misc.php @@ -7,12 +7,11 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Validator; - class Misc { public function __construct() { - return; + } public function updateSettings(Request $request) @@ -48,14 +47,14 @@ class Misc $validator->after(function ($validator) use ($request) { // if enable-recaptcha is true then recaptcha-site-key and recaptcha-secret-key must be set - if ($request->get('enable-recaptcha') == 'true' && (!$request->get('recaptcha-site-key') || !$request->get('recaptcha-secret-key'))) { + if ($request->get('enable-recaptcha') == 'true' && (! $request->get('recaptcha-site-key') || ! $request->get('recaptcha-secret-key'))) { $validator->errors()->add('recaptcha-site-key', 'The site key is required if recaptcha is enabled.'); $validator->errors()->add('recaptcha-secret-key', 'The secret key is required if recaptcha is enabled.'); } }); if ($validator->fails()) { - return redirect(route('admin.settings.index') . '#misc')->with('error', __('Misc settings have not been updated!'))->withErrors($validator) + return redirect(route('admin.settings.index').'#misc')->with('error', __('Misc settings have not been updated!'))->withErrors($validator) ->withInput(); } @@ -67,31 +66,30 @@ class Misc } $values = [ - "SETTINGS::DISCORD:BOT_TOKEN" => "discord-bot-token", - "SETTINGS::DISCORD:CLIENT_ID" => "discord-client-id", - "SETTINGS::DISCORD:CLIENT_SECRET" => "discord-client-secret", - "SETTINGS::DISCORD:GUILD_ID" => "discord-guild-id", - "SETTINGS::DISCORD:INVITE_URL" => "discord-invite-url", - "SETTINGS::DISCORD:ROLE_ID" => "discord-role-id", - "SETTINGS::RECAPTCHA:SITE_KEY" => "recaptcha-site-key", - "SETTINGS::RECAPTCHA:SECRET_KEY" => "recaptcha-secret-key", - "SETTINGS::RECAPTCHA:ENABLED" => "enable-recaptcha", - "SETTINGS::MAIL:MAILER" => "mailservice", - "SETTINGS::MAIL:HOST" => "mailhost", - "SETTINGS::MAIL:PORT" => "mailport", - "SETTINGS::MAIL:USERNAME" => "mailusername", - "SETTINGS::MAIL:PASSWORD" => "mailpassword", - "SETTINGS::MAIL:ENCRYPTION" => "mailencryption", - "SETTINGS::MAIL:FROM_ADDRESS" => "mailfromadress", - "SETTINGS::MAIL:FROM_NAME" => "mailfromname", - "SETTINGS::REFERRAL::ENABLED" => "enable_referral", - "SETTINGS::REFERRAL::REWARD" => "referral_reward", - "SETTINGS::REFERRAL::ALLOWED" => "referral_allowed", - "SETTINGS::REFERRAL:MODE" => "referral_mode", - "SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION" => "always_give_commission", - "SETTINGS::REFERRAL:PERCENTAGE" => "referral_percentage", - "SETTINGS::TICKET:ENABLED" => "ticket_enabled" - + 'SETTINGS::DISCORD:BOT_TOKEN' => 'discord-bot-token', + 'SETTINGS::DISCORD:CLIENT_ID' => 'discord-client-id', + 'SETTINGS::DISCORD:CLIENT_SECRET' => 'discord-client-secret', + 'SETTINGS::DISCORD:GUILD_ID' => 'discord-guild-id', + 'SETTINGS::DISCORD:INVITE_URL' => 'discord-invite-url', + 'SETTINGS::DISCORD:ROLE_ID' => 'discord-role-id', + 'SETTINGS::RECAPTCHA:SITE_KEY' => 'recaptcha-site-key', + 'SETTINGS::RECAPTCHA:SECRET_KEY' => 'recaptcha-secret-key', + 'SETTINGS::RECAPTCHA:ENABLED' => 'enable-recaptcha', + 'SETTINGS::MAIL:MAILER' => 'mailservice', + 'SETTINGS::MAIL:HOST' => 'mailhost', + 'SETTINGS::MAIL:PORT' => 'mailport', + 'SETTINGS::MAIL:USERNAME' => 'mailusername', + 'SETTINGS::MAIL:PASSWORD' => 'mailpassword', + 'SETTINGS::MAIL:ENCRYPTION' => 'mailencryption', + 'SETTINGS::MAIL:FROM_ADDRESS' => 'mailfromadress', + 'SETTINGS::MAIL:FROM_NAME' => 'mailfromname', + 'SETTINGS::REFERRAL::ENABLED' => 'enable_referral', + 'SETTINGS::REFERRAL::REWARD' => 'referral_reward', + 'SETTINGS::REFERRAL::ALLOWED' => 'referral_allowed', + 'SETTINGS::REFERRAL:MODE' => 'referral_mode', + 'SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION' => 'always_give_commission', + 'SETTINGS::REFERRAL:PERCENTAGE' => 'referral_percentage', + 'SETTINGS::TICKET:ENABLED' => 'ticket_enabled', ]; @@ -99,10 +97,9 @@ class Misc $param = $request->get($value); Settings::where('key', $key)->updateOrCreate(['key' => $key], ['value' => $param]); - Cache::forget("setting" . ':' . $key); + Cache::forget('setting'.':'.$key); } - - return redirect(route('admin.settings.index') . '#misc')->with('success', __('Misc settings updated!')); + return redirect(route('admin.settings.index').'#misc')->with('success', __('Misc settings updated!')); } } diff --git a/app/Classes/Settings/Payments.php b/app/Classes/Settings/Payments.php index 262e2886..0139abc6 100644 --- a/app/Classes/Settings/Payments.php +++ b/app/Classes/Settings/Payments.php @@ -7,55 +7,52 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Validator; - class Payments { public function __construct() { - return; - } + } public function updateSettings(Request $request) { $validator = Validator::make($request->all(), [ - "paypal-client_id" => "nullable|string", - "paypal-client-secret" => "nullable|string", - "paypal-sandbox-secret" => "nullable|string", - "stripe-secret-key" => "nullable|string", - "stripe-endpoint-secret" => "nullable|string", - "stripe-test-secret-key" => "nullable|string", - "stripe-test-endpoint-secret" => "nullable|string", - "stripe-methods" => "nullable|string", - "sales-tax" => "nullable|numeric", + 'paypal-client_id' => 'nullable|string', + 'paypal-client-secret' => 'nullable|string', + 'paypal-sandbox-secret' => 'nullable|string', + 'stripe-secret-key' => 'nullable|string', + 'stripe-endpoint-secret' => 'nullable|string', + 'stripe-test-secret-key' => 'nullable|string', + 'stripe-test-endpoint-secret' => 'nullable|string', + 'stripe-methods' => 'nullable|string', + 'sales-tax' => 'nullable|numeric', ]); if ($validator->fails()) { - return redirect(route('admin.settings.index') . '#payment')->with('error', __('Payment settings have not been updated!'))->withErrors($validator) + return redirect(route('admin.settings.index').'#payment')->with('error', __('Payment settings have not been updated!'))->withErrors($validator) ->withInput(); } $values = [ //SETTINGS::VALUE => REQUEST-VALUE (coming from the html-form) - "SETTINGS::PAYMENTS:PAYPAL:SECRET" => "paypal-client-secret", - "SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID" => "paypal-client-id", - "SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET" => "paypal-sandbox-secret", - "SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID" => "paypal-sandbox-id", - "SETTINGS::PAYMENTS:STRIPE:SECRET" => "stripe-secret", - "SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET" => "stripe-endpoint-secret", - "SETTINGS::PAYMENTS:STRIPE:TEST_SECRET" => "stripe-test-secret", - "SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET" => "stripe-endpoint-test-secret", - "SETTINGS::PAYMENTS:STRIPE:METHODS" => "stripe-methods", - "SETTINGS::PAYMENTS:SALES_TAX" => "sales-tax" + 'SETTINGS::PAYMENTS:PAYPAL:SECRET' => 'paypal-client-secret', + 'SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID' => 'paypal-client-id', + 'SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET' => 'paypal-sandbox-secret', + 'SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID' => 'paypal-sandbox-id', + 'SETTINGS::PAYMENTS:STRIPE:SECRET' => 'stripe-secret', + 'SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET' => 'stripe-endpoint-secret', + 'SETTINGS::PAYMENTS:STRIPE:TEST_SECRET' => 'stripe-test-secret', + 'SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET' => 'stripe-endpoint-test-secret', + 'SETTINGS::PAYMENTS:STRIPE:METHODS' => 'stripe-methods', + 'SETTINGS::PAYMENTS:SALES_TAX' => 'sales-tax', ]; - foreach ($values as $key => $value) { $param = $request->get($value); Settings::where('key', $key)->updateOrCreate(['key' => $key], ['value' => $param]); - Cache::forget("setting" . ':' . $key); + Cache::forget('setting'.':'.$key); } - return redirect(route('admin.settings.index') . '#payment')->with('success', __('Payment settings updated!')); + return redirect(route('admin.settings.index').'#payment')->with('success', __('Payment settings updated!')); } } diff --git a/app/Classes/Settings/System.php b/app/Classes/Settings/System.php index f2759c1f..fe881892 100644 --- a/app/Classes/Settings/System.php +++ b/app/Classes/Settings/System.php @@ -10,101 +10,101 @@ use Illuminate\Support\Facades\Validator; class System { - - public function __construct() { - return; + } -public function checkPteroClientkey(){ - $response = Pterodactyl::getClientUser(); + public function checkPteroClientkey() + { + $response = Pterodactyl::getClientUser(); - if ($response->failed()){ return redirect()->back()->with('error', __('Your Key or URL is not correct')); } - return redirect()->back()->with('success', __('Everything is good!')); -} + if ($response->failed()) { + return redirect()->back()->with('error', __('Your Key or URL is not correct')); + } + + return redirect()->back()->with('success', __('Everything is good!')); + } public function updateSettings(Request $request) { $validator = Validator::make($request->all(), [ - "register-ip-check" => "string", - "server-create-charge-first-hour" => "string", - "credits-display-name" => "required|string", - "allocation-limit" => "required|min:0|integer", - "force-email-verification" => "string", - "force-discord-verification" => "string", - "initial-credits" => "required|min:0|integer", - "initial-server-limit" => "required|min:0|integer", - "credits-reward-amount-discord" => "required|min:0|integer", - "credits-reward-amount-email" => "required|min:0|integer", - "server-limit-discord" => "required|min:0|integer", - "server-limit-email" => "required|min:0|integer", - "server-limit-purchase" => "required|min:0|integer", - "pterodactyl-api-key" => "required|string", - "pterodactyl-url" => "required|string", - "per-page-limit" => "required|min:0|integer", - "pterodactyl-admin-api-key" => "required|string", - "enable-upgrades" => "string", - "enable-disable-servers" => "string", - "show-imprint" => "string", - "show-privacy" => "string", - "show-tos" => "string", + 'register-ip-check' => 'string', + 'server-create-charge-first-hour' => 'string', + 'credits-display-name' => 'required|string', + 'allocation-limit' => 'required|min:0|integer', + 'force-email-verification' => 'string', + 'force-discord-verification' => 'string', + 'initial-credits' => 'required|min:0|integer', + 'initial-server-limit' => 'required|min:0|integer', + 'credits-reward-amount-discord' => 'required|min:0|integer', + 'credits-reward-amount-email' => 'required|min:0|integer', + 'server-limit-discord' => 'required|min:0|integer', + 'server-limit-email' => 'required|min:0|integer', + 'server-limit-purchase' => 'required|min:0|integer', + 'pterodactyl-api-key' => 'required|string', + 'pterodactyl-url' => 'required|string', + 'per-page-limit' => 'required|min:0|integer', + 'pterodactyl-admin-api-key' => 'required|string', + 'enable-upgrades' => 'string', + 'enable-disable-servers' => 'string', + 'show-imprint' => 'string', + 'show-privacy' => 'string', + 'show-tos' => 'string', ]); $validator->after(function ($validator) use ($request) { // if enable-recaptcha is true then recaptcha-site-key and recaptcha-secret-key must be set - if ($request->get('enable-upgrades') == 'true' && (!$request->get('pterodactyl-admin-api-key'))) { + if ($request->get('enable-upgrades') == 'true' && (! $request->get('pterodactyl-admin-api-key'))) { $validator->errors()->add('pterodactyl-admin-api-key', 'The admin api key is required when upgrades are enabled.'); } }); if ($validator->fails()) { - return redirect(route('admin.settings.index') . '#system')->with('error', __('System settings have not been updated!'))->withErrors($validator) + return redirect(route('admin.settings.index').'#system')->with('error', __('System settings have not been updated!'))->withErrors($validator) ->withInput(); } // update Icons from request $this->updateIcons($request); - $values = [ - "SETTINGS::SYSTEM:REGISTER_IP_CHECK" => "register-ip-check", - "SETTINGS::SYSTEM:SERVER_CREATE_CHARGE_FIRST_HOUR" => "server-create-charge-first-hour", - "SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME" => "credits-display-name", - "SETTINGS::SERVER:ALLOCATION_LIMIT" => "allocation-limit", - "SETTINGS::USER:FORCE_DISCORD_VERIFICATION" => "force-discord-verification", - "SETTINGS::USER:FORCE_EMAIL_VERIFICATION" => "force-email-verification", - "SETTINGS::USER:INITIAL_CREDITS" => "initial-credits", - "SETTINGS::USER:INITIAL_SERVER_LIMIT" => "initial-server-limit", - "SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD" => "credits-reward-amount-discord", - "SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_EMAIL" => "credits-reward-amount-email", - "SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_DISCORD" => "server-limit-discord", - "SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_EMAIL" => "server-limit-email", - "SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE" => "server-limit-purchase", - "SETTINGS::MISC:PHPMYADMIN:URL" => "phpmyadmin-url", - "SETTINGS::SYSTEM:PTERODACTYL:URL" => "pterodactyl-url", - 'SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT' => "per-page-limit", - "SETTINGS::SYSTEM:PTERODACTYL:TOKEN" => "pterodactyl-api-key", - "SETTINGS::SYSTEM:ENABLE_LOGIN_LOGO" => "enable-login-logo", - "SETTINGS::SYSTEM:PTERODACTYL:ADMIN_USER_TOKEN" => "pterodactyl-admin-api-key", - "SETTINGS::SYSTEM:ENABLE_UPGRADE" => "enable-upgrade", - "SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS" => "enable-disable-servers", - "SETTINGS::SYSTEM:CREATION_OF_NEW_USERS" => "enable-disable-new-users", - "SETTINGS::SYSTEM:SHOW_IMPRINT" => "show-imprint", - "SETTINGS::SYSTEM:SHOW_PRIVACY" => "show-privacy", - "SETTINGS::SYSTEM:SHOW_TOS" => "show-tos", + 'SETTINGS::SYSTEM:REGISTER_IP_CHECK' => 'register-ip-check', + 'SETTINGS::SYSTEM:SERVER_CREATE_CHARGE_FIRST_HOUR' => 'server-create-charge-first-hour', + 'SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME' => 'credits-display-name', + 'SETTINGS::SERVER:ALLOCATION_LIMIT' => 'allocation-limit', + 'SETTINGS::USER:FORCE_DISCORD_VERIFICATION' => 'force-discord-verification', + 'SETTINGS::USER:FORCE_EMAIL_VERIFICATION' => 'force-email-verification', + 'SETTINGS::USER:INITIAL_CREDITS' => 'initial-credits', + 'SETTINGS::USER:INITIAL_SERVER_LIMIT' => 'initial-server-limit', + 'SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD' => 'credits-reward-amount-discord', + 'SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_EMAIL' => 'credits-reward-amount-email', + 'SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_DISCORD' => 'server-limit-discord', + 'SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_EMAIL' => 'server-limit-email', + 'SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE' => 'server-limit-purchase', + 'SETTINGS::MISC:PHPMYADMIN:URL' => 'phpmyadmin-url', + 'SETTINGS::SYSTEM:PTERODACTYL:URL' => 'pterodactyl-url', + 'SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT' => 'per-page-limit', + 'SETTINGS::SYSTEM:PTERODACTYL:TOKEN' => 'pterodactyl-api-key', + 'SETTINGS::SYSTEM:ENABLE_LOGIN_LOGO' => 'enable-login-logo', + 'SETTINGS::SYSTEM:PTERODACTYL:ADMIN_USER_TOKEN' => 'pterodactyl-admin-api-key', + 'SETTINGS::SYSTEM:ENABLE_UPGRADE' => 'enable-upgrade', + 'SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS' => 'enable-disable-servers', + 'SETTINGS::SYSTEM:CREATION_OF_NEW_USERS' => 'enable-disable-new-users', + 'SETTINGS::SYSTEM:SHOW_IMPRINT' => 'show-imprint', + 'SETTINGS::SYSTEM:SHOW_PRIVACY' => 'show-privacy', + 'SETTINGS::SYSTEM:SHOW_TOS' => 'show-tos', ]; - foreach ($values as $key => $value) { $param = $request->get($value); Settings::where('key', $key)->updateOrCreate(['key' => $key], ['value' => $param]); - Cache::forget("setting" . ':' . $key); + Cache::forget('setting'.':'.$key); } - return redirect(route('admin.settings.index') . '#system')->with('success', __('System settings updated!')); - } + return redirect(route('admin.settings.index').'#system')->with('success', __('System settings updated!')); + } private function updateIcons(Request $request) { diff --git a/app/Console/Commands/ChargeCreditsCommand.php b/app/Console/Commands/ChargeCreditsCommand.php index 35bfad0a..e51bfdf9 100644 --- a/app/Console/Commands/ChargeCreditsCommand.php +++ b/app/Console/Commands/ChargeCreditsCommand.php @@ -24,9 +24,9 @@ class ChargeCreditsCommand extends Command */ protected $description = 'Charge all users with active servers'; - /** * A list of users that have to be notified + * * @var array */ protected $usersToNotify = []; @@ -56,24 +56,23 @@ class ChargeCreditsCommand extends Command /** @var User $user */ $user = $server->user; - #charge credits / suspend server + //charge credits / suspend server if ($user->credits >= $product->getHourlyPrice()) { $this->line("{$user->name} Current credits: {$user->credits} Credits to be removed: {$product->getHourlyPrice()}"); $user->decrement('credits', $product->getHourlyPrice()); } else { try { - #suspend server + //suspend server $this->line("{$server->name} from user: {$user->name} has been suspended!"); $server->suspend(); - #add user to notify list - if (!in_array($user, $this->usersToNotify)) { + //add user to notify list + if (! in_array($user, $this->usersToNotify)) { array_push($this->usersToNotify, $user); } } catch (\Exception $exception) { $this->error($exception->getMessage()); } - } } }); @@ -86,7 +85,7 @@ class ChargeCreditsCommand extends Command */ public function notifyUsers() { - if (!empty($this->usersToNotify)) { + if (! empty($this->usersToNotify)) { /** @var User $user */ foreach ($this->usersToNotify as $user) { $this->line("Notified user: {$user->name}"); @@ -94,8 +93,9 @@ class ChargeCreditsCommand extends Command } } - #reset array - $this->usersToNotify = array(); + //reset array + $this->usersToNotify = []; + return true; } } diff --git a/app/Console/Commands/ImportUsersFromPteroCommand.php b/app/Console/Commands/ImportUsersFromPteroCommand.php index f3021dd1..8893693b 100644 --- a/app/Console/Commands/ImportUsersFromPteroCommand.php +++ b/app/Console/Commands/ImportUsersFromPteroCommand.php @@ -12,6 +12,7 @@ class ImportUsersFromPteroCommand extends Command * @var string */ private $importFileName = 'users.json'; + /** * The name and signature of the console command. * @@ -39,25 +40,28 @@ class ImportUsersFromPteroCommand extends Command /** * Execute the console command. * - * @return boolean + * @return bool */ public function handle() { //check if json file exists - if (!Storage::disk('local')->exists('users.json')) { - $this->error('[ERROR] ' . storage_path('app') . '/' . $this->importFileName . ' is missing'); + if (! Storage::disk('local')->exists('users.json')) { + $this->error('[ERROR] '.storage_path('app').'/'.$this->importFileName.' is missing'); + return false; } //check if json file is valid $json = json_decode(Storage::disk('local')->get('users.json')); - if (!array_key_exists(2, $json)) { + if (! array_key_exists(2, $json)) { $this->error('[ERROR] Invalid json file'); + return false; } - if (!$json[2]->data) { + if (! $json[2]->data) { $this->error('[ERROR] Invalid json file / No users found!'); + return false; } @@ -69,12 +73,14 @@ class ImportUsersFromPteroCommand extends Command //cancel if ($confirm !== 'y') { $this->error('[ERROR] Stopped import script!'); + return false; } //import users $this->deleteCurrentUserBase(); $this->importUsingJsonFile($json, $initial_credits, $initial_server_limit); + return true; } @@ -84,7 +90,9 @@ class ImportUsersFromPteroCommand extends Command private function deleteCurrentUserBase() { $currentUserCount = User::count(); - if ($currentUserCount == 0) return; + if ($currentUserCount == 0) { + return; + } $this->line("Deleting ({$currentUserCount}) users.."); foreach (User::all() as $user) { @@ -104,20 +112,20 @@ class ImportUsersFromPteroCommand extends Command $role = $user->root_admin == '0' ? 'member' : 'admin'; User::create([ - "pterodactyl_id" => $user->id, - "name" => $user->name_first, - "email" => $user->email, - "password" => $user->password, - "role" => $role, - "credits" => $initial_credits, - "server_limit" => $initial_server_limit, - "created_at" => $user->created_at, - "updated_at" => $user->updated_at, + 'pterodactyl_id' => $user->id, + 'name' => $user->name_first, + 'email' => $user->email, + 'password' => $user->password, + 'role' => $role, + 'credits' => $initial_credits, + 'server_limit' => $initial_server_limit, + 'created_at' => $user->created_at, + 'updated_at' => $user->updated_at, ]); }); $this->newLine(); - $this->line("Done importing, you can now login using your pterodactyl credentials."); + $this->line('Done importing, you can now login using your pterodactyl credentials.'); $this->newLine(); } } diff --git a/app/Console/Commands/MakeUserCommand.php b/app/Console/Commands/MakeUserCommand.php index a06f0d18..0564b3dd 100644 --- a/app/Console/Commands/MakeUserCommand.php +++ b/app/Console/Commands/MakeUserCommand.php @@ -7,7 +7,6 @@ use App\Models\User; use Illuminate\Console\Command; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; -use Illuminate\Validation\ValidationException; class MakeUserCommand extends Command { @@ -59,6 +58,7 @@ class MakeUserCommand extends Command if ($validator->fails()) { $this->error($validator->errors()->first()); + return 0; } @@ -66,9 +66,16 @@ class MakeUserCommand extends Command $response = $this->pterodactyl->getUser($ptero_id); if (isset($response['errors'])) { - if (isset($response['errors'][0]['code'])) $this->error("code: {$response['errors'][0]['code']}"); - if (isset($response['errors'][0]['status'])) $this->error("status: {$response['errors'][0]['status']}"); - if (isset($response['errors'][0]['detail'])) $this->error("detail: {$response['errors'][0]['detail']}"); + if (isset($response['errors'][0]['code'])) { + $this->error("code: {$response['errors'][0]['code']}"); + } + if (isset($response['errors'][0]['status'])) { + $this->error("status: {$response['errors'][0]['status']}"); + } + if (isset($response['errors'][0]['detail'])) { + $this->error("detail: {$response['errors'][0]['detail']}"); + } + return 0; } @@ -77,7 +84,7 @@ class MakeUserCommand extends Command 'email' => $response['email'], 'role' => 'admin', 'password' => Hash::make($password), - 'pterodactyl_id' => $response['id'] + 'pterodactyl_id' => $response['id'], ]); $this->table(['Field', 'Value'], [ diff --git a/app/Console/Commands/notify.php b/app/Console/Commands/notify.php index ffc2ec01..8b2c6ca1 100644 --- a/app/Console/Commands/notify.php +++ b/app/Console/Commands/notify.php @@ -36,12 +36,13 @@ class notify extends Command /** * Execute the console command. * - * @param int $id + * @param int $id * @return int */ public function handle() { User::findOrFail($this->argument('id'))->notify(new ServerCreationError(Server::all()[0])); + return 'message send'; } } diff --git a/app/Console/Commands/update.php b/app/Console/Commands/update.php index 2ed305bc..deb12c86 100644 --- a/app/Console/Commands/update.php +++ b/app/Console/Commands/update.php @@ -2,10 +2,10 @@ namespace App\Console\Commands; -use Illuminate\Console\Command; use Closure; -use Symfony\Component\Process\Process; +use Illuminate\Console\Command; use Symfony\Component\Console\Helper\ProgressBar; +use Symfony\Component\Process\Process; class update extends Command { @@ -45,7 +45,7 @@ class update extends Command $this->output->warning('This command does just pull the newest changes from the github repo. Verify the github repo before running this'); if (version_compare(PHP_VERSION, '8.0.0') < 0) { - $this->error('Cannot execute self-upgrade process. The minimum required PHP version required is 8.0.0, you have [' . PHP_VERSION . '].'); + $this->error('Cannot execute self-upgrade process. The minimum required PHP version required is 8.0.0, you have ['.PHP_VERSION.'].'); } $user = 'www-data'; @@ -55,7 +55,7 @@ class update extends Command $userDetails = posix_getpwuid(fileowner('public')); $user = $userDetails['name'] ?? 'www-data'; - if (!$this->confirm("Your webserver user has been detected as [{$user}]: is this correct?", true)) { + if (! $this->confirm("Your webserver user has been detected as [{$user}]: is this correct?", true)) { $user = $this->anticipate( 'Please enter the name of the user running your webserver process. This varies from system to system, but is generally "www-data", "nginx", or "apache".', [ @@ -71,7 +71,7 @@ class update extends Command $groupDetails = posix_getgrgid(filegroup('public')); $group = $groupDetails['name'] ?? 'www-data'; - if (!$this->confirm("Your webserver group has been detected as [{$group}]: is this correct?", true)) { + if (! $this->confirm("Your webserver group has been detected as [{$group}]: is this correct?", true)) { $group = $this->anticipate( 'Please enter the name of the group running your webserver process. Normally this is the same as your user.', [ @@ -85,24 +85,21 @@ class update extends Command ini_set('output_buffering', 0); - if (!$this->confirm('Are you sure you want to run the upgrade process for your Dashboard?')) { + if (! $this->confirm('Are you sure you want to run the upgrade process for your Dashboard?')) { return false; } - $bar = $this->output->createProgressBar(9); $bar->start(); - $this->withProgress($bar, function () { - $this->line("\$upgrader> git pull"); - $process = Process::fromShellCommandline("git pull"); + $this->line('$upgrader> git pull'); + $process = Process::fromShellCommandline('git pull'); $process->run(function ($type, $buffer) { $this->{$type === Process::ERR ? 'error' : 'line'}($buffer); }); }); - $this->withProgress($bar, function () { $this->line('$upgrader> php artisan down'); $this->call('down'); @@ -118,12 +115,12 @@ class update extends Command $this->withProgress($bar, function () { $command = ['composer', 'install', '--no-ansi']; - if (config('app.env') === 'production' && !config('app.debug')) { + if (config('app.env') === 'production' && ! config('app.debug')) { $command[] = '--optimize-autoloader'; $command[] = '--no-dev'; } - $this->line('$upgrader> ' . implode(' ', $command)); + $this->line('$upgrader> '.implode(' ', $command)); $process = new Process($command); $process->setTimeout(10 * 60); $process->run(function ($type, $buffer) { @@ -162,10 +159,9 @@ class update extends Command $this->newLine(); $this->info('Finished running upgrade.'); - }; + } } - protected function withProgress(ProgressBar $bar, Closure $callback) { $bar->clear(); diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index fe25d44c..28cdc1f1 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -20,7 +20,7 @@ class Kernel extends ConsoleKernel /** * Define the application's command schedule. * - * @param \Illuminate\Console\Scheduling\Schedule $schedule + * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) @@ -29,7 +29,7 @@ class Kernel extends ConsoleKernel //log cronjob activity $schedule->call(function () { - Storage::disk('logs')->put('cron.log' , "Last activity from cronjobs - " . now()); + Storage::disk('logs')->put('cron.log', 'Last activity from cronjobs - '.now()); })->everyMinute(); } @@ -40,7 +40,7 @@ class Kernel extends ConsoleKernel */ protected function commands() { - $this->load(__DIR__ . '/Commands'); + $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } diff --git a/app/Events/UserUpdateCreditsEvent.php b/app/Events/UserUpdateCreditsEvent.php index 7194bd8a..7548de60 100644 --- a/app/Events/UserUpdateCreditsEvent.php +++ b/app/Events/UserUpdateCreditsEvent.php @@ -3,11 +3,7 @@ namespace App\Events; use App\Models\User; -use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; -use Illuminate\Broadcasting\PresenceChannel; -use Illuminate\Broadcasting\PrivateChannel; -use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; @@ -23,7 +19,7 @@ class UserUpdateCreditsEvent /** * Create a new event instance. * - * @param User $user + * @param User $user */ public function __construct(User $user) { diff --git a/app/Http/Controllers/Admin/ActivityLogController.php b/app/Http/Controllers/Admin/ActivityLogController.php index 305639bc..2b061094 100644 --- a/app/Http/Controllers/Admin/ActivityLogController.php +++ b/app/Http/Controllers/Admin/ActivityLogController.php @@ -24,17 +24,16 @@ class ActivityLogController extends Controller $cronLogs = Storage::disk('logs')->exists('cron.log') ? Storage::disk('logs')->get('cron.log') : null; if ($request->input('search')) { - $query = Activity::whereHasMorph('causer' , [User::class] , function($query) use ($request) { - $query->where('name', 'like' , "%{$request->input('search')}%"); - })->orderBy('created_at' , 'desc')->paginate(20); + $query = Activity::whereHasMorph('causer', [User::class], function ($query) use ($request) { + $query->where('name', 'like', "%{$request->input('search')}%"); + })->orderBy('created_at', 'desc')->paginate(20); } else { - $query = Activity::orderBy('created_at' , 'desc')->paginate(20); + $query = Activity::orderBy('created_at', 'desc')->paginate(20); } - return view('admin.activitylogs.index')->with([ 'logs' => $query, - 'cronlogs' => $cronLogs + 'cronlogs' => $cronLogs, ]); } @@ -51,7 +50,7 @@ class ActivityLogController extends Controller /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return Response */ public function store(Request $request) @@ -84,7 +83,7 @@ class ActivityLogController extends Controller /** * Update the specified resource in storage. * - * @param Request $request + * @param Request $request * @param int $id * @return Response */ diff --git a/app/Http/Controllers/Admin/ApplicationApiController.php b/app/Http/Controllers/Admin/ApplicationApiController.php index 52827a60..b7168939 100644 --- a/app/Http/Controllers/Admin/ApplicationApiController.php +++ b/app/Http/Controllers/Admin/ApplicationApiController.php @@ -12,7 +12,6 @@ use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; -use Illuminate\Support\Str; class ApplicationApiController extends Controller { @@ -39,17 +38,17 @@ class ApplicationApiController extends Controller /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return RedirectResponse */ public function store(Request $request) { $request->validate([ - 'memo' => 'nullable|string|max:60' + 'memo' => 'nullable|string|max:60', ]); ApplicationApi::create([ - 'memo' => $request->input('memo') + 'memo' => $request->input('memo'), ]); return redirect()->route('admin.api.index')->with('success', __('api key created!')); @@ -58,7 +57,7 @@ class ApplicationApiController extends Controller /** * Display the specified resource. * - * @param ApplicationApi $applicationApi + * @param ApplicationApi $applicationApi * @return Response */ public function show(ApplicationApi $applicationApi) @@ -69,27 +68,27 @@ class ApplicationApiController extends Controller /** * Show the form for editing the specified resource. * - * @param ApplicationApi $applicationApi + * @param ApplicationApi $applicationApi * @return Application|Factory|View|Response */ public function edit(ApplicationApi $applicationApi) { - return view('admin.api.edit' , [ - 'applicationApi' => $applicationApi + return view('admin.api.edit', [ + 'applicationApi' => $applicationApi, ]); } /** * Update the specified resource in storage. * - * @param Request $request - * @param ApplicationApi $applicationApi + * @param Request $request + * @param ApplicationApi $applicationApi * @return RedirectResponse */ public function update(Request $request, ApplicationApi $applicationApi) { $request->validate([ - 'memo' => 'nullable|string|max:60' + 'memo' => 'nullable|string|max:60', ]); $applicationApi->update($request->all()); @@ -100,18 +99,20 @@ class ApplicationApiController extends Controller /** * Remove the specified resource from storage. * - * @param ApplicationApi $applicationApi + * @param ApplicationApi $applicationApi * @return RedirectResponse */ public function destroy(ApplicationApi $applicationApi) { $applicationApi->delete(); + return redirect()->back()->with('success', __('api key has been removed!')); } /** - * @param Request $request + * @param Request $request * @return JsonResponse|mixed + * * @throws Exception */ public function dataTable(Request $request) @@ -121,21 +122,21 @@ class ApplicationApiController extends Controller return datatables($query) ->addColumn('actions', function (ApplicationApi $apiKey) { return ' - -
- ' . csrf_field() . ' - ' . method_field("DELETE") . ' - + + + '.csrf_field().' + '.method_field('DELETE').' +
'; }) - ->editColumn('token' , function (ApplicationApi $apiKey) { + ->editColumn('token', function (ApplicationApi $apiKey) { return "{$apiKey->token}"; }) - ->editColumn('last_used' , function (ApplicationApi $apiKey) { + ->editColumn('last_used', function (ApplicationApi $apiKey) { return $apiKey->last_used ? $apiKey->last_used->diffForHumans() : ''; }) - ->rawColumns(['actions' , 'token']) + ->rawColumns(['actions', 'token']) ->make(); } } diff --git a/app/Http/Controllers/Admin/InvoiceController.php b/app/Http/Controllers/Admin/InvoiceController.php index 0ed1d45d..e3fc0bca 100644 --- a/app/Http/Controllers/Admin/InvoiceController.php +++ b/app/Http/Controllers/Admin/InvoiceController.php @@ -10,15 +10,14 @@ use ZipArchive; class InvoiceController extends Controller { - public function downloadAllInvoices() { $zip = new ZipArchive; $zip_safe_path = storage_path('invoices.zip'); $res = $zip->open($zip_safe_path, ZipArchive::CREATE | ZipArchive::OVERWRITE); $result = $this::rglob(storage_path('app/invoice/*')); - if ($res === TRUE) { - $zip->addFromString("1. Info.txt", __("Created at") . " " . now()->format("d.m.Y")); + if ($res === true) { + $zip->addFromString('1. Info.txt', __('Created at').' '.now()->format('d.m.Y')); foreach ($result as $file) { if (file_exists($file) && is_file($file)) { $zip->addFile($file, basename($file)); @@ -26,6 +25,7 @@ class InvoiceController extends Controller } $zip->close(); } + return response()->download($zip_safe_path); } @@ -37,9 +37,10 @@ class InvoiceController extends Controller public function rglob($pattern, $flags = 0) { $files = glob($pattern, $flags); - foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) { - $files = array_merge($files, $this::rglob($dir . '/' . basename($pattern), $flags)); + foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) { + $files = array_merge($files, $this::rglob($dir.'/'.basename($pattern), $flags)); } + return $files; } @@ -53,16 +54,15 @@ class InvoiceController extends Controller try { $query = Invoice::where('payment_id', '=', $id)->firstOrFail(); } catch (Throwable $e) { - return redirect()->back()->with("error", __("Error!")); + return redirect()->back()->with('error', __('Error!')); } - $invoice_path = storage_path('app/invoice/' . $query->invoice_user . '/' . $query->created_at->format("Y") . '/' . $query->invoice_name . '.pdf'); + $invoice_path = storage_path('app/invoice/'.$query->invoice_user.'/'.$query->created_at->format('Y').'/'.$query->invoice_name.'.pdf'); - if (!file_exists($invoice_path)) { - return redirect()->back()->with("error", __("Invoice does not exist on filesystem!")); + if (! file_exists($invoice_path)) { + return redirect()->back()->with('error', __('Invoice does not exist on filesystem!')); } - return response()->download($invoice_path); } } diff --git a/app/Http/Controllers/Admin/OverViewController.php b/app/Http/Controllers/Admin/OverViewController.php index f46f803d..baf51dea 100644 --- a/app/Http/Controllers/Admin/OverViewController.php +++ b/app/Http/Controllers/Admin/OverViewController.php @@ -2,18 +2,17 @@ namespace App\Http\Controllers\Admin; +use App\Classes\Pterodactyl; use App\Http\Controllers\Controller; use App\Models\Egg; use App\Models\Location; use App\Models\Nest; use App\Models\Node; use App\Models\Payment; -use App\Models\Server; -use App\Models\User; -use Illuminate\Support\Facades\Cache; -use App\Classes\Pterodactyl; use App\Models\Product; +use App\Models\Server; use App\Models\Ticket; +use App\Models\User; use Carbon\Carbon; class OverViewController extends Controller @@ -26,7 +25,7 @@ class OverViewController extends Controller $counters = collect(); //Set basic variables in the collection $counters->put('users', User::query()->count()); - $counters->put('credits', number_format(User::query()->where("role","!=","admin")->sum('credits'), 2, '.', '')); + $counters->put('credits', number_format(User::query()->where('role', '!=', 'admin')->sum('credits'), 2, '.', '')); $counters->put('payments', Payment::query()->count()); $counters->put('eggs', Egg::query()->count()); $counters->put('nests', Nest::query()->count()); @@ -53,7 +52,6 @@ class OverViewController extends Controller $counters['payments']['lastMonth']->timeStart = Carbon::today()->startOfMonth()->subMonth()->toDateString(); $counters['payments']['lastMonth']->timeEnd = Carbon::today()->endOfMonth()->subMonth()->toDateString(); - //Prepare subCollection 'taxPayments' $counters->put('taxPayments', collect()); //Get and save taxPayments from last 2 years for later filtering and looping @@ -65,33 +63,33 @@ class OverViewController extends Controller $counters['taxPayments']['thisYear']->timeEnd = Carbon::today()->toDateString(); $counters['taxPayments']['lastYear']->timeStart = Carbon::today()->startOfYear()->subYear()->toDateString(); $counters['taxPayments']['lastYear']->timeEnd = Carbon::today()->endOfYear()->subYear()->toDateString(); - + //Fill out variables for each currency separately - foreach($payments->where('created_at', '>=', Carbon::today()->startOfMonth()) as $payment){ + foreach ($payments->where('created_at', '>=', Carbon::today()->startOfMonth()) as $payment) { $paymentCurrency = $payment->currency_code; - if(!isset($counters['payments']['thisMonth'][$paymentCurrency])){ + if (! isset($counters['payments']['thisMonth'][$paymentCurrency])) { $counters['payments']['thisMonth']->put($paymentCurrency, collect()); $counters['payments']['thisMonth'][$paymentCurrency]->total = 0; $counters['payments']['thisMonth'][$paymentCurrency]->count = 0; } $counters['payments']['thisMonth'][$paymentCurrency]->total += $payment->total_price; - $counters['payments']['thisMonth'][$paymentCurrency]->count ++; + $counters['payments']['thisMonth'][$paymentCurrency]->count++; } - foreach($payments->where('created_at', '<', Carbon::today()->startOfMonth()) as $payment){ + foreach ($payments->where('created_at', '<', Carbon::today()->startOfMonth()) as $payment) { $paymentCurrency = $payment->currency_code; - if(!isset($counters['payments']['lastMonth'][$paymentCurrency])){ + if (! isset($counters['payments']['lastMonth'][$paymentCurrency])) { $counters['payments']['lastMonth']->put($paymentCurrency, collect()); $counters['payments']['lastMonth'][$paymentCurrency]->total = 0; $counters['payments']['lastMonth'][$paymentCurrency]->count = 0; } $counters['payments']['lastMonth'][$paymentCurrency]->total += $payment->total_price; - $counters['payments']['lastMonth'][$paymentCurrency]->count ++; + $counters['payments']['lastMonth'][$paymentCurrency]->count++; } $counters['payments']->total = Payment::query()->count(); - foreach($taxPayments->where('created_at', '>=', Carbon::today()->startOfYear()->subYear()) as $taxPayment){ + foreach ($taxPayments->where('created_at', '>=', Carbon::today()->startOfYear()->subYear()) as $taxPayment) { $paymentCurrency = $payment->currency_code; - if(!isset($counters['taxPayments']['thisYear'][$paymentCurrency])){ + if (! isset($counters['taxPayments']['thisYear'][$paymentCurrency])) { $counters['taxPayments']['thisYear']->put($paymentCurrency, collect()); $counters['taxPayments']['thisYear'][$paymentCurrency]->total = 0; $counters['taxPayments']['thisYear'][$paymentCurrency]->count = 0; @@ -99,13 +97,13 @@ class OverViewController extends Controller $counters['taxPayments']['thisYear'][$paymentCurrency]->taxes = 0; } $counters['taxPayments']['thisYear'][$paymentCurrency]->total += $taxPayment->total_price; - $counters['taxPayments']['thisYear'][$paymentCurrency]->count ++; + $counters['taxPayments']['thisYear'][$paymentCurrency]->count++; $counters['taxPayments']['thisYear'][$paymentCurrency]->price += $taxPayment->price; $counters['taxPayments']['thisYear'][$paymentCurrency]->taxes += $taxPayment->tax_value; } - foreach($taxPayments->where('created_at', '<', Carbon::today()->startOfYear()) as $taxPayment){ + foreach ($taxPayments->where('created_at', '<', Carbon::today()->startOfYear()) as $taxPayment) { $paymentCurrency = $payment->currency_code; - if(!isset($counters['taxPayments']['lastYear'][$paymentCurrency])){ + if (! isset($counters['taxPayments']['lastYear'][$paymentCurrency])) { $counters['taxPayments']['lastYear']->put($paymentCurrency, collect()); $counters['taxPayments']['lastYear'][$paymentCurrency]->total = 0; $counters['taxPayments']['lastYear'][$paymentCurrency]->count = 0; @@ -113,29 +111,29 @@ class OverViewController extends Controller $counters['taxPayments']['lastYear'][$paymentCurrency]->taxes = 0; } $counters['taxPayments']['lastYear'][$paymentCurrency]->total += $taxPayment->total_price; - $counters['taxPayments']['lastYear'][$paymentCurrency]->count ++; + $counters['taxPayments']['lastYear'][$paymentCurrency]->count++; $counters['taxPayments']['lastYear'][$paymentCurrency]->price += $taxPayment->price; $counters['taxPayments']['lastYear'][$paymentCurrency]->taxes += $taxPayment->tax_value; } $lastEgg = Egg::query()->latest('updated_at')->first(); $syncLastUpdate = $lastEgg ? $lastEgg->updated_at->isoFormat('LLL') : __('unknown'); - - //Get node information and prepare collection $pteroNodeIds = []; - foreach(Pterodactyl::getNodes() as $pteroNode){ + foreach (Pterodactyl::getNodes() as $pteroNode) { array_push($pteroNodeIds, $pteroNode['attributes']['id']); } $nodes = collect(); - foreach($DBnodes = Node::query()->get() as $DBnode){ //gets all node information and prepares the structure + foreach ($DBnodes = Node::query()->get() as $DBnode) { //gets all node information and prepares the structure $nodeId = $DBnode['id']; - if(!in_array($nodeId, $pteroNodeIds)) continue; //Check if node exists on pterodactyl too, if not, skip + if (! in_array($nodeId, $pteroNodeIds)) { + continue; + } //Check if node exists on pterodactyl too, if not, skip $nodes->put($nodeId, collect()); $nodes[$nodeId]->name = $DBnode['name']; $pteroNode = Pterodactyl::getNode($nodeId); - $nodes[$nodeId]->usagePercent = round(max($pteroNode['allocated_resources']['memory']/($pteroNode['memory']*($pteroNode['memory_overallocate']+100)/100), $pteroNode['allocated_resources']['disk']/($pteroNode['disk']*($pteroNode['disk_overallocate']+100)/100))*100, 2); + $nodes[$nodeId]->usagePercent = round(max($pteroNode['allocated_resources']['memory'] / ($pteroNode['memory'] * ($pteroNode['memory_overallocate'] + 100) / 100), $pteroNode['allocated_resources']['disk'] / ($pteroNode['disk'] * ($pteroNode['disk_overallocate'] + 100) / 100)) * 100, 2); $counters['totalUsagePercent'] += $nodes[$nodeId]->usagePercent; $nodes[$nodeId]->totalServers = 0; @@ -143,31 +141,29 @@ class OverViewController extends Controller $nodes[$nodeId]->totalEarnings = 0; $nodes[$nodeId]->activeEarnings = 0; } - $counters['totalUsagePercent'] = ($DBnodes->count())?round($counters['totalUsagePercent']/$DBnodes->count(), 2):0; + $counters['totalUsagePercent'] = ($DBnodes->count()) ? round($counters['totalUsagePercent'] / $DBnodes->count(), 2) : 0; - foreach(Pterodactyl::getServers() as $server){ //gets all servers from Pterodactyl and calculates total of credit usage for each node separately + total + foreach (Pterodactyl::getServers() as $server) { //gets all servers from Pterodactyl and calculates total of credit usage for each node separately + total $nodeId = $server['attributes']['node']; - - if($CPServer = Server::query()->where('pterodactyl_id', $server['attributes']['id'])->first()){ + + if ($CPServer = Server::query()->where('pterodactyl_id', $server['attributes']['id'])->first()) { $price = Product::query()->where('id', $CPServer->product_id)->first()->price; - if (!$CPServer->suspended){ + if (! $CPServer->suspended) { $counters['earnings']->active += $price; - $counters['servers']->active ++; + $counters['servers']->active++; $nodes[$nodeId]->activeEarnings += $price; - $nodes[$nodeId]->activeServers ++; + $nodes[$nodeId]->activeServers++; } $counters['earnings']->total += $price; - $counters['servers']->total ++; + $counters['servers']->total++; $nodes[$nodeId]->totalEarnings += $price; - $nodes[$nodeId]->totalServers ++; + $nodes[$nodeId]->totalServers++; } } - - //Get latest tickets $tickets = collect(); - foreach(Ticket::query()->latest()->take(5)->get() as $ticket){ + foreach (Ticket::query()->latest()->take(5)->get() as $ticket) { $tickets->put($ticket->ticket_id, collect()); $tickets[$ticket->ticket_id]->title = $ticket->title; $user = User::query()->where('id', $ticket->user_id)->first(); @@ -192,14 +188,14 @@ class OverViewController extends Controller } return view('admin.overview.index', [ - 'counters' => $counters, - 'nodes' => $nodes, + 'counters' => $counters, + 'nodes' => $nodes, 'syncLastUpdate' => $syncLastUpdate, - 'deletedNodesPresent'=> ($DBnodes->count() != count($pteroNodeIds))?true:false, - 'perPageLimit' => ($counters['servers']->total != Server::query()->count())?true:false, - 'tickets' => $tickets + 'deletedNodesPresent' => ($DBnodes->count() != count($pteroNodeIds)) ? true : false, + 'perPageLimit' => ($counters['servers']->total != Server::query()->count()) ? true : false, + 'tickets' => $tickets, ]); - } + } /** * @description Sync locations,nodes,nests,eggs with the linked pterodactyl panel diff --git a/app/Http/Controllers/Admin/PaymentController.php b/app/Http/Controllers/Admin/PaymentController.php index 30f03085..c109d8ef 100644 --- a/app/Http/Controllers/Admin/PaymentController.php +++ b/app/Http/Controllers/Admin/PaymentController.php @@ -4,14 +4,13 @@ namespace App\Http\Controllers\Admin; use App\Events\UserUpdateCreditsEvent; use App\Http\Controllers\Controller; -use App\Models\InvoiceSettings; use App\Models\PartnerDiscount; use App\Models\Payment; -use App\Models\ShopProduct; use App\Models\Settings; +use App\Models\ShopProduct; use App\Models\User; -use App\Notifications\InvoiceNotification; use App\Notifications\ConfirmPaymentNotification; +use App\Notifications\InvoiceNotification; use Exception; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; @@ -36,41 +35,39 @@ use PayPalHttp\HttpException; use Stripe\Stripe; use Symfony\Component\Intl\Currencies; - class PaymentController extends Controller { - /** * @return Application|Factory|View */ public function index() { return view('admin.payments.index')->with([ - 'payments' => Payment::paginate(15) + 'payments' => Payment::paginate(15), ]); } /** - * @param Request $request - * @param ShopProduct $shopProduct + * @param Request $request + * @param ShopProduct $shopProduct * @return Application|Factory|View */ public function checkOut(Request $request, ShopProduct $shopProduct) { return view('store.checkout')->with([ - 'product' => $shopProduct, - 'discountpercent' => PartnerDiscount::getDiscount(), - 'discountvalue' => PartnerDiscount::getDiscount() * $shopProduct->price/100, - 'discountedprice' => $shopProduct->getPriceAfterDiscount(), - 'taxvalue' => $shopProduct->getTaxValue(), - 'taxpercent' => $shopProduct->getTaxPercent(), - 'total' => $shopProduct->getTotalPrice() + 'product' => $shopProduct, + 'discountpercent' => PartnerDiscount::getDiscount(), + 'discountvalue' => PartnerDiscount::getDiscount() * $shopProduct->price / 100, + 'discountedprice' => $shopProduct->getPriceAfterDiscount(), + 'taxvalue' => $shopProduct->getTaxValue(), + 'taxpercent' => $shopProduct->getTaxPercent(), + 'total' => $shopProduct->getTotalPrice(), ]); } /** - * @param Request $request - * @param ShopProduct $shopProduct + * @param Request $request + * @param ShopProduct $shopProduct * @return RedirectResponse */ public function PaypalPay(Request $request, ShopProduct $shopProduct) @@ -78,43 +75,40 @@ class PaymentController extends Controller $request = new OrdersCreateRequest(); $request->prefer('return=representation'); $request->body = [ - "intent" => "CAPTURE", - "purchase_units" => [ + 'intent' => 'CAPTURE', + 'purchase_units' => [ [ - "reference_id" => uniqid(), - "description" => $shopProduct->display . (PartnerDiscount::getDiscount()?(" (" . __('Discount') . " " . PartnerDiscount::getDiscount() . '%)'):""), - "amount" => [ - "value" => $shopProduct->getTotalPrice(), + 'reference_id' => uniqid(), + 'description' => $shopProduct->display.(PartnerDiscount::getDiscount() ? (' ('.__('Discount').' '.PartnerDiscount::getDiscount().'%)') : ''), + 'amount' => [ + 'value' => $shopProduct->getTotalPrice(), 'currency_code' => strtoupper($shopProduct->currency_code), 'breakdown' => [ - 'item_total' => - [ + 'item_total' => [ 'currency_code' => strtoupper($shopProduct->currency_code), 'value' => $shopProduct->getPriceAfterDiscount(), ], - 'tax_total' => - [ + 'tax_total' => [ 'currency_code' => strtoupper($shopProduct->currency_code), 'value' => $shopProduct->getTaxValue(), - ] - ] - ] - ] + ], + ], + ], + ], + ], + 'application_context' => [ + 'cancel_url' => route('payment.Cancel'), + 'return_url' => route('payment.PaypalSuccess', ['product' => $shopProduct->id]), + 'brand_name' => config('app.name', 'Laravel'), + 'shipping_preference' => 'NO_SHIPPING', ], - "application_context" => [ - "cancel_url" => route('payment.Cancel'), - "return_url" => route('payment.PaypalSuccess', ['product' => $shopProduct->id]), - 'brand_name' => config('app.name', 'Laravel'), - 'shipping_preference' => 'NO_SHIPPING' - ] - ]; - try { // Call API with your client and get a response for your call $response = $this->getPayPalClient()->execute($request); + return redirect()->away($response->result->links[1]->href); // If call returns body in response, you can get the deserialized version from the result attribute of the response @@ -141,7 +135,7 @@ class PaymentController extends Controller */ protected function getPaypalClientId() { - return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID") : config("SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID"); + return env('APP_ENV') == 'local' ? config('SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID') : config('SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID'); } /** @@ -149,11 +143,11 @@ class PaymentController extends Controller */ protected function getPaypalClientSecret() { - return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET") : config("SETTINGS::PAYMENTS:PAYPAL:SECRET"); + return env('APP_ENV') == 'local' ? config('SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET') : config('SETTINGS::PAYMENTS:PAYPAL:SECRET'); } /** - * @param Request $laravelRequest + * @param Request $laravelRequest */ public function PaypalSuccess(Request $laravelRequest) { @@ -178,26 +172,25 @@ class PaymentController extends Controller } //update User with bought item - if ($shopProduct->type=="Credits") { + if ($shopProduct->type == 'Credits') { $user->increment('credits', $shopProduct->quantity); - }elseif ($shopProduct->type=="Server slots"){ + } elseif ($shopProduct->type == 'Server slots') { $user->increment('server_limit', $shopProduct->quantity); } //give referral commission always - if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both") && $shopProduct->type=="Credits" && config("SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION") == "true"){ - if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){ + if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits' && config('SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION') == 'true') { + if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) { $ref_user = User::findOrFail($ref_user->referral_id); - $increment = number_format($shopProduct->quantity*(PartnerDiscount::getCommission($ref_user->id))/100,0,"",""); + $increment = number_format($shopProduct->quantity * (PartnerDiscount::getCommission($ref_user->id)) / 100, 0, '', ''); $ref_user->increment('credits', $increment); //LOGS REFERRALS IN THE ACTIVITY LOG activity() ->performedOn($user) ->causedBy($ref_user) - ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')'); + ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')'); } - } //update role give Referral-reward @@ -205,21 +198,19 @@ class PaymentController extends Controller $user->update(['role' => 'client']); //give referral commission only on first purchase - if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both") && $shopProduct->type=="Credits" && config("SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION") == "false"){ - if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){ + if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits' && config('SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION') == 'false') { + if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) { $ref_user = User::findOrFail($ref_user->referral_id); - $increment = number_format($shopProduct->quantity*(PartnerDiscount::getCommission($ref_user->id))/100,0,"",""); + $increment = number_format($shopProduct->quantity * (PartnerDiscount::getCommission($ref_user->id)) / 100, 0, '', ''); $ref_user->increment('credits', $increment); //LOGS REFERRALS IN THE ACTIVITY LOG activity() ->performedOn($user) ->causedBy($ref_user) - ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')'); + ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')'); } - } - } //store payment @@ -230,7 +221,7 @@ class PaymentController extends Controller 'type' => $shopProduct->type, 'status' => 'paid', 'amount' => $shopProduct->quantity, - 'price' => $shopProduct->price - ($shopProduct->price*PartnerDiscount::getDiscount()/100), + 'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100), 'tax_value' => $shopProduct->getTaxValue(), 'tax_percent' => $shopProduct->getTaxPercent(), 'total_price' => $shopProduct->getTotalPrice(), @@ -238,7 +229,6 @@ class PaymentController extends Controller 'shop_item_product_id' => $shopProduct->id, ]); - event(new UserUpdateCreditsEvent($user)); //only create invoice if SETTINGS::INVOICE:ENABLED is true @@ -246,12 +236,10 @@ class PaymentController extends Controller $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code); } - //redirect back to home return redirect()->route('home')->with('success', __('Your credit balance has been increased!')); } - // If call returns body in response, you can get the deserialized version from the result attribute of the response if (env('APP_ENV') == 'local') { dd($response); @@ -268,9 +256,8 @@ class PaymentController extends Controller } } - /** - * @param Request $request + * @param Request $request */ public function Cancel(Request $request) { @@ -278,22 +265,21 @@ class PaymentController extends Controller } /** - * @param Request $request - * @param ShopProduct $shopProduct + * @param Request $request + * @param ShopProduct $shopProduct * @return RedirectResponse */ public function StripePay(Request $request, ShopProduct $shopProduct) { $stripeClient = $this->getStripeClient(); - $request = $stripeClient->checkout->sessions->create([ 'line_items' => [ [ 'price_data' => [ 'currency' => $shopProduct->currency_code, 'product_data' => [ - 'name' => $shopProduct->display . (PartnerDiscount::getDiscount()?(" (" . __('Discount') . " " . PartnerDiscount::getDiscount() . '%)'):""), + 'name' => $shopProduct->display.(PartnerDiscount::getDiscount() ? (' ('.__('Discount').' '.PartnerDiscount::getDiscount().'%)') : ''), 'description' => $shopProduct->description, ], 'unit_amount_decimal' => round($shopProduct->getPriceAfterDiscount() * 100, 2), @@ -305,27 +291,25 @@ class PaymentController extends Controller 'currency' => $shopProduct->currency_code, 'product_data' => [ 'name' => __('Tax'), - 'description' => $shopProduct->getTaxPercent() . "%", + 'description' => $shopProduct->getTaxPercent().'%', ], 'unit_amount_decimal' => round($shopProduct->getTaxValue(), 2) * 100, ], 'quantity' => 1, - ] + ], ], 'mode' => 'payment', - "payment_method_types" => str_getcsv(config("SETTINGS::PAYMENTS:STRIPE:METHODS")), - 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]) . '&session_id={CHECKOUT_SESSION_ID}', + 'payment_method_types' => str_getcsv(config('SETTINGS::PAYMENTS:STRIPE:METHODS')), + 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]).'&session_id={CHECKOUT_SESSION_ID}', 'cancel_url' => route('payment.Cancel'), ]); - - return redirect($request->url, 303); } /** - * @param Request $request + * @param Request $request */ public function StripeSuccess(Request $request) { @@ -346,9 +330,7 @@ class PaymentController extends Controller $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count(); // check if payment is 100% completed and payment does not exist in db already - if ($paymentSession->status == "complete" && $paymentIntent->status == "succeeded" && $paymentDbEntry == 0) { - - + if ($paymentSession->status == 'complete' && $paymentIntent->status == 'succeeded' && $paymentDbEntry == 0) { //update server limit if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) { @@ -358,9 +340,9 @@ class PaymentController extends Controller } //update User with bought item - if ($shopProduct->type=="Credits") { + if ($shopProduct->type == 'Credits') { $user->increment('credits', $shopProduct->quantity); - }elseif ($shopProduct->type=="Server slots"){ + } elseif ($shopProduct->type == 'Server slots') { $user->increment('server_limit', $shopProduct->quantity); } @@ -368,21 +350,19 @@ class PaymentController extends Controller if ($user->role == 'member') { $user->update(['role' => 'client']); - if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both") && $shopProduct->type=="Credits"){ - if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){ + if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits') { + if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) { $ref_user = User::findOrFail($ref_user->referral_id); - $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"",""); + $increment = number_format($shopProduct->quantity / 100 * config('SETTINGS::REFERRAL:PERCENTAGE'), 0, '', ''); $ref_user->increment('credits', $increment); //LOGS REFERRALS IN THE ACTIVITY LOG activity() ->performedOn($user) ->causedBy($ref_user) - ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')'); + ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')'); } - } - } //store paid payment @@ -393,7 +373,7 @@ class PaymentController extends Controller 'type' => $shopProduct->type, 'status' => 'paid', 'amount' => $shopProduct->quantity, - 'price' => $shopProduct->price - ($shopProduct->price*PartnerDiscount::getDiscount()/100), + 'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100), 'tax_value' => $shopProduct->getTaxValue(), 'total_price' => $shopProduct->getTotalPrice(), 'tax_percent' => $shopProduct->getTaxPercent(), @@ -414,7 +394,7 @@ class PaymentController extends Controller //redirect back to home return redirect()->route('home')->with('success', __('Your credit balance has been increased!')); } else { - if ($paymentIntent->status == "processing") { + if ($paymentIntent->status == 'processing') { //store processing payment $payment = Payment::create([ @@ -440,7 +420,7 @@ class PaymentController extends Controller //redirect back to home return redirect()->route('home')->with('success', __('Your payment is being processed!')); } - if ($paymentDbEntry == 0 && $paymentIntent->status != "processing") { + if ($paymentDbEntry == 0 && $paymentIntent->status != 'processing') { $stripeClient->paymentIntents->cancel($paymentIntent->id); //redirect back to home @@ -460,7 +440,7 @@ class PaymentController extends Controller } /** - * @param Request $request + * @param Request $request */ protected function handleStripePaymentSuccessHook($paymentIntent) { @@ -471,7 +451,6 @@ class PaymentController extends Controller if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') { - //update server limit if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) { if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) { @@ -479,9 +458,9 @@ class PaymentController extends Controller } } //update User with bought item - if ($shopProduct->type=="Credits") { + if ($shopProduct->type == 'Credits') { $user->increment('credits', $shopProduct->quantity); - }elseif ($shopProduct->type=="Server slots"){ + } elseif ($shopProduct->type == 'Server slots') { $user->increment('server_limit', $shopProduct->quantity); } @@ -489,21 +468,19 @@ class PaymentController extends Controller if ($user->role == 'member') { $user->update(['role' => 'client']); - if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both")&& $shopProduct->type=="Credits"){ - if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){ + if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits') { + if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) { $ref_user = User::findOrFail($ref_user->referral_id); - $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"",""); + $increment = number_format($shopProduct->quantity / 100 * config('SETTINGS::REFERRAL:PERCENTAGE'), 0, '', ''); $ref_user->increment('credits', $increment); //LOGS REFERRALS IN THE ACTIVITY LOG activity() ->performedOn($user) ->causedBy($ref_user) - ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')'); + ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')'); } - } - } //update payment db entry status @@ -524,7 +501,7 @@ class PaymentController extends Controller } /** - * @param Request $request + * @param Request $request */ public function StripeWebhooks(Request $request) { @@ -556,7 +533,7 @@ class PaymentController extends Controller $this->handleStripePaymentSuccessHook($paymentIntent); break; default: - echo 'Received unknown event type ' . $event->type; + echo 'Received unknown event type '.$event->type; } } @@ -574,8 +551,8 @@ class PaymentController extends Controller protected function getStripeSecret() { return env('APP_ENV') == 'local' - ? config("SETTINGS::PAYMENTS:STRIPE:TEST_SECRET") - : config("SETTINGS::PAYMENTS:STRIPE:SECRET"); + ? config('SETTINGS::PAYMENTS:STRIPE:TEST_SECRET') + : config('SETTINGS::PAYMENTS:STRIPE:SECRET'); } /** @@ -584,31 +561,29 @@ class PaymentController extends Controller protected function getStripeEndpointSecret() { return env('APP_ENV') == 'local' - ? config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET") - : config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET"); + ? config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET') + : config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET'); } - protected function createInvoice($user, $payment, $paymentStatus, $currencyCode) { $shopProduct = ShopProduct::where('id', $payment->shop_item_product_id)->first(); //create invoice - $lastInvoiceID = \App\Models\Invoice::where("invoice_name", "like", "%" . now()->format('mY') . "%")->count("id"); + $lastInvoiceID = \App\Models\Invoice::where('invoice_name', 'like', '%'.now()->format('mY').'%')->count('id'); $newInvoiceID = $lastInvoiceID + 1; $logoPath = storage_path('app/public/logo.png'); $seller = new Party([ - 'name' => config("SETTINGS::INVOICE:COMPANY_NAME"), - 'phone' => config("SETTINGS::INVOICE:COMPANY_PHONE"), - 'address' => config("SETTINGS::INVOICE:COMPANY_ADDRESS"), - 'vat' => config("SETTINGS::INVOICE:COMPANY_VAT"), + 'name' => config('SETTINGS::INVOICE:COMPANY_NAME'), + 'phone' => config('SETTINGS::INVOICE:COMPANY_PHONE'), + 'address' => config('SETTINGS::INVOICE:COMPANY_ADDRESS'), + 'vat' => config('SETTINGS::INVOICE:COMPANY_VAT'), 'custom_fields' => [ - 'E-Mail' => config("SETTINGS::INVOICE:COMPANY_MAIL"), - "Web" => config("SETTINGS::INVOICE:COMPANY_WEBSITE") + 'E-Mail' => config('SETTINGS::INVOICE:COMPANY_MAIL'), + 'Web' => config('SETTINGS::INVOICE:COMPANY_WEBSITE'), ], ]); - $customer = new Buyer([ 'name' => $user->name, 'custom_fields' => [ @@ -621,14 +596,13 @@ class PaymentController extends Controller ->pricePerUnit($shopProduct->price); $notes = [ - __("Payment method") . ": " . $payment->payment_method, + __('Payment method').': '.$payment->payment_method, ]; - $notes = implode("
", $notes); - + $notes = implode('
', $notes); $invoice = Invoice::make() ->template('controlpanel') - ->name(__("Invoice")) + ->name(__('Invoice')) ->buyer($customer) ->seller($seller) ->discountByPercent(PartnerDiscount::getDiscount()) @@ -637,9 +611,9 @@ class PaymentController extends Controller ->addItem($item) ->status(__($paymentStatus)) ->series(now()->format('mY')) - ->delimiter("-") + ->delimiter('-') ->sequence($newInvoiceID) - ->serialNumberFormat(config("SETTINGS::INVOICE:PREFIX") . '{DELIMITER}{SERIES}{SEQUENCE}') + ->serialNumberFormat(config('SETTINGS::INVOICE:PREFIX').'{DELIMITER}{SERIES}{SEQUENCE}') ->currencyCode($currencyCode) ->currencySymbol(Currencies::getSymbol($currencyCode)) ->notes($notes); @@ -649,10 +623,9 @@ class PaymentController extends Controller } //Save the invoice in "storage\app\invoice\USER_ID\YEAR" - $invoice->filename = $invoice->getSerialNumber() . '.pdf'; + $invoice->filename = $invoice->getSerialNumber().'.pdf'; $invoice->render(); - Storage::disk("local")->put("invoice/" . $user->id . "/" . now()->format('Y') . "/" . $invoice->filename, $invoice->output); - + Storage::disk('local')->put('invoice/'.$user->id.'/'.now()->format('Y').'/'.$invoice->filename, $invoice->output); \App\Models\Invoice::create([ 'invoice_user' => $user->id, @@ -666,6 +639,7 @@ class PaymentController extends Controller /** * @return JsonResponse|mixed + * * @throws Exception */ public function dataTable() @@ -674,8 +648,8 @@ class PaymentController extends Controller return datatables($query) ->editColumn('user', function (Payment $payment) { - return - ($payment->user)?''.$payment->user->name.'':__('Unknown user'); + return + ($payment->user) ? ''.$payment->user->name.'' : __('Unknown user'); }) ->editColumn('price', function (Payment $payment) { return $payment->formatToCurrency($payment->price); @@ -684,7 +658,7 @@ class PaymentController extends Controller return $payment->formatToCurrency($payment->tax_value); }) ->editColumn('tax_percent', function (Payment $payment) { - return $payment->tax_percent . ' %'; + return $payment->tax_percent.' %'; }) ->editColumn('total_price', function (Payment $payment) { return $payment->formatToCurrency($payment->total_price); @@ -694,9 +668,9 @@ class PaymentController extends Controller return $payment->created_at ? $payment->created_at->diffForHumans() : ''; }) ->addColumn('actions', function (Payment $payment) { - return ''; + return ''; }) ->rawColumns(['actions', 'user']) ->make(true); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Admin/ProductController.php b/app/Http/Controllers/Admin/ProductController.php index 6b855f9f..c90c3c5f 100644 --- a/app/Http/Controllers/Admin/ProductController.php +++ b/app/Http/Controllers/Admin/ProductController.php @@ -6,7 +6,6 @@ use App\Http\Controllers\Controller; use App\Models\Location; use App\Models\Nest; use App\Models\Product; -use App\Models\Settings; use Exception; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; @@ -52,33 +51,33 @@ class ProductController extends Controller /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return RedirectResponse */ public function store(Request $request) { $request->validate([ - "name" => "required|max:30", - "price" => "required|numeric|max:1000000|min:0", - "memory" => "required|numeric|max:1000000|min:5", - "cpu" => "required|numeric|max:1000000|min:0", - "swap" => "required|numeric|max:1000000|min:0", - "description" => "required|string|max:191", - "disk" => "required|numeric|max:1000000|min:5", - "minimum_credits" => "required|numeric|max:1000000|min:-1", - "io" => "required|numeric|max:1000000|min:0", - "databases" => "required|numeric|max:1000000|min:0", - "backups" => "required|numeric|max:1000000|min:0", - "allocations" => "required|numeric|max:1000000|min:0", - "nodes.*" => "required|exists:nodes,id", - "eggs.*" => "required|exists:eggs,id", - "disabled" => "nullable", + 'name' => 'required|max:30', + 'price' => 'required|numeric|max:1000000|min:0', + 'memory' => 'required|numeric|max:1000000|min:5', + 'cpu' => 'required|numeric|max:1000000|min:0', + 'swap' => 'required|numeric|max:1000000|min:0', + 'description' => 'required|string|max:191', + 'disk' => 'required|numeric|max:1000000|min:5', + 'minimum_credits' => 'required|numeric|max:1000000|min:-1', + 'io' => 'required|numeric|max:1000000|min:0', + 'databases' => 'required|numeric|max:1000000|min:0', + 'backups' => 'required|numeric|max:1000000|min:0', + 'allocations' => 'required|numeric|max:1000000|min:0', + 'nodes.*' => 'required|exists:nodes,id', + 'eggs.*' => 'required|exists:eggs,id', + 'disabled' => 'nullable', ]); - $disabled = !is_null($request->input('disabled')); + $disabled = ! is_null($request->input('disabled')); $product = Product::create(array_merge($request->all(), ['disabled' => $disabled])); - #link nodes and eggs + //link nodes and eggs $product->eggs()->attach($request->input('eggs')); $product->nodes()->attach($request->input('nodes')); @@ -88,21 +87,21 @@ class ProductController extends Controller /** * Display the specified resource. * - * @param Product $product + * @param Product $product * @return Application|Factory|View */ public function show(Product $product) { return view('admin.products.show', [ 'product' => $product, - 'minimum_credits' => config("SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER"), + 'minimum_credits' => config('SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER'), ]); } /** * Show the form for editing the specified resource. * - * @param Product $product + * @param Product $product * @return Application|Factory|View */ public function edit(Product $product) @@ -117,34 +116,34 @@ class ProductController extends Controller /** * Update the specified resource in storage. * - * @param Request $request - * @param Product $product + * @param Request $request + * @param Product $product * @return RedirectResponse */ public function update(Request $request, Product $product): RedirectResponse { $request->validate([ - "name" => "required|max:30", - "price" => "required|numeric|max:1000000|min:0", - "memory" => "required|numeric|max:1000000|min:5", - "cpu" => "required|numeric|max:1000000|min:0", - "swap" => "required|numeric|max:1000000|min:0", - "description" => "required|string|max:191", - "disk" => "required|numeric|max:1000000|min:5", - "io" => "required|numeric|max:1000000|min:0", - "minimum_credits" => "required|numeric|max:1000000|min:-1", - "databases" => "required|numeric|max:1000000|min:0", - "backups" => "required|numeric|max:1000000|min:0", - "allocations" => "required|numeric|max:1000000|min:0", - "nodes.*" => "required|exists:nodes,id", - "eggs.*" => "required|exists:eggs,id", - "disabled" => "nullable", + 'name' => 'required|max:30', + 'price' => 'required|numeric|max:1000000|min:0', + 'memory' => 'required|numeric|max:1000000|min:5', + 'cpu' => 'required|numeric|max:1000000|min:0', + 'swap' => 'required|numeric|max:1000000|min:0', + 'description' => 'required|string|max:191', + 'disk' => 'required|numeric|max:1000000|min:5', + 'io' => 'required|numeric|max:1000000|min:0', + 'minimum_credits' => 'required|numeric|max:1000000|min:-1', + 'databases' => 'required|numeric|max:1000000|min:0', + 'backups' => 'required|numeric|max:1000000|min:0', + 'allocations' => 'required|numeric|max:1000000|min:0', + 'nodes.*' => 'required|exists:nodes,id', + 'eggs.*' => 'required|exists:eggs,id', + 'disabled' => 'nullable', ]); - $disabled = !is_null($request->input('disabled')); + $disabled = ! is_null($request->input('disabled')); $product->update(array_merge($request->all(), ['disabled' => $disabled])); - #link nodes and eggs + //link nodes and eggs $product->eggs()->detach(); $product->nodes()->detach(); $product->eggs()->attach($request->input('eggs')); @@ -154,13 +153,13 @@ class ProductController extends Controller } /** - * @param Request $request - * @param Product $product + * @param Request $request + * @param Product $product * @return RedirectResponse */ public function disable(Request $request, Product $product) { - $product->update(['disabled' => !$product->disabled]); + $product->update(['disabled' => ! $product->disabled]); return redirect()->route('admin.products.index')->with('success', 'Product has been updated!'); } @@ -168,7 +167,7 @@ class ProductController extends Controller /** * Remove the specified resource from storage. * - * @param Product $product + * @param Product $product * @return RedirectResponse */ public function destroy(Product $product) @@ -179,12 +178,13 @@ class ProductController extends Controller } $product->delete(); + return redirect()->back()->with('success', __('Product has been removed!')); } - /** * @return JsonResponse|mixed + * * @throws Exception|Exception */ public function dataTable() @@ -194,14 +194,14 @@ class ProductController extends Controller return datatables($query) ->addColumn('actions', function (Product $product) { return ' - - - + + + -
- ' . csrf_field() . ' - ' . method_field("DELETE") . ' - + + '.csrf_field().' + '.method_field('DELETE').' +
'; }) @@ -216,14 +216,15 @@ class ProductController extends Controller return $product->eggs()->count(); }) ->addColumn('disabled', function (Product $product) { - $checked = $product->disabled == false ? "checked" : ""; + $checked = $product->disabled == false ? 'checked' : ''; + return ' -
- ' . csrf_field() . ' - ' . method_field("PATCH") . ' + + '.csrf_field().' + '.method_field('PATCH').'
- - + +
'; diff --git a/app/Http/Controllers/Admin/ServerController.php b/app/Http/Controllers/Admin/ServerController.php index a34b097b..2be3b51d 100644 --- a/app/Http/Controllers/Admin/ServerController.php +++ b/app/Http/Controllers/Admin/ServerController.php @@ -3,10 +3,8 @@ namespace App\Http\Controllers\Admin; use App\Classes\Pterodactyl; -use App\Classes\PterodactylWrapper; use App\Http\Controllers\Controller; use App\Models\Server; -use App\Models\Settings; use Exception; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; @@ -41,7 +39,7 @@ class ServerController extends Controller /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return Response */ public function store(Request $request) @@ -52,7 +50,7 @@ class ServerController extends Controller /** * Display the specified resource. * - * @param Server $server + * @param Server $server * @return Response */ public function show(Server $server) @@ -63,28 +61,27 @@ class ServerController extends Controller /** * Show the form for editing the specified resource. * - * @param Server $server + * @param Server $server * @return Response */ - public function edit(Server $server) { return view('admin.servers.edit')->with([ - 'server' => $server + 'server' => $server, ]); } /** * Update the specified resource in storage. * - * @param Request $request - * @param Server $server + * @param Request $request + * @param Server $server * @return Response */ public function update(Request $request, Server $server) { $request->validate([ - "identifier" => "required|string", + 'identifier' => 'required|string', ]); $server->update($request->all()); @@ -95,27 +92,28 @@ class ServerController extends Controller /** * Remove the specified resource from storage. * - * @param Server $server + * @param Server $server * @return RedirectResponse|Response */ public function destroy(Server $server) { try { $server->delete(); + return redirect()->route('admin.servers.index')->with('success', __('Server removed')); } catch (Exception $e) { - return redirect()->route('admin.servers.index')->with('error', __('An exception has occurred while trying to remove a resource "') . $e->getMessage() . '"'); + return redirect()->route('admin.servers.index')->with('error', __('An exception has occurred while trying to remove a resource "').$e->getMessage().'"'); } } /** - * @param Server $server + * @param Server $server * @return RedirectResponse */ public function toggleSuspended(Server $server) { try { - $server->isSuspended() ? $server->unSuspend() : $server->suspend(); + $server->isSuspended() ? $server->unSuspend() : $server->suspend(); } catch (Exception $exception) { return redirect()->back()->with('error', $exception->getMessage()); } @@ -130,20 +128,20 @@ class ServerController extends Controller $CPIDArray = []; $renameCount = 0; - foreach($CPServers as $CPServer)//go thru all CP servers and make array with IDs as keys. All values are false. - { - if($CPServer->pterodactyl_id) $CPIDArray[$CPServer->pterodactyl_id] = false; + foreach ($CPServers as $CPServer) {//go thru all CP servers and make array with IDs as keys. All values are false. + if ($CPServer->pterodactyl_id) { + $CPIDArray[$CPServer->pterodactyl_id] = false; + } } - foreach($pteroServers as $server)//go thru all ptero servers, if server exists, change value to true in array. - { - if(isset($CPIDArray[$server['attributes']['id']])){ - $CPIDArray[$server['attributes']['id']]=true; + foreach ($pteroServers as $server) {//go thru all ptero servers, if server exists, change value to true in array. + if (isset($CPIDArray[$server['attributes']['id']])) { + $CPIDArray[$server['attributes']['id']] = true; - if(isset($server['attributes']['name'])){//failsafe + if (isset($server['attributes']['name'])) {//failsafe //Check if a server got renamed $savedServer = Server::query()->where('pterodactyl_id', $server['attributes']['id'])->first(); - if($savedServer->name != $server['attributes']['name']){ + if ($savedServer->name != $server['attributes']['name']) { $savedServer->name = $server['attributes']['name']; $savedServer->save(); $renameCount++; @@ -151,58 +149,66 @@ class ServerController extends Controller } } } - $filteredArray = array_filter($CPIDArray, function($v, $k) { return $v == false; }, ARRAY_FILTER_USE_BOTH); //Array of servers, that dont exist on ptero (value == false) + $filteredArray = array_filter($CPIDArray, function ($v, $k) { + return $v == false; + }, ARRAY_FILTER_USE_BOTH); //Array of servers, that dont exist on ptero (value == false) $deleteCount = 0; - foreach($filteredArray as $key => $CPID)//delete servers that dont exist on ptero anymore - { - if(!Pterodactyl::getServerAttributes($key, true)) $deleteCount++; + foreach ($filteredArray as $key => $CPID) {//delete servers that dont exist on ptero anymore + if (! Pterodactyl::getServerAttributes($key, true)) { + $deleteCount++; + } } - return redirect()->back()->with('success', __('Servers synced successfully' . (($renameCount)?(',\n' . __('renamed') . ' ' . $renameCount . ' ' . __('servers')):'') . ((count($filteredArray))?(',\n' . __('deleted') . ' ' . $deleteCount . '/' . count($filteredArray) . ' ' . __('old servers')):''))) . '.'; + return redirect()->back()->with('success', __('Servers synced successfully'.(($renameCount) ? (',\n'.__('renamed').' '.$renameCount.' '.__('servers')) : '').((count($filteredArray)) ? (',\n'.__('deleted').' '.$deleteCount.'/'.count($filteredArray).' '.__('old servers')) : ''))).'.'; } /** * @return JsonResponse|mixed + * * @throws Exception */ public function dataTable(Request $request) { $query = Server::with(['user', 'product']); - if ($request->has('product')) $query->where('product_id', '=', $request->input('product')); - if ($request->has('user')) $query->where('user_id', '=', $request->input('user')); + if ($request->has('product')) { + $query->where('product_id', '=', $request->input('product')); + } + if ($request->has('user')) { + $query->where('user_id', '=', $request->input('user')); + } $query->select('servers.*'); - return datatables($query) ->addColumn('user', function (Server $server) { - return '' . $server->user->name . ''; + return ''.$server->user->name.''; }) ->addColumn('resources', function (Server $server) { return $server->product->description; }) ->addColumn('actions', function (Server $server) { - $suspendColor = $server->isSuspended() ? "btn-success" : "btn-warning"; - $suspendIcon = $server->isSuspended() ? "fa-play-circle" : "fa-pause-circle"; - $suspendText = $server->isSuspended() ? __("Unsuspend") : __("Suspend"); + $suspendColor = $server->isSuspended() ? 'btn-success' : 'btn-warning'; + $suspendIcon = $server->isSuspended() ? 'fa-play-circle' : 'fa-pause-circle'; + $suspendText = $server->isSuspended() ? __('Unsuspend') : __('Suspend'); return ' - -
- ' . csrf_field() . ' - + + + '.csrf_field().' +
-
- ' . csrf_field() . ' - ' . method_field("DELETE") . ' - + + '.csrf_field().' + '.method_field('DELETE').' +
'; }) ->addColumn('status', function (Server $server) { $labelColor = $server->isSuspended() ? 'text-danger' : 'text-success'; - return ''; + + return ''; }) ->editColumn('created_at', function (Server $server) { return $server->created_at ? $server->created_at->diffForHumans() : ''; @@ -211,7 +217,7 @@ class ServerController extends Controller return $server->suspended ? $server->suspended->diffForHumans() : ''; }) ->editColumn('name', function (Server $server) { - return 'pterodactyl_id . '">' . strip_tags($server->name) . ''; + return ''.strip_tags($server->name).''; }) ->rawColumns(['user', 'actions', 'status', 'name']) ->make(); diff --git a/app/Http/Controllers/Admin/SettingsController.php b/app/Http/Controllers/Admin/SettingsController.php index e1648eba..ec317385 100644 --- a/app/Http/Controllers/Admin/SettingsController.php +++ b/app/Http/Controllers/Admin/SettingsController.php @@ -3,11 +3,9 @@ namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; -use App\Models\Settings; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; -use Illuminate\Http\Request; use Illuminate\Http\Response; class SettingsController extends Controller @@ -22,7 +20,7 @@ class SettingsController extends Controller //Get all tabs as laravel view paths $tabs = []; foreach (glob(resource_path('views/admin/settings/tabs/*.blade.php')) as $filename) { - $tabs[] = 'admin.settings.tabs.' . basename($filename, '.blade.php'); + $tabs[] = 'admin.settings.tabs.'.basename($filename, '.blade.php'); } //Generate a html list item for each tab based on tabs file basename, set first tab as active @@ -30,8 +28,8 @@ class SettingsController extends Controller foreach ($tabs as $tab) { $tabName = str_replace('admin.settings.tabs.', '', $tab); $tabListItems[] = ''; } diff --git a/app/Http/Controllers/Admin/ShopProductController.php b/app/Http/Controllers/Admin/ShopProductController.php index e5930032..0ff534fd 100644 --- a/app/Http/Controllers/Admin/ShopProductController.php +++ b/app/Http/Controllers/Admin/ShopProductController.php @@ -3,7 +3,6 @@ namespace App\Http\Controllers\Admin; use App\Models\ShopProduct; -use App\Models\Settings; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; @@ -26,12 +25,14 @@ class ShopProductController extends Controller if ( env('APP_ENV') == 'local' || - config("SETTINGS::PAYMENTS:PAYPAL:SECRET") && config("SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID") || - config("SETTINGS::PAYMENTS:STRIPE:SECRET") && config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET") && config("SETTINGS::PAYMENTS:STRIPE:METHODS") - ) $isPaymentSetup = true; + config('SETTINGS::PAYMENTS:PAYPAL:SECRET') && config('SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID') || + config('SETTINGS::PAYMENTS:STRIPE:SECRET') && config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET') && config('SETTINGS::PAYMENTS:STRIPE:METHODS') + ) { + $isPaymentSetup = true; + } return view('admin.store.index', [ - 'isPaymentSetup' => $isPaymentSetup + 'isPaymentSetup' => $isPaymentSetup, ]); } @@ -43,29 +44,29 @@ class ShopProductController extends Controller public function create() { return view('admin.store.create', [ - 'currencyCodes' => config('currency_codes') + 'currencyCodes' => config('currency_codes'), ]); } /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return RedirectResponse */ public function store(Request $request) { $request->validate([ - "disabled" => "nullable", - "type" => "required|string", - "currency_code" => ["required", "string", "max:3", Rule::in(config('currency_codes'))], - "price" => "required|regex:/^\d+(\.\d{1,2})?$/", - "quantity" => "required|numeric", - "description" => "required|string|max:60", - "display" => "required|string|max:60", + 'disabled' => 'nullable', + 'type' => 'required|string', + 'currency_code' => ['required', 'string', 'max:3', Rule::in(config('currency_codes'))], + 'price' => "required|regex:/^\d+(\.\d{1,2})?$/", + 'quantity' => 'required|numeric', + 'description' => 'required|string|max:60', + 'display' => 'required|string|max:60', ]); - $disabled = !is_null($request->input('disabled')); + $disabled = ! is_null($request->input('disabled')); ShopProduct::create(array_merge($request->all(), ['disabled' => $disabled])); return redirect()->route('admin.store.index')->with('success', __('Store item has been created!')); @@ -74,7 +75,7 @@ class ShopProductController extends Controller /** * Display the specified resource. * - * @param ShopProduct $shopProduct + * @param ShopProduct $shopProduct * @return Response */ public function show(ShopProduct $shopProduct) @@ -85,50 +86,50 @@ class ShopProductController extends Controller /** * Show the form for editing the specified resource. * - * @param ShopProduct $shopProduct + * @param ShopProduct $shopProduct * @return Application|Factory|View|Response */ public function edit(ShopProduct $shopProduct) { return view('admin.store.edit', [ 'currencyCodes' => config('currency_codes'), - 'shopProduct' => $shopProduct + 'shopProduct' => $shopProduct, ]); } /** * Update the specified resource in storage. * - * @param Request $request - * @param ShopProduct $shopProduct + * @param Request $request + * @param ShopProduct $shopProduct * @return RedirectResponse */ public function update(Request $request, ShopProduct $shopProduct) { $request->validate([ - "disabled" => "nullable", - "type" => "required|string", - "currency_code" => ["required", "string", "max:3", Rule::in(config('currency_codes'))], - "price" => "required|regex:/^\d+(\.\d{1,2})?$/", - "quantity" => "required|numeric|max:100000000", - "description" => "required|string|max:60", - "display" => "required|string|max:60", + 'disabled' => 'nullable', + 'type' => 'required|string', + 'currency_code' => ['required', 'string', 'max:3', Rule::in(config('currency_codes'))], + 'price' => "required|regex:/^\d+(\.\d{1,2})?$/", + 'quantity' => 'required|numeric|max:100000000', + 'description' => 'required|string|max:60', + 'display' => 'required|string|max:60', ]); - $disabled = !is_null($request->input('disabled')); + $disabled = ! is_null($request->input('disabled')); $shopProduct->update(array_merge($request->all(), ['disabled' => $disabled])); return redirect()->route('admin.store.index')->with('success', __('Store item has been updated!')); } /** - * @param Request $request - * @param ShopProduct $shopProduct + * @param Request $request + * @param ShopProduct $shopProduct * @return RedirectResponse */ public function disable(Request $request, ShopProduct $shopProduct) { - $shopProduct->update(['disabled' => !$shopProduct->disabled]); + $shopProduct->update(['disabled' => ! $shopProduct->disabled]); return redirect()->route('admin.store.index')->with('success', __('Product has been updated!')); } @@ -136,16 +137,16 @@ class ShopProductController extends Controller /** * Remove the specified resource from storage. * - * @param ShopProduct $shopProduct + * @param ShopProduct $shopProduct * @return RedirectResponse */ public function destroy(ShopProduct $shopProduct) { $shopProduct->delete(); + return redirect()->back()->with('success', __('Store item has been removed!')); } - public function dataTable() { $query = ShopProduct::query(); @@ -153,24 +154,25 @@ class ShopProductController extends Controller return datatables($query) ->addColumn('actions', function (ShopProduct $shopProduct) { return ' - + -
- ' . csrf_field() . ' - ' . method_field("DELETE") . ' - + + '.csrf_field().' + '.method_field('DELETE').' +
'; }) ->addColumn('disabled', function (ShopProduct $shopProduct) { - $checked = $shopProduct->disabled == false ? "checked" : ""; + $checked = $shopProduct->disabled == false ? 'checked' : ''; + return ' -
- ' . csrf_field() . ' - ' . method_field("PATCH") . ' + + '.csrf_field().' + '.method_field('PATCH').'
- - + +
'; diff --git a/app/Http/Controllers/Admin/UsefulLinkController.php b/app/Http/Controllers/Admin/UsefulLinkController.php index f15e3f11..ea51c37d 100644 --- a/app/Http/Controllers/Admin/UsefulLinkController.php +++ b/app/Http/Controllers/Admin/UsefulLinkController.php @@ -36,27 +36,27 @@ class UsefulLinkController extends Controller /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return RedirectResponse */ public function store(Request $request) { - $request->validate([ - 'icon' => 'required|string', - 'title' => 'required|string|max:60', - 'link' => 'required|url|string|max:191', - 'description' => 'required|string|max:2000', + 'icon' => 'required|string', + 'title' => 'required|string|max:60', + 'link' => 'required|url|string|max:191', + 'description' => 'required|string|max:2000', ]); UsefulLink::create($request->all()); + return redirect()->route('admin.usefullinks.index')->with('success', __('link has been created!')); } /** * Display the specified resource. * - * @param UsefulLink $usefullink + * @param UsefulLink $usefullink * @return Response */ public function show(UsefulLink $usefullink) @@ -67,21 +67,21 @@ class UsefulLinkController extends Controller /** * Show the form for editing the specified resource. * - * @param UsefulLink $usefullink + * @param UsefulLink $usefullink * @return Application|Factory|View */ public function edit(UsefulLink $usefullink) { - return view('admin.usefullinks.edit' , [ - 'link' => $usefullink + return view('admin.usefullinks.edit', [ + 'link' => $usefullink, ]); } /** * Update the specified resource in storage. * - * @param Request $request - * @param UsefulLink $usefullink + * @param Request $request + * @param UsefulLink $usefullink * @return RedirectResponse */ public function update(Request $request, UsefulLink $usefullink) @@ -94,18 +94,20 @@ class UsefulLinkController extends Controller ]); $usefullink->update($request->all()); + return redirect()->route('admin.usefullinks.index')->with('success', __('link has been updated!')); } /** * Remove the specified resource from storage. * - * @param UsefulLink $usefullink + * @param UsefulLink $usefullink * @return Response */ public function destroy(UsefulLink $usefullink) { $usefullink->delete(); + return redirect()->back()->with('success', __('product has been removed!')); } @@ -116,12 +118,12 @@ class UsefulLinkController extends Controller return datatables($query) ->addColumn('actions', function (UsefulLink $link) { return ' - + -
- ' . csrf_field() . ' - ' . method_field("DELETE") . ' - + + '.csrf_field().' + '.method_field('DELETE').' +
'; }) @@ -131,7 +133,7 @@ class UsefulLinkController extends Controller ->editColumn('icon', function (UsefulLink $link) { return ""; }) - ->rawColumns(['actions' , 'icon']) + ->rawColumns(['actions', 'icon']) ->make(); } } diff --git a/app/Http/Controllers/Admin/UserController.php b/app/Http/Controllers/Admin/UserController.php index e372f121..329fe04c 100644 --- a/app/Http/Controllers/Admin/UserController.php +++ b/app/Http/Controllers/Admin/UserController.php @@ -5,11 +5,8 @@ namespace App\Http\Controllers\Admin; use App\Classes\Pterodactyl; use App\Events\UserUpdateCreditsEvent; use App\Http\Controllers\Controller; -use App\Models\Settings; use App\Models\User; use App\Notifications\DynamicNotification; -use Illuminate\Support\Facades\DB; -use Spatie\QueryBuilder\QueryBuilder; use Exception; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; @@ -19,11 +16,13 @@ use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Illuminate\Support\HtmlString; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; +use Spatie\QueryBuilder\QueryBuilder; class UserController extends Controller { @@ -37,7 +36,7 @@ class UserController extends Controller /** * Display a listing of the resource. * - * @param Request $request + * @param Request $request * @return Application|Factory|View|Response */ public function index(Request $request) @@ -48,23 +47,23 @@ class UserController extends Controller /** * Display the specified resource. * - * @param User $user + * @param User $user * @return Application|Factory|View|Response */ public function show(User $user) { //QUERY ALL REFERRALS A USER HAS //i am not proud of this at all. - $allReferals = array(); - $referrals = DB::table("user_referrals")->where("referral_id","=",$user->id)->get(); - foreach($referrals as $referral){ - array_push($allReferals, $allReferals["id"] = User::query()->findOrFail($referral->registered_user_id)); - } - array_pop($allReferals); + $allReferals = []; + $referrals = DB::table('user_referrals')->where('referral_id', '=', $user->id)->get(); + foreach ($referrals as $referral) { + array_push($allReferals, $allReferals['id'] = User::query()->findOrFail($referral->registered_user_id)); + } + array_pop($allReferals); return view('admin.users.show')->with([ 'user' => $user, - 'referrals' => $allReferals + 'referrals' => $allReferals, ]); } @@ -92,50 +91,51 @@ class UserController extends Controller return $item; }); } + /** * Show the form for editing the specified resource. * - * @param User $user + * @param User $user * @return Application|Factory|View|Response */ public function edit(User $user) { return view('admin.users.edit')->with([ - 'user' => $user + 'user' => $user, ]); } /** * Update the specified resource in storage. * - * @param Request $request - * @param User $user + * @param Request $request + * @param User $user * @return RedirectResponse + * * @throws Exception */ public function update(Request $request, User $user) { - $request->validate([ - "name" => "required|string|min:4|max:30", - "pterodactyl_id" => "required|numeric|unique:users,pterodactyl_id,{$user->id}", - "email" => "required|string|email", - "credits" => "required|numeric|min:0|max:99999999", - "server_limit" => "required|numeric|min:0|max:1000000", - "role" => Rule::in(['admin', 'moderator', 'client', 'member']), - "referral_code" => "required|string|min:2|max:32|unique:users,referral_code,{$user->id}", + 'name' => 'required|string|min:4|max:30', + 'pterodactyl_id' => "required|numeric|unique:users,pterodactyl_id,{$user->id}", + 'email' => 'required|string|email', + 'credits' => 'required|numeric|min:0|max:99999999', + 'server_limit' => 'required|numeric|min:0|max:1000000', + 'role' => Rule::in(['admin', 'moderator', 'client', 'member']), + 'referral_code' => "required|string|min:2|max:32|unique:users,referral_code,{$user->id}", ]); if (isset($this->pterodactyl->getUser($request->input('pterodactyl_id'))['errors'])) { throw ValidationException::withMessages([ - 'pterodactyl_id' => [__("User does not exists on pterodactyl's panel")] + 'pterodactyl_id' => [__("User does not exists on pterodactyl's panel")], ]); } - if (!is_null($request->input('new_password'))) { + if (! is_null($request->input('new_password'))) { $request->validate([ 'new_password' => 'required|string|min:8', - 'new_password_confirmation' => 'required|same:new_password' + 'new_password_confirmation' => 'required|same:new_password', ]); $user->update([ @@ -152,53 +152,58 @@ class UserController extends Controller /** * Remove the specified resource from storage. * - * @param User $user + * @param User $user * @return RedirectResponse */ public function destroy(User $user) { $user->delete(); + return redirect()->back()->with('success', __('user has been removed!')); } + /** * Verifys the users email * - * @param User $user + * @param User $user * @return RedirectResponse */ public function verifyEmail(Request $request, User $user) { $user->verifyEmail(); + return redirect()->back()->with('success', __('Email has been verified!')); } /** - * @param Request $request - * @param User $user + * @param Request $request + * @param User $user * @return RedirectResponse */ public function loginAs(Request $request, User $user) { $request->session()->put('previousUser', Auth::user()->id); Auth::login($user); + return redirect()->route('home'); } /** - * @param Request $request + * @param Request $request * @return RedirectResponse */ public function logBackIn(Request $request) { Auth::loginUsingId($request->session()->get('previousUser'), true); $request->session()->remove('previousUser'); + return redirect()->route('admin.users.index'); } /** * Show the form for seding notifications to the specified resource. * - * @param User $user + * @param User $user * @return Application|Factory|View|Response */ public function notifications(User $user) @@ -209,50 +214,52 @@ class UserController extends Controller /** * Notify the specified resource. * - * @param Request $request - * @param User $user + * @param Request $request + * @param User $user * @return RedirectResponse + * * @throws Exception */ public function notify(Request $request) { $data = $request->validate([ - "via" => "required|min:1|array", - "via.*" => "required|string|in:mail,database", - "all" => "required_without:users|boolean", - "users" => "required_without:all|min:1|array", - "users.*" => "exists:users,id", - "title" => "required|string|min:1", - "content" => "required|string|min:1" + 'via' => 'required|min:1|array', + 'via.*' => 'required|string|in:mail,database', + 'all' => 'required_without:users|boolean', + 'users' => 'required_without:all|min:1|array', + 'users.*' => 'exists:users,id', + 'title' => 'required|string|min:1', + 'content' => 'required|string|min:1', ]); $mail = null; $database = null; - if (in_array('database', $data["via"])) { + if (in_array('database', $data['via'])) { $database = [ - "title" => $data["title"], - "content" => $data["content"] + 'title' => $data['title'], + 'content' => $data['content'], ]; } - if (in_array('mail', $data["via"])) { + if (in_array('mail', $data['via'])) { $mail = (new MailMessage) - ->subject($data["title"]) - ->line(new HtmlString($data["content"])); + ->subject($data['title']) + ->line(new HtmlString($data['content'])); } - $all = $data["all"] ?? false; - $users = $all ? User::all() : User::whereIn("id", $data["users"])->get(); - Notification::send($users, new DynamicNotification($data["via"], $database, $mail)); + $all = $data['all'] ?? false; + $users = $all ? User::all() : User::whereIn('id', $data['users'])->get(); + Notification::send($users, new DynamicNotification($data['via'], $database, $mail)); + return redirect()->route('admin.users.notifications')->with('success', __('Notification sent!')); } /** - * @param User $user + * @param User $user * @return RedirectResponse */ public function toggleSuspended(User $user) { try { - !$user->isSuspended() ? $user->suspend() : $user->unSuspend(); + ! $user->isSuspended() ? $user->suspend() : $user->unSuspend(); } catch (Exception $exception) { return redirect()->back()->with('error', $exception->getMessage()); } @@ -261,7 +268,6 @@ class UserController extends Controller } /** - * * @throws Exception */ public function dataTable() @@ -270,10 +276,10 @@ class UserController extends Controller return datatables($query) ->addColumn('avatar', function (User $user) { - return ''; + return ''; }) ->addColumn('credits', function (User $user) { - return ' ' . $user->credits(); + return ' '.$user->credits(); }) ->addColumn('verified', function (User $user) { return $user->getVerifiedStatus(); @@ -282,32 +288,33 @@ class UserController extends Controller return $user->servers->count(); }) ->addColumn('referrals', function (User $user) { - return DB::table('user_referrals')->where("referral_id","=",$user->id)->count(); + return DB::table('user_referrals')->where('referral_id', '=', $user->id)->count(); }) ->addColumn('discordId', function (User $user) { return $user->discordUser ? $user->discordUser->id : ''; }) ->addColumn('last_seen', function (User $user) { return ['display' => $user->last_seen ? $user->last_seen->diffForHumans() : '', - 'raw' => $user->last_seen ? strtotime($user->last_seen) : '']; + 'raw' => $user->last_seen ? strtotime($user->last_seen) : '', ]; }) ->addColumn('actions', function (User $user) { - $suspendColor = $user->isSuspended() ? "btn-success" : "btn-warning"; - $suspendIcon = $user->isSuspended() ? "fa-play-circle" : "fa-pause-circle"; - $suspendText = $user->isSuspended() ? __("Unsuspend") : __("Suspend"); + $suspendColor = $user->isSuspended() ? 'btn-success' : 'btn-warning'; + $suspendIcon = $user->isSuspended() ? 'fa-play-circle' : 'fa-pause-circle'; + $suspendText = $user->isSuspended() ? __('Unsuspend') : __('Suspend'); + return ' - - - - -
- ' . csrf_field() . ' - + + + + + + '.csrf_field().' +
-
- ' . csrf_field() . ' - ' . method_field("DELETE") . ' - + + '.csrf_field().' + '.method_field('DELETE').' +
'; }) @@ -327,10 +334,10 @@ class UserController extends Controller break; } - return '' . $user->role . ''; + return ''.$user->role.''; }) ->editColumn('name', function (User $user) { - return 'pterodactyl_id . '">' . strip_tags($user->name) . ''; + return ''.strip_tags($user->name).''; }) /*->orderColumn('last_seen', function ($query) { $query->orderBy('last_seen', "desc"); diff --git a/app/Http/Controllers/Admin/VoucherController.php b/app/Http/Controllers/Admin/VoucherController.php index 51cb5000..ce8bcf5d 100644 --- a/app/Http/Controllers/Admin/VoucherController.php +++ b/app/Http/Controllers/Admin/VoucherController.php @@ -40,16 +40,16 @@ class VoucherController extends Controller /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return RedirectResponse */ public function store(Request $request) { $request->validate([ - 'memo' => 'nullable|string|max:191', - 'code' => 'required|string|alpha_dash|max:36|min:4|unique:vouchers', - 'uses' => 'required|numeric|max:2147483647|min:1', - 'credits' => 'required|numeric|between:0,99999999', + 'memo' => 'nullable|string|max:191', + 'code' => 'required|string|alpha_dash|max:36|min:4|unique:vouchers', + 'uses' => 'required|numeric|max:2147483647|min:1', + 'credits' => 'required|numeric|between:0,99999999', 'expires_at' => 'nullable|multiple_date_format:d-m-Y H:i:s,d-m-Y|after:now|before:10 years', ]); @@ -61,7 +61,7 @@ class VoucherController extends Controller /** * Display the specified resource. * - * @param Voucher $voucher + * @param Voucher $voucher * @return Response */ public function show(Voucher $voucher) @@ -72,30 +72,30 @@ class VoucherController extends Controller /** * Show the form for editing the specified resource. * - * @param Voucher $voucher + * @param Voucher $voucher * @return Application|Factory|View */ public function edit(Voucher $voucher) { return view('admin.vouchers.edit', [ - 'voucher' => $voucher + 'voucher' => $voucher, ]); } /** * Update the specified resource in storage. * - * @param Request $request - * @param Voucher $voucher + * @param Request $request + * @param Voucher $voucher * @return RedirectResponse */ public function update(Request $request, Voucher $voucher) { $request->validate([ - 'memo' => 'nullable|string|max:191', - 'code' => "required|string|alpha_dash|max:36|min:4|unique:vouchers,code,{$voucher->id}", - 'uses' => 'required|numeric|max:2147483647|min:1', - 'credits' => 'required|numeric|between:0,99999999', + 'memo' => 'nullable|string|max:191', + 'code' => "required|string|alpha_dash|max:36|min:4|unique:vouchers,code,{$voucher->id}", + 'uses' => 'required|numeric|max:2147483647|min:1', + 'credits' => 'required|numeric|between:0,99999999', 'expires_at' => 'nullable|multiple_date_format:d-m-Y H:i:s,d-m-Y|after:now|before:10 years', ]); @@ -107,61 +107,71 @@ class VoucherController extends Controller /** * Remove the specified resource from storage. * - * @param Voucher $voucher + * @param Voucher $voucher * @return RedirectResponse */ public function destroy(Voucher $voucher) { $voucher->delete(); + return redirect()->back()->with('success', __('voucher has been removed!')); } public function users(Voucher $voucher) { return view('admin.vouchers.users', [ - 'voucher' => $voucher + 'voucher' => $voucher, ]); } /** - * @param Request $request + * @param Request $request * @return JsonResponse + * * @throws ValidationException */ public function redeem(Request $request) { - #general validations + //general validations $request->validate([ - 'code' => 'required|exists:vouchers,code' + 'code' => 'required|exists:vouchers,code', ]); - #get voucher by code + //get voucher by code $voucher = Voucher::where('code', '=', $request->input('code'))->firstOrFail(); - #extra validations - if ($voucher->getStatus() == 'USES_LIMIT_REACHED') throw ValidationException::withMessages([ - 'code' => __('This voucher has reached the maximum amount of uses') - ]); + //extra validations + if ($voucher->getStatus() == 'USES_LIMIT_REACHED') { + throw ValidationException::withMessages([ + 'code' => __('This voucher has reached the maximum amount of uses'), + ]); + } - if ($voucher->getStatus() == 'EXPIRED') throw ValidationException::withMessages([ - 'code' => __('This voucher has expired') - ]); + if ($voucher->getStatus() == 'EXPIRED') { + throw ValidationException::withMessages([ + 'code' => __('This voucher has expired'), + ]); + } - if (!$request->user()->vouchers()->where('id', '=', $voucher->id)->get()->isEmpty()) throw ValidationException::withMessages([ - 'code' => __('You already redeemed this voucher code') - ]); + if (! $request->user()->vouchers()->where('id', '=', $voucher->id)->get()->isEmpty()) { + throw ValidationException::withMessages([ + 'code' => __('You already redeemed this voucher code'), + ]); + } - if ($request->user()->credits + $voucher->credits >= 99999999) throw ValidationException::withMessages([ - 'code' => "You can't redeem this voucher because you would exceed the limit of " . CREDITS_DISPLAY_NAME - ]); + if ($request->user()->credits + $voucher->credits >= 99999999) { + throw ValidationException::withMessages([ + 'code' => "You can't redeem this voucher because you would exceed the limit of ".CREDITS_DISPLAY_NAME, + ]); + } - #redeem voucher + //redeem voucher $voucher->redeem($request->user()); event(new UserUpdateCreditsEvent($request->user())); return response()->json([ - 'success' => "{$voucher->credits} " . CREDITS_DISPLAY_NAME ." ". __("have been added to your balance!") + 'success' => "{$voucher->credits} ".CREDITS_DISPLAY_NAME.' '.__('have been added to your balance!'), ]); } @@ -171,10 +181,10 @@ class VoucherController extends Controller return datatables($users) ->editColumn('name', function (User $user) { - return '' . $user->name . ''; + return ''.$user->name.''; }) ->addColumn('credits', function (User $user) { - return ' ' . $user->credits(); + return ' '.$user->credits(); }) ->addColumn('last_seen', function (User $user) { return $user->last_seen ? $user->last_seen->diffForHumans() : ''; @@ -182,6 +192,7 @@ class VoucherController extends Controller ->rawColumns(['name', 'credits', 'last_seen']) ->make(); } + public function dataTable() { $query = Voucher::query(); @@ -189,20 +200,23 @@ class VoucherController extends Controller return datatables($query) ->addColumn('actions', function (Voucher $voucher) { return ' - - + + -
- ' . csrf_field() . ' - ' . method_field("DELETE") . ' - + + '.csrf_field().' + '.method_field('DELETE').' +
'; }) ->addColumn('status', function (Voucher $voucher) { $color = 'success'; - if ($voucher->getStatus() != __('VALID')) $color = 'danger'; - return '' . $voucher->getStatus() . ''; + if ($voucher->getStatus() != __('VALID')) { + $color = 'danger'; + } + + return ''.$voucher->getStatus().''; }) ->editColumn('uses', function (Voucher $voucher) { return "{$voucher->used} / {$voucher->uses}"; @@ -211,7 +225,10 @@ class VoucherController extends Controller return number_format($voucher->credits, 2, '.', ''); }) ->editColumn('expires_at', function (Voucher $voucher) { - if (!$voucher->expires_at) return ""; + if (! $voucher->expires_at) { + return ''; + } + return $voucher->expires_at ? $voucher->expires_at->diffForHumans() : ''; }) ->editColumn('code', function (Voucher $voucher) { diff --git a/app/Http/Controllers/Api/NotificationController.php b/app/Http/Controllers/Api/NotificationController.php index 9fe61c79..9ccc47af 100644 --- a/app/Http/Controllers/Api/NotificationController.php +++ b/app/Http/Controllers/Api/NotificationController.php @@ -19,8 +19,9 @@ class NotificationController extends Controller { /** * Display all notifications of an user. - * @param Request $request - * @param int $userId + * + * @param Request $request + * @param int $userId * @return Response */ public function index(Request $request, int $userId) @@ -28,14 +29,14 @@ class NotificationController extends Controller $discordUser = DiscordUser::find($userId); $user = $discordUser ? $discordUser->user : User::findOrFail($userId); - return $user->notifications()->paginate($request->query("per_page", 50)); + return $user->notifications()->paginate($request->query('per_page', 50)); } /** * Display a specific notification * - * @param int $userId - * @param int $notificationId + * @param int $userId + * @param int $notificationId * @return JsonResponse */ public function view(int $userId, $notificationId) @@ -43,10 +44,10 @@ class NotificationController extends Controller $discordUser = DiscordUser::find($userId); $user = $discordUser ? $discordUser->user : User::findOrFail($userId); - $notification = $user->notifications()->where("id", $notificationId)->get()->first(); + $notification = $user->notifications()->where('id', $notificationId)->get()->first(); - if (!$notification) { - return response()->json(["message" => "Notification not found."], 404); + if (! $notification) { + return response()->json(['message' => 'Notification not found.'], 404); } return $notification; @@ -55,42 +56,43 @@ class NotificationController extends Controller /** * Send a notification to an user. * - * @param Request $request + * @param Request $request * @return JsonResponse + * * @throws ValidationException */ public function send(Request $request) { $data = $request->validate([ - "via" => ["required", new Delimited("in:mail,database")], - "all" => "required_without:users|boolean", - "users" => ["required_without:all"], - "title" => "required|string|min:1", - "content" => "required|string|min:1" + 'via' => ['required', new Delimited('in:mail,database')], + 'all' => 'required_without:users|boolean', + 'users' => ['required_without:all'], + 'title' => 'required|string|min:1', + 'content' => 'required|string|min:1', ]); - $via = explode(",", $data["via"]); + $via = explode(',', $data['via']); $mail = null; $database = null; - if (in_array("database", $via)) { + if (in_array('database', $via)) { $database = [ - "title" => $data["title"], - "content" => $data["content"] + 'title' => $data['title'], + 'content' => $data['content'], ]; } - if (in_array("mail", $via)) { + if (in_array('mail', $via)) { $mail = (new MailMessage) - ->subject($data["title"]) - ->line(new HtmlString($data["content"])); + ->subject($data['title']) + ->line(new HtmlString($data['content'])); } - $all = $data["all"] ?? false; + $all = $data['all'] ?? false; if ($all) { $users = User::all(); } else { - $userIds = explode(",", $data["users"]); + $userIds = explode(',', $data['users']); $users = User::query() - ->whereIn("id", $userIds) + ->whereIn('id', $userIds) ->orWhereHas('discordUser', function (Builder $builder) use ($userIds) { $builder->whereIn('id', $userIds); }) @@ -104,13 +106,14 @@ class NotificationController extends Controller } Notification::send($users, new DynamicNotification($via, $database, $mail)); - return response()->json(["message" => "Notification successfully sent.", 'user_count' => $users->count()]); + + return response()->json(['message' => 'Notification successfully sent.', 'user_count' => $users->count()]); } /** * Delete all notifications from an user * - * @param int $userId + * @param int $userId * @return JsonResponse */ public function delete(int $userId) @@ -120,15 +123,14 @@ class NotificationController extends Controller $count = $user->notifications()->delete(); - return response()->json(["message" => "All notifications have been successfully deleted.", "count" => $count]); + return response()->json(['message' => 'All notifications have been successfully deleted.', 'count' => $count]); } - /** * Delete a specific notification * - * @param int $userId - * @param int $notificationId + * @param int $userId + * @param int $notificationId * @return JsonResponse */ public function deleteOne(int $userId, $notificationid) @@ -136,13 +138,14 @@ class NotificationController extends Controller $discordUser = DiscordUser::find($userId); $user = $discordUser ? $discordUser->user : User::findOrFail($userId); - $notification = $user->notifications()->where("id", $notificationid)->get()->first(); + $notification = $user->notifications()->where('id', $notificationid)->get()->first(); - if (!$notification) { - return response()->json(["message" => "Notification not found."], 404); + if (! $notification) { + return response()->json(['message' => 'Notification not found.'], 404); } $notification->delete(); + return response()->json($notification); } } diff --git a/app/Http/Controllers/Api/ServerController.php b/app/Http/Controllers/Api/ServerController.php index 1b9468c0..bd591ced 100644 --- a/app/Http/Controllers/Api/ServerController.php +++ b/app/Http/Controllers/Api/ServerController.php @@ -15,12 +15,13 @@ use Spatie\QueryBuilder\QueryBuilder; class ServerController extends Controller { public const ALLOWED_INCLUDES = ['product', 'user']; + public const ALLOWED_FILTERS = ['name', 'suspended', 'identifier', 'pterodactyl_id', 'user_id', 'product_id']; /** * Display a listing of the resource. * - * @param Request $request + * @param Request $request * @return LengthAwarePaginator */ public function index(Request $request) @@ -35,8 +36,7 @@ class ServerController extends Controller /** * Display the specified resource. * - * @param Server $server - * + * @param Server $server * @return Server|Collection|Model */ public function show(Server $server) @@ -51,19 +51,20 @@ class ServerController extends Controller /** * Remove the specified resource from storage. * - * @param Server $server + * @param Server $server * @return Server */ public function destroy(Server $server) { $server->delete(); + return $server; } - /** * suspend server - * @param Server $server + * + * @param Server $server * @return Server|JsonResponse */ public function suspend(Server $server) @@ -77,10 +78,10 @@ class ServerController extends Controller return $server->load('product'); } - /** * unsuspend server - * @param Server $server + * + * @param Server $server * @return Server|JsonResponse */ public function unSuspend(Server $server) diff --git a/app/Http/Controllers/Api/UserController.php b/app/Http/Controllers/Api/UserController.php index 3f308405..dab72dba 100644 --- a/app/Http/Controllers/Api/UserController.php +++ b/app/Http/Controllers/Api/UserController.php @@ -6,7 +6,6 @@ use App\Classes\Pterodactyl; use App\Events\UserUpdateCreditsEvent; use App\Http\Controllers\Controller; use App\Models\DiscordUser; -use App\Models\Settings; use App\Models\User; use App\Notifications\ReferralNotification; use Carbon\Carbon; @@ -29,12 +28,13 @@ use Spatie\QueryBuilder\QueryBuilder; class UserController extends Controller { const ALLOWED_INCLUDES = ['servers', 'notifications', 'payments', 'vouchers', 'discordUser']; + const ALLOWED_FILTERS = ['name', 'server_limit', 'email', 'pterodactyl_id', 'role', 'suspended']; /** * Display a listing of the resource. * - * @param Request $request + * @param Request $request * @return LengthAwarePaginator */ public function index(Request $request) @@ -46,12 +46,10 @@ class UserController extends Controller return $query->paginate($request->input('per_page') ?? 50); } - /** * Display the specified resource. * - * @param int $id - * + * @param int $id * @return User|Builder|Collection|Model */ public function show(int $id) @@ -70,12 +68,11 @@ class UserController extends Controller return $query->firstOrFail(); } - /** * Update the specified resource in storage. * - * @param Request $request - * @param int $id + * @param Request $request + * @param int $id * @return User */ public function update(Request $request, int $id) @@ -84,28 +81,28 @@ class UserController extends Controller $user = $discordUser ? $discordUser->user : User::findOrFail($id); $request->validate([ - "name" => "sometimes|string|min:4|max:30", - "email" => "sometimes|string|email", - "credits" => "sometimes|numeric|min:0|max:1000000", - "server_limit" => "sometimes|numeric|min:0|max:1000000", - "role" => ['sometimes', Rule::in(['admin', 'moderator', 'client', 'member'])], + 'name' => 'sometimes|string|min:4|max:30', + 'email' => 'sometimes|string|email', + 'credits' => 'sometimes|numeric|min:0|max:1000000', + 'server_limit' => 'sometimes|numeric|min:0|max:1000000', + 'role' => ['sometimes', Rule::in(['admin', 'moderator', 'client', 'member'])], ]); event(new UserUpdateCreditsEvent($user)); //Update Users Password on Pterodactyl //Username,Mail,First and Lastname are required aswell - $response = Pterodactyl::client()->patch('/application/users/' . $user->pterodactyl_id, [ - "username" => $request->name, - "first_name" => $request->name, - "last_name" => $request->name, - "email" => $request->email, + $response = Pterodactyl::client()->patch('/application/users/'.$user->pterodactyl_id, [ + 'username' => $request->name, + 'first_name' => $request->name, + 'last_name' => $request->name, + 'email' => $request->email, ]); if ($response->failed()) { throw ValidationException::withMessages([ 'pterodactyl_error_message' => $response->toException()->getMessage(), - 'pterodactyl_error_status' => $response->toException()->getCode() + 'pterodactyl_error_status' => $response->toException()->getCode(), ]); } $user->update($request->all()); @@ -116,9 +113,10 @@ class UserController extends Controller /** * increments the users credits or/and server_limit * - * @param Request $request - * @param int $id + * @param Request $request + * @param int $id * @return User + * * @throws ValidationException */ public function increment(Request $request, int $id) @@ -127,22 +125,26 @@ class UserController extends Controller $user = $discordUser ? $discordUser->user : User::findOrFail($id); $request->validate([ - "credits" => "sometimes|numeric|min:0|max:1000000", - "server_limit" => "sometimes|numeric|min:0|max:1000000", + 'credits' => 'sometimes|numeric|min:0|max:1000000', + 'server_limit' => 'sometimes|numeric|min:0|max:1000000', ]); if ($request->credits) { - if ($user->credits + $request->credits >= 99999999) throw ValidationException::withMessages([ - 'credits' => "You can't add this amount of credits because you would exceed the credit limit" - ]); + if ($user->credits + $request->credits >= 99999999) { + throw ValidationException::withMessages([ + 'credits' => "You can't add this amount of credits because you would exceed the credit limit", + ]); + } event(new UserUpdateCreditsEvent($user)); $user->increment('credits', $request->credits); } if ($request->server_limit) { - if ($user->server_limit + $request->server_limit >= 2147483647) throw ValidationException::withMessages([ - 'server_limit' => "You cannot add this amount of servers because it would exceed the server limit." - ]); + if ($user->server_limit + $request->server_limit >= 2147483647) { + throw ValidationException::withMessages([ + 'server_limit' => 'You cannot add this amount of servers because it would exceed the server limit.', + ]); + } $user->increment('server_limit', $request->server_limit); } @@ -152,9 +154,10 @@ class UserController extends Controller /** * decrements the users credits or/and server_limit * - * @param Request $request - * @param int $id + * @param Request $request + * @param int $id * @return User + * * @throws ValidationException */ public function decrement(Request $request, int $id) @@ -163,21 +166,25 @@ class UserController extends Controller $user = $discordUser ? $discordUser->user : User::findOrFail($id); $request->validate([ - "credits" => "sometimes|numeric|min:0|max:1000000", - "server_limit" => "sometimes|numeric|min:0|max:1000000", + 'credits' => 'sometimes|numeric|min:0|max:1000000', + 'server_limit' => 'sometimes|numeric|min:0|max:1000000', ]); if ($request->credits) { - if ($user->credits - $request->credits < 0) throw ValidationException::withMessages([ - 'credits' => "You can't remove this amount of credits because you would exceed the minimum credit limit" - ]); + if ($user->credits - $request->credits < 0) { + throw ValidationException::withMessages([ + 'credits' => "You can't remove this amount of credits because you would exceed the minimum credit limit", + ]); + } $user->decrement('credits', $request->credits); } if ($request->server_limit) { - if ($user->server_limit - $request->server_limit < 0) throw ValidationException::withMessages([ - 'server_limit' => "You cannot remove this amount of servers because it would exceed the minimum server." - ]); + if ($user->server_limit - $request->server_limit < 0) { + throw ValidationException::withMessages([ + 'server_limit' => 'You cannot remove this amount of servers because it would exceed the minimum server.', + ]); + } $user->decrement('server_limit', $request->server_limit); } @@ -187,9 +194,10 @@ class UserController extends Controller /** * Suspends the user * - * @param Request $request - * @param int $id + * @param Request $request + * @param int $id * @return bool + * * @throws ValidationException */ public function suspend(Request $request, int $id) @@ -210,9 +218,10 @@ class UserController extends Controller /** * Unsuspend the user * - * @param Request $request - * @param int $id + * @param Request $request + * @param int $id * @return bool + * * @throws ValidationException */ public function unsuspend(Request $request, int $id) @@ -220,9 +229,9 @@ class UserController extends Controller $discordUser = DiscordUser::find($id); $user = $discordUser ? $discordUser->user : User::findOrFail($id); - if (!$user->isSuspended()) { + if (! $user->isSuspended()) { throw ValidationException::withMessages([ - 'error' => "You cannot unsuspend an User who is not suspended." + 'error' => 'You cannot unsuspend an User who is not suspended.', ]); } @@ -230,17 +239,22 @@ class UserController extends Controller return $user; } + /** * Create a unique Referral Code for User + * * @return string */ - protected function createReferralCode(){ + protected function createReferralCode() + { $referralcode = STR::random(8); if (User::where('referral_code', '=', $referralcode)->exists()) { $this->createReferralCode(); } + return $referralcode; } + /** * @throws ValidationException */ @@ -251,13 +265,13 @@ class UserController extends Controller 'email' => ['required', 'string', 'email', 'max:64', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'max:191'], ]); - + // Prevent the creation of new users via API if this is enabled. - if (!config('SETTINGS::SYSTEM:CREATION_OF_NEW_USERS', 'true')) { + if (! config('SETTINGS::SYSTEM:CREATION_OF_NEW_USERS', 'true')) { throw ValidationException::withMessages([ - 'error' => "The creation of new users has been blocked by the system administrator." + 'error' => 'The creation of new users has been blocked by the system administrator.', ]); - } + } $user = User::create([ 'name' => $request->input('name'), @@ -269,45 +283,44 @@ class UserController extends Controller ]); $response = Pterodactyl::client()->post('/application/users', [ - "external_id" => App::environment('local') ? Str::random(16) : (string)$user->id, - "username" => $user->name, - "email" => $user->email, - "first_name" => $user->name, - "last_name" => $user->name, - "password" => $request->input('password'), - "root_admin" => false, - "language" => "en" + 'external_id' => App::environment('local') ? Str::random(16) : (string) $user->id, + 'username' => $user->name, + 'email' => $user->email, + 'first_name' => $user->name, + 'last_name' => $user->name, + 'password' => $request->input('password'), + 'root_admin' => false, + 'language' => 'en', ]); if ($response->failed()) { $user->delete(); throw ValidationException::withMessages([ 'pterodactyl_error_message' => $response->toException()->getMessage(), - 'pterodactyl_error_status' => $response->toException()->getCode() + 'pterodactyl_error_status' => $response->toException()->getCode(), ]); } $user->update([ - 'pterodactyl_id' => $response->json()['attributes']['id'] + 'pterodactyl_id' => $response->json()['attributes']['id'], ]); //INCREMENT REFERRAL-USER CREDITS - if(!empty($request->input("referral_code"))){ - $ref_code = $request->input("referral_code"); + if (! empty($request->input('referral_code'))) { + $ref_code = $request->input('referral_code'); $new_user = $user->id; - if($ref_user = User::query()->where('referral_code', '=', $ref_code)->first()) { - if(config("SETTINGS::REFERRAL:MODE") == "register" || config("SETTINGS::REFERRAL:MODE") == "both") { - $ref_user->increment('credits', config("SETTINGS::REFERRAL::REWARD")); + if ($ref_user = User::query()->where('referral_code', '=', $ref_code)->first()) { + if (config('SETTINGS::REFERRAL:MODE') == 'register' || config('SETTINGS::REFERRAL:MODE') == 'both') { + $ref_user->increment('credits', config('SETTINGS::REFERRAL::REWARD')); $ref_user->notify(new ReferralNotification($ref_user->id, $new_user)); } //INSERT INTO USER_REFERRALS TABLE DB::table('user_referrals')->insert([ 'referral_id' => $ref_user->id, 'registered_user_id' => $user->id, - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now() + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), ]); } - } $user->sendEmailVerificationNotification(); @@ -317,7 +330,7 @@ class UserController extends Controller /** * Remove the specified resource from storage. * - * @param int $id + * @param int $id * @return Application|Response|ResponseFactory */ public function destroy(int $id) @@ -326,6 +339,7 @@ class UserController extends Controller $user = $discordUser ? $discordUser->user : User::findOrFail($id); $user->delete(); + return response($user, 200); } } diff --git a/app/Http/Controllers/Api/VoucherController.php b/app/Http/Controllers/Api/VoucherController.php index a094fe1d..6b3b8d3c 100644 --- a/app/Http/Controllers/Api/VoucherController.php +++ b/app/Http/Controllers/Api/VoucherController.php @@ -15,6 +15,7 @@ use Spatie\QueryBuilder\QueryBuilder; class VoucherController extends Controller { const ALLOWED_INCLUDES = ['users']; + const ALLOWED_FILTERS = ['code', 'memo', 'credits', 'uses']; /** @@ -44,7 +45,7 @@ class VoucherController extends Controller /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return Response */ public function store(Request $request) @@ -54,7 +55,7 @@ class VoucherController extends Controller 'code' => 'required|string|alpha_dash|max:36|min:4|unique:vouchers', 'uses' => 'required|numeric|max:2147483647|min:1', 'credits' => 'required|numeric|between:0,99999999', - 'expires_at' => 'nullable|multiple_date_format:d-m-Y H:i:s,d-m-Y|after:now|before:10 years' + 'expires_at' => 'nullable|multiple_date_format:d-m-Y H:i:s,d-m-Y|after:now|before:10 years', ]); return Voucher::create($request->all()); @@ -63,8 +64,7 @@ class VoucherController extends Controller /** * Display the specified resource. * - * @param int $id - * + * @param int $id * @return Voucher|Collection|Model */ public function show(int $id) @@ -79,7 +79,7 @@ class VoucherController extends Controller /** * Show the form for editing the specified resource. * - * @param int $id + * @param int $id * @return Response */ public function edit($id) @@ -90,8 +90,8 @@ class VoucherController extends Controller /** * Update the specified resource in storage. * - * @param Request $request - * @param int $id + * @param Request $request + * @param int $id * @return Response */ public function update(Request $request, int $id) @@ -103,7 +103,7 @@ class VoucherController extends Controller 'code' => "required|string|alpha_dash|max:36|min:4|unique:vouchers,code,{$voucher->id}", 'uses' => 'required|numeric|max:2147483647|min:1', 'credits' => 'required|numeric|between:0,99999999', - 'expires_at' => 'nullable|multiple_date_format:d-m-Y H:i:s,d-m-Y|after:now|before:10 years' + 'expires_at' => 'nullable|multiple_date_format:d-m-Y H:i:s,d-m-Y|after:now|before:10 years', ]); $voucher->update($request->all()); @@ -114,21 +114,22 @@ class VoucherController extends Controller /** * Remove the specified resource from storage. * - * @param int $id + * @param int $id * @return Response */ public function destroy(int $id) { $voucher = Voucher::findOrFail($id); $voucher->delete(); + return $voucher; } - /** * get linked users - * @param Request $request - * @param Voucher $voucher + * + * @param Request $request + * @param Voucher $voucher * @return LengthAwarePaginator */ public function users(Request $request, Voucher $voucher) @@ -138,7 +139,7 @@ class VoucherController extends Controller 'nullable', 'string', Rule::in(['discorduser']), - ] + ], ]); if ($request->input('include') == 'discorduser') { diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index 01c08be3..bd9df2d8 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -4,7 +4,6 @@ namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\SendsPasswordResetEmails; -use Illuminate\Support\Facades\Validator; use Illuminate\Http\Request; class ForgotPasswordController extends Controller @@ -32,7 +31,6 @@ class ForgotPasswordController extends Controller $this->middleware('guest'); } - protected function validateEmail(Request $request) { $this->validate($request, [ @@ -44,8 +42,5 @@ class ForgotPasswordController extends Controller 'g-recaptcha-response' => 'required|recaptcha', ]); } - - - } } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 62089d7e..0b40b07e 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -8,7 +8,6 @@ use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Log; class LoginController extends Controller { @@ -44,18 +43,15 @@ class LoginController extends Controller public function login(Request $request) { - $validationRules = [ - $this->username() => 'required|string', - 'password' => 'required|string', + $this->username() => 'required|string', + 'password' => 'required|string', ]; if (config('SETTINGS::RECAPTCHA:ENABLED') == 'true') { $validationRules['g-recaptcha-response'] = ['required', 'recaptcha']; } $request->validate($validationRules); - - // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. @@ -72,6 +68,7 @@ class LoginController extends Controller $user = Auth::user(); $user->last_seen = now(); $user->save(); + return $this->sendLoginResponse($request); } diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index f08f6274..0aabb601 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -4,14 +4,12 @@ namespace App\Http\Controllers\Auth; use App\Classes\Pterodactyl; use App\Http\Controllers\Controller; -use App\Models\Settings; use App\Models\User; use App\Notifications\ReferralNotification; use App\Providers\RouteServiceProvider; use Carbon\Carbon; use Illuminate\Foundation\Auth\RegistersUsers; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; @@ -54,15 +52,15 @@ class RegisterController extends Controller /** * Get a validator for an incoming registration request. * - * @param array $data + * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { $validationRules = [ - 'name' => ['required', 'string', 'max:30', 'min:4', 'alpha_num', 'unique:users'], - 'email' => ['required', 'string', 'email', 'max:64', 'unique:users'], - 'password' => ['required', 'string', 'min:8', 'confirmed'], + 'name' => ['required', 'string', 'max:30', 'min:4', 'alpha_num', 'unique:users'], + 'email' => ['required', 'string', 'email', 'max:64', 'unique:users'], + 'password' => ['required', 'string', 'min:8', 'confirmed'], ]; if (config('SETTINGS::RECAPTCHA:ENABLED') == 'true') { $validationRules['g-recaptcha-response'] = ['required', 'recaptcha']; @@ -75,10 +73,13 @@ class RegisterController extends Controller //check if ip has already made an account $data['ip'] = session()->get('ip') ?? request()->ip(); - if (User::where('ip', '=', request()->ip())->exists()) session()->put('ip', request()->ip()); - $validationRules['ip'] = ['unique:users']; + if (User::where('ip', '=', request()->ip())->exists()) { + session()->put('ip', request()->ip()); + } + $validationRules['ip'] = ['unique:users']; + return Validator::make($data, $validationRules, [ - 'ip.unique' => "You have already made an account! Please contact support if you think this is incorrect." + 'ip.unique' => 'You have already made an account! Please contact support if you think this is incorrect.', ]); } @@ -88,43 +89,46 @@ class RegisterController extends Controller /** * Create a unique Referral Code for User + * * @return string */ - protected function createReferralCode(){ + protected function createReferralCode() + { $referralcode = STR::random(8); if (User::where('referral_code', '=', $referralcode)->exists()) { $this->createReferralCode(); } + return $referralcode; } /** * Create a new user instance after a valid registration. * - * @param array $data + * @param array $data * @return User */ protected function create(array $data) { $user = User::create([ - 'name' => $data['name'], - 'email' => $data['email'], - 'credits' => config('SETTINGS::USER:INITIAL_CREDITS', 150), + 'name' => $data['name'], + 'email' => $data['email'], + 'credits' => config('SETTINGS::USER:INITIAL_CREDITS', 150), 'server_limit' => config('SETTINGS::USER:INITIAL_SERVER_LIMIT', 1), - 'password' => Hash::make($data['password']), + 'password' => Hash::make($data['password']), 'referral_code' => $this->createReferralCode(), ]); $response = Pterodactyl::client()->post('/application/users', [ - "external_id" => App::environment('local') ? Str::random(16) : (string)$user->id, - "username" => $user->name, - "email" => $user->email, - "first_name" => $user->name, - "last_name" => $user->name, - "password" => $data['password'], - "root_admin" => false, - "language" => "en" + 'external_id' => App::environment('local') ? Str::random(16) : (string) $user->id, + 'username' => $user->name, + 'email' => $user->email, + 'first_name' => $user->name, + 'last_name' => $user->name, + 'password' => $data['password'], + 'root_admin' => false, + 'language' => 'en', ]); if ($response->failed()) { @@ -135,33 +139,32 @@ class RegisterController extends Controller } $user->update([ - 'pterodactyl_id' => $response->json()['attributes']['id'] + 'pterodactyl_id' => $response->json()['attributes']['id'], ]); //INCREMENT REFERRAL-USER CREDITS - if(!empty($data['referral_code'])){ + if (! empty($data['referral_code'])) { $ref_code = $data['referral_code']; $new_user = $user->id; - if($ref_user = User::query()->where('referral_code', '=', $ref_code)->first()) { - if(config("SETTINGS::REFERRAL:MODE") == "sign-up" || config("SETTINGS::REFERRAL:MODE") == "both") { - $ref_user->increment('credits', config("SETTINGS::REFERRAL::REWARD")); + if ($ref_user = User::query()->where('referral_code', '=', $ref_code)->first()) { + if (config('SETTINGS::REFERRAL:MODE') == 'sign-up' || config('SETTINGS::REFERRAL:MODE') == 'both') { + $ref_user->increment('credits', config('SETTINGS::REFERRAL::REWARD')); $ref_user->notify(new ReferralNotification($ref_user->id, $new_user)); //LOGS REFERRALS IN THE ACTIVITY LOG activity() ->performedOn($user) ->causedBy($ref_user) - ->log('gained '. config("SETTINGS::REFERRAL::REWARD").' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for sign-up-referral of '.$user->name.' (ID:'.$user->id.')'); + ->log('gained '.config('SETTINGS::REFERRAL::REWARD').' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for sign-up-referral of '.$user->name.' (ID:'.$user->id.')'); } //INSERT INTO USER_REFERRALS TABLE DB::table('user_referrals')->insert([ 'referral_id' => $ref_user->id, 'registered_user_id' => $user->id, - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now() + 'created_at' => Carbon::now(), + 'updated_at' => Carbon::now(), ]); } - } return $user; diff --git a/app/Http/Controllers/Auth/SocialiteController.php b/app/Http/Controllers/Auth/SocialiteController.php index c91a18f3..101a367a 100644 --- a/app/Http/Controllers/Auth/SocialiteController.php +++ b/app/Http/Controllers/Auth/SocialiteController.php @@ -4,10 +4,7 @@ namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Models\DiscordUser; -use App\Models\Settings; use App\Models\User; -use App\Models\Voucher; -use Exception; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Http; use Laravel\Socialite\Facades\Socialite; @@ -16,7 +13,7 @@ class SocialiteController extends Controller { public function redirect() { - $scopes = !empty(config("SETTINGS::DISCORD:BOT_TOKEN")) && !empty(config("SETTINGS::DISCORD:GUILD_ID")) ? ['guilds.join'] : []; + $scopes = ! empty(config('SETTINGS::DISCORD:BOT_TOKEN')) && ! empty(config('SETTINGS::DISCORD:GUILD_ID')) ? ['guilds.join'] : []; return Socialite::driver('discord') ->scopes($scopes) @@ -32,40 +29,39 @@ class SocialiteController extends Controller /** @var User $user */ $user = Auth::user(); $discord = Socialite::driver('discord')->user(); - $botToken = config("SETTINGS::DISCORD:BOT_TOKEN"); - $guildId = config("SETTINGS::DISCORD:GUILD_ID"); - $roleId = config("SETTINGS::DISCORD:ROLE_ID"); + $botToken = config('SETTINGS::DISCORD:BOT_TOKEN'); + $guildId = config('SETTINGS::DISCORD:GUILD_ID'); + $roleId = config('SETTINGS::DISCORD:ROLE_ID'); - //save / update discord_users + //save / update discord_users - //check if discord account is already linked to an cpgg account - if (is_null($user->discordUser)) { - $discordLinked = DiscordUser::where('id', '=', $discord->id)->first(); - if ($discordLinked !== null) { - return redirect()->route('profile.index')->with( + //check if discord account is already linked to an cpgg account + if (is_null($user->discordUser)) { + $discordLinked = DiscordUser::where('id', '=', $discord->id)->first(); + if ($discordLinked !== null) { + return redirect()->route('profile.index')->with( 'error', 'Discord account already linked!' ); - } - - //create discord user in db - DiscordUser::create(array_merge($discord->user, ['user_id' => Auth::user()->id])); - - //update user - Auth::user()->increment('credits', config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD')); - Auth::user()->increment('server_limit', config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_DISCORD')); - Auth::user()->update(['discord_verified_at' => now()]); - - } else { - $user->discordUser->update($discord->user); } + //create discord user in db + DiscordUser::create(array_merge($discord->user, ['user_id' => Auth::user()->id])); + + //update user + Auth::user()->increment('credits', config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD')); + Auth::user()->increment('server_limit', config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_DISCORD')); + Auth::user()->update(['discord_verified_at' => now()]); + } else { + $user->discordUser->update($discord->user); + } + //force user into discord server //TODO Add event on failure, to notify ppl involved - if (!empty($guildId) && !empty($botToken)) { + if (! empty($guildId) && ! empty($botToken)) { $response = Http::withHeaders( [ - 'Authorization' => 'Bot ' . $botToken, + 'Authorization' => 'Bot '.$botToken, 'Content-Type' => 'application/json', ] )->put( @@ -74,10 +70,10 @@ class SocialiteController extends Controller ); //give user a role in the discord server - if (!empty($roleId)) { + if (! empty($roleId)) { $response = Http::withHeaders( [ - 'Authorization' => 'Bot ' . $botToken, + 'Authorization' => 'Bot '.$botToken, 'Content-Type' => 'application/json', ] )->put( diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 472d0345..ce72d947 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -12,22 +12,26 @@ use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\URL; - class HomeController extends Controller { - const TIME_LEFT_BG_SUCCESS = "bg-success"; - const TIME_LEFT_BG_WARNING = "bg-warning"; - const TIME_LEFT_BG_DANGER = "bg-danger"; + const TIME_LEFT_BG_SUCCESS = 'bg-success'; + + const TIME_LEFT_BG_WARNING = 'bg-warning'; + + const TIME_LEFT_BG_DANGER = 'bg-danger'; public function __construct() { $this->middleware('auth'); } - public function callHome(){ - if(Storage::exists("callHome")){return;} + public function callHome() + { + if (Storage::exists('callHome')) { + return; + } Http::asForm()->post('https://market.controlpanel.gg/callhome.php', [ - 'id' => Hash::make(URL::current()) + 'id' => Hash::make(URL::current()), ]); Storage::put('callHome', 'This is only used to count the installations of cpgg.'); } @@ -35,8 +39,7 @@ class HomeController extends Controller /** * @description Get the Background Color for the Days-Left-Box in HomeView * - * @param float $daysLeft - * + * @param float $daysLeft * @return string */ public function getTimeLeftBoxBackground(float $daysLeft): string @@ -47,36 +50,40 @@ class HomeController extends Controller if ($daysLeft <= 7) { return $this::TIME_LEFT_BG_DANGER; } + return $this::TIME_LEFT_BG_WARNING; } - /** * @description Set "hours", "days" or nothing behind the remaining time * - * @param float $daysLeft - * @param float $hoursLeft - * + * @param float $daysLeft + * @param float $hoursLeft * @return string|void */ public function getTimeLeftBoxUnit(float $daysLeft, float $hoursLeft) { - if ($daysLeft > 1) return __('days'); - return $hoursLeft < 1 ? null : __("hours"); + if ($daysLeft > 1) { + return __('days'); + } + + return $hoursLeft < 1 ? null : __('hours'); } /** * @description Get the Text for the Days-Left-Box in HomeView * - * @param float $daysLeft - * @param float $hoursLeft - * + * @param float $daysLeft + * @param float $hoursLeft * @return string */ public function getTimeLeftBoxText(float $daysLeft, float $hoursLeft) { - if ($daysLeft > 1) return strval(number_format($daysLeft, 0)); - return ($hoursLeft < 1 ? __("You ran out of Credits") : strval($hoursLeft)); + if ($daysLeft > 1) { + return strval(number_format($daysLeft, 0)); + } + + return $hoursLeft < 1 ? __('You ran out of Credits') : strval($hoursLeft); } /** Show the application dashboard. */ @@ -84,9 +91,9 @@ class HomeController extends Controller { $usage = Auth::user()->creditUsage(); $credits = Auth::user()->Credits(); - $bg = ""; - $boxText = ""; - $unit = ""; + $bg = ''; + $boxText = ''; + $unit = ''; /** Build our Time-Left-Box */ if ($credits > 0.01 and $usage > 0) { @@ -95,7 +102,7 @@ class HomeController extends Controller $bg = $this->getTimeLeftBoxBackground($daysLeft); $boxText = $this->getTimeLeftBoxText($daysLeft, $hoursLeft); - $unit = $daysLeft < 1 ? ($hoursLeft < 1 ? null : __("hours")) : __("days"); + $unit = $daysLeft < 1 ? ($hoursLeft < 1 ? null : __('hours')) : __('days'); } $this->callhome(); @@ -108,9 +115,9 @@ class HomeController extends Controller 'bg' => $bg, 'boxText' => $boxText, 'unit' => $unit, - 'numberOfReferrals' => DB::table('user_referrals')->where("referral_id","=",Auth::user()->id)->count(), + 'numberOfReferrals' => DB::table('user_referrals')->where('referral_id', '=', Auth::user()->id)->count(), 'partnerDiscount' => PartnerDiscount::where('user_id', Auth::user()->id)->first(), - 'myDiscount' => PartnerDiscount::getDiscount() + 'myDiscount' => PartnerDiscount::getDiscount(), ]); } } diff --git a/app/Http/Controllers/Moderation/TicketsController.php b/app/Http/Controllers/Moderation/TicketsController.php index ac08ba08..3a6787ac 100644 --- a/app/Http/Controllers/Moderation/TicketsController.php +++ b/app/Http/Controllers/Moderation/TicketsController.php @@ -2,63 +2,71 @@ namespace App\Http\Controllers\Moderation; -use App\Models\User; -use App\Models\Ticket; +use App\Http\Controllers\Controller; use App\Models\Server; +use App\Models\Ticket; +use App\Models\TicketBlacklist; use App\Models\TicketCategory; use App\Models\TicketComment; -use App\Models\TicketBlacklist; - -use App\Http\Controllers\Controller; -use Illuminate\Support\Facades\Cache; +use App\Models\User; +use App\Notifications\Ticket\User\ReplyNotification; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; -use App\Notifications\Ticket\User\ReplyNotification; class TicketsController extends Controller { - public function index() { - $tickets = Ticket::orderBy('id','desc')->paginate(10); + public function index() + { + $tickets = Ticket::orderBy('id', 'desc')->paginate(10); $ticketcategories = TicketCategory::all(); - return view("moderator.ticket.index", compact("tickets", "ticketcategories")); + + return view('moderator.ticket.index', compact('tickets', 'ticketcategories')); } - public function show($ticket_id) { - $ticket = Ticket::where("ticket_id", $ticket_id)->firstOrFail(); + + public function show($ticket_id) + { + $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail(); $ticketcomments = $ticket->ticketcomments; $ticketcategory = $ticket->ticketcategory; $server = Server::where('id', $ticket->server)->first(); - return view("moderator.ticket.show", compact("ticket", "ticketcategory", "ticketcomments", "server")); + + return view('moderator.ticket.show', compact('ticket', 'ticketcategory', 'ticketcomments', 'server')); } - public function close($ticket_id) { - $ticket = Ticket::where("ticket_id", $ticket_id)->firstOrFail(); - $ticket->status = "Closed"; + public function close($ticket_id) + { + $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail(); + $ticket->status = 'Closed'; $ticket->save(); $ticketOwner = $ticket->user; - return redirect()->back()->with('success', __('A ticket has been closed, ID: #') . $ticket->ticket_id); + + return redirect()->back()->with('success', __('A ticket has been closed, ID: #').$ticket->ticket_id); } - public function delete($ticket_id){ - $ticket = Ticket::where("ticket_id", $ticket_id)->firstOrFail(); - TicketComment::where("ticket_id", $ticket->id)->delete(); + public function delete($ticket_id) + { + $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail(); + TicketComment::where('ticket_id', $ticket->id)->delete(); $ticket->delete(); - return redirect()->back()->with('success', __('A ticket has been deleted, ID: #') . $ticket_id); + return redirect()->back()->with('success', __('A ticket has been deleted, ID: #').$ticket_id); } - public function reply(Request $request) { - $this->validate($request, array("ticketcomment" => "required")); - $ticket = Ticket::where('id', $request->input("ticket_id"))->firstOrFail(); - $ticket->status = "Answered"; + public function reply(Request $request) + { + $this->validate($request, ['ticketcomment' => 'required']); + $ticket = Ticket::where('id', $request->input('ticket_id'))->firstOrFail(); + $ticket->status = 'Answered'; $ticket->update(); - TicketComment::create(array( - "ticket_id" => $request->input("ticket_id"), - "user_id" => Auth::user()->id, - "ticketcomment" => $request->input("ticketcomment"), - )); + TicketComment::create([ + 'ticket_id' => $request->input('ticket_id'), + 'user_id' => Auth::user()->id, + 'ticketcomment' => $request->input('ticketcomment'), + ]); $user = User::where('id', $ticket->user_id)->firstOrFail(); - $newmessage = $request->input("ticketcomment"); + $newmessage = $request->input('ticketcomment'); $user->notify(new ReplyNotification($ticket, $user, $newmessage)); + return redirect()->back()->with('success', __('Your comment has been submitted')); } @@ -71,23 +79,23 @@ class TicketsController extends Controller return $tickets->ticketcategory->name; }) ->editColumn('title', function (Ticket $tickets) { - return '' . "#" . $tickets->ticket_id . " - " . $tickets->title . ''; + return ''.'#'.$tickets->ticket_id.' - '.$tickets->title.''; }) ->editColumn('user_id', function (Ticket $tickets) { - return '' . $tickets->user->name . ''; + return ''.$tickets->user->name.''; }) ->addColumn('actions', function (Ticket $tickets) { return ' - -
- ' . csrf_field() . ' - ' . method_field("POST") . ' - + + + '.csrf_field().' + '.method_field('POST').' +
-
- ' . csrf_field() . ' - ' . method_field("POST") . ' - + + '.csrf_field().' + '.method_field('POST').' +
'; }) @@ -107,7 +115,7 @@ class TicketsController extends Controller break; } - return '' . $tickets->status . ''; + return ''.$tickets->status.''; }) ->editColumn('updated_at', function (Ticket $tickets) { return $tickets->updated_at ? $tickets->updated_at->diffForHumans() : ''; @@ -116,84 +124,89 @@ class TicketsController extends Controller ->make(true); } - public function blacklist() { - return view("moderator.ticket.blacklist"); + public function blacklist() + { + return view('moderator.ticket.blacklist'); } - public function blacklistAdd(Request $request) { + public function blacklistAdd(Request $request) + { $user = User::where('id', $request->user_id)->first(); $check = TicketBlacklist::where('user_id', $user->id)->first(); - if($check){ + if ($check) { $check->reason = $request->reason; - $check->status = "True"; + $check->status = 'True'; $check->save(); return redirect()->back()->with('info', __('Target User already in blacklist. Reason updated')); } - TicketBlacklist::create(array( - "user_id" => $user->id, - "status" => "True", - "reason" => $request->reason, - )); - return redirect()->back()->with('success', __('Successfully add User to blacklist, User name: ' . $user->name)); + TicketBlacklist::create([ + 'user_id' => $user->id, + 'status' => 'True', + 'reason' => $request->reason, + ]); + + return redirect()->back()->with('success', __('Successfully add User to blacklist, User name: '.$user->name)); } - - public function blacklistDelete($id) { + public function blacklistDelete($id) + { $blacklist = TicketBlacklist::where('id', $id)->first(); $blacklist->delete(); - return redirect()->back()->with('success', __('Successfully remove User from blacklist, User name: ' . $blacklist->user->name)); + + return redirect()->back()->with('success', __('Successfully remove User from blacklist, User name: '.$blacklist->user->name)); } - public function blacklistChange($id) { + public function blacklistChange($id) + { $blacklist = TicketBlacklist::where('id', $id)->first(); - if($blacklist->status == "True") - { - $blacklist->status = "False"; - + if ($blacklist->status == 'True') { + $blacklist->status = 'False'; } else { - $blacklist->status = "True"; + $blacklist->status = 'True'; } $blacklist->update(); - return redirect()->back()->with('success', __('Successfully change status blacklist from, User name: ' . $blacklist->user->name)); + return redirect()->back()->with('success', __('Successfully change status blacklist from, User name: '.$blacklist->user->name)); } + public function dataTableBlacklist() { $query = TicketBlacklist::with(['user']); $query->select('ticket_blacklists.*'); + return datatables($query) ->editColumn('user', function (TicketBlacklist $blacklist) { - return '' . $blacklist->user->name . ''; + return ''.$blacklist->user->name.''; }) ->editColumn('status', function (TicketBlacklist $blacklist) { switch ($blacklist->status) { case 'True': - $text = "Blocked"; + $text = 'Blocked'; $badgeColor = 'badge-danger'; break; default: - $text = "Unblocked"; + $text = 'Unblocked'; $badgeColor = 'badge-success'; break; } - return '' . $text . ''; + return ''.$text.''; }) ->editColumn('reason', function (TicketBlacklist $blacklist) { return $blacklist->reason; }) ->addColumn('actions', function (TicketBlacklist $blacklist) { return ' -
- ' . csrf_field() . ' - ' . method_field("POST") . ' - + + '.csrf_field().' + '.method_field('POST').' +
-
- ' . csrf_field() . ' - ' . method_field("POST") . ' - + + '.csrf_field().' + '.method_field('POST').' +
'; }) @@ -203,5 +216,4 @@ class TicketsController extends Controller ->rawColumns(['user', 'status', 'reason', 'created_at', 'actions']) ->make(true); } - } diff --git a/app/Http/Controllers/NotificationController.php b/app/Http/Controllers/NotificationController.php index 7853c1ac..c8ee5912 100644 --- a/app/Http/Controllers/NotificationController.php +++ b/app/Http/Controllers/NotificationController.php @@ -10,8 +10,9 @@ class NotificationController extends Controller public function index() { $notifications = Auth::user()->notifications()->paginate(); + return view('notifications.index')->with([ - 'notifications' => $notifications + 'notifications' => $notifications, ]); } @@ -21,17 +22,19 @@ class NotificationController extends Controller $notification = Auth::user()->notifications()->findOrFail($id); $notification->markAsRead(); + return view('notifications.show')->with([ - 'notification' => $notification + 'notification' => $notification, ]); } - public function readAll(){ + public function readAll() + { $notifications = Auth::user()->notifications()->get(); - foreach($notifications as $notification){ + foreach ($notifications as $notification) { $notification->markAsRead(); } - return redirect()->back(); + return redirect()->back(); } } diff --git a/app/Http/Controllers/PartnerController.php b/app/Http/Controllers/PartnerController.php index bc546511..887e56d3 100644 --- a/app/Http/Controllers/PartnerController.php +++ b/app/Http/Controllers/PartnerController.php @@ -21,23 +21,23 @@ class PartnerController extends Controller public function create() { return view('admin.partners.create', [ - 'partners' =>PartnerDiscount::get(), - 'users' => User::orderBy('name')->get() + 'partners' => PartnerDiscount::get(), + 'users' => User::orderBy('name')->get(), ]); } /** * Store a newly created resource in storage. * - * @param Request $request + * @param Request $request * @return RedirectResponse */ public function store(Request $request) { $request->validate([ - 'user_id' => 'required|integer|min:0', - 'partner_discount' => 'required|integer|max:100|min:0', - 'registered_user_discount' => 'required|integer|max:100|min:0' + 'user_id' => 'required|integer|min:0', + 'partner_discount' => 'required|integer|max:100|min:0', + 'registered_user_discount' => 'required|integer|max:100|min:0', ]); PartnerDiscount::create($request->all()); @@ -48,7 +48,7 @@ class PartnerController extends Controller /** * Display the specified resource. * - * @param Voucher $voucher + * @param Voucher $voucher * @return Response */ public function show(Voucher $voucher) @@ -59,32 +59,32 @@ class PartnerController extends Controller /** * Show the form for editing the specified resource. * - * @param Voucher $voucher + * @param Voucher $voucher * @return Application|Factory|View */ public function edit(PartnerDiscount $partner) { return view('admin.partners.edit', [ - 'partners' =>PartnerDiscount::get(), - 'partner' => $partner, - 'users' => User::orderBy('name')->get() + 'partners' => PartnerDiscount::get(), + 'partner' => $partner, + 'users' => User::orderBy('name')->get(), ]); } /** * Update the specified resource in storage. * - * @param Request $request - * @param Voucher $voucher + * @param Request $request + * @param Voucher $voucher * @return RedirectResponse */ public function update(Request $request, PartnerDiscount $partner) { //dd($request); $request->validate([ - 'user_id' => 'required|integer|min:0', - 'partner_discount' => 'required|integer|max:100|min:0', - 'registered_user_discount' => 'required|integer|max:100|min:0' + 'user_id' => 'required|integer|min:0', + 'partner_discount' => 'required|integer|max:100|min:0', + 'registered_user_discount' => 'required|integer|max:100|min:0', ]); $partner->update($request->all()); @@ -95,61 +95,71 @@ class PartnerController extends Controller /** * Remove the specified resource from storage. * - * @param Voucher $voucher + * @param Voucher $voucher * @return RedirectResponse */ public function destroy(PartnerDiscount $partner) { $partner->delete(); + return redirect()->back()->with('success', __('partner has been removed!')); } public function users(Voucher $voucher) { return view('admin.vouchers.users', [ - 'voucher' => $voucher + 'voucher' => $voucher, ]); } /** - * @param Request $request + * @param Request $request * @return JsonResponse + * * @throws ValidationException */ public function redeem(Request $request) { - #general validations + //general validations $request->validate([ - 'code' => 'required|exists:vouchers,code' + 'code' => 'required|exists:vouchers,code', ]); - #get voucher by code + //get voucher by code $voucher = Voucher::where('code', '=', $request->input('code'))->firstOrFail(); - #extra validations - if ($voucher->getStatus() == 'USES_LIMIT_REACHED') throw ValidationException::withMessages([ - 'code' => __('This voucher has reached the maximum amount of uses') - ]); + //extra validations + if ($voucher->getStatus() == 'USES_LIMIT_REACHED') { + throw ValidationException::withMessages([ + 'code' => __('This voucher has reached the maximum amount of uses'), + ]); + } - if ($voucher->getStatus() == 'EXPIRED') throw ValidationException::withMessages([ - 'code' => __('This voucher has expired') - ]); + if ($voucher->getStatus() == 'EXPIRED') { + throw ValidationException::withMessages([ + 'code' => __('This voucher has expired'), + ]); + } - if (!$request->user()->vouchers()->where('id', '=', $voucher->id)->get()->isEmpty()) throw ValidationException::withMessages([ - 'code' => __('You already redeemed this voucher code') - ]); + if (! $request->user()->vouchers()->where('id', '=', $voucher->id)->get()->isEmpty()) { + throw ValidationException::withMessages([ + 'code' => __('You already redeemed this voucher code'), + ]); + } - if ($request->user()->credits + $voucher->credits >= 99999999) throw ValidationException::withMessages([ - 'code' => "You can't redeem this voucher because you would exceed the limit of " . CREDITS_DISPLAY_NAME - ]); + if ($request->user()->credits + $voucher->credits >= 99999999) { + throw ValidationException::withMessages([ + 'code' => "You can't redeem this voucher because you would exceed the limit of ".CREDITS_DISPLAY_NAME, + ]); + } - #redeem voucher + //redeem voucher $voucher->redeem($request->user()); event(new UserUpdateCreditsEvent($request->user())); return response()->json([ - 'success' => "{$voucher->credits} " . CREDITS_DISPLAY_NAME ." ". __("have been added to your balance!") + 'success' => "{$voucher->credits} ".CREDITS_DISPLAY_NAME.' '.__('have been added to your balance!'), ]); } @@ -159,10 +169,10 @@ class PartnerController extends Controller return datatables($users) ->editColumn('name', function (User $user) { - return '' . $user->name . ''; + return ''.$user->name.''; }) ->addColumn('credits', function (User $user) { - return ' ' . $user->credits(); + return ' '.$user->credits(); }) ->addColumn('last_seen', function (User $user) { return $user->last_seen ? $user->last_seen->diffForHumans() : ''; @@ -170,6 +180,7 @@ class PartnerController extends Controller ->rawColumns(['name', 'credits', 'last_seen']) ->make(); } + public function dataTable() { $query = PartnerDiscount::query(); @@ -177,30 +188,30 @@ class PartnerController extends Controller return datatables($query) ->addColumn('actions', function (PartnerDiscount $partner) { return ' - -
- ' . csrf_field() . ' - ' . method_field("DELETE") . ' - + + + '.csrf_field().' + '.method_field('DELETE').' +
'; }) ->addColumn('user', function (PartnerDiscount $partner) { - return ($user=User::where('id', $partner->user_id)->first())?''.$user->name.'':__('Unknown user'); + return ($user = User::where('id', $partner->user_id)->first()) ? ''.$user->name.'' : __('Unknown user'); }) ->editColumn('created_at', function (PartnerDiscount $partner) { return $partner->created_at ? $partner->created_at->diffForHumans() : ''; }) ->editColumn('partner_discount', function (PartnerDiscount $partner) { - return $partner->partner_discount ? $partner->partner_discount . "%" : "0%"; + return $partner->partner_discount ? $partner->partner_discount.'%' : '0%'; }) ->editColumn('registered_user_discount', function (PartnerDiscount $partner) { - return $partner->registered_user_discount ? $partner->registered_user_discount . "%" : "0%"; + return $partner->registered_user_discount ? $partner->registered_user_discount.'%' : '0%'; }) ->editColumn('referral_system_commission', function (PartnerDiscount $partner) { - return $partner->referral_system_commission>=0 ? $partner->referral_system_commission . "%" : __('Default') . " (" . config("SETTINGS::REFERRAL:PERCENTAGE") . "%)"; + return $partner->referral_system_commission >= 0 ? $partner->referral_system_commission.'%' : __('Default').' ('.config('SETTINGS::REFERRAL:PERCENTAGE').'%)'; }) ->rawColumns(['user', 'actions']) ->make(); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index 61e480f0..117ac33e 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -16,15 +16,18 @@ class ProductController extends Controller { /** * @description get product locations based on selected egg - * @param Request $request - * @param Egg $egg + * + * @param Request $request + * @param Egg $egg * @return Collection|JsonResponse */ public function getNodesBasedOnEgg(Request $request, Egg $egg) { - if (is_null($egg->id)) return response()->json('Egg ID is required', '400'); + if (is_null($egg->id)) { + return response()->json('Egg ID is required', '400'); + } - #get products that include this egg + //get products that include this egg $products = Product::query() ->with('nodes') ->where('disabled', '=', false) @@ -34,31 +37,33 @@ class ProductController extends Controller $nodes = collect(); - #filter unique nodes + //filter unique nodes $products->each(function (Product $product) use ($nodes) { $product->nodes->each(function (Node $node) use ($nodes) { - if (!$nodes->contains('id', $node->id) && !$node->disabled) { + if (! $nodes->contains('id', $node->id) && ! $node->disabled) { $nodes->add($node); } }); }); - return $nodes; } /** * @description get product locations based on selected egg - * @param Request $request - * @param Egg $egg + * + * @param Request $request + * @param Egg $egg * @return Collection|JsonResponse */ public function getLocationsBasedOnEgg(Request $request, Egg $egg) { $nodes = $this->getNodesBasedOnEgg($request, $egg); - foreach($nodes as $key => $node){ + foreach ($nodes as $key => $node) { $pteroNode = Pterodactyl::getNode($node->id); - if($pteroNode['allocated_resources']['memory']>=($pteroNode['memory']*($pteroNode['memory_overallocate']+100)/100)||$pteroNode['allocated_resources']['disk']>=($pteroNode['disk']*($pteroNode['disk_overallocate']+100)/100)) $nodes->forget($key); + if ($pteroNode['allocated_resources']['memory'] >= ($pteroNode['memory'] * ($pteroNode['memory_overallocate'] + 100) / 100) || $pteroNode['allocated_resources']['disk'] >= ($pteroNode['disk'] * ($pteroNode['disk_overallocate'] + 100) / 100)) { + $nodes->forget($key); + } } $locations = collect(); @@ -67,7 +72,7 @@ class ProductController extends Controller /** @var Location $location */ $location = $node->location; - if (!$locations->contains('id', $location->id)) { + if (! $locations->contains('id', $location->id)) { $nodeIds = $nodes->map(function ($node) { return $node->id; }); @@ -84,13 +89,15 @@ class ProductController extends Controller } /** - * @param Node $node - * @param Egg $egg + * @param Node $node + * @param Egg $egg * @return Collection|JsonResponse */ public function getProductsBasedOnNode(Egg $egg, Node $node) { - if (is_null($egg->id) || is_null($node->id)) return response()->json('node and egg id is required', '400'); + if (is_null($egg->id) || is_null($node->id)) { + return response()->json('node and egg id is required', '400'); + } $products = Product::query() ->where('disabled', '=', false) @@ -103,8 +110,10 @@ class ProductController extends Controller ->get(); $pteroNode = Pterodactyl::getNode($node->id); - foreach($products as $key => $product){ - if($product->memory>($pteroNode['memory']*($pteroNode['memory_overallocate']+100)/100)-$pteroNode['allocated_resources']['memory']||$product->disk>($pteroNode['disk']*($pteroNode['disk_overallocate']+100)/100)-$pteroNode['allocated_resources']['disk']) $product->doesNotFit = true; + foreach ($products as $key => $product) { + if ($product->memory > ($pteroNode['memory'] * ($pteroNode['memory_overallocate'] + 100) / 100) - $pteroNode['allocated_resources']['memory'] || $product->disk > ($pteroNode['disk'] * ($pteroNode['disk_overallocate'] + 100) / 100) - $pteroNode['allocated_resources']['disk']) { + $product->doesNotFit = true; + } } return $products; diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index 0a555493..94bff453 100644 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -2,7 +2,6 @@ namespace App\Http\Controllers; - use App\Classes\Pterodactyl; use App\Models\User; use Illuminate\Http\RedirectResponse; @@ -30,6 +29,7 @@ class ProfileController extends Controller $badgeColor = 'badge-secondary'; break; } + return view('profile.index')->with([ 'user' => Auth::user(), 'credits_reward_after_verify_discord' => config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD'), @@ -39,80 +39,81 @@ class ProfileController extends Controller ]); } + public function selfDestroyUser() + { + $user = Auth::user(); + //if ($user->role == "admin") return back()->with("error", "You cannot delete yourself as an admin!"); + $user->delete(); - public function selfDestroyUser(){ - - $user = Auth::user(); - //if ($user->role == "admin") return back()->with("error", "You cannot delete yourself as an admin!"); - - $user->delete(); - return redirect("/login")->with('success', __("Account permanently deleted!")); - + return redirect('/login')->with('success', __('Account permanently deleted!')); } /** Update the specified resource in storage. - * @param Request $request - * @param int $id + * @param Request $request + * @param int $id * @return RedirectResponse */ public function update(Request $request, int $id) { //prevent other users from editing a user - if ($id != Auth::user()->id) dd(401); + if ($id != Auth::user()->id) { + dd(401); + } $user = User::findOrFail($id); //update password if necessary - if (!is_null($request->input('new_password'))) { + if (! is_null($request->input('new_password'))) { //validate password request $request->validate([ 'current_password' => [ 'required', function ($attribute, $value, $fail) use ($user) { - if (!Hash::check($value, $user->password)) { - $fail('The ' . $attribute . ' is invalid.'); + if (! Hash::check($value, $user->password)) { + $fail('The '.$attribute.' is invalid.'); } }, ], 'new_password' => 'required|string|min:8', - 'new_password_confirmation' => 'required|same:new_password' + 'new_password_confirmation' => 'required|same:new_password', ]); //Update Users Password on Pterodactyl //Username,Mail,First and Lastname are required aswell $response = Pterodactyl::client()->patch('/application/users/'.$user->pterodactyl_id, [ - "password" => $request->input('new_password'), - "username" => $request->input('name'), - "first_name" => $request->input('name'), - "last_name" => $request->input('name'), - "email" => $request->input('email'), + 'password' => $request->input('new_password'), + 'username' => $request->input('name'), + 'first_name' => $request->input('name'), + 'last_name' => $request->input('name'), + 'email' => $request->input('email'), ]); if ($response->failed()) { throw ValidationException::withMessages([ 'pterodactyl_error_message' => $response->toException()->getMessage(), - 'pterodactyl_error_status' => $response->toException()->getCode() + 'pterodactyl_error_status' => $response->toException()->getCode(), ]); } //update password $user->update([ 'password' => Hash::make($request->input('new_password')), ]); - } //validate request $request->validate([ - 'name' => 'required|min:4|max:30|alpha_num|unique:users,name,' . $id . ',id', - 'email' => 'required|email|max:64|unique:users,email,' . $id . ',id', - 'avatar' => 'nullable' + 'name' => 'required|min:4|max:30|alpha_num|unique:users,name,'.$id.',id', + 'email' => 'required|email|max:64|unique:users,email,'.$id.',id', + 'avatar' => 'nullable', ]); //update avatar - if (!is_null($request->input('avatar'))) { + if (! is_null($request->input('avatar'))) { $avatar = json_decode($request->input('avatar')); - if ($avatar->input->size > 3000000) abort(500); + if ($avatar->input->size > 3000000) { + abort(500); + } $user->update([ 'avatar' => $avatar->output->image, @@ -125,16 +126,16 @@ class ProfileController extends Controller //update name and email on Pterodactyl $response = Pterodactyl::client()->patch('/application/users/'.$user->pterodactyl_id, [ - "username" => $request->input('name'), - "first_name" => $request->input('name'), - "last_name" => $request->input('name'), - "email" => $request->input('email'), + 'username' => $request->input('name'), + 'first_name' => $request->input('name'), + 'last_name' => $request->input('name'), + 'email' => $request->input('email'), ]); if ($response->failed()) { throw ValidationException::withMessages([ 'pterodactyl_error_message' => $response->toException()->getMessage(), - 'pterodactyl_error_status' => $response->toException()->getCode() + 'pterodactyl_error_status' => $response->toException()->getCode(), ]); } @@ -147,7 +148,7 @@ class ProfileController extends Controller if ($request->input('email') != Auth::user()->email) { $user->reVerifyEmail(); $user->sendEmailVerificationNotification(); - }; + } return redirect()->route('profile.index')->with('success', __('Profile updated')); } diff --git a/app/Http/Controllers/ServerController.php b/app/Http/Controllers/ServerController.php index 905c702c..8ddd22a6 100644 --- a/app/Http/Controllers/ServerController.php +++ b/app/Http/Controllers/ServerController.php @@ -31,7 +31,9 @@ class ServerController extends Controller //Get server infos from ptero $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id, true); - if(!$serverAttributes) continue; + if (! $serverAttributes) { + continue; + } $serverRelationships = $serverAttributes['relationships']; $serverLocationAttributes = $serverRelationships['location']['attributes']; @@ -47,7 +49,7 @@ class ServerController extends Controller //Check if a server got renamed on Pterodactyl $savedServer = Server::query()->where('id', $server->id)->first(); - if($savedServer->name != $serverAttributes['name']){ + if ($savedServer->name != $serverAttributes['name']) { $savedServer->name = $serverAttributes['name']; $server->name = $serverAttributes['name']; $savedServer->save(); @@ -59,14 +61,16 @@ class ServerController extends Controller } return view('servers.index')->with([ - 'servers' => $servers + 'servers' => $servers, ]); } /** Show the form for creating a new resource. */ public function create() { - if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules(); + if (! is_null($this->validateConfigurationRules())) { + return $this->validateConfigurationRules(); + } $productCount = Product::query()->where('disabled', '=', false)->count(); $locations = Location::all(); @@ -90,11 +94,11 @@ class ServerController extends Controller return view('servers.create')->with([ 'productCount' => $productCount, - 'nodeCount' => $nodeCount, - 'nests' => $nests, - 'locations' => $locations, - 'eggs' => $eggs, - 'user' => Auth::user(), + 'nodeCount' => $nodeCount, + 'nests' => $nests, + 'locations' => $locations, + 'eggs' => $eggs, + 'user' => Auth::user(), ]); } @@ -109,8 +113,8 @@ class ServerController extends Controller } // minimum credits && Check for Allocation - if (FacadesRequest::has("product")) { - $product = Product::findOrFail(FacadesRequest::input("product")); + if (FacadesRequest::has('product')) { + $product = Product::findOrFail(FacadesRequest::input('product')); // Get node resource allocation info $node = $product->nodes()->findOrFail(FacadesRequest::input('node')); @@ -118,7 +122,9 @@ class ServerController extends Controller // Check if node has enough memory and disk space $checkResponse = Pterodactyl::checkNodeResources($node, $product->memory, $product->disk); - if ($checkResponse == False) return redirect()->route('servers.index')->with('error', __("The node '" . $nodeName . "' doesn't have the required memory or disk left to allocate this product.")); + if ($checkResponse == false) { + return redirect()->route('servers.index')->with('error', __("The node '".$nodeName."' doesn't have the required memory or disk left to allocate this product.")); + } // Min. Credits if ( @@ -127,24 +133,24 @@ class ServerController extends Controller ? config('SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER', 50) : $product->minimum_credits) ) { - return redirect()->route('servers.index')->with('error', "You do not have the required amount of " . CREDITS_DISPLAY_NAME . " to use this product!"); + return redirect()->route('servers.index')->with('error', 'You do not have the required amount of '.CREDITS_DISPLAY_NAME.' to use this product!'); } } //Required Verification for creating an server - if (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', 'false') === 'true' && !Auth::user()->hasVerifiedEmail()) { - return redirect()->route('profile.index')->with('error', __("You are required to verify your email address before you can create a server.")); - } - - //Required Verification for creating an server - - if (!config('SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS', 'true') && Auth::user()->role != "admin") { - return redirect()->route('servers.index')->with('error', __("The system administrator has blocked the creation of new servers.")); + if (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', 'false') === 'true' && ! Auth::user()->hasVerifiedEmail()) { + return redirect()->route('profile.index')->with('error', __('You are required to verify your email address before you can create a server.')); } //Required Verification for creating an server - if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', 'false') === 'true' && !Auth::user()->discordUser) { - return redirect()->route('profile.index')->with('error', __("You are required to link your discord account before you can create a server.")); + + if (! config('SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS', 'true') && Auth::user()->role != 'admin') { + return redirect()->route('servers.index')->with('error', __('The system administrator has blocked the creation of new servers.')); + } + + //Required Verification for creating an server + if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', 'false') === 'true' && ! Auth::user()->discordUser) { + return redirect()->route('profile.index')->with('error', __('You are required to link your discord account before you can create a server.')); } return null; @@ -156,14 +162,15 @@ class ServerController extends Controller /** @var Node $node */ /** @var Egg $egg */ /** @var Product $product */ - - if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules(); + if (! is_null($this->validateConfigurationRules())) { + return $this->validateConfigurationRules(); + } $request->validate([ - "name" => "required|max:191", - "node" => "required|exists:nodes,id", - "egg" => "required|exists:eggs,id", - "product" => "required|exists:products,id" + 'name' => 'required|max:191', + 'node' => 'required|exists:nodes,id', + 'egg' => 'required|exists:eggs,id', + 'product' => 'required|exists:products,id', ]); //get required resources @@ -172,23 +179,27 @@ class ServerController extends Controller $node = $product->nodes()->findOrFail($request->input('node')); $server = $request->user()->servers()->create([ - 'name' => $request->input('name'), + 'name' => $request->input('name'), 'product_id' => $request->input('product'), ]); //get free allocation ID $allocationId = Pterodactyl::getFreeAllocationId($node); - if (!$allocationId) return $this->noAllocationsError($server); + if (! $allocationId) { + return $this->noAllocationsError($server); + } //create server on pterodactyl $response = Pterodactyl::createServer($server, $egg, $allocationId); - if ($response->failed()) return $this->serverCreationFailed($response, $server); + if ($response->failed()) { + return $this->serverCreationFailed($response, $server); + } $serverAttributes = $response->json()['attributes']; //update server with pterodactyl_id $server->update([ 'pterodactyl_id' => $serverAttributes['id'], - 'identifier' => $serverAttributes['identifier'] + 'identifier' => $serverAttributes['identifier'], ]); if (config('SETTINGS::SYSTEM:SERVER_CREATE_CHARGE_FIRST_HOUR', 'true') == 'true') { @@ -202,7 +213,8 @@ class ServerController extends Controller /** * return redirect with error - * @param Server $server + * + * @param Server $server * @return RedirectResponse */ private function noAllocationsError(Server $server) @@ -210,13 +222,15 @@ class ServerController extends Controller $server->delete(); Auth::user()->notify(new ServerCreationError($server)); + return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.')); } /** * return redirect with error - * @param Response $response - * @param Server $server + * + * @param Response $response + * @param Server $server * @return RedirectResponse */ private function serverCreationFailed(Response $response, Server $server) @@ -231,18 +245,19 @@ class ServerController extends Controller { try { $server->delete(); + return redirect()->route('servers.index')->with('success', __('Server removed')); } catch (Exception $e) { - return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource "') . $e->getMessage() . '"'); + return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource "').$e->getMessage().'"'); } } /** Show Server Settings */ public function show(Server $server) { - - - if($server->user_id != Auth::user()->id){ return back()->with('error', __('´This is not your Server!'));} + if ($server->user_id != Auth::user()->id) { + return back()->with('error', __('´This is not your Server!')); + } $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id); $serverRelationships = $serverAttributes['relationships']; $serverLocationAttributes = $serverRelationships['location']['attributes']; @@ -261,7 +276,7 @@ class ServerController extends Controller $pteroNode = Pterodactyl::getNode($serverRelationships['node']['attributes']['id']); - $products = Product::orderBy("created_at") + $products = Product::orderBy('created_at') ->whereHas('nodes', function (Builder $builder) use ($serverRelationships) { //Only show products for that node $builder->where('id', '=', $serverRelationships['node']['attributes']['id']); }) @@ -270,20 +285,23 @@ class ServerController extends Controller // Set the each product eggs array to just contain the eggs name foreach ($products as $product) { $product->eggs = $product->eggs->pluck('name')->toArray(); - if($product->memory-$currentProduct->memory>($pteroNode['memory']*($pteroNode['memory_overallocate']+100)/100)-$pteroNode['allocated_resources']['memory']||$product->disk-$currentProduct->disk>($pteroNode['disk']*($pteroNode['disk_overallocate']+100)/100)-$pteroNode['allocated_resources']['disk']) $product->doesNotFit = true; + if ($product->memory - $currentProduct->memory > ($pteroNode['memory'] * ($pteroNode['memory_overallocate'] + 100) / 100) - $pteroNode['allocated_resources']['memory'] || $product->disk - $currentProduct->disk > ($pteroNode['disk'] * ($pteroNode['disk_overallocate'] + 100) / 100) - $pteroNode['allocated_resources']['disk']) { + $product->doesNotFit = true; + } } return view('servers.settings')->with([ 'server' => $server, - 'products' => $products + 'products' => $products, ]); } public function upgrade(Server $server, Request $request) { - if($server->user_id != Auth::user()->id) return redirect()->route('servers.index'); - if(!isset($request->product_upgrade)) - { + if ($server->user_id != Auth::user()->id) { + return redirect()->route('servers.index'); + } + if (! isset($request->product_upgrade)) { return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one')); } $user = Auth::user(); @@ -299,32 +317,35 @@ class ServerController extends Controller // Check if node has enough memory and disk space $requireMemory = $newProduct->memory - $oldProduct->memory; - $requiredisk = $newProduct->disk - $oldProduct->disk; + $requiredisk = $newProduct->disk - $oldProduct->disk; $checkResponse = Pterodactyl::checkNodeResources($node, $requireMemory, $requiredisk); - if ($checkResponse == False) return redirect()->route('servers.index')->with('error', __("The node '" . $nodeName . "' doesn't have the required memory or disk left to upgrade the server.")); + if ($checkResponse == false) { + return redirect()->route('servers.index')->with('error', __("The node '".$nodeName."' doesn't have the required memory or disk left to upgrade the server.")); + } $priceupgrade = $newProduct->getHourlyPrice(); if ($priceupgrade < $oldProduct->getHourlyPrice()) { - $priceupgrade = 0; + $priceupgrade = 0; } - if ($user->credits >= $priceupgrade && $user->credits >= $newProduct->minimum_credits) - { - + if ($user->credits >= $priceupgrade && $user->credits >= $newProduct->minimum_credits) { $server->product_id = $request->product_upgrade; $server->update(); $server->allocation = $serverAttributes['allocation']; $response = Pterodactyl::updateServer($server, $newProduct); - if ($response->failed()) return $this->serverCreationFailed($response, $server); + if ($response->failed()) { + return $this->serverCreationFailed($response, $server); + } //update user balance $user->decrement('credits', $priceupgrade); //restart the server - $response = Pterodactyl::powerAction($server, "restart"); - if ($response->failed()) return redirect()->route('servers.index')->with('error', $response->json()['errors'][0]['detail']); + $response = Pterodactyl::powerAction($server, 'restart'); + if ($response->failed()) { + return redirect()->route('servers.index')->with('error', $response->json()['errors'][0]['detail']); + } + return redirect()->route('servers.show', ['server' => $server->id])->with('success', __('Server Successfully Upgraded')); - } - else - { + } else { return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('Not Enough Balance for Upgrade')); } } diff --git a/app/Http/Controllers/StoreController.php b/app/Http/Controllers/StoreController.php index 8995d659..fb4efe3a 100644 --- a/app/Http/Controllers/StoreController.php +++ b/app/Http/Controllers/StoreController.php @@ -3,7 +3,6 @@ namespace App\Http\Controllers; use App\Models\ShopProduct; -use App\Models\Settings; use Illuminate\Support\Facades\Auth; class StoreController extends Controller @@ -15,18 +14,20 @@ class StoreController extends Controller if ( env('APP_ENV') == 'local' || - config("SETTINGS::PAYMENTS:PAYPAL:SECRET") && config("SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID") || - config("SETTINGS::PAYMENTS:STRIPE:SECRET") && config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET") && config("SETTINGS::PAYMENTS:STRIPE:METHODS") - ) $isPaymentSetup = true; - - //Required Verification for creating an server - if (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', false) === 'true' && !Auth::user()->hasVerifiedEmail()) { - return redirect()->route('profile.index')->with('error', __("You are required to verify your email address before you can purchase credits.")); + config('SETTINGS::PAYMENTS:PAYPAL:SECRET') && config('SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID') || + config('SETTINGS::PAYMENTS:STRIPE:SECRET') && config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET') && config('SETTINGS::PAYMENTS:STRIPE:METHODS') + ) { + $isPaymentSetup = true; } //Required Verification for creating an server - if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', false) === 'true' && !Auth::user()->discordUser) { - return redirect()->route('profile.index')->with('error', __("You are required to link your discord account before you can purchase Credits")); + if (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', false) === 'true' && ! Auth::user()->hasVerifiedEmail()) { + return redirect()->route('profile.index')->with('error', __('You are required to verify your email address before you can purchase credits.')); + } + + //Required Verification for creating an server + if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', false) === 'true' && ! Auth::user()->discordUser) { + return redirect()->route('profile.index')->with('error', __('You are required to link your discord account before you can purchase Credits')); } return view('store.index')->with([ diff --git a/app/Http/Controllers/TicketsController.php b/app/Http/Controllers/TicketsController.php index 8bb21a66..5e8d22dd 100644 --- a/app/Http/Controllers/TicketsController.php +++ b/app/Http/Controllers/TicketsController.php @@ -2,113 +2,121 @@ namespace App\Http\Controllers; -use App\Models\User; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Session; -use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Str; -use Illuminate\Support\Facades\Notification; - -use App\Models\Ticket; use App\Models\Server; -use App\Models\TicketComment; -use App\Models\TicketCategory; +use App\Models\Ticket; use App\Models\TicketBlacklist; -use App\Notifications\Ticket\User\CreateNotification; +use App\Models\TicketCategory; +use App\Models\TicketComment; +use App\Models\User; use App\Notifications\Ticket\Admin\AdminCreateNotification; use App\Notifications\Ticket\Admin\AdminReplyNotification; - +use App\Notifications\Ticket\User\CreateNotification; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Notification; +use Illuminate\Support\Str; class TicketsController extends Controller { public function index() { - $tickets = Ticket::where("user_id", Auth::user()->id)->paginate(10); + $tickets = Ticket::where('user_id', Auth::user()->id)->paginate(10); $ticketcategories = TicketCategory::all(); - - return view("ticket.index", compact("tickets", "ticketcategories")); + + return view('ticket.index', compact('tickets', 'ticketcategories')); } - public function create() { - #check in blacklist + + public function create() + { + //check in blacklist $check = TicketBlacklist::where('user_id', Auth::user()->id)->first(); - if($check && $check->status == "True"){ - return redirect()->route('ticket.index')->with('error', __("You can't make a ticket because you're on the blacklist for a reason: '" . $check->reason . "', please contact the administrator")); + if ($check && $check->status == 'True') { + return redirect()->route('ticket.index')->with('error', __("You can't make a ticket because you're on the blacklist for a reason: '".$check->reason."', please contact the administrator")); } $ticketcategories = TicketCategory::all(); $servers = Auth::user()->servers; - return view("ticket.create", compact("ticketcategories", "servers")); + + return view('ticket.create', compact('ticketcategories', 'servers')); } - public function store(Request $request) { - $this->validate($request, array( - "title" => "required", - "ticketcategory" => "required", - "priority" => "required", - "message" => "required") - ); - $ticket = new Ticket(array( - "title" => $request->input("title"), - "user_id" => Auth::user()->id, - "ticket_id" => strtoupper(Str::random(5)), - "ticketcategory_id" => $request->input("ticketcategory"), - "priority" => $request->input("priority"), - "message" => $request->input("message"), - "status" => "Open", - "server" => $request->input("server")) - ); + + public function store(Request $request) + { + $this->validate($request, [ + 'title' => 'required', + 'ticketcategory' => 'required', + 'priority' => 'required', + 'message' => 'required', ] + ); + $ticket = new Ticket([ + 'title' => $request->input('title'), + 'user_id' => Auth::user()->id, + 'ticket_id' => strtoupper(Str::random(5)), + 'ticketcategory_id' => $request->input('ticketcategory'), + 'priority' => $request->input('priority'), + 'message' => $request->input('message'), + 'status' => 'Open', + 'server' => $request->input('server'), ] + ); $ticket->save(); $user = Auth::user(); $admin = User::where('role', 'admin')->orWhere('role', 'mod')->get(); $user->notify(new CreateNotification($ticket)); Notification::send($admin, new AdminCreateNotification($ticket, $user)); - - return redirect()->route('ticket.index')->with('success', __('A ticket has been opened, ID: #') . $ticket->ticket_id); + + return redirect()->route('ticket.index')->with('success', __('A ticket has been opened, ID: #').$ticket->ticket_id); } - public function show($ticket_id) { - $ticket = Ticket::where("ticket_id", $ticket_id)->firstOrFail(); + + public function show($ticket_id) + { + $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail(); $ticketcomments = $ticket->ticketcomments; $ticketcategory = $ticket->ticketcategory; $server = Server::where('id', $ticket->server)->first(); - return view("ticket.show", compact("ticket", "ticketcategory", "ticketcomments", "server")); + + return view('ticket.show', compact('ticket', 'ticketcategory', 'ticketcomments', 'server')); } - public function reply(Request $request) { - #check in blacklist + + public function reply(Request $request) + { + //check in blacklist $check = TicketBlacklist::where('user_id', Auth::user()->id)->first(); - if($check && $check->status == "True"){ - return redirect()->route('ticket.index')->with('error', __("You can't reply a ticket because you're on the blacklist for a reason: '" . $check->reason . "', please contact the administrator")); + if ($check && $check->status == 'True') { + return redirect()->route('ticket.index')->with('error', __("You can't reply a ticket because you're on the blacklist for a reason: '".$check->reason."', please contact the administrator")); } - $this->validate($request, array("ticketcomment" => "required")); - $ticket = Ticket::where('id', $request->input("ticket_id"))->firstOrFail(); - $ticket->status = "Client Reply"; + $this->validate($request, ['ticketcomment' => 'required']); + $ticket = Ticket::where('id', $request->input('ticket_id'))->firstOrFail(); + $ticket->status = 'Client Reply'; $ticket->update(); - $ticketcomment = TicketComment::create(array( - "ticket_id" => $request->input("ticket_id"), - "user_id" => Auth::user()->id, - "ticketcomment" => $request->input("ticketcomment"), - "message" => $request->input("message") - )); + $ticketcomment = TicketComment::create([ + 'ticket_id' => $request->input('ticket_id'), + 'user_id' => Auth::user()->id, + 'ticketcomment' => $request->input('ticketcomment'), + 'message' => $request->input('message'), + ]); $user = Auth::user(); $admin = User::where('role', 'admin')->orWhere('role', 'mod')->get(); - $newmessage = $request->input("ticketcomment"); + $newmessage = $request->input('ticketcomment'); Notification::send($admin, new AdminReplyNotification($ticket, $user, $newmessage)); + return redirect()->back()->with('success', __('Your comment has been submitted')); } public function dataTable() { - $query = Ticket::where("user_id", Auth::user()->id)->get(); + $query = Ticket::where('user_id', Auth::user()->id)->get(); return datatables($query) ->addColumn('category', function (Ticket $tickets) { return $tickets->ticketcategory->name; }) ->editColumn('title', function (Ticket $tickets) { - return '' . "#" . $tickets->ticket_id . " - " . $tickets->title . ''; + return ''.'#'.$tickets->ticket_id.' - '.$tickets->title.''; }) ->editColumn('status', function (Ticket $tickets) { switch ($tickets->status) { case 'Open': $badgeColor = 'badge-success'; - break; + break; case 'Closed': $badgeColor = 'badge-danger'; break; @@ -120,7 +128,7 @@ class TicketsController extends Controller break; } - return '' . $tickets->status . ''; + return ''.$tickets->status.''; }) ->editColumn('updated_at', function (Ticket $tickets) { return $tickets->updated_at ? $tickets->updated_at->diffForHumans() : ''; diff --git a/app/Http/Controllers/TranslationController.php b/app/Http/Controllers/TranslationController.php index d771f8f2..d486902f 100644 --- a/app/Http/Controllers/TranslationController.php +++ b/app/Http/Controllers/TranslationController.php @@ -8,16 +8,15 @@ use Illuminate\Support\Facades\Session; class TranslationController extends Controller { /** - * * Change session locale - * @param Request $request + * + * @param Request $request * @return Response */ public function changeLocale(Request $request) { Session::put('locale', $request->inputLocale); + return redirect()->back(); } - - } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 2ee71131..8a57b337 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -51,7 +51,7 @@ class Kernel extends HttpKernel 'api' => [ 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, - GlobalNames::class + GlobalNames::class, ], ]; @@ -75,6 +75,6 @@ class Kernel extends HttpKernel 'admin' => isAdmin::class, 'moderator' => isMod::class, 'api.token' => ApiAuthToken::class, - 'checkSuspended' => CheckSuspended::class + 'checkSuspended' => CheckSuspended::class, ]; } diff --git a/app/Http/Middleware/ApiAuthToken.php b/app/Http/Middleware/ApiAuthToken.php index 8063e2ef..1881230f 100644 --- a/app/Http/Middleware/ApiAuthToken.php +++ b/app/Http/Middleware/ApiAuthToken.php @@ -11,18 +11,23 @@ class ApiAuthToken /** * Handle an incoming request. * - * @param Request $request - * @param Closure $next + * @param Request $request + * @param Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { - if (empty($request->bearerToken())) return response()->json(['message' => 'Missing Authorization header'], 403); + if (empty($request->bearerToken())) { + return response()->json(['message' => 'Missing Authorization header'], 403); + } $token = ApplicationApi::find($request->bearerToken()); - if (is_null($token)) return response()->json(['message' => 'Invalid Authorization token'], 401); + if (is_null($token)) { + return response()->json(['message' => 'Invalid Authorization token'], 401); + } $token->updateLastUsed(); + return $next($request); } } diff --git a/app/Http/Middleware/CheckSuspended.php b/app/Http/Middleware/CheckSuspended.php index 59fcc614..60cda0af 100644 --- a/app/Http/Middleware/CheckSuspended.php +++ b/app/Http/Middleware/CheckSuspended.php @@ -23,6 +23,7 @@ class CheckSuspended return redirect()->route('login')->withMessage($message); } + return $next($request); } } diff --git a/app/Http/Middleware/GlobalNames.php b/app/Http/Middleware/GlobalNames.php index fbff5594..4874a2f6 100644 --- a/app/Http/Middleware/GlobalNames.php +++ b/app/Http/Middleware/GlobalNames.php @@ -2,8 +2,6 @@ namespace App\Http\Middleware; -use App\Models\Configuration; -use App\Models\Settings; use Closure; use Illuminate\Http\Request; @@ -12,15 +10,15 @@ class GlobalNames /** * Handle an incoming request. * - * @param Request $request - * @param Closure $next + * @param Request $request + * @param Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { define('CREDITS_DISPLAY_NAME', config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME', 'Credits')); - $unsupported_lang_array = explode(',', config("app.unsupported_locales")); + $unsupported_lang_array = explode(',', config('app.unsupported_locales')); $unsupported_lang_array = array_map('strtolower', $unsupported_lang_array); define('UNSUPPORTED_LANGS', $unsupported_lang_array); diff --git a/app/Http/Middleware/LastSeen.php b/app/Http/Middleware/LastSeen.php index 567c1f39..a6667b64 100644 --- a/app/Http/Middleware/LastSeen.php +++ b/app/Http/Middleware/LastSeen.php @@ -3,7 +3,6 @@ namespace App\Http\Middleware; use Closure; -use DateTime; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; @@ -12,17 +11,17 @@ class LastSeen /** * Handle an incoming request. * - * @param Request $request - * @param Closure $next + * @param Request $request + * @param Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { - if (env('APP_ENV' , 'local') == 'local'){ + if (env('APP_ENV', 'local') == 'local') { return $next($request); } - if (!Auth::check()) { + if (! Auth::check()) { return $next($request); } @@ -32,7 +31,7 @@ class LastSeen Auth::user()->update([ 'last_seen' => now(), - 'ip' => $request->ip() + 'ip' => $request->ip(), ]); return $next($request); diff --git a/app/Http/Middleware/SetLocale.php b/app/Http/Middleware/SetLocale.php index bd5188b0..64174677 100644 --- a/app/Http/Middleware/SetLocale.php +++ b/app/Http/Middleware/SetLocale.php @@ -2,7 +2,6 @@ namespace App\Http\Middleware; -use App\Models\Settings; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; @@ -10,27 +9,25 @@ use Illuminate\Support\Facades\Session; class SetLocale { - /** - * * Handle an incoming request. * - * @param Request $request - * @param Closure $next + * @param Request $request + * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { if (Session::has('locale')) { - $locale = Session::get('locale', config("SETTINGS::LOCALE:DEFAULT")); + $locale = Session::get('locale', config('SETTINGS::LOCALE:DEFAULT')); } else { - if (config("SETTINGS::LOCALE:DYNAMIC") !== "true") { - $locale = config("SETTINGS::LOCALE:DEFAULT"); + if (config('SETTINGS::LOCALE:DYNAMIC') !== 'true') { + $locale = config('SETTINGS::LOCALE:DEFAULT'); } else { $locale = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2); - if (!in_array($locale, explode(',', config("SETTINGS::LOCALE:AVAILABLE")))) { - $locale = config("SETTINGS::LOCALE:DEFAULT"); + if (! in_array($locale, explode(',', config('SETTINGS::LOCALE:AVAILABLE')))) { + $locale = config('SETTINGS::LOCALE:DEFAULT'); } } } diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php index 45cfc598..45698844 100644 --- a/app/Http/Middleware/VerifyCsrfToken.php +++ b/app/Http/Middleware/VerifyCsrfToken.php @@ -12,6 +12,6 @@ class VerifyCsrfToken extends Middleware * @var array */ protected $except = [ - 'payment/StripeWebhooks' + 'payment/StripeWebhooks', ]; } diff --git a/app/Http/Middleware/isAdmin.php b/app/Http/Middleware/isAdmin.php index 3c839d50..3dbb4957 100644 --- a/app/Http/Middleware/isAdmin.php +++ b/app/Http/Middleware/isAdmin.php @@ -12,8 +12,8 @@ class isAdmin /** * Handle an incoming request. * - * @param Request $request - * @param Closure $next + * @param Request $request + * @param Closure $next * @return mixed */ public function handle(Request $request, Closure $next) diff --git a/app/Http/Middleware/isMod.php b/app/Http/Middleware/isMod.php index 4e8b9b79..c9120719 100644 --- a/app/Http/Middleware/isMod.php +++ b/app/Http/Middleware/isMod.php @@ -12,8 +12,8 @@ class isMod /** * Handle an incoming request. * - * @param Request $request - * @param Closure $next + * @param Request $request + * @param Closure $next * @return mixed */ public function handle(Request $request, Closure $next) diff --git a/app/Listeners/UnsuspendServers.php b/app/Listeners/UnsuspendServers.php index 7f75364c..587cd84f 100644 --- a/app/Listeners/UnsuspendServers.php +++ b/app/Listeners/UnsuspendServers.php @@ -4,7 +4,6 @@ namespace App\Listeners; use App\Events\UserUpdateCreditsEvent; use App\Models\Server; -use App\Models\Settings; use Exception; use Illuminate\Contracts\Queue\ShouldQueue; @@ -13,8 +12,9 @@ class UnsuspendServers implements ShouldQueue /** * Handle the event. * - * @param UserUpdateCreditsEvent $event + * @param UserUpdateCreditsEvent $event * @return void + * * @throws Exception */ public function handle(UserUpdateCreditsEvent $event) @@ -22,7 +22,9 @@ class UnsuspendServers implements ShouldQueue if ($event->user->credits > config('SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER', 50)) { /** @var Server $server */ foreach ($event->user->servers as $server) { - if ($server->isSuspended()) $server->unSuspend(); + if ($server->isSuspended()) { + $server->unSuspend(); + } } } } diff --git a/app/Listeners/Verified.php b/app/Listeners/Verified.php index c4932707..6863e462 100644 --- a/app/Listeners/Verified.php +++ b/app/Listeners/Verified.php @@ -17,12 +17,12 @@ class Verified /** * Handle the event. * - * @param object $event + * @param object $event * @return void */ public function handle($event) { - if (!$event->user->email_verified_reward) { + if (! $event->user->email_verified_reward) { $event->user->increment('server_limit', config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_EMAIL')); $event->user->increment('credits', config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_EMAIL')); } diff --git a/app/Models/ApplicationApi.php b/app/Models/ApplicationApi.php index 799cb110..41c00e36 100644 --- a/app/Models/ApplicationApi.php +++ b/app/Models/ApplicationApi.php @@ -10,7 +10,7 @@ class ApplicationApi extends Model { use HasFactory; - protected $fillable = ['token', 'memo' , 'last_used']; + protected $fillable = ['token', 'memo', 'last_used']; protected $primaryKey = 'token'; @@ -29,7 +29,8 @@ class ApplicationApi extends Model }); } - public function updateLastUsed(){ + public function updateLastUsed() + { $this->update(['last_used' => now()]); } } diff --git a/app/Models/DiscordUser.php b/app/Models/DiscordUser.php index ab53dba7..03051ea3 100644 --- a/app/Models/DiscordUser.php +++ b/app/Models/DiscordUser.php @@ -11,18 +11,18 @@ class DiscordUser extends Model use HasFactory; protected $fillable = [ - "id", - "user_id", - "username", - "avatar", - "discriminator", - "public_flags", - "flags", - "locale", - "mfa_enabled", - "premium_type", - "email", - "verified", + 'id', + 'user_id', + 'username', + 'avatar', + 'discriminator', + 'public_flags', + 'flags', + 'locale', + 'mfa_enabled', + 'premium_type', + 'email', + 'verified', ]; public $incrementing = false; @@ -30,14 +30,16 @@ class DiscordUser extends Model /** * @return BelongsTo */ - public function user(){ + public function user() + { return $this->belongsTo(User::class); } /** * @return string */ - public function getAvatar(){ - return "https://cdn.discordapp.com/avatars/" . $this->id . "/" . $this->avatar . ".png"; + public function getAvatar() + { + return 'https://cdn.discordapp.com/avatars/'.$this->id.'/'.$this->avatar.'.png'; } } diff --git a/app/Models/Egg.php b/app/Models/Egg.php index 435b8cb0..23bf34ef 100644 --- a/app/Models/Egg.php +++ b/app/Models/Egg.php @@ -61,8 +61,8 @@ class Egg extends Model $array['environment'] = json_encode([$environment]); self::query()->updateOrCreate([ - 'id' => $array['id'] - ], array_diff_key($array, array_flip(["id"])) + 'id' => $array['id'], + ], array_diff_key($array, array_flip(['id'])) ); } @@ -72,8 +72,9 @@ class Egg extends Model /** * @description remove eggs that have been deleted on pterodactyl - * @param Nest $nest - * @param array $eggs + * + * @param Nest $nest + * @param array $eggs */ private static function removeDeletedEggs(Nest $nest, array $eggs): void { @@ -82,7 +83,9 @@ class Egg extends Model }, $eggs); $nest->eggs()->each(function (Egg $egg) use ($ids) { - if (!in_array($egg->id, $ids)) $egg->delete(); + if (! in_array($egg->id, $ids)) { + $egg->delete(); + } }); } diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php index c0618ab5..b01c3c71 100644 --- a/app/Models/Invoice.php +++ b/app/Models/Invoice.php @@ -12,7 +12,6 @@ class Invoice extends Model protected $fillable = [ 'invoice_name', 'invoice_user', - 'payment_id' + 'payment_id', ]; - } diff --git a/app/Models/Location.php b/app/Models/Location.php index 9066a4d4..a020c73f 100644 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -28,6 +28,7 @@ class Location extends Model /** * Sync locations with pterodactyl panel + * * @throws Exception */ public static function syncLocations() @@ -36,21 +37,21 @@ class Location extends Model //map response $locations = array_map(function ($val) { - return array( - 'id' => $val['attributes']['id'], - 'name' => $val['attributes']['short'], - 'description' => $val['attributes']['long'] - ); + return [ + 'id' => $val['attributes']['id'], + 'name' => $val['attributes']['short'], + 'description' => $val['attributes']['long'], + ]; }, $locations); //update or create foreach ($locations as $location) { self::query()->updateOrCreate( [ - 'id' => $location['id'] + 'id' => $location['id'], ], [ - 'name' => $location['name'], + 'name' => $location['name'], 'description' => $location['name'], ] ); @@ -61,7 +62,8 @@ class Location extends Model /** * @description remove locations that have been deleted on pterodactyl - * @param array $locations + * + * @param array $locations */ private static function removeDeletedLocation(array $locations): void { @@ -70,7 +72,9 @@ class Location extends Model }, $locations); self::all()->each(function (Location $location) use ($ids) { - if (!in_array($location->id, $ids)) $location->delete(); + if (! in_array($location->id, $ids)) { + $location->delete(); + } }); } @@ -78,5 +82,4 @@ class Location extends Model { return $this->hasMany(Node::class, 'location_id', 'id'); } - } diff --git a/app/Models/Nest.php b/app/Models/Nest.php index fdc36a94..06c5ce26 100644 --- a/app/Models/Nest.php +++ b/app/Models/Nest.php @@ -36,20 +36,20 @@ class Nest extends Model //map response $nests = array_map(function ($nest) { - return array( - 'id' => $nest['attributes']['id'], - 'name' => $nest['attributes']['name'], + return [ + 'id' => $nest['attributes']['id'], + 'name' => $nest['attributes']['name'], 'description' => $nest['attributes']['description'], - ); + ]; }, $nests); foreach ($nests as $nest) { self::query()->updateOrCreate([ - 'id' => $nest['id'] + 'id' => $nest['id'], ], [ - 'name' => $nest['name'], + 'name' => $nest['name'], 'description' => $nest['description'], - 'disabled' => false + 'disabled' => false, ]); } @@ -58,7 +58,8 @@ class Nest extends Model /** * @description remove nests that have been deleted on pterodactyl - * @param array $nests + * + * @param array $nests */ private static function removeDeletedNests(array $nests): void { @@ -67,7 +68,9 @@ class Nest extends Model }, $nests); self::all()->each(function (Nest $nest) use ($ids) { - if (!in_array($nest->id, $ids)) $nest->delete(); + if (! in_array($nest->id, $ids)) { + $nest->delete(); + } }); } diff --git a/app/Models/Node.php b/app/Models/Node.php index c0d1ab3e..01eee0ea 100644 --- a/app/Models/Node.php +++ b/app/Models/Node.php @@ -26,7 +26,6 @@ class Node extends Model }); } - /** * @throws Exception */ @@ -37,25 +36,25 @@ class Node extends Model //map response $nodes = array_map(function ($node) { - return array( - 'id' => $node['attributes']['id'], + return [ + 'id' => $node['attributes']['id'], 'location_id' => $node['attributes']['location_id'], - 'name' => $node['attributes']['name'], + 'name' => $node['attributes']['name'], 'description' => $node['attributes']['description'], - ); + ]; }, $nodes); //update or create foreach ($nodes as $node) { self::query()->updateOrCreate( [ - 'id' => $node['id'] + 'id' => $node['id'], ], [ - 'name' => $node['name'], + 'name' => $node['name'], 'description' => $node['description'], 'location_id' => $node['location_id'], - 'disabled' => false + 'disabled' => false, ]); } @@ -64,7 +63,8 @@ class Node extends Model /** * @description remove nodes that have been deleted on pterodactyl - * @param array $nodes + * + * @param array $nodes */ private static function removeDeletedNodes(array $nodes): void { @@ -73,7 +73,9 @@ class Node extends Model }, $nodes); self::all()->each(function (Node $node) use ($ids) { - if (!in_array($node->id, $ids)) $node->delete(); + if (! in_array($node->id, $ids)) { + $node->delete(); + } }); } diff --git a/app/Models/PartnerDiscount.php b/app/Models/PartnerDiscount.php index c2bea233..c1bd50b0 100644 --- a/app/Models/PartnerDiscount.php +++ b/app/Models/PartnerDiscount.php @@ -15,27 +15,32 @@ class PartnerDiscount extends Model 'user_id', 'partner_discount', 'registered_user_discount', - 'referral_system_commission' + 'referral_system_commission', ]; public static function getDiscount() { - if($partnerDiscount = PartnerDiscount::where('user_id', Auth::user()->id)->first()){ + if ($partnerDiscount = PartnerDiscount::where('user_id', Auth::user()->id)->first()) { return $partnerDiscount->partner_discount; - } - else if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', Auth::user()->id)->first()){ - if($partnerDiscount = PartnerDiscount::where('user_id', $ref_user->referral_id)->first()){ + } elseif ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', Auth::user()->id)->first()) { + if ($partnerDiscount = PartnerDiscount::where('user_id', $ref_user->referral_id)->first()) { return $partnerDiscount->registered_user_discount; } + return 0; } + return 0; } + public static function getCommission($user_id) { - if($partnerDiscount = PartnerDiscount::where('user_id', $user_id)->first()){ - if($partnerDiscount->referral_system_commission>=0) return $partnerDiscount->referral_system_commission>=0; + if ($partnerDiscount = PartnerDiscount::where('user_id', $user_id)->first()) { + if ($partnerDiscount->referral_system_commission >= 0) { + return $partnerDiscount->referral_system_commission >= 0; + } } - return config("SETTINGS::REFERRAL:PERCENTAGE"); + + return config('SETTINGS::REFERRAL:PERCENTAGE'); } -} \ No newline at end of file +} diff --git a/app/Models/Payment.php b/app/Models/Payment.php index df6acb24..63c99ae0 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -55,14 +55,14 @@ class Payment extends Model } /** - * @param mixed $value - * @param string $locale - * + * @param mixed $value + * @param string $locale * @return float */ public function formatToCurrency($value, $locale = 'en_US') { $formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY); + return $formatter->formatCurrency($value, $this->currency_code); } } diff --git a/app/Models/Product.php b/app/Models/Product.php index 52a37c28..e0aca926 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -7,7 +7,6 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; -use Illuminate\Database\Eloquent\Relations\HasMany; use Spatie\Activitylog\Traits\LogsActivity; class Product extends Model @@ -29,7 +28,7 @@ class Product extends Model $product->{$product->getKeyName()} = $client->generateId($size = 21); }); - static::deleting(function(Product $product) { + static::deleting(function (Product $product) { $product->nodes()->detach(); $product->eggs()->detach(); }); @@ -42,12 +41,12 @@ class Product extends Model public function getDailyPrice() { - return ($this->price / 30); + return $this->price / 30; } public function getWeeklyPrice() { - return ($this->price / 4); + return $this->price / 4; } /** @@ -61,14 +60,16 @@ class Product extends Model /** * @return BelongsToMany */ - public function eggs() { + public function eggs() + { return $this->belongsToMany(Egg::class); } /** * @return BelongsToMany */ - public function nodes() { + public function nodes() + { return $this->belongsToMany(Node::class); } } diff --git a/app/Models/Server.php b/app/Models/Server.php index 34c992ba..87c408a8 100644 --- a/app/Models/Server.php +++ b/app/Models/Server.php @@ -15,7 +15,6 @@ use Spatie\Activitylog\Traits\LogsActivity; /** * Class Server - * @package App\Models */ class Server extends Model { @@ -41,24 +40,21 @@ class Server extends Model * @var string[] */ protected $fillable = [ - "name", - "description", - "suspended", - "identifier", - "product_id", - "pterodactyl_id", + 'name', + 'description', + 'suspended', + 'identifier', + 'product_id', + 'pterodactyl_id', ]; /** * @var string[] */ protected $dates = [ - 'suspended' + 'suspended', ]; - /** - * - */ public static function boot() { parent::boot(); @@ -71,7 +67,7 @@ class Server extends Model static::deleting(function (Server $server) { $response = Pterodactyl::client()->delete("/application/servers/{$server->pterodactyl_id}"); - if ($response->failed() && !is_null($server->pterodactyl_id)) { + if ($response->failed() && ! is_null($server->pterodactyl_id)) { //only return error when it's not a 404 error if ($response['errors'][0]['status'] != '404') { throw new Exception($response['errors'][0]['code']); @@ -85,10 +81,9 @@ class Server extends Model */ public function isSuspended() { - return !is_null($this->suspended); + return ! is_null($this->suspended); } - /** * @return PromiseInterface|Response */ @@ -98,7 +93,6 @@ class Server extends Model } /** - * * @throws Exception */ public function suspend() @@ -107,7 +101,7 @@ class Server extends Model if ($response->successful()) { $this->update([ - 'suspended' => now() + 'suspended' => now(), ]); } @@ -123,14 +117,13 @@ class Server extends Model if ($response->successful()) { $this->update([ - 'suspended' => null + 'suspended' => null, ]); } return $this; } - /** * @return HasOne */ @@ -146,5 +139,4 @@ class Server extends Model { return $this->belongsTo(User::class, 'user_id', 'id'); } - } diff --git a/app/Models/Settings.php b/app/Models/Settings.php index 1db90d7a..ccad0f4a 100644 --- a/app/Models/Settings.php +++ b/app/Models/Settings.php @@ -31,19 +31,20 @@ class Settings extends Model parent::boot(); static::updated(function (Settings $settings) { - Cache::forget(self::CACHE_TAG .':'. $settings->key); + Cache::forget(self::CACHE_TAG.':'.$settings->key); }); } /** - * @param string $key + * @param string $key * @param $default * @return mixed */ public static function getValueByKey(string $key, $default = null) { - return Cache::rememberForever(self::CACHE_TAG .':'. $key, function () use ($default, $key) { + return Cache::rememberForever(self::CACHE_TAG.':'.$key, function () use ($default, $key) { $settings = self::find($key); + return $settings ? $settings->value : $default; }); } diff --git a/app/Models/ShopProduct.php b/app/Models/ShopProduct.php index 3339a169..4cbc5ba5 100644 --- a/app/Models/ShopProduct.php +++ b/app/Models/ShopProduct.php @@ -6,11 +6,11 @@ use Hidehalo\Nanoid\Client; use Illuminate\Database\Eloquent\Model; use NumberFormatter; use Spatie\Activitylog\Traits\LogsActivity; -use App\Models\Configuration; class ShopProduct extends Model { use LogsActivity; + /** * @var bool */ @@ -20,13 +20,13 @@ class ShopProduct extends Model * @var string[] */ protected $fillable = [ - "type", - "price", - "description", - "display", - "currency_code", - "quantity", - "disabled", + 'type', + 'price', + 'description', + 'display', + 'currency_code', + 'quantity', + 'disabled', ]; public static function boot() @@ -41,14 +41,14 @@ class ShopProduct extends Model } /** - * @param mixed $value - * @param string $locale - * + * @param mixed $value + * @param string $locale * @return float */ public function formatToCurrency($value, $locale = 'en_US') { $formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY); + return $formatter->formatCurrency($value, $this->currency_code); } @@ -59,7 +59,8 @@ class ShopProduct extends Model */ public function getTaxPercent() { - $tax = config("SETTINGS::PAYMENTS:SALES_TAX"); + $tax = config('SETTINGS::PAYMENTS:SALES_TAX'); + return $tax < 0 ? 0 : $tax; } @@ -87,4 +88,4 @@ class ShopProduct extends Model { return number_format($this->getPriceAfterDiscount() + $this->getTaxValue(), 2); } -} \ No newline at end of file +} diff --git a/app/Models/Ticket.php b/app/Models/Ticket.php index 16f548a9..a7effb9d 100644 --- a/app/Models/Ticket.php +++ b/app/Models/Ticket.php @@ -4,18 +4,24 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; -class Ticket extends Model { +class Ticket extends Model +{ protected $fillable = [ - 'user_id', 'ticketcategory_id', 'ticket_id', 'title', 'priority', 'message', 'status', 'server' + 'user_id', 'ticketcategory_id', 'ticket_id', 'title', 'priority', 'message', 'status', 'server', ]; - public function ticketcategory(){ - return $this->belongsTo(TicketCategory::class);} + public function ticketcategory() + { + return $this->belongsTo(TicketCategory::class); + } - public function ticketcomments(){ - return $this->hasMany(TicketComment::class);} + public function ticketcomments() + { + return $this->hasMany(TicketComment::class); + } - public function user(){ - return $this->belongsTo(User::class);} -} - \ No newline at end of file + public function user() + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Models/TicketBlacklist.php b/app/Models/TicketBlacklist.php index 21ea1ff4..4a7290e7 100644 --- a/app/Models/TicketBlacklist.php +++ b/app/Models/TicketBlacklist.php @@ -4,14 +4,14 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; -class TicketBlacklist extends Model { +class TicketBlacklist extends Model +{ protected $fillable = [ - 'user_id', 'status', 'reason' + 'user_id', 'status', 'reason', ]; public function user() { return $this->belongsTo(User::class, 'user_id', 'id'); } -} - \ No newline at end of file +} diff --git a/app/Models/TicketCategory.php b/app/Models/TicketCategory.php index 8301a108..d261f4c1 100644 --- a/app/Models/TicketCategory.php +++ b/app/Models/TicketCategory.php @@ -4,10 +4,12 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; -class TicketCategory extends Model { +class TicketCategory extends Model +{ protected $fillable = ['name']; - - public function tickets(){ - return $this->hasMany(Ticket::class);} + + public function tickets() + { + return $this->hasMany(Ticket::class); + } } - \ No newline at end of file diff --git a/app/Models/TicketComment.php b/app/Models/TicketComment.php index c44a5bf1..3fcf1a85 100644 --- a/app/Models/TicketComment.php +++ b/app/Models/TicketComment.php @@ -4,18 +4,24 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; -class TicketComment extends Model { -protected $fillable = [ - 'ticket_id', 'user_id', 'ticketcomment' -]; +class TicketComment extends Model +{ + protected $fillable = [ + 'ticket_id', 'user_id', 'ticketcomment', + ]; - public function ticketcategory(){ - return $this->belongsTo(TicketCategory::class);} + public function ticketcategory() + { + return $this->belongsTo(TicketCategory::class); + } - public function ticket(){ - return $this->belongsTo(Ticket::class);} + public function ticket() + { + return $this->belongsTo(Ticket::class); + } - public function user(){ - return $this->belongsTo(User::class);} + public function user() + { + return $this->belongsTo(User::class); + } } - \ No newline at end of file diff --git a/app/Models/UsefulLink.php b/app/Models/UsefulLink.php index ba8eeb15..4d788e0d 100644 --- a/app/Models/UsefulLink.php +++ b/app/Models/UsefulLink.php @@ -15,6 +15,6 @@ class UsefulLink extends Model 'icon', 'title', 'link', - 'description' + 'description', ]; } diff --git a/app/Models/User.php b/app/Models/User.php index 31bb29e5..887737b2 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -17,7 +17,6 @@ use Spatie\Activitylog\Traits\LogsActivity; /** * Class User - * @package App\Models */ class User extends Authenticatable implements MustVerifyEmail { @@ -38,7 +37,7 @@ class User extends Authenticatable implements MustVerifyEmail 'server_limit', 'last_seen', 'ip', - 'pterodactyl_id' + 'pterodactyl_id', ]; /** @@ -60,7 +59,7 @@ class User extends Authenticatable implements MustVerifyEmail 'discord_verified_at', 'avatar', 'suspended', - 'referral_code' + 'referral_code', ]; /** @@ -85,9 +84,6 @@ class User extends Authenticatable implements MustVerifyEmail 'server_limit' => 'float', ]; - /** - * - */ public static function boot() { parent::boot(); @@ -119,7 +115,6 @@ class User extends Authenticatable implements MustVerifyEmail $user->vouchers()->detach(); - $user->discordUser()->delete(); Pterodactyl::client()->delete("/application/users/{$user->pterodactyl_id}"); @@ -174,9 +169,6 @@ class User extends Authenticatable implements MustVerifyEmail return $this->hasOne(DiscordUser::class); } - /** - * - */ public function sendEmailVerificationNotification() { $this->notify(new QueuedVerifyEmail); @@ -199,7 +191,6 @@ class User extends Authenticatable implements MustVerifyEmail } /** - * * @throws Exception */ public function suspend() @@ -209,7 +200,7 @@ class User extends Authenticatable implements MustVerifyEmail } $this->update([ - 'suspended' => true + 'suspended' => true, ]); return $this; @@ -227,7 +218,7 @@ class User extends Authenticatable implements MustVerifyEmail } $this->update([ - 'suspended' => false + 'suspended' => false, ]); return $this; @@ -256,8 +247,7 @@ class User extends Authenticatable implements MustVerifyEmail // $avatar = "https://www.gravatar.com/avatar/" . md5(strtolower(trim($this->email))); // } - return "https://www.gravatar.com/avatar/" . md5(strtolower(trim($this->email))); - + return 'https://www.gravatar.com/avatar/'.md5(strtolower(trim($this->email))); } /** @@ -279,9 +269,14 @@ class User extends Authenticatable implements MustVerifyEmail public function getVerifiedStatus() { $status = ''; - if ($this->hasVerifiedEmail()) $status .= 'email '; - if ($this->discordUser()->exists()) $status .= 'discord'; + if ($this->hasVerifiedEmail()) { + $status .= 'email '; + } + if ($this->discordUser()->exists()) { + $status .= 'discord'; + } $status = str_replace(' ', '/', $status); + return $status; } diff --git a/app/Models/Voucher.php b/app/Models/Voucher.php index 17548c4f..873aa0ac 100644 --- a/app/Models/Voucher.php +++ b/app/Models/Voucher.php @@ -10,7 +10,6 @@ use Spatie\Activitylog\Traits\LogsActivity; /** * Class Voucher - * @package App\Models */ class Voucher extends Model { @@ -28,7 +27,7 @@ class Voucher extends Model ]; protected $dates = [ - 'expires_at' + 'expires_at', ]; /** @@ -38,7 +37,7 @@ class Voucher extends Model */ protected $casts = [ 'credits' => 'float', - 'uses' => 'integer' + 'uses' => 'integer', ]; protected $appends = ['used', 'status']; @@ -59,9 +58,6 @@ class Voucher extends Model return $this->getStatus(); } - /** - * - */ public static function boot() { parent::boot(); @@ -84,17 +80,22 @@ class Voucher extends Model */ public function getStatus() { - if ($this->users()->count() >= $this->uses) return 'USES_LIMIT_REACHED'; - if (!is_null($this->expires_at)) { - if ($this->expires_at->isPast()) return __('EXPIRED'); + if ($this->users()->count() >= $this->uses) { + return 'USES_LIMIT_REACHED'; + } + if (! is_null($this->expires_at)) { + if ($this->expires_at->isPast()) { + return __('EXPIRED'); + } } return __('VALID'); } /** - * @param User $user + * @param User $user * @return float + * * @throws Exception */ public function redeem(User $user) @@ -111,7 +112,7 @@ class Voucher extends Model } /** - * @param User $user + * @param User $user * @return null */ private function logRedeem(User $user) diff --git a/app/Notifications/ConfirmPaymentNotification.php b/app/Notifications/ConfirmPaymentNotification.php index 37638c15..7d6ddd36 100644 --- a/app/Notifications/ConfirmPaymentNotification.php +++ b/app/Notifications/ConfirmPaymentNotification.php @@ -10,7 +10,6 @@ use Illuminate\Notifications\Notification; class ConfirmPaymentNotification extends Notification implements ShouldQueue { - //THIS IS BASICALLY NOT USED ANYMORE WITH INVOICENOTIFICATION IN PLACE use Queueable; @@ -48,20 +47,20 @@ class ConfirmPaymentNotification extends Notification implements ShouldQueue { return (new MailMessage) ->subject(__('Payment Confirmation')) - ->markdown('mail.payment.confirmed' , ['payment' => $this->payment]); + ->markdown('mail.payment.confirmed', ['payment' => $this->payment]); } /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ - 'title' => __("Payment Confirmed!"), - 'content' => __("Payment Confirmed!"), + 'title' => __('Payment Confirmed!'), + 'content' => __('Payment Confirmed!'), ]; } } diff --git a/app/Notifications/DynamicNotification.php b/app/Notifications/DynamicNotification.php index 6e24c329..b61b053b 100644 --- a/app/Notifications/DynamicNotification.php +++ b/app/Notifications/DynamicNotification.php @@ -6,27 +6,30 @@ use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; class DynamicNotification extends Notification - { use Queueable; + /** * @var array */ private $via; + /** * @var array */ private $database; + /** * @var MailMessage */ private $mail; + /** * Create a new notification instance. * - * @param array $via - * @param array $database - * @param MailMessage $mail + * @param array $via + * @param array $database + * @param MailMessage $mail */ public function __construct($via, $database, $mail) { @@ -38,7 +41,7 @@ class DynamicNotification extends Notification /** * Get the notification's delivery channels. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function via() @@ -50,10 +53,11 @@ class DynamicNotification extends Notification { return $this->mail; } + /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray() diff --git a/app/Notifications/InvoiceNotification.php b/app/Notifications/InvoiceNotification.php index 75fcd5ac..af7c5fa9 100644 --- a/app/Notifications/InvoiceNotification.php +++ b/app/Notifications/InvoiceNotification.php @@ -10,7 +10,6 @@ use Illuminate\Notifications\Notification; use LaravelDaily\Invoices\Invoice; class InvoiceNotification extends Notification - { use Queueable; @@ -20,13 +19,15 @@ class InvoiceNotification extends Notification * * @var invoice */ private $invoice; + private $user; + private $payment; /** * Create a new notification instance. * - * @param Invoice $invoice + * @param Invoice $invoice */ public function __construct(Invoice $invoice, User $user, Payment $payment) { @@ -38,7 +39,7 @@ class InvoiceNotification extends Notification /** * Get the notification's delivery channels. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function via($notifiable) @@ -49,7 +50,7 @@ class InvoiceNotification extends Notification /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable) @@ -57,13 +58,13 @@ class InvoiceNotification extends Notification return (new MailMessage) ->subject(__('Your Payment was successful!')) ->greeting(__('Hello').',') - ->line(__("Your payment was processed successfully!")) - ->line(__('Status').': ' . $this->payment->status) - ->line(__('Price').': ' . $this->payment->formatToCurrency($this->payment->total_price)) - ->line(__('Type').': ' . $this->payment->type) - ->line(__('Amount').': ' . $this->payment->amount) - ->line(__('Balance').': ' . number_format($this->user->credits,2)) - ->line(__('User ID').': ' . $this->payment->user_id) - ->attach(storage_path('app/invoice/' . $this->user->id . '/' . now()->format('Y') . '/' . $this->invoice->filename)); + ->line(__('Your payment was processed successfully!')) + ->line(__('Status').': '.$this->payment->status) + ->line(__('Price').': '.$this->payment->formatToCurrency($this->payment->total_price)) + ->line(__('Type').': '.$this->payment->type) + ->line(__('Amount').': '.$this->payment->amount) + ->line(__('Balance').': '.number_format($this->user->credits, 2)) + ->line(__('User ID').': '.$this->payment->user_id) + ->attach(storage_path('app/invoice/'.$this->user->id.'/'.now()->format('Y').'/'.$this->invoice->filename)); } } diff --git a/app/Notifications/ReferralNotification.php b/app/Notifications/ReferralNotification.php index 1f48df37..dec1ea0e 100644 --- a/app/Notifications/ReferralNotification.php +++ b/app/Notifications/ReferralNotification.php @@ -5,12 +5,11 @@ namespace App\Notifications; use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; -use Illuminate\Support\Facades\Auth; class ReferralNotification extends Notification - { use Queueable; + /** * @var User */ @@ -19,7 +18,7 @@ class ReferralNotification extends Notification /** * Create a new notification instance. * - * @param User $user + * @param User $user */ public function __construct(int $user, int $ref_user) { @@ -30,7 +29,7 @@ class ReferralNotification extends Notification /** * Get the notification's delivery channels. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function via($notifiable) @@ -41,19 +40,19 @@ class ReferralNotification extends Notification /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ - 'title' => __("Someone registered using your Code!"), - 'content' => " -

You received ".config('SETTINGS::REFERRAL::REWARD')." ".config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME')."

-

because ".$this->ref_user->name." registered with your Referral-Code!

+ 'title' => __('Someone registered using your Code!'), + 'content' => ' +

You received '.config('SETTINGS::REFERRAL::REWARD').' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').'

+

because '.$this->ref_user->name.' registered with your Referral-Code!

Thank you very much for supporting us!.

-

".config('app.name', 'Laravel')."

- ", +

'.config('app.name', 'Laravel').'

+ ', ]; } } diff --git a/app/Notifications/ServerCreationError.php b/app/Notifications/ServerCreationError.php index 8c24c8c0..4f9bcc58 100644 --- a/app/Notifications/ServerCreationError.php +++ b/app/Notifications/ServerCreationError.php @@ -3,14 +3,13 @@ namespace App\Notifications; use App\Models\Server; -use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; class ServerCreationError extends Notification - { use Queueable; + /** * @var Server */ @@ -19,7 +18,7 @@ class ServerCreationError extends Notification /** * Create a new notification instance. * - * @param Server $server + * @param Server $server */ public function __construct(Server $server) { @@ -29,7 +28,7 @@ class ServerCreationError extends Notification /** * Get the notification's delivery channels. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function via($notifiable) @@ -40,19 +39,19 @@ class ServerCreationError extends Notification /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ - 'title' => __("Server Creation Error"), + 'title' => __('Server Creation Error'), 'content' => "

Hello {$this->server->User->name}, An unexpected error has occurred...

There was a problem creating your server on our pterodactyl panel. There are likely no allocations or rooms left on the selected node. Please contact one of our support members through our discord server to get this resolved asap!

We thank you for your patience and our deepest apologies for this inconvenience.

-

".config('app.name', 'Laravel')."

- ", +

".config('app.name', 'Laravel').'

+ ', ]; } } diff --git a/app/Notifications/ServersSuspendedNotification.php b/app/Notifications/ServersSuspendedNotification.php index c6ed279b..a9ea0612 100644 --- a/app/Notifications/ServersSuspendedNotification.php +++ b/app/Notifications/ServersSuspendedNotification.php @@ -29,7 +29,7 @@ class ServersSuspendedNotification extends Notification implements ShouldQueue */ public function via($notifiable) { - return ['mail' , 'database']; + return ['mail', 'database']; } /** @@ -43,7 +43,7 @@ class ServersSuspendedNotification extends Notification implements ShouldQueue return (new MailMessage) ->subject(__('Your servers have been suspended!')) ->greeting(__('Your servers have been suspended!')) - ->line(__("To automatically re-enable your server/s, you need to purchase more credits.")) + ->line(__('To automatically re-enable your server/s, you need to purchase more credits.')) ->action(__('Purchase credits'), route('store.index')) ->line(__('If you have any questions please let us know.')); } @@ -57,13 +57,13 @@ class ServersSuspendedNotification extends Notification implements ShouldQueue public function toArray($notifiable) { return [ - 'title' => __('Your servers have been suspended!'), - 'content' => " -
". __('Your servers have been suspended!')."
-

". __("To automatically re-enable your server/s, you need to purchase more credits.")."

-

". __('If you have any questions please let us know.')."

-

". __('Regards').",
" . config('app.name', 'Laravel') . "

- ", + 'title' => __('Your servers have been suspended!'), + 'content' => ' +
'.__('Your servers have been suspended!').'
+

'.__('To automatically re-enable your server/s, you need to purchase more credits.').'

+

'.__('If you have any questions please let us know.').'

+

'.__('Regards').',
'.config('app.name', 'Laravel').'

+ ', ]; } } diff --git a/app/Notifications/Ticket/Admin/AdminCreateNotification.php b/app/Notifications/Ticket/Admin/AdminCreateNotification.php index eb832596..0340dfaa 100644 --- a/app/Notifications/Ticket/Admin/AdminCreateNotification.php +++ b/app/Notifications/Ticket/Admin/AdminCreateNotification.php @@ -11,12 +11,12 @@ use Illuminate\Notifications\Notification; class AdminCreateNotification extends Notification implements ShouldQueue { - //THIS IS BASICALLY NOT USED ANYMORE WITH INVOICENOTIFICATION IN PLACE use Queueable; private Ticket $ticket; + private User $user; /** @@ -27,7 +27,7 @@ class AdminCreateNotification extends Notification implements ShouldQueue public function __construct(Ticket $ticket, User $user) { $this->ticket = $ticket; - $this->user = $user; + $this->user = $user; } /** @@ -38,7 +38,8 @@ class AdminCreateNotification extends Notification implements ShouldQueue */ public function via($notifiable) { - $via = ['mail','database']; + $via = ['mail', 'database']; + return $via; } @@ -51,20 +52,20 @@ class AdminCreateNotification extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->subject('[Ticket ID: ' . $this->ticket->ticket_id . '] ' . $this->ticket->title) - ->markdown('mail.ticket.admin.create' , ['ticket' => $this->ticket, 'user' => $this->user]); + ->subject('[Ticket ID: '.$this->ticket->ticket_id.'] '.$this->ticket->title) + ->markdown('mail.ticket.admin.create', ['ticket' => $this->ticket, 'user' => $this->user]); } /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ - 'title' => '[Ticket ID: ' . $this->ticket->ticket_id . '] ' . $this->ticket->title, + 'title' => '[Ticket ID: '.$this->ticket->ticket_id.'] '.$this->ticket->title, 'content' => "Ticket With ID : {$this->ticket->ticket_id} has been opened by {$this->user->name}", ]; } diff --git a/app/Notifications/Ticket/Admin/AdminReplyNotification.php b/app/Notifications/Ticket/Admin/AdminReplyNotification.php index 250d06d6..d49758b9 100644 --- a/app/Notifications/Ticket/Admin/AdminReplyNotification.php +++ b/app/Notifications/Ticket/Admin/AdminReplyNotification.php @@ -11,13 +11,14 @@ use Illuminate\Notifications\Notification; class AdminReplyNotification extends Notification implements ShouldQueue { - //THIS IS BASICALLY NOT USED ANYMORE WITH INVOICENOTIFICATION IN PLACE use Queueable; private Ticket $ticket; + private User $user; + private $newmessage; /** @@ -27,8 +28,8 @@ class AdminReplyNotification extends Notification implements ShouldQueue */ public function __construct(Ticket $ticket, User $user, $newmessage) { - $this->ticket = $ticket; - $this->user = $user; + $this->ticket = $ticket; + $this->user = $user; $this->newmessage = $newmessage; } @@ -40,7 +41,8 @@ class AdminReplyNotification extends Notification implements ShouldQueue */ public function via($notifiable) { - $via = ['mail','database']; + $via = ['mail', 'database']; + return $via; } @@ -53,20 +55,20 @@ class AdminReplyNotification extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->subject('[Ticket ID: ' . $this->ticket->ticket_id . '] ' . $this->ticket->title) - ->markdown('mail.ticket.admin.reply' , ['ticket' => $this->ticket, 'user' => $this->user, 'newmessage' => $this->newmessage]); + ->subject('[Ticket ID: '.$this->ticket->ticket_id.'] '.$this->ticket->title) + ->markdown('mail.ticket.admin.reply', ['ticket' => $this->ticket, 'user' => $this->user, 'newmessage' => $this->newmessage]); } /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ - 'title' => '[Ticket ID: ' . $this->ticket->ticket_id . '] ' . $this->ticket->title, + 'title' => '[Ticket ID: '.$this->ticket->ticket_id.'] '.$this->ticket->title, 'content' => "

Ticket With ID : {$this->ticket->ticket_id} has had a new reply posted by {$this->user->name}


diff --git a/app/Notifications/Ticket/User/CreateNotification.php b/app/Notifications/Ticket/User/CreateNotification.php index 3d258030..6cb48832 100644 --- a/app/Notifications/Ticket/User/CreateNotification.php +++ b/app/Notifications/Ticket/User/CreateNotification.php @@ -10,7 +10,6 @@ use Illuminate\Notifications\Notification; class CreateNotification extends Notification implements ShouldQueue { - //THIS IS BASICALLY NOT USED ANYMORE WITH INVOICENOTIFICATION IN PLACE use Queueable; @@ -35,7 +34,8 @@ class CreateNotification extends Notification implements ShouldQueue */ public function via($notifiable) { - $via = ['mail','database']; + $via = ['mail', 'database']; + return $via; } @@ -48,20 +48,20 @@ class CreateNotification extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->subject('[Ticket ID: ' . $this->ticket->ticket_id . '] ' . $this->ticket->title) - ->markdown('mail.ticket.user.create' , ['ticket' => $this->ticket]); + ->subject('[Ticket ID: '.$this->ticket->ticket_id.'] '.$this->ticket->title) + ->markdown('mail.ticket.user.create', ['ticket' => $this->ticket]); } /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ - 'title' => '[Ticket ID: ' . $this->ticket->ticket_id . '] ' . $this->ticket->title, + 'title' => '[Ticket ID: '.$this->ticket->ticket_id.'] '.$this->ticket->title, 'content' => "Your Ticket has been Created With ID : {$this->ticket->ticket_id}", ]; } diff --git a/app/Notifications/Ticket/User/ReplyNotification.php b/app/Notifications/Ticket/User/ReplyNotification.php index 1d2b733a..19b52514 100644 --- a/app/Notifications/Ticket/User/ReplyNotification.php +++ b/app/Notifications/Ticket/User/ReplyNotification.php @@ -2,8 +2,8 @@ namespace App\Notifications\Ticket\User; -use App\Models\User; use App\Models\Ticket; +use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; @@ -11,13 +11,14 @@ use Illuminate\Notifications\Notification; class ReplyNotification extends Notification implements ShouldQueue { - //THIS IS BASICALLY NOT USED ANYMORE WITH INVOICENOTIFICATION IN PLACE use Queueable; private Ticket $ticket; + private User $user; + private $newmessage; /** @@ -27,8 +28,8 @@ class ReplyNotification extends Notification implements ShouldQueue */ public function __construct(Ticket $ticket, User $user, $newmessage) { - $this->ticket = $ticket; - $this->user = $user; + $this->ticket = $ticket; + $this->user = $user; $this->newmessage = $newmessage; } @@ -40,7 +41,8 @@ class ReplyNotification extends Notification implements ShouldQueue */ public function via($notifiable) { - $via = ['mail','database']; + $via = ['mail', 'database']; + return $via; } @@ -53,20 +55,20 @@ class ReplyNotification extends Notification implements ShouldQueue public function toMail($notifiable) { return (new MailMessage) - ->subject('[Ticket ID: ' . $this->ticket->ticket_id . '] ' . $this->ticket->title) - ->markdown('mail.ticket.user.reply' , ['ticket' => $this->ticket, 'user' => $this->user, 'newmessage' => $this->newmessage]); + ->subject('[Ticket ID: '.$this->ticket->ticket_id.'] '.$this->ticket->title) + ->markdown('mail.ticket.user.reply', ['ticket' => $this->ticket, 'user' => $this->user, 'newmessage' => $this->newmessage]); } /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ - 'title' => '[Ticket ID: ' . $this->ticket->ticket_id . '] ' . $this->ticket->title, + 'title' => '[Ticket ID: '.$this->ticket->ticket_id.'] '.$this->ticket->title, 'content' => "

Ticket With ID : {$this->ticket->ticket_id} A response has been added to your ticket. Please see below for our response!


diff --git a/app/Notifications/WelcomeMessage.php b/app/Notifications/WelcomeMessage.php index 3841fc83..d6aa073b 100644 --- a/app/Notifications/WelcomeMessage.php +++ b/app/Notifications/WelcomeMessage.php @@ -2,7 +2,6 @@ namespace App\Notifications; -use App\Models\Settings; use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -20,7 +19,7 @@ class WelcomeMessage extends Notification implements ShouldQueue /** * Create a new notification instance. * - * @param User $user + * @param User $user */ public function __construct(User $user) { @@ -30,56 +29,56 @@ class WelcomeMessage extends Notification implements ShouldQueue /** * Get the notification's delivery channels. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['database']; } + public function AdditionalLines() { - - $AdditionalLine = ""; + $AdditionalLine = ''; if (config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_EMAIL') != 0) { - $AdditionalLine .= __("Verifying your e-mail address will grant you ") . config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_EMAIL'). " " . __("additional") . " " . config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME') . ".
"; + $AdditionalLine .= __('Verifying your e-mail address will grant you ').config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_EMAIL').' '.__('additional').' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').'.
'; } if (config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_EMAIL') != 0) { - $AdditionalLine .= __("Verifying your e-mail will also increase your Server Limit by ") . config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_EMAIL') . ".
"; + $AdditionalLine .= __('Verifying your e-mail will also increase your Server Limit by ').config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_EMAIL').'.
'; } - $AdditionalLine .= "
"; + $AdditionalLine .= '
'; if (config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD') != 0) { - $AdditionalLine .= __("You can also verify your discord account to get another ") . config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD') . " " . config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME') . ".
"; + $AdditionalLine .= __('You can also verify your discord account to get another ').config('SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD').' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').'.
'; } if (config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_DISCORD') != 0) { - $AdditionalLine .= __("Verifying your Discord account will also increase your Server Limit by ") . config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_DISCORD') . ".
"; + $AdditionalLine .= __('Verifying your Discord account will also increase your Server Limit by ').config('SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_DISCORD').'.
'; } return $AdditionalLine; } + /** * Get the array representation of the notification. * - * @param mixed $notifiable + * @param mixed $notifiable * @return array */ public function toArray($notifiable) { - return [ - 'title' => __("Getting started!"), - 'content' => " -

".__("Hello")." {$this->user->name}, ".__("Welcome to our dashboard")."!

-
".__("Verification")."
-

".__("You can verify your e-mail address and link/verify your Discord account.")."

+ 'title' => __('Getting started!'), + 'content' => ' +

'.__('Hello')." {$this->user->name}, ".__('Welcome to our dashboard').'!

+
'.__('Verification').'
+

'.__('You can verify your e-mail address and link/verify your Discord account.').'

- " . $this->AdditionalLines() . " + '.$this->AdditionalLines().'

-
".__("Information")."
-

".__("This dashboard can be used to create and delete servers").".
".__("These servers can be used and managed on our pterodactyl panel").".
".__("If you have any questions, please join our Discord server and #create-a-ticket").".

-

".__("We hope you can enjoy this hosting experience and if you have any suggestions please let us know")."!

-

".__("Regards").",
" . config('app.name', 'Laravel') . "

- ", +
'.__('Information').'
+

'.__('This dashboard can be used to create and delete servers').'.
'.__('These servers can be used and managed on our pterodactyl panel').'.
'.__('If you have any questions, please join our Discord server and #create-a-ticket').'.

+

'.__('We hope you can enjoy this hosting experience and if you have any suggestions please let us know').'!

+

'.__('Regards').',
'.config('app.name', 'Laravel').'

+ ', ]; } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 4a193f98..2e382312 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -3,13 +3,13 @@ namespace App\Providers; use App\Models\Settings; +use Exception; use Illuminate\Pagination\Paginator; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Validator; use Illuminate\Support\ServiceProvider; -use Exception; class AppServiceProvider extends ServiceProvider { @@ -44,9 +44,9 @@ class AppServiceProvider extends ServiceProvider } //if none of result array is true. it sets ok to false - if (!in_array(true, $result)) { + if (! in_array(true, $result)) { $ok = false; - $validator->setCustomMessages(['multiple_date_format' => 'The format must be one of ' . join(",", $parameters)]); + $validator->setCustomMessages(['multiple_date_format' => 'The format must be one of '.implode(',', $parameters)]); } return $ok; @@ -88,10 +88,9 @@ class AppServiceProvider extends ServiceProvider Artisan::call('queue:restart'); } - // Set Recaptcha API Config // Load recaptcha package if recaptcha is enabled - if(config('SETTINGS::RECAPTCHA:ENABLED') == 'true') { + if (config('SETTINGS::RECAPTCHA:ENABLED') == 'true') { $this->app->register(\Biscolab\ReCaptcha\ReCaptchaServiceProvider::class); } @@ -107,29 +106,27 @@ class AppServiceProvider extends ServiceProvider Artisan::call('cache:clear'); } - try { $stringfromfile = file(base_path().'/.git/HEAD'); $firstLine = $stringfromfile[0]; //get the string from the array - $explodedstring = explode("/", $firstLine, 3); //seperate out by the "/" in the string + $explodedstring = explode('/', $firstLine, 3); //seperate out by the "/" in the string $branchname = $explodedstring[2]; //get the one that is always the branch name } catch (Exception $e) { - $branchname = "unknown"; + $branchname = 'unknown'; Log::error($e); } config(['BRANCHNAME' => $branchname]); - // Set Discord-API Config config(['services.discord.client_id' => config('SETTINGS::DISCORD:CLIENT_ID')]); config(['services.discord.client_secret' => config('SETTINGS::DISCORD:CLIENT_SECRET')]); } catch (Exception $e) { - error_log("Settings Error: Could not load settings from database. The Installation probably is not done yet."); + error_log('Settings Error: Could not load settings from database. The Installation probably is not done yet.'); error_log($e); - Log::error("Settings Error: Could not load settings from database. The Installation probably is not done yet."); + Log::error('Settings Error: Could not load settings from database. The Installation probably is not done yet.'); Log::error($e); } } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index ce744916..d49c3869 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -3,7 +3,6 @@ namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; -use Illuminate\Support\Facades\Gate; class AuthServiceProvider extends ServiceProvider { diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index d42ccae5..ad31f958 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -23,7 +23,7 @@ class EventServiceProvider extends ServiceProvider SendEmailVerificationNotification::class, ], UserUpdateCreditsEvent::class => [ - UnsuspendServers::class + UnsuspendServers::class, ], SocialiteWasCalled::class => [ // ... other providers diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index eef3de13..c0fc745e 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -46,7 +46,6 @@ class RouteServiceProvider extends ServiceProvider Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); - }); } diff --git a/config/app.php b/config/app.php index f7cc4229..43f07801 100644 --- a/config/app.php +++ b/config/app.php @@ -41,7 +41,7 @@ return [ | */ - 'debug' => (bool)env('APP_DEBUG', false), + 'debug' => (bool) env('APP_DEBUG', false), /* |-------------------------------------------------------------------------- @@ -71,7 +71,6 @@ return [ 'timezone' => env('APP_TIMEZONE', 'UTC'), - /* |-------------------------------------------------------------------------- | Application Locale Configuration @@ -83,7 +82,7 @@ return [ | */ - 'locale' => "en", + 'locale' => 'en', /* |-------------------------------------------------------------------------- @@ -96,8 +95,7 @@ return [ | */ - 'available_locales' => array_map('basename', preg_replace('/\\.[^.\\s]{3,4}$/', '', glob(resource_path() . "/lang/*.json", GLOB_BRACE))), - + 'available_locales' => array_map('basename', preg_replace('/\\.[^.\\s]{3,4}$/', '', glob(resource_path().'/lang/*.json', GLOB_BRACE))), /* |-------------------------------------------------------------------------- @@ -179,7 +177,6 @@ return [ Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, - /* * Package Service Providers... */ @@ -196,7 +193,6 @@ return [ KKomelin\TranslatableStringExporter\Providers\ExporterServiceProvider::class, - ], /* diff --git a/config/currency_codes.php b/config/currency_codes.php index 6fee59c7..5c3800f4 100644 --- a/config/currency_codes.php +++ b/config/currency_codes.php @@ -1,5 +1,5 @@ 'public', ], - 's3' => [ 'driver' => 's3', 'key' => env('AWS_ACCESS_KEY_ID'), diff --git a/config/invoices.php b/config/invoices.php index 772ef1fd..7944c13d 100644 --- a/config/invoices.php +++ b/config/invoices.php @@ -13,13 +13,13 @@ return [ ], 'serial_number' => [ - 'series' => 'AA', + 'series' => 'AA', 'sequence' => 1, /* * Sequence will be padded accordingly, for ex. 00001 */ 'sequence_padding' => 5, - 'delimiter' => '.', + 'delimiter' => '.', /* * Supported tags {SERIES}, {DELIMITER}, {SEQUENCE} * Example: AA.00001 @@ -36,7 +36,7 @@ return [ * Example: Amount in words: Eight hundred fifty thousand sixty-eight EUR and fifteen ct. */ 'fraction' => 'ct.', - 'symbol' => '€', + 'symbol' => '€', /* * Example: 19.00 */ @@ -59,7 +59,7 @@ return [ 'paper' => [ // A4 = 210 mm x 297 mm = 595 pt x 842 pt - 'size' => 'a4', + 'size' => 'a4', 'orientation' => 'portrait', ], @@ -78,11 +78,11 @@ return [ * Default attributes for Seller::class */ 'attributes' => [ - 'name' => 'Towne, Smith and Ebert', - 'address' => '89982 Pfeffer Falls Damianstad, CO 66972-8160', - 'code' => '41-1985581', - 'vat' => '123456789', - 'phone' => '760-355-3930', + 'name' => 'Towne, Smith and Ebert', + 'address' => '89982 Pfeffer Falls Damianstad, CO 66972-8160', + 'code' => '41-1985581', + 'vat' => '123456789', + 'phone' => '760-355-3930', 'custom_fields' => [ /* * Custom attributes for Seller::class diff --git a/config/recaptcha.php b/config/recaptcha.php index be52269f..ce76c3e1 100644 --- a/config/recaptcha.php +++ b/config/recaptcha.php @@ -14,134 +14,119 @@ return [ /** - * * The site key * get site key @ www.google.com/recaptcha/admin - * */ - 'api_site_key' => env('RECAPTCHA_SITE_KEY', ''), + 'api_site_key' => env('RECAPTCHA_SITE_KEY', ''), /** - * * The secret key * get secret key @ www.google.com/recaptcha/admin - * */ - 'api_secret_key' => env('RECAPTCHA_SECRET_KEY', ''), + 'api_secret_key' => env('RECAPTCHA_SECRET_KEY', ''), /** - * * ReCATCHA version * Supported: "v2", "invisible", "v3", * * get more info @ https://developers.google.com/recaptcha/docs/versions - * */ - 'version' => 'v2', + 'version' => 'v2', /** - * * The curl timout in seconds to validate a recaptcha token + * * @since v3.5.0 - * */ - 'curl_timeout' => 10, + 'curl_timeout' => 10, /** - * * IP addresses for which validation will be skipped - * */ - 'skip_ip' => [], + 'skip_ip' => [], /** - * * Default route called to check the Google reCAPTCHA token - * @since v3.2.0 * + * @since v3.2.0 */ - 'default_validation_route' => 'biscolab-recaptcha/validate', + 'default_validation_route' => 'biscolab-recaptcha/validate', /** - * * The name of the parameter used to send Google reCAPTCHA token to verify route - * @since v3.2.0 * + * @since v3.2.0 */ 'default_token_parameter_name' => 'token', /** - * * The default Google reCAPTCHA language code * It has no effect with v3 + * * @see https://developers.google.com/recaptcha/docs/language * @since v3.6.0 - * */ - 'default_language' => null, + 'default_language' => null, /** - * * The default form ID. Only for "invisible" reCAPTCHA - * @since v4.0.0 * + * @since v4.0.0 */ - 'default_form_id' => 'biscolab-recaptcha-invisible-form', + 'default_form_id' => 'biscolab-recaptcha-invisible-form', /** - * * Deferring the render can be achieved by specifying your onload callback function and adding parameters to the JavaScript resource. * It has no effect with v3 and invisible + * * @see https://developers.google.com/recaptcha/docs/display#explicit_render * @since v4.0.0 * Supported true, false - * */ - 'explicit' => false, + 'explicit' => false, /** - * * Set API domain. You can use "www.recaptcha.net" in case "www.google.com" is not accessible. * (no check will be made on the entered value) + * * @see https://developers.google.com/recaptcha/docs/faq#can-i-use-recaptcha-globally * @since v4.3.0 * Default 'www.google.com' (ReCaptchaBuilder::DEFAULT_RECAPTCHA_API_DOMAIN) - * */ - 'api_domain' => 'www.google.com', + 'api_domain' => 'www.google.com', /** - * * g-recaptcha tag attributes and grecaptcha.render parameters (v2 only) + * * @see https://developers.google.com/recaptcha/docs/display#render_param * @since v4.0.0 */ - 'tag_attributes' => [ + 'tag_attributes' => [ /** * The color theme of the widget. * Supported "light", "dark" */ - 'theme' => 'dark', + 'theme' => 'dark', /** * The size of the widget. * Supported "normal", "compact" */ - 'size' => 'normal', + 'size' => 'normal', /** * The tabindex of the widget and challenge. * If other elements in your page use tabindex, it should be set to make user navigation easier. */ - 'tabindex' => 0, + 'tabindex' => 0, /** * The name of your callback function, executed when the user submits a successful response. * The g-recaptcha-response token is passed to your callback. * DO NOT SET "biscolabOnloadCallback" */ - 'callback' => null, + 'callback' => null, /** * The name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify. @@ -154,6 +139,6 @@ return [ * If you specify a function here, you are responsible for informing the user that they should retry. * DO NOT SET "biscolabOnloadCallback" */ - 'error-callback' => null, - ] + 'error-callback' => null, + ], ]; diff --git a/config/services.php b/config/services.php index 5cfe5840..0920c90d 100644 --- a/config/services.php +++ b/config/services.php @@ -33,10 +33,10 @@ return [ 'discord' => [ 'client_id' => env('DISCORD_CLIENT_ID'), 'client_secret' => env('DISCORD_CLIENT_SECRET'), - 'redirect' => env('APP_URL' , 'http://localhost') . "/auth/callback", + 'redirect' => env('APP_URL', 'http://localhost').'/auth/callback', // 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 ], diff --git a/config/trustedproxy.php b/config/trustedproxy.php index 8cfd785e..d14bf4a1 100644 --- a/config/trustedproxy.php +++ b/config/trustedproxy.php @@ -51,4 +51,4 @@ return [ * \Symfony\Component\HttpFoundation\Request::$trustedHeaders */ 'headers' => \Illuminate\Http\Request::HEADER_X_FORWARDED_ALL, -]; \ No newline at end of file +]; diff --git a/database/factories/ApplicationApiFactory.php b/database/factories/ApplicationApiFactory.php index 13c666db..ed8d5a51 100644 --- a/database/factories/ApplicationApiFactory.php +++ b/database/factories/ApplicationApiFactory.php @@ -22,7 +22,7 @@ class ApplicationApiFactory extends Factory public function definition() { return [ - 'memo' => $this->faker->word() + 'memo' => $this->faker->word(), ]; } } diff --git a/database/factories/DiscordUserFactory.php b/database/factories/DiscordUserFactory.php index e4a7345b..0826d864 100644 --- a/database/factories/DiscordUserFactory.php +++ b/database/factories/DiscordUserFactory.php @@ -24,7 +24,7 @@ class DiscordUserFactory extends Factory public function definition() { return [ - 'id' => $this->faker->numberBetween(186902438396035072 , 986902438396035072), + 'id' => $this->faker->numberBetween(186902438396035072, 986902438396035072), 'user_id' => function () { return User::factory()->create()->id; }, diff --git a/database/factories/PaymentFactory.php b/database/factories/PaymentFactory.php index ad85e725..72ecc37e 100644 --- a/database/factories/PaymentFactory.php +++ b/database/factories/PaymentFactory.php @@ -27,11 +27,11 @@ class PaymentFactory extends Factory 'payment_id' => Str::random(30), 'payer_id' => Str::random(30), 'user_id' => User::factory(), - 'type' => "Credits", - 'status' => "Completed", + 'type' => 'Credits', + 'status' => 'Completed', 'amount' => $this->faker->numberBetween(10, 10000), 'price' => $this->faker->numerify('##.##'), - 'currency_code' => ['EUR', 'USD'][rand(0,1)], + 'currency_code' => ['EUR', 'USD'][rand(0, 1)], 'payer' => '{}', ]; } diff --git a/database/factories/ProductFactory.php b/database/factories/ProductFactory.php index 323317cb..76b11330 100644 --- a/database/factories/ProductFactory.php +++ b/database/factories/ProductFactory.php @@ -24,10 +24,10 @@ class ProductFactory extends Factory return [ 'name' => $this->faker->name, 'description' => $this->faker->text(60), - 'price' => $this->faker->numberBetween(0 , 1000), - 'memory' => $this->faker->numberBetween(32 , 1024), - 'disk' => $this->faker->numberBetween(500 , 5000), - 'databases' => $this->faker->numberBetween(1 , 10) + 'price' => $this->faker->numberBetween(0, 1000), + 'memory' => $this->faker->numberBetween(32, 1024), + 'disk' => $this->faker->numberBetween(500, 5000), + 'databases' => $this->faker->numberBetween(1, 10), ]; } } diff --git a/database/factories/ServerFactory.php b/database/factories/ServerFactory.php index b15e981c..f32281e5 100644 --- a/database/factories/ServerFactory.php +++ b/database/factories/ServerFactory.php @@ -27,8 +27,8 @@ class ServerFactory extends Factory 'name' => $this->faker->name, 'description' => $this->faker->text(60), 'identifier' => Str::random(30), - 'pterodactyl_id' => $this->faker->numberBetween(1000000,1000000000), - 'product_id' => Product::factory() + 'pterodactyl_id' => $this->faker->numberBetween(1000000, 1000000000), + 'product_id' => Product::factory(), ]; } } diff --git a/database/factories/VoucherFactory.php b/database/factories/VoucherFactory.php index 9a381296..02cbf614 100644 --- a/database/factories/VoucherFactory.php +++ b/database/factories/VoucherFactory.php @@ -23,12 +23,11 @@ class VoucherFactory extends Factory public function definition() { return [ - 'memo' => $this->faker->word(), - 'code' => Str::random(36), - 'credits' => $this->faker->numberBetween(100, 1000), - 'uses' => $this->faker->numberBetween(1, 1000), - 'expires_at' => now()->addDays($this->faker->numberBetween(1, 90))->format('d-m-Y') + 'memo' => $this->faker->word(), + 'code' => Str::random(36), + 'credits' => $this->faker->numberBetween(100, 1000), + 'uses' => $this->faker->numberBetween(1, 1000), + 'expires_at' => now()->addDays($this->faker->numberBetween(1, 90))->format('d-m-Y'), ]; - } } diff --git a/database/migrations/2014_10_12_000000_create_users_table.php b/database/migrations/2014_10_12_000000_create_users_table.php index d37bbc76..90bb0008 100644 --- a/database/migrations/2014_10_12_000000_create_users_table.php +++ b/database/migrations/2014_10_12_000000_create_users_table.php @@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { protected $defaultAvatar = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAgAElEQVR4Xu3dCbht5RgH8HUUGqRBqO6gwi1xhZIGlCYSUlGmkjGVaFJCSinNhWgwplCh2ayQoQxFGg0paUaDBlMcz+97+p9n3d05Z9179tn3nnP2Ws9znrP3XtO3vvf/zu/7rYHZs2cP/utf/6r++c9/Vv/973+rRzziEeVvcHCwfB8YGKjabfLOADoutNBChY7/+9//yp/viyyySPXoRz+6Gpg1a9bgf/7zn+rf//53IbqdAYCD223yzwB6BgBh6kc96lHVIx/5yGpg5syZg37MjoUXXrgFwOSn+RxPUAfAgw8+OMToRTJMmzZtEOf7i/iHFt9JgFYFTG40hK51moaufhuYPn36YB6x/PCQzo++AIp2m7wzgI5hbE8RZh+iORXQ+Xjhfr+3EmDyEj8E9z9qoPNpBmbMmDEYIj8MHQ+pgsk9Bf09+oj+4aQ8es+hAoZDTOsJTG4AdXp0nRL9YQCY3I/bjn5eZ6AFwLzO2BQ7vgXAFCPovD5OC4B5nbEpdnwLgClG0Hl9nBYA8zpjU+z4FgBTjKDz+jgtAOZ1xqbY8ZMeADJaIlr1IFb9u1qHRRddtJLlTH5D5tPm3GRBBUikSP3/xz/+Ua65xBJLlM+jbbnXZMXFpAdAklWdhMh3xEfov/zlL4XYyy23XKX+4d57762WXnrpavHFF69uu+22sg8A7FMoATB33313tdhii7UAmAzofliI86Gs5n333VeIueSSSxYJ8Pe//71UwwDFHXfcUT3wwAPVSiutVI65//77yz7FMYDw+Mc/vrrnnntaAExkAJSExkPEHu6//Spf7rrrrvJ/qaWWKtIAcbfZZptqlVVWqY466qjqN7/5TbXyyiuXY4DEeZEGrQqYwAhoAgARjssRVt0jm+BFL3pRteuuu1bPf/7zKxKCOvj0pz9dHX/88YX4j3vc4wqoSAXSoAXABAZAhjaSCkDQxz72sUWfz5o1q9p///2rl73sZeU0wKDvEdn/yy+/vEiDb3zjG0VFMAKVULUAmMAAaDICifGZM2dWr3nNa6o3vvGNhbtxPXsAMCJBIvIZgxdddFH1sY99rABhxowZLQAmMP0Lp47mBm677bbVDjvsUM2ePbs8BhXgnJRK+07U2+IJ+Pz73/++uuCCC6pDDjmkBcCCBADXjI7GsUSy74iGsxExNW9EuO1vf/tb0d+vfOUrq3e84x3Vc5/73CEut59IR2jnuYZrcQddy+d66RS74dprr61OOeWU6stf/nIxHnkT7hXVECBRJ67L7fTftXkUTXGCpv29nvsJHwcQiFlmmWUK4elzrhrChODx1xPweeYzn1m96U1vqrbYYosCGBtiIKxjnOvvpz/9aeHuv/71r9W+++5bjkfU2Ayuy2hERMS98MILq89//vPlPODxewAUW8EYAQQIeR3UTYJOIxGyBUADxE00X9xkm+j46Qw3RDXpJtHEb7XVVtXOO+9cLbvssoWQaXJxLqLjzt/97nfVkUceWZ155plDFbIISlLsueee1Ute8pIyIgQEAvfM+X4//fTTy/m//e1vi21hu/POO4ekgtgCF9PfrbfeWsY3kY3IBS4BmqqO66HciG/nIAoORdjNNtus2nvvvaunP/3p5XcEJSHqLiIQfeELX6g+8pGPFA5dccUVi2oBIoQGGMQGore+9a3lWjYSCHDqnx37qU99qjrssMOKRCKhjMMGdH4DUNdrJUADhzcBgB/PanccQsRvnz59evWsZz2r2mWXXap11123EBKRhXZ9RjjnIgAdfswxx1Q33HBDNW3atAIQx5Ia9qcM3meAI7oFidgQPgNeJM5jHvOYMhZqAbefcMIJ1ec+97kiMZ785CcXULqee99+++1lPK0EGGUGmhpPEMRWGhkHBgoAVlhhheotb3lLtdNOOxXuxckm2mdExIWIJrpHMhD7fnMNcX/cyvATG4g+d24kCw52PSJeXEC0EJfbACF9dgkd//CHP6xOPPHE6vvf/365XuyMuJwtALoAgMmMcYZo2223XfXud7+7EBAYEARxTDwuRLibbrqpcOVpp51WOJUedtxwngSOxrFA5D5J/uBkGwAKHG2//fbV8573vMrxjovrGDVjLF/96lerz3zmM8U+cM9kIFsAdAEAXMrwe/GLX1zttttu1XOe85xCTIQV148ljjB+/9KXvlTE/TXXXFNAQswHBKQNQvkfYxIxo7/9jw73e8Q9QFEdb3vb2woQfLY/QAAsQCBhbrnllurjH/94deqppxZbwDX6GgAmO3l4ojONCp3tZ6VVeWBgKD+PsIytF7zgBdUb3vCGEslDHMSMOI91jhDf/va3q6OPPrr6+c9/XvR2dHBTOrfBRClEfsITnlDUxY033lg94xnPqPbYY49iLCbDGJuDtABKG3UgdnD22WcPeSuZC/vr/fokReIJ7ue5ckyTimwaf9P+nnsBsYY9MIKGs3ALfe17dDZQZLGKNddcsxAdx+FWm0CMz8R8Jkmg5vDDD6/OOOOMQnTGIc4LMXB8N1vGLWz8xCc+sYxB7EBC6c1vfnP18pe/vEieAM39PBtAG4NoIon0s5/9bCjJZHxURAJZqUOIVwJYiUP0ujNrvgAAATxkCMlCR/h0rWYCAcIxuOvtb397sapNaKpzYoS5Fosedx100EFDq11kf66NCN1OYIiUNRSi8xNjYB9QTQxF0sn+ANRz+czj4IkwFMUGqCYA9jvgpBopQDA/MSa7Ae/cnNtzAJgoW8Sfh/PwHpy4NLEmwu+CMPvss0+J2zPC4kLFSEvyhqHFB//DH/5QOD6hXZwXNxA3EdvO6WZLriE99UDlWRDXGD2L8YkdvO997yvE9TxZgsW9SQzBKR4IwAom2e83YycZE9PwDO4FxAlzdzP+pnN7DoBwYdw5BEF8FvvNN99cJIPw7bve9a5qyy23LNxgQiMtTELWLuJuITxxaqITdzd5zouNELeQyHafbjbXRexEEmObGDdbI4RDXGDkdkpAJWcR/e4ZjMuzc09FEwHBmJWpmRdzRIo4x595aAokdfNsxc6oLxDR7cWGOz++e3xvyBY69Z1xtfvuu1eveMUrCjeYTBMXaz0+Oj9ewOUrX/lKIQYuNzkAgNtY2s4xef6bZPchAZqs8KZnNgZjcr0QB7F8T7jYMcbvN1FGgSlAYCfYZxwAmziDZ6fafvSjH1UHH3xwMS6Bg+53L/sQvm7rNI1zrPt7DoBYszjaQyU6xsCj51ddddXy8ESfY8JRCGmC+fMnn3xydeWVVxb3K7kB+02QyaQ+XDt+d7yDVAONdXKcFxsifn241H2TmwCMGHaOZyguv/zy1UYbbVQSTcLOyTY6FhAydjYB24DbGKC4r/vEU+hm/E3n9hwAMZZwvclhNEm6rLHGGmVsibXjbJ8TnmU0KdH61a9+VSYT4VOijdBZ2SwuYbjL/6gdYErApmkiRtrvev7ingFCQsyIntKx3DN5iEggYxdWFkNI/CBjQnAg8gzsGWqBlEuKOupwrGOfm/O6BsBwg8ykZXKgfK211iouXfxnho+JJMoRKqlbbtNHP/rR6ic/+UmZmCRiRnqYbq38uZmk0Y5pymWkBP3Zz352sXOoO9IOmJNSdkzUmudn5J577rllfurP31n4EunazTP0HAD0mbj9O9/5zqHyqvj7SeUiND0vkHPOOecUSZEoX5MRNNEBUI9heG51ByQgw5c6AATGZPIK5oJKBID3vve9c6zRNCkBQMzR4yx8D8kGYPVCN+IxmqRWHWMfY4mIrLuLoyF8ogMgnO55STrPKHdBGlILYh02mUXGJcBQAULKgkwkpa2zcCTfmyRQk3TouQSAZlG6DTfccMjAQ2AP/N3vfrf65Cc/WYIjuCF+v4d2jIly/mhbtxU13U5g0wQjfJpL4j1gCmoAI7zuda8rUuGpT31quZR5iI3ht0Q8m+4z1v09BwAXBwBe+tKXDoVLEf/AAw8s1n09YMIQJAJjG+CeJGpGesCJDgDc7Hl4LakVoPqoNhIRwTfddNPquOOOK8auOTAnJOPqq6/etRHbBIyeAwCHyY6RAImXC+PuuOOOlcDOk570pPLQCfawnlOcmUBP00N0s7/bZEsTAEkyRPZcnid2jzFnWV6fzzrrrOppT3vakGdEVahm5h0MZ+xFcjXdv2lueg4AXCwZwvqF7Oh3NsEVV1wxFNCJN4DjqQIgwAXxDpoeZKz7ew0AKkx9oGf32XPVu5D9hgkUnSbRZQ5EFgWU6p1JIXpdbU14ANB/jLxXvepVhQsMnijceOONq+uvv36odDqESPuWyaAziclebr0GQFrS0nOQeIVnSl7BsypSFUoGeEQH/he+8IVztKdPSAB0iqcgMpm+eAEMnUTrGHnq9kkALhAp4aEjElOnlzSxewgQiQwyioRd0xtQD/SMxU2K6knMwdh4FkLIidq5f6zzFJsaS7qHAdW4EtRKCXqsd+NCbGPlFrsXQruG65EIDGIRQ+e6lnkjATBAagWSkApojb1bI7ZrFdAtAEyMCUp1bsKfSbum5s+kqAUEFC4SfZq8eyTEWADgukBIUqWkDEGTm2e3pFyMakrQCgjFLjJ+0g1IADV2jPElYpkqpMQ1EsJOKrhvAZDFGBJuDcoR1WeTjgtwjHAyrhRVFC+47LLL5vCPxwIAQMK5rs1OkckDCEGYP/7xj0N9ASQOqeD/n/70pzIu1UHCu/H15QCErhGddHBssnyeBScnPZ74hTH3tQQwQdGL9QpgHINb6MJU+eAa5Vg8CJMunawnoBsJYPIRTq0ht1Ql8NVXX11qExApqWCAY7OIUGoyVaOomcRGShgP9cFqP+mkk6pvfetbJY4RNYLwyWWk8MPzxDboWwlAbKYAwmSSCNGz6a9Lo4UcAVvCpBLBMoSbb755VwAgATSCahPD9XT0XnvtVSKTVg5JQunPf/5z0dEaS+QzgBXBcXpqFhA4BSiMOi1qSW+TKsYNUCSJ68bG6WsJAAB0pi0p1+hQ3BG3UMpULCG2AX1Nb6+//vpdAcA9if9vfvObpRIJlwvTpuQ89QA4X8UP9xUhjRsAfvnLX1a//vWviw+/3nrrFY4OCH784x+XHAhVojglxaPxbqIW+hoA0ZHUQMCQ0m161m+XXHJJIXIKP4SORc0YYZtssklXAAAkUkQPge3YY4+t9ttvv2JjIDSjDgGlaiVxWOe2X/ziF0UVGAvuZiiuttpq5VxRT89DkpEsonykmfGnYynFK6RAXwMg7hbuII5T509/0sfCyJECVAFRLHDi2PFQAQiBaIpTeBziFQCHKMYGIGLysnNAQXQrSSMJgNM4U9xJkhgXNfH617++SAgif+utty5t5uH8NKo41v6+BgAxKCmCs5IHYEjhtve///1l0hINUz5GKhx66KFFnDqOBHCNWNWdUbLUCaYqOR1C8bdZ8VYCUZ5GDSjujM8PEIiLoPoEk77F4bp/SCGcn/qHlKipctIllKJPxqVuJsYiUNVtnhSwMAIB27hSTEKlJG4Q99j/KRUHMIm4OsYfLldKpSgiuXREs6jTZz/72bJ0i8840XkSKaMBIO5k3C8TSE/T6US7km7rBpEyjD+qIGKZuAYM9+UlMPw0oCCmfWkTy/oDniG1fVQJT8G1FLdoacs5iBrJZ7979y0ATABOS308t4/oP+KII4rRxyXTAZy8AYK95z3vKRMrIJTCy5EkQJIw6fyNmiG6AQjXr7322sX4QzBEBji6n34HMGVa8fVV9eDodA2n1q8exQQCksQzpLZRWZhqYBKNqmAUki59DwCE94cYJgfHXXfddaVQ4tWvfnUh0FVXXVUCLrKIiI9jTbKMWZMKwJ3pD0zzZ4is+whxqRX5CpztPq5tLO7nN4RMx7D7XXzxxUX8ZxFKnkk6eZwn3S1Y9Z3vfGdocQnA5VoCXlLE6SnoawkQTjDBaRSpu3p+15Ur6KO2QGqZa2USiXD6eDQVgPNFERE17VjUByJRM1w+HMlnZ9wlqENSAJgyNSVtyVaSSgCakrW4iVQLO4Y9w/ij/wGFBKAaqBHjFjfwPeXsqWDuWxWQUikTatIZVybJdyIepxHP6c8nWkUD6VAAYC802QAmHJBShpawrrp8ANTIyaVLG1cCUkDzxS9+sQDQeBBeuBh4UuSRtra0epFg6W/43ve+N7SMjHQvz4HqYNtI9/Iq0p3ctwBInz8LOz1zCEG8AgQi4D6umAWaROtY5Vmho8kGqJd1kwDAAgAIrssI4dTuWwAKyHBvAlLuLaKnhB3B2SGigOnwSbkWEZ6ilvQiGLtzrWJi/MDmXM/oWGNIxLOvVYCJimVu8ohR3JZFnUNABMdZH/zgB0t5NeOJtJALGE0C1N2nRIyyjgDpQbXgTGsA2NJngGhyBF/72tdK7YLv1hwgAYwjMQLcbF9Ku43F2D0Dj0K+wG84nCcAAHoFkzVMXUDfSoDU/yV3Xk8vh3jJh/MQSAANpCkl7zQC6dx6uZTvxD/dTO8iHq7k++M8zSeuSdWk9Sv/EdWCEww6dgSVwzdHvHQtBwiInNoG3E2NSQrpBwByncxsgCxFkyLYvlcBYwEAgiGsUHBnHKATAAERYiIE7tSPx5bwmwigoE2s/ywC6VjGoUWkRfIAx3ccjXhsB/9tVIJaBQBzP4CzX/QwZd84nMHpuukudq7Pfa0CxgsA9Tr5ugTwe4xAXIpQmk/EGqwmIv9PsmQVkDSW4nJuoICO9DOi4voNNtigGKckStYDSP4fQCLBSAzXTxEJl5DdQQXUy98QvwVAxytf6rVvCBgVkFU9qQCTKI07XBzA+c7LHz3tz/FCzOwInPihD32o+PhZiRSBU4CCUES+cLTj2Q2kh6ZWtkBUlusaH+7PK2YYkQDFDaQOHCN8bW0AwEkpV4pfWgDMJQBiA6Rlqg6AlFrFaAzxASUNqoh0/vnnF72Mo6kPsQU+u+/OAQwJIADgqkkOiRdkUSj5CK6h/YkBICCDkeHn/s4T+eP7R9czNLmbaYM3XvdqbYCHGkRHMgLrEmA4AMQGqAMg10oxpu/CujwGxMOR6vBl7Bh/CBivI6uGJnOnKIT+TtGodQqsTyjhg7vTxh2XFQgAU9SPzjcugLLYFQnjXsl41pehbb2AWv9bZ/nzcF6AY2QDxe/jBiaCWAdAzhXV04am2YKriYhsASI5PjwiImhqEf2OQ4WJ3Qc4xPNFDYExmTsGYhaQ8hvQWJbWK2iMU4xBoilxhnQFZxWQVgWMogLim5vIugTwOwAIBWeNoE4AIGTi9CYZ11sDWG5BEYj9adlC/KR/064GDAw7/jt3kTiP7WBlMq5eUsDOcS3xhAMOOKC4limDf+1rX1udd955xdMgiZxnSwdUXwOAHx0Cpo0qTSGqb5POZZ2bMG6b6hybghBBGhwoW5eiEscm/ZtVSRh/In6se8Rj3HkbSMrRhsqKOj4gDhCQFur0E/ThRn79618vIOJREPtEOwNVwipLxWt/0wCaWgcg5olk7aJUDlkXwHVSIMte6Yt6gIjDFH6EI02E9mhiE4ETYvWiJyFVhGV4SdYgQiJx9CzxG2Mr8X9LsCTtSzcT5cR/04shXTvEcF3WfRaalhbm68sNsAm4lMLGWVMIWEgaEodaYGjyZNL1zOOgZripfQsAhGeAsaoR1AQjokn8wQ9+UKpkEMkkpa06vjWwOM6WrBq1gFNxmes5B1HE5YECEVnyKUdvkgAASmTLQ+BkgaF0LqVvMcvAGQcweAaeAJdR7aD7GrPjSBSg9MzpM+hrACB8LHCiNmVWJkcGTU8AItUXZ8ZZ9HHKq9KKZXKpBQYbLkME54r8CcPaLDvL4nZuVvUcSfz7PW8PBQIqiZhW6CknkCggIMSecD+SQdpaniGvowFG40xdIXWWJti+BkAWQ0h0zKTQkwiewssUcsS6j/WNO9NTmAaLlHinpczkKirxyjjFnsK6pEUWnZwbCeAayRKmH0CJGNdOOXikkwAR1aIAlNTiElJfxuY+QJnGTwDMYld9DYAs146j84YNk5eIXAI60fOx9LNqV6xv3wHDcQy9LEerduADH/hAsc65gfzzuhhuWoSKBHCM+2YFk5SfCSIhchZ0SKjZWOh7qgBgEuyhrlzPOJ2X/sO+BoCJwBUpuUpghd7ku6er1uTWF1RIW1UaS10jFrpzk6gBKtxPN+sldA33TNNniDmSGsC1CkGoIpKDdAIwRCRFWPPGzKBk6RP77pmCFedlgQjSIOdFjaViqG+NQIRAPBOBw0xWauaynkAWgKyv2JmmUscmoIITs75AQsB1yZEVOvxGQqQgdTQbIF2/7AWfsyIoVWO8afi0j6j3PUZiGk95NBm7c9zf+WkXm9QSIImX+iQmHu+/wAcdzKdNUMfD86NZ+Ymf19O2aQlLanY0AiULONIxsS1G2t8kAUa799zsA0jPARjulZJzzwiEwAu4Ygp5i7nfqQoxjqwSNjf3GssxXa8P0AQADyB+zqePOKf7fFeEGXGahE0IZrJwVQI6Iz3cRAdAun8CtOQP/A78XENhZOliaiNShcoS82iKU4yF6HMwa7eLRTcBAMKlQYVD4yoBAAufxeyBs5BC6v/8lsKKNIdMVgAkkhn1kJBzVhRBfGlnNoAydRID8BFeqpvN0cut5xLAA2jrloRJxk4kzds2xMdjJAFKpEFW5ACMpq1JAiSxNFYANd2/aX/8/bi7eTcCIDAihZAVtkoYCU3Hy2ELPeUpT2mUgE33b9rfcwAgpuibVCxkJ3LnVe1y8zpnY5zhivpaeo71vRsbYEEDIG4mjk5IO4UjxLywtqXldRbzhBxPUgpiqT6qrxLWRMyx7O85ALhJXp4ka4cbSIS87AHaiT/VMkBCCmTdQMCZGyu9SQKMZVLG8xzPQM+TAMR93itsBRItbww9W95ZnG4hgAEA5/Zy6zkAIFgmjshHeFteBcfgS2UMjwAQ1M8LoOASHkRToGaiAwBBxQgAWuBI5FBZu4qhJMCoBZ9Tu0jyWXSC1Gx6/m7B0XMAeHAPwerX6wfVKdWOLx9Xia9tPQAZProxeYBuVEC3E9Tt+dHzQK3FXJuZfAfgp7GkvkyOQJJopfoDxnDspm7HMdL5XQOgaWCx8IkygQ/VNKpsZesi7hIk8bCOl3T5xCc+UerqqQ3Bl8T93S8hX9zfWQuYGETG1a2fTy1lUae8ICJL3jLUiHiSjchOx5DxZZ/fZBFJQEvEZ6lYxxh/7CLXlmlUfaTqGHAcE5A0zfNY9/ccAEmKpHnSA2nz4hWYlJRhZb29LKGCcDqGZd4UUzKKZORMmslyPLD4n7BvYvZ55479TUZg08QZr7+sGOL+eZl11gegv1MaDhxUF2BYRo76U4SK621ZdMp+n41ZrQLia4W3JT+Sl2E3jbGb/T0HQMKhJi4191KjxBvLV1k2zkixpP+2FFACgi4e6w1feumlpawqlbs4hCVNVbi2CGO4MNZ0tyI0/YQIbCwpMWfbJG4RYBoLogK4ohN9AGlq9UzGZ5yRZhpbVCbxiOxL6jggcWyvl8rtOQA8eOLxWUnTA7KGM6mCRMq1dNEAhwcHkOQCwi04RWMoyYDoKctGiHT+hPC5djfc4VwSJNk84ARMHM9IpcYQiNTi7VBxysiVrXmRpM3+1P8nwMUY5PV4bRx1FzUSglN7TRHQbp8r5/ccADgla+kSaanbA4aI/3gF7AP1dERgXvkWfYqgqdVX4OGlUlmDz/EBSfIIJA7CJO4w1gnLCiPOT+IpQZ30BwIg41baWdmZDcCpoHrVj7lQmKqm0YqinodEC4iSCU2lEanQ7Wvvmp675wAIkhHQ51TBZFHmcCxOM0HEp9U01NfZEkL1OSFSk6JEi7fAfQwQ6hm52AfdBlJcO4WaqfJN8SqQcutUAPNwbKx4Mf68BCrSg3vLnlGNJOLJJkh6OXrfmIEWeHPfrJ7aRMix7u85AMKFJjEWdVbqSmrUJCVTlgUgvV6OfjTBWVnTceEO1wAojR46cCzKSCQLtqgjwJ28h26TKe7heqQYtcNCZ5CyX/IyrCz1VjfsIrmIeNFOreIIKyaA8FldzPNkXcTYQSll79aDmRtQ9BwABpF35eB6QEhqNBZ6OCueQDifdc9lBIZ11lmnPE/EIg7JIguqfUwwt9GEi6lTMazxuGxzMxnDHYOQAEhMM/IATFmZ2kJt5vUt3IqTNZYqJZcHCVfXVz2LKkyRiDkBjKw4kpK2GMVjHX/TefMFAKMNoilfHxtCG5dAioBKCi5wiP0p1WJNM64s6sDeiJhNWDleSIzL+OAmP7WBKUvHhUS1fQzThGbF7bM8bcK3sQ+y4odgluXs6HlSaLRtQUcyJzwAEA8XIIyuHoUkLO2syoWr6nYCwiuu4DFYny+Wd2IEeQFDJENeS4MQwOR6WfIFwEghhhq7RNzCcdRUwGF/spaKTgWw3N8WL6EFwCgz0CQBsnATIiMQ4ij71ttHLSBGLOW6xU78Kzj58Ic/XApC86IHqiPXQjz9e6KUgIGoiInj3Yu4J+qpIbo72brkMKgwnyW0qB/SB2C5gylTa4rk9b0EaIrUEb0IEV8f5yIoguDIqIXYB/4n+MJeIBGsNG49wFT4pjIJ8ZKpi9VOz9ukafUSiOIlZA1g9DzDDYEBxXsBJLGsVySTGfVC4rhW1NNIPNACYGBgVB1pQpNHT3IEaACDdW7SdfpQDcmmxcBKcYUbiCKKs/PDERGX2g8kRDxJgqDazbl1av5tLPQUdcSI85taBmpGlFKzSELSAXTcvyaA9z0AmqxU3Mf9oqsRnBGY6t/U/yMci5yBljeIpOsnXMs3twGAZV9SIg5A2slIFHF7QEJMkoO6SDo2fQiikNw64t5vopckEqngj5uI6HllTIzLVgI0UXqE/YhBTNPzJpgYN8EIg8hZ0DkulKXfSASLOcXFSgbOuaQI8S0MK6LIXUN4NkXWCsgqYe5J9aSMW8xBy5d74nog4QmwI9gH4h6Dl00AAALgSURBVAPUj/OM2fjquYDhHrGVAA3AiMGF6xE+L1oAjMQBEkfwP/X2wsqIigAIGH86nUYIy1B0DXF710dQ4IjeToAKWEgNRaxUR7051XmuAWxJFAGDc927KZnTAmCMkmG406Jv63r3qKOOKquOBwh5V49jEniKJ5JmERID9/LjJamI+CwCFfWTGEK32cZxfPwxXWqBxwHGNOoRThoOAHQyi179neaUepYtLeUIj5BxJzV5cuv8adZAfG4hteP8LCMzN40r4/l8vbjWlAdAxDhwCCnjaETNGgRZWMLkSuQozBDJY3AieDicakgIO4Zd+hN7QZj5dc0pDwA6NoRjH/Ai2AYqkuhzwMDh3gSC40UPGZt5FxBiJ7OYpWwQJyVd84tQvbrPlAdA3vSB09OTz/JfffXVS/4esaWVBXTk57NgBWJLYsUjSP0eQmSxCuBoimT2inDjdd0pD4C4jiaMJEhpGmNQ5hAoiPqkpgMYv0XUp08RKBA8Yd4WAOMFw3G6znBGYN7uGVdNKDlGn7QxNy3VvkQ9Iqdkm6sooBPRj/jpYjbk4foix+lR5ttlprwEQCTER0QuXN7Zl1Ct7wCAqxl1AQeJ4HggCOfHbUyVURJL841aPbjRlAJAD+Znyl+yBcCUJ/HoD9gCoAXA9ME+n4O+fvxWAvQ1+auqBUALgFYF9DMGWgnQz9QXzOpcJSwFCp1Rrz6fp0n7+Elapcuos0ZxYMaMGYP5MdUyedqpEOqctJQbp4F30rC+gEYpmp05c+bD3EA7RkLMOI2rvcx8moFOid552zlUQB0dAJCFHefTWNvb9GAGQsOkrR8m5adNmzaYHx0U3R8p0FTX3oMxt5ccxxlAx06aZsGKwvBUQFKgaeHuNBzGcTztpRbADNQNelnQVEmpjxiYNWvWYGrqs6MFwAKgUg9vWQcAZsfoUtnS2wOzZ88eTLFE8t4BQA7u4djaS/d4BsLUKWTJQhx5N+L/AfjNYarLl7XXAAAAAElFTkSuQmCC'; + /** * Run the migrations. * diff --git a/database/migrations/2021_02_08_190205_create_activity_log_table.php b/database/migrations/2021_02_08_190205_create_activity_log_table.php index cb4f3cc5..cd9afe3f 100644 --- a/database/migrations/2021_02_08_190205_create_activity_log_table.php +++ b/database/migrations/2021_02_08_190205_create_activity_log_table.php @@ -1,8 +1,8 @@ uuid('id'); $table->foreignId('user_id')->references('id')->on('users'); $table->string('payment_id')->nullable(); - $table->string('payer_id')->nullable();; - $table->string('type')->nullable();; - $table->string('status')->nullable();; - $table->string('amount')->nullable();; - $table->string('price')->nullable();; - $table->text('payer')->nullable();; + $table->string('payer_id')->nullable(); + $table->string('type')->nullable(); + $table->string('status')->nullable(); + $table->string('amount')->nullable(); + $table->string('price')->nullable(); + $table->text('payer')->nullable(); $table->timestamps(); }); } diff --git a/database/migrations/2021_04_11_190944_create_discord_users_table.php b/database/migrations/2021_04_11_190944_create_discord_users_table.php index 6d556704..7a519c28 100644 --- a/database/migrations/2021_04_11_190944_create_discord_users_table.php +++ b/database/migrations/2021_04_11_190944_create_discord_users_table.php @@ -3,7 +3,6 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -use Illuminate\Support\Str; class CreateDiscordUsersTable extends Migration { diff --git a/database/migrations/2021_05_08_164658_create_configurations_table.php b/database/migrations/2021_05_08_164658_create_configurations_table.php index ca5cb6f0..f353c4aa 100644 --- a/database/migrations/2021_05_08_164658_create_configurations_table.php +++ b/database/migrations/2021_05_08_164658_create_configurations_table.php @@ -21,6 +21,7 @@ class CreateConfigurationsTable extends Migration $table->timestamps(); }); } + /** * Reverse the migrations. * diff --git a/database/migrations/2021_06_09_213306_create_useful_links_table.php b/database/migrations/2021_06_09_213306_create_useful_links_table.php index c6fc7337..cb9e2614 100644 --- a/database/migrations/2021_06_09_213306_create_useful_links_table.php +++ b/database/migrations/2021_06_09_213306_create_useful_links_table.php @@ -2,7 +2,6 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CreateUsefulLinksTable extends Migration diff --git a/database/migrations/2021_06_23_090026_update_price_to_payments_table.php b/database/migrations/2021_06_23_090026_update_price_to_payments_table.php index a3bb56af..fa6c9447 100644 --- a/database/migrations/2021_06_23_090026_update_price_to_payments_table.php +++ b/database/migrations/2021_06_23_090026_update_price_to_payments_table.php @@ -26,7 +26,7 @@ class UpdatePriceToPaymentsTable extends Migration public function down() { Schema::table('payments', function (Blueprint $table) { - $table->string('price')->change()->nullable();; + $table->string('price')->change()->nullable(); }); } } diff --git a/database/migrations/2021_06_23_090806_add__currency_code_to_payments_table.php b/database/migrations/2021_06_23_090806_add__currency_code_to_payments_table.php index 3e6710bb..fc34c864 100644 --- a/database/migrations/2021_06_23_090806_add__currency_code_to_payments_table.php +++ b/database/migrations/2021_06_23_090806_add__currency_code_to_payments_table.php @@ -14,7 +14,7 @@ class AddCurrencyCodeToPaymentsTable extends Migration public function up() { Schema::table('payments', function (Blueprint $table) { - $table->string('currency_code' , 3)->default('USD')->after('price'); + $table->string('currency_code', 3)->default('USD')->after('price'); }); } diff --git a/database/migrations/2021_11_05_071456_add_tax_to_paymentlogs.php b/database/migrations/2021_11_05_071456_add_tax_to_paymentlogs.php index 3796ee9e..159f1f30 100644 --- a/database/migrations/2021_11_05_071456_add_tax_to_paymentlogs.php +++ b/database/migrations/2021_11_05_071456_add_tax_to_paymentlogs.php @@ -14,9 +14,9 @@ class AddTaxToPaymentlogs extends Migration public function up() { Schema::table('payments', function (Blueprint $table) { - $table->decimal('tax_value',8,2)->after('price')->nullable(); + $table->decimal('tax_value', 8, 2)->after('price')->nullable(); $table->integer('tax_percent')->after('tax_value')->nullable(); - $table->decimal('total_price',8,2)->after('tax_percent')->nullable(); + $table->decimal('total_price', 8, 2)->after('tax_percent')->nullable(); }); } diff --git a/database/migrations/2021_12_15_120346_update_to_payments_table.php b/database/migrations/2021_12_15_120346_update_to_payments_table.php index 50900f29..e2847c9a 100644 --- a/database/migrations/2021_12_15_120346_update_to_payments_table.php +++ b/database/migrations/2021_12_15_120346_update_to_payments_table.php @@ -2,9 +2,8 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\DB; - +use Illuminate\Support\Facades\Schema; class UpdateToPaymentsTable extends Migration { diff --git a/database/migrations/2021_12_28_203515_rename_paypal_products_table.php b/database/migrations/2021_12_28_203515_rename_paypal_products_table.php index b3b64dca..a4a069d8 100644 --- a/database/migrations/2021_12_28_203515_rename_paypal_products_table.php +++ b/database/migrations/2021_12_28_203515_rename_paypal_products_table.php @@ -1,7 +1,6 @@ renameColumn('credit_product_id', 'shop_item_product_id'); }); } @@ -28,7 +28,7 @@ class RenameCreditsProduct extends Migration { Schema::rename('shop_products', 'credit_products'); - Schema::table('payments', function(Blueprint $table) { + Schema::table('payments', function (Blueprint $table) { $table->renameColumn('shop_item_product_id', 'credit_product_id'); }); } diff --git a/database/migrations/2022_06_02_081655_referral_code.php b/database/migrations/2022_06_02_081655_referral_code.php index 15cca0b7..362ea5ca 100644 --- a/database/migrations/2022_06_02_081655_referral_code.php +++ b/database/migrations/2022_06_02_081655_referral_code.php @@ -9,18 +9,18 @@ use Illuminate\Support\Str; class ReferralCode extends Migration { - - public function generateCode($userid){ - - $random = STR::random(8); - if (User::where('referral_code', '=', $random)->doesntExist()) { - DB::table("users") - ->where("id", "=", $userid) + public function generateCode($userid) + { + $random = STR::random(8); + if (User::where('referral_code', '=', $random)->doesntExist()) { + DB::table('users') + ->where('id', '=', $userid) ->update(['referral_code' => $random]); - }else{ - $this->generateCode($userid); - } + } else { + $this->generateCode($userid); + } } + /** * Run the migrations. * @@ -32,14 +32,12 @@ class ReferralCode extends Migration $table->string('referral_code')->lenght(8)->nullable(); }); - $existing_user = User::where('referral_code', '')->orWhere('referral_code', NULL)->get(); + $existing_user = User::where('referral_code', '')->orWhere('referral_code', null)->get(); foreach ($existing_user as $user) { $this->generateCode($user->id); - } } - - + } /** * Reverse the migrations. @@ -52,5 +50,4 @@ class ReferralCode extends Migration $table->dropColumn('referral_code'); }); } - } diff --git a/database/migrations/2022_06_02_091921_table-user-referrals.php b/database/migrations/2022_06_02_091921_table-user-referrals.php index a6fdbd83..344ec8ff 100644 --- a/database/migrations/2022_06_02_091921_table-user-referrals.php +++ b/database/migrations/2022_06_02_091921_table-user-referrals.php @@ -16,11 +16,10 @@ class TableUserReferrals extends Migration Schema::create('user_referrals', function (Blueprint $table) { $table->unsignedBigInteger('referral_id'); $table->unsignedBigInteger('registered_user_id'); - $table->foreign('referral_id')->references('id')->on('users')->onDelete('cascade');; - $table->foreign('registered_user_id')->references('id')->on('users')->onDelete('cascade');; + $table->foreign('referral_id')->references('id')->on('users')->onDelete('cascade'); + $table->foreign('registered_user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); - } /** diff --git a/database/migrations/2022_07_12_051152_decimals-in-price.php b/database/migrations/2022_07_12_051152_decimals-in-price.php index 4b5fff4a..c9d84553 100644 --- a/database/migrations/2022_07_12_051152_decimals-in-price.php +++ b/database/migrations/2022_07_12_051152_decimals-in-price.php @@ -14,7 +14,7 @@ class DecimalsInPrice extends Migration public function up() { Schema::table('products', function (Blueprint $table) { - $table->decimal('price',['11','2'])->change(); + $table->decimal('price', ['11', '2'])->change(); }); } diff --git a/database/migrations/2022_08_01_170819_create_tickets_table.php b/database/migrations/2022_08_01_170819_create_tickets_table.php index 5ae8cda7..023b42ca 100644 --- a/database/migrations/2022_08_01_170819_create_tickets_table.php +++ b/database/migrations/2022_08_01_170819_create_tickets_table.php @@ -1,8 +1,8 @@ increments('id'); - $table->string('name'); + $table->string('name'); $table->timestamps(); }); DB::table('ticket_categories')->insert( - array( + [ 'name' => 'Technical', - ) + ] ); DB::table('ticket_categories')->insert( - array( + [ 'name' => 'Billing', - ) + ] ); DB::table('ticket_categories')->insert( - array( + [ 'name' => 'Issue', - ) + ] ); DB::table('ticket_categories')->insert( - array( + [ 'name' => 'Request', - ) + ] ); DB::table('ticket_categories')->insert( - array( + [ 'name' => 'Other', - ) + ] ); } - /** * Reverse the migrations. diff --git a/database/migrations/2022_08_01_181607_create_ticketcomments_table.php b/database/migrations/2022_08_01_181607_create_ticketcomments_table.php index 58886b45..d81e942a 100644 --- a/database/migrations/2022_08_01_181607_create_ticketcomments_table.php +++ b/database/migrations/2022_08_01_181607_create_ticketcomments_table.php @@ -1,15 +1,15 @@ id(); $table->unsignedBigInteger('user_id')->unsigned(); - $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; + $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->string('status'); $table->string('reason'); $table->timestamps(); diff --git a/database/migrations/2022_08_25_202109_create_partner_discounts_table.php b/database/migrations/2022_08_25_202109_create_partner_discounts_table.php index 976aa3a8..184e80e1 100644 --- a/database/migrations/2022_08_25_202109_create_partner_discounts_table.php +++ b/database/migrations/2022_08_25_202109_create_partner_discounts_table.php @@ -32,4 +32,4 @@ class CreatePartnerDiscountsTable extends Migration { Schema::dropIfExists('partner_discounts'); } -} \ No newline at end of file +} diff --git a/database/migrations/2022_11_29_075851_email_verify_d_b.php b/database/migrations/2022_11_29_075851_email_verify_d_b.php index 04e2663b..2689edba 100644 --- a/database/migrations/2022_11_29_075851_email_verify_d_b.php +++ b/database/migrations/2022_11_29_075851_email_verify_d_b.php @@ -26,7 +26,6 @@ class EmailVerifyDB extends Migration } } - /** * Reverse the migrations. * diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index e759a595..6ed3baa0 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -17,6 +17,5 @@ class DatabaseSeeder extends Seeder $this->call([ SettingsSeeder::class, ]); - } } diff --git a/database/seeders/ExampleItemsSeeder.php b/database/seeders/ExampleItemsSeeder.php index 42fb4bbc..925fda7d 100644 --- a/database/seeders/ExampleItemsSeeder.php +++ b/database/seeders/ExampleItemsSeeder.php @@ -2,9 +2,9 @@ namespace Database\Seeders; +use Database\Seeders\Seeds\ApplicationApiSeeder; use Database\Seeders\Seeds\ProductSeeder; use Database\Seeders\Seeds\ShopProductSeeder; -use Database\Seeders\Seeds\ApplicationApiSeeder; use Database\Seeders\Seeds\UsefulLinksSeeder; use Illuminate\Database\Seeder; @@ -21,8 +21,7 @@ class ExampleItemsSeeder extends Seeder ProductSeeder::class, ShopProductSeeder::class, ApplicationApiSeeder::class, - UsefulLinksSeeder::class + UsefulLinksSeeder::class, ]); - } } diff --git a/database/seeders/Seeds/ApplicationApiSeeder.php b/database/seeders/Seeds/ApplicationApiSeeder.php index da66c937..963f848f 100644 --- a/database/seeders/Seeds/ApplicationApiSeeder.php +++ b/database/seeders/Seeds/ApplicationApiSeeder.php @@ -15,7 +15,7 @@ class ApplicationApiSeeder extends Seeder public function run() { ApplicationApi::create([ - 'memo' => 'admin' + 'memo' => 'admin', ]); } } diff --git a/database/seeders/Seeds/ProductSeeder.php b/database/seeders/Seeds/ProductSeeder.php index 7664dc86..4f5e4375 100644 --- a/database/seeders/Seeds/ProductSeeder.php +++ b/database/seeders/Seeds/ProductSeeder.php @@ -20,7 +20,7 @@ class ProductSeeder extends Seeder 'price' => 140, 'memory' => 64, 'disk' => 1000, - 'databases' => 1 + 'databases' => 1, ]); Product::create([ @@ -29,7 +29,7 @@ class ProductSeeder extends Seeder 'price' => 210, 'memory' => 128, 'disk' => 2000, - 'databases' => 2 + 'databases' => 2, ]); Product::create([ @@ -38,7 +38,7 @@ class ProductSeeder extends Seeder 'price' => 280, 'memory' => 256, 'disk' => 5000, - 'databases' => 5 + 'databases' => 5, ]); } } diff --git a/database/seeders/Seeds/SettingsSeeder.php b/database/seeders/Seeds/SettingsSeeder.php index 83f88da4..8639252d 100644 --- a/database/seeders/Seeds/SettingsSeeder.php +++ b/database/seeders/Seeds/SettingsSeeder.php @@ -18,544 +18,543 @@ class SettingsSeeder extends Seeder Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:INITIAL_CREDITS', ], [ - 'value' => '250', - 'type' => 'integer', - 'description' => 'The initial amount of credits the user starts with.' + 'value' => '250', + 'type' => 'integer', + 'description' => 'The initial amount of credits the user starts with.', ]); Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:INITIAL_SERVER_LIMIT', ], [ - 'value' => '1', - 'type' => 'integer', - 'description' => 'The initial server limit the user starts with.' + 'value' => '1', + 'type' => 'integer', + 'description' => 'The initial server limit the user starts with.', ]); //verify email event Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_EMAIL', ], [ - 'value' => '250', - 'type' => 'integer', - 'description' => 'Increase in credits after the user has verified their email account.' + 'value' => '250', + 'type' => 'integer', + 'description' => 'Increase in credits after the user has verified their email account.', ]); Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_EMAIL', ], [ - 'value' => '2', - 'type' => 'integer', - 'description' => 'Increase in server limit after the user has verified their email account.' + 'value' => '2', + 'type' => 'integer', + 'description' => 'Increase in server limit after the user has verified their email account.', ]); //verify discord event Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:CREDITS_REWARD_AFTER_VERIFY_DISCORD', ], [ - 'value' => '375', - 'type' => 'integer', - 'description' => 'Increase in credits after the user has verified their discord account.' + 'value' => '375', + 'type' => 'integer', + 'description' => 'Increase in credits after the user has verified their discord account.', ]); Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:SERVER_LIMIT_REWARD_AFTER_VERIFY_DISCORD', ], [ - 'value' => '2', - 'type' => 'integer', - 'description' => 'Increase in server limit after the user has verified their discord account.' + 'value' => '2', + 'type' => 'integer', + 'description' => 'Increase in server limit after the user has verified their discord account.', ]); //other Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER', ], [ - 'value' => '50', - 'type' => 'integer', - 'description' => 'The minimum amount of credits the user would need to make a server.' + 'value' => '50', + 'type' => 'integer', + 'description' => 'The minimum amount of credits the user would need to make a server.', ]); //purchasing Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE', ], [ - 'value' => '10', - 'type' => 'integer', + 'value' => '10', + 'type' => 'integer', 'description' => 'updates the users server limit to this amount (unless the user already has a higher server limit) after making a purchase with real money, set to 0 to ignore this.', ]); - //force email and discord verification Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:FORCE_EMAIL_VERIFICATION', ], [ - 'value' => 'false', - 'type' => 'boolean', - 'description' => 'Force an user to verify the email adress before creating a server / buying credits.' + 'value' => 'false', + 'type' => 'boolean', + 'description' => 'Force an user to verify the email adress before creating a server / buying credits.', ]); Settings::firstOrCreate([ 'key' => 'SETTINGS::USER:FORCE_DISCORD_VERIFICATION', ], [ - 'value' => 'false', - 'type' => 'boolean', - 'description' => 'Force an user to link an Discord Account before creating a server / buying credits.' + 'value' => 'false', + 'type' => 'boolean', + 'description' => 'Force an user to link an Discord Account before creating a server / buying credits.', ]); //disable ip check on register Settings::firstOrCreate([ 'key' => 'SETTINGS::SYSTEM:REGISTER_IP_CHECK', ], [ - 'value' => 'true', - 'type' => 'boolean', - 'description' => 'Prevent users from making multiple accounts using the same IP address' + 'value' => 'true', + 'type' => 'boolean', + 'description' => 'Prevent users from making multiple accounts using the same IP address', ]); //per_page on allocations request Settings::firstOrCreate([ 'key' => 'SETTINGS::SERVER:ALLOCATION_LIMIT', ], [ - 'value' => '200', - 'type' => 'integer', - 'description' => 'The maximum amount of allocations to pull per node for automatic deployment, if more allocations are being used than this limit is set to, no new servers can be created!' + 'value' => '200', + 'type' => 'integer', + 'description' => 'The maximum amount of allocations to pull per node for automatic deployment, if more allocations are being used than this limit is set to, no new servers can be created!', ]); //credits display name Settings::firstOrCreate([ 'key' => 'SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME', ], [ - 'value' => 'Credits', - 'type' => 'string', - 'description' => 'Set the display name of your currency :)' + 'value' => 'Credits', + 'type' => 'string', + 'description' => 'Set the display name of your currency :)', ]); //credits display name Settings::firstOrCreate([ 'key' => 'SETTINGS::SYSTEM:SERVER_CREATE_CHARGE_FIRST_HOUR', ], [ - 'value' => 'true', - 'type' => 'boolean', - 'description' => 'Charges the first hour worth of credits upon creating a server.' + 'value' => 'true', + 'type' => 'boolean', + 'description' => 'Charges the first hour worth of credits upon creating a server.', ]); //sales tax Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:SALES_TAX', + 'key' => 'SETTINGS::PAYMENTS:SALES_TAX', ], [ 'value' => '0', - 'type' => 'integer', - 'description' => 'The %-value of tax that will be added to the product price on checkout' + 'type' => 'integer', + 'description' => 'The %-value of tax that will be added to the product price on checkout', ]); //Invoices enabled Settings::firstOrCreate([ - 'key' => 'SETTINGS::INVOICE:ENABLED', + 'key' => 'SETTINGS::INVOICE:ENABLED', ], [ 'value' => 'false', - 'type' => 'boolean', - 'description' => 'Enables or disables the invoice feature for payments' + 'type' => 'boolean', + 'description' => 'Enables or disables the invoice feature for payments', ]); //Invoice company name Settings::firstOrCreate([ - 'key' => 'SETTINGS::INVOICE:COMPANY_NAME', + 'key' => 'SETTINGS::INVOICE:COMPANY_NAME', ], [ 'value' => '', - 'type' => 'string', - 'description' => 'The name of the Company on the Invoices' + 'type' => 'string', + 'description' => 'The name of the Company on the Invoices', ]); //Invoice company address Settings::firstOrCreate([ - 'key' => 'SETTINGS::INVOICE:COMPANY_ADDRESS', + 'key' => 'SETTINGS::INVOICE:COMPANY_ADDRESS', ], [ 'value' => '', - 'type' => 'string', - 'description' => 'The address of the Company on the Invoices' + 'type' => 'string', + 'description' => 'The address of the Company on the Invoices', ]); //Invoice company phone Settings::firstOrCreate([ - 'key' => 'SETTINGS::INVOICE:COMPANY_PHONE', + 'key' => 'SETTINGS::INVOICE:COMPANY_PHONE', ], [ 'value' => '', - 'type' => 'string', - 'description' => 'The phone number of the Company on the Invoices' + 'type' => 'string', + 'description' => 'The phone number of the Company on the Invoices', ]); //Invoice company mail Settings::firstOrCreate([ - 'key' => 'SETTINGS::INVOICE:COMPANY_MAIL', + 'key' => 'SETTINGS::INVOICE:COMPANY_MAIL', ], [ 'value' => '', - 'type' => 'string', - 'description' => 'The email address of the Company on the Invoices' + 'type' => 'string', + 'description' => 'The email address of the Company on the Invoices', ]); //Invoice VAT Settings::firstOrCreate([ - 'key' => 'SETTINGS::INVOICE:COMPANY_VAT', + 'key' => 'SETTINGS::INVOICE:COMPANY_VAT', ], [ 'value' => '', - 'type' => 'string', - 'description' => 'The VAT-Number of the Company on the Invoices' + 'type' => 'string', + 'description' => 'The VAT-Number of the Company on the Invoices', ]); //Invoice Website Settings::firstOrCreate([ - 'key' => 'SETTINGS::INVOICE:COMPANY_WEBSITE', + 'key' => 'SETTINGS::INVOICE:COMPANY_WEBSITE', ], [ 'value' => '', - 'type' => 'string', - 'description' => 'The Website of the Company on the Invoices' + 'type' => 'string', + 'description' => 'The Website of the Company on the Invoices', ]); //Invoice Website Settings::firstOrCreate([ - 'key' => 'SETTINGS::INVOICE:PREFIX', + 'key' => 'SETTINGS::INVOICE:PREFIX', ], [ 'value' => 'INV', - 'type' => 'string', - 'description' => 'The invoice prefix' + 'type' => 'string', + 'description' => 'The invoice prefix', ]); //Locale Settings::firstOrCreate([ - 'key' => 'SETTINGS::LOCALE:DEFAULT', + 'key' => 'SETTINGS::LOCALE:DEFAULT', ], [ 'value' => 'en', - 'type' => 'string', - 'description' => 'The default Language the dashboard will be shown in' + 'type' => 'string', + 'description' => 'The default Language the dashboard will be shown in', ]); //Dynamic locale Settings::firstOrCreate([ - 'key' => 'SETTINGS::LOCALE:DYNAMIC', + 'key' => 'SETTINGS::LOCALE:DYNAMIC', ], [ 'value' => 'false', - 'type' => 'boolean', - 'description' => 'If this is true, the Language will change to the Clients browserlanguage or default.' + 'type' => 'boolean', + 'description' => 'If this is true, the Language will change to the Clients browserlanguage or default.', ]); //User can change Locale Settings::firstOrCreate([ - 'key' => 'SETTINGS::LOCALE:CLIENTS_CAN_CHANGE', + 'key' => 'SETTINGS::LOCALE:CLIENTS_CAN_CHANGE', ], [ 'value' => 'false', - 'type' => 'boolean', - 'description' => 'If this is true, the clients will be able to change their Locale.' + 'type' => 'boolean', + 'description' => 'If this is true, the clients will be able to change their Locale.', ]); //Locale Settings::firstOrCreate([ - 'key' => 'SETTINGS::LOCALE:AVAILABLE', + 'key' => 'SETTINGS::LOCALE:AVAILABLE', ], [ 'value' => '', - 'type' => 'string', - 'description' => 'The available languages' + 'type' => 'string', + 'description' => 'The available languages', ]); //Locale Settings::firstOrCreate([ - 'key' => 'SETTINGS::LOCALE:DATATABLES', + 'key' => 'SETTINGS::LOCALE:DATATABLES', ], [ 'value' => 'en-gb', - 'type' => 'string', - 'description' => 'The Language of the Datatables. Grab the Language-Codes from here https://datatables.net/plug-ins/i18n/' + 'type' => 'string', + 'description' => 'The Language of the Datatables. Grab the Language-Codes from here https://datatables.net/plug-ins/i18n/', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:PAYPAL:SECRET', + 'key' => 'SETTINGS::PAYMENTS:PAYPAL:SECRET', ], [ 'value' => env('PAYPAL_SECRET', ''), - 'type' => 'string', - 'description' => 'Your PayPal Secret-Key ( https://developer.paypal.com/docs/integration/direct/rest/)' + 'type' => 'string', + 'description' => 'Your PayPal Secret-Key ( https://developer.paypal.com/docs/integration/direct/rest/)', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID', + 'key' => 'SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID', ], [ 'value' => env('PAYPAL_CLIENT_ID', ''), - 'type' => 'string', - 'description' => 'Your PayPal Client_ID' + 'type' => 'string', + 'description' => 'Your PayPal Client_ID', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET', + 'key' => 'SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET', ], [ 'value' => env('PAYPAL_SANDBOX_SECRET', ''), - 'type' => 'string', - 'description' => 'Your PayPal SANDBOX Secret-Key used for testing ' + 'type' => 'string', + 'description' => 'Your PayPal SANDBOX Secret-Key used for testing ', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID', + 'key' => 'SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID', ], [ 'value' => env('PAYPAL_SANDBOX_CLIENT_ID', ''), - 'type' => 'string', - 'description' => 'Your PayPal SANDBOX Client-ID used for testing ' + 'type' => 'string', + 'description' => 'Your PayPal SANDBOX Client-ID used for testing ', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:STRIPE:SECRET', + 'key' => 'SETTINGS::PAYMENTS:STRIPE:SECRET', ], [ 'value' => env('STRIPE_SECRET', ''), - 'type' => 'string', - 'description' => 'Your Stripe Secret-Key ( https://dashboard.stripe.com/account/apikeys )' + 'type' => 'string', + 'description' => 'Your Stripe Secret-Key ( https://dashboard.stripe.com/account/apikeys )', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET', + 'key' => 'SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET', ], [ 'value' => env('STRIPE_ENDPOINT_SECRET', ''), - 'type' => 'string', - 'description' => 'Your Stripe endpoint secret-key' + 'type' => 'string', + 'description' => 'Your Stripe endpoint secret-key', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:STRIPE:TEST_SECRET', + 'key' => 'SETTINGS::PAYMENTS:STRIPE:TEST_SECRET', ], [ 'value' => env('STRIPE_TEST_SECRET', ''), - 'type' => 'string', - 'description' => 'Your Stripe test secret-key' + 'type' => 'string', + 'description' => 'Your Stripe test secret-key', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET', + 'key' => 'SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET', ], [ 'value' => env('STRIPE_ENDPOINT_TEST_SECRET', ''), - 'type' => 'string', - 'description' => 'Your Stripe endpoint test secret-key' + 'type' => 'string', + 'description' => 'Your Stripe endpoint test secret-key', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::PAYMENTS:STRIPE:METHODS', + 'key' => 'SETTINGS::PAYMENTS:STRIPE:METHODS', ], [ 'value' => env('STRIPE_METHODS', 'card,sepa_debit'), - 'type' => 'string', - 'description' => 'Comma seperated list of payment methods that are enabled (https://stripe.com/docs/payments/payment-methods/integration-options)' + 'type' => 'string', + 'description' => 'Comma seperated list of payment methods that are enabled (https://stripe.com/docs/payments/payment-methods/integration-options)', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::DISCORD:CLIENT_ID', + 'key' => 'SETTINGS::DISCORD:CLIENT_ID', ], [ 'value' => env('DISCORD_CLIENT_ID', ''), - 'type' => 'string', - 'description' => 'Discord API Credentials - https://discordapp.com/developers/applications/' + 'type' => 'string', + 'description' => 'Discord API Credentials - https://discordapp.com/developers/applications/', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::DISCORD:CLIENT_SECRET', + 'key' => 'SETTINGS::DISCORD:CLIENT_SECRET', ], [ 'value' => env('DISCORD_CLIENT_SECRET', ''), - 'type' => 'string', - 'description' => 'Discord API Credentials - https://discordapp.com/developers/applications/' + 'type' => 'string', + 'description' => 'Discord API Credentials - https://discordapp.com/developers/applications/', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::DISCORD:BOT_TOKEN', + 'key' => 'SETTINGS::DISCORD:BOT_TOKEN', ], [ - 'value' => env('DISCORD_BOT_TOKEN', ''), - 'type' => 'string', - 'description' => 'Discord API Credentials - https://discordapp.com/developers/applications/' + 'value' => env('DISCORD_BOT_TOKEN', ''), + 'type' => 'string', + 'description' => 'Discord API Credentials - https://discordapp.com/developers/applications/', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::DISCORD:GUILD_ID', + 'key' => 'SETTINGS::DISCORD:GUILD_ID', ], [ - 'value' => env('DISCORD_GUILD_ID', ''), - 'type' => 'string', - 'description' => 'Discord API Credentials - https://discordapp.com/developers/applications/' + 'value' => env('DISCORD_GUILD_ID', ''), + 'type' => 'string', + 'description' => 'Discord API Credentials - https://discordapp.com/developers/applications/', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::DISCORD:ROLE_ID', + 'key' => 'SETTINGS::DISCORD:ROLE_ID', ], [ 'value' => env('DISCORD_ROLE_ID', ''), - 'type' => 'string', - 'description' => 'Discord role that will be assigned to users when they register' + 'type' => 'string', + 'description' => 'Discord role that will be assigned to users when they register', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::DISCORD:INVITE_URL', + 'key' => 'SETTINGS::DISCORD:INVITE_URL', ], [ 'value' => env('DISCORD_INVITE_URL', ''), - 'type' => 'string', - 'description' => 'The invite URL to your Discord Server' + 'type' => 'string', + 'description' => 'The invite URL to your Discord Server', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:PTERODACTYL:TOKEN', + 'key' => 'SETTINGS::SYSTEM:PTERODACTYL:TOKEN', ], [ 'value' => env('PTERODACTYL_TOKEN', ''), - 'type' => 'string', - 'description' => 'Admin API Token from Pterodactyl Panel - necessary for the Panel to work. The Key needs all read&write permissions!' + 'type' => 'string', + 'description' => 'Admin API Token from Pterodactyl Panel - necessary for the Panel to work. The Key needs all read&write permissions!', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:PTERODACTYL:URL', + 'key' => 'SETTINGS::SYSTEM:PTERODACTYL:URL', ], [ 'value' => env('PTERODACTYL_URL', ''), - 'type' => 'string', - 'description' => 'The URL to your Pterodactyl Panel. Must not end with a / ' + 'type' => 'string', + 'description' => 'The URL to your Pterodactyl Panel. Must not end with a / ', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT', + 'key' => 'SETTINGS::SYSTEM:PTERODACTYL:PER_PAGE_LIMIT', ], [ 'value' => 200, - 'type' => 'integer', - 'description' => 'The Pterodactyl API perPage limit. It is necessary to set it higher than your server count.' + 'type' => 'integer', + 'description' => 'The Pterodactyl API perPage limit. It is necessary to set it higher than your server count.', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MISC:PHPMYADMIN:URL', + 'key' => 'SETTINGS::MISC:PHPMYADMIN:URL', ], [ 'value' => env('PHPMYADMIN_URL', ''), - 'type' => 'string', - 'description' => 'The URL to your PHPMYADMIN Panel. Must not end with a /, remove to remove database button' + 'type' => 'string', + 'description' => 'The URL to your PHPMYADMIN Panel. Must not end with a /, remove to remove database button', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::RECAPTCHA:SITE_KEY', + 'key' => 'SETTINGS::RECAPTCHA:SITE_KEY', ], [ 'value' => env('RECAPTCHA_SITE_KEY', '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'), - 'type' => 'string', - 'description' => 'Google Recaptcha API Credentials - https://www.google.com/recaptcha/admin - reCaptcha V2 (not v3)' + 'type' => 'string', + 'description' => 'Google Recaptcha API Credentials - https://www.google.com/recaptcha/admin - reCaptcha V2 (not v3)', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::RECAPTCHA:SECRET_KEY', + 'key' => 'SETTINGS::RECAPTCHA:SECRET_KEY', ], [ 'value' => env('RECAPTCHA_SECRET_KEY', '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'), - 'type' => 'string', - 'description' => 'Google Recaptcha API Credentials - https://www.google.com/recaptcha/admin - reCaptcha V2 (not v3)' + 'type' => 'string', + 'description' => 'Google Recaptcha API Credentials - https://www.google.com/recaptcha/admin - reCaptcha V2 (not v3)', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::RECAPTCHA:ENABLED', + 'key' => 'SETTINGS::RECAPTCHA:ENABLED', ], [ 'value' => 'true', - 'type' => 'boolean', - 'description' => 'Enables or disables the ReCaptcha feature on the registration/login page' + 'type' => 'boolean', + 'description' => 'Enables or disables the ReCaptcha feature on the registration/login page', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MAIL:MAILER', + 'key' => 'SETTINGS::MAIL:MAILER', ], [ 'value' => env('MAIL_MAILER', 'smtp'), - 'type' => 'string', - 'description' => 'Selected Mailer (smtp, mailgun, sendgrid, mailtrap)' + 'type' => 'string', + 'description' => 'Selected Mailer (smtp, mailgun, sendgrid, mailtrap)', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MAIL:HOST', + 'key' => 'SETTINGS::MAIL:HOST', ], [ 'value' => env('MAIL_HOST', 'localhost'), - 'type' => 'string', - 'description' => 'Mailer Host Adress' + 'type' => 'string', + 'description' => 'Mailer Host Adress', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MAIL:PORT', + 'key' => 'SETTINGS::MAIL:PORT', ], [ - 'value' => env('MAIL_PORT', '25'), - 'type' => 'string', - 'description' => 'Mailer Server Port' + 'value' => env('MAIL_PORT', '25'), + 'type' => 'string', + 'description' => 'Mailer Server Port', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MAIL:USERNAME', + 'key' => 'SETTINGS::MAIL:USERNAME', ], [ - 'value' => env('MAIL_USERNAME', ''), - 'type' => 'string', - 'description' => 'Mailer Username' + 'value' => env('MAIL_USERNAME', ''), + 'type' => 'string', + 'description' => 'Mailer Username', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MAIL:PASSWORD', + 'key' => 'SETTINGS::MAIL:PASSWORD', ], [ - 'value' => env('MAIL_PASSWORD', ''), - 'type' => 'string', - 'description' => 'Mailer Password' + 'value' => env('MAIL_PASSWORD', ''), + 'type' => 'string', + 'description' => 'Mailer Password', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MAIL:ENCRYPTION', + 'key' => 'SETTINGS::MAIL:ENCRYPTION', ], [ - 'value' => env('MAIL_ENCRYPTION', 'tls'), - 'type' => 'string', - 'description' => 'Mailer Encryption (tls, ssl)' + 'value' => env('MAIL_ENCRYPTION', 'tls'), + 'type' => 'string', + 'description' => 'Mailer Encryption (tls, ssl)', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MAIL:FROM_ADDRESS', + 'key' => 'SETTINGS::MAIL:FROM_ADDRESS', ], [ - 'value' => env('MAIL_FROM_ADDRESS', ''), - 'type' => 'string', - 'description' => 'Mailer From Address' + 'value' => env('MAIL_FROM_ADDRESS', ''), + 'type' => 'string', + 'description' => 'Mailer From Address', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::MAIL:FROM_NAME', + 'key' => 'SETTINGS::MAIL:FROM_NAME', ], [ 'value' => env('APP_NAME', 'Controlpanel'), - 'type' => 'string', - 'description' => 'Mailer From Name' + 'type' => 'string', + 'description' => 'Mailer From Name', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::REFERRAL::ENABLED', + 'key' => 'SETTINGS::REFERRAL::ENABLED', ], [ - 'value' =>"true", - 'type' => 'string', - 'description' => 'Enable or disable the referral system' + 'value' => 'true', + 'type' => 'string', + 'description' => 'Enable or disable the referral system', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION', + 'key' => 'SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION', ], [ - 'value' =>"false", - 'type' => 'string', - 'description' => 'Whether referrals get percentage commission only on first purchase or on every purchase' + 'value' => 'false', + 'type' => 'string', + 'description' => 'Whether referrals get percentage commission only on first purchase or on every purchase', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::REFERRAL::REWARD', + 'key' => 'SETTINGS::REFERRAL::REWARD', ], [ - 'value' =>100, - 'type' => 'integer', - 'description' => 'Credit reward a user should receive when a user registers with his referral code' + 'value' => 100, + 'type' => 'integer', + 'description' => 'Credit reward a user should receive when a user registers with his referral code', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::REFERRAL::ALLOWED', + 'key' => 'SETTINGS::REFERRAL::ALLOWED', ], [ - 'value' =>"client", - 'type' => 'string', - 'description' => 'Who should be allowed to to use the referral code. all/client' + 'value' => 'client', + 'type' => 'string', + 'description' => 'Who should be allowed to to use the referral code. all/client', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::REFERRAL:MODE', + 'key' => 'SETTINGS::REFERRAL:MODE', ], [ - 'value' =>"sign-up", - 'type' => 'string', - 'description' => 'Whether referrals get Credits on User-Registration or if a User buys credits' + 'value' => 'sign-up', + 'type' => 'string', + 'description' => 'Whether referrals get Credits on User-Registration or if a User buys credits', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::REFERRAL:PERCENTAGE', + 'key' => 'SETTINGS::REFERRAL:PERCENTAGE', ], [ - 'value' =>100, - 'type' => 'integer', - 'description' => 'The Percentage Value a referred user gets' + 'value' => 100, + 'type' => 'integer', + 'description' => 'The Percentage Value a referred user gets', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:PTERODACTYL:ADMIN_USER_TOKEN', + 'key' => 'SETTINGS::SYSTEM:PTERODACTYL:ADMIN_USER_TOKEN', ], [ - 'value' =>"", - 'type' => 'string', - 'description' => 'The Client API Key of an Pterodactyl Admin Account' + 'value' => '', + 'type' => 'string', + 'description' => 'The Client API Key of an Pterodactyl Admin Account', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:ENABLE_UPGRADE', + 'key' => 'SETTINGS::SYSTEM:ENABLE_UPGRADE', ], [ - 'value' => "false", - 'type' => 'boolean', - 'description' => 'Enables the updgrade/downgrade feature for servers' + 'value' => 'false', + 'type' => 'boolean', + 'description' => 'Enables the updgrade/downgrade feature for servers', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS', + 'key' => 'SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS', ], [ - 'value' => "true", - 'type' => 'boolean', - 'description' => 'Enable/disable the creation of new servers' + 'value' => 'true', + 'type' => 'boolean', + 'description' => 'Enable/disable the creation of new servers', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:CREATION_OF_NEW_USERS', + 'key' => 'SETTINGS::SYSTEM:CREATION_OF_NEW_USERS', ], [ - 'value' => "false", - 'type' => 'boolean', - 'description' => 'Enable/disable the creation of new users' + 'value' => 'false', + 'type' => 'boolean', + 'description' => 'Enable/disable the creation of new users', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:SHOW_IMPRINT', + 'key' => 'SETTINGS::SYSTEM:SHOW_IMPRINT', ], [ - 'value' => "true", - 'type' => 'boolean', - 'description' => 'Enable/disable imprint in footer' + 'value' => 'true', + 'type' => 'boolean', + 'description' => 'Enable/disable imprint in footer', ]); Settings::firstOrCreate([ - 'key' => 'SETTINGS::SYSTEM:SHOW_PRIVACY', + 'key' => 'SETTINGS::SYSTEM:SHOW_PRIVACY', ], [ - 'value' => "true", - 'type' => 'boolean', - 'description' => 'Enable/disable privacy policy in footer' + 'value' => 'true', + 'type' => 'boolean', + 'description' => 'Enable/disable privacy policy in footer', ]); } } diff --git a/database/seeders/Seeds/UsefulLinksSeeder.php b/database/seeders/Seeds/UsefulLinksSeeder.php index e5db8e39..57f45a4a 100644 --- a/database/seeders/Seeds/UsefulLinksSeeder.php +++ b/database/seeders/Seeds/UsefulLinksSeeder.php @@ -18,19 +18,19 @@ class UsefulLinksSeeder extends Seeder 'icon' => 'fas fa-egg', 'title' => 'Pterodactyl Panel', 'link' => env('PTERODACTYL_URL', 'http://localhost'), - 'description' => 'Use your servers on our pterodactyl panel (You can use the same login details)' + 'description' => 'Use your servers on our pterodactyl panel (You can use the same login details)', ]); UsefulLink::create([ 'icon' => 'fas fa-database', 'title' => 'phpMyAdmin', 'link' => env('PHPMYADMIN_URL', 'http://localhost'), - 'description' => 'View your database online using phpMyAdmin' + 'description' => 'View your database online using phpMyAdmin', ]); UsefulLink::create([ 'icon' => 'fab fa-discord', 'title' => 'Discord', - 'link' => env('DISCORD_INVITE_URL' , 'https://discord.gg/4Y6HjD2uyU'), - 'description' => 'Need a helping hand? Want to chat? Got any questions? Join our discord!' + 'link' => env('DISCORD_INVITE_URL', 'https://discord.gg/4Y6HjD2uyU'), + 'description' => 'Need a helping hand? Want to chat? Got any questions? Join our discord!', ]); } } diff --git a/database/seeders/Seeds/UserSeeder.php b/database/seeders/Seeds/UserSeeder.php index d96a6669..ed407b3b 100644 --- a/database/seeders/Seeds/UserSeeder.php +++ b/database/seeders/Seeds/UserSeeder.php @@ -17,7 +17,7 @@ class UserSeeder extends Seeder { User::factory() ->count(10) - ->has(Server::factory()->count(rand(1,3)) , 'servers') + ->has(Server::factory()->count(rand(1, 3)), 'servers') ->create(); } } diff --git a/public/install/dotenv.php b/public/install/dotenv.php index 01a94658..40455ad7 100644 --- a/public/install/dotenv.php +++ b/public/install/dotenv.php @@ -11,10 +11,9 @@ class DotEnv */ protected $path; - public function __construct(string $path) { - if (!file_exists($path)) { + if (! file_exists($path)) { throw new \InvalidArgumentException(sprintf('%s does not exist', $path)); } $this->path = $path; @@ -22,22 +21,21 @@ class DotEnv public function load(): void { - if (!is_readable($this->path)) { + if (! is_readable($this->path)) { throw new \RuntimeException(sprintf('%s file is not readable', $this->path)); } $lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach ($lines as $line) { - if (strpos(trim($line), '#') === 0) { continue; } - list($name, $value) = explode('=', $line, 2); + [$name, $value] = explode('=', $line, 2); $name = trim($name); $value = trim($value); - if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) { + if (! array_key_exists($name, $_SERVER) && ! array_key_exists($name, $_ENV)) { putenv(sprintf('%s=%s', $name, $value)); $_ENV[$name] = $value; $_SERVER[$name] = $value; @@ -45,4 +43,3 @@ class DotEnv } } } - diff --git a/public/install/forms.php b/public/install/forms.php index bb0bdd7d..980ee3ce 100644 --- a/public/install/forms.php +++ b/public/install/forms.php @@ -9,89 +9,77 @@ require 'phpmailer/Exception.php'; require 'phpmailer/PHPMailer.php'; require 'phpmailer/SMTP.php'; +(new DotEnv(dirname(__FILE__, 3).'/.env'))->load(); -(new DotEnv(dirname(__FILE__, 3) . "/.env"))->load(); - -include("functions.php"); +include 'functions.php'; if (isset($_POST['checkDB'])) { - $values = [ //SETTINGS::VALUE => REQUEST-VALUE (coming from the html-form) - "DB_HOST" => "databasehost", - "DB_DATABASE" => "database", - "DB_USERNAME" => "databaseuser", - "DB_PASSWORD" => "databaseuserpass", - "DB_PORT" => "databaseport", - "DB_CONNECTION" => "databasedriver" + 'DB_HOST' => 'databasehost', + 'DB_DATABASE' => 'database', + 'DB_USERNAME' => 'databaseuser', + 'DB_PASSWORD' => 'databaseuserpass', + 'DB_PORT' => 'databaseport', + 'DB_CONNECTION' => 'databasedriver', ]; - - $db = new mysqli($_POST["databasehost"], $_POST["databaseuser"], $_POST["databaseuserpass"], $_POST["database"], $_POST["databaseport"]); + $db = new mysqli($_POST['databasehost'], $_POST['databaseuser'], $_POST['databaseuserpass'], $_POST['database'], $_POST['databaseport']); if ($db->connect_error) { wh_log($db->connect_error); - header("LOCATION: index.php?step=2&message=Could not connect to the Database"); - die(); + header('LOCATION: index.php?step=2&message=Could not connect to the Database'); + exit(); } foreach ($values as $key => $value) { $param = $_POST[$value]; - # if ($key == "DB_PASSWORD") { - # $param = '"' . $_POST[$value] . '"'; - # } + // if ($key == "DB_PASSWORD") { + // $param = '"' . $_POST[$value] . '"'; + // } setEnvironmentValue($key, $param); } - header("LOCATION: index.php?step=2.5"); - + header('LOCATION: index.php?step=2.5'); } - if (isset($_POST['checkGeneral'])) { - - - $appname = '"' . $_POST['name'] . '"'; + $appname = '"'.$_POST['name'].'"'; $appurl = $_POST['url']; - if (substr($appurl, -1) === "/") { - $appurl = substr_replace($appurl, "", -1); + if (substr($appurl, -1) === '/') { + $appurl = substr_replace($appurl, '', -1); } + setEnvironmentValue('APP_NAME', $appname); + setEnvironmentValue('APP_URL', $appurl); - setEnvironmentValue("APP_NAME", $appname); - setEnvironmentValue("APP_URL", $appurl); - - header("LOCATION: index.php?step=4"); - + header('LOCATION: index.php?step=4'); } if (isset($_POST['feedDB'])) { - $logs = ""; + $logs = ''; - #$logs .= run_console(putenv('COMPOSER_HOME=' . dirname(__FILE__, 3) . '/vendor/bin/composer')); - #$logs .= run_console('composer install --no-dev --optimize-autoloader'); + //$logs .= run_console(putenv('COMPOSER_HOME=' . dirname(__FILE__, 3) . '/vendor/bin/composer')); + //$logs .= run_console('composer install --no-dev --optimize-autoloader'); $logs .= run_console('php artisan migrate --seed --force'); $logs .= run_console('php artisan db:seed --class=ExampleItemsSeeder --force'); - if (strpos(getEnvironmentValue("APP_KEY"), 'base64') === false) { + if (strpos(getEnvironmentValue('APP_KEY'), 'base64') === false) { $logs .= run_console('php artisan key:generate --force'); - }else{ - $logs .= "Key already exists. Skipping\n"; + } else { + $logs .= "Key already exists. Skipping\n"; } $logs .= run_console('php artisan storage:link'); wh_log($logs); - if (strpos(getEnvironmentValue("APP_KEY"), 'base64') !== false) { - header("LOCATION: index.php?step=3"); + if (strpos(getEnvironmentValue('APP_KEY'), 'base64') !== false) { + header('LOCATION: index.php?step=3'); } else { - header("LOCATION: index.php?step=2.5&message=There was an error. Please check the .txt file in /var/www/controlpanel/public/install/logs !"); + header('LOCATION: index.php?step=2.5&message=There was an error. Please check the .txt file in /var/www/controlpanel/public/install/logs !'); } - - } if (isset($_POST['checkSMTP'])) { - try { $mail = new PHPMailer(true); @@ -111,39 +99,36 @@ if (isset($_POST['checkSMTP'])) { // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'It Worked!'; - $mail->Body = "Your E-Mail Settings are correct!"; - + $mail->Body = 'Your E-Mail Settings are correct!'; $mail->send(); } catch (Exception $e) { - header("LOCATION: index.php?step=4&message=Something wasnt right when sending the E-Mail!"); - die(); + header('LOCATION: index.php?step=4&message=Something wasnt right when sending the E-Mail!'); + exit(); } - $db = new mysqli(getEnvironmentValue("DB_HOST"), getEnvironmentValue("DB_USERNAME"), getEnvironmentValue("DB_PASSWORD"), getEnvironmentValue("DB_DATABASE"), getEnvironmentValue("DB_PORT")); + $db = new mysqli(getEnvironmentValue('DB_HOST'), getEnvironmentValue('DB_USERNAME'), getEnvironmentValue('DB_PASSWORD'), getEnvironmentValue('DB_DATABASE'), getEnvironmentValue('DB_PORT')); if ($db->connect_error) { wh_log($db->connect_error); - header("LOCATION: index.php?step=4&message=Could not connect to the Database: "); - die(); + header('LOCATION: index.php?step=4&message=Could not connect to the Database: '); + exit(); } $values = [ - "SETTINGS::MAIL:MAILER" => $_POST["method"], - "SETTINGS::MAIL:HOST" => $_POST["host"], - "SETTINGS::MAIL:PORT" => $_POST["port"], - "SETTINGS::MAIL:USERNAME" => $_POST["user"], - "SETTINGS::MAIL:PASSWORD" => $_POST["pass"], - "SETTINGS::MAIL:ENCRYPTION" => $_POST["encryption"], - "SETTINGS::MAIL:FROM_ADDRESS" => $_POST["user"] + 'SETTINGS::MAIL:MAILER' => $_POST['method'], + 'SETTINGS::MAIL:HOST' => $_POST['host'], + 'SETTINGS::MAIL:PORT' => $_POST['port'], + 'SETTINGS::MAIL:USERNAME' => $_POST['user'], + 'SETTINGS::MAIL:PASSWORD' => $_POST['pass'], + 'SETTINGS::MAIL:ENCRYPTION' => $_POST['encryption'], + 'SETTINGS::MAIL:FROM_ADDRESS' => $_POST['user'], ]; foreach ($values as $key => $value) { - $query = "UPDATE `" . getEnvironmentValue("DB_DATABASE") . "`.`settings` SET `value` = '$value' WHERE (`key` = '$key')"; + $query = 'UPDATE `'.getEnvironmentValue('DB_DATABASE')."`.`settings` SET `value` = '$value' WHERE (`key` = '$key')"; $db->query($query); } - header("LOCATION: index.php?step=5"); - - + header('LOCATION: index.php?step=5'); } if (isset($_POST['checkPtero'])) { @@ -151,163 +136,143 @@ if (isset($_POST['checkPtero'])) { $key = $_POST['key']; $clientkey = $_POST['clientkey']; - if (substr($url, -1) === "/") { - $url = substr_replace($url, "", -1); + if (substr($url, -1) === '/') { + $url = substr_replace($url, '', -1); } - $callpteroURL = $url . "/api/client/account"; + $callpteroURL = $url.'/api/client/account'; $call = curl_init(); curl_setopt($call, CURLOPT_URL, $callpteroURL); curl_setopt($call, CURLOPT_RETURNTRANSFER, true); - curl_setopt($call, CURLOPT_HTTPHEADER, array( - "Accept: application/json", - "Content-Type: application/json", - "Authorization: Bearer " . $clientkey - )); + curl_setopt($call, CURLOPT_HTTPHEADER, [ + 'Accept: application/json', + 'Content-Type: application/json', + 'Authorization: Bearer '.$clientkey, + ]); $callresponse = curl_exec($call); $callresult = json_decode($callresponse, true); curl_close($call); // Close the connection - - - - $pteroURL = $url . "/api/application/users"; + $pteroURL = $url.'/api/application/users'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $pteroURL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( - "Accept: application/json", - "Content-Type: application/json", - "Authorization: Bearer " . $key - )); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Accept: application/json', + 'Content-Type: application/json', + 'Authorization: Bearer '.$key, + ]); $response = curl_exec($ch); $result = json_decode($response, true); curl_close($ch); // Close the connection - - if (!is_array($result) or in_array($result["errors"][0]["code"], $result)) { - header("LOCATION: index.php?step=5&message=Couldnt connect to Pterodactyl. Make sure your API key has all read and write permissions!"); - wh_log("API CALL ERROR: ".$result["errors"][0]["code"]); - die(); - }elseif (!is_array($callresult) or in_array($result["errors"][0]["code"], $result) or $callresult["attributes"]["admin"] == false) { - header("LOCATION: index.php?step=5&message=Your ClientAPI Key is wrong or the account is not an admin!"); - wh_log("API CALL ERROR: ".$result["errors"][0]["code"]); - die(); + if (! is_array($result) or in_array($result['errors'][0]['code'], $result)) { + header('LOCATION: index.php?step=5&message=Couldnt connect to Pterodactyl. Make sure your API key has all read and write permissions!'); + wh_log('API CALL ERROR: '.$result['errors'][0]['code']); + exit(); + } elseif (! is_array($callresult) or in_array($result['errors'][0]['code'], $result) or $callresult['attributes']['admin'] == false) { + header('LOCATION: index.php?step=5&message=Your ClientAPI Key is wrong or the account is not an admin!'); + wh_log('API CALL ERROR: '.$result['errors'][0]['code']); + exit(); } else { + $query1 = 'UPDATE `'.getEnvironmentValue('DB_DATABASE')."`.`settings` SET `value` = '$url' WHERE (`key` = 'SETTINGS::SYSTEM:PTERODACTYL:URL')"; + $query2 = 'UPDATE `'.getEnvironmentValue('DB_DATABASE')."`.`settings` SET `value` = '$key' WHERE (`key` = 'SETTINGS::SYSTEM:PTERODACTYL:TOKEN')"; + $query3 = 'UPDATE `'.getEnvironmentValue('DB_DATABASE')."`.`settings` SET `value` = '$clientkey' WHERE (`key` = 'SETTINGS::SYSTEM:PTERODACTYL:ADMIN_USER_TOKEN')"; - $query1 = "UPDATE `" . getEnvironmentValue("DB_DATABASE") . "`.`settings` SET `value` = '$url' WHERE (`key` = 'SETTINGS::SYSTEM:PTERODACTYL:URL')"; - $query2 = "UPDATE `" . getEnvironmentValue("DB_DATABASE") . "`.`settings` SET `value` = '$key' WHERE (`key` = 'SETTINGS::SYSTEM:PTERODACTYL:TOKEN')"; - $query3 = "UPDATE `" . getEnvironmentValue("DB_DATABASE") . "`.`settings` SET `value` = '$clientkey' WHERE (`key` = 'SETTINGS::SYSTEM:PTERODACTYL:ADMIN_USER_TOKEN')"; - - - $db = new mysqli(getEnvironmentValue("DB_HOST"), getEnvironmentValue("DB_USERNAME"), getEnvironmentValue("DB_PASSWORD"), getEnvironmentValue("DB_DATABASE"), getEnvironmentValue("DB_PORT")); + $db = new mysqli(getEnvironmentValue('DB_HOST'), getEnvironmentValue('DB_USERNAME'), getEnvironmentValue('DB_PASSWORD'), getEnvironmentValue('DB_DATABASE'), getEnvironmentValue('DB_PORT')); if ($db->connect_error) { wh_log($db->connect_error); - header("LOCATION: index.php?step=5&message=Could not connect to the Database"); - die(); + header('LOCATION: index.php?step=5&message=Could not connect to the Database'); + exit(); } if ($db->query($query1) && $db->query($query2) && $db->query($query3)) { - header("LOCATION: index.php?step=6"); + header('LOCATION: index.php?step=6'); } else { wh_log($db->error); - header("LOCATION: index.php?step=5&message=Something went wrong when communicating with the Database!"); + header('LOCATION: index.php?step=5&message=Something went wrong when communicating with the Database!'); } } - - } if (isset($_POST['createUser'])) { - $db = new mysqli(getEnvironmentValue("DB_HOST"), getEnvironmentValue("DB_USERNAME"), getEnvironmentValue("DB_PASSWORD"), getEnvironmentValue("DB_DATABASE"), getEnvironmentValue("DB_PORT")); + $db = new mysqli(getEnvironmentValue('DB_HOST'), getEnvironmentValue('DB_USERNAME'), getEnvironmentValue('DB_PASSWORD'), getEnvironmentValue('DB_DATABASE'), getEnvironmentValue('DB_PORT')); if ($db->connect_error) { wh_log($db->connect_error); - header("LOCATION: index.php?step=6&message=Could not connect to the Database"); - die(); + header('LOCATION: index.php?step=6&message=Could not connect to the Database'); + exit(); } - $pteroID = $_POST['pteroID']; $pass = $_POST['pass']; $repass = $_POST['repass']; - $key = $db->query("SELECT `value` FROM `" . getEnvironmentValue("DB_DATABASE") . "`.`settings` WHERE `key` = 'SETTINGS::SYSTEM:PTERODACTYL:TOKEN'")->fetch_assoc(); - $pterobaseurl = $db->query("SELECT `value` FROM `" . getEnvironmentValue("DB_DATABASE") . "`.`settings` WHERE `key` = 'SETTINGS::SYSTEM:PTERODACTYL:URL'")->fetch_assoc(); + $key = $db->query('SELECT `value` FROM `'.getEnvironmentValue('DB_DATABASE')."`.`settings` WHERE `key` = 'SETTINGS::SYSTEM:PTERODACTYL:TOKEN'")->fetch_assoc(); + $pterobaseurl = $db->query('SELECT `value` FROM `'.getEnvironmentValue('DB_DATABASE')."`.`settings` WHERE `key` = 'SETTINGS::SYSTEM:PTERODACTYL:URL'")->fetch_assoc(); - - - $pteroURL = $pterobaseurl["value"] . "/api/application/users/" . $pteroID; + $pteroURL = $pterobaseurl['value'].'/api/application/users/'.$pteroID; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $pteroURL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( - "Accept: application/json", - "Content-Type: application/json", - "Authorization: Bearer " . $key["value"] - )); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Accept: application/json', + 'Content-Type: application/json', + 'Authorization: Bearer '.$key['value'], + ]); $response = curl_exec($ch); $result = json_decode($response, true); curl_close($ch); // Close the connection - if (!$result["attributes"]["email"]) { - header("LOCATION: index.php?step=6&message=Could not find the user with pterodactyl ID ".$pteroID); - die(); + if (! $result['attributes']['email']) { + header('LOCATION: index.php?step=6&message=Could not find the user with pterodactyl ID '.$pteroID); + exit(); } if ($pass !== $repass) { - header("LOCATION: index.php?step=6&message=The Passwords did not match!"); - die(); + header('LOCATION: index.php?step=6&message=The Passwords did not match!'); + exit(); } - $mail = $result["attributes"]["email"]; - $name = $result["attributes"]["username"]; + $mail = $result['attributes']['email']; + $name = $result['attributes']['username']; $pass = password_hash($pass, PASSWORD_DEFAULT); - $pteroURL = $pterobaseurl["value"] . "/api/application/users/" . $pteroID; + $pteroURL = $pterobaseurl['value'].'/api/application/users/'.$pteroID; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $pteroURL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( - "Accept: application/json", - "Content-Type: application/json", - "Authorization: Bearer " . $key["value"] - )); - curl_setopt($ch, CURLOPT_POSTFIELDS, array( - "email" => $mail, - "username" => $name, - "first_name" => $name, - "last_name" => $name, - "password" => $pass - )); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Accept: application/json', + 'Content-Type: application/json', + 'Authorization: Bearer '.$key['value'], + ]); + curl_setopt($ch, CURLOPT_POSTFIELDS, [ + 'email' => $mail, + 'username' => $name, + 'first_name' => $name, + 'last_name' => $name, + 'password' => $pass, + ]); $response = curl_exec($ch); $result = json_decode($response, true); curl_close($ch); // Close the connection - if (!is_array($result) or in_array($result["errors"][0]["code"], $result)) { - header("LOCATION: index.php?step=5&message=Couldnt connect to Pterodactyl. Make sure your API key has all read and write permissions!"); - die(); + if (! is_array($result) or in_array($result['errors'][0]['code'], $result)) { + header('LOCATION: index.php?step=5&message=Couldnt connect to Pterodactyl. Make sure your API key has all read and write permissions!'); + exit(); } - $random = generateRandomString(); - $query1 = "INSERT INTO `" . getEnvironmentValue("DB_DATABASE") . "`.`users` (`name`, `role`, `credits`, `server_limit`, `pterodactyl_id`, `email`, `password`, `created_at`, `referral_code`) VALUES ('$name', 'admin', '250', '1', '$pteroID', '$mail', '$pass', CURRENT_TIMESTAMP, '$random')"; - - + $query1 = 'INSERT INTO `'.getEnvironmentValue('DB_DATABASE')."`.`users` (`name`, `role`, `credits`, `server_limit`, `pterodactyl_id`, `email`, `password`, `created_at`, `referral_code`) VALUES ('$name', 'admin', '250', '1', '$pteroID', '$mail', '$pass', CURRENT_TIMESTAMP, '$random')"; if ($db->query($query1)) { - wh_log("[USER MAKER] Created user with Email ".$mail. " and pterodactyl ID ". $pteroID); - header("LOCATION: index.php?step=7"); + wh_log('[USER MAKER] Created user with Email '.$mail.' and pterodactyl ID '.$pteroID); + header('LOCATION: index.php?step=7'); } else { wh_log($db->error); - header("LOCATION: index.php?step=6&message=Something went wrong when communicating with the Database"); - + header('LOCATION: index.php?step=6&message=Something went wrong when communicating with the Database'); } - - } - - -?> diff --git a/public/install/functions.php b/public/install/functions.php index 10baf2e7..8788f127 100644 --- a/public/install/functions.php +++ b/public/install/functions.php @@ -1,29 +1,29 @@ "7.4", - "maxPhp" => "8.1", // This version is not supported - "mysql" => "5.7.22", + 'minPhp' => '7.4', + 'maxPhp' => '8.1', // This version is not supported + 'mysql' => '5.7.22', ]; function checkPhpVersion() { global $requirements; - if (version_compare(phpversion(), $requirements["minPhp"], '>=') && version_compare(phpversion(), $requirements["maxPhp"], '<')) { - return "OK"; + if (version_compare(phpversion(), $requirements['minPhp'], '>=') && version_compare(phpversion(), $requirements['maxPhp'], '<')) { + return 'OK'; } - return "not OK"; + + return 'not OK'; } function checkWriteable() { - return is_writable("../../.env"); + return is_writable('../../.env'); } function checkHTTPS() { - return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') + return (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443; } @@ -34,42 +34,39 @@ function getMySQLVersion() $output = shell_exec('mysql -V'); preg_match('@[0-9]+\.[0-9]+\.[0-9]+@', $output, $version); - $versionoutput = $version[0] ?? "0"; + $versionoutput = $version[0] ?? '0'; - return (intval($versionoutput) > intval($requirements["mysql"]) ? "OK" : $versionoutput); + return intval($versionoutput) > intval($requirements['mysql']) ? 'OK' : $versionoutput; } function getZipVersion() { - $output = shell_exec('zip -v'); preg_match('@[0-9]+\.[0-9]+\.[0-9]+@', $output, $version); $versionoutput = $version[0] ?? 0; - return ($versionoutput != 0 ? "OK" : "not OK"); + return $versionoutput != 0 ? 'OK' : 'not OK'; } function getGitVersion() { - $output = shell_exec('git --version'); preg_match('@[0-9]+\.[0-9]+\.[0-9]+@', $output, $version); $versionoutput = $version[0] ?? 0; - return ($versionoutput != 0 ? "OK" : "not OK"); + return $versionoutput != 0 ? 'OK' : 'not OK'; } function getTarVersion() { - $output = shell_exec('tar --version'); preg_match('@[0-9]+\.[0-9]+@', $output, $version); $versionoutput = $version[0] ?? 0; - return ($versionoutput != 0 ? "OK" : "not OK"); + return $versionoutput != 0 ? 'OK' : 'not OK'; } function checkExtensions() @@ -80,16 +77,17 @@ function checkExtensions() $extentions = get_loaded_extensions(); foreach ($required_extentions as $ext) { - if (!preg_grep("/^(?=.*" . $ext . ").*$/", $extentions)) + if (! preg_grep('/^(?=.*'.$ext.').*$/', $extentions)) { array_push($not_ok, $ext); + } } + return $not_ok; } function setEnvironmentValue($envKey, $envValue) { - - $envFile = dirname(__FILE__, 3) . "/.env"; + $envFile = dirname(__FILE__, 3).'/.env'; $str = file_get_contents($envFile); $str .= "\n"; // In case the searched variable is in the last line without \n @@ -106,47 +104,46 @@ function setEnvironmentValue($envKey, $envValue) function getEnvironmentValue($envKey) { - $envFile = dirname(__FILE__, 3) . "/.env"; + $envFile = dirname(__FILE__, 3).'/.env'; $str = file_get_contents($envFile); $str .= "\n"; // In case the searched variable is in the last line without \n $keyPosition = strpos($str, "{$envKey}="); $endOfLinePosition = strpos($str, PHP_EOL, $keyPosition); $oldLine = substr($str, $keyPosition, $endOfLinePosition - $keyPosition); - $value = substr($oldLine, strpos($oldLine, "=") + 1); - - + $value = substr($oldLine, strpos($oldLine, '=') + 1); return $value; } - function run_console($command) { $path = dirname(__FILE__, 3); $cmd = "cd '$path' && bash -c 'exec -a ServerCPP $command' 2>&1"; + return shell_exec($cmd); } function wh_log($log_msg) { - $log_filename = "logs"; - if (!file_exists($log_filename)) { + $log_filename = 'logs'; + if (! file_exists($log_filename)) { // create directory/folder uploads. mkdir($log_filename, 0777, true); } - $log_file_data = $log_filename . '/installer.log'; + $log_file_data = $log_filename.'/installer.log'; // if you don't add `FILE_APPEND`, the file will be erased each time you add a log - file_put_contents($log_file_data, "[" . date('h:i:s') . "] " . $log_msg . "\n", FILE_APPEND); + file_put_contents($log_file_data, '['.date('h:i:s').'] '.$log_msg."\n", FILE_APPEND); } - -function generateRandomString($length = 8) { +function generateRandomString($length = 8) +{ $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } + return $randomString; } diff --git a/public/install/index.php b/public/install/index.php index bc37320a..d834a8d9 100644 --- a/public/install/index.php +++ b/public/install/index.php @@ -1,8 +1,8 @@ @@ -52,43 +52,38 @@ $cardheader = '
'; - -if (!isset($_GET['step'])) { - - - if (!file_exists("../../.env")) { +if (! isset($_GET['step'])) { + if (! file_exists('../../.env')) { echo run_console('cp .env.example .env'); - } - echo $cardheader; - ?> + echo $cardheader; ?> -

">HTTPS is required

+

HTTPS is required

-

">Write-permissions on .env-file

+

Write-permissions on .env-file

-

"> php - version: (minimum required )

-

"> mysql - version: (minimum required )

+

php + version: (minimum required )

+

mysql + version: (minimum required )

-

"> Missing - php-extentions: "> Missing + php-extentions:

+ echo count(checkExtensions()) == 0 ? '' : '(Proceed anyway)'; ?>

- -

"> Git +

Git version:

-

"> Tar +

Tar version:

@@ -101,13 +96,11 @@ if (!isset($_GET['step'])) { + echo $cardheader; ?> " . $_GET['message'] . "

"; -} -?> + echo "

".$_GET['message'].'

'; + } ?>
@@ -174,17 +167,14 @@ echo $cardheader;
+ echo $cardheader; ?>

This process might take a while. Please do not refresh or close this page!

" . $_GET['message'] . "

"; - } - - ?> + echo "

".$_GET['message'].'

'; + } ?> @@ -198,18 +188,15 @@ echo $cardheader; + echo $cardheader; ?> " . $_GET['message'] . "

"; - } - ?> + echo "

".$_GET['message'].'

'; + } ?> @@ -222,7 +209,7 @@ echo $cardheader; " class="form-control"> + value="" class="form-control">
@@ -245,17 +232,15 @@ echo $cardheader;
+ echo $cardheader; ?> " . $_GET['message'] . "

"; - } - ?> + echo "

".$_GET['message'].'

'; + } ?> + echo $cardheader; ?> " . $_GET['message'] . "

"; - } - ?> + echo "

".$_GET['message'].'

'; + } ?> + echo $cardheader; ?> " . $_GET['message'] . "

"; - } - ?> + echo "

".$_GET['message'].'

'; + } ?> @@ -446,18 +426,16 @@ echo $cardheader; + echo $cardheader; ?> - "> + diff --git a/public/install/phpmailer/Exception.php b/public/install/phpmailer/Exception.php index 52eaf951..34b5bd4b 100644 --- a/public/install/phpmailer/Exception.php +++ b/public/install/phpmailer/Exception.php @@ -35,6 +35,6 @@ class Exception extends \Exception */ public function errorMessage() { - return '' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "
\n"; + return ''.htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401)."
\n"; } } diff --git a/public/install/phpmailer/PHPMailer.php b/public/install/phpmailer/PHPMailer.php index e1b0c88f..82dbc52a 100644 --- a/public/install/phpmailer/PHPMailer.php +++ b/public/install/phpmailer/PHPMailer.php @@ -32,32 +32,51 @@ namespace PHPMailer\PHPMailer; class PHPMailer { const CHARSET_ASCII = 'us-ascii'; + const CHARSET_ISO88591 = 'iso-8859-1'; + const CHARSET_UTF8 = 'utf-8'; const CONTENT_TYPE_PLAINTEXT = 'text/plain'; + const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'; + const CONTENT_TYPE_TEXT_HTML = 'text/html'; + const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; + const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'; + const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related'; const ENCODING_7BIT = '7bit'; + const ENCODING_8BIT = '8bit'; + const ENCODING_BASE64 = 'base64'; + const ENCODING_BINARY = 'binary'; + const ENCODING_QUOTED_PRINTABLE = 'quoted-printable'; const ENCRYPTION_STARTTLS = 'tls'; + const ENCRYPTION_SMTPS = 'ssl'; const ICAL_METHOD_REQUEST = 'REQUEST'; + const ICAL_METHOD_PUBLISH = 'PUBLISH'; + const ICAL_METHOD_REPLY = 'REPLY'; + const ICAL_METHOD_ADD = 'ADD'; + const ICAL_METHOD_CANCEL = 'CANCEL'; + const ICAL_METHOD_REFRESH = 'REFRESH'; + const ICAL_METHOD_COUNTER = 'COUNTER'; + const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; /** @@ -389,12 +408,12 @@ class PHPMailer * SMTP class debug output mode. * Debug output level. * Options: + * * @see SMTP::DEBUG_OFF: No output * @see SMTP::DEBUG_CLIENT: Client messages * @see SMTP::DEBUG_SERVER: Client and server messages * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed - * * @see SMTP::$do_debug * * @var int @@ -821,7 +840,7 @@ class PHPMailer /** * Constructor. * - * @param bool $exceptions Should we throw external exceptions? + * @param bool $exceptions Should we throw external exceptions? */ public function __construct($exceptions = null) { @@ -847,12 +866,11 @@ class PHPMailer * claims to be sendmail), don't pass params (not a perfect fix, * but it will do). * - * @param string $to To - * @param string $subject Subject - * @param string $body Message Body - * @param string $header Additional Header(s) - * @param string|null $params Params - * + * @param string $to To + * @param string $subject Subject + * @param string $body Message Body + * @param string $header Additional Header(s) + * @param string|null $params Params * @return bool */ private function mailPassthru($to, $subject, $body, $header, $params) @@ -865,18 +883,19 @@ class PHPMailer } //Calling mail() with null params breaks $this->edebug('Sending with mail()'); - $this->edebug('Sendmail path: ' . ini_get('sendmail_path')); + $this->edebug('Sendmail path: '.ini_get('sendmail_path')); $this->edebug("Envelope sender: {$this->Sender}"); $this->edebug("To: {$to}"); $this->edebug("Subject: {$subject}"); $this->edebug("Headers: {$header}"); - if (!$this->UseSendmailOptions || null === $params) { + if (! $this->UseSendmailOptions || null === $params) { $result = @mail($to, $subject, $body, $header); } else { $this->edebug("Additional params: {$params}"); $result = @mail($to, $subject, $body, $header, $params); } - $this->edebug('Result: ' . ($result ? 'true' : 'false')); + $this->edebug('Result: '.($result ? 'true' : 'false')); + return $result; } @@ -887,7 +906,7 @@ class PHPMailer * @see PHPMailer::$Debugoutput * @see PHPMailer::$SMTPDebug * - * @param string $str + * @param string $str */ protected function edebug($str) { @@ -901,7 +920,7 @@ class PHPMailer return; } //Avoid clash with built-in function names - if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { + if (is_callable($this->Debugoutput) && ! in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { call_user_func($this->Debugoutput, $str, $this->SMTPDebug); return; @@ -942,7 +961,7 @@ class PHPMailer /** * Sets message type to HTML or plain. * - * @param bool $isHtml True for HTML mode + * @param bool $isHtml True for HTML mode */ public function isHTML($isHtml = true) { @@ -1002,12 +1021,11 @@ class PHPMailer /** * Add a "To" address. * - * @param string $address The email address to send to - * @param string $name + * @param string $address The email address to send to + * @param string $name + * @return bool true on success, false if address already used or invalid in some way * * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way */ public function addAddress($address, $name = '') { @@ -1017,12 +1035,11 @@ class PHPMailer /** * Add a "CC" address. * - * @param string $address The email address to send to - * @param string $name + * @param string $address The email address to send to + * @param string $name + * @return bool true on success, false if address already used or invalid in some way * * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way */ public function addCC($address, $name = '') { @@ -1032,12 +1049,11 @@ class PHPMailer /** * Add a "BCC" address. * - * @param string $address The email address to send to - * @param string $name + * @param string $address The email address to send to + * @param string $name + * @return bool true on success, false if address already used or invalid in some way * * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way */ public function addBCC($address, $name = '') { @@ -1047,12 +1063,11 @@ class PHPMailer /** * Add a "Reply-To" address. * - * @param string $address The email address to reply to - * @param string $name + * @param string $address The email address to reply to + * @param string $name + * @return bool true on success, false if address already used or invalid in some way * * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way */ public function addReplyTo($address, $name = '') { @@ -1065,13 +1080,12 @@ class PHPMailer * be modified after calling this function), addition of such addresses is delayed until send(). * Addresses that have been added already return false, but do not throw exceptions. * - * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' - * @param string $address The email address to send, resp. to reply to - * @param string $name + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * @return bool true on success, false if address already used or invalid in some way * * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way */ protected function addOrEnqueueAnAddress($kind, $address, $name) { @@ -1098,12 +1112,12 @@ class PHPMailer //Enqueue addresses with IDN until we know the PHPMailer::$CharSet. if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) { if ('Reply-To' !== $kind) { - if (!array_key_exists($address, $this->RecipientsQueue)) { + if (! array_key_exists($address, $this->RecipientsQueue)) { $this->RecipientsQueue[$address] = $params; return true; } - } elseif (!array_key_exists($address, $this->ReplyToQueue)) { + } elseif (! array_key_exists($address, $this->ReplyToQueue)) { $this->ReplyToQueue[$address] = $params; return true; @@ -1120,17 +1134,16 @@ class PHPMailer * Add an address to one of the recipient arrays or to the ReplyTo array. * Addresses that have been added already return false, but do not throw exceptions. * - * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' - * @param string $address The email address to send, resp. to reply to - * @param string $name + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * @return bool true on success, false if address already used or invalid in some way * * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way */ protected function addAnAddress($kind, $address, $name = '') { - if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { + if (! in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { $error_message = sprintf( '%s: %s', $this->lang('Invalid recipient kind'), @@ -1144,7 +1157,7 @@ class PHPMailer return false; } - if (!static::validateAddress($address)) { + if (! static::validateAddress($address)) { $error_message = sprintf( '%s (%s): %s', $this->lang('invalid_address'), @@ -1160,13 +1173,13 @@ class PHPMailer return false; } if ('Reply-To' !== $kind) { - if (!array_key_exists(strtolower($address), $this->all_recipients)) { + if (! array_key_exists(strtolower($address), $this->all_recipients)) { $this->{$kind}[] = [$address, $name]; $this->all_recipients[strtolower($address)] = true; return true; } - } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) { + } elseif (! array_key_exists(strtolower($address), $this->ReplyTo)) { $this->ReplyTo[strtolower($address)] = [$address, $name]; return true; @@ -1183,10 +1196,9 @@ class PHPMailer * * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation * - * @param string $addrstr The address list string - * @param bool $useimap Whether to use the IMAP extension to parse the list - * @param string $charset The charset to use when decoding the address list string. - * + * @param string $addrstr The address list string + * @param bool $useimap Whether to use the IMAP extension to parse the list + * @param string $charset The charset to use when decoding the address list string. * @return array */ public static function parseAddresses($addrstr, $useimap = true, $charset = self::CHARSET_ISO88591) @@ -1200,7 +1212,7 @@ class PHPMailer foreach ($list as $address) { if ( '.SYNTAX-ERROR.' !== $address->host && - static::validateAddress($address->mailbox . '@' . $address->host) + static::validateAddress($address->mailbox.'@'.$address->host) ) { //Decode the name part if it's present and encoded if ( @@ -1220,7 +1232,7 @@ class PHPMailer $addresses[] = [ 'name' => (property_exists($address, 'personal') ? $address->personal : ''), - 'address' => $address->mailbox . '@' . $address->host, + 'address' => $address->mailbox.'@'.$address->host, ]; } } @@ -1239,7 +1251,7 @@ class PHPMailer ]; } } else { - list($name, $email) = explode('<', $address); + [$name, $email] = explode('<', $address); $email = trim(str_replace('>', '', $email)); $name = trim($name); if (static::validateAddress($email)) { @@ -1270,13 +1282,12 @@ class PHPMailer /** * Set the From and FromName properties. * - * @param string $address - * @param string $name - * @param bool $auto Whether to also set the Sender address, defaults to true + * @param string $address + * @param string $name + * @param bool $auto Whether to also set the Sender address, defaults to true + * @return bool * * @throws Exception - * - * @return bool */ public function setFrom($address, $name = '', $auto = true) { @@ -1286,8 +1297,8 @@ class PHPMailer $pos = strrpos($address, '@'); if ( (false === $pos) - || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported()) - && !static::validateAddress($address)) + || ((! $this->has8bitChars(substr($address, ++$pos)) || ! static::idnSupported()) + && ! static::validateAddress($address)) ) { $error_message = sprintf( '%s (From): %s', @@ -1343,9 +1354,8 @@ class PHPMailer * * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. * - * @param string $address The email address to check - * @param string|callable $patternselect Which pattern to use - * + * @param string $address The email address to check + * @param string|callable $patternselect Which pattern to use * @return bool */ public static function validateAddress($address, $patternselect = null) @@ -1354,7 +1364,7 @@ class PHPMailer $patternselect = static::$validator; } //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603 - if (is_callable($patternselect) && !is_string($patternselect)) { + if (is_callable($patternselect) && ! is_string($patternselect)) { return call_user_func($patternselect, $address); } //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 @@ -1381,14 +1391,14 @@ class PHPMailer * Feel free to use and redistribute this code. But please keep this copyright notice. */ return (bool) preg_match( - '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . - '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . - '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . - '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . - '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . - '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . - '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . - '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)'. + '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)'. + '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)'. + '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*'. + '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)'. + '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}'. + '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:'. + '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}'. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address ); @@ -1399,7 +1409,7 @@ class PHPMailer * @see https://html.spec.whatwg.org/#e-mail-state-(type=email) */ return (bool) preg_match( - '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . + '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}'. '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', $address ); @@ -1430,8 +1440,7 @@ class PHPMailer * * @see PHPMailer::$CharSet * - * @param string $address The email address to convert - * + * @param string $address The email address to convert * @return string The encoded address in ASCII form */ public function punyencodeAddress($address) @@ -1439,7 +1448,7 @@ class PHPMailer //Verify we have required functions, CharSet, and at-sign. $pos = strrpos($address, '@'); if ( - !empty($this->CharSet) && + ! empty($this->CharSet) && false !== $pos && static::idnSupported() ) { @@ -1466,7 +1475,7 @@ class PHPMailer $punycode = idn_to_ascii($domain, $errorcode); } if (false !== $punycode) { - return substr($address, 0, $pos) . $punycode; + return substr($address, 0, $pos).$punycode; } } } @@ -1478,14 +1487,14 @@ class PHPMailer * Create a message and send it. * Uses the sending method specified by $Mailer. * - * @throws Exception - * * @return bool false on error - See the ErrorInfo property for details of the error + * + * @throws Exception */ public function send() { try { - if (!$this->preSend()) { + if (! $this->preSend()) { return false; } @@ -1504,9 +1513,9 @@ class PHPMailer /** * Prepare a message for sending. * - * @throws Exception - * * @return bool + * + * @throws Exception */ public function preSend() { @@ -1552,7 +1561,7 @@ class PHPMailer continue; } $this->$address_kind = $this->punyencodeAddress($this->$address_kind); - if (!static::validateAddress($this->$address_kind)) { + if (! static::validateAddress($this->$address_kind)) { $error_message = sprintf( '%s (%s): %s', $this->lang('invalid_address'), @@ -1576,7 +1585,7 @@ class PHPMailer $this->setMessageType(); //Refuse to send an empty message unless we are specifically allowing it - if (!$this->AllowEmpty && empty($this->Body)) { + if (! $this->AllowEmpty && empty($this->Body)) { throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); } @@ -1606,22 +1615,22 @@ class PHPMailer //Sign with DKIM if enabled if ( - !empty($this->DKIM_domain) - && !empty($this->DKIM_selector) - && (!empty($this->DKIM_private_string) - || (!empty($this->DKIM_private) + ! empty($this->DKIM_domain) + && ! empty($this->DKIM_selector) + && (! empty($this->DKIM_private_string) + || (! empty($this->DKIM_private) && static::isPermittedPath($this->DKIM_private) && file_exists($this->DKIM_private) ) ) ) { $header_dkim = $this->DKIM_Add( - $this->MIMEHeader . $this->mailHeader, + $this->MIMEHeader.$this->mailHeader, $this->encodeHeader($this->secureHeader($this->Subject)), $this->MIMEBody ); - $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . - static::normalizeBreaks($header_dkim) . static::$LE; + $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader).static::$LE. + static::normalizeBreaks($header_dkim).static::$LE; } return true; @@ -1638,9 +1647,9 @@ class PHPMailer /** * Actually send a message via the selected mechanism. * - * @throws Exception - * * @return bool + * + * @throws Exception */ public function postSend() { @@ -1655,7 +1664,7 @@ class PHPMailer case 'mail': return $this->mailSend($this->MIMEHeader, $this->MIMEBody); default: - $sendMethod = $this->Mailer . 'Send'; + $sendMethod = $this->Mailer.'Send'; if (method_exists($this, $sendMethod)) { return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); } @@ -1681,12 +1690,11 @@ class PHPMailer * * @see PHPMailer::$Sendmail * - * @param string $header The message headers - * @param string $body The message body + * @param string $header The message headers + * @param string $body The message body + * @return bool * * @throws Exception - * - * @return bool */ protected function sendmailSend($header, $body) { @@ -1695,7 +1703,7 @@ class PHPMailer } else { $this->edebug('Sending with sendmail'); } - $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + $header = static::stripTrailingWSP($header).static::$LE.static::$LE; //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver //A space after `-f` is optional, but there is a long history of its presence //causing problems, so we don't use one @@ -1706,12 +1714,12 @@ class PHPMailer //PHP 5.6 workaround $sendmail_from_value = ini_get('sendmail_from'); - if (empty($this->Sender) && !empty($sendmail_from_value)) { + if (empty($this->Sender) && ! empty($sendmail_from_value)) { //PHP config has a sender address we can use $this->Sender = ini_get('sendmail_from'); } //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. - if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { + if (! empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { if ($this->Mailer === 'qmail') { $sendmailFmt = '%s -f%s'; } else { @@ -1727,19 +1735,19 @@ class PHPMailer } $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); - $this->edebug('Sendmail path: ' . $this->Sendmail); - $this->edebug('Sendmail command: ' . $sendmail); - $this->edebug('Envelope sender: ' . $this->Sender); + $this->edebug('Sendmail path: '.$this->Sendmail); + $this->edebug('Sendmail command: '.$sendmail); + $this->edebug('Envelope sender: '.$this->Sender); $this->edebug("Headers: {$header}"); if ($this->SingleTo) { foreach ($this->SingleToArray as $toAddr) { $mail = @popen($sendmail, 'w'); - if (!$mail) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + if (! $mail) { + throw new Exception($this->lang('execute').$this->Sendmail, self::STOP_CRITICAL); } $this->edebug("To: {$toAddr}"); - fwrite($mail, 'To: ' . $toAddr . "\n"); + fwrite($mail, 'To: '.$toAddr."\n"); fwrite($mail, $header); fwrite($mail, $body); $result = pclose($mail); @@ -1754,15 +1762,15 @@ class PHPMailer $this->From, [] ); - $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); + $this->edebug('Result: '.($result === 0 ? 'true' : 'false')); if (0 !== $result) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + throw new Exception($this->lang('execute').$this->Sendmail, self::STOP_CRITICAL); } } } else { $mail = @popen($sendmail, 'w'); - if (!$mail) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + if (! $mail) { + throw new Exception($this->lang('execute').$this->Sendmail, self::STOP_CRITICAL); } fwrite($mail, $header); fwrite($mail, $body); @@ -1777,9 +1785,9 @@ class PHPMailer $this->From, [] ); - $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); + $this->edebug('Result: '.($result === 0 ? 'true' : 'false')); if (0 !== $result) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + throw new Exception($this->lang('execute').$this->Sendmail, self::STOP_CRITICAL); } } @@ -1792,8 +1800,7 @@ class PHPMailer * * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report * - * @param string $string The string to be validated - * + * @param string $string The string to be validated * @return bool */ protected static function isShellSafe($string) @@ -1801,20 +1808,20 @@ class PHPMailer //Future-proof if ( escapeshellcmd($string) !== $string - || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) + || ! in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) ) { return false; } $length = strlen($string); - for ($i = 0; $i < $length; ++$i) { + for ($i = 0; $i < $length; $i++) { $c = $string[$i]; //All other characters have a special meaning in at least one common shell, including = and +. //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. //Note that this does permit non-Latin alphanumeric characters based on the current locale. - if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { + if (! ctype_alnum($c) && strpos('@_-.', $c) === false) { return false; } } @@ -1827,26 +1834,24 @@ class PHPMailer * Used to reject URLs and phar files from functions that access local file paths, * such as addAttachment. * - * @param string $path A relative or absolute path to a file - * + * @param string $path A relative or absolute path to a file * @return bool */ protected static function isPermittedPath($path) { //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1 - return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path); + return ! preg_match('#^[a-z][a-z\d+.-]*://#i', $path); } /** * Check whether a file path is safe, accessible, and readable. * - * @param string $path A relative or absolute path to a file - * + * @param string $path A relative or absolute path to a file * @return bool */ protected static function fileIsAccessible($path) { - if (!static::isPermittedPath($path)) { + if (! static::isPermittedPath($path)) { return false; } $readable = file_exists($path); @@ -1854,6 +1859,7 @@ class PHPMailer if (strpos($path, '\\\\') !== 0) { $readable = $readable && is_readable($path); } + return $readable; } @@ -1862,16 +1868,15 @@ class PHPMailer * * @see http://www.php.net/manual/en/book.mail.php * - * @param string $header The message headers - * @param string $body The message body + * @param string $header The message headers + * @param string $body The message body + * @return bool * * @throws Exception - * - * @return bool */ protected function mailSend($header, $body) { - $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + $header = static::stripTrailingWSP($header).static::$LE.static::$LE; $toArr = []; foreach ($this->to as $toaddr) { @@ -1891,11 +1896,11 @@ class PHPMailer //PHP 5.6 workaround $sendmail_from_value = ini_get('sendmail_from'); - if (empty($this->Sender) && !empty($sendmail_from_value)) { + if (empty($this->Sender) && ! empty($sendmail_from_value)) { //PHP config has a sender address we can use $this->Sender = ini_get('sendmail_from'); } - if (!empty($this->Sender) && static::validateAddress($this->Sender)) { + if (! empty($this->Sender) && static::validateAddress($this->Sender)) { if (self::isShellSafe($this->Sender)) { $params = sprintf('-f%s', $this->Sender); } @@ -1925,7 +1930,7 @@ class PHPMailer if (isset($old_from)) { ini_set('sendmail_from', $old_from); } - if (!$result) { + if (! $result) { throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); } @@ -1941,7 +1946,7 @@ class PHPMailer */ public function getSMTPInstance() { - if (!is_object($this->smtp)) { + if (! is_object($this->smtp)) { $this->smtp = new SMTP(); } @@ -1968,18 +1973,17 @@ class PHPMailer * * @uses \PHPMailer\PHPMailer\SMTP * - * @param string $header The message headers - * @param string $body The message body + * @param string $header The message headers + * @param string $body The message body + * @return bool * * @throws Exception - * - * @return bool */ protected function smtpSend($header, $body) { - $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + $header = static::stripTrailingWSP($header).static::$LE.static::$LE; $bad_rcpt = []; - if (!$this->smtpConnect($this->SMTPOptions)) { + if (! $this->smtpConnect($this->SMTPOptions)) { throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); } //Sender already validated in preSend() @@ -1988,8 +1992,8 @@ class PHPMailer } else { $smtp_from = $this->Sender; } - if (!$this->smtp->mail($smtp_from)) { - $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + if (! $this->smtp->mail($smtp_from)) { + $this->setError($this->lang('from_failed').$smtp_from.' : '.implode(',', $this->smtp->getError())); throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); } @@ -1997,7 +2001,7 @@ class PHPMailer //Attempt to send to all recipients foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { foreach ($togroup as $to) { - if (!$this->smtp->recipient($to[0], $this->dsn)) { + if (! $this->smtp->recipient($to[0], $this->dsn)) { $error = $this->smtp->getError(); $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; $isSent = false; @@ -2010,7 +2014,7 @@ class PHPMailer } //Only send the DATA command if we have viable recipients - if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { + if ((count($this->all_recipients) > count($bad_rcpt)) && ! $this->smtp->data($header.$body)) { throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); } @@ -2040,9 +2044,9 @@ class PHPMailer if (count($bad_rcpt) > 0) { $errstr = ''; foreach ($bad_rcpt as $bad) { - $errstr .= $bad['to'] . ': ' . $bad['error']; + $errstr .= $bad['to'].': '.$bad['error']; } - throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); + throw new Exception($this->lang('recipients_failed').$errstr, self::STOP_CONTINUE); } return true; @@ -2052,13 +2056,12 @@ class PHPMailer * Initiate a connection to an SMTP server. * Returns false if the operation failed. * - * @param array $options An array of options compatible with stream_context_create() + * @param array $options An array of options compatible with stream_context_create() + * @return bool * * @throws Exception * * @uses \PHPMailer\PHPMailer\SMTP - * - * @return bool */ public function smtpConnect($options = null) { @@ -2086,13 +2089,13 @@ class PHPMailer foreach ($hosts as $hostentry) { $hostinfo = []; if ( - !preg_match( + ! preg_match( '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', trim($hostentry), $hostinfo ) ) { - $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); + $this->edebug($this->lang('invalid_hostentry').' '.trim($hostentry)); //Not a valid host entry continue; } @@ -2103,8 +2106,8 @@ class PHPMailer //If it's not specified, the default value is used //Check the host name is a valid name or IP address before trying to use it - if (!static::isValidHost($hostinfo[2])) { - $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); + if (! static::isValidHost($hostinfo[2])) { + $this->edebug($this->lang('invalid_host').' '.$hostinfo[2]); continue; } $prefix = ''; @@ -2123,8 +2126,8 @@ class PHPMailer $sslext = defined('OPENSSL_ALGO_SHA256'); if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled - if (!$sslext) { - throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); + if (! $sslext) { + throw new Exception($this->lang('extension_missing').'openssl', self::STOP_CRITICAL); } } $host = $hostinfo[2]; @@ -2137,7 +2140,7 @@ class PHPMailer ) { $port = (int) $hostinfo[3]; } - if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { + if ($this->smtp->connect($prefix.$host, $port, $this->Timeout, $options)) { try { if ($this->Helo) { $hello = $this->Helo; @@ -2154,14 +2157,14 @@ class PHPMailer $tls = true; } if ($tls) { - if (!$this->smtp->startTLS()) { + if (! $this->smtp->startTLS()) { throw new Exception($this->lang('connect_host')); } //We must resend EHLO after TLS negotiation $this->smtp->hello($hello); } if ( - $this->SMTPAuth && !$this->smtp->authenticate( + $this->SMTPAuth && ! $this->smtp->authenticate( $this->Username, $this->Password, $this->AuthType, @@ -2205,12 +2208,11 @@ class PHPMailer * Set the language for error messages. * The default language is English. * - * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") + * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") * Optionally, the language code can be enhanced with a 4-character * script annotation and/or a 2-character country annotation. - * @param string $lang_path Path to the language file directory, with trailing separator (slash) + * @param string $lang_path Path to the language file directory, with trailing separator (slash) * Do not set this from user input! - * * @return bool Returns true if the requested language was loaded, false otherwise. */ public function setLanguage($langcode = 'en', $lang_path = '') @@ -2234,8 +2236,8 @@ class PHPMailer //Define full set of translatable strings in English $PHPMAILER_LANG = [ 'authenticate' => 'SMTP Error: Could not authenticate.', - 'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' . - ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . + 'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.'. + ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in'. ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'data_not_accepted' => 'SMTP Error: data not accepted.', @@ -2264,14 +2266,14 @@ class PHPMailer ]; if (empty($lang_path)) { //Calculate an absolute path so it can work if CWD is not here - $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; + $lang_path = dirname(__DIR__).DIRECTORY_SEPARATOR.'language'.DIRECTORY_SEPARATOR; } //Validate $langcode $foundlang = true; - $langcode = strtolower($langcode); + $langcode = strtolower($langcode); if ( - !preg_match('/^(?P[a-z]{2})(?P