1
1
mirror of https://github.com/pterodactyl/panel.git synced 2024-11-25 02:22:36 +01:00

Merge branch '1.0-develop' into dusk

# Conflicts:
#	composer.json
#	composer.lock
This commit is contained in:
Lance Pioch 2024-02-19 22:14:22 -05:00
commit ee8f935cae
No known key found for this signature in database
224 changed files with 3525 additions and 2492 deletions

View File

@ -8,7 +8,7 @@ APP_ENVIRONMENT_ONLY=true
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=panel_test
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=

View File

@ -23,7 +23,7 @@ REDIS_PASSWORD=null
REDIS_PORT=6379
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
QUEUE_CONNECTION=redis
SESSION_DRIVER=file
HASHIDS_SALT=
@ -41,4 +41,4 @@ MAIL_FROM_NAME="Pterodactyl Panel"
# mail servers such as Gmail to reject your mail.
#
# @see: https://github.com/pterodactyl/panel/pull/3110
# SERVER_NAME=panel.example.com
# MAIL_EHLO_DOMAIN=panel.example.com

View File

@ -1,9 +1,3 @@
const prettier = {
singleQuote: true,
jsxSingleQuote: true,
printWidth: 120,
};
/** @type {import('eslint').Linter.Config} */
module.exports = {
parser: '@typescript-eslint/parser',
@ -21,20 +15,15 @@ module.exports = {
version: 'detect',
},
linkComponents: [
{name: 'Link', linkAttribute: 'to'},
{name: 'NavLink', linkAttribute: 'to'},
{ name: 'Link', linkAttribute: 'to' },
{ name: 'NavLink', linkAttribute: 'to' },
],
},
env: {
browser: true,
es6: true,
},
plugins: [
'react',
'react-hooks',
'prettier',
'@typescript-eslint',
],
plugins: ['react', 'react-hooks', 'prettier', '@typescript-eslint'],
extends: [
// 'standard',
'eslint:recommended',
@ -44,7 +33,7 @@ module.exports = {
],
rules: {
eqeqeq: 'error',
'prettier/prettier': ['error', prettier],
'prettier/prettier': ['error', {}, { usePrettierrc: true }],
// TypeScript can infer this significantly better than eslint ever can.
'react/prop-types': 0,
'react/display-name': 0,
@ -56,7 +45,7 @@ module.exports = {
// @see https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-use-before-define.md#how-to-use
'no-use-before-define': 0,
'@typescript-eslint/no-use-before-define': 'warn',
'@typescript-eslint/no-unused-vars': ['warn', {argsIgnorePattern: '^_', varsIgnorePattern: '^_'}],
'@typescript-eslint/ban-ts-comment': ['error', {'ts-expect-error': 'allow-with-description'}],
}
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
'@typescript-eslint/ban-ts-comment': ['error', { 'ts-expect-error': 'allow-with-description' }],
},
};

View File

@ -68,8 +68,8 @@ body:
Run the following command to collect logs on your system.
Wings: `sudo wings diagnostics`
Panel: `tail -n 100 /var/www/pterodactyl/storage/logs/laravel-$(date +%F).log | nc bin.ptdl.co 99`
placeholder: "https://bin.ptdl.co/a1h6z"
Panel: `tail -n 150 /var/www/pterodactyl/storage/logs/laravel-$(date +%F).log | nc pteropaste.com 99`
placeholder: "https://pteropaste.com/a1h6z"
render: bash
validations:
required: false

View File

@ -1,4 +1,4 @@
blank_issues_enabled: false
blank_issues_enabled: true
contact_links:
- name: Installation Help
url: https://discord.gg/pterodactyl

View File

@ -3,7 +3,7 @@ cd /app
mkdir -p /var/log/panel/logs/ /var/log/supervisord/ /var/log/nginx/ /var/log/php7/ \
&& chmod 777 /var/log/panel/logs/ \
&& ln -s /var/log/panel/logs/ /app/storage/logs/
&& ln -s /app/storage/logs/ /var/log/panel/
## check for .env file and generate app keys if missing
if [ -f /app/var/.env ]; then

View File

@ -17,14 +17,14 @@ jobs:
strategy:
fail-fast: false
matrix:
php: [8.0, 8.1]
php: [8.1, 8.2]
database: ["mariadb:10.2", "mysql:8"]
services:
database:
image: ${{ matrix.database }}
env:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: panel_test
MYSQL_DATABASE: testing
ports:
- 3306
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3

View File

@ -1,61 +1,68 @@
name: Publish Docker Image
name: Docker
on:
push:
branches:
- "develop"
- "release/v*"
- develop
- 1.0-develop
pull_request:
branches:
- develop
- 1.0-develop
release:
types:
- published
jobs:
push:
name: Push Image to GitHub Packages
name: Push
runs-on: ubuntu-20.04
# Always run against a tag, even if the commit into the tag has [docker skip]
# within the commit message.
if: "!contains(github.ref, 'develop') || (!contains(github.event.head_commit.message, 'skip docker') && !contains(github.event.head_commit.message, 'docker skip'))"
steps:
- name: Code Checkout
- name: Code checkout
uses: actions/checkout@v3
- name: Docker Metadata
uses: docker/metadata-action@v4
- name: Docker metadata
id: docker_meta
uses: docker/metadata-action@v4
with:
images: ghcr.io/pterodactyl/panel
flavor: |
latest=false
tags: |
type=raw,value=latest,enable=${{ github.event_name == 'release' && github.event.action == 'published' && github.event.release.prerelease == false }}
type=ref,event=tag
type=ref,event=branch
- name: Setup QEMU
uses: docker/setup-qemu-action@v2
- name: Setup Docker Buildx
- name: Setup Docker buildx
uses: docker/setup-buildx-action@v2
- name: Docker Login
- name: Login to GitHub Container Registry
uses: docker/login-action@v2
if: "github.event_name != 'pull_request'"
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Release production build
uses: docker/build-push-action@v2
if: "contains(github.ref, 'release/v')"
with:
context: .
file: ./Dockerfile
push: true
platforms: linux/amd64,linux/arm64
tags: ${{ steps.docker_meta.outputs.tags }}
labels: ${{ steps.docker_meta.outputs.labels }}
- name: Update version
if: "github.event_name == 'release' && github.event.action == 'published'"
env:
REF: ${{ github.event.release.tag_name }}
run: |
sed -i "s/ 'version' => 'canary',/ 'version' => '${REF:1}',/" config/app.php
- name: Release development build
uses: docker/build-push-action@v2
if: "contains(github.ref, 'develop')"
- name: Build and Push
uses: docker/build-push-action@v4
with:
context: .
file: ./Dockerfile
push: ${{ github.event_name != 'pull_request' }}
platforms: linux/amd64,linux/arm64
tags: ${{ steps.docker_meta.outputs.tags }}
labels: ${{ steps.docker_meta.outputs.labels }}
tags: ${{ steps.docker_meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max

View File

@ -10,7 +10,7 @@ jobs:
name: Release
runs-on: ubuntu-20.04
steps:
- name: Code Checkout
- name: Code checkout
uses: actions/checkout@v3
- name: Setup Node
@ -36,21 +36,19 @@ jobs:
git push -u origin $BRANCH
sed -i "s/ 'version' => 'canary',/ 'version' => '${REF:11}',/" config/app.php
git add config/app.php
git commit -m "bump version for release"
git commit -m "ci(release): bump version"
git push
- name: Create release archive
run: |
rm -rf node_modules/ test/ codecov.yml CODE_OF_CONDUCT.md CONTRIBUTING.md phpunit.xml Vagrantfile
tar -czf panel.tar.gz * .env.example .eslintignore .eslintrc.js
rm -rf node_modules tests CODE_OF_CONDUCT.md CONTRIBUTING.md flake.lock flake.nix phpunit.xml shell.nix
tar -czf panel.tar.gz * .editorconfig .env.example .eslintignore .eslintrc.js .gitignore .prettierrc.json
- name: Extract changelog
id: extract_changelog
env:
REF: ${{ github.ref }}
run: |
sed -n "/^## ${REF:10}/,/^## /{/^## /b;p}" CHANGELOG.md > ./RELEASE_CHANGELOG
echo ::set-output name=version_name::`sed -nr "s/^## (${REF:10} .*)$/\1/p" CHANGELOG.md`
- name: Create checksum and add to changelog
run: |
@ -58,17 +56,15 @@ jobs:
echo -e "\n#### SHA256 Checksum\n\n\`\`\`\n$SUM\n\`\`\`\n" >> ./RELEASE_CHANGELOG
echo $SUM > checksum.txt
- name: Create Release
- name: Create release
id: create_release
uses: actions/create-release@v1
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ steps.extract_changelog.outputs.version_name }}
body_path: ./RELEASE_CHANGELOG
draft: true
prerelease: ${{ contains(github.ref, 'beta') || contains(github.ref, 'alpha') }}
prerelease: ${{ contains(github.ref, 'rc') || contains(github.ref, 'beta') || contains(github.ref, 'alpha') }}
body_path: ./RELEASE_CHANGELOG
- name: Upload release archive
id: upload-release-archive

5
.gitignore vendored
View File

@ -29,3 +29,8 @@ misc
coverage.xml
resources/lang/locales.js
.phpunit.result.cache
/public/build
/public/hot
result
docker-compose.yaml

9
.prettierrc.json Normal file
View File

@ -0,0 +1,9 @@
{
"printWidth": 120,
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": true,
"jsxSingleQuote": true,
"endOfLine": "lf"
}

View File

@ -3,10 +3,100 @@ This file is a running track of new features and fixes to each version of the pa
This project follows [Semantic Versioning](http://semver.org) guidelines.
## [Unreleased]
## v1.11.5
### Fixed
* Rust egg using the wrong Docker image, breaking Rust modding frameworks.
## v1.11.4
### Added
* Added support for the `server.queryport` option on the Rust egg.
* Added support for the Carbon modding framework to the Rust egg.
### Changed
* Changed minimum PHP version is now 8.0 instead of `7.4`.
* Upgraded to Laravel 10.
* Sensitive data is no longer shown in the CopyOnClick toast notification.
### Fixed
* Allow SVGs to be edited in the server's file manager.
* Properly validate the request body when creating a backup.
* Fixed issue with schedules running at the wrong time when the panel utilized a timezone with non-hour offsets (such as `Australia/Darwin`).
* Fixes the log directory when running the Panel in a container.
* Fixes the permission name used to check if a user has permission to read files/folders.
* Fixes the ability to unset a server's description through the client API.
* Fixed the MassActionBar on the server's file manager blocking elements below it, preventing them from being interacted with.
## v1.11.3
### Changed
* When updating a server's description through the client API, if no value is specified, the description will now remain unchanged.
* When installing the Panel for the first time, the queue driver will now all default to `redis` instead of `sync`.
### Fixed
* `php artisan p:environment:mail` not correctly setting the right variable for `MAIL_FROM_ADDRESS`.
* Fixed the conflict state rendering on the UI for a server showing `reinstall_failed` as `restoring_backup`.
* Fixed the unknown column `uuid` error when jobs fail, causing them not to get stored correctly.
* Fixed the server task endpoints in the client API not allowing `sequence_id` and `continue_on_failure` to be set.
## v1.11.2
### Changed
* Telemetry no longer sends a map of Egg and Nest UUIDs to the number of servers using them.
* Increased the timeout for the decompress files endpoint in the client API from 15 seconds to 15 minutes.
### Fixed
* Fixed Panel Docker image having a `v` prefix in the version displayed in the admin area.
* Fixed emails using the wrong queue name, causing them to not be sent.
* Fixed the settings keys used for configuring SMTP settings, causing settings to not save properly.
* Fixed the `MAIL_EHLO_DOMAIN` environment variable not being properly backwards compatible with the old `SERVER_NAME` variable.
## v1.11.1
### Fixed
* Fixed Panel Docker image showing `canary` as it's version.
## v1.11.0
### Changed (since 1.10.4)
* Changed minimum PHP version requirement from `7.4` to `8.0`.
* Upgraded from Laravel 8 to Laravel 9.
* This release requires Wings v1.11.x in order for Server Transfers to work.
* `MB` byte suffixes are now displayed as `MiB` to more accurately reflect the actual value.
* Server re-installation failures are tracked independently of the initial installation process.
### Fixed (since 1.10.4)
* Node maintenance mode now properly blocks access to servers.
* Fixed the length validation on the Minecraft Forge egg.
* Fixed the password in the JDBC string not being properly URL encoded.
* Fixed an issue where Wings would throw a validation error while attempting to upload activity logs.
* Properly handle a missing `Content-Length` header in the response from the daemon.
* Ensure activity log properties are always returned as an object instead of an empty array.
### Added (since 1.10.4)
* Added the `server:settings.description` activity log event for when a server description is changed.
* Added the ability to cancel file uploads in the file manager for a server.
* Added a telemetry service to collect anonymous metrics from the panel, this feature is *enabled* by default and can be toggled using the `PTERODACTYL_TELEMETRY_ENABLED` environment variable.
## v1.11.0-rc.2
### Changed
* `MB` byte suffixes are now displayed as `MiB` to more accurately reflect the actual value.
* Server re-installation failures are tracked independently of the initial installation process.
### Fixed
* Properly handle a missing `Content-Length` header in the response from the daemon.
* Ensure activity log properties are always returned as an object instead of an empty array.
### Added
* Added the `server:settings.description` activity log event for when a server description is changed.
* Added the ability to cancel file uploads in the file manager for a server.
* Added a telemetry service to collect anonymous metrics from the panel, this feature is disabled by default and can be toggled using the `PTERODACTYL_TELEMETRY_ENABLED` environment variable.
## v1.11.0-rc.1
### Changed
* Changed minimum PHP version requirement from `7.4` to `8.0`.
* Upgraded from Laravel 8 to Laravel 9.
* This release requires Wings v1.11.x in order for Server Transfers to work.
### Fixed
* Node maintenance mode now properly blocks access to servers.
* Fixed the length validation on the Minecraft Forge egg.
* Fixed the password in the JDBC string not being properly URL encoded.
* Fixed an issue where Wings would throw a validation error while attempting to upload activity logs.
## v1.10.4
### Fixed

View File

@ -23,6 +23,7 @@ RUN apk add --no-cache --update ca-certificates dcron curl git supervisor tar un
&& chmod 777 -R bootstrap storage \
&& composer install --no-dev --optimize-autoloader \
&& rm -rf .env bootstrap/cache/*.php \
&& mkdir -p /app/storage/logs/ \
&& chown -R nginx:nginx .
RUN rm /usr/local/etc/php-fpm.conf \

View File

@ -1,12 +1,13 @@
[![Logo Image](https://cdn.pterodactyl.io/logos/new/pterodactyl_logo.png)](https://pterodactyl.io)
![GitHub Workflow Status](https://img.shields.io/github/workflow/status/pterodactyl/panel/tests?label=Tests&style=for-the-badge)
![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/pterodactyl/panel/ci.yaml?label=Tests&style=for-the-badge&branch=1.0-develop)
![Discord](https://img.shields.io/discord/122900397965705216?label=Discord&logo=Discord&logoColor=white&style=for-the-badge)
![GitHub Releases](https://img.shields.io/github/downloads/pterodactyl/panel/latest/total?style=for-the-badge)
![GitHub contributors](https://img.shields.io/github/contributors/pterodactyl/panel?style=for-the-badge)
# Pterodactyl Panel
Pterodactyl® is a free, open-source game server management panel built with PHP, React, and Go. Designed with security
Pterodactyl® is a free, open-source game server management panel built with PHP, React, and Go. Designed with security
in mind, Pterodactyl runs all game servers in isolated Docker containers while exposing a beautiful and intuitive
UI to end users.
@ -15,30 +16,26 @@ Stop settling for less. Make game servers a first class citizen on your platform
![Image](https://cdn.pterodactyl.io/site-assets/pterodactyl_v1_demo.gif)
## Documentation
* [Panel Documentation](https://pterodactyl.io/panel/1.0/getting_started.html)
* [Wings Documentation](https://pterodactyl.io/wings/1.0/installing.html)
* [Community Guides](https://pterodactyl.io/community/about.html)
* Or, get additional help [via Discord](https://discord.gg/pterodactyl)
## Sponsors
I would like to extend my sincere thanks to the following sponsors for helping fund Pterodactyl's developement.
I would like to extend my sincere thanks to the following sponsors for helping fund Pterodactyl's development.
[Interested in becoming a sponsor?](https://github.com/sponsors/matthewpi)
| Company | About |
| ------- | ----- |
| [**WISP**](https://wisp.gg) | Extra features. |
| [**BisectHosting**](https://www.bisecthosting.com/) | BisectHosting provides Minecraft, Valheim and other server hosting services with the highest reliability and lightning fast support since 2012. |
| [**Fragnet**](https://fragnet.net) | Providing low latency, high-end game hosting solutions to gamers, game studios and eSports platforms. |
| [**Tempest**](https://tempest.net/) | Tempest Hosting is a subsidiary of Path Network, Inc. offering unmetered DDoS protected 10Gbps dedicated servers, starting at just $80/month. Full anycast, tons of filters. |
| [**Bloom.host**](https://bloom.host) | Bloom.host offers dedicated core VPS and Minecraft hosting with Ryzen 9 processors. With owned-hardware, we offer truly unbeatable prices on high-performance hosting. |
| [**MineStrator**](https://minestrator.com/) | Looking for the most highend French hosting company for your minecraft server? More than 24,000 members on our discord trust us. Give us a try! |
| [**Skynode**](https://www.skynode.pro/) | Skynode provides blazing fast game servers along with a top-notch user experience. Whatever our clients are looking for, we're able to provide it! |
| [**DeinServerHost**](https://deinserverhost.de/) | DeinServerHost offers Dedicated, vps and Gameservers for many popular Games like Minecraft and Rust in Germany since 2013. |
| [**Aussie Server Hosts**](https://aussieserverhosts.com/) | No frills Australian Owned and operated High Performance Server hosting for some of the most demanding games serving Australia and New Zealand. |
| [**VibeGAMES**](https://vibegames.net/) | VibeGAMES is a game server provider that specializes in DDOS protection for the games we offer. We have multiple locations in the US, Brazil, France, Germany, Singapore, Australia and South Africa.|
| [**Gamenodes**](https://gamenodes.nl) | Gamenodes love quality. For Minecraft, Discord Bots and other services, among others. With our own programmers, we provide just that little bit of extra service! |
| Company | About |
|-----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [**Aussie Server Hosts**](https://aussieserverhosts.com/) | No frills Australian Owned and operated High Performance Server hosting for some of the most demanding games serving Australia and New Zealand. |
| [**BisectHosting**](https://www.bisecthosting.com/) | BisectHosting provides Minecraft, Valheim and other server hosting services with the highest reliability and lightning fast support since 2012. |
| [**MineStrator**](https://minestrator.com/) | Looking for the most highend French hosting company for your minecraft server? More than 24,000 members on our discord trust us. Give us a try! |
| [**VibeGAMES**](https://vibegames.net/) | VibeGAMES is a game server provider that specializes in DDOS protection for the games we offer. We have multiple locations in the US, Brazil, France, Germany, Singapore, Australia and South Africa. |
### Supported Games
Pterodactyl supports a wide variety of games by utilizing Docker containers to isolate each instance. This gives
you the power to run game servers without bloating machines with a host of additional dependencies.
@ -67,6 +64,7 @@ and there are plenty more games available provided by the community. Some of the
* [and many more...](https://github.com/parkervcp/eggs)
## License
Pterodactyl® Copyright © 2015 - 2022 Dane Everitt and contributors.
Code released under the [MIT License](./LICENSE.md).

View File

@ -1,11 +1,13 @@
# Security Policy
## Supported Versions
The following versions of Pterodactyl are receiving active support and maintenance. Any security vulnerabilities discovered must be reproducible in supported versions.
| Panel | Daemon | Supported |
|--------|--------------|--------------------|
| 1.10.x | wings@1.7.x | :white_check_mark: |
| 1.11.x | wings@1.11.x | :white_check_mark: |
| 0.7.x | daemon@0.6.x | :x: |

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Console\Commands\Environment;
use DateTimeZone;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel;
use Pterodactyl\Traits\Commands\EnvironmentWriterTrait;
@ -44,7 +43,8 @@ class AppSettingsCommand extends Command
{--redis-host= : Redis host to use for connections.}
{--redis-pass= : Password used to connect to redis.}
{--redis-port= : Port to connect to redis over.}
{--settings-ui= : Enable or disable the settings UI.}';
{--settings-ui= : Enable or disable the settings UI.}
{--telemetry= : Enable or disable anonymous telemetry.}';
protected array $variables = [];
@ -88,7 +88,7 @@ class AppSettingsCommand extends Command
$this->output->comment('The timezone should match one of PHP\'s supported timezones. If you are unsure, please reference https://php.net/manual/en/timezones.php.');
$this->variables['APP_TIMEZONE'] = $this->option('timezone') ?? $this->anticipate(
'Application Timezone',
DateTimeZone::listIdentifiers(),
\DateTimeZone::listIdentifiers(),
config('app.timezone')
);
@ -119,6 +119,12 @@ class AppSettingsCommand extends Command
$this->variables['APP_ENVIRONMENT_ONLY'] = $this->confirm('Enable UI based settings editor?', true) ? 'false' : 'true';
}
$this->output->comment('Please reference https://pterodactyl.io/panel/1.0/additional_configuration.html#telemetry for more detailed information regarding telemetry data and collection.');
$this->variables['PTERODACTYL_TELEMETRY_ENABLED'] = $this->option('telemetry') ?? $this->confirm(
'Enable sending anonymous telemetry data?',
config('pterodactyl.telemetry.enabled', true)
) ? 'true' : 'false';
// Make sure session cookies are set as "secure" when using HTTPS
if (str_starts_with($this->variables['APP_URL'], 'https://')) {
$this->variables['SESSION_SECURE_COOKIE'] = 'true';

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Console\Commands\Environment;
use PDOException;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\DatabaseManager;
@ -72,7 +71,7 @@ class DatabaseSettingsCommand extends Command
try {
$this->testMySQLConnection();
} catch (PDOException $exception) {
} catch (\PDOException $exception) {
$this->output->error(sprintf('Unable to connect to the MySQL server using the provided credentials. The error returned was "%s".', $exception->getMessage()));
$this->output->error('Your connection credentials have NOT been saved. You will need to provide valid connection information before proceeding.');

View File

@ -44,7 +44,7 @@ class EmailSettingsCommand extends Command
trans('command/messages.environment.mail.ask_driver'),
[
'smtp' => 'SMTP Server',
'mail' => 'PHP\'s Internal Mail Function',
'sendmail' => 'sendmail Binary',
'mailgun' => 'Mailgun Transactional Email',
'mandrill' => 'Mandrill Transactional Email',
'postmark' => 'Postmark Transactional Email',
@ -57,7 +57,7 @@ class EmailSettingsCommand extends Command
$this->{$method}();
}
$this->variables['MAIL_FROM'] = $this->option('email') ?? $this->ask(
$this->variables['MAIL_FROM_ADDRESS'] = $this->option('email') ?? $this->ask(
trans('command/messages.environment.mail.ask_mail_from'),
$this->config->get('mail.from.address')
);
@ -67,12 +67,6 @@ class EmailSettingsCommand extends Command
$this->config->get('mail.from.name')
);
$this->variables['MAIL_ENCRYPTION'] = $this->option('encryption') ?? $this->choice(
trans('command/messages.environment.mail.ask_encryption'),
['tls' => 'TLS', 'ssl' => 'SSL', '' => 'None'],
$this->config->get('mail.encryption', 'tls')
);
$this->writeToEnvironment($this->variables);
$this->line('Updating stored environment configuration file.');
@ -102,6 +96,12 @@ class EmailSettingsCommand extends Command
$this->variables['MAIL_PASSWORD'] = $this->option('password') ?? $this->secret(
trans('command/messages.environment.mail.ask_smtp_password')
);
$this->variables['MAIL_ENCRYPTION'] = $this->option('encryption') ?? $this->choice(
trans('command/messages.environment.mail.ask_encryption'),
['tls' => 'TLS', 'ssl' => 'SSL', '' => 'None'],
$this->config->get('mail.mailers.smtp.encryption', 'tls')
);
}
/**

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Console\Commands\Maintenance;
use SplFileInfo;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\Filesystem;
@ -35,7 +34,7 @@ class CleanServiceBackupFilesCommand extends Command
{
$files = $this->disk->files('services/.bak');
collect($files)->each(function (SplFileInfo $file) {
collect($files)->each(function (\SplFileInfo $file) {
$lastModified = Carbon::createFromTimestamp($this->disk->lastModified($file->getPath()));
if ($lastModified->diffInMinutes(Carbon::now()) > self::BACKUP_THRESHOLD_MINUTES) {
$this->disk->delete($file->getPath());

View File

@ -3,7 +3,6 @@
namespace Pterodactyl\Console\Commands\Maintenance;
use Carbon\CarbonImmutable;
use InvalidArgumentException;
use Illuminate\Console\Command;
use Pterodactyl\Repositories\Eloquent\BackupRepository;
@ -11,7 +10,7 @@ class PruneOrphanedBackupsCommand extends Command
{
protected $signature = 'p:maintenance:prune-backups {--prune-age=}';
protected $description = 'Marks all backups that have not completed in the last "n" minutes as being failed.';
protected $description = 'Marks all backups older than "n" minutes that have not yet completed as being failed.';
/**
* PruneOrphanedBackupsCommand constructor.
@ -25,7 +24,7 @@ class PruneOrphanedBackupsCommand extends Command
{
$since = $this->option('prune-age') ?? config('backups.prune_age', 360);
if (!$since || !is_digit($since)) {
throw new InvalidArgumentException('The "--prune-age" argument must be a value greater than 0.');
throw new \InvalidArgumentException('The "--prune-age" argument must be a value greater than 0.');
}
$query = $this->backupRepository->getBuilder()
@ -39,7 +38,7 @@ class PruneOrphanedBackupsCommand extends Command
return;
}
$this->warn("Marking $count backups that have not been marked as completed in the last $since minutes as failed.");
$this->warn("Marking $count uncompleted backups that are older than $since minutes as failed.");
$query->update([
'is_successful' => false,

View File

@ -3,7 +3,6 @@
namespace Pterodactyl\Console\Commands\Schedule;
use Exception;
use Throwable;
use Illuminate\Console\Command;
use Pterodactyl\Models\Schedule;
use Illuminate\Support\Facades\Log;
@ -68,7 +67,7 @@ class ProcessRunnableCommand extends Command
'schedule' => $schedule->name,
'hash' => $schedule->hashid,
]));
} catch (Throwable|Exception $exception) {
} catch (\Throwable|\Exception $exception) {
Log::error($exception, ['schedule_id' => $schedule->id]);
$this->error("An error was encountered while processing Schedule #$schedule->id: " . $exception->getMessage());

View File

@ -0,0 +1,34 @@
<?php
namespace Pterodactyl\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\VarDumper\VarDumper;
use Pterodactyl\Services\Telemetry\TelemetryCollectionService;
class TelemetryCommand extends Command
{
protected $description = 'Displays all the data that would be sent to the Pterodactyl Telemetry Service if telemetry collection is enabled.';
protected $signature = 'p:telemetry';
/**
* TelemetryCommand constructor.
*/
public function __construct(private TelemetryCollectionService $telemetryCollectionService)
{
parent::__construct();
}
/**
* Handle execution of command.
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/
public function handle()
{
$this->output->info('Collecting telemetry data, this may take a while...');
VarDumper::dump($this->telemetryCollectionService->collect());
}
}

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Console\Commands;
use Closure;
use Illuminate\Console\Command;
use Pterodactyl\Console\Kernel;
use Symfony\Component\Process\Process;
@ -177,7 +176,7 @@ class UpgradeCommand extends Command
$this->info('Panel has been successfully upgraded. Please ensure you also update any Wings instances: https://pterodactyl.io/wings/1.0/upgrading.html');
}
protected function withProgress(ProgressBar $bar, Closure $callback)
protected function withProgress(ProgressBar $bar, \Closure $callback)
{
$bar->clear();
$callback();

View File

@ -2,10 +2,13 @@
namespace Pterodactyl\Console;
use Ramsey\Uuid\Uuid;
use Pterodactyl\Models\ActivityLog;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Database\Console\PruneCommand;
use Pterodactyl\Repositories\Eloquent\SettingsRepository;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Pterodactyl\Services\Telemetry\TelemetryCollectionService;
use Pterodactyl\Console\Commands\Schedule\ProcessRunnableCommand;
use Pterodactyl\Console\Commands\Maintenance\PruneOrphanedBackupsCommand;
use Pterodactyl\Console\Commands\Maintenance\CleanServiceBackupFilesCommand;
@ -15,7 +18,7 @@ class Kernel extends ConsoleKernel
/**
* Register the commands for the application.
*/
protected function commands()
protected function commands(): void
{
$this->load(__DIR__ . '/Commands');
}
@ -23,8 +26,11 @@ class Kernel extends ConsoleKernel
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule)
protected function schedule(Schedule $schedule): void
{
// https://laravel.com/docs/10.x/upgrade#redis-cache-tags
$schedule->command('cache:prune-stale-tags')->hourly();
// Execute scheduled commands for servers every minute, as if there was a normal cron running.
$schedule->command(ProcessRunnableCommand::class)->everyMinute()->withoutOverlapping();
$schedule->command(CleanServiceBackupFilesCommand::class)->daily();
@ -37,5 +43,34 @@ class Kernel extends ConsoleKernel
if (config('activity.prune_days')) {
$schedule->command(PruneCommand::class, ['--model' => [ActivityLog::class]])->daily();
}
if (config('pterodactyl.telemetry.enabled')) {
$this->registerTelemetry($schedule);
}
}
/**
* I wonder what this does.
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
private function registerTelemetry(Schedule $schedule): void
{
$settingsRepository = app()->make(SettingsRepository::class);
$uuid = $settingsRepository->get('app:telemetry:uuid');
if (is_null($uuid)) {
$uuid = Uuid::uuid4()->toString();
$settingsRepository->set('app:telemetry:uuid', $uuid);
}
// Calculate a fixed time to run the data push at, this will be the same time every day.
$time = hexdec(str_replace('-', '', substr($uuid, 27))) % 1440;
$hour = floor($time / 60);
$minute = $time % 60;
// Run the telemetry collector.
$schedule->call(app()->make(TelemetryCollectionService::class))->description('Collect Telemetry')->dailyAt("$hour:$minute");
}
}

View File

@ -2,8 +2,6 @@
namespace Pterodactyl\Exceptions;
use Exception;
class AccountNotFoundException extends Exception
class AccountNotFoundException extends \Exception
{
}

View File

@ -2,8 +2,6 @@
namespace Pterodactyl\Exceptions;
use Exception;
class AutoDeploymentException extends Exception
class AutoDeploymentException extends \Exception
{
}

View File

@ -3,7 +3,6 @@
namespace Pterodactyl\Exceptions;
use Exception;
use Throwable;
use Illuminate\Http\Request;
use Psr\Log\LoggerInterface;
use Illuminate\Http\Response;
@ -23,7 +22,7 @@ class DisplayException extends PterodactylException implements HttpExceptionInte
/**
* DisplayException constructor.
*/
public function __construct(string $message, ?Throwable $previous = null, protected string $level = self::LEVEL_ERROR, int $code = 0)
public function __construct(string $message, ?\Throwable $previous = null, protected string $level = self::LEVEL_ERROR, int $code = 0)
{
parent::__construct($message, $code, $previous);
}
@ -67,7 +66,7 @@ class DisplayException extends PterodactylException implements HttpExceptionInte
*/
public function report()
{
if (!$this->getPrevious() instanceof Exception || !Handler::isReportable($this->getPrevious())) {
if (!$this->getPrevious() instanceof \Exception || !Handler::isReportable($this->getPrevious())) {
return null;
}

View File

@ -3,8 +3,6 @@
namespace Pterodactyl\Exceptions;
use Exception;
use Throwable;
use PDOException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\JsonResponse;
@ -75,13 +73,13 @@ class Handler extends ExceptionHandler
*
* @noinspection PhpUnusedLocalVariableInspection
*/
public function register()
public function register(): void
{
if (config('app.exceptions.report_all', false)) {
$this->dontReport = [];
}
$this->reportable(function (PDOException $ex) {
$this->reportable(function (\PDOException $ex) {
$ex = $this->generateCleanedExceptionStack($ex);
});
@ -90,7 +88,7 @@ class Handler extends ExceptionHandler
});
}
private function generateCleanedExceptionStack(Throwable $exception): string
private function generateCleanedExceptionStack(\Throwable $exception): string
{
$cleanedStack = '';
foreach ($exception->getTrace() as $index => $item) {
@ -123,7 +121,7 @@ class Handler extends ExceptionHandler
*
* @throws \Throwable
*/
public function render($request, Throwable $e): Response
public function render($request, \Throwable $e): Response
{
$connections = $this->container->make(Connection::class);
@ -189,7 +187,7 @@ class Handler extends ExceptionHandler
/**
* Return the exception as a JSONAPI representation for use on API requests.
*/
protected function convertExceptionToArray(Throwable $e, array $override = []): array
protected function convertExceptionToArray(\Throwable $e, array $override = []): array
{
$match = self::$exceptionResponseCodes[get_class($e)] ?? null;
@ -235,7 +233,7 @@ class Handler extends ExceptionHandler
/**
* Return an array of exceptions that should not be reported.
*/
public static function isReportable(Exception $exception): bool
public static function isReportable(\Exception $exception): bool
{
return (new static(Container::getInstance()))->shouldReport($exception);
}
@ -260,11 +258,11 @@ class Handler extends ExceptionHandler
*
* @return \Throwable[]
*/
protected function extractPrevious(Throwable $e): array
protected function extractPrevious(\Throwable $e): array
{
$previous = [];
while ($value = $e->getPrevious()) {
if (!$value instanceof Throwable) {
if (!$value instanceof \Throwable) {
break;
}
$previous[] = $value;
@ -278,7 +276,7 @@ class Handler extends ExceptionHandler
* Helper method to allow reaching into the handler to convert an exception
* into the expected array response type.
*/
public static function toArray(Throwable $e): array
public static function toArray(\Throwable $e): array
{
return (new self(app()))->convertExceptionToArray($e);
}

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Exceptions\Http\Server;
use Throwable;
use Pterodactyl\Models\Server;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
@ -12,11 +11,13 @@ class ServerStateConflictException extends ConflictHttpException
* Exception thrown when the server is in an unsupported state for API access or
* certain operations within the codebase.
*/
public function __construct(Server $server, Throwable $previous = null)
public function __construct(Server $server, \Throwable $previous = null)
{
$message = 'This server is currently in an unsupported state, please try again later.';
if ($server->isSuspended()) {
$message = 'This server is currently suspended and the functionality requested is unavailable.';
} elseif ($server->node->isUnderMaintenance()) {
$message = 'The node of this server is currently under maintenance and the functionality requested is unavailable.';
} elseif (!$server->isInstalled()) {
$message = 'This server has not yet completed its installation process, please try again later.';
} elseif ($server->status === Server::STATUS_RESTORING_BACKUP) {

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Exceptions\Http;
use Throwable;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
@ -12,7 +11,7 @@ class TwoFactorAuthRequiredException extends HttpException implements HttpExcept
/**
* TwoFactorAuthRequiredException constructor.
*/
public function __construct(Throwable $previous = null)
public function __construct(\Throwable $previous = null)
{
parent::__construct(Response::HTTP_BAD_REQUEST, 'Two-factor authentication is required on this account in order to access this endpoint.', $previous);
}

View File

@ -0,0 +1,14 @@
<?php
namespace Pterodactyl\Exceptions;
use Spatie\Ignition\Contracts\Solution;
use Spatie\Ignition\Contracts\ProvidesSolution;
class ManifestDoesNotExistException extends \Exception implements ProvidesSolution
{
public function getSolution(): Solution
{
return new Solutions\ManifestDoesNotExistSolution();
}
}

View File

@ -2,8 +2,6 @@
namespace Pterodactyl\Exceptions;
use Exception;
class PterodactylException extends Exception
class PterodactylException extends \Exception
{
}

View File

@ -2,8 +2,6 @@
namespace Pterodactyl\Exceptions\Service\Helper;
use Exception;
class CdnVersionFetchingException extends Exception
class CdnVersionFetchingException extends \Exception
{
}

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Exceptions\Service;
use Throwable;
use Pterodactyl\Exceptions\DisplayException;
class ServiceLimitExceededException extends DisplayException
@ -11,7 +10,7 @@ class ServiceLimitExceededException extends DisplayException
* Exception thrown when something goes over a defined limit, such as allocated
* ports, tasks, databases, etc.
*/
public function __construct(string $message, Throwable $previous = null)
public function __construct(string $message, \Throwable $previous = null)
{
parent::__construct($message, $previous, self::LEVEL_WARNING);
}

View File

@ -0,0 +1,25 @@
<?php
namespace Pterodactyl\Exceptions\Solutions;
use Spatie\Ignition\Contracts\Solution;
class ManifestDoesNotExistSolution implements Solution
{
public function getSolutionTitle(): string
{
return "The manifest.json file hasn't been generated yet";
}
public function getSolutionDescription(): string
{
return 'Run yarn run build:production to build the frontend first.';
}
public function getDocumentationLinks(): array
{
return [
'Docs' => 'https://github.com/pterodactyl/panel/blob/develop/package.json',
];
}
}

View File

@ -7,7 +7,6 @@ use Aws\S3\S3Client;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Webmozart\Assert\Assert;
use InvalidArgumentException;
use Illuminate\Foundation\Application;
use League\Flysystem\FilesystemAdapter;
use Pterodactyl\Extensions\Filesystem\S3Filesystem;
@ -70,7 +69,7 @@ class BackupManager
$config = $this->getConfig($name);
if (empty($config['adapter'])) {
throw new InvalidArgumentException("Backup disk [$name] does not have a configured adapter.");
throw new \InvalidArgumentException("Backup disk [$name] does not have a configured adapter.");
}
$adapter = $config['adapter'];
@ -88,7 +87,7 @@ class BackupManager
return $instance;
}
throw new InvalidArgumentException("Adapter [$adapter] is not supported.");
throw new \InvalidArgumentException("Adapter [$adapter] is not supported.");
}
/**
@ -164,7 +163,7 @@ class BackupManager
/**
* Register a custom adapter creator closure.
*/
public function extend(string $adapter, Closure $callback): self
public function extend(string $adapter, \Closure $callback): self
{
$this->customCreators[$adapter] = $callback;

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Extensions\Lcobucci\JWT\Encoding;
use DateTimeImmutable;
use Lcobucci\JWT\ClaimsFormatter;
use Lcobucci\JWT\Token\RegisteredClaims;
@ -21,7 +20,7 @@ final class TimestampDates implements ClaimsFormatter
continue;
}
assert($claims[$claim] instanceof DateTimeImmutable);
assert($claims[$claim] instanceof \DateTimeImmutable);
$claims[$claim] = $claims[$claim]->getTimestamp();
}

View File

@ -15,8 +15,6 @@ final class Time
*/
public static function getMySQLTimezoneOffset(string $timezone): string
{
$offset = round(CarbonImmutable::now($timezone)->getTimezone()->getOffset(CarbonImmutable::now('UTC')) / 3600);
return sprintf('%s%s:00', $offset > 0 ? '+' : '-', str_pad((string) abs($offset), 2, '0', STR_PAD_LEFT));
return CarbonImmutable::now($timezone)->getTimezone()->toOffsetName();
}
}

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Helpers;
use Exception;
use Carbon\Carbon;
use Cron\CronExpression;
use Illuminate\Support\Facades\Log;
@ -25,7 +24,7 @@ class Utilities
$string = substr_replace($string, $character, random_int(0, $length - 1), 1);
}
} catch (Exception $exception) {
} catch (\Exception $exception) {
// Just log the error and hope for the best at this point.
Log::error($exception);
}

View File

@ -3,7 +3,6 @@
namespace Pterodactyl\Http\Controllers\Admin;
use Exception;
use PDOException;
use Illuminate\View\View;
use Pterodactyl\Models\DatabaseHost;
use Illuminate\Http\RedirectResponse;
@ -69,8 +68,8 @@ class DatabaseController extends Controller
{
try {
$host = $this->creationService->handle($request->normalize());
} catch (Exception $exception) {
if ($exception instanceof PDOException || $exception->getPrevious() instanceof PDOException) {
} catch (\Exception $exception) {
if ($exception instanceof \PDOException || $exception->getPrevious() instanceof \PDOException) {
$this->alert->danger(
sprintf('There was an error while trying to connect to the host or while executing a query: "%s"', $exception->getMessage())
)->flash();
@ -98,10 +97,10 @@ class DatabaseController extends Controller
try {
$this->updateService->handle($host->id, $request->normalize());
$this->alert->success('Database host was updated successfully.')->flash();
} catch (Exception $exception) {
} catch (\Exception $exception) {
// Catch any SQL related exceptions and display them back to the user, otherwise just
// throw the exception like normal and move on with it.
if ($exception instanceof PDOException || $exception->getPrevious() instanceof PDOException) {
if ($exception instanceof \PDOException || $exception->getPrevious() instanceof \PDOException) {
$this->alert->danger(
sprintf('There was an error while trying to connect to the host or while executing a query: "%s"', $exception->getMessage())
)->flash();

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Controllers\Admin\Nests;
use JavaScript;
use Illuminate\View\View;
use Pterodactyl\Models\Egg;
use Illuminate\Http\RedirectResponse;
@ -40,7 +39,7 @@ class EggController extends Controller
public function create(): View
{
$nests = $this->nestRepository->getWithEggs();
JavaScript::put(['nests' => $nests->keyBy('id')]);
\JavaScript::put(['nests' => $nests->keyBy('id')]);
return $this->view->make('admin.eggs.new', ['nests' => $nests]);
}

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Controllers\Admin\Servers;
use JavaScript;
use Illuminate\View\View;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Location;
@ -45,7 +44,7 @@ class CreateServerController extends Controller
$nests = $this->nestRepository->getWithEggs();
JavaScript::put([
\JavaScript::put([
'nodeData' => $this->nodeRepository->getNodesForServerCreation(),
'nests' => $nests->map(function ($item) {
return array_merge($item->toArray(), [

View File

@ -2,15 +2,17 @@
namespace Pterodactyl\Http\Controllers\Admin\Servers;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Pterodactyl\Models\Server;
use Illuminate\Http\RedirectResponse;
use Prologue\Alerts\AlertsMessageBag;
use Pterodactyl\Models\ServerTransfer;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Services\Servers\TransferService;
use Pterodactyl\Services\Nodes\NodeJWTService;
use Pterodactyl\Repositories\Eloquent\NodeRepository;
use Pterodactyl\Repositories\Wings\DaemonConfigurationRepository;
use Pterodactyl\Repositories\Wings\DaemonTransferRepository;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
class ServerTransferController extends Controller
@ -21,9 +23,10 @@ class ServerTransferController extends Controller
public function __construct(
private AlertsMessageBag $alert,
private AllocationRepositoryInterface $allocationRepository,
private NodeRepository $nodeRepository,
private TransferService $transferService,
private DaemonConfigurationRepository $daemonConfigurationRepository
private ConnectionInterface $connection,
private DaemonTransferRepository $daemonTransferRepository,
private NodeJWTService $nodeJWTService,
private NodeRepository $nodeRepository
) {
}
@ -46,12 +49,15 @@ class ServerTransferController extends Controller
// Check if the node is viable for the transfer.
$node = $this->nodeRepository->getNodeWithResourceUsage($node_id);
if ($node->isViable($server->memory, $server->disk)) {
// Check if the selected daemon is online.
$this->daemonConfigurationRepository->setNode($node)->getSystemInformation();
if (!$node->isViable($server->memory, $server->disk)) {
$this->alert->danger(trans('admin/server.alerts.transfer_not_viable'))->flash();
$server->validateTransferState();
return redirect()->route('admin.servers.view.manage', $server->id);
}
$server->validateTransferState();
$this->connection->transaction(function () use ($server, $node_id, $allocation_id, $additional_allocations) {
// Create a new ServerTransfer entry.
$transfer = new ServerTransfer();
@ -68,13 +74,19 @@ class ServerTransferController extends Controller
// Add the allocations to the server, so they cannot be automatically assigned while the transfer is in progress.
$this->assignAllocationsToServer($server, $node_id, $allocation_id, $additional_allocations);
// Request an archive from the server's current daemon. (this also checks if the daemon is online)
$this->transferService->requestArchive($server);
// Generate a token for the destination node that the source node can use to authenticate with.
$token = $this->nodeJWTService
->setExpiresAt(CarbonImmutable::now()->addMinutes(15))
->setSubject($server->uuid)
->handle($transfer->newNode, $server->uuid, 'sha256');
$this->alert->success(trans('admin/server.alerts.transfer_started'))->flash();
} else {
$this->alert->danger(trans('admin/server.alerts.transfer_not_viable'))->flash();
}
// Notify the source node of the pending outgoing transfer.
$this->daemonTransferRepository->setServer($server)->notify($transfer->newNode, $token);
return $transfer;
});
$this->alert->success(trans('admin/server.alerts.transfer_started'))->flash();
return redirect()->route('admin.servers.view.manage', $server->id);
}

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Controllers\Admin\Servers;
use JavaScript;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Pterodactyl\Models\Nest;
@ -134,7 +133,7 @@ class ServerViewController extends Controller
$canTransfer = true;
}
JavaScript::put([
\JavaScript::put([
'nodeData' => $this->nodeRepository->getNodesForServerCreation(),
]);

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Controllers\Admin\Settings;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
@ -57,8 +56,8 @@ class MailController extends Controller
}
$values = $request->normalize();
if (array_get($values, 'mail:password') === '!e') {
$values['mail:password'] = '';
if (array_get($values, 'mail:mailers:smtp:password') === '!e') {
$values['mail:mailers:smtp:password'] = '';
}
foreach ($values as $key => $value) {
@ -82,7 +81,7 @@ class MailController extends Controller
try {
Notification::route('mail', $request->user()->email)
->notify(new MailTested($request->user()));
} catch (Exception $exception) {
} catch (\Exception $exception) {
return response($exception->getMessage(), 500);
}

View File

@ -18,6 +18,7 @@ use Pterodactyl\Transformers\Api\Client\BackupTransformer;
use Pterodactyl\Http\Controllers\Api\Client\ClientApiController;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Pterodactyl\Http\Requests\Api\Client\Servers\Backups\StoreBackupRequest;
use Pterodactyl\Http\Requests\Api\Client\Servers\Backups\RestoreBackupRequest;
class BackupController extends ClientApiController
{
@ -188,12 +189,8 @@ class BackupController extends ClientApiController
*
* @throws \Throwable
*/
public function restore(Request $request, Server $server, Backup $backup): JsonResponse
public function restore(RestoreBackupRequest $request, Server $server, Backup $backup): JsonResponse
{
if (!$request->user()->can(Permission::ACTION_BACKUP_RESTORE, $server)) {
throw new AuthorizationException();
}
// Cannot restore a backup unless a server is fully installed and not currently
// processing a different backup restoration request.
if (!is_null($server->status)) {

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Controllers\Api\Client\Servers;
use Exception;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
@ -178,7 +177,7 @@ class ScheduleController extends ClientApiController
$request->input('month'),
$request->input('day_of_week')
);
} catch (Exception $exception) {
} catch (\Exception $exception) {
throw new DisplayException('The cron data provided does not evaluate to a valid expression.');
}
}

View File

@ -9,6 +9,7 @@ use Pterodactyl\Models\Schedule;
use Illuminate\Http\JsonResponse;
use Pterodactyl\Facades\Activity;
use Pterodactyl\Models\Permission;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Repositories\Eloquent\TaskRepository;
use Pterodactyl\Exceptions\Http\HttpForbiddenException;
use Pterodactyl\Transformers\Api\Client\TaskTransformer;
@ -23,8 +24,10 @@ class ScheduleTaskController extends ClientApiController
/**
* ScheduleTaskController constructor.
*/
public function __construct(private TaskRepository $repository)
{
public function __construct(
private ConnectionInterface $connection,
private TaskRepository $repository
) {
parent::__construct();
}
@ -49,14 +52,35 @@ class ScheduleTaskController extends ClientApiController
$lastTask = $schedule->tasks()->orderByDesc('sequence_id')->first();
/** @var \Pterodactyl\Models\Task $task */
$task = $this->repository->create([
'schedule_id' => $schedule->id,
'sequence_id' => ($lastTask->sequence_id ?? 0) + 1,
'action' => $request->input('action'),
'payload' => $request->input('payload') ?? '',
'time_offset' => $request->input('time_offset'),
'continue_on_failure' => (bool) $request->input('continue_on_failure'),
]);
$task = $this->connection->transaction(function () use ($request, $schedule, $lastTask) {
$sequenceId = ($lastTask->sequence_id ?? 0) + 1;
$requestSequenceId = $request->integer('sequence_id', $sequenceId);
// Ensure that the sequence id is at least 1.
if ($requestSequenceId < 1) {
$requestSequenceId = 1;
}
// If the sequence id from the request is greater than or equal to the next available
// sequence id, we don't need to do anything special. Otherwise, we need to update
// the sequence id of all tasks that are greater than or equal to the request sequence
// id to be one greater than the current value.
if ($requestSequenceId < $sequenceId) {
$schedule->tasks()
->where('sequence_id', '>=', $requestSequenceId)
->increment('sequence_id');
$sequenceId = $requestSequenceId;
}
return $this->repository->create([
'schedule_id' => $schedule->id,
'sequence_id' => $sequenceId,
'action' => $request->input('action'),
'payload' => $request->input('payload') ?? '',
'time_offset' => $request->input('time_offset'),
'continue_on_failure' => $request->boolean('continue_on_failure'),
]);
});
Activity::event('server:task.create')
->subject($schedule, $task)
@ -84,12 +108,34 @@ class ScheduleTaskController extends ClientApiController
throw new HttpForbiddenException("A backup task cannot be created when the server's backup limit is set to 0.");
}
$this->repository->update($task->id, [
'action' => $request->input('action'),
'payload' => $request->input('payload') ?? '',
'time_offset' => $request->input('time_offset'),
'continue_on_failure' => (bool) $request->input('continue_on_failure'),
]);
$this->connection->transaction(function () use ($request, $schedule, $task) {
$sequenceId = $request->integer('sequence_id', $task->sequence_id);
// Ensure that the sequence id is at least 1.
if ($sequenceId < 1) {
$sequenceId = 1;
}
// Shift all other tasks in the schedule up or down to make room for the new task.
if ($sequenceId < $task->sequence_id) {
$schedule->tasks()
->where('sequence_id', '>=', $sequenceId)
->where('sequence_id', '<', $task->sequence_id)
->increment('sequence_id');
} elseif ($sequenceId > $task->sequence_id) {
$schedule->tasks()
->where('sequence_id', '>', $task->sequence_id)
->where('sequence_id', '<=', $sequenceId)
->decrement('sequence_id');
}
$this->repository->update($task->id, [
'sequence_id' => $sequenceId,
'action' => $request->input('action'),
'payload' => $request->input('payload') ?? '',
'time_offset' => $request->input('time_offset'),
'continue_on_failure' => $request->boolean('continue_on_failure'),
]);
});
Activity::event('server:task.update')
->subject($schedule, $task)
@ -117,10 +163,9 @@ class ScheduleTaskController extends ClientApiController
throw new HttpForbiddenException('You do not have permission to perform this action.');
}
$schedule->tasks()->where('sequence_id', '>', $task->sequence_id)->update([
'sequence_id' => $schedule->tasks()->getConnection()->raw('(sequence_id - 1)'),
]);
$schedule->tasks()
->where('sequence_id', '>', $task->sequence_id)
->decrement('sequence_id');
$task->delete();
Activity::event('server:task.delete')->subject($schedule, $task)->property('name', $schedule->name)->log();

View File

@ -34,13 +34,22 @@ class SettingsController extends ClientApiController
*/
public function rename(RenameServerRequest $request, Server $server): JsonResponse
{
$name = $request->input('name');
$description = $request->has('description') ? (string) $request->input('description') : $server->description;
$this->repository->update($server->id, [
'name' => $request->input('name'),
'name' => $name,
'description' => $description,
]);
if ($server->name !== $request->input('name')) {
if ($server->name !== $name) {
Activity::event('server:settings.rename')
->property(['old' => $server->name, 'new' => $request->input('name')])
->property(['old' => $server->name, 'new' => $name])
->log();
}
if ($server->description !== $description) {
Activity::event('server:settings.description')
->property(['old' => $server->description, 'new' => $description])
->log();
}

View File

@ -2,9 +2,7 @@
namespace Pterodactyl\Http\Controllers\Api\Remote;
use Exception;
use Carbon\Carbon;
use DateTimeInterface;
use Illuminate\Support\Str;
use Pterodactyl\Models\User;
use Webmozart\Assert\Assert;
@ -37,11 +35,11 @@ class ActivityProcessingController extends Controller
try {
$when = Carbon::createFromFormat(
DateTimeInterface::RFC3339,
\DateTimeInterface::RFC3339,
preg_replace('/(\.\d+)Z$/', 'Z', $datum['timestamp']),
'UTC'
);
} catch (Exception $exception) {
} catch (\Exception $exception) {
Log::warning($exception, ['timestamp' => $datum['timestamp']]);
// If we cannot parse the value for some reason don't blow up this request, just go ahead

View File

@ -48,8 +48,18 @@ class ServerInstallController extends Controller
public function store(InstallationDataRequest $request, string $uuid): JsonResponse
{
$server = $this->repository->getByUuid($uuid);
$status = null;
$status = $request->boolean('successful') ? null : Server::STATUS_INSTALL_FAILED;
// Make sure the type of failure is accurate
if (!$request->boolean('successful')) {
$status = Server::STATUS_INSTALL_FAILED;
if ($request->boolean('reinstall')) {
$status = Server::STATUS_REINSTALL_FAILED;
}
}
// Keep the server suspended if it's already suspended
if ($server->status === Server::STATUS_SUSPENDED) {
$status = Server::STATUS_SUSPENDED;
}

View File

@ -2,8 +2,6 @@
namespace Pterodactyl\Http\Controllers\Api\Remote\Servers;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Pterodactyl\Models\Allocation;
@ -11,10 +9,9 @@ use Illuminate\Support\Facades\Log;
use Pterodactyl\Models\ServerTransfer;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Services\Nodes\NodeJWTService;
use Pterodactyl\Repositories\Eloquent\ServerRepository;
use Pterodactyl\Repositories\Wings\DaemonServerRepository;
use Pterodactyl\Repositories\Wings\DaemonTransferRepository;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException;
class ServerTransferController extends Controller
@ -25,52 +22,10 @@ class ServerTransferController extends Controller
public function __construct(
private ConnectionInterface $connection,
private ServerRepository $repository,
private DaemonServerRepository $daemonServerRepository,
private DaemonTransferRepository $daemonTransferRepository,
private NodeJWTService $jwtService
private DaemonServerRepository $daemonServerRepository
) {
}
/**
* The daemon notifies us about the archive status.
*
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @throws \Throwable
*/
public function archive(Request $request, string $uuid): JsonResponse
{
$server = $this->repository->getByUuid($uuid);
// Unsuspend the server and don't continue the transfer.
if (!$request->input('successful')) {
return $this->processFailedTransfer($server->transfer);
}
$this->connection->transaction(function () use ($server) {
// This token is used by the new node the server is being transferred to. It allows
// that node to communicate with the old node during the process to initiate the
// actual file transfer.
$token = $this->jwtService
->setExpiresAt(CarbonImmutable::now()->addMinutes(15))
->setSubject($server->uuid)
->handle($server->node, $server->uuid, 'sha256');
// Update the archived field on the transfer to make clients connect to the websocket
// on the new node to be able to receive transfer logs.
$server->transfer->forceFill(['archived' => true])->saveOrFail();
// On the daemon transfer repository, make sure to set the node after the server
// because setServer() tells the repository to use the server's node and not the one
// we want to specify.
$this->daemonTransferRepository
->setServer($server)
->setNode($server->transfer->newNode)
->notify($server, $token);
});
return new JsonResponse([], Response::HTTP_NO_CONTENT);
}
/**
* The daemon notifies us about a transfer failure.
*
@ -79,8 +34,12 @@ class ServerTransferController extends Controller
public function failure(string $uuid): JsonResponse
{
$server = $this->repository->getByUuid($uuid);
$transfer = $server->transfer;
if (is_null($transfer)) {
throw new ConflictHttpException('Server is not being transferred.');
}
return $this->processFailedTransfer($server->transfer);
return $this->processFailedTransfer($transfer);
}
/**
@ -92,6 +51,9 @@ class ServerTransferController extends Controller
{
$server = $this->repository->getByUuid($uuid);
$transfer = $server->transfer;
if (is_null($transfer)) {
throw new ConflictHttpException('Server is not being transferred.');
}
/** @var \Pterodactyl\Models\Server $server */
$server = $this->connection->transaction(function () use ($server, $transfer) {

View File

@ -86,7 +86,7 @@ class Kernel extends HttpKernel
/**
* The application's route middleware.
*/
protected $routeMiddleware = [
protected $middlewareAliases = [
'auth' => Authenticate::class,
'auth.basic' => AuthenticateWithBasicAuth::class,
'auth.session' => AuthenticateSession::class,

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Activity;
use Closure;
use Illuminate\Http\Request;
use Pterodactyl\Facades\LogTarget;
@ -12,7 +11,7 @@ class AccountSubject
* Sets the actor and default subject for all requests passing through this
* middleware to be the currently logged in user.
*/
public function handle(Request $request, Closure $next)
public function handle(Request $request, \Closure $next)
{
LogTarget::setActor($request->user());
LogTarget::setSubject($request->user());

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Activity;
use Closure;
use Illuminate\Http\Request;
use Pterodactyl\Models\Server;
use Pterodactyl\Facades\LogTarget;
@ -17,7 +16,7 @@ class ServerSubject
* If no server is found this is a no-op as the activity log service can always
* set the user based on the authmanager response.
*/
public function handle(Request $request, Closure $next)
public function handle(Request $request, \Closure $next)
{
$server = $request->route()->parameter('server');
if ($server instanceof Server) {

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Activity;
use Closure;
use Illuminate\Http\Request;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Facades\LogTarget;
@ -15,7 +14,7 @@ class TrackAPIKey
* request singleton so that all tracked activity log events are properly associated
* with the given API key.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
if ($request->user()) {
$token = $request->user()->currentAccessToken();

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Admin\Servers;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Pterodactyl\Models\Server;
@ -14,7 +13,7 @@ class ServerInstalled
/**
* Checks that the server is installed before allowing access through the route.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
/** @var \Pterodactyl\Models\Server|null $server */
$server = $request->route()->parameter('server');

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@ -13,7 +12,7 @@ class AdminAuthenticate
*
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
if (!$request->user() || !$request->user()->root_admin) {
throw new AccessDeniedHttpException();

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Api\Application;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@ -12,7 +11,7 @@ class AuthenticateApplicationUser
* Authenticate that the currently authenticated user is an administrator
* and should be allowed to proceed through the application API.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
/** @var \Pterodactyl\Models\User|null $user */
$user = $request->user();

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Api;
use Closure;
use IPTools\IP;
use IPTools\Range;
use Illuminate\Http\Request;
@ -18,7 +17,7 @@ class AuthenticateIPAccess
* @throws \Exception
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
/** @var \Laravel\Sanctum\TransientToken|\Pterodactyl\Models\ApiKey $token */
$token = $request->user()->currentAccessToken();

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Api\Client\Server;
use Closure;
use Illuminate\Http\Request;
use Pterodactyl\Models\Server;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@ -27,7 +26,7 @@ class AuthenticateServerAccess
/**
* Authenticate that this server exists and is not suspended or marked as installing.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
/** @var \Pterodactyl\Models\User $user */
$user = $request->user();
@ -53,7 +52,7 @@ class AuthenticateServerAccess
// Still allow users to get information about their server if it is installing or
// being transferred.
if (!$request->routeIs('api:client:server.view')) {
if ($server->isSuspended() && !$request->routeIs('api:client:server.resources')) {
if (($server->isSuspended() || $server->node->isUnderMaintenance()) && !$request->routeIs('api:client:server.resources')) {
throw $exception;
}
if (!$user->root_admin || !$request->routeIs($this->except)) {

View File

@ -2,11 +2,9 @@
namespace Pterodactyl\Http\Middleware\Api\Client\Server;
use Closure;
use Illuminate\Http\Request;
use Pterodactyl\Models\Task;
use Pterodactyl\Models\User;
use InvalidArgumentException;
use Pterodactyl\Models\Backup;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Subuser;
@ -26,11 +24,11 @@ class ResourceBelongsToServer
* server that is expected, and that we're not accessing a resource completely
* unrelated to the server provided in the request.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
$params = $request->route()->parameters();
if (is_null($params) || !$params['server'] instanceof Server) {
throw new InvalidArgumentException('This middleware cannot be used in a context that is missing a server in the parameters.');
throw new \InvalidArgumentException('This middleware cannot be used in a context that is missing a server in the parameters.');
}
/** @var \Pterodactyl\Models\Server $server */
@ -79,7 +77,7 @@ class ResourceBelongsToServer
default:
// Don't return a 404 here since we want to make sure no one relies
// on this middleware in a context in which it will not work. Fail safe.
throw new InvalidArgumentException('There is no handler configured for a resource of this type: ' . get_class($model));
throw new \InvalidArgumentException('There is no handler configured for a resource of this type: ' . get_class($model));
}
}

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Api\Client;
use Closure;
use Pterodactyl\Models\Server;
use Illuminate\Routing\Middleware\SubstituteBindings;
@ -11,7 +10,7 @@ class SubstituteClientBindings extends SubstituteBindings
/**
* @param \Illuminate\Http\Request $request
*/
public function handle($request, Closure $next): mixed
public function handle($request, \Closure $next): mixed
{
// Override default behavior of the model binding to use a specific table
// column rather than the default 'id'.

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware\Api\Daemon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Repositories\Eloquent\NodeRepository;
@ -32,7 +31,7 @@ class DaemonAuthenticate
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
if (in_array($request->route()->getName(), $this->except)) {
return $next($request);

View File

@ -2,8 +2,6 @@
namespace Pterodactyl\Http\Middleware\Api;
use Closure;
use JsonException;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
@ -14,12 +12,12 @@ class IsValidJson
* parsing the data. This avoids confusing validation errors where every field is flagged and
* it is not immediately clear that there is an issue with the JSON being passed.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
if ($request->isJson() && !empty($request->getContent())) {
try {
json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
} catch (\JsonException $exception) {
throw new BadRequestHttpException('The JSON data passed in the request appears to be malformed: ' . $exception->getMessage());
}
}

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
@ -18,7 +17,7 @@ class LanguageMiddleware
/**
* Handle an incoming request and set the user's preferred language.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
$this->app->setLocale($request->user()->language ?? config('app.locale', 'en'));

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
@ -18,7 +17,7 @@ class MaintenanceMiddleware
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
/** @var \Pterodactyl\Models\Server $server */
$server = $request->attributes->get('server');

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Auth\AuthManager;
@ -18,7 +17,7 @@ class RedirectIfAuthenticated
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next, string $guard = null): mixed
public function handle(Request $request, \Closure $next, string $guard = null): mixed
{
if ($this->authManager->guard($guard)->check()) {
return redirect()->route('index');

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Middleware;
use Closure;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Prologue\Alerts\AlertsMessageBag;
@ -34,7 +33,7 @@ class RequireTwoFactorAuthentication
*
* @throws \Pterodactyl\Exceptions\Http\TwoFactorAuthRequiredException
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
/** @var \Pterodactyl\Models\User $user */
$user = $request->user();

View File

@ -2,8 +2,6 @@
namespace Pterodactyl\Http\Middleware;
use Closure;
use stdClass;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
@ -24,7 +22,7 @@ class VerifyReCaptcha
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): mixed
public function handle(Request $request, \Closure $next): mixed
{
if (!$this->config->get('recaptcha.enabled')) {
return $next($request);
@ -61,7 +59,7 @@ class VerifyReCaptcha
/**
* Determine if the response from the recaptcha servers was valid.
*/
private function isResponseVerified(stdClass $result, Request $request): bool
private function isResponseVerified(\stdClass $result, Request $request): bool
{
if (!$this->config->get('recaptcha.verify_domain')) {
return false;

View File

@ -13,11 +13,11 @@ class MailSettingsFormRequest extends AdminFormRequest
public function rules(): array
{
return [
'mail:host' => 'required|string',
'mail:port' => 'required|integer|between:1,65535',
'mail:encryption' => ['present', Rule::in([null, 'tls', 'ssl'])],
'mail:username' => 'nullable|string|max:191',
'mail:password' => 'nullable|string|max:191',
'mail:mailers:smtp:host' => 'required|string',
'mail:mailers:smtp:port' => 'required|integer|between:1,65535',
'mail:mailers:smtp:encryption' => ['present', Rule::in([null, 'tls', 'ssl'])],
'mail:mailers:smtp:username' => 'nullable|string|max:191',
'mail:mailers:smtp:password' => 'nullable|string|max:191',
'mail:from:address' => 'required|string|email',
'mail:from:name' => 'nullable|string|max:191',
];
@ -31,8 +31,8 @@ class MailSettingsFormRequest extends AdminFormRequest
{
$keys = array_flip(array_keys($this->rules()));
if (empty($this->input('mail:password'))) {
unset($keys['mail:password']);
if (empty($this->input('mail:mailers:smtp:password'))) {
unset($keys['mail:mailers:smtp:password']);
}
return $this->only(array_flip($keys));

View File

@ -24,6 +24,7 @@ class StoreNodeRequest extends ApplicationApiRequest
'fqdn',
'scheme',
'behind_proxy',
'maintenance_mode',
'memory',
'memory_overallocate',
'disk',

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Requests\Api\Client\Account;
use Exception;
use phpseclib3\Crypt\DSA;
use phpseclib3\Crypt\RSA;
use Pterodactyl\Models\UserSSHKey;
@ -71,7 +70,7 @@ class StoreSSHKeyRequest extends ClientApiRequest
public function getKeyFingerprint(): string
{
if (!$this->key) {
throw new Exception('The public key was not properly loaded for this request.');
throw new \Exception('The public key was not properly loaded for this request.');
}
return $this->key->getFingerprint('sha256');

View File

@ -0,0 +1,19 @@
<?php
namespace Pterodactyl\Http\Requests\Api\Client\Servers\Backups;
use Pterodactyl\Models\Permission;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
class RestoreBackupRequest extends ClientApiRequest
{
public function permission(): string
{
return Permission::ACTION_BACKUP_RESTORE;
}
public function rules(): array
{
return ['truncate' => 'required|boolean'];
}
}

View File

@ -23,6 +23,7 @@ class StoreTaskRequest extends ViewScheduleRequest
'payload' => 'required_unless:action,backup|string|nullable',
'time_offset' => 'required|numeric|min:0|max:900',
'sequence_id' => 'sometimes|required|numeric|min:1',
'continue_on_failure' => 'sometimes|required|boolean',
];
}
}

View File

@ -11,7 +11,7 @@ class RenameServerRequest extends ClientApiRequest implements ClientPermissionsR
{
/**
* Returns the permissions string indicating which permission should be used to
* validate that the authenticated user has permission to perform this action aganist
* validate that the authenticated user has permission to perform this action against
* the given resource (server).
*/
public function permission(): string
@ -26,6 +26,7 @@ class RenameServerRequest extends ClientApiRequest implements ClientPermissionsR
{
return [
'name' => Server::getRules()['name'],
'description' => 'string|nullable',
];
}
}

View File

@ -17,11 +17,11 @@ class ActivityEventRequest extends FormRequest
return [
'data' => ['required', 'array'],
'data.*' => ['array'],
'data.*.user' => ['present', 'uuid'],
'data.*.user' => ['sometimes', 'nullable', 'uuid'],
'data.*.server' => ['required', 'uuid'],
'data.*.event' => ['required', 'string'],
'data.*.metadata' => ['present', 'nullable', 'array'],
'data.*.ip' => ['present', 'ip'],
'data.*.ip' => ['sometimes', 'nullable', 'ip'],
'data.*.timestamp' => ['required', 'string'],
];
}

View File

@ -15,6 +15,7 @@ class InstallationDataRequest extends FormRequest
{
return [
'successful' => 'present|boolean',
'reinstall' => 'sometimes|boolean',
];
}
}

View File

@ -6,7 +6,6 @@ use Exception;
use Pterodactyl\Jobs\Job;
use Carbon\CarbonImmutable;
use Pterodactyl\Models\Task;
use InvalidArgumentException;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
@ -72,9 +71,9 @@ class RunTaskJob extends Job implements ShouldQueue
$backupService->setIgnoredFiles(explode(PHP_EOL, $this->task->payload))->handle($server, null, true);
break;
default:
throw new InvalidArgumentException('Invalid task action provided: ' . $this->task->action);
throw new \InvalidArgumentException('Invalid task action provided: ' . $this->task->action);
}
} catch (Exception $exception) {
} catch (\Exception $exception) {
// If this isn't a DaemonConnectionException on a task that allows for failures
// throw the exception back up the chain so that the task is stopped.
if (!($this->task->continue_on_failure && $exception instanceof DaemonConnectionException)) {
@ -89,7 +88,7 @@ class RunTaskJob extends Job implements ShouldQueue
/**
* Handle a failure while sending the action to the daemon or otherwise processing the job.
*/
public function failed(Exception $exception = null)
public function failed(\Exception $exception = null)
{
$this->markTaskNotQueued();
$this->markScheduleComplete();

View File

@ -3,7 +3,6 @@
namespace Pterodactyl\Models;
use Carbon\Carbon;
use LogicException;
use Illuminate\Support\Facades\Event;
use Pterodactyl\Events\ActivityLogged;
use Illuminate\Database\Eloquent\Builder;
@ -124,7 +123,7 @@ class ActivityLog extends Model
public function prunable()
{
if (is_null(config('activity.prune_days'))) {
throw new LogicException('Cannot prune activity logs: no "prune_days" configuration value is set.');
throw new \LogicException('Cannot prune activity logs: no "prune_days" configuration value is set.');
}
return static::where('timestamp', '<=', Carbon::now()->subDays(config('activity.prune_days')));

View File

@ -18,6 +18,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property array|null $allowed_ips
* @property string|null $memo
* @property \Illuminate\Support\Carbon|null $last_used_at
* @property \Illuminate\Support\Carbon|null $expires_at
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property int $r_servers
@ -97,6 +98,10 @@ class ApiKey extends Model
protected $casts = [
'allowed_ips' => 'array',
'user_id' => 'int',
'last_used_at' => 'datetime',
'expires_at' => 'datetime',
self::CREATED_AT => 'datetime',
self::UPDATED_AT => 'datetime',
'r_' . AdminAcl::RESOURCE_USERS => 'int',
'r_' . AdminAcl::RESOURCE_ALLOCATIONS => 'int',
'r_' . AdminAcl::RESOURCE_DATABASE_HOSTS => 'int',
@ -117,6 +122,7 @@ class ApiKey extends Model
'allowed_ips',
'memo',
'last_used_at',
'expires_at',
];
/**
@ -137,6 +143,7 @@ class ApiKey extends Model
'allowed_ips' => 'nullable|array',
'allowed_ips.*' => 'string',
'last_used_at' => 'nullable|date',
'expires_at' => 'nullable|date',
'r_' . AdminAcl::RESOURCE_USERS => 'integer|min:0|max:3',
'r_' . AdminAcl::RESOURCE_ALLOCATIONS => 'integer|min:0|max:3',
'r_' . AdminAcl::RESOURCE_DATABASE_HOSTS => 'integer|min:0|max:3',
@ -148,12 +155,6 @@ class ApiKey extends Model
'r_' . AdminAcl::RESOURCE_SERVERS => 'integer|min:0|max:3',
];
protected $dates = [
self::CREATED_AT,
self::UPDATED_AT,
'last_used_at',
];
/**
* Returns the user this token is assigned to.
*/

View File

@ -43,10 +43,7 @@ class Backup extends Model
'is_locked' => 'bool',
'ignored_files' => 'array',
'bytes' => 'int',
];
protected $dates = [
'completed_at',
'completed_at' => 'datetime',
];
protected $attributes = [

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Models\Filters;
use BadMethodCallException;
use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
@ -17,7 +16,7 @@ class AdminServerFilter implements Filter
public function __invoke(Builder $query, $value, string $property)
{
if ($query->getQuery()->from !== 'servers') {
throw new BadMethodCallException('Cannot use the AdminServerFilter against a non-server model.');
throw new \BadMethodCallException('Cannot use the AdminServerFilter against a non-server model.');
}
$query
->select('servers.*')

View File

@ -2,7 +2,6 @@
namespace Pterodactyl\Models\Filters;
use BadMethodCallException;
use Illuminate\Support\Str;
use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
@ -25,7 +24,7 @@ class MultiFieldServerFilter implements Filter
public function __invoke(Builder $query, $value, string $property)
{
if ($query->getQuery()->from !== 'servers') {
throw new BadMethodCallException('Cannot use the MultiFieldServerFilter against a non-server model.');
throw new \BadMethodCallException('Cannot use the MultiFieldServerFilter against a non-server model.');
}
if (preg_match(self::IPV4_REGEX, $value) || preg_match('/^:\d{1,5}$/', $value)) {

View File

@ -186,6 +186,11 @@ class Node extends Model
);
}
public function isUnderMaintenance(): bool
{
return $this->maintenance_mode;
}
public function mounts(): HasManyThrough
{
return $this->hasManyThrough(Mount::class, MountNode::class, 'node_id', 'id', 'id', 'mount_id');

View File

@ -195,7 +195,7 @@ class Permission extends Model
'settings' => [
'description' => 'Permissions that control a user\'s access to the settings for this server.',
'keys' => [
'rename' => 'Allows a user to rename this server.',
'rename' => 'Allows a user to rename this server and change the description of it.',
'reinstall' => 'Allows a user to trigger a reinstall of this server.',
],
],

View File

@ -71,14 +71,8 @@ class Schedule extends Model
'is_active' => 'boolean',
'is_processing' => 'boolean',
'only_when_online' => 'boolean',
];
/**
* Columns to mutate to a date.
*/
protected $dates = [
'last_run_at',
'next_run_at',
'last_run_at' => 'datetime',
'next_run_at' => 'datetime',
];
protected $attributes = [

View File

@ -115,6 +115,7 @@ class Server extends Model
public const STATUS_INSTALLING = 'installing';
public const STATUS_INSTALL_FAILED = 'install_failed';
public const STATUS_REINSTALL_FAILED = 'reinstall_failed';
public const STATUS_SUSPENDED = 'suspended';
public const STATUS_RESTORING_BACKUP = 'restoring_backup';
@ -138,11 +139,6 @@ class Server extends Model
*/
protected $with = ['allocation'];
/**
* The attributes that should be mutated to dates.
*/
protected $dates = [self::CREATED_AT, self::UPDATED_AT, 'deleted_at', 'installed_at'];
/**
* Fields that are not mass assignable.
*/
@ -192,6 +188,10 @@ class Server extends Model
'database_limit' => 'integer',
'allocation_limit' => 'integer',
'backup_limit' => 'integer',
self::CREATED_AT => 'datetime',
self::UPDATED_AT => 'datetime',
'deleted_at' => 'datetime',
'installed_at' => 'datetime',
];
/**
@ -354,6 +354,7 @@ class Server extends Model
{
if (
$this->isSuspended() ||
$this->node->isUnderMaintenance() ||
!$this->isInstalled() ||
$this->status === self::STATUS_RESTORING_BACKUP ||
!is_null($this->transfer)

View File

@ -2,6 +2,13 @@
namespace Pterodactyl\Models;
/**
* Pterodactyl\Models\Setting.
*
* @property int $id
* @property string $key
* @property string $value
*/
class Setting extends Model
{
/**

View File

@ -23,10 +23,8 @@ class TaskLog extends Model
'id' => 'integer',
'task_id' => 'integer',
'run_status' => 'integer',
'run_time' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
/**
* The attributes that should be mutated to dates.
*/
protected $dates = ['run_time', 'created_at', 'updated_at'];
}

View File

@ -134,10 +134,9 @@ class User extends Model implements
'root_admin' => 'boolean',
'use_totp' => 'boolean',
'gravatar' => 'boolean',
'totp_authenticated_at' => 'datetime',
];
protected $dates = ['totp_authenticated_at'];
/**
* The attributes excluded from the model's JSON form.
*/

View File

@ -2,12 +2,12 @@
namespace Pterodactyl\Providers;
use View;
use Cache;
use Pterodactyl\Models;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\URL;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Pterodactyl\Extensions\Themes\Theme;
@ -18,7 +18,7 @@ class AppServiceProvider extends ServiceProvider
/**
* Bootstrap any application services.
*/
public function boot()
public function boot(): void
{
Schema::defaultStringLength(191);
@ -54,7 +54,7 @@ class AppServiceProvider extends ServiceProvider
/**
* Register application service providers.
*/
public function register()
public function register(): void
{
// Only load the settings service provider if the environment
// is configured to allow it.

View File

@ -17,14 +17,12 @@ class AuthServiceProvider extends ServiceProvider
Server::class => ServerPolicy::class,
];
public function boot()
public function boot(): void
{
Sanctum::usePersonalAccessTokenModel(ApiKey::class);
$this->registerPolicies();
}
public function register()
public function register(): void
{
Sanctum::ignoreMigrations();
}

View File

@ -11,7 +11,7 @@ class BackupsServiceProvider extends ServiceProvider implements DeferrableProvid
/**
* Register the S3 backup disk.
*/
public function register()
public function register(): void
{
$this->app->singleton(BackupManager::class, function ($app) {
return new BackupManager($app);

View File

@ -9,7 +9,7 @@ class BladeServiceProvider extends ServiceProvider
/**
* Perform post-registration booting of services.
*/
public function boot()
public function boot(): void
{
$this->app->make('blade.compiler')
->directive('datetimeHuman', function ($expression) {

View File

@ -10,7 +10,7 @@ class BroadcastServiceProvider extends ServiceProvider
/**
* Bootstrap any application services.
*/
public function boot()
public function boot(): void
{
Broadcast::routes();

View File

@ -11,7 +11,7 @@ class HashidsServiceProvider extends ServiceProvider
/**
* Register the ability to use Hashids.
*/
public function register()
public function register(): void
{
$this->app->singleton(HashidsInterface::class, function () {
/** @var \Illuminate\Contracts\Config\Repository $config */

View File

@ -41,9 +41,9 @@ use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Register all of the repository bindings.
* Register all the repository bindings.
*/
public function register()
public function register(): void
{
// Eloquent Repositories
$this->app->bind(AllocationRepositoryInterface::class, AllocationRepository::class);

View File

@ -19,7 +19,7 @@ class RouteServiceProvider extends ServiceProvider
/**
* Define your route model bindings, pattern filters, etc.
*/
public function boot()
public function boot(): void
{
$this->configureRateLimiting();
@ -70,7 +70,7 @@ class RouteServiceProvider extends ServiceProvider
/**
* Configure the rate limiters for the application.
*/
protected function configureRateLimiting()
protected function configureRateLimiting(): void
{
// Authentication rate limiting. For login and checkpoint endpoints we'll apply
// a limit of 10 requests per minute, for the forgot password endpoint apply a

View File

@ -37,13 +37,13 @@ class SettingsServiceProvider extends ServiceProvider
* when using the SMTP driver.
*/
protected array $emailKeys = [
'mail:host',
'mail:port',
'mail:mailers:smtp:host',
'mail:mailers:smtp:port',
'mail:mailers:smtp:encryption',
'mail:mailers:smtp:username',
'mail:mailers:smtp:password',
'mail:from:address',
'mail:from:name',
'mail:encryption',
'mail:username',
'mail:password',
];
/**
@ -51,13 +51,13 @@ class SettingsServiceProvider extends ServiceProvider
* configuration array.
*/
protected static array $encrypted = [
'mail:password',
'mail:mailers:smtp:password',
];
/**
* Boot the service provider.
*/
public function boot(ConfigRepository $config, Encrypter $encrypter, Log $log, SettingsRepositoryInterface $settings)
public function boot(ConfigRepository $config, Encrypter $encrypter, Log $log, SettingsRepositoryInterface $settings): void
{
// Only set the email driver settings from the database if we
// are configured using SMTP as the driver.

Some files were not shown because too many files have changed in this diff Show More